This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
t/uni/fold.t: Generalize for non-ASCII platforms
[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     /* lastsib == 1, op_sibling == 0 implies a solitary unattached op */
301     o->op_lastsib = 1;
302     assert(!o->op_sibling);
303
304     return (void *)o;
305 }
306
307 #undef INIT_OPSLOT
308
309 #ifdef PERL_DEBUG_READONLY_OPS
310 void
311 Perl_Slab_to_ro(pTHX_ OPSLAB *slab)
312 {
313     PERL_ARGS_ASSERT_SLAB_TO_RO;
314
315     if (slab->opslab_readonly) return;
316     slab->opslab_readonly = 1;
317     for (; slab; slab = slab->opslab_next) {
318         /*DEBUG_U(PerlIO_printf(Perl_debug_log,"mprotect ->ro %lu at %p\n",
319                               (unsigned long) slab->opslab_size, slab));*/
320         if (mprotect(slab, slab->opslab_size * sizeof(I32 *), PROT_READ))
321             Perl_warn(aTHX_ "mprotect for %p %lu failed with %d", slab,
322                              (unsigned long)slab->opslab_size, errno);
323     }
324 }
325
326 void
327 Perl_Slab_to_rw(pTHX_ OPSLAB *const slab)
328 {
329     OPSLAB *slab2;
330
331     PERL_ARGS_ASSERT_SLAB_TO_RW;
332
333     if (!slab->opslab_readonly) return;
334     slab2 = slab;
335     for (; slab2; slab2 = slab2->opslab_next) {
336         /*DEBUG_U(PerlIO_printf(Perl_debug_log,"mprotect ->rw %lu at %p\n",
337                               (unsigned long) size, slab2));*/
338         if (mprotect((void *)slab2, slab2->opslab_size * sizeof(I32 *),
339                      PROT_READ|PROT_WRITE)) {
340             Perl_warn(aTHX_ "mprotect RW for %p %lu failed with %d", slab,
341                              (unsigned long)slab2->opslab_size, errno);
342         }
343     }
344     slab->opslab_readonly = 0;
345 }
346
347 #else
348 #  define Slab_to_rw(op)    NOOP
349 #endif
350
351 /* This cannot possibly be right, but it was copied from the old slab
352    allocator, to which it was originally added, without explanation, in
353    commit 083fcd5. */
354 #ifdef NETWARE
355 #    define PerlMemShared PerlMem
356 #endif
357
358 void
359 Perl_Slab_Free(pTHX_ void *op)
360 {
361     OP * const o = (OP *)op;
362     OPSLAB *slab;
363
364     PERL_ARGS_ASSERT_SLAB_FREE;
365
366     if (!o->op_slabbed) {
367         if (!o->op_static)
368             PerlMemShared_free(op);
369         return;
370     }
371
372     slab = OpSLAB(o);
373     /* If this op is already freed, our refcount will get screwy. */
374     assert(o->op_type != OP_FREED);
375     o->op_type = OP_FREED;
376     o->op_next = slab->opslab_freed;
377     slab->opslab_freed = o;
378     DEBUG_S_warn((aTHX_ "free op at %p, recorded in slab %p", (void*)o, (void*)slab));
379     OpslabREFCNT_dec_padok(slab);
380 }
381
382 void
383 Perl_opslab_free_nopad(pTHX_ OPSLAB *slab)
384 {
385     const bool havepad = !!PL_comppad;
386     PERL_ARGS_ASSERT_OPSLAB_FREE_NOPAD;
387     if (havepad) {
388         ENTER;
389         PAD_SAVE_SETNULLPAD();
390     }
391     opslab_free(slab);
392     if (havepad) LEAVE;
393 }
394
395 void
396 Perl_opslab_free(pTHX_ OPSLAB *slab)
397 {
398     OPSLAB *slab2;
399     PERL_ARGS_ASSERT_OPSLAB_FREE;
400     PERL_UNUSED_CONTEXT;
401     DEBUG_S_warn((aTHX_ "freeing slab %p", (void*)slab));
402     assert(slab->opslab_refcnt == 1);
403     for (; slab; slab = slab2) {
404         slab2 = slab->opslab_next;
405 #ifdef DEBUGGING
406         slab->opslab_refcnt = ~(size_t)0;
407 #endif
408 #ifdef PERL_DEBUG_READONLY_OPS
409         DEBUG_m(PerlIO_printf(Perl_debug_log, "Deallocate slab at %p\n",
410                                                (void*)slab));
411         if (munmap(slab, slab->opslab_size * sizeof(I32 *))) {
412             perror("munmap failed");
413             abort();
414         }
415 #else
416         PerlMemShared_free(slab);
417 #endif
418     }
419 }
420
421 void
422 Perl_opslab_force_free(pTHX_ OPSLAB *slab)
423 {
424     OPSLAB *slab2;
425     OPSLOT *slot;
426 #ifdef DEBUGGING
427     size_t savestack_count = 0;
428 #endif
429     PERL_ARGS_ASSERT_OPSLAB_FORCE_FREE;
430     slab2 = slab;
431     do {
432         for (slot = slab2->opslab_first;
433              slot->opslot_next;
434              slot = slot->opslot_next) {
435             if (slot->opslot_op.op_type != OP_FREED
436              && !(slot->opslot_op.op_savefree
437 #ifdef DEBUGGING
438                   && ++savestack_count
439 #endif
440                  )
441             ) {
442                 assert(slot->opslot_op.op_slabbed);
443                 op_free(&slot->opslot_op);
444                 if (slab->opslab_refcnt == 1) goto free;
445             }
446         }
447     } while ((slab2 = slab2->opslab_next));
448     /* > 1 because the CV still holds a reference count. */
449     if (slab->opslab_refcnt > 1) { /* still referenced by the savestack */
450 #ifdef DEBUGGING
451         assert(savestack_count == slab->opslab_refcnt-1);
452 #endif
453         /* Remove the CV’s reference count. */
454         slab->opslab_refcnt--;
455         return;
456     }
457    free:
458     opslab_free(slab);
459 }
460
461 #ifdef PERL_DEBUG_READONLY_OPS
462 OP *
463 Perl_op_refcnt_inc(pTHX_ OP *o)
464 {
465     if(o) {
466         OPSLAB *const slab = o->op_slabbed ? OpSLAB(o) : NULL;
467         if (slab && slab->opslab_readonly) {
468             Slab_to_rw(slab);
469             ++o->op_targ;
470             Slab_to_ro(slab);
471         } else {
472             ++o->op_targ;
473         }
474     }
475     return o;
476
477 }
478
479 PADOFFSET
480 Perl_op_refcnt_dec(pTHX_ OP *o)
481 {
482     PADOFFSET result;
483     OPSLAB *const slab = o->op_slabbed ? OpSLAB(o) : NULL;
484
485     PERL_ARGS_ASSERT_OP_REFCNT_DEC;
486
487     if (slab && slab->opslab_readonly) {
488         Slab_to_rw(slab);
489         result = --o->op_targ;
490         Slab_to_ro(slab);
491     } else {
492         result = --o->op_targ;
493     }
494     return result;
495 }
496 #endif
497 /*
498  * In the following definition, the ", (OP*)0" is just to make the compiler
499  * think the expression is of the right type: croak actually does a Siglongjmp.
500  */
501 #define CHECKOP(type,o) \
502     ((PL_op_mask && PL_op_mask[type])                           \
503      ? ( op_free((OP*)o),                                       \
504          Perl_croak(aTHX_ "'%s' trapped by operation mask", PL_op_desc[type]),  \
505          (OP*)0 )                                               \
506      : PL_check[type](aTHX_ (OP*)o))
507
508 #define RETURN_UNLIMITED_NUMBER (PERL_INT_MAX / 2)
509
510 #define CHANGE_TYPE(o,type) \
511     STMT_START {                                \
512         o->op_type = (OPCODE)type;              \
513         o->op_ppaddr = PL_ppaddr[type];         \
514     } STMT_END
515
516 STATIC OP *
517 S_no_fh_allowed(pTHX_ OP *o)
518 {
519     PERL_ARGS_ASSERT_NO_FH_ALLOWED;
520
521     yyerror(Perl_form(aTHX_ "Missing comma after first argument to %s function",
522                  OP_DESC(o)));
523     return o;
524 }
525
526 STATIC OP *
527 S_too_few_arguments_pv(pTHX_ OP *o, const char* name, U32 flags)
528 {
529     PERL_ARGS_ASSERT_TOO_FEW_ARGUMENTS_PV;
530     yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %s", name), flags);
531     return o;
532 }
533  
534 STATIC OP *
535 S_too_many_arguments_pv(pTHX_ OP *o, const char *name, U32 flags)
536 {
537     PERL_ARGS_ASSERT_TOO_MANY_ARGUMENTS_PV;
538
539     yyerror_pv(Perl_form(aTHX_ "Too many arguments for %s", name), flags);
540     return o;
541 }
542
543 STATIC void
544 S_bad_type_pv(pTHX_ I32 n, const char *t, const OP *o, const OP *kid)
545 {
546     PERL_ARGS_ASSERT_BAD_TYPE_PV;
547
548     yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %s must be %s (not %s)",
549                  (int)n, PL_op_desc[(o)->op_type], t, OP_DESC(kid)), 0);
550 }
551
552 /* remove flags var, its unused in all callers, move to to right end since gv
553   and kid are always the same */
554 STATIC void
555 S_bad_type_gv(pTHX_ I32 n, GV *gv, const OP *kid, const char *t)
556 {
557     SV * const namesv = cv_name((CV *)gv, NULL, 0);
558     PERL_ARGS_ASSERT_BAD_TYPE_GV;
559  
560     yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %"SVf" must be %s (not %s)",
561                  (int)n, SVfARG(namesv), t, OP_DESC(kid)), SvUTF8(namesv));
562 }
563
564 STATIC void
565 S_no_bareword_allowed(pTHX_ OP *o)
566 {
567     PERL_ARGS_ASSERT_NO_BAREWORD_ALLOWED;
568
569     qerror(Perl_mess(aTHX_
570                      "Bareword \"%"SVf"\" not allowed while \"strict subs\" in use",
571                      SVfARG(cSVOPo_sv)));
572     o->op_private &= ~OPpCONST_STRICT; /* prevent warning twice about the same OP */
573 }
574
575 /* "register" allocation */
576
577 PADOFFSET
578 Perl_allocmy(pTHX_ const char *const name, const STRLEN len, const U32 flags)
579 {
580     PADOFFSET off;
581     const bool is_our = (PL_parser->in_my == KEY_our);
582
583     PERL_ARGS_ASSERT_ALLOCMY;
584
585     if (flags & ~SVf_UTF8)
586         Perl_croak(aTHX_ "panic: allocmy illegal flag bits 0x%" UVxf,
587                    (UV)flags);
588
589     /* complain about "my $<special_var>" etc etc */
590     if (len &&
591         !(is_our ||
592           isALPHA(name[1]) ||
593           ((flags & SVf_UTF8) && isIDFIRST_utf8((U8 *)name+1)) ||
594           (name[1] == '_' && (*name == '$' || len > 2))))
595     {
596         if (!(flags & SVf_UTF8 && UTF8_IS_START(name[1]))
597          && isASCII(name[1])
598          && (!isPRINT(name[1]) || strchr("\t\n\r\f", name[1]))) {
599             yyerror(Perl_form(aTHX_ "Can't use global %c^%c%.*s in \"%s\"",
600                               name[0], toCTRL(name[1]), (int)(len - 2), name + 2,
601                               PL_parser->in_my == KEY_state ? "state" : "my"));
602         } else {
603             yyerror_pv(Perl_form(aTHX_ "Can't use global %.*s in \"%s\"", (int) len, name,
604                               PL_parser->in_my == KEY_state ? "state" : "my"), flags & SVf_UTF8);
605         }
606     }
607     else if (len == 2 && name[1] == '_' && !is_our)
608         /* diag_listed_as: Use of my $_ is experimental */
609         Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__LEXICAL_TOPIC),
610                               "Use of %s $_ is experimental",
611                                PL_parser->in_my == KEY_state
612                                  ? "state"
613                                  : "my");
614
615     /* allocate a spare slot and store the name in that slot */
616
617     off = pad_add_name_pvn(name, len,
618                        (is_our ? padadd_OUR :
619                         PL_parser->in_my == KEY_state ? padadd_STATE : 0),
620                     PL_parser->in_my_stash,
621                     (is_our
622                         /* $_ is always in main::, even with our */
623                         ? (PL_curstash && !memEQs(name,len,"$_")
624                             ? PL_curstash
625                             : PL_defstash)
626                         : NULL
627                     )
628     );
629     /* anon sub prototypes contains state vars should always be cloned,
630      * otherwise the state var would be shared between anon subs */
631
632     if (PL_parser->in_my == KEY_state && CvANON(PL_compcv))
633         CvCLONE_on(PL_compcv);
634
635     return off;
636 }
637
638 /*
639 =head1 Optree Manipulation Functions
640
641 =for apidoc alloccopstash
642
643 Available only under threaded builds, this function allocates an entry in
644 C<PL_stashpad> for the stash passed to it.
645
646 =cut
647 */
648
649 #ifdef USE_ITHREADS
650 PADOFFSET
651 Perl_alloccopstash(pTHX_ HV *hv)
652 {
653     PADOFFSET off = 0, o = 1;
654     bool found_slot = FALSE;
655
656     PERL_ARGS_ASSERT_ALLOCCOPSTASH;
657
658     if (PL_stashpad[PL_stashpadix] == hv) return PL_stashpadix;
659
660     for (; o < PL_stashpadmax; ++o) {
661         if (PL_stashpad[o] == hv) return PL_stashpadix = o;
662         if (!PL_stashpad[o] || SvTYPE(PL_stashpad[o]) != SVt_PVHV)
663             found_slot = TRUE, off = o;
664     }
665     if (!found_slot) {
666         Renew(PL_stashpad, PL_stashpadmax + 10, HV *);
667         Zero(PL_stashpad + PL_stashpadmax, 10, HV *);
668         off = PL_stashpadmax;
669         PL_stashpadmax += 10;
670     }
671
672     PL_stashpad[PL_stashpadix = off] = hv;
673     return off;
674 }
675 #endif
676
677 /* free the body of an op without examining its contents.
678  * Always use this rather than FreeOp directly */
679
680 static void
681 S_op_destroy(pTHX_ OP *o)
682 {
683     FreeOp(o);
684 }
685
686 /* Destructor */
687
688 /*
689 =for apidoc Am|void|op_free|OP *o
690
691 Free an op.  Only use this when an op is no longer linked to from any
692 optree.
693
694 =cut
695 */
696
697 void
698 Perl_op_free(pTHX_ OP *o)
699 {
700     dVAR;
701     OPCODE type;
702     SSize_t defer_ix = -1;
703     SSize_t defer_stack_alloc = 0;
704     OP **defer_stack = NULL;
705
706     do {
707
708         /* Though ops may be freed twice, freeing the op after its slab is a
709            big no-no. */
710         assert(!o || !o->op_slabbed || OpSLAB(o)->opslab_refcnt != ~(size_t)0);
711         /* During the forced freeing of ops after compilation failure, kidops
712            may be freed before their parents. */
713         if (!o || o->op_type == OP_FREED)
714             continue;
715
716         type = o->op_type;
717
718         /* an op should only ever acquire op_private flags that we know about.
719          * If this fails, you may need to fix something in regen/op_private */
720         if (o->op_ppaddr == PL_ppaddr[o->op_type]) {
721             assert(!(o->op_private & ~PL_op_private_valid[type]));
722         }
723
724         if (o->op_private & OPpREFCOUNTED) {
725             switch (type) {
726             case OP_LEAVESUB:
727             case OP_LEAVESUBLV:
728             case OP_LEAVEEVAL:
729             case OP_LEAVE:
730             case OP_SCOPE:
731             case OP_LEAVEWRITE:
732                 {
733                 PADOFFSET refcnt;
734                 OP_REFCNT_LOCK;
735                 refcnt = OpREFCNT_dec(o);
736                 OP_REFCNT_UNLOCK;
737                 if (refcnt) {
738                     /* Need to find and remove any pattern match ops from the list
739                        we maintain for reset().  */
740                     find_and_forget_pmops(o);
741                     continue;
742                 }
743                 }
744                 break;
745             default:
746                 break;
747             }
748         }
749
750         /* Call the op_free hook if it has been set. Do it now so that it's called
751          * at the right time for refcounted ops, but still before all of the kids
752          * are freed. */
753         CALL_OPFREEHOOK(o);
754
755         if (o->op_flags & OPf_KIDS) {
756             OP *kid, *nextkid;
757             for (kid = cUNOPo->op_first; kid; kid = nextkid) {
758                 nextkid = OpSIBLING(kid); /* Get before next freeing kid */
759                 if (!kid || kid->op_type == OP_FREED)
760                     /* During the forced freeing of ops after
761                        compilation failure, kidops may be freed before
762                        their parents. */
763                     continue;
764                 if (!(kid->op_flags & OPf_KIDS))
765                     /* If it has no kids, just free it now */
766                     op_free(kid);
767                 else
768                     DEFER_OP(kid);
769             }
770         }
771         if (type == OP_NULL)
772             type = (OPCODE)o->op_targ;
773
774         if (o->op_slabbed)
775             Slab_to_rw(OpSLAB(o));
776
777         /* COP* is not cleared by op_clear() so that we may track line
778          * numbers etc even after null() */
779         if (type == OP_NEXTSTATE || type == OP_DBSTATE) {
780             cop_free((COP*)o);
781         }
782
783         op_clear(o);
784         FreeOp(o);
785 #ifdef DEBUG_LEAKING_SCALARS
786         if (PL_op == o)
787             PL_op = NULL;
788 #endif
789     } while ( (o = POP_DEFERRED_OP()) );
790
791     Safefree(defer_stack);
792 }
793
794 /* S_op_clear_gv(): free a GV attached to an OP */
795
796 #ifdef USE_ITHREADS
797 void S_op_clear_gv(pTHX_ OP *o, PADOFFSET *ixp)
798 #else
799 void S_op_clear_gv(pTHX_ OP *o, SV**svp)
800 #endif
801 {
802
803     GV *gv = (o->op_type == OP_GV || o->op_type == OP_GVSV
804             || o->op_type == OP_MULTIDEREF)
805 #ifdef USE_ITHREADS
806                 && PL_curpad
807                 ? ((GV*)PAD_SVl(*ixp)) : NULL;
808 #else
809                 ? (GV*)(*svp) : NULL;
810 #endif
811     /* It's possible during global destruction that the GV is freed
812        before the optree. Whilst the SvREFCNT_inc is happy to bump from
813        0 to 1 on a freed SV, the corresponding SvREFCNT_dec from 1 to 0
814        will trigger an assertion failure, because the entry to sv_clear
815        checks that the scalar is not already freed.  A check of for
816        !SvIS_FREED(gv) turns out to be invalid, because during global
817        destruction the reference count can be forced down to zero
818        (with SVf_BREAK set).  In which case raising to 1 and then
819        dropping to 0 triggers cleanup before it should happen.  I
820        *think* that this might actually be a general, systematic,
821        weakness of the whole idea of SVf_BREAK, in that code *is*
822        allowed to raise and lower references during global destruction,
823        so any *valid* code that happens to do this during global
824        destruction might well trigger premature cleanup.  */
825     bool still_valid = gv && SvREFCNT(gv);
826
827     if (still_valid)
828         SvREFCNT_inc_simple_void(gv);
829 #ifdef USE_ITHREADS
830     if (*ixp > 0) {
831         pad_swipe(*ixp, TRUE);
832         *ixp = 0;
833     }
834 #else
835     SvREFCNT_dec(*svp);
836     *svp = NULL;
837 #endif
838     if (still_valid) {
839         int try_downgrade = SvREFCNT(gv) == 2;
840         SvREFCNT_dec_NN(gv);
841         if (try_downgrade)
842             gv_try_downgrade(gv);
843     }
844 }
845
846
847 void
848 Perl_op_clear(pTHX_ OP *o)
849 {
850
851     dVAR;
852
853     PERL_ARGS_ASSERT_OP_CLEAR;
854
855     switch (o->op_type) {
856     case OP_NULL:       /* Was holding old type, if any. */
857         /* FALLTHROUGH */
858     case OP_ENTERTRY:
859     case OP_ENTEREVAL:  /* Was holding hints. */
860         o->op_targ = 0;
861         break;
862     default:
863         if (!(o->op_flags & OPf_REF)
864             || (PL_check[o->op_type] != Perl_ck_ftst))
865             break;
866         /* FALLTHROUGH */
867     case OP_GVSV:
868     case OP_GV:
869     case OP_AELEMFAST:
870 #ifdef USE_ITHREADS
871             S_op_clear_gv(aTHX_ o, &(cPADOPx(o)->op_padix));
872 #else
873             S_op_clear_gv(aTHX_ o, &(cSVOPx(o)->op_sv));
874 #endif
875         break;
876     case OP_METHOD_REDIR:
877     case OP_METHOD_REDIR_SUPER:
878 #ifdef USE_ITHREADS
879         if (cMETHOPx(o)->op_rclass_targ) {
880             pad_swipe(cMETHOPx(o)->op_rclass_targ, 1);
881             cMETHOPx(o)->op_rclass_targ = 0;
882         }
883 #else
884         SvREFCNT_dec(cMETHOPx(o)->op_rclass_sv);
885         cMETHOPx(o)->op_rclass_sv = NULL;
886 #endif
887     case OP_METHOD_NAMED:
888     case OP_METHOD_SUPER:
889         SvREFCNT_dec(cMETHOPx(o)->op_u.op_meth_sv);
890         cMETHOPx(o)->op_u.op_meth_sv = NULL;
891 #ifdef USE_ITHREADS
892         if (o->op_targ) {
893             pad_swipe(o->op_targ, 1);
894             o->op_targ = 0;
895         }
896 #endif
897         break;
898     case OP_CONST:
899     case OP_HINTSEVAL:
900         SvREFCNT_dec(cSVOPo->op_sv);
901         cSVOPo->op_sv = NULL;
902 #ifdef USE_ITHREADS
903         /** Bug #15654
904           Even if op_clear does a pad_free for the target of the op,
905           pad_free doesn't actually remove the sv that exists in the pad;
906           instead it lives on. This results in that it could be reused as 
907           a target later on when the pad was reallocated.
908         **/
909         if(o->op_targ) {
910           pad_swipe(o->op_targ,1);
911           o->op_targ = 0;
912         }
913 #endif
914         break;
915     case OP_DUMP:
916     case OP_GOTO:
917     case OP_NEXT:
918     case OP_LAST:
919     case OP_REDO:
920         if (o->op_flags & (OPf_SPECIAL|OPf_STACKED|OPf_KIDS))
921             break;
922         /* FALLTHROUGH */
923     case OP_TRANS:
924     case OP_TRANSR:
925         if (o->op_private & (OPpTRANS_FROM_UTF|OPpTRANS_TO_UTF)) {
926             assert(o->op_type == OP_TRANS || o->op_type == OP_TRANSR);
927 #ifdef USE_ITHREADS
928             if (cPADOPo->op_padix > 0) {
929                 pad_swipe(cPADOPo->op_padix, TRUE);
930                 cPADOPo->op_padix = 0;
931             }
932 #else
933             SvREFCNT_dec(cSVOPo->op_sv);
934             cSVOPo->op_sv = NULL;
935 #endif
936         }
937         else {
938             PerlMemShared_free(cPVOPo->op_pv);
939             cPVOPo->op_pv = NULL;
940         }
941         break;
942     case OP_SUBST:
943         op_free(cPMOPo->op_pmreplrootu.op_pmreplroot);
944         goto clear_pmop;
945     case OP_PUSHRE:
946 #ifdef USE_ITHREADS
947         if (cPMOPo->op_pmreplrootu.op_pmtargetoff) {
948             pad_swipe(cPMOPo->op_pmreplrootu.op_pmtargetoff, TRUE);
949         }
950 #else
951         SvREFCNT_dec(MUTABLE_SV(cPMOPo->op_pmreplrootu.op_pmtargetgv));
952 #endif
953         /* FALLTHROUGH */
954     case OP_MATCH:
955     case OP_QR:
956     clear_pmop:
957         if (!(cPMOPo->op_pmflags & PMf_CODELIST_PRIVATE))
958             op_free(cPMOPo->op_code_list);
959         cPMOPo->op_code_list = NULL;
960         forget_pmop(cPMOPo);
961         cPMOPo->op_pmreplrootu.op_pmreplroot = NULL;
962         /* we use the same protection as the "SAFE" version of the PM_ macros
963          * here since sv_clean_all might release some PMOPs
964          * after PL_regex_padav has been cleared
965          * and the clearing of PL_regex_padav needs to
966          * happen before sv_clean_all
967          */
968 #ifdef USE_ITHREADS
969         if(PL_regex_pad) {        /* We could be in destruction */
970             const IV offset = (cPMOPo)->op_pmoffset;
971             ReREFCNT_dec(PM_GETRE(cPMOPo));
972             PL_regex_pad[offset] = &PL_sv_undef;
973             sv_catpvn_nomg(PL_regex_pad[0], (const char *)&offset,
974                            sizeof(offset));
975         }
976 #else
977         ReREFCNT_dec(PM_GETRE(cPMOPo));
978         PM_SETRE(cPMOPo, NULL);
979 #endif
980
981         break;
982
983     case OP_MULTIDEREF:
984         {
985             UNOP_AUX_item *items = cUNOP_AUXo->op_aux;
986             UV actions = items->uv;
987             bool last = 0;
988             bool is_hash = FALSE;
989
990             while (!last) {
991                 switch (actions & MDEREF_ACTION_MASK) {
992
993                 case MDEREF_reload:
994                     actions = (++items)->uv;
995                     continue;
996
997                 case MDEREF_HV_padhv_helem:
998                     is_hash = TRUE;
999                 case MDEREF_AV_padav_aelem:
1000                     pad_free((++items)->pad_offset);
1001                     goto do_elem;
1002
1003                 case MDEREF_HV_gvhv_helem:
1004                     is_hash = TRUE;
1005                 case MDEREF_AV_gvav_aelem:
1006 #ifdef USE_ITHREADS
1007                     S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1008 #else
1009                     S_op_clear_gv(aTHX_ o, &((++items)->sv));
1010 #endif
1011                     goto do_elem;
1012
1013                 case MDEREF_HV_gvsv_vivify_rv2hv_helem:
1014                     is_hash = TRUE;
1015                 case MDEREF_AV_gvsv_vivify_rv2av_aelem:
1016 #ifdef USE_ITHREADS
1017                     S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1018 #else
1019                     S_op_clear_gv(aTHX_ o, &((++items)->sv));
1020 #endif
1021                     goto do_vivify_rv2xv_elem;
1022
1023                 case MDEREF_HV_padsv_vivify_rv2hv_helem:
1024                     is_hash = TRUE;
1025                 case MDEREF_AV_padsv_vivify_rv2av_aelem:
1026                     pad_free((++items)->pad_offset);
1027                     goto do_vivify_rv2xv_elem;
1028
1029                 case MDEREF_HV_pop_rv2hv_helem:
1030                 case MDEREF_HV_vivify_rv2hv_helem:
1031                     is_hash = TRUE;
1032                 do_vivify_rv2xv_elem:
1033                 case MDEREF_AV_pop_rv2av_aelem:
1034                 case MDEREF_AV_vivify_rv2av_aelem:
1035                 do_elem:
1036                     switch (actions & MDEREF_INDEX_MASK) {
1037                     case MDEREF_INDEX_none:
1038                         last = 1;
1039                         break;
1040                     case MDEREF_INDEX_const:
1041                         if (is_hash) {
1042 #ifdef USE_ITHREADS
1043                             /* see RT #15654 */
1044                             pad_swipe((++items)->pad_offset, 1);
1045 #else
1046                             SvREFCNT_dec((++items)->sv);
1047 #endif
1048                         }
1049                         else
1050                             items++;
1051                         break;
1052                     case MDEREF_INDEX_padsv:
1053                         pad_free((++items)->pad_offset);
1054                         break;
1055                     case MDEREF_INDEX_gvsv:
1056 #ifdef USE_ITHREADS
1057                         S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1058 #else
1059                         S_op_clear_gv(aTHX_ o, &((++items)->sv));
1060 #endif
1061                         break;
1062                     }
1063
1064                     if (actions & MDEREF_FLAG_last)
1065                         last = 1;
1066                     is_hash = FALSE;
1067
1068                     break;
1069
1070                 default:
1071                     assert(0);
1072                     last = 1;
1073                     break;
1074
1075                 } /* switch */
1076
1077                 actions >>= MDEREF_SHIFT;
1078             } /* while */
1079
1080             /* start of malloc is at op_aux[-1], where the length is
1081              * stored */
1082             PerlMemShared_free(cUNOP_AUXo->op_aux - 1);
1083         }
1084         break;
1085     }
1086
1087     if (o->op_targ > 0) {
1088         pad_free(o->op_targ);
1089         o->op_targ = 0;
1090     }
1091 }
1092
1093 STATIC void
1094 S_cop_free(pTHX_ COP* cop)
1095 {
1096     PERL_ARGS_ASSERT_COP_FREE;
1097
1098     CopFILE_free(cop);
1099     if (! specialWARN(cop->cop_warnings))
1100         PerlMemShared_free(cop->cop_warnings);
1101     cophh_free(CopHINTHASH_get(cop));
1102     if (PL_curcop == cop)
1103        PL_curcop = NULL;
1104 }
1105
1106 STATIC void
1107 S_forget_pmop(pTHX_ PMOP *const o
1108               )
1109 {
1110     HV * const pmstash = PmopSTASH(o);
1111
1112     PERL_ARGS_ASSERT_FORGET_PMOP;
1113
1114     if (pmstash && !SvIS_FREED(pmstash) && SvMAGICAL(pmstash)) {
1115         MAGIC * const mg = mg_find((const SV *)pmstash, PERL_MAGIC_symtab);
1116         if (mg) {
1117             PMOP **const array = (PMOP**) mg->mg_ptr;
1118             U32 count = mg->mg_len / sizeof(PMOP**);
1119             U32 i = count;
1120
1121             while (i--) {
1122                 if (array[i] == o) {
1123                     /* Found it. Move the entry at the end to overwrite it.  */
1124                     array[i] = array[--count];
1125                     mg->mg_len = count * sizeof(PMOP**);
1126                     /* Could realloc smaller at this point always, but probably
1127                        not worth it. Probably worth free()ing if we're the
1128                        last.  */
1129                     if(!count) {
1130                         Safefree(mg->mg_ptr);
1131                         mg->mg_ptr = NULL;
1132                     }
1133                     break;
1134                 }
1135             }
1136         }
1137     }
1138     if (PL_curpm == o) 
1139         PL_curpm = NULL;
1140 }
1141
1142 STATIC void
1143 S_find_and_forget_pmops(pTHX_ OP *o)
1144 {
1145     PERL_ARGS_ASSERT_FIND_AND_FORGET_PMOPS;
1146
1147     if (o->op_flags & OPf_KIDS) {
1148         OP *kid = cUNOPo->op_first;
1149         while (kid) {
1150             switch (kid->op_type) {
1151             case OP_SUBST:
1152             case OP_PUSHRE:
1153             case OP_MATCH:
1154             case OP_QR:
1155                 forget_pmop((PMOP*)kid);
1156             }
1157             find_and_forget_pmops(kid);
1158             kid = OpSIBLING(kid);
1159         }
1160     }
1161 }
1162
1163 /*
1164 =for apidoc Am|void|op_null|OP *o
1165
1166 Neutralizes an op when it is no longer needed, but is still linked to from
1167 other ops.
1168
1169 =cut
1170 */
1171
1172 void
1173 Perl_op_null(pTHX_ OP *o)
1174 {
1175     dVAR;
1176
1177     PERL_ARGS_ASSERT_OP_NULL;
1178
1179     if (o->op_type == OP_NULL)
1180         return;
1181     op_clear(o);
1182     o->op_targ = o->op_type;
1183     CHANGE_TYPE(o, OP_NULL);
1184 }
1185
1186 void
1187 Perl_op_refcnt_lock(pTHX)
1188 {
1189 #ifdef USE_ITHREADS
1190     dVAR;
1191 #endif
1192     PERL_UNUSED_CONTEXT;
1193     OP_REFCNT_LOCK;
1194 }
1195
1196 void
1197 Perl_op_refcnt_unlock(pTHX)
1198 {
1199 #ifdef USE_ITHREADS
1200     dVAR;
1201 #endif
1202     PERL_UNUSED_CONTEXT;
1203     OP_REFCNT_UNLOCK;
1204 }
1205
1206
1207 /*
1208 =for apidoc op_sibling_splice
1209
1210 A general function for editing the structure of an existing chain of
1211 op_sibling nodes.  By analogy with the perl-level splice() function, allows
1212 you to delete zero or more sequential nodes, replacing them with zero or
1213 more different nodes.  Performs the necessary op_first/op_last
1214 housekeeping on the parent node and op_sibling manipulation on the
1215 children.  The last deleted node will be marked as as the last node by
1216 updating the op_sibling or op_lastsib field as appropriate.
1217
1218 Note that op_next is not manipulated, and nodes are not freed; that is the
1219 responsibility of the caller.  It also won't create a new list op for an
1220 empty list etc; use higher-level functions like op_append_elem() for that.
1221
1222 parent is the parent node of the sibling chain.
1223
1224 start is the node preceding the first node to be spliced.  Node(s)
1225 following it will be deleted, and ops will be inserted after it.  If it is
1226 NULL, the first node onwards is deleted, and nodes are inserted at the
1227 beginning.
1228
1229 del_count is the number of nodes to delete.  If zero, no nodes are deleted.
1230 If -1 or greater than or equal to the number of remaining kids, all
1231 remaining kids are deleted.
1232
1233 insert is the first of a chain of nodes to be inserted in place of the nodes.
1234 If NULL, no nodes are inserted.
1235
1236 The head of the chain of deleted ops is returned, or NULL if no ops were
1237 deleted.
1238
1239 For example:
1240
1241     action                    before      after         returns
1242     ------                    -----       -----         -------
1243
1244                               P           P
1245     splice(P, A, 2, X-Y-Z)    |           |             B-C
1246                               A-B-C-D     A-X-Y-Z-D
1247
1248                               P           P
1249     splice(P, NULL, 1, X-Y)   |           |             A
1250                               A-B-C-D     X-Y-B-C-D
1251
1252                               P           P
1253     splice(P, NULL, 3, NULL)  |           |             A-B-C
1254                               A-B-C-D     D
1255
1256                               P           P
1257     splice(P, B, 0, X-Y)      |           |             NULL
1258                               A-B-C-D     A-B-X-Y-C-D
1259
1260 =cut
1261 */
1262
1263 OP *
1264 Perl_op_sibling_splice(OP *parent, OP *start, int del_count, OP* insert)
1265 {
1266     OP *first = start ? OpSIBLING(start) : cLISTOPx(parent)->op_first;
1267     OP *rest;
1268     OP *last_del = NULL;
1269     OP *last_ins = NULL;
1270
1271     PERL_ARGS_ASSERT_OP_SIBLING_SPLICE;
1272
1273     assert(del_count >= -1);
1274
1275     if (del_count && first) {
1276         last_del = first;
1277         while (--del_count && OpHAS_SIBLING(last_del))
1278             last_del = OpSIBLING(last_del);
1279         rest = OpSIBLING(last_del);
1280         OpSIBLING_set(last_del, NULL);
1281         last_del->op_lastsib = 1;
1282     }
1283     else
1284         rest = first;
1285
1286     if (insert) {
1287         last_ins = insert;
1288         while (OpHAS_SIBLING(last_ins))
1289             last_ins = OpSIBLING(last_ins);
1290         OpSIBLING_set(last_ins, rest);
1291         last_ins->op_lastsib = rest ? 0 : 1;
1292     }
1293     else
1294         insert = rest;
1295
1296     if (start) {
1297         OpSIBLING_set(start, insert);
1298         start->op_lastsib = insert ? 0 : 1;
1299     }
1300     else {
1301         cLISTOPx(parent)->op_first = insert;
1302         if (insert)
1303             parent->op_flags |= OPf_KIDS;
1304         else
1305             parent->op_flags &= ~OPf_KIDS;
1306     }
1307
1308     if (!rest) {
1309         /* update op_last etc */
1310         U32 type = parent->op_type;
1311         OP *lastop;
1312
1313         if (type == OP_NULL)
1314             type = parent->op_targ;
1315         type = PL_opargs[type] & OA_CLASS_MASK;
1316
1317         lastop = last_ins ? last_ins : start ? start : NULL;
1318         if (   type == OA_BINOP
1319             || type == OA_LISTOP
1320             || type == OA_PMOP
1321             || type == OA_LOOP
1322         )
1323             cLISTOPx(parent)->op_last = lastop;
1324
1325         if (lastop) {
1326             lastop->op_lastsib = 1;
1327 #ifdef PERL_OP_PARENT
1328             lastop->op_sibling = parent;
1329 #endif
1330         }
1331     }
1332     return last_del ? first : NULL;
1333 }
1334
1335 /*
1336 =for apidoc op_parent
1337
1338 returns the parent OP of o, if it has a parent.  Returns NULL otherwise.
1339 (Currently perl must be built with C<-DPERL_OP_PARENT> for this feature to
1340 work.
1341
1342 =cut
1343 */
1344
1345 OP *
1346 Perl_op_parent(OP *o)
1347 {
1348     PERL_ARGS_ASSERT_OP_PARENT;
1349 #ifdef PERL_OP_PARENT
1350     while (OpHAS_SIBLING(o))
1351         o = OpSIBLING(o);
1352     return o->op_sibling;
1353 #else
1354     PERL_UNUSED_ARG(o);
1355     return NULL;
1356 #endif
1357 }
1358
1359
1360 /* replace the sibling following start with a new UNOP, which becomes
1361  * the parent of the original sibling; e.g.
1362  *
1363  *  op_sibling_newUNOP(P, A, unop-args...)
1364  *
1365  *  P              P
1366  *  |      becomes |
1367  *  A-B-C          A-U-C
1368  *                   |
1369  *                   B
1370  *
1371  * where U is the new UNOP.
1372  *
1373  * parent and start args are the same as for op_sibling_splice();
1374  * type and flags args are as newUNOP().
1375  *
1376  * Returns the new UNOP.
1377  */
1378
1379 OP *
1380 S_op_sibling_newUNOP(pTHX_ OP *parent, OP *start, I32 type, I32 flags)
1381 {
1382     OP *kid, *newop;
1383
1384     kid = op_sibling_splice(parent, start, 1, NULL);
1385     newop = newUNOP(type, flags, kid);
1386     op_sibling_splice(parent, start, 0, newop);
1387     return newop;
1388 }
1389
1390
1391 /* lowest-level newLOGOP-style function - just allocates and populates
1392  * the struct. Higher-level stuff should be done by S_new_logop() /
1393  * newLOGOP(). This function exists mainly to avoid op_first assignment
1394  * being spread throughout this file.
1395  */
1396
1397 LOGOP *
1398 S_alloc_LOGOP(pTHX_ I32 type, OP *first, OP* other)
1399 {
1400     dVAR;
1401     LOGOP *logop;
1402     OP *kid = first;
1403     NewOp(1101, logop, 1, LOGOP);
1404     CHANGE_TYPE(logop, type);
1405     logop->op_first = first;
1406     logop->op_other = other;
1407     logop->op_flags = OPf_KIDS;
1408     while (kid && OpHAS_SIBLING(kid))
1409         kid = OpSIBLING(kid);
1410     if (kid) {
1411         kid->op_lastsib = 1;
1412 #ifdef PERL_OP_PARENT
1413         kid->op_sibling = (OP*)logop;
1414 #endif
1415     }
1416     return logop;
1417 }
1418
1419
1420 /* Contextualizers */
1421
1422 /*
1423 =for apidoc Am|OP *|op_contextualize|OP *o|I32 context
1424
1425 Applies a syntactic context to an op tree representing an expression.
1426 I<o> is the op tree, and I<context> must be C<G_SCALAR>, C<G_ARRAY>,
1427 or C<G_VOID> to specify the context to apply.  The modified op tree
1428 is returned.
1429
1430 =cut
1431 */
1432
1433 OP *
1434 Perl_op_contextualize(pTHX_ OP *o, I32 context)
1435 {
1436     PERL_ARGS_ASSERT_OP_CONTEXTUALIZE;
1437     switch (context) {
1438         case G_SCALAR: return scalar(o);
1439         case G_ARRAY:  return list(o);
1440         case G_VOID:   return scalarvoid(o);
1441         default:
1442             Perl_croak(aTHX_ "panic: op_contextualize bad context %ld",
1443                        (long) context);
1444     }
1445 }
1446
1447 /*
1448
1449 =for apidoc Am|OP*|op_linklist|OP *o
1450 This function is the implementation of the L</LINKLIST> macro.  It should
1451 not be called directly.
1452
1453 =cut
1454 */
1455
1456 OP *
1457 Perl_op_linklist(pTHX_ OP *o)
1458 {
1459     OP *first;
1460
1461     PERL_ARGS_ASSERT_OP_LINKLIST;
1462
1463     if (o->op_next)
1464         return o->op_next;
1465
1466     /* establish postfix order */
1467     first = cUNOPo->op_first;
1468     if (first) {
1469         OP *kid;
1470         o->op_next = LINKLIST(first);
1471         kid = first;
1472         for (;;) {
1473             OP *sibl = OpSIBLING(kid);
1474             if (sibl) {
1475                 kid->op_next = LINKLIST(sibl);
1476                 kid = sibl;
1477             } else {
1478                 kid->op_next = o;
1479                 break;
1480             }
1481         }
1482     }
1483     else
1484         o->op_next = o;
1485
1486     return o->op_next;
1487 }
1488
1489 static OP *
1490 S_scalarkids(pTHX_ OP *o)
1491 {
1492     if (o && o->op_flags & OPf_KIDS) {
1493         OP *kid;
1494         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
1495             scalar(kid);
1496     }
1497     return o;
1498 }
1499
1500 STATIC OP *
1501 S_scalarboolean(pTHX_ OP *o)
1502 {
1503     PERL_ARGS_ASSERT_SCALARBOOLEAN;
1504
1505     if (o->op_type == OP_SASSIGN && cBINOPo->op_first->op_type == OP_CONST
1506      && !(cBINOPo->op_first->op_flags & OPf_SPECIAL)) {
1507         if (ckWARN(WARN_SYNTAX)) {
1508             const line_t oldline = CopLINE(PL_curcop);
1509
1510             if (PL_parser && PL_parser->copline != NOLINE) {
1511                 /* This ensures that warnings are reported at the first line
1512                    of the conditional, not the last.  */
1513                 CopLINE_set(PL_curcop, PL_parser->copline);
1514             }
1515             Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "Found = in conditional, should be ==");
1516             CopLINE_set(PL_curcop, oldline);
1517         }
1518     }
1519     return scalar(o);
1520 }
1521
1522 static SV *
1523 S_op_varname(pTHX_ const OP *o)
1524 {
1525     assert(o);
1526     assert(o->op_type == OP_PADAV || o->op_type == OP_RV2AV ||
1527            o->op_type == OP_PADHV || o->op_type == OP_RV2HV);
1528     {
1529         const char funny  = o->op_type == OP_PADAV
1530                          || o->op_type == OP_RV2AV ? '@' : '%';
1531         if (o->op_type == OP_RV2AV || o->op_type == OP_RV2HV) {
1532             GV *gv;
1533             if (cUNOPo->op_first->op_type != OP_GV
1534              || !(gv = cGVOPx_gv(cUNOPo->op_first)))
1535                 return NULL;
1536             return varname(gv, funny, 0, NULL, 0, 1);
1537         }
1538         return
1539             varname(MUTABLE_GV(PL_compcv), funny, o->op_targ, NULL, 0, 1);
1540     }
1541 }
1542
1543 static void
1544 S_op_pretty(pTHX_ const OP *o, SV **retsv, const char **retpv)
1545 { /* or not so pretty :-) */
1546     if (o->op_type == OP_CONST) {
1547         *retsv = cSVOPo_sv;
1548         if (SvPOK(*retsv)) {
1549             SV *sv = *retsv;
1550             *retsv = sv_newmortal();
1551             pv_pretty(*retsv, SvPVX_const(sv), SvCUR(sv), 32, NULL, NULL,
1552                       PERL_PV_PRETTY_DUMP |PERL_PV_ESCAPE_UNI_DETECT);
1553         }
1554         else if (!SvOK(*retsv))
1555             *retpv = "undef";
1556     }
1557     else *retpv = "...";
1558 }
1559
1560 static void
1561 S_scalar_slice_warning(pTHX_ const OP *o)
1562 {
1563     OP *kid;
1564     const char lbrack =
1565         o->op_type == OP_HSLICE ? '{' : '[';
1566     const char rbrack =
1567         o->op_type == OP_HSLICE ? '}' : ']';
1568     SV *name;
1569     SV *keysv = NULL; /* just to silence compiler warnings */
1570     const char *key = NULL;
1571
1572     if (!(o->op_private & OPpSLICEWARNING))
1573         return;
1574     if (PL_parser && PL_parser->error_count)
1575         /* This warning can be nonsensical when there is a syntax error. */
1576         return;
1577
1578     kid = cLISTOPo->op_first;
1579     kid = OpSIBLING(kid); /* get past pushmark */
1580     /* weed out false positives: any ops that can return lists */
1581     switch (kid->op_type) {
1582     case OP_BACKTICK:
1583     case OP_GLOB:
1584     case OP_READLINE:
1585     case OP_MATCH:
1586     case OP_RV2AV:
1587     case OP_EACH:
1588     case OP_VALUES:
1589     case OP_KEYS:
1590     case OP_SPLIT:
1591     case OP_LIST:
1592     case OP_SORT:
1593     case OP_REVERSE:
1594     case OP_ENTERSUB:
1595     case OP_CALLER:
1596     case OP_LSTAT:
1597     case OP_STAT:
1598     case OP_READDIR:
1599     case OP_SYSTEM:
1600     case OP_TMS:
1601     case OP_LOCALTIME:
1602     case OP_GMTIME:
1603     case OP_ENTEREVAL:
1604     case OP_REACH:
1605     case OP_RKEYS:
1606     case OP_RVALUES:
1607         return;
1608     }
1609
1610     /* Don't warn if we have a nulled list either. */
1611     if (kid->op_type == OP_NULL && kid->op_targ == OP_LIST)
1612         return;
1613
1614     assert(OpSIBLING(kid));
1615     name = S_op_varname(aTHX_ OpSIBLING(kid));
1616     if (!name) /* XS module fiddling with the op tree */
1617         return;
1618     S_op_pretty(aTHX_ kid, &keysv, &key);
1619     assert(SvPOK(name));
1620     sv_chop(name,SvPVX(name)+1);
1621     if (key)
1622        /* diag_listed_as: Scalar value @%s[%s] better written as $%s[%s] */
1623         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1624                    "Scalar value @%"SVf"%c%s%c better written as $%"SVf
1625                    "%c%s%c",
1626                     SVfARG(name), lbrack, key, rbrack, SVfARG(name),
1627                     lbrack, key, rbrack);
1628     else
1629        /* diag_listed_as: Scalar value @%s[%s] better written as $%s[%s] */
1630         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1631                    "Scalar value @%"SVf"%c%"SVf"%c better written as $%"
1632                     SVf"%c%"SVf"%c",
1633                     SVfARG(name), lbrack, SVfARG(keysv), rbrack,
1634                     SVfARG(name), lbrack, SVfARG(keysv), rbrack);
1635 }
1636
1637 OP *
1638 Perl_scalar(pTHX_ OP *o)
1639 {
1640     OP *kid;
1641
1642     /* assumes no premature commitment */
1643     if (!o || (PL_parser && PL_parser->error_count)
1644          || (o->op_flags & OPf_WANT)
1645          || o->op_type == OP_RETURN)
1646     {
1647         return o;
1648     }
1649
1650     o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_SCALAR;
1651
1652     switch (o->op_type) {
1653     case OP_REPEAT:
1654         scalar(cBINOPo->op_first);
1655         if (o->op_private & OPpREPEAT_DOLIST) {
1656             kid = cLISTOPx(cUNOPo->op_first)->op_first;
1657             assert(kid->op_type == OP_PUSHMARK);
1658             if (OpHAS_SIBLING(kid) && !OpHAS_SIBLING(OpSIBLING(kid))) {
1659                 op_null(cLISTOPx(cUNOPo->op_first)->op_first);
1660                 o->op_private &=~ OPpREPEAT_DOLIST;
1661             }
1662         }
1663         break;
1664     case OP_OR:
1665     case OP_AND:
1666     case OP_COND_EXPR:
1667         for (kid = OpSIBLING(cUNOPo->op_first); kid; kid = OpSIBLING(kid))
1668             scalar(kid);
1669         break;
1670         /* FALLTHROUGH */
1671     case OP_SPLIT:
1672     case OP_MATCH:
1673     case OP_QR:
1674     case OP_SUBST:
1675     case OP_NULL:
1676     default:
1677         if (o->op_flags & OPf_KIDS) {
1678             for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid))
1679                 scalar(kid);
1680         }
1681         break;
1682     case OP_LEAVE:
1683     case OP_LEAVETRY:
1684         kid = cLISTOPo->op_first;
1685         scalar(kid);
1686         kid = OpSIBLING(kid);
1687     do_kids:
1688         while (kid) {
1689             OP *sib = OpSIBLING(kid);
1690             if (sib && kid->op_type != OP_LEAVEWHEN
1691              && (  OpHAS_SIBLING(sib) || sib->op_type != OP_NULL
1692                 || (  sib->op_targ != OP_NEXTSTATE
1693                    && sib->op_targ != OP_DBSTATE  )))
1694                 scalarvoid(kid);
1695             else
1696                 scalar(kid);
1697             kid = sib;
1698         }
1699         PL_curcop = &PL_compiling;
1700         break;
1701     case OP_SCOPE:
1702     case OP_LINESEQ:
1703     case OP_LIST:
1704         kid = cLISTOPo->op_first;
1705         goto do_kids;
1706     case OP_SORT:
1707         Perl_ck_warner(aTHX_ packWARN(WARN_VOID), "Useless use of sort in scalar context");
1708         break;
1709     case OP_KVHSLICE:
1710     case OP_KVASLICE:
1711     {
1712         /* Warn about scalar context */
1713         const char lbrack = o->op_type == OP_KVHSLICE ? '{' : '[';
1714         const char rbrack = o->op_type == OP_KVHSLICE ? '}' : ']';
1715         SV *name;
1716         SV *keysv;
1717         const char *key = NULL;
1718
1719         /* This warning can be nonsensical when there is a syntax error. */
1720         if (PL_parser && PL_parser->error_count)
1721             break;
1722
1723         if (!ckWARN(WARN_SYNTAX)) break;
1724
1725         kid = cLISTOPo->op_first;
1726         kid = OpSIBLING(kid); /* get past pushmark */
1727         assert(OpSIBLING(kid));
1728         name = S_op_varname(aTHX_ OpSIBLING(kid));
1729         if (!name) /* XS module fiddling with the op tree */
1730             break;
1731         S_op_pretty(aTHX_ kid, &keysv, &key);
1732         assert(SvPOK(name));
1733         sv_chop(name,SvPVX(name)+1);
1734         if (key)
1735   /* diag_listed_as: %%s[%s] in scalar context better written as $%s[%s] */
1736             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1737                        "%%%"SVf"%c%s%c in scalar context better written "
1738                        "as $%"SVf"%c%s%c",
1739                         SVfARG(name), lbrack, key, rbrack, SVfARG(name),
1740                         lbrack, key, rbrack);
1741         else
1742   /* diag_listed_as: %%s[%s] in scalar context better written as $%s[%s] */
1743             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1744                        "%%%"SVf"%c%"SVf"%c in scalar context better "
1745                        "written as $%"SVf"%c%"SVf"%c",
1746                         SVfARG(name), lbrack, SVfARG(keysv), rbrack,
1747                         SVfARG(name), lbrack, SVfARG(keysv), rbrack);
1748     }
1749     }
1750     return o;
1751 }
1752
1753 OP *
1754 Perl_scalarvoid(pTHX_ OP *arg)
1755 {
1756     dVAR;
1757     OP *kid;
1758     SV* sv;
1759     U8 want;
1760     SSize_t defer_stack_alloc = 0;
1761     SSize_t defer_ix = -1;
1762     OP **defer_stack = NULL;
1763     OP *o = arg;
1764
1765     PERL_ARGS_ASSERT_SCALARVOID;
1766
1767     do {
1768         SV *useless_sv = NULL;
1769         const char* useless = NULL;
1770
1771         if (o->op_type == OP_NEXTSTATE
1772             || o->op_type == OP_DBSTATE
1773             || (o->op_type == OP_NULL && (o->op_targ == OP_NEXTSTATE
1774                                           || o->op_targ == OP_DBSTATE)))
1775             PL_curcop = (COP*)o;                /* for warning below */
1776
1777         /* assumes no premature commitment */
1778         want = o->op_flags & OPf_WANT;
1779         if ((want && want != OPf_WANT_SCALAR)
1780             || (PL_parser && PL_parser->error_count)
1781             || o->op_type == OP_RETURN || o->op_type == OP_REQUIRE || o->op_type == OP_LEAVEWHEN)
1782         {
1783             continue;
1784         }
1785
1786         if ((o->op_private & OPpTARGET_MY)
1787             && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
1788         {
1789             /* newASSIGNOP has already applied scalar context, which we
1790                leave, as if this op is inside SASSIGN.  */
1791             continue;
1792         }
1793
1794         o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
1795
1796         switch (o->op_type) {
1797         default:
1798             if (!(PL_opargs[o->op_type] & OA_FOLDCONST))
1799                 break;
1800             /* FALLTHROUGH */
1801         case OP_REPEAT:
1802             if (o->op_flags & OPf_STACKED)
1803                 break;
1804             if (o->op_type == OP_REPEAT)
1805                 scalar(cBINOPo->op_first);
1806             goto func_ops;
1807         case OP_SUBSTR:
1808             if (o->op_private == 4)
1809                 break;
1810             /* FALLTHROUGH */
1811         case OP_WANTARRAY:
1812         case OP_GV:
1813         case OP_SMARTMATCH:
1814         case OP_AV2ARYLEN:
1815         case OP_REF:
1816         case OP_REFGEN:
1817         case OP_SREFGEN:
1818         case OP_DEFINED:
1819         case OP_HEX:
1820         case OP_OCT:
1821         case OP_LENGTH:
1822         case OP_VEC:
1823         case OP_INDEX:
1824         case OP_RINDEX:
1825         case OP_SPRINTF:
1826         case OP_KVASLICE:
1827         case OP_KVHSLICE:
1828         case OP_UNPACK:
1829         case OP_PACK:
1830         case OP_JOIN:
1831         case OP_LSLICE:
1832         case OP_ANONLIST:
1833         case OP_ANONHASH:
1834         case OP_SORT:
1835         case OP_REVERSE:
1836         case OP_RANGE:
1837         case OP_FLIP:
1838         case OP_FLOP:
1839         case OP_CALLER:
1840         case OP_FILENO:
1841         case OP_EOF:
1842         case OP_TELL:
1843         case OP_GETSOCKNAME:
1844         case OP_GETPEERNAME:
1845         case OP_READLINK:
1846         case OP_TELLDIR:
1847         case OP_GETPPID:
1848         case OP_GETPGRP:
1849         case OP_GETPRIORITY:
1850         case OP_TIME:
1851         case OP_TMS:
1852         case OP_LOCALTIME:
1853         case OP_GMTIME:
1854         case OP_GHBYNAME:
1855         case OP_GHBYADDR:
1856         case OP_GHOSTENT:
1857         case OP_GNBYNAME:
1858         case OP_GNBYADDR:
1859         case OP_GNETENT:
1860         case OP_GPBYNAME:
1861         case OP_GPBYNUMBER:
1862         case OP_GPROTOENT:
1863         case OP_GSBYNAME:
1864         case OP_GSBYPORT:
1865         case OP_GSERVENT:
1866         case OP_GPWNAM:
1867         case OP_GPWUID:
1868         case OP_GGRNAM:
1869         case OP_GGRGID:
1870         case OP_GETLOGIN:
1871         case OP_PROTOTYPE:
1872         case OP_RUNCV:
1873         func_ops:
1874             useless = OP_DESC(o);
1875             break;
1876
1877         case OP_GVSV:
1878         case OP_PADSV:
1879         case OP_PADAV:
1880         case OP_PADHV:
1881         case OP_PADANY:
1882         case OP_AELEM:
1883         case OP_AELEMFAST:
1884         case OP_AELEMFAST_LEX:
1885         case OP_ASLICE:
1886         case OP_HELEM:
1887         case OP_HSLICE:
1888             if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))
1889                 /* Otherwise it's "Useless use of grep iterator" */
1890                 useless = OP_DESC(o);
1891             break;
1892
1893         case OP_SPLIT:
1894             kid = cLISTOPo->op_first;
1895             if (kid && kid->op_type == OP_PUSHRE
1896                 && !kid->op_targ
1897                 && !(o->op_flags & OPf_STACKED)
1898 #ifdef USE_ITHREADS
1899                 && !((PMOP*)kid)->op_pmreplrootu.op_pmtargetoff
1900 #else
1901                 && !((PMOP*)kid)->op_pmreplrootu.op_pmtargetgv
1902 #endif
1903                 )
1904                 useless = OP_DESC(o);
1905             break;
1906
1907         case OP_NOT:
1908             kid = cUNOPo->op_first;
1909             if (kid->op_type != OP_MATCH && kid->op_type != OP_SUBST &&
1910                 kid->op_type != OP_TRANS && kid->op_type != OP_TRANSR) {
1911                 goto func_ops;
1912             }
1913             useless = "negative pattern binding (!~)";
1914             break;
1915
1916         case OP_SUBST:
1917             if (cPMOPo->op_pmflags & PMf_NONDESTRUCT)
1918                 useless = "non-destructive substitution (s///r)";
1919             break;
1920
1921         case OP_TRANSR:
1922             useless = "non-destructive transliteration (tr///r)";
1923             break;
1924
1925         case OP_RV2GV:
1926         case OP_RV2SV:
1927         case OP_RV2AV:
1928         case OP_RV2HV:
1929             if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)) &&
1930                 (!OpHAS_SIBLING(o) || OpSIBLING(o)->op_type != OP_READLINE))
1931                 useless = "a variable";
1932             break;
1933
1934         case OP_CONST:
1935             sv = cSVOPo_sv;
1936             if (cSVOPo->op_private & OPpCONST_STRICT)
1937                 no_bareword_allowed(o);
1938             else {
1939                 if (ckWARN(WARN_VOID)) {
1940                     NV nv;
1941                     /* don't warn on optimised away booleans, eg
1942                      * use constant Foo, 5; Foo || print; */
1943                     if (cSVOPo->op_private & OPpCONST_SHORTCIRCUIT)
1944                         useless = NULL;
1945                     /* the constants 0 and 1 are permitted as they are
1946                        conventionally used as dummies in constructs like
1947                        1 while some_condition_with_side_effects;  */
1948                     else if (SvNIOK(sv) && ((nv = SvNV(sv)) == 0.0 || nv == 1.0))
1949                         useless = NULL;
1950                     else if (SvPOK(sv)) {
1951                         SV * const dsv = newSVpvs("");
1952                         useless_sv
1953                             = Perl_newSVpvf(aTHX_
1954                                             "a constant (%s)",
1955                                             pv_pretty(dsv, SvPVX_const(sv),
1956                                                       SvCUR(sv), 32, NULL, NULL,
1957                                                       PERL_PV_PRETTY_DUMP
1958                                                       | PERL_PV_ESCAPE_NOCLEAR
1959                                                       | PERL_PV_ESCAPE_UNI_DETECT));
1960                         SvREFCNT_dec_NN(dsv);
1961                     }
1962                     else if (SvOK(sv)) {
1963                         useless_sv = Perl_newSVpvf(aTHX_ "a constant (%"SVf")", SVfARG(sv));
1964                     }
1965                     else
1966                         useless = "a constant (undef)";
1967                 }
1968             }
1969             op_null(o);         /* don't execute or even remember it */
1970             break;
1971
1972         case OP_POSTINC:
1973             CHANGE_TYPE(o, OP_PREINC);  /* pre-increment is faster */
1974             break;
1975
1976         case OP_POSTDEC:
1977             CHANGE_TYPE(o, OP_PREDEC);  /* pre-decrement is faster */
1978             break;
1979
1980         case OP_I_POSTINC:
1981             CHANGE_TYPE(o, OP_I_PREINC);        /* pre-increment is faster */
1982             break;
1983
1984         case OP_I_POSTDEC:
1985             CHANGE_TYPE(o, OP_I_PREDEC);        /* pre-decrement is faster */
1986             break;
1987
1988         case OP_SASSIGN: {
1989             OP *rv2gv;
1990             UNOP *refgen, *rv2cv;
1991             LISTOP *exlist;
1992
1993             if ((o->op_private & ~OPpASSIGN_BACKWARDS) != 2)
1994                 break;
1995
1996             rv2gv = ((BINOP *)o)->op_last;
1997             if (!rv2gv || rv2gv->op_type != OP_RV2GV)
1998                 break;
1999
2000             refgen = (UNOP *)((BINOP *)o)->op_first;
2001
2002             if (!refgen || (refgen->op_type != OP_REFGEN
2003                             && refgen->op_type != OP_SREFGEN))
2004                 break;
2005
2006             exlist = (LISTOP *)refgen->op_first;
2007             if (!exlist || exlist->op_type != OP_NULL
2008                 || exlist->op_targ != OP_LIST)
2009                 break;
2010
2011             if (exlist->op_first->op_type != OP_PUSHMARK
2012                 && exlist->op_first != exlist->op_last)
2013                 break;
2014
2015             rv2cv = (UNOP*)exlist->op_last;
2016
2017             if (rv2cv->op_type != OP_RV2CV)
2018                 break;
2019
2020             assert ((rv2gv->op_private & OPpDONT_INIT_GV) == 0);
2021             assert ((o->op_private & OPpASSIGN_CV_TO_GV) == 0);
2022             assert ((rv2cv->op_private & OPpMAY_RETURN_CONSTANT) == 0);
2023
2024             o->op_private |= OPpASSIGN_CV_TO_GV;
2025             rv2gv->op_private |= OPpDONT_INIT_GV;
2026             rv2cv->op_private |= OPpMAY_RETURN_CONSTANT;
2027
2028             break;
2029         }
2030
2031         case OP_AASSIGN: {
2032             inplace_aassign(o);
2033             break;
2034         }
2035
2036         case OP_OR:
2037         case OP_AND:
2038             kid = cLOGOPo->op_first;
2039             if (kid->op_type == OP_NOT
2040                 && (kid->op_flags & OPf_KIDS)) {
2041                 if (o->op_type == OP_AND) {
2042                     CHANGE_TYPE(o, OP_OR);
2043                 } else {
2044                     CHANGE_TYPE(o, OP_AND);
2045                 }
2046                 op_null(kid);
2047             }
2048             /* FALLTHROUGH */
2049
2050         case OP_DOR:
2051         case OP_COND_EXPR:
2052         case OP_ENTERGIVEN:
2053         case OP_ENTERWHEN:
2054             for (kid = OpSIBLING(cUNOPo->op_first); kid; kid = OpSIBLING(kid))
2055                 if (!(kid->op_flags & OPf_KIDS))
2056                     scalarvoid(kid);
2057                 else
2058                     DEFER_OP(kid);
2059         break;
2060
2061         case OP_NULL:
2062             if (o->op_flags & OPf_STACKED)
2063                 break;
2064             /* FALLTHROUGH */
2065         case OP_NEXTSTATE:
2066         case OP_DBSTATE:
2067         case OP_ENTERTRY:
2068         case OP_ENTER:
2069             if (!(o->op_flags & OPf_KIDS))
2070                 break;
2071             /* FALLTHROUGH */
2072         case OP_SCOPE:
2073         case OP_LEAVE:
2074         case OP_LEAVETRY:
2075         case OP_LEAVELOOP:
2076         case OP_LINESEQ:
2077         case OP_LEAVEGIVEN:
2078         case OP_LEAVEWHEN:
2079         kids:
2080             for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2081                 if (!(kid->op_flags & OPf_KIDS))
2082                     scalarvoid(kid);
2083                 else
2084                     DEFER_OP(kid);
2085             break;
2086         case OP_LIST:
2087             /* If the first kid after pushmark is something that the padrange
2088                optimisation would reject, then null the list and the pushmark.
2089             */
2090             if ((kid = cLISTOPo->op_first)->op_type == OP_PUSHMARK
2091                 && (  !(kid = OpSIBLING(kid))
2092                       || (  kid->op_type != OP_PADSV
2093                             && kid->op_type != OP_PADAV
2094                             && kid->op_type != OP_PADHV)
2095                       || kid->op_private & ~OPpLVAL_INTRO
2096                       || !(kid = OpSIBLING(kid))
2097                       || (  kid->op_type != OP_PADSV
2098                             && kid->op_type != OP_PADAV
2099                             && kid->op_type != OP_PADHV)
2100                       || kid->op_private & ~OPpLVAL_INTRO)
2101             ) {
2102                 op_null(cUNOPo->op_first); /* NULL the pushmark */
2103                 op_null(o); /* NULL the list */
2104             }
2105             goto kids;
2106         case OP_ENTEREVAL:
2107             scalarkids(o);
2108             break;
2109         case OP_SCALAR:
2110             scalar(o);
2111             break;
2112         }
2113
2114         if (useless_sv) {
2115             /* mortalise it, in case warnings are fatal.  */
2116             Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
2117                            "Useless use of %"SVf" in void context",
2118                            SVfARG(sv_2mortal(useless_sv)));
2119         }
2120         else if (useless) {
2121             Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
2122                            "Useless use of %s in void context",
2123                            useless);
2124         }
2125     } while ( (o = POP_DEFERRED_OP()) );
2126
2127     Safefree(defer_stack);
2128
2129     return arg;
2130 }
2131
2132 static OP *
2133 S_listkids(pTHX_ OP *o)
2134 {
2135     if (o && o->op_flags & OPf_KIDS) {
2136         OP *kid;
2137         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2138             list(kid);
2139     }
2140     return o;
2141 }
2142
2143 OP *
2144 Perl_list(pTHX_ OP *o)
2145 {
2146     OP *kid;
2147
2148     /* assumes no premature commitment */
2149     if (!o || (o->op_flags & OPf_WANT)
2150          || (PL_parser && PL_parser->error_count)
2151          || o->op_type == OP_RETURN)
2152     {
2153         return o;
2154     }
2155
2156     if ((o->op_private & OPpTARGET_MY)
2157         && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
2158     {
2159         return o;                               /* As if inside SASSIGN */
2160     }
2161
2162     o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_LIST;
2163
2164     switch (o->op_type) {
2165     case OP_FLOP:
2166         list(cBINOPo->op_first);
2167         break;
2168     case OP_REPEAT:
2169         if (o->op_private & OPpREPEAT_DOLIST
2170          && !(o->op_flags & OPf_STACKED))
2171         {
2172             list(cBINOPo->op_first);
2173             kid = cBINOPo->op_last;
2174             if (kid->op_type == OP_CONST && SvIOK(kSVOP_sv)
2175              && SvIVX(kSVOP_sv) == 1)
2176             {
2177                 op_null(o); /* repeat */
2178                 op_null(cUNOPx(cBINOPo->op_first)->op_first);/* pushmark */
2179                 /* const (rhs): */
2180                 op_free(op_sibling_splice(o, cBINOPo->op_first, 1, NULL));
2181             }
2182         }
2183         break;
2184     case OP_OR:
2185     case OP_AND:
2186     case OP_COND_EXPR:
2187         for (kid = OpSIBLING(cUNOPo->op_first); kid; kid = OpSIBLING(kid))
2188             list(kid);
2189         break;
2190     default:
2191     case OP_MATCH:
2192     case OP_QR:
2193     case OP_SUBST:
2194     case OP_NULL:
2195         if (!(o->op_flags & OPf_KIDS))
2196             break;
2197         if (!o->op_next && cUNOPo->op_first->op_type == OP_FLOP) {
2198             list(cBINOPo->op_first);
2199             return gen_constant_list(o);
2200         }
2201         listkids(o);
2202         break;
2203     case OP_LIST:
2204         listkids(o);
2205         if (cLISTOPo->op_first->op_type == OP_PUSHMARK) {
2206             op_null(cUNOPo->op_first); /* NULL the pushmark */
2207             op_null(o); /* NULL the list */
2208         }
2209         break;
2210     case OP_LEAVE:
2211     case OP_LEAVETRY:
2212         kid = cLISTOPo->op_first;
2213         list(kid);
2214         kid = OpSIBLING(kid);
2215     do_kids:
2216         while (kid) {
2217             OP *sib = OpSIBLING(kid);
2218             if (sib && kid->op_type != OP_LEAVEWHEN)
2219                 scalarvoid(kid);
2220             else
2221                 list(kid);
2222             kid = sib;
2223         }
2224         PL_curcop = &PL_compiling;
2225         break;
2226     case OP_SCOPE:
2227     case OP_LINESEQ:
2228         kid = cLISTOPo->op_first;
2229         goto do_kids;
2230     }
2231     return o;
2232 }
2233
2234 static OP *
2235 S_scalarseq(pTHX_ OP *o)
2236 {
2237     if (o) {
2238         const OPCODE type = o->op_type;
2239
2240         if (type == OP_LINESEQ || type == OP_SCOPE ||
2241             type == OP_LEAVE || type == OP_LEAVETRY)
2242         {
2243             OP *kid, *sib;
2244             for (kid = cLISTOPo->op_first; kid; kid = sib) {
2245                 if ((sib = OpSIBLING(kid))
2246                  && (  OpHAS_SIBLING(sib) || sib->op_type != OP_NULL
2247                     || (  sib->op_targ != OP_NEXTSTATE
2248                        && sib->op_targ != OP_DBSTATE  )))
2249                 {
2250                     scalarvoid(kid);
2251                 }
2252             }
2253             PL_curcop = &PL_compiling;
2254         }
2255         o->op_flags &= ~OPf_PARENS;
2256         if (PL_hints & HINT_BLOCK_SCOPE)
2257             o->op_flags |= OPf_PARENS;
2258     }
2259     else
2260         o = newOP(OP_STUB, 0);
2261     return o;
2262 }
2263
2264 STATIC OP *
2265 S_modkids(pTHX_ OP *o, I32 type)
2266 {
2267     if (o && o->op_flags & OPf_KIDS) {
2268         OP *kid;
2269         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2270             op_lvalue(kid, type);
2271     }
2272     return o;
2273 }
2274
2275
2276 /* for a helem/hslice/kvslice, if its a fixed hash, croak on invalid
2277  * const fields. Also, convert CONST keys to HEK-in-SVs.
2278  * rop is the op that retrieves the hash;
2279  * key_op is the first key
2280  */
2281
2282 void
2283 S_check_hash_fields_and_hekify(pTHX_ UNOP *rop, SVOP *key_op)
2284 {
2285     PADNAME *lexname;
2286     GV **fields;
2287     bool check_fields;
2288
2289     /* find the padsv corresponding to $lex->{} or @{$lex}{} */
2290     if (rop) {
2291         if (rop->op_first->op_type == OP_PADSV)
2292             /* @$hash{qw(keys here)} */
2293             rop = (UNOP*)rop->op_first;
2294         else {
2295             /* @{$hash}{qw(keys here)} */
2296             if (rop->op_first->op_type == OP_SCOPE
2297                 && cLISTOPx(rop->op_first)->op_last->op_type == OP_PADSV)
2298                 {
2299                     rop = (UNOP*)cLISTOPx(rop->op_first)->op_last;
2300                 }
2301             else
2302                 rop = NULL;
2303         }
2304     }
2305
2306     lexname = NULL; /* just to silence compiler warnings */
2307     fields  = NULL; /* just to silence compiler warnings */
2308
2309     check_fields =
2310             rop
2311          && (lexname = padnamelist_fetch(PL_comppad_name, rop->op_targ),
2312              SvPAD_TYPED(lexname))
2313          && (fields = (GV**)hv_fetchs(PadnameTYPE(lexname), "FIELDS", FALSE))
2314          && isGV(*fields) && GvHV(*fields);
2315
2316     for (; key_op; key_op = (SVOP*)OpSIBLING(key_op)) {
2317         SV **svp, *sv;
2318         if (key_op->op_type != OP_CONST)
2319             continue;
2320         svp = cSVOPx_svp(key_op);
2321
2322         /* Make the CONST have a shared SV */
2323         if (   !SvIsCOW_shared_hash(sv = *svp)
2324             && SvTYPE(sv) < SVt_PVMG
2325             && SvOK(sv)
2326             && !SvROK(sv))
2327         {
2328             SSize_t keylen;
2329             const char * const key = SvPV_const(sv, *(STRLEN*)&keylen);
2330             SV *nsv = newSVpvn_share(key, SvUTF8(sv) ? -keylen : keylen, 0);
2331             SvREFCNT_dec_NN(sv);
2332             *svp = nsv;
2333         }
2334
2335         if (   check_fields
2336             && !hv_fetch_ent(GvHV(*fields), *svp, FALSE, 0))
2337         {
2338             Perl_croak(aTHX_ "No such class field \"%"SVf"\" "
2339                         "in variable %"PNf" of type %"HEKf,
2340                         SVfARG(*svp), PNfARG(lexname),
2341                         HEKfARG(HvNAME_HEK(PadnameTYPE(lexname))));
2342         }
2343     }
2344 }
2345
2346
2347 /*
2348 =for apidoc finalize_optree
2349
2350 This function finalizes the optree.  Should be called directly after
2351 the complete optree is built.  It does some additional
2352 checking which can't be done in the normal ck_xxx functions and makes
2353 the tree thread-safe.
2354
2355 =cut
2356 */
2357 void
2358 Perl_finalize_optree(pTHX_ OP* o)
2359 {
2360     PERL_ARGS_ASSERT_FINALIZE_OPTREE;
2361
2362     ENTER;
2363     SAVEVPTR(PL_curcop);
2364
2365     finalize_op(o);
2366
2367     LEAVE;
2368 }
2369
2370 #ifdef USE_ITHREADS
2371 /* Relocate sv to the pad for thread safety.
2372  * Despite being a "constant", the SV is written to,
2373  * for reference counts, sv_upgrade() etc. */
2374 PERL_STATIC_INLINE void
2375 S_op_relocate_sv(pTHX_ SV** svp, PADOFFSET* targp)
2376 {
2377     PADOFFSET ix;
2378     PERL_ARGS_ASSERT_OP_RELOCATE_SV;
2379     if (!*svp) return;
2380     ix = pad_alloc(OP_CONST, SVf_READONLY);
2381     SvREFCNT_dec(PAD_SVl(ix));
2382     PAD_SETSV(ix, *svp);
2383     /* XXX I don't know how this isn't readonly already. */
2384     if (!SvIsCOW(PAD_SVl(ix))) SvREADONLY_on(PAD_SVl(ix));
2385     *svp = NULL;
2386     *targp = ix;
2387 }
2388 #endif
2389
2390
2391 STATIC void
2392 S_finalize_op(pTHX_ OP* o)
2393 {
2394     PERL_ARGS_ASSERT_FINALIZE_OP;
2395
2396
2397     switch (o->op_type) {
2398     case OP_NEXTSTATE:
2399     case OP_DBSTATE:
2400         PL_curcop = ((COP*)o);          /* for warnings */
2401         break;
2402     case OP_EXEC:
2403         if (OpHAS_SIBLING(o)) {
2404             OP *sib = OpSIBLING(o);
2405             if ((  sib->op_type == OP_NEXTSTATE || sib->op_type == OP_DBSTATE)
2406                 && ckWARN(WARN_EXEC)
2407                 && OpHAS_SIBLING(sib))
2408             {
2409                     const OPCODE type = OpSIBLING(sib)->op_type;
2410                     if (type != OP_EXIT && type != OP_WARN && type != OP_DIE) {
2411                         const line_t oldline = CopLINE(PL_curcop);
2412                         CopLINE_set(PL_curcop, CopLINE((COP*)sib));
2413                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
2414                             "Statement unlikely to be reached");
2415                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
2416                             "\t(Maybe you meant system() when you said exec()?)\n");
2417                         CopLINE_set(PL_curcop, oldline);
2418                     }
2419             }
2420         }
2421         break;
2422
2423     case OP_GV:
2424         if ((o->op_private & OPpEARLY_CV) && ckWARN(WARN_PROTOTYPE)) {
2425             GV * const gv = cGVOPo_gv;
2426             if (SvTYPE(gv) == SVt_PVGV && GvCV(gv) && SvPVX_const(GvCV(gv))) {
2427                 /* XXX could check prototype here instead of just carping */
2428                 SV * const sv = sv_newmortal();
2429                 gv_efullname3(sv, gv, NULL);
2430                 Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
2431                     "%"SVf"() called too early to check prototype",
2432                     SVfARG(sv));
2433             }
2434         }
2435         break;
2436
2437     case OP_CONST:
2438         if (cSVOPo->op_private & OPpCONST_STRICT)
2439             no_bareword_allowed(o);
2440         /* FALLTHROUGH */
2441 #ifdef USE_ITHREADS
2442     case OP_HINTSEVAL:
2443         op_relocate_sv(&cSVOPo->op_sv, &o->op_targ);
2444 #endif
2445         break;
2446
2447 #ifdef USE_ITHREADS
2448     /* Relocate all the METHOP's SVs to the pad for thread safety. */
2449     case OP_METHOD_NAMED:
2450     case OP_METHOD_SUPER:
2451     case OP_METHOD_REDIR:
2452     case OP_METHOD_REDIR_SUPER:
2453         op_relocate_sv(&cMETHOPx(o)->op_u.op_meth_sv, &o->op_targ);
2454         break;
2455 #endif
2456
2457     case OP_HELEM: {
2458         UNOP *rop;
2459         SVOP *key_op;
2460         OP *kid;
2461
2462         if ((key_op = cSVOPx(((BINOP*)o)->op_last))->op_type != OP_CONST)
2463             break;
2464
2465         rop = (UNOP*)((BINOP*)o)->op_first;
2466
2467         goto check_keys;
2468
2469     case OP_HSLICE:
2470         S_scalar_slice_warning(aTHX_ o);
2471         /* FALLTHROUGH */
2472
2473     case OP_KVHSLICE:
2474         kid = OpSIBLING(cLISTOPo->op_first);
2475         if (/* I bet there's always a pushmark... */
2476             OP_TYPE_ISNT_AND_WASNT_NN(kid, OP_LIST)
2477             && OP_TYPE_ISNT_NN(kid, OP_CONST))
2478         {
2479             break;
2480         }
2481
2482         key_op = (SVOP*)(kid->op_type == OP_CONST
2483                                 ? kid
2484                                 : OpSIBLING(kLISTOP->op_first));
2485
2486         rop = (UNOP*)((LISTOP*)o)->op_last;
2487
2488       check_keys:       
2489         if (o->op_private & OPpLVAL_INTRO || rop->op_type != OP_RV2HV)
2490             rop = NULL;
2491         S_check_hash_fields_and_hekify(aTHX_ rop, key_op);
2492         break;
2493     }
2494     case OP_ASLICE:
2495         S_scalar_slice_warning(aTHX_ o);
2496         break;
2497
2498     case OP_SUBST: {
2499         if (cPMOPo->op_pmreplrootu.op_pmreplroot)
2500             finalize_op(cPMOPo->op_pmreplrootu.op_pmreplroot);
2501         break;
2502     }
2503     default:
2504         break;
2505     }
2506
2507     if (o->op_flags & OPf_KIDS) {
2508         OP *kid;
2509
2510 #ifdef DEBUGGING
2511         /* check that op_last points to the last sibling, and that
2512          * the last op_sibling field points back to the parent, and
2513          * that the only ops with KIDS are those which are entitled to
2514          * them */
2515         U32 type = o->op_type;
2516         U32 family;
2517         bool has_last;
2518
2519         if (type == OP_NULL) {
2520             type = o->op_targ;
2521             /* ck_glob creates a null UNOP with ex-type GLOB
2522              * (which is a list op. So pretend it wasn't a listop */
2523             if (type == OP_GLOB)
2524                 type = OP_NULL;
2525         }
2526         family = PL_opargs[type] & OA_CLASS_MASK;
2527
2528         has_last = (   family == OA_BINOP
2529                     || family == OA_LISTOP
2530                     || family == OA_PMOP
2531                     || family == OA_LOOP
2532                    );
2533         assert(  has_last /* has op_first and op_last, or ...
2534               ... has (or may have) op_first: */
2535               || family == OA_UNOP
2536               || family == OA_UNOP_AUX
2537               || family == OA_LOGOP
2538               || family == OA_BASEOP_OR_UNOP
2539               || family == OA_FILESTATOP
2540               || family == OA_LOOPEXOP
2541               || family == OA_METHOP
2542               /* I don't know why SASSIGN is tagged as OA_BASEOP - DAPM */
2543               || type == OP_SASSIGN
2544               || type == OP_CUSTOM
2545               || type == OP_NULL /* new_logop does this */
2546               );
2547
2548         for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
2549 #  ifdef PERL_OP_PARENT
2550             if (!OpHAS_SIBLING(kid)) {
2551                 if (has_last)
2552                     assert(kid == cLISTOPo->op_last);
2553                 assert(kid->op_sibling == o);
2554             }
2555 #  else
2556             if (OpHAS_SIBLING(kid)) {
2557                 assert(!kid->op_lastsib);
2558             }
2559             else {
2560                 assert(kid->op_lastsib);
2561                 if (has_last)
2562                     assert(kid == cLISTOPo->op_last);
2563             }
2564 #  endif
2565         }
2566 #endif
2567
2568         for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid))
2569             finalize_op(kid);
2570     }
2571 }
2572
2573 /*
2574 =for apidoc Amx|OP *|op_lvalue|OP *o|I32 type
2575
2576 Propagate lvalue ("modifiable") context to an op and its children.
2577 I<type> represents the context type, roughly based on the type of op that
2578 would do the modifying, although C<local()> is represented by OP_NULL,
2579 because it has no op type of its own (it is signalled by a flag on
2580 the lvalue op).
2581
2582 This function detects things that can't be modified, such as C<$x+1>, and
2583 generates errors for them.  For example, C<$x+1 = 2> would cause it to be
2584 called with an op of type OP_ADD and a C<type> argument of OP_SASSIGN.
2585
2586 It also flags things that need to behave specially in an lvalue context,
2587 such as C<$$x = 5> which might have to vivify a reference in C<$x>.
2588
2589 =cut
2590 */
2591
2592 static void
2593 S_mark_padname_lvalue(pTHX_ PADNAME *pn)
2594 {
2595     CV *cv = PL_compcv;
2596     PadnameLVALUE_on(pn);
2597     while (PadnameOUTER(pn) && PARENT_PAD_INDEX(pn)) {
2598         cv = CvOUTSIDE(cv);
2599         assert(cv);
2600         assert(CvPADLIST(cv));
2601         pn =
2602            PadlistNAMESARRAY(CvPADLIST(cv))[PARENT_PAD_INDEX(pn)];
2603         assert(PadnameLEN(pn));
2604         PadnameLVALUE_on(pn);
2605     }
2606 }
2607
2608 static bool
2609 S_vivifies(const OPCODE type)
2610 {
2611     switch(type) {
2612     case OP_RV2AV:     case   OP_ASLICE:
2613     case OP_RV2HV:     case OP_KVASLICE:
2614     case OP_RV2SV:     case   OP_HSLICE:
2615     case OP_AELEMFAST: case OP_KVHSLICE:
2616     case OP_HELEM:
2617     case OP_AELEM:
2618         return 1;
2619     }
2620     return 0;
2621 }
2622
2623 static void
2624 S_lvref(pTHX_ OP *o, I32 type)
2625 {
2626     dVAR;
2627     OP *kid;
2628     switch (o->op_type) {
2629     case OP_COND_EXPR:
2630         for (kid = OpSIBLING(cUNOPo->op_first); kid;
2631              kid = OpSIBLING(kid))
2632             S_lvref(aTHX_ kid, type);
2633         /* FALLTHROUGH */
2634     case OP_PUSHMARK:
2635         return;
2636     case OP_RV2AV:
2637         if (cUNOPo->op_first->op_type != OP_GV) goto badref;
2638         o->op_flags |= OPf_STACKED;
2639         if (o->op_flags & OPf_PARENS) {
2640             if (o->op_private & OPpLVAL_INTRO) {
2641                  yyerror(Perl_form(aTHX_ "Can't modify reference to "
2642                       "localized parenthesized array in list assignment"));
2643                 return;
2644             }
2645           slurpy:
2646             CHANGE_TYPE(o, OP_LVAVREF);
2647             o->op_private &= OPpLVAL_INTRO|OPpPAD_STATE;
2648             o->op_flags |= OPf_MOD|OPf_REF;
2649             return;
2650         }
2651         o->op_private |= OPpLVREF_AV;
2652         goto checkgv;
2653     case OP_RV2CV:
2654         kid = cUNOPo->op_first;
2655         if (kid->op_type == OP_NULL)
2656             kid = cUNOPx(kUNOP->op_first->op_sibling)
2657                 ->op_first;
2658         o->op_private = OPpLVREF_CV;
2659         if (kid->op_type == OP_GV)
2660             o->op_flags |= OPf_STACKED;
2661         else if (kid->op_type == OP_PADCV) {
2662             o->op_targ = kid->op_targ;
2663             kid->op_targ = 0;
2664             op_free(cUNOPo->op_first);
2665             cUNOPo->op_first = NULL;
2666             o->op_flags &=~ OPf_KIDS;
2667         }
2668         else goto badref;
2669         break;
2670     case OP_RV2HV:
2671         if (o->op_flags & OPf_PARENS) {
2672           parenhash:
2673             yyerror(Perl_form(aTHX_ "Can't modify reference to "
2674                                  "parenthesized hash in list assignment"));
2675                 return;
2676         }
2677         o->op_private |= OPpLVREF_HV;
2678         /* FALLTHROUGH */
2679     case OP_RV2SV:
2680       checkgv:
2681         if (cUNOPo->op_first->op_type != OP_GV) goto badref;
2682         o->op_flags |= OPf_STACKED;
2683         break;
2684     case OP_PADHV:
2685         if (o->op_flags & OPf_PARENS) goto parenhash;
2686         o->op_private |= OPpLVREF_HV;
2687         /* FALLTHROUGH */
2688     case OP_PADSV:
2689         PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
2690         break;
2691     case OP_PADAV:
2692         PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
2693         if (o->op_flags & OPf_PARENS) goto slurpy;
2694         o->op_private |= OPpLVREF_AV;
2695         break;
2696     case OP_AELEM:
2697     case OP_HELEM:
2698         o->op_private |= OPpLVREF_ELEM;
2699         o->op_flags   |= OPf_STACKED;
2700         break;
2701     case OP_ASLICE:
2702     case OP_HSLICE:
2703         CHANGE_TYPE(o, OP_LVREFSLICE);
2704         o->op_private &= OPpLVAL_INTRO|OPpLVREF_ELEM;
2705         return;
2706     case OP_NULL:
2707         if (o->op_flags & OPf_SPECIAL)          /* do BLOCK */
2708             goto badref;
2709         else if (!(o->op_flags & OPf_KIDS))
2710             return;
2711         if (o->op_targ != OP_LIST) {
2712             S_lvref(aTHX_ cBINOPo->op_first, type);
2713             return;
2714         }
2715         /* FALLTHROUGH */
2716     case OP_LIST:
2717         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid)) {
2718             assert((kid->op_flags & OPf_WANT) != OPf_WANT_VOID);
2719             S_lvref(aTHX_ kid, type);
2720         }
2721         return;
2722     case OP_STUB:
2723         if (o->op_flags & OPf_PARENS)
2724             return;
2725         /* FALLTHROUGH */
2726     default:
2727       badref:
2728         /* diag_listed_as: Can't modify reference to %s in %s assignment */
2729         yyerror(Perl_form(aTHX_ "Can't modify reference to %s in %s",
2730                      o->op_type == OP_NULL && o->op_flags & OPf_SPECIAL
2731                       ? "do block"
2732                       : OP_DESC(o),
2733                      PL_op_desc[type]));
2734     }
2735     CHANGE_TYPE(o, OP_LVREF);
2736     o->op_private &=
2737         OPpLVAL_INTRO|OPpLVREF_ELEM|OPpLVREF_TYPE|OPpPAD_STATE;
2738     if (type == OP_ENTERLOOP)
2739         o->op_private |= OPpLVREF_ITER;
2740 }
2741
2742 OP *
2743 Perl_op_lvalue_flags(pTHX_ OP *o, I32 type, U32 flags)
2744 {
2745     dVAR;
2746     OP *kid;
2747     /* -1 = error on localize, 0 = ignore localize, 1 = ok to localize */
2748     int localize = -1;
2749
2750     if (!o || (PL_parser && PL_parser->error_count))
2751         return o;
2752
2753     if ((o->op_private & OPpTARGET_MY)
2754         && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
2755     {
2756         return o;
2757     }
2758
2759     assert( (o->op_flags & OPf_WANT) != OPf_WANT_VOID );
2760
2761     if (type == OP_PRTF || type == OP_SPRINTF) type = OP_ENTERSUB;
2762
2763     switch (o->op_type) {
2764     case OP_UNDEF:
2765         PL_modcount++;
2766         return o;
2767     case OP_STUB:
2768         if ((o->op_flags & OPf_PARENS))
2769             break;
2770         goto nomod;
2771     case OP_ENTERSUB:
2772         if ((type == OP_UNDEF || type == OP_REFGEN || type == OP_LOCK) &&
2773             !(o->op_flags & OPf_STACKED)) {
2774             CHANGE_TYPE(o, OP_RV2CV);           /* entersub => rv2cv */
2775             assert(cUNOPo->op_first->op_type == OP_NULL);
2776             op_null(((LISTOP*)cUNOPo->op_first)->op_first);/* disable pushmark */
2777             break;
2778         }
2779         else {                          /* lvalue subroutine call */
2780             o->op_private |= OPpLVAL_INTRO;
2781             PL_modcount = RETURN_UNLIMITED_NUMBER;
2782             if (type == OP_GREPSTART || type == OP_ENTERSUB
2783              || type == OP_REFGEN    || type == OP_LEAVESUBLV) {
2784                 /* Potential lvalue context: */
2785                 o->op_private |= OPpENTERSUB_INARGS;
2786                 break;
2787             }
2788             else {                      /* Compile-time error message: */
2789                 OP *kid = cUNOPo->op_first;
2790                 CV *cv;
2791                 GV *gv;
2792
2793                 if (kid->op_type != OP_PUSHMARK) {
2794                     if (kid->op_type != OP_NULL || kid->op_targ != OP_LIST)
2795                         Perl_croak(aTHX_
2796                                 "panic: unexpected lvalue entersub "
2797                                 "args: type/targ %ld:%"UVuf,
2798                                 (long)kid->op_type, (UV)kid->op_targ);
2799                     kid = kLISTOP->op_first;
2800                 }
2801                 while (OpHAS_SIBLING(kid))
2802                     kid = OpSIBLING(kid);
2803                 if (!(kid->op_type == OP_NULL && kid->op_targ == OP_RV2CV)) {
2804                     break;      /* Postpone until runtime */
2805                 }
2806
2807                 kid = kUNOP->op_first;
2808                 if (kid->op_type == OP_NULL && kid->op_targ == OP_RV2SV)
2809                     kid = kUNOP->op_first;
2810                 if (kid->op_type == OP_NULL)
2811                     Perl_croak(aTHX_
2812                                "Unexpected constant lvalue entersub "
2813                                "entry via type/targ %ld:%"UVuf,
2814                                (long)kid->op_type, (UV)kid->op_targ);
2815                 if (kid->op_type != OP_GV) {
2816                     break;
2817                 }
2818
2819                 gv = kGVOP_gv;
2820                 cv = isGV(gv)
2821                     ? GvCV(gv)
2822                     : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
2823                         ? MUTABLE_CV(SvRV(gv))
2824                         : NULL;
2825                 if (!cv)
2826                     break;
2827                 if (CvLVALUE(cv))
2828                     break;
2829             }
2830         }
2831         /* FALLTHROUGH */
2832     default:
2833       nomod:
2834         if (flags & OP_LVALUE_NO_CROAK) return NULL;
2835         /* grep, foreach, subcalls, refgen */
2836         if (type == OP_GREPSTART || type == OP_ENTERSUB
2837          || type == OP_REFGEN    || type == OP_LEAVESUBLV)
2838             break;
2839         yyerror(Perl_form(aTHX_ "Can't modify %s in %s",
2840                      (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)
2841                       ? "do block"
2842                       : (o->op_type == OP_ENTERSUB
2843                         ? "non-lvalue subroutine call"
2844                         : OP_DESC(o))),
2845                      type ? PL_op_desc[type] : "local"));
2846         return o;
2847
2848     case OP_PREINC:
2849     case OP_PREDEC:
2850     case OP_POW:
2851     case OP_MULTIPLY:
2852     case OP_DIVIDE:
2853     case OP_MODULO:
2854     case OP_ADD:
2855     case OP_SUBTRACT:
2856     case OP_CONCAT:
2857     case OP_LEFT_SHIFT:
2858     case OP_RIGHT_SHIFT:
2859     case OP_BIT_AND:
2860     case OP_BIT_XOR:
2861     case OP_BIT_OR:
2862     case OP_I_MULTIPLY:
2863     case OP_I_DIVIDE:
2864     case OP_I_MODULO:
2865     case OP_I_ADD:
2866     case OP_I_SUBTRACT:
2867         if (!(o->op_flags & OPf_STACKED))
2868             goto nomod;
2869         PL_modcount++;
2870         break;
2871
2872     case OP_REPEAT:
2873         if (o->op_flags & OPf_STACKED) {
2874             PL_modcount++;
2875             break;
2876         }
2877         if (!(o->op_private & OPpREPEAT_DOLIST))
2878             goto nomod;
2879         else {
2880             const I32 mods = PL_modcount;
2881             modkids(cBINOPo->op_first, type);
2882             if (type != OP_AASSIGN)
2883                 goto nomod;
2884             kid = cBINOPo->op_last;
2885             if (kid->op_type == OP_CONST && SvIOK(kSVOP_sv)) {
2886                 const IV iv = SvIV(kSVOP_sv);
2887                 if (PL_modcount != RETURN_UNLIMITED_NUMBER)
2888                     PL_modcount =
2889                         mods + (PL_modcount - mods) * (iv < 0 ? 0 : iv);
2890             }
2891             else
2892                 PL_modcount = RETURN_UNLIMITED_NUMBER;
2893         }
2894         break;
2895
2896     case OP_COND_EXPR:
2897         localize = 1;
2898         for (kid = OpSIBLING(cUNOPo->op_first); kid; kid = OpSIBLING(kid))
2899             op_lvalue(kid, type);
2900         break;
2901
2902     case OP_RV2AV:
2903     case OP_RV2HV:
2904         if (type == OP_REFGEN && o->op_flags & OPf_PARENS) {
2905            PL_modcount = RETURN_UNLIMITED_NUMBER;
2906             return o;           /* Treat \(@foo) like ordinary list. */
2907         }
2908         /* FALLTHROUGH */
2909     case OP_RV2GV:
2910         if (scalar_mod_type(o, type))
2911             goto nomod;
2912         ref(cUNOPo->op_first, o->op_type);
2913         /* FALLTHROUGH */
2914     case OP_ASLICE:
2915     case OP_HSLICE:
2916         localize = 1;
2917         /* FALLTHROUGH */
2918     case OP_AASSIGN:
2919         /* Do not apply the lvsub flag for rv2[ah]v in scalar context.  */
2920         if (type == OP_LEAVESUBLV && (
2921                 (o->op_type != OP_RV2AV && o->op_type != OP_RV2HV)
2922              || (o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
2923            ))
2924             o->op_private |= OPpMAYBE_LVSUB;
2925         /* FALLTHROUGH */
2926     case OP_NEXTSTATE:
2927     case OP_DBSTATE:
2928        PL_modcount = RETURN_UNLIMITED_NUMBER;
2929         break;
2930     case OP_KVHSLICE:
2931     case OP_KVASLICE:
2932         if (type == OP_LEAVESUBLV)
2933             o->op_private |= OPpMAYBE_LVSUB;
2934         goto nomod;
2935     case OP_AV2ARYLEN:
2936         PL_hints |= HINT_BLOCK_SCOPE;
2937         if (type == OP_LEAVESUBLV)
2938             o->op_private |= OPpMAYBE_LVSUB;
2939         PL_modcount++;
2940         break;
2941     case OP_RV2SV:
2942         ref(cUNOPo->op_first, o->op_type);
2943         localize = 1;
2944         /* FALLTHROUGH */
2945     case OP_GV:
2946         PL_hints |= HINT_BLOCK_SCOPE;
2947         /* FALLTHROUGH */
2948     case OP_SASSIGN:
2949     case OP_ANDASSIGN:
2950     case OP_ORASSIGN:
2951     case OP_DORASSIGN:
2952         PL_modcount++;
2953         break;
2954
2955     case OP_AELEMFAST:
2956     case OP_AELEMFAST_LEX:
2957         localize = -1;
2958         PL_modcount++;
2959         break;
2960
2961     case OP_PADAV:
2962     case OP_PADHV:
2963        PL_modcount = RETURN_UNLIMITED_NUMBER;
2964         if (type == OP_REFGEN && o->op_flags & OPf_PARENS)
2965             return o;           /* Treat \(@foo) like ordinary list. */
2966         if (scalar_mod_type(o, type))
2967             goto nomod;
2968         if ((o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
2969           && type == OP_LEAVESUBLV)
2970             o->op_private |= OPpMAYBE_LVSUB;
2971         /* FALLTHROUGH */
2972     case OP_PADSV:
2973         PL_modcount++;
2974         if (!type) /* local() */
2975             Perl_croak(aTHX_ "Can't localize lexical variable %"PNf,
2976                               PNfARG(PAD_COMPNAME(o->op_targ)));
2977         if (!(o->op_private & OPpLVAL_INTRO)
2978          || (  type != OP_SASSIGN && type != OP_AASSIGN
2979             && PadnameIsSTATE(PAD_COMPNAME_SV(o->op_targ))  ))
2980             S_mark_padname_lvalue(aTHX_ PAD_COMPNAME_SV(o->op_targ));
2981         break;
2982
2983     case OP_PUSHMARK:
2984         localize = 0;
2985         break;
2986
2987     case OP_KEYS:
2988     case OP_RKEYS:
2989         if (type != OP_SASSIGN && type != OP_LEAVESUBLV)
2990             goto nomod;
2991         goto lvalue_func;
2992     case OP_SUBSTR:
2993         if (o->op_private == 4) /* don't allow 4 arg substr as lvalue */
2994             goto nomod;
2995         /* FALLTHROUGH */
2996     case OP_POS:
2997     case OP_VEC:
2998       lvalue_func:
2999         if (type == OP_LEAVESUBLV)
3000             o->op_private |= OPpMAYBE_LVSUB;
3001         if (o->op_flags & OPf_KIDS)
3002             op_lvalue(OpSIBLING(cBINOPo->op_first), type);
3003         break;
3004
3005     case OP_AELEM:
3006     case OP_HELEM:
3007         ref(cBINOPo->op_first, o->op_type);
3008         if (type == OP_ENTERSUB &&
3009              !(o->op_private & (OPpLVAL_INTRO | OPpDEREF)))
3010             o->op_private |= OPpLVAL_DEFER;
3011         if (type == OP_LEAVESUBLV)
3012             o->op_private |= OPpMAYBE_LVSUB;
3013         localize = 1;
3014         PL_modcount++;
3015         break;
3016
3017     case OP_LEAVE:
3018     case OP_LEAVELOOP:
3019         o->op_private |= OPpLVALUE;
3020         /* FALLTHROUGH */
3021     case OP_SCOPE:
3022     case OP_ENTER:
3023     case OP_LINESEQ:
3024         localize = 0;
3025         if (o->op_flags & OPf_KIDS)
3026             op_lvalue(cLISTOPo->op_last, type);
3027         break;
3028
3029     case OP_NULL:
3030         localize = 0;
3031         if (o->op_flags & OPf_SPECIAL)          /* do BLOCK */
3032             goto nomod;
3033         else if (!(o->op_flags & OPf_KIDS))
3034             break;
3035         if (o->op_targ != OP_LIST) {
3036             op_lvalue(cBINOPo->op_first, type);
3037             break;
3038         }
3039         /* FALLTHROUGH */
3040     case OP_LIST:
3041         localize = 0;
3042         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
3043             /* elements might be in void context because the list is
3044                in scalar context or because they are attribute sub calls */
3045             if ( (kid->op_flags & OPf_WANT) != OPf_WANT_VOID )
3046                 op_lvalue(kid, type);
3047         break;
3048
3049     case OP_COREARGS:
3050         return o;
3051
3052     case OP_AND:
3053     case OP_OR:
3054         if (type == OP_LEAVESUBLV
3055          || !S_vivifies(cLOGOPo->op_first->op_type))
3056             op_lvalue(cLOGOPo->op_first, type);
3057         if (type == OP_LEAVESUBLV
3058          || !S_vivifies(OpSIBLING(cLOGOPo->op_first)->op_type))
3059             op_lvalue(OpSIBLING(cLOGOPo->op_first), type);
3060         goto nomod;
3061
3062     case OP_SREFGEN:
3063         if (type != OP_AASSIGN && type != OP_SASSIGN
3064          && type != OP_ENTERLOOP)
3065             goto nomod;
3066         /* Don’t bother applying lvalue context to the ex-list.  */
3067         kid = cUNOPx(cUNOPo->op_first)->op_first;
3068         assert (!OpHAS_SIBLING(kid));
3069         goto kid_2lvref;
3070     case OP_REFGEN:
3071         if (type != OP_AASSIGN) goto nomod;
3072         kid = cUNOPo->op_first;
3073       kid_2lvref:
3074         {
3075             const U8 ec = PL_parser ? PL_parser->error_count : 0;
3076             S_lvref(aTHX_ kid, type);
3077             if (!PL_parser || PL_parser->error_count == ec) {
3078                 if (!FEATURE_REFALIASING_IS_ENABLED)
3079                     Perl_croak(aTHX_
3080                        "Experimental aliasing via reference not enabled");
3081                 Perl_ck_warner_d(aTHX_
3082                                  packWARN(WARN_EXPERIMENTAL__REFALIASING),
3083                                 "Aliasing via reference is experimental");
3084             }
3085         }
3086         if (o->op_type == OP_REFGEN)
3087             op_null(cUNOPx(cUNOPo->op_first)->op_first); /* pushmark */
3088         op_null(o);
3089         return o;
3090
3091     case OP_SPLIT:
3092         kid = cLISTOPo->op_first;
3093         if (kid && kid->op_type == OP_PUSHRE &&
3094                 (  kid->op_targ
3095                 || o->op_flags & OPf_STACKED
3096 #ifdef USE_ITHREADS
3097                 || ((PMOP*)kid)->op_pmreplrootu.op_pmtargetoff
3098 #else
3099                 || ((PMOP*)kid)->op_pmreplrootu.op_pmtargetgv
3100 #endif
3101         )) {
3102             /* This is actually @array = split.  */
3103             PL_modcount = RETURN_UNLIMITED_NUMBER;
3104             break;
3105         }
3106         goto nomod;
3107
3108     case OP_SCALAR:
3109         op_lvalue(cUNOPo->op_first, OP_ENTERSUB);
3110         goto nomod;
3111     }
3112
3113     /* [20011101.069] File test operators interpret OPf_REF to mean that
3114        their argument is a filehandle; thus \stat(".") should not set
3115        it. AMS 20011102 */
3116     if (type == OP_REFGEN &&
3117         PL_check[o->op_type] == Perl_ck_ftst)
3118         return o;
3119
3120     if (type != OP_LEAVESUBLV)
3121         o->op_flags |= OPf_MOD;
3122
3123     if (type == OP_AASSIGN || type == OP_SASSIGN)
3124         o->op_flags |= OPf_SPECIAL|OPf_REF;
3125     else if (!type) { /* local() */
3126         switch (localize) {
3127         case 1:
3128             o->op_private |= OPpLVAL_INTRO;
3129             o->op_flags &= ~OPf_SPECIAL;
3130             PL_hints |= HINT_BLOCK_SCOPE;
3131             break;
3132         case 0:
3133             break;
3134         case -1:
3135             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
3136                            "Useless localization of %s", OP_DESC(o));
3137         }
3138     }
3139     else if (type != OP_GREPSTART && type != OP_ENTERSUB
3140              && type != OP_LEAVESUBLV)
3141         o->op_flags |= OPf_REF;
3142     return o;
3143 }
3144
3145 STATIC bool
3146 S_scalar_mod_type(const OP *o, I32 type)
3147 {
3148     switch (type) {
3149     case OP_POS:
3150     case OP_SASSIGN:
3151         if (o && o->op_type == OP_RV2GV)
3152             return FALSE;
3153         /* FALLTHROUGH */
3154     case OP_PREINC:
3155     case OP_PREDEC:
3156     case OP_POSTINC:
3157     case OP_POSTDEC:
3158     case OP_I_PREINC:
3159     case OP_I_PREDEC:
3160     case OP_I_POSTINC:
3161     case OP_I_POSTDEC:
3162     case OP_POW:
3163     case OP_MULTIPLY:
3164     case OP_DIVIDE:
3165     case OP_MODULO:
3166     case OP_REPEAT:
3167     case OP_ADD:
3168     case OP_SUBTRACT:
3169     case OP_I_MULTIPLY:
3170     case OP_I_DIVIDE:
3171     case OP_I_MODULO:
3172     case OP_I_ADD:
3173     case OP_I_SUBTRACT:
3174     case OP_LEFT_SHIFT:
3175     case OP_RIGHT_SHIFT:
3176     case OP_BIT_AND:
3177     case OP_BIT_XOR:
3178     case OP_BIT_OR:
3179     case OP_CONCAT:
3180     case OP_SUBST:
3181     case OP_TRANS:
3182     case OP_TRANSR:
3183     case OP_READ:
3184     case OP_SYSREAD:
3185     case OP_RECV:
3186     case OP_ANDASSIGN:
3187     case OP_ORASSIGN:
3188     case OP_DORASSIGN:
3189         return TRUE;
3190     default:
3191         return FALSE;
3192     }
3193 }
3194
3195 STATIC bool
3196 S_is_handle_constructor(const OP *o, I32 numargs)
3197 {
3198     PERL_ARGS_ASSERT_IS_HANDLE_CONSTRUCTOR;
3199
3200     switch (o->op_type) {
3201     case OP_PIPE_OP:
3202     case OP_SOCKPAIR:
3203         if (numargs == 2)
3204             return TRUE;
3205         /* FALLTHROUGH */
3206     case OP_SYSOPEN:
3207     case OP_OPEN:
3208     case OP_SELECT:             /* XXX c.f. SelectSaver.pm */
3209     case OP_SOCKET:
3210     case OP_OPEN_DIR:
3211     case OP_ACCEPT:
3212         if (numargs == 1)
3213             return TRUE;
3214         /* FALLTHROUGH */
3215     default:
3216         return FALSE;
3217     }
3218 }
3219
3220 static OP *
3221 S_refkids(pTHX_ OP *o, I32 type)
3222 {
3223     if (o && o->op_flags & OPf_KIDS) {
3224         OP *kid;
3225         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
3226             ref(kid, type);
3227     }
3228     return o;
3229 }
3230
3231 OP *
3232 Perl_doref(pTHX_ OP *o, I32 type, bool set_op_ref)
3233 {
3234     dVAR;
3235     OP *kid;
3236
3237     PERL_ARGS_ASSERT_DOREF;
3238
3239     if (!o || (PL_parser && PL_parser->error_count))
3240         return o;
3241
3242     switch (o->op_type) {
3243     case OP_ENTERSUB:
3244         if ((type == OP_EXISTS || type == OP_DEFINED) &&
3245             !(o->op_flags & OPf_STACKED)) {
3246             CHANGE_TYPE(o, OP_RV2CV);             /* entersub => rv2cv */
3247             assert(cUNOPo->op_first->op_type == OP_NULL);
3248             op_null(((LISTOP*)cUNOPo->op_first)->op_first);     /* disable pushmark */
3249             o->op_flags |= OPf_SPECIAL;
3250         }
3251         else if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV){
3252             o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
3253                               : type == OP_RV2HV ? OPpDEREF_HV
3254                               : OPpDEREF_SV);
3255             o->op_flags |= OPf_MOD;
3256         }
3257
3258         break;
3259
3260     case OP_COND_EXPR:
3261         for (kid = OpSIBLING(cUNOPo->op_first); kid; kid = OpSIBLING(kid))
3262             doref(kid, type, set_op_ref);
3263         break;
3264     case OP_RV2SV:
3265         if (type == OP_DEFINED)
3266             o->op_flags |= OPf_SPECIAL;         /* don't create GV */
3267         doref(cUNOPo->op_first, o->op_type, set_op_ref);
3268         /* FALLTHROUGH */
3269     case OP_PADSV:
3270         if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
3271             o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
3272                               : type == OP_RV2HV ? OPpDEREF_HV
3273                               : OPpDEREF_SV);
3274             o->op_flags |= OPf_MOD;
3275         }
3276         break;
3277
3278     case OP_RV2AV:
3279     case OP_RV2HV:
3280         if (set_op_ref)
3281             o->op_flags |= OPf_REF;
3282         /* FALLTHROUGH */
3283     case OP_RV2GV:
3284         if (type == OP_DEFINED)
3285             o->op_flags |= OPf_SPECIAL;         /* don't create GV */
3286         doref(cUNOPo->op_first, o->op_type, set_op_ref);
3287         break;
3288
3289     case OP_PADAV:
3290     case OP_PADHV:
3291         if (set_op_ref)
3292             o->op_flags |= OPf_REF;
3293         break;
3294
3295     case OP_SCALAR:
3296     case OP_NULL:
3297         if (!(o->op_flags & OPf_KIDS) || type == OP_DEFINED)
3298             break;
3299         doref(cBINOPo->op_first, type, set_op_ref);
3300         break;
3301     case OP_AELEM:
3302     case OP_HELEM:
3303         doref(cBINOPo->op_first, o->op_type, set_op_ref);
3304         if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
3305             o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
3306                               : type == OP_RV2HV ? OPpDEREF_HV
3307                               : OPpDEREF_SV);
3308             o->op_flags |= OPf_MOD;
3309         }
3310         break;
3311
3312     case OP_SCOPE:
3313     case OP_LEAVE:
3314         set_op_ref = FALSE;
3315         /* FALLTHROUGH */
3316     case OP_ENTER:
3317     case OP_LIST:
3318         if (!(o->op_flags & OPf_KIDS))
3319             break;
3320         doref(cLISTOPo->op_last, type, set_op_ref);
3321         break;
3322     default:
3323         break;
3324     }
3325     return scalar(o);
3326
3327 }
3328
3329 STATIC OP *
3330 S_dup_attrlist(pTHX_ OP *o)
3331 {
3332     OP *rop;
3333
3334     PERL_ARGS_ASSERT_DUP_ATTRLIST;
3335
3336     /* An attrlist is either a simple OP_CONST or an OP_LIST with kids,
3337      * where the first kid is OP_PUSHMARK and the remaining ones
3338      * are OP_CONST.  We need to push the OP_CONST values.
3339      */
3340     if (o->op_type == OP_CONST)
3341         rop = newSVOP(OP_CONST, o->op_flags, SvREFCNT_inc_NN(cSVOPo->op_sv));
3342     else {
3343         assert((o->op_type == OP_LIST) && (o->op_flags & OPf_KIDS));
3344         rop = NULL;
3345         for (o = cLISTOPo->op_first; o; o = OpSIBLING(o)) {
3346             if (o->op_type == OP_CONST)
3347                 rop = op_append_elem(OP_LIST, rop,
3348                                   newSVOP(OP_CONST, o->op_flags,
3349                                           SvREFCNT_inc_NN(cSVOPo->op_sv)));
3350         }
3351     }
3352     return rop;
3353 }
3354
3355 STATIC void
3356 S_apply_attrs(pTHX_ HV *stash, SV *target, OP *attrs)
3357 {
3358     SV * const stashsv = stash ? newSVhek(HvNAME_HEK(stash)) : &PL_sv_no;
3359
3360     PERL_ARGS_ASSERT_APPLY_ATTRS;
3361
3362     /* fake up C<use attributes $pkg,$rv,@attrs> */
3363
3364 #define ATTRSMODULE "attributes"
3365 #define ATTRSMODULE_PM "attributes.pm"
3366
3367     Perl_load_module(aTHX_ PERL_LOADMOD_IMPORT_OPS,
3368                          newSVpvs(ATTRSMODULE),
3369                          NULL,
3370                          op_prepend_elem(OP_LIST,
3371                                       newSVOP(OP_CONST, 0, stashsv),
3372                                       op_prepend_elem(OP_LIST,
3373                                                    newSVOP(OP_CONST, 0,
3374                                                            newRV(target)),
3375                                                    dup_attrlist(attrs))));
3376 }
3377
3378 STATIC void
3379 S_apply_attrs_my(pTHX_ HV *stash, OP *target, OP *attrs, OP **imopsp)
3380 {
3381     OP *pack, *imop, *arg;
3382     SV *meth, *stashsv, **svp;
3383
3384     PERL_ARGS_ASSERT_APPLY_ATTRS_MY;
3385
3386     if (!attrs)
3387         return;
3388
3389     assert(target->op_type == OP_PADSV ||
3390            target->op_type == OP_PADHV ||
3391            target->op_type == OP_PADAV);
3392
3393     /* Ensure that attributes.pm is loaded. */
3394     /* Don't force the C<use> if we don't need it. */
3395     svp = hv_fetchs(GvHVn(PL_incgv), ATTRSMODULE_PM, FALSE);
3396     if (svp && *svp != &PL_sv_undef)
3397         NOOP;   /* already in %INC */
3398     else
3399         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
3400                                newSVpvs(ATTRSMODULE), NULL);
3401
3402     /* Need package name for method call. */
3403     pack = newSVOP(OP_CONST, 0, newSVpvs(ATTRSMODULE));
3404
3405     /* Build up the real arg-list. */
3406     stashsv = stash ? newSVhek(HvNAME_HEK(stash)) : &PL_sv_no;
3407
3408     arg = newOP(OP_PADSV, 0);
3409     arg->op_targ = target->op_targ;
3410     arg = op_prepend_elem(OP_LIST,
3411                        newSVOP(OP_CONST, 0, stashsv),
3412                        op_prepend_elem(OP_LIST,
3413                                     newUNOP(OP_REFGEN, 0,
3414                                             arg),
3415                                     dup_attrlist(attrs)));
3416
3417     /* Fake up a method call to import */
3418     meth = newSVpvs_share("import");
3419     imop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL|OPf_WANT_VOID,
3420                    op_append_elem(OP_LIST,
3421                                op_prepend_elem(OP_LIST, pack, arg),
3422                                newMETHOP_named(OP_METHOD_NAMED, 0, meth)));
3423
3424     /* Combine the ops. */
3425     *imopsp = op_append_elem(OP_LIST, *imopsp, imop);
3426 }
3427
3428 /*
3429 =notfor apidoc apply_attrs_string
3430
3431 Attempts to apply a list of attributes specified by the C<attrstr> and
3432 C<len> arguments to the subroutine identified by the C<cv> argument which
3433 is expected to be associated with the package identified by the C<stashpv>
3434 argument (see L<attributes>).  It gets this wrong, though, in that it
3435 does not correctly identify the boundaries of the individual attribute
3436 specifications within C<attrstr>.  This is not really intended for the
3437 public API, but has to be listed here for systems such as AIX which
3438 need an explicit export list for symbols.  (It's called from XS code
3439 in support of the C<ATTRS:> keyword from F<xsubpp>.)  Patches to fix it
3440 to respect attribute syntax properly would be welcome.
3441
3442 =cut
3443 */
3444
3445 void
3446 Perl_apply_attrs_string(pTHX_ const char *stashpv, CV *cv,
3447                         const char *attrstr, STRLEN len)
3448 {
3449     OP *attrs = NULL;
3450
3451     PERL_ARGS_ASSERT_APPLY_ATTRS_STRING;
3452
3453     if (!len) {
3454         len = strlen(attrstr);
3455     }
3456
3457     while (len) {
3458         for (; isSPACE(*attrstr) && len; --len, ++attrstr) ;
3459         if (len) {
3460             const char * const sstr = attrstr;
3461             for (; !isSPACE(*attrstr) && len; --len, ++attrstr) ;
3462             attrs = op_append_elem(OP_LIST, attrs,
3463                                 newSVOP(OP_CONST, 0,
3464                                         newSVpvn(sstr, attrstr-sstr)));
3465         }
3466     }
3467
3468     Perl_load_module(aTHX_ PERL_LOADMOD_IMPORT_OPS,
3469                      newSVpvs(ATTRSMODULE),
3470                      NULL, op_prepend_elem(OP_LIST,
3471                                   newSVOP(OP_CONST, 0, newSVpv(stashpv,0)),
3472                                   op_prepend_elem(OP_LIST,
3473                                                newSVOP(OP_CONST, 0,
3474                                                        newRV(MUTABLE_SV(cv))),
3475                                                attrs)));
3476 }
3477
3478 STATIC void
3479 S_move_proto_attr(pTHX_ OP **proto, OP **attrs, const GV * name)
3480 {
3481     OP *new_proto = NULL;
3482     STRLEN pvlen;
3483     char *pv;
3484     OP *o;
3485
3486     PERL_ARGS_ASSERT_MOVE_PROTO_ATTR;
3487
3488     if (!*attrs)
3489         return;
3490
3491     o = *attrs;
3492     if (o->op_type == OP_CONST) {
3493         pv = SvPV(cSVOPo_sv, pvlen);
3494         if (pvlen >= 10 && memEQ(pv, "prototype(", 10)) {
3495             SV * const tmpsv = newSVpvn_flags(pv + 10, pvlen - 11, SvUTF8(cSVOPo_sv));
3496             SV ** const tmpo = cSVOPx_svp(o);
3497             SvREFCNT_dec(cSVOPo_sv);
3498             *tmpo = tmpsv;
3499             new_proto = o;
3500             *attrs = NULL;
3501         }
3502     } else if (o->op_type == OP_LIST) {
3503         OP * lasto;
3504         assert(o->op_flags & OPf_KIDS);
3505         lasto = cLISTOPo->op_first;
3506         assert(lasto->op_type == OP_PUSHMARK);
3507         for (o = OpSIBLING(lasto); o; o = OpSIBLING(o)) {
3508             if (o->op_type == OP_CONST) {
3509                 pv = SvPV(cSVOPo_sv, pvlen);
3510                 if (pvlen >= 10 && memEQ(pv, "prototype(", 10)) {
3511                     SV * const tmpsv = newSVpvn_flags(pv + 10, pvlen - 11, SvUTF8(cSVOPo_sv));
3512                     SV ** const tmpo = cSVOPx_svp(o);
3513                     SvREFCNT_dec(cSVOPo_sv);
3514                     *tmpo = tmpsv;
3515                     if (new_proto && ckWARN(WARN_MISC)) {
3516                         STRLEN new_len;
3517                         const char * newp = SvPV(cSVOPo_sv, new_len);
3518                         Perl_warner(aTHX_ packWARN(WARN_MISC),
3519                             "Attribute prototype(%"UTF8f") discards earlier prototype attribute in same sub",
3520                             UTF8fARG(SvUTF8(cSVOPo_sv), new_len, newp));
3521                         op_free(new_proto);
3522                     }
3523                     else if (new_proto)
3524                         op_free(new_proto);
3525                     new_proto = o;
3526                     /* excise new_proto from the list */
3527                     op_sibling_splice(*attrs, lasto, 1, NULL);
3528                     o = lasto;
3529                     continue;
3530                 }
3531             }
3532             lasto = o;
3533         }
3534         /* If the list is now just the PUSHMARK, scrap the whole thing; otherwise attributes.xs
3535            would get pulled in with no real need */
3536         if (!OpHAS_SIBLING(cLISTOPx(*attrs)->op_first)) {
3537             op_free(*attrs);
3538             *attrs = NULL;
3539         }
3540     }
3541
3542     if (new_proto) {
3543         SV *svname;
3544         if (isGV(name)) {
3545             svname = sv_newmortal();
3546             gv_efullname3(svname, name, NULL);
3547         }
3548         else if (SvPOK(name) && *SvPVX((SV *)name) == '&')
3549             svname = newSVpvn_flags(SvPVX((SV *)name)+1, SvCUR(name)-1, SvUTF8(name)|SVs_TEMP);
3550         else
3551             svname = (SV *)name;
3552         if (ckWARN(WARN_ILLEGALPROTO))
3553             (void)validate_proto(svname, cSVOPx_sv(new_proto), TRUE);
3554         if (*proto && ckWARN(WARN_PROTOTYPE)) {
3555             STRLEN old_len, new_len;
3556             const char * oldp = SvPV(cSVOPx_sv(*proto), old_len);
3557             const char * newp = SvPV(cSVOPx_sv(new_proto), new_len);
3558
3559             Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
3560                 "Prototype '%"UTF8f"' overridden by attribute 'prototype(%"UTF8f")'"
3561                 " in %"SVf,
3562                 UTF8fARG(SvUTF8(cSVOPx_sv(*proto)), old_len, oldp),
3563                 UTF8fARG(SvUTF8(cSVOPx_sv(new_proto)), new_len, newp),
3564                 SVfARG(svname));
3565         }
3566         if (*proto)
3567             op_free(*proto);
3568         *proto = new_proto;
3569     }
3570 }
3571
3572 static void
3573 S_cant_declare(pTHX_ OP *o)
3574 {
3575     if (o->op_type == OP_NULL
3576      && (o->op_flags & (OPf_SPECIAL|OPf_KIDS)) == OPf_KIDS)
3577         o = cUNOPo->op_first;
3578     yyerror(Perl_form(aTHX_ "Can't declare %s in \"%s\"",
3579                              o->op_type == OP_NULL
3580                                && o->op_flags & OPf_SPECIAL
3581                                  ? "do block"
3582                                  : OP_DESC(o),
3583                              PL_parser->in_my == KEY_our   ? "our"   :
3584                              PL_parser->in_my == KEY_state ? "state" :
3585                                                              "my"));
3586 }
3587
3588 STATIC OP *
3589 S_my_kid(pTHX_ OP *o, OP *attrs, OP **imopsp)
3590 {
3591     I32 type;
3592     const bool stately = PL_parser && PL_parser->in_my == KEY_state;
3593
3594     PERL_ARGS_ASSERT_MY_KID;
3595
3596     if (!o || (PL_parser && PL_parser->error_count))
3597         return o;
3598
3599     type = o->op_type;
3600
3601     if (type == OP_LIST) {
3602         OP *kid;
3603         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
3604             my_kid(kid, attrs, imopsp);
3605         return o;
3606     } else if (type == OP_UNDEF || type == OP_STUB) {
3607         return o;
3608     } else if (type == OP_RV2SV ||      /* "our" declaration */
3609                type == OP_RV2AV ||
3610                type == OP_RV2HV) { /* XXX does this let anything illegal in? */
3611         if (cUNOPo->op_first->op_type != OP_GV) { /* MJD 20011224 */
3612             S_cant_declare(aTHX_ o);
3613         } else if (attrs) {
3614             GV * const gv = cGVOPx_gv(cUNOPo->op_first);
3615             assert(PL_parser);
3616             PL_parser->in_my = FALSE;
3617             PL_parser->in_my_stash = NULL;
3618             apply_attrs(GvSTASH(gv),
3619                         (type == OP_RV2SV ? GvSV(gv) :
3620                          type == OP_RV2AV ? MUTABLE_SV(GvAV(gv)) :
3621                          type == OP_RV2HV ? MUTABLE_SV(GvHV(gv)) : MUTABLE_SV(gv)),
3622                         attrs);
3623         }
3624         o->op_private |= OPpOUR_INTRO;
3625         return o;
3626     }
3627     else if (type != OP_PADSV &&
3628              type != OP_PADAV &&
3629              type != OP_PADHV &&
3630              type != OP_PUSHMARK)
3631     {
3632         S_cant_declare(aTHX_ o);
3633         return o;
3634     }
3635     else if (attrs && type != OP_PUSHMARK) {
3636         HV *stash;
3637
3638         assert(PL_parser);
3639         PL_parser->in_my = FALSE;
3640         PL_parser->in_my_stash = NULL;
3641
3642         /* check for C<my Dog $spot> when deciding package */
3643         stash = PAD_COMPNAME_TYPE(o->op_targ);
3644         if (!stash)
3645             stash = PL_curstash;
3646         apply_attrs_my(stash, o, attrs, imopsp);
3647     }
3648     o->op_flags |= OPf_MOD;
3649     o->op_private |= OPpLVAL_INTRO;
3650     if (stately)
3651         o->op_private |= OPpPAD_STATE;
3652     return o;
3653 }
3654
3655 OP *
3656 Perl_my_attrs(pTHX_ OP *o, OP *attrs)
3657 {
3658     OP *rops;
3659     int maybe_scalar = 0;
3660
3661     PERL_ARGS_ASSERT_MY_ATTRS;
3662
3663 /* [perl #17376]: this appears to be premature, and results in code such as
3664    C< our(%x); > executing in list mode rather than void mode */
3665 #if 0
3666     if (o->op_flags & OPf_PARENS)
3667         list(o);
3668     else
3669         maybe_scalar = 1;
3670 #else
3671     maybe_scalar = 1;
3672 #endif
3673     if (attrs)
3674         SAVEFREEOP(attrs);
3675     rops = NULL;
3676     o = my_kid(o, attrs, &rops);
3677     if (rops) {
3678         if (maybe_scalar && o->op_type == OP_PADSV) {
3679             o = scalar(op_append_list(OP_LIST, rops, o));
3680             o->op_private |= OPpLVAL_INTRO;
3681         }
3682         else {
3683             /* The listop in rops might have a pushmark at the beginning,
3684                which will mess up list assignment. */
3685             LISTOP * const lrops = (LISTOP *)rops; /* for brevity */
3686             if (rops->op_type == OP_LIST && 
3687                 lrops->op_first && lrops->op_first->op_type == OP_PUSHMARK)
3688             {
3689                 OP * const pushmark = lrops->op_first;
3690                 /* excise pushmark */
3691                 op_sibling_splice(rops, NULL, 1, NULL);
3692                 op_free(pushmark);
3693             }
3694             o = op_append_list(OP_LIST, o, rops);
3695         }
3696     }
3697     PL_parser->in_my = FALSE;
3698     PL_parser->in_my_stash = NULL;
3699     return o;
3700 }
3701
3702 OP *
3703 Perl_sawparens(pTHX_ OP *o)
3704 {
3705     PERL_UNUSED_CONTEXT;
3706     if (o)
3707         o->op_flags |= OPf_PARENS;
3708     return o;
3709 }
3710
3711 OP *
3712 Perl_bind_match(pTHX_ I32 type, OP *left, OP *right)
3713 {
3714     OP *o;
3715     bool ismatchop = 0;
3716     const OPCODE ltype = left->op_type;
3717     const OPCODE rtype = right->op_type;
3718
3719     PERL_ARGS_ASSERT_BIND_MATCH;
3720
3721     if ( (ltype == OP_RV2AV || ltype == OP_RV2HV || ltype == OP_PADAV
3722           || ltype == OP_PADHV) && ckWARN(WARN_MISC))
3723     {
3724       const char * const desc
3725           = PL_op_desc[(
3726                           rtype == OP_SUBST || rtype == OP_TRANS
3727                        || rtype == OP_TRANSR
3728                        )
3729                        ? (int)rtype : OP_MATCH];
3730       const bool isary = ltype == OP_RV2AV || ltype == OP_PADAV;
3731       SV * const name =
3732         S_op_varname(aTHX_ left);
3733       if (name)
3734         Perl_warner(aTHX_ packWARN(WARN_MISC),
3735              "Applying %s to %"SVf" will act on scalar(%"SVf")",
3736              desc, SVfARG(name), SVfARG(name));
3737       else {
3738         const char * const sample = (isary
3739              ? "@array" : "%hash");
3740         Perl_warner(aTHX_ packWARN(WARN_MISC),
3741              "Applying %s to %s will act on scalar(%s)",
3742              desc, sample, sample);
3743       }
3744     }
3745
3746     if (rtype == OP_CONST &&
3747         cSVOPx(right)->op_private & OPpCONST_BARE &&
3748         cSVOPx(right)->op_private & OPpCONST_STRICT)
3749     {
3750         no_bareword_allowed(right);
3751     }
3752
3753     /* !~ doesn't make sense with /r, so error on it for now */
3754     if (rtype == OP_SUBST && (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT) &&
3755         type == OP_NOT)
3756         /* diag_listed_as: Using !~ with %s doesn't make sense */
3757         yyerror("Using !~ with s///r doesn't make sense");
3758     if (rtype == OP_TRANSR && type == OP_NOT)
3759         /* diag_listed_as: Using !~ with %s doesn't make sense */
3760         yyerror("Using !~ with tr///r doesn't make sense");
3761
3762     ismatchop = (rtype == OP_MATCH ||
3763                  rtype == OP_SUBST ||
3764                  rtype == OP_TRANS || rtype == OP_TRANSR)
3765              && !(right->op_flags & OPf_SPECIAL);
3766     if (ismatchop && right->op_private & OPpTARGET_MY) {
3767         right->op_targ = 0;
3768         right->op_private &= ~OPpTARGET_MY;
3769     }
3770     if (!(right->op_flags & OPf_STACKED) && !right->op_targ && ismatchop) {
3771         if (left->op_type == OP_PADSV
3772          && !(left->op_private & OPpLVAL_INTRO))
3773         {
3774             right->op_targ = left->op_targ;
3775             op_free(left);
3776             o = right;
3777         }
3778         else {
3779             right->op_flags |= OPf_STACKED;
3780             if (rtype != OP_MATCH && rtype != OP_TRANSR &&
3781             ! (rtype == OP_TRANS &&
3782                right->op_private & OPpTRANS_IDENTICAL) &&
3783             ! (rtype == OP_SUBST &&
3784                (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT)))
3785                 left = op_lvalue(left, rtype);
3786             if (right->op_type == OP_TRANS || right->op_type == OP_TRANSR)
3787                 o = newBINOP(OP_NULL, OPf_STACKED, scalar(left), right);
3788             else
3789                 o = op_prepend_elem(rtype, scalar(left), right);
3790         }
3791         if (type == OP_NOT)
3792             return newUNOP(OP_NOT, 0, scalar(o));
3793         return o;
3794     }
3795     else
3796         return bind_match(type, left,
3797                 pmruntime(newPMOP(OP_MATCH, 0), right, NULL, 0, 0));
3798 }
3799
3800 OP *
3801 Perl_invert(pTHX_ OP *o)
3802 {
3803     if (!o)
3804         return NULL;
3805     return newUNOP(OP_NOT, OPf_SPECIAL, scalar(o));
3806 }
3807
3808 /*
3809 =for apidoc Amx|OP *|op_scope|OP *o
3810
3811 Wraps up an op tree with some additional ops so that at runtime a dynamic
3812 scope will be created.  The original ops run in the new dynamic scope,
3813 and then, provided that they exit normally, the scope will be unwound.
3814 The additional ops used to create and unwind the dynamic scope will
3815 normally be an C<enter>/C<leave> pair, but a C<scope> op may be used
3816 instead if the ops are simple enough to not need the full dynamic scope
3817 structure.
3818
3819 =cut
3820 */
3821
3822 OP *
3823 Perl_op_scope(pTHX_ OP *o)
3824 {
3825     dVAR;
3826     if (o) {
3827         if (o->op_flags & OPf_PARENS || PERLDB_NOOPT || TAINTING_get) {
3828             o = op_prepend_elem(OP_LINESEQ, newOP(OP_ENTER, 0), o);
3829             CHANGE_TYPE(o, OP_LEAVE);
3830         }
3831         else if (o->op_type == OP_LINESEQ) {
3832             OP *kid;
3833             CHANGE_TYPE(o, OP_SCOPE);
3834             kid = ((LISTOP*)o)->op_first;
3835             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) {
3836                 op_null(kid);
3837
3838                 /* The following deals with things like 'do {1 for 1}' */
3839                 kid = OpSIBLING(kid);
3840                 if (kid &&
3841                     (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE))
3842                     op_null(kid);
3843             }
3844         }
3845         else
3846             o = newLISTOP(OP_SCOPE, 0, o, NULL);
3847     }
3848     return o;
3849 }
3850
3851 OP *
3852 Perl_op_unscope(pTHX_ OP *o)
3853 {
3854     if (o && o->op_type == OP_LINESEQ) {
3855         OP *kid = cLISTOPo->op_first;
3856         for(; kid; kid = OpSIBLING(kid))
3857             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE)
3858                 op_null(kid);
3859     }
3860     return o;
3861 }
3862
3863 /*
3864 =for apidoc Am|int|block_start|int full
3865
3866 Handles compile-time scope entry.
3867 Arranges for hints to be restored on block
3868 exit and also handles pad sequence numbers to make lexical variables scope
3869 right.  Returns a savestack index for use with C<block_end>.
3870
3871 =cut
3872 */
3873
3874 int
3875 Perl_block_start(pTHX_ int full)
3876 {
3877     const int retval = PL_savestack_ix;
3878
3879     PL_compiling.cop_seq = PL_cop_seqmax;
3880     COP_SEQMAX_INC;
3881     pad_block_start(full);
3882     SAVEHINTS();
3883     PL_hints &= ~HINT_BLOCK_SCOPE;
3884     SAVECOMPILEWARNINGS();
3885     PL_compiling.cop_warnings = DUP_WARNINGS(PL_compiling.cop_warnings);
3886     SAVEI32(PL_compiling.cop_seq);
3887     PL_compiling.cop_seq = 0;
3888
3889     CALL_BLOCK_HOOKS(bhk_start, full);
3890
3891     return retval;
3892 }
3893
3894 /*
3895 =for apidoc Am|OP *|block_end|I32 floor|OP *seq
3896
3897 Handles compile-time scope exit.  I<floor>
3898 is the savestack index returned by
3899 C<block_start>, and I<seq> is the body of the block.  Returns the block,
3900 possibly modified.
3901
3902 =cut
3903 */
3904
3905 OP*
3906 Perl_block_end(pTHX_ I32 floor, OP *seq)
3907 {
3908     const int needblockscope = PL_hints & HINT_BLOCK_SCOPE;
3909     OP* retval = scalarseq(seq);
3910     OP *o;
3911
3912     /* XXX Is the null PL_parser check necessary here? */
3913     assert(PL_parser); /* Let’s find out under debugging builds.  */
3914     if (PL_parser && PL_parser->parsed_sub) {
3915         o = newSTATEOP(0, NULL, NULL);
3916         op_null(o);
3917         retval = op_append_elem(OP_LINESEQ, retval, o);
3918     }
3919
3920     CALL_BLOCK_HOOKS(bhk_pre_end, &retval);
3921
3922     LEAVE_SCOPE(floor);
3923     if (needblockscope)
3924         PL_hints |= HINT_BLOCK_SCOPE; /* propagate out */
3925     o = pad_leavemy();
3926
3927     if (o) {
3928         /* pad_leavemy has created a sequence of introcv ops for all my
3929            subs declared in the block.  We have to replicate that list with
3930            clonecv ops, to deal with this situation:
3931
3932                sub {
3933                    my sub s1;
3934                    my sub s2;
3935                    sub s1 { state sub foo { \&s2 } }
3936                }->()
3937
3938            Originally, I was going to have introcv clone the CV and turn
3939            off the stale flag.  Since &s1 is declared before &s2, the
3940            introcv op for &s1 is executed (on sub entry) before the one for
3941            &s2.  But the &foo sub inside &s1 (which is cloned when &s1 is
3942            cloned, since it is a state sub) closes over &s2 and expects
3943            to see it in its outer CV’s pad.  If the introcv op clones &s1,
3944            then &s2 is still marked stale.  Since &s1 is not active, and
3945            &foo closes over &s1’s implicit entry for &s2, we get a â€˜Varia-
3946            ble will not stay shared’ warning.  Because it is the same stub
3947            that will be used when the introcv op for &s2 is executed, clos-
3948            ing over it is safe.  Hence, we have to turn off the stale flag
3949            on all lexical subs in the block before we clone any of them.
3950            Hence, having introcv clone the sub cannot work.  So we create a
3951            list of ops like this:
3952
3953                lineseq
3954                   |
3955                   +-- introcv
3956                   |
3957                   +-- introcv
3958                   |
3959                   +-- introcv
3960                   |
3961                   .
3962                   .
3963                   .
3964                   |
3965                   +-- clonecv
3966                   |
3967                   +-- clonecv
3968                   |
3969                   +-- clonecv
3970                   |
3971                   .
3972                   .
3973                   .
3974          */
3975         OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : o;
3976         OP * const last = o->op_flags & OPf_KIDS ? cLISTOPo->op_last : o;
3977         for (;; kid = OpSIBLING(kid)) {
3978             OP *newkid = newOP(OP_CLONECV, 0);
3979             newkid->op_targ = kid->op_targ;
3980             o = op_append_elem(OP_LINESEQ, o, newkid);
3981             if (kid == last) break;
3982         }
3983         retval = op_prepend_elem(OP_LINESEQ, o, retval);
3984     }
3985
3986     CALL_BLOCK_HOOKS(bhk_post_end, &retval);
3987
3988     return retval;
3989 }
3990
3991 /*
3992 =head1 Compile-time scope hooks
3993
3994 =for apidoc Aox||blockhook_register
3995
3996 Register a set of hooks to be called when the Perl lexical scope changes
3997 at compile time.  See L<perlguts/"Compile-time scope hooks">.
3998
3999 =cut
4000 */
4001
4002 void
4003 Perl_blockhook_register(pTHX_ BHK *hk)
4004 {
4005     PERL_ARGS_ASSERT_BLOCKHOOK_REGISTER;
4006
4007     Perl_av_create_and_push(aTHX_ &PL_blockhooks, newSViv(PTR2IV(hk)));
4008 }
4009
4010 void
4011 Perl_newPROG(pTHX_ OP *o)
4012 {
4013     PERL_ARGS_ASSERT_NEWPROG;
4014
4015     if (PL_in_eval) {
4016         PERL_CONTEXT *cx;
4017         I32 i;
4018         if (PL_eval_root)
4019                 return;
4020         PL_eval_root = newUNOP(OP_LEAVEEVAL,
4021                                ((PL_in_eval & EVAL_KEEPERR)
4022                                 ? OPf_SPECIAL : 0), o);
4023
4024         cx = &cxstack[cxstack_ix];
4025         assert(CxTYPE(cx) == CXt_EVAL);
4026
4027         if ((cx->blk_gimme & G_WANT) == G_VOID)
4028             scalarvoid(PL_eval_root);
4029         else if ((cx->blk_gimme & G_WANT) == G_ARRAY)
4030             list(PL_eval_root);
4031         else
4032             scalar(PL_eval_root);
4033
4034         PL_eval_start = op_linklist(PL_eval_root);
4035         PL_eval_root->op_private |= OPpREFCOUNTED;
4036         OpREFCNT_set(PL_eval_root, 1);
4037         PL_eval_root->op_next = 0;
4038         i = PL_savestack_ix;
4039         SAVEFREEOP(o);
4040         ENTER;
4041         CALL_PEEP(PL_eval_start);
4042         finalize_optree(PL_eval_root);
4043         S_prune_chain_head(&PL_eval_start);
4044         LEAVE;
4045         PL_savestack_ix = i;
4046     }
4047     else {
4048         if (o->op_type == OP_STUB) {
4049             /* This block is entered if nothing is compiled for the main
4050                program. This will be the case for an genuinely empty main
4051                program, or one which only has BEGIN blocks etc, so already
4052                run and freed.
4053
4054                Historically (5.000) the guard above was !o. However, commit
4055                f8a08f7b8bd67b28 (Jun 2001), integrated to blead as
4056                c71fccf11fde0068, changed perly.y so that newPROG() is now
4057                called with the output of block_end(), which returns a new
4058                OP_STUB for the case of an empty optree. ByteLoader (and
4059                maybe other things) also take this path, because they set up
4060                PL_main_start and PL_main_root directly, without generating an
4061                optree.
4062
4063                If the parsing the main program aborts (due to parse errors,
4064                or due to BEGIN or similar calling exit), then newPROG()
4065                isn't even called, and hence this code path and its cleanups
4066                are skipped. This shouldn't make a make a difference:
4067                * a non-zero return from perl_parse is a failure, and
4068                  perl_destruct() should be called immediately.
4069                * however, if exit(0) is called during the parse, then
4070                  perl_parse() returns 0, and perl_run() is called. As
4071                  PL_main_start will be NULL, perl_run() will return
4072                  promptly, and the exit code will remain 0.
4073             */
4074
4075             PL_comppad_name = 0;
4076             PL_compcv = 0;
4077             S_op_destroy(aTHX_ o);
4078             return;
4079         }
4080         PL_main_root = op_scope(sawparens(scalarvoid(o)));
4081         PL_curcop = &PL_compiling;
4082         PL_main_start = LINKLIST(PL_main_root);
4083         PL_main_root->op_private |= OPpREFCOUNTED;
4084         OpREFCNT_set(PL_main_root, 1);
4085         PL_main_root->op_next = 0;
4086         CALL_PEEP(PL_main_start);
4087         finalize_optree(PL_main_root);
4088         S_prune_chain_head(&PL_main_start);
4089         cv_forget_slab(PL_compcv);
4090         PL_compcv = 0;
4091
4092         /* Register with debugger */
4093         if (PERLDB_INTER) {
4094             CV * const cv = get_cvs("DB::postponed", 0);
4095             if (cv) {
4096                 dSP;
4097                 PUSHMARK(SP);
4098                 XPUSHs(MUTABLE_SV(CopFILEGV(&PL_compiling)));
4099                 PUTBACK;
4100                 call_sv(MUTABLE_SV(cv), G_DISCARD);
4101             }
4102         }
4103     }
4104 }
4105
4106 OP *
4107 Perl_localize(pTHX_ OP *o, I32 lex)
4108 {
4109     PERL_ARGS_ASSERT_LOCALIZE;
4110
4111     if (o->op_flags & OPf_PARENS)
4112 /* [perl #17376]: this appears to be premature, and results in code such as
4113    C< our(%x); > executing in list mode rather than void mode */
4114 #if 0
4115         list(o);
4116 #else
4117         NOOP;
4118 #endif
4119     else {
4120         if ( PL_parser->bufptr > PL_parser->oldbufptr
4121             && PL_parser->bufptr[-1] == ','
4122             && ckWARN(WARN_PARENTHESIS))
4123         {
4124             char *s = PL_parser->bufptr;
4125             bool sigil = FALSE;
4126
4127             /* some heuristics to detect a potential error */
4128             while (*s && (strchr(", \t\n", *s)))
4129                 s++;
4130
4131             while (1) {
4132                 if (*s && strchr("@$%*", *s) && *++s
4133                        && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s))) {
4134                     s++;
4135                     sigil = TRUE;
4136                     while (*s && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s)))
4137                         s++;
4138                     while (*s && (strchr(", \t\n", *s)))
4139                         s++;
4140                 }
4141                 else
4142                     break;
4143             }
4144             if (sigil && (*s == ';' || *s == '=')) {
4145                 Perl_warner(aTHX_ packWARN(WARN_PARENTHESIS),
4146                                 "Parentheses missing around \"%s\" list",
4147                                 lex
4148                                     ? (PL_parser->in_my == KEY_our
4149                                         ? "our"
4150                                         : PL_parser->in_my == KEY_state
4151                                             ? "state"
4152                                             : "my")
4153                                     : "local");
4154             }
4155         }
4156     }
4157     if (lex)
4158         o = my(o);
4159     else
4160         o = op_lvalue(o, OP_NULL);              /* a bit kludgey */
4161     PL_parser->in_my = FALSE;
4162     PL_parser->in_my_stash = NULL;
4163     return o;
4164 }
4165
4166 OP *
4167 Perl_jmaybe(pTHX_ OP *o)
4168 {
4169     PERL_ARGS_ASSERT_JMAYBE;
4170
4171     if (o->op_type == OP_LIST) {
4172         OP * const o2
4173             = newSVREF(newGVOP(OP_GV, 0, gv_fetchpvs(";", GV_ADD|GV_NOTQUAL, SVt_PV)));
4174         o = op_convert_list(OP_JOIN, 0, op_prepend_elem(OP_LIST, o2, o));
4175     }
4176     return o;
4177 }
4178
4179 PERL_STATIC_INLINE OP *
4180 S_op_std_init(pTHX_ OP *o)
4181 {
4182     I32 type = o->op_type;
4183
4184     PERL_ARGS_ASSERT_OP_STD_INIT;
4185
4186     if (PL_opargs[type] & OA_RETSCALAR)
4187         scalar(o);
4188     if (PL_opargs[type] & OA_TARGET && !o->op_targ)
4189         o->op_targ = pad_alloc(type, SVs_PADTMP);
4190
4191     return o;
4192 }
4193
4194 PERL_STATIC_INLINE OP *
4195 S_op_integerize(pTHX_ OP *o)
4196 {
4197     I32 type = o->op_type;
4198
4199     PERL_ARGS_ASSERT_OP_INTEGERIZE;
4200
4201     /* integerize op. */
4202     if ((PL_opargs[type] & OA_OTHERINT) && (PL_hints & HINT_INTEGER))
4203     {
4204         dVAR;
4205         o->op_ppaddr = PL_ppaddr[++(o->op_type)];
4206     }
4207
4208     if (type == OP_NEGATE)
4209         /* XXX might want a ck_negate() for this */
4210         cUNOPo->op_first->op_private &= ~OPpCONST_STRICT;
4211
4212     return o;
4213 }
4214
4215 static OP *
4216 S_fold_constants(pTHX_ OP *o)
4217 {
4218     dVAR;
4219     OP * VOL curop;
4220     OP *newop;
4221     VOL I32 type = o->op_type;
4222     bool is_stringify;
4223     SV * VOL sv = NULL;
4224     int ret = 0;
4225     I32 oldscope;
4226     OP *old_next;
4227     SV * const oldwarnhook = PL_warnhook;
4228     SV * const olddiehook  = PL_diehook;
4229     COP not_compiling;
4230     U8 oldwarn = PL_dowarn;
4231     dJMPENV;
4232
4233     PERL_ARGS_ASSERT_FOLD_CONSTANTS;
4234
4235     if (!(PL_opargs[type] & OA_FOLDCONST))
4236         goto nope;
4237
4238     switch (type) {
4239     case OP_UCFIRST:
4240     case OP_LCFIRST:
4241     case OP_UC:
4242     case OP_LC:
4243     case OP_FC:
4244 #ifdef USE_LOCALE_CTYPE
4245         if (IN_LC_COMPILETIME(LC_CTYPE))
4246             goto nope;
4247 #endif
4248         break;
4249     case OP_SLT:
4250     case OP_SGT:
4251     case OP_SLE:
4252     case OP_SGE:
4253     case OP_SCMP:
4254 #ifdef USE_LOCALE_COLLATE
4255         if (IN_LC_COMPILETIME(LC_COLLATE))
4256             goto nope;
4257 #endif
4258         break;
4259     case OP_SPRINTF:
4260         /* XXX what about the numeric ops? */
4261 #ifdef USE_LOCALE_NUMERIC
4262         if (IN_LC_COMPILETIME(LC_NUMERIC))
4263             goto nope;
4264 #endif
4265         break;
4266     case OP_PACK:
4267         if (!OpHAS_SIBLING(cLISTOPo->op_first)
4268           || OpSIBLING(cLISTOPo->op_first)->op_type != OP_CONST)
4269             goto nope;
4270         {
4271             SV * const sv = cSVOPx_sv(OpSIBLING(cLISTOPo->op_first));
4272             if (!SvPOK(sv) || SvGMAGICAL(sv)) goto nope;
4273             {
4274                 const char *s = SvPVX_const(sv);
4275                 while (s < SvEND(sv)) {
4276                     if (isALPHA_FOLD_EQ(*s, 'p')) goto nope;
4277                     s++;
4278                 }
4279             }
4280         }
4281         break;
4282     case OP_REPEAT:
4283         if (o->op_private & OPpREPEAT_DOLIST) goto nope;
4284         break;
4285     case OP_SREFGEN:
4286         if (cUNOPx(cUNOPo->op_first)->op_first->op_type != OP_CONST
4287          || SvPADTMP(cSVOPx_sv(cUNOPx(cUNOPo->op_first)->op_first)))
4288             goto nope;
4289     }
4290
4291     if (PL_parser && PL_parser->error_count)
4292         goto nope;              /* Don't try to run w/ errors */
4293
4294     for (curop = LINKLIST(o); curop != o; curop = LINKLIST(curop)) {
4295         const OPCODE type = curop->op_type;
4296         if ((type != OP_CONST || (curop->op_private & OPpCONST_BARE)) &&
4297             type != OP_LIST &&
4298             type != OP_SCALAR &&
4299             type != OP_NULL &&
4300             type != OP_PUSHMARK)
4301         {
4302             goto nope;
4303         }
4304     }
4305
4306     curop = LINKLIST(o);
4307     old_next = o->op_next;
4308     o->op_next = 0;
4309     PL_op = curop;
4310
4311     oldscope = PL_scopestack_ix;
4312     create_eval_scope(G_FAKINGEVAL);
4313
4314     /* Verify that we don't need to save it:  */
4315     assert(PL_curcop == &PL_compiling);
4316     StructCopy(&PL_compiling, &not_compiling, COP);
4317     PL_curcop = &not_compiling;
4318     /* The above ensures that we run with all the correct hints of the
4319        currently compiling COP, but that IN_PERL_RUNTIME is true. */
4320     assert(IN_PERL_RUNTIME);
4321     PL_warnhook = PERL_WARNHOOK_FATAL;
4322     PL_diehook  = NULL;
4323     JMPENV_PUSH(ret);
4324
4325     /* Effective $^W=1.  */
4326     if ( ! (PL_dowarn & G_WARN_ALL_MASK))
4327         PL_dowarn |= G_WARN_ON;
4328
4329     switch (ret) {
4330     case 0:
4331         CALLRUNOPS(aTHX);
4332         sv = *(PL_stack_sp--);
4333         if (o->op_targ && sv == PAD_SV(o->op_targ)) {   /* grab pad temp? */
4334             pad_swipe(o->op_targ,  FALSE);
4335         }
4336         else if (SvTEMP(sv)) {                  /* grab mortal temp? */
4337             SvREFCNT_inc_simple_void(sv);
4338             SvTEMP_off(sv);
4339         }
4340         else { assert(SvIMMORTAL(sv)); }
4341         break;
4342     case 3:
4343         /* Something tried to die.  Abandon constant folding.  */
4344         /* Pretend the error never happened.  */
4345         CLEAR_ERRSV();
4346         o->op_next = old_next;
4347         break;
4348     default:
4349         JMPENV_POP;
4350         /* Don't expect 1 (setjmp failed) or 2 (something called my_exit)  */
4351         PL_warnhook = oldwarnhook;
4352         PL_diehook  = olddiehook;
4353         /* XXX note that this croak may fail as we've already blown away
4354          * the stack - eg any nested evals */
4355         Perl_croak(aTHX_ "panic: fold_constants JMPENV_PUSH returned %d", ret);
4356     }
4357     JMPENV_POP;
4358     PL_dowarn   = oldwarn;
4359     PL_warnhook = oldwarnhook;
4360     PL_diehook  = olddiehook;
4361     PL_curcop = &PL_compiling;
4362
4363     if (PL_scopestack_ix > oldscope)
4364         delete_eval_scope();
4365
4366     if (ret)
4367         goto nope;
4368
4369     /* OP_STRINGIFY and constant folding are used to implement qq.
4370        Here the constant folding is an implementation detail that we
4371        want to hide.  If the stringify op is itself already marked
4372        folded, however, then it is actually a folded join.  */
4373     is_stringify = type == OP_STRINGIFY && !o->op_folded;
4374     op_free(o);
4375     assert(sv);
4376     if (is_stringify)
4377         SvPADTMP_off(sv);
4378     else if (!SvIMMORTAL(sv)) {
4379         SvPADTMP_on(sv);
4380         SvREADONLY_on(sv);
4381     }
4382     newop = newSVOP(OP_CONST, 0, MUTABLE_SV(sv));
4383     if (!is_stringify) newop->op_folded = 1;
4384     return newop;
4385
4386  nope:
4387     return o;
4388 }
4389
4390 static OP *
4391 S_gen_constant_list(pTHX_ OP *o)
4392 {
4393     dVAR;
4394     OP *curop;
4395     const SSize_t oldtmps_floor = PL_tmps_floor;
4396     SV **svp;
4397     AV *av;
4398
4399     list(o);
4400     if (PL_parser && PL_parser->error_count)
4401         return o;               /* Don't attempt to run with errors */
4402
4403     curop = LINKLIST(o);
4404     o->op_next = 0;
4405     CALL_PEEP(curop);
4406     S_prune_chain_head(&curop);
4407     PL_op = curop;
4408     Perl_pp_pushmark(aTHX);
4409     CALLRUNOPS(aTHX);
4410     PL_op = curop;
4411     assert (!(curop->op_flags & OPf_SPECIAL));
4412     assert(curop->op_type == OP_RANGE);
4413     Perl_pp_anonlist(aTHX);
4414     PL_tmps_floor = oldtmps_floor;
4415
4416     CHANGE_TYPE(o, OP_RV2AV);
4417     o->op_flags &= ~OPf_REF;    /* treat \(1..2) like an ordinary list */
4418     o->op_flags |= OPf_PARENS;  /* and flatten \(1..2,3) */
4419     o->op_opt = 0;              /* needs to be revisited in rpeep() */
4420     av = (AV *)SvREFCNT_inc_NN(*PL_stack_sp--);
4421
4422     /* replace subtree with an OP_CONST */
4423     curop = ((UNOP*)o)->op_first;
4424     op_sibling_splice(o, NULL, -1, newSVOP(OP_CONST, 0, (SV *)av));
4425     op_free(curop);
4426
4427     if (AvFILLp(av) != -1)
4428         for (svp = AvARRAY(av) + AvFILLp(av); svp >= AvARRAY(av); --svp)
4429         {
4430             SvPADTMP_on(*svp);
4431             SvREADONLY_on(*svp);
4432         }
4433     LINKLIST(o);
4434     return list(o);
4435 }
4436
4437 /*
4438 =head1 Optree Manipulation Functions
4439 */
4440
4441 /* List constructors */
4442
4443 /*
4444 =for apidoc Am|OP *|op_append_elem|I32 optype|OP *first|OP *last
4445
4446 Append an item to the list of ops contained directly within a list-type
4447 op, returning the lengthened list.  I<first> is the list-type op,
4448 and I<last> is the op to append to the list.  I<optype> specifies the
4449 intended opcode for the list.  If I<first> is not already a list of the
4450 right type, it will be upgraded into one.  If either I<first> or I<last>
4451 is null, the other is returned unchanged.
4452
4453 =cut
4454 */
4455
4456 OP *
4457 Perl_op_append_elem(pTHX_ I32 type, OP *first, OP *last)
4458 {
4459     if (!first)
4460         return last;
4461
4462     if (!last)
4463         return first;
4464
4465     if (first->op_type != (unsigned)type
4466         || (type == OP_LIST && (first->op_flags & OPf_PARENS)))
4467     {
4468         return newLISTOP(type, 0, first, last);
4469     }
4470
4471     op_sibling_splice(first, ((LISTOP*)first)->op_last, 0, last);
4472     first->op_flags |= OPf_KIDS;
4473     return first;
4474 }
4475
4476 /*
4477 =for apidoc Am|OP *|op_append_list|I32 optype|OP *first|OP *last
4478
4479 Concatenate the lists of ops contained directly within two list-type ops,
4480 returning the combined list.  I<first> and I<last> are the list-type ops
4481 to concatenate.  I<optype> specifies the intended opcode for the list.
4482 If either I<first> or I<last> is not already a list of the right type,
4483 it will be upgraded into one.  If either I<first> or I<last> is null,
4484 the other is returned unchanged.
4485
4486 =cut
4487 */
4488
4489 OP *
4490 Perl_op_append_list(pTHX_ I32 type, OP *first, OP *last)
4491 {
4492     if (!first)
4493         return last;
4494
4495     if (!last)
4496         return first;
4497
4498     if (first->op_type != (unsigned)type)
4499         return op_prepend_elem(type, first, last);
4500
4501     if (last->op_type != (unsigned)type)
4502         return op_append_elem(type, first, last);
4503
4504     ((LISTOP*)first)->op_last->op_lastsib = 0;
4505     OpSIBLING_set(((LISTOP*)first)->op_last, ((LISTOP*)last)->op_first);
4506     ((LISTOP*)first)->op_last = ((LISTOP*)last)->op_last;
4507     ((LISTOP*)first)->op_last->op_lastsib = 1;
4508 #ifdef PERL_OP_PARENT
4509     ((LISTOP*)first)->op_last->op_sibling = first;
4510 #endif
4511     first->op_flags |= (last->op_flags & OPf_KIDS);
4512
4513
4514     S_op_destroy(aTHX_ last);
4515
4516     return first;
4517 }
4518
4519 /*
4520 =for apidoc Am|OP *|op_prepend_elem|I32 optype|OP *first|OP *last
4521
4522 Prepend an item to the list of ops contained directly within a list-type
4523 op, returning the lengthened list.  I<first> is the op to prepend to the
4524 list, and I<last> is the list-type op.  I<optype> specifies the intended
4525 opcode for the list.  If I<last> is not already a list of the right type,
4526 it will be upgraded into one.  If either I<first> or I<last> is null,
4527 the other is returned unchanged.
4528
4529 =cut
4530 */
4531
4532 OP *
4533 Perl_op_prepend_elem(pTHX_ I32 type, OP *first, OP *last)
4534 {
4535     if (!first)
4536         return last;
4537
4538     if (!last)
4539         return first;
4540
4541     if (last->op_type == (unsigned)type) {
4542         if (type == OP_LIST) {  /* already a PUSHMARK there */
4543             /* insert 'first' after pushmark */
4544             op_sibling_splice(last, cLISTOPx(last)->op_first, 0, first);
4545             if (!(first->op_flags & OPf_PARENS))
4546                 last->op_flags &= ~OPf_PARENS;
4547         }
4548         else
4549             op_sibling_splice(last, NULL, 0, first);
4550         last->op_flags |= OPf_KIDS;
4551         return last;
4552     }
4553
4554     return newLISTOP(type, 0, first, last);
4555 }
4556
4557 /*
4558 =for apidoc Am|OP *|op_convert_list|I32 type|I32 flags|OP *o
4559
4560 Converts I<o> into a list op if it is not one already, and then converts it
4561 into the specified I<type>, calling its check function, allocating a target if
4562 it needs one, and folding constants.
4563
4564 A list-type op is usually constructed one kid at a time via C<newLISTOP>,
4565 C<op_prepend_elem> and C<op_append_elem>.  Then finally it is passed to
4566 C<op_convert_list> to make it the right type.
4567
4568 =cut
4569 */
4570
4571 OP *
4572 Perl_op_convert_list(pTHX_ I32 type, I32 flags, OP *o)
4573 {
4574     dVAR;
4575     if (type < 0) type = -type, flags |= OPf_SPECIAL;
4576     if (!o || o->op_type != OP_LIST)
4577         o = force_list(o, 0);
4578     else
4579     {
4580         o->op_flags &= ~OPf_WANT;
4581         o->op_private &= ~OPpLVAL_INTRO;
4582     }
4583
4584     if (!(PL_opargs[type] & OA_MARK))
4585         op_null(cLISTOPo->op_first);
4586     else {
4587         OP * const kid2 = OpSIBLING(cLISTOPo->op_first);
4588         if (kid2 && kid2->op_type == OP_COREARGS) {
4589             op_null(cLISTOPo->op_first);
4590             kid2->op_private |= OPpCOREARGS_PUSHMARK;
4591         }
4592     }
4593
4594     CHANGE_TYPE(o, type);
4595     o->op_flags |= flags;
4596     if (flags & OPf_FOLDED)
4597         o->op_folded = 1;
4598
4599     o = CHECKOP(type, o);
4600     if (o->op_type != (unsigned)type)
4601         return o;
4602
4603     return fold_constants(op_integerize(op_std_init(o)));
4604 }
4605
4606 /* Constructors */
4607
4608
4609 /*
4610 =head1 Optree construction
4611
4612 =for apidoc Am|OP *|newNULLLIST
4613
4614 Constructs, checks, and returns a new C<stub> op, which represents an
4615 empty list expression.
4616
4617 =cut
4618 */
4619
4620 OP *
4621 Perl_newNULLLIST(pTHX)
4622 {
4623     return newOP(OP_STUB, 0);
4624 }
4625
4626 /* promote o and any siblings to be a list if its not already; i.e.
4627  *
4628  *  o - A - B
4629  *
4630  * becomes
4631  *
4632  *  list
4633  *    |
4634  *  pushmark - o - A - B
4635  *
4636  * If nullit it true, the list op is nulled.
4637  */
4638
4639 static OP *
4640 S_force_list(pTHX_ OP *o, bool nullit)
4641 {
4642     if (!o || o->op_type != OP_LIST) {
4643         OP *rest = NULL;
4644         if (o) {
4645             /* manually detach any siblings then add them back later */
4646             rest = OpSIBLING(o);
4647             OpSIBLING_set(o, NULL);
4648             o->op_lastsib = 1;
4649         }
4650         o = newLISTOP(OP_LIST, 0, o, NULL);
4651         if (rest)
4652             op_sibling_splice(o, cLISTOPo->op_last, 0, rest);
4653     }
4654     if (nullit)
4655         op_null(o);
4656     return o;
4657 }
4658
4659 /*
4660 =for apidoc Am|OP *|newLISTOP|I32 type|I32 flags|OP *first|OP *last
4661
4662 Constructs, checks, and returns an op of any list type.  I<type> is
4663 the opcode.  I<flags> gives the eight bits of C<op_flags>, except that
4664 C<OPf_KIDS> will be set automatically if required.  I<first> and I<last>
4665 supply up to two ops to be direct children of the list op; they are
4666 consumed by this function and become part of the constructed op tree.
4667
4668 For most list operators, the check function expects all the kid ops to be
4669 present already, so calling C<newLISTOP(OP_JOIN, ...)> (e.g.) is not
4670 appropriate.  What you want to do in that case is create an op of type
4671 OP_LIST, append more children to it, and then call L</op_convert_list>.
4672 See L</op_convert_list> for more information.
4673
4674
4675 =cut
4676 */
4677
4678 OP *
4679 Perl_newLISTOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
4680 {
4681     dVAR;
4682     LISTOP *listop;
4683
4684     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LISTOP
4685         || type == OP_CUSTOM);
4686
4687     NewOp(1101, listop, 1, LISTOP);
4688
4689     CHANGE_TYPE(listop, type);
4690     if (first || last)
4691         flags |= OPf_KIDS;
4692     listop->op_flags = (U8)flags;
4693
4694     if (!last && first)
4695         last = first;
4696     else if (!first && last)
4697         first = last;
4698     else if (first)
4699         OpSIBLING_set(first, last);
4700     listop->op_first = first;
4701     listop->op_last = last;
4702     if (type == OP_LIST) {
4703         OP* const pushop = newOP(OP_PUSHMARK, 0);
4704         pushop->op_lastsib = 0;
4705         OpSIBLING_set(pushop, first);
4706         listop->op_first = pushop;
4707         listop->op_flags |= OPf_KIDS;
4708         if (!last)
4709             listop->op_last = pushop;
4710     }
4711     if (first)
4712         first->op_lastsib = 0;
4713     if (listop->op_last) {
4714         listop->op_last->op_lastsib = 1;
4715 #ifdef PERL_OP_PARENT
4716         listop->op_last->op_sibling = (OP*)listop;
4717 #endif
4718     }
4719
4720     return CHECKOP(type, listop);
4721 }
4722
4723 /*
4724 =for apidoc Am|OP *|newOP|I32 type|I32 flags
4725
4726 Constructs, checks, and returns an op of any base type (any type that
4727 has no extra fields).  I<type> is the opcode.  I<flags> gives the
4728 eight bits of C<op_flags>, and, shifted up eight bits, the eight bits
4729 of C<op_private>.
4730
4731 =cut
4732 */
4733
4734 OP *
4735 Perl_newOP(pTHX_ I32 type, I32 flags)
4736 {
4737     dVAR;
4738     OP *o;
4739
4740     if (type == -OP_ENTEREVAL) {
4741         type = OP_ENTEREVAL;
4742         flags |= OPpEVAL_BYTES<<8;
4743     }
4744
4745     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP
4746         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
4747         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
4748         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
4749
4750     NewOp(1101, o, 1, OP);
4751     CHANGE_TYPE(o, type);
4752     o->op_flags = (U8)flags;
4753
4754     o->op_next = o;
4755     o->op_private = (U8)(0 | (flags >> 8));
4756     if (PL_opargs[type] & OA_RETSCALAR)
4757         scalar(o);
4758     if (PL_opargs[type] & OA_TARGET)
4759         o->op_targ = pad_alloc(type, SVs_PADTMP);
4760     return CHECKOP(type, o);
4761 }
4762
4763 /*
4764 =for apidoc Am|OP *|newUNOP|I32 type|I32 flags|OP *first
4765
4766 Constructs, checks, and returns an op of any unary type.  I<type> is
4767 the opcode.  I<flags> gives the eight bits of C<op_flags>, except that
4768 C<OPf_KIDS> will be set automatically if required, and, shifted up eight
4769 bits, the eight bits of C<op_private>, except that the bit with value 1
4770 is automatically set.  I<first> supplies an optional op to be the direct
4771 child of the unary op; it is consumed by this function and become part
4772 of the constructed op tree.
4773
4774 =cut
4775 */
4776
4777 OP *
4778 Perl_newUNOP(pTHX_ I32 type, I32 flags, OP *first)
4779 {
4780     dVAR;
4781     UNOP *unop;
4782
4783     if (type == -OP_ENTEREVAL) {
4784         type = OP_ENTEREVAL;
4785         flags |= OPpEVAL_BYTES<<8;
4786     }
4787
4788     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP
4789         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
4790         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
4791         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
4792         || type == OP_SASSIGN
4793         || type == OP_ENTERTRY
4794         || type == OP_CUSTOM
4795         || type == OP_NULL );
4796
4797     if (!first)
4798         first = newOP(OP_STUB, 0);
4799     if (PL_opargs[type] & OA_MARK)
4800         first = force_list(first, 1);
4801
4802     NewOp(1101, unop, 1, UNOP);
4803     CHANGE_TYPE(unop, type);
4804     unop->op_first = first;
4805     unop->op_flags = (U8)(flags | OPf_KIDS);
4806     unop->op_private = (U8)(1 | (flags >> 8));
4807
4808 #ifdef PERL_OP_PARENT
4809     if (!OpHAS_SIBLING(first)) /* true unless weird syntax error */
4810         first->op_sibling = (OP*)unop;
4811 #endif
4812
4813     unop = (UNOP*) CHECKOP(type, unop);
4814     if (unop->op_next)
4815         return (OP*)unop;
4816
4817     return fold_constants(op_integerize(op_std_init((OP *) unop)));
4818 }
4819
4820 /*
4821 =for apidoc newUNOP_AUX
4822
4823 Similar to C<newUNOP>, but creates an UNOP_AUX struct instead, with op_aux
4824 initialised to aux
4825
4826 =cut
4827 */
4828
4829 OP *
4830 Perl_newUNOP_AUX(pTHX_ I32 type, I32 flags, OP *first, UNOP_AUX_item *aux)
4831 {
4832     dVAR;
4833     UNOP_AUX *unop;
4834
4835     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP_AUX
4836         || type == OP_CUSTOM);
4837
4838     NewOp(1101, unop, 1, UNOP_AUX);
4839     unop->op_type = (OPCODE)type;
4840     unop->op_ppaddr = PL_ppaddr[type];
4841     unop->op_first = first;
4842     unop->op_flags = (U8)(flags | (first ? OPf_KIDS : 0));
4843     unop->op_private = (U8)((first ? 1 : 0) | (flags >> 8));
4844     unop->op_aux = aux;
4845
4846 #ifdef PERL_OP_PARENT
4847     if (first && !OpHAS_SIBLING(first)) /* true unless weird syntax error */
4848         first->op_sibling = (OP*)unop;
4849 #endif
4850
4851     unop = (UNOP_AUX*) CHECKOP(type, unop);
4852
4853     return op_std_init((OP *) unop);
4854 }
4855
4856 /*
4857 =for apidoc Am|OP *|newMETHOP|I32 type|I32 flags|OP *first
4858
4859 Constructs, checks, and returns an op of method type with a method name
4860 evaluated at runtime.  I<type> is the opcode.  I<flags> gives the eight
4861 bits of C<op_flags>, except that C<OPf_KIDS> will be set automatically,
4862 and, shifted up eight bits, the eight bits of C<op_private>, except that
4863 the bit with value 1 is automatically set.  I<dynamic_meth> supplies an
4864 op which evaluates method name; it is consumed by this function and
4865 become part of the constructed op tree.
4866 Supported optypes: OP_METHOD.
4867
4868 =cut
4869 */
4870
4871 static OP*
4872 S_newMETHOP_internal(pTHX_ I32 type, I32 flags, OP* dynamic_meth, SV* const_meth) {
4873     dVAR;
4874     METHOP *methop;
4875
4876     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_METHOP
4877         || type == OP_CUSTOM);
4878
4879     NewOp(1101, methop, 1, METHOP);
4880     if (dynamic_meth) {
4881         if (PL_opargs[type] & OA_MARK) dynamic_meth = force_list(dynamic_meth, 1);
4882         methop->op_flags = (U8)(flags | OPf_KIDS);
4883         methop->op_u.op_first = dynamic_meth;
4884         methop->op_private = (U8)(1 | (flags >> 8));
4885
4886 #ifdef PERL_OP_PARENT
4887         if (!OpHAS_SIBLING(dynamic_meth))
4888             dynamic_meth->op_sibling = (OP*)methop;
4889 #endif
4890     }
4891     else {
4892         assert(const_meth);
4893         methop->op_flags = (U8)(flags & ~OPf_KIDS);
4894         methop->op_u.op_meth_sv = const_meth;
4895         methop->op_private = (U8)(0 | (flags >> 8));
4896         methop->op_next = (OP*)methop;
4897     }
4898
4899 #ifdef USE_ITHREADS
4900     methop->op_rclass_targ = 0;
4901 #else
4902     methop->op_rclass_sv = NULL;
4903 #endif
4904
4905     CHANGE_TYPE(methop, type);
4906     return CHECKOP(type, methop);
4907 }
4908
4909 OP *
4910 Perl_newMETHOP (pTHX_ I32 type, I32 flags, OP* dynamic_meth) {
4911     PERL_ARGS_ASSERT_NEWMETHOP;
4912     return newMETHOP_internal(type, flags, dynamic_meth, NULL);
4913 }
4914
4915 /*
4916 =for apidoc Am|OP *|newMETHOP_named|I32 type|I32 flags|SV *const_meth
4917
4918 Constructs, checks, and returns an op of method type with a constant
4919 method name.  I<type> is the opcode.  I<flags> gives the eight bits of
4920 C<op_flags>, and, shifted up eight bits, the eight bits of
4921 C<op_private>.  I<const_meth> supplies a constant method name;
4922 it must be a shared COW string.
4923 Supported optypes: OP_METHOD_NAMED.
4924
4925 =cut
4926 */
4927
4928 OP *
4929 Perl_newMETHOP_named (pTHX_ I32 type, I32 flags, SV* const_meth) {
4930     PERL_ARGS_ASSERT_NEWMETHOP_NAMED;
4931     return newMETHOP_internal(type, flags, NULL, const_meth);
4932 }
4933
4934 /*
4935 =for apidoc Am|OP *|newBINOP|I32 type|I32 flags|OP *first|OP *last
4936
4937 Constructs, checks, and returns an op of any binary type.  I<type>
4938 is the opcode.  I<flags> gives the eight bits of C<op_flags>, except
4939 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
4940 the eight bits of C<op_private>, except that the bit with value 1 or
4941 2 is automatically set as required.  I<first> and I<last> supply up to
4942 two ops to be the direct children of the binary op; they are consumed
4943 by this function and become part of the constructed op tree.
4944
4945 =cut
4946 */
4947
4948 OP *
4949 Perl_newBINOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
4950 {
4951     dVAR;
4952     BINOP *binop;
4953
4954     ASSUME((PL_opargs[type] & OA_CLASS_MASK) == OA_BINOP
4955         || type == OP_SASSIGN || type == OP_NULL || type == OP_CUSTOM);
4956
4957     NewOp(1101, binop, 1, BINOP);
4958
4959     if (!first)
4960         first = newOP(OP_NULL, 0);
4961
4962     CHANGE_TYPE(binop, type);
4963     binop->op_first = first;
4964     binop->op_flags = (U8)(flags | OPf_KIDS);
4965     if (!last) {
4966         last = first;
4967         binop->op_private = (U8)(1 | (flags >> 8));
4968     }
4969     else {
4970         binop->op_private = (U8)(2 | (flags >> 8));
4971         OpSIBLING_set(first, last);
4972         first->op_lastsib = 0;
4973     }
4974
4975 #ifdef PERL_OP_PARENT
4976     if (!OpHAS_SIBLING(last)) /* true unless weird syntax error */
4977         last->op_sibling = (OP*)binop;
4978 #endif
4979
4980     binop->op_last = OpSIBLING(binop->op_first);
4981 #ifdef PERL_OP_PARENT
4982     if (binop->op_last)
4983         binop->op_last->op_sibling = (OP*)binop;
4984 #endif
4985
4986     binop = (BINOP*)CHECKOP(type, binop);
4987     if (binop->op_next || binop->op_type != (OPCODE)type)
4988         return (OP*)binop;
4989
4990     return fold_constants(op_integerize(op_std_init((OP *)binop)));
4991 }
4992
4993 static int uvcompare(const void *a, const void *b)
4994     __attribute__nonnull__(1)
4995     __attribute__nonnull__(2)
4996     __attribute__pure__;
4997 static int uvcompare(const void *a, const void *b)
4998 {
4999     if (*((const UV *)a) < (*(const UV *)b))
5000         return -1;
5001     if (*((const UV *)a) > (*(const UV *)b))
5002         return 1;
5003     if (*((const UV *)a+1) < (*(const UV *)b+1))
5004         return -1;
5005     if (*((const UV *)a+1) > (*(const UV *)b+1))
5006         return 1;
5007     return 0;
5008 }
5009
5010 static OP *
5011 S_pmtrans(pTHX_ OP *o, OP *expr, OP *repl)
5012 {
5013     SV * const tstr = ((SVOP*)expr)->op_sv;
5014     SV * const rstr =
5015                               ((SVOP*)repl)->op_sv;
5016     STRLEN tlen;
5017     STRLEN rlen;
5018     const U8 *t = (U8*)SvPV_const(tstr, tlen);
5019     const U8 *r = (U8*)SvPV_const(rstr, rlen);
5020     I32 i;
5021     I32 j;
5022     I32 grows = 0;
5023     short *tbl;
5024
5025     const I32 complement = o->op_private & OPpTRANS_COMPLEMENT;
5026     const I32 squash     = o->op_private & OPpTRANS_SQUASH;
5027     I32 del              = o->op_private & OPpTRANS_DELETE;
5028     SV* swash;
5029
5030     PERL_ARGS_ASSERT_PMTRANS;
5031
5032     PL_hints |= HINT_BLOCK_SCOPE;
5033
5034     if (SvUTF8(tstr))
5035         o->op_private |= OPpTRANS_FROM_UTF;
5036
5037     if (SvUTF8(rstr))
5038         o->op_private |= OPpTRANS_TO_UTF;
5039
5040     if (o->op_private & (OPpTRANS_FROM_UTF|OPpTRANS_TO_UTF)) {
5041         SV* const listsv = newSVpvs("# comment\n");
5042         SV* transv = NULL;
5043         const U8* tend = t + tlen;
5044         const U8* rend = r + rlen;
5045         STRLEN ulen;
5046         UV tfirst = 1;
5047         UV tlast = 0;
5048         IV tdiff;
5049         STRLEN tcount = 0;
5050         UV rfirst = 1;
5051         UV rlast = 0;
5052         IV rdiff;
5053         STRLEN rcount = 0;
5054         IV diff;
5055         I32 none = 0;
5056         U32 max = 0;
5057         I32 bits;
5058         I32 havefinal = 0;
5059         U32 final = 0;
5060         const I32 from_utf  = o->op_private & OPpTRANS_FROM_UTF;
5061         const I32 to_utf    = o->op_private & OPpTRANS_TO_UTF;
5062         U8* tsave = NULL;
5063         U8* rsave = NULL;
5064         const U32 flags = UTF8_ALLOW_DEFAULT;
5065
5066         if (!from_utf) {
5067             STRLEN len = tlen;
5068             t = tsave = bytes_to_utf8(t, &len);
5069             tend = t + len;
5070         }
5071         if (!to_utf && rlen) {
5072             STRLEN len = rlen;
5073             r = rsave = bytes_to_utf8(r, &len);
5074             rend = r + len;
5075         }
5076
5077 /* There is a snag with this code on EBCDIC: scan_const() in toke.c has
5078  * encoded chars in native encoding which makes ranges in the EBCDIC 0..255
5079  * odd.  */
5080
5081         if (complement) {
5082             U8 tmpbuf[UTF8_MAXBYTES+1];
5083             UV *cp;
5084             UV nextmin = 0;
5085             Newx(cp, 2*tlen, UV);
5086             i = 0;
5087             transv = newSVpvs("");
5088             while (t < tend) {
5089                 cp[2*i] = utf8n_to_uvchr(t, tend-t, &ulen, flags);
5090                 t += ulen;
5091                 if (t < tend && *t == ILLEGAL_UTF8_BYTE) {
5092                     t++;
5093                     cp[2*i+1] = utf8n_to_uvchr(t, tend-t, &ulen, flags);
5094                     t += ulen;
5095                 }
5096                 else {
5097                  cp[2*i+1] = cp[2*i];
5098                 }
5099                 i++;
5100             }
5101             qsort(cp, i, 2*sizeof(UV), uvcompare);
5102             for (j = 0; j < i; j++) {
5103                 UV  val = cp[2*j];
5104                 diff = val - nextmin;
5105                 if (diff > 0) {
5106                     t = uvchr_to_utf8(tmpbuf,nextmin);
5107                     sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
5108                     if (diff > 1) {
5109                         U8  range_mark = ILLEGAL_UTF8_BYTE;
5110                         t = uvchr_to_utf8(tmpbuf, val - 1);
5111                         sv_catpvn(transv, (char *)&range_mark, 1);
5112                         sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
5113                     }
5114                 }
5115                 val = cp[2*j+1];
5116                 if (val >= nextmin)
5117                     nextmin = val + 1;
5118             }
5119             t = uvchr_to_utf8(tmpbuf,nextmin);
5120             sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
5121             {
5122                 U8 range_mark = ILLEGAL_UTF8_BYTE;
5123                 sv_catpvn(transv, (char *)&range_mark, 1);
5124             }
5125             t = uvchr_to_utf8(tmpbuf, 0x7fffffff);
5126             sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
5127             t = (const U8*)SvPVX_const(transv);
5128             tlen = SvCUR(transv);
5129             tend = t + tlen;
5130             Safefree(cp);
5131         }
5132         else if (!rlen && !del) {
5133             r = t; rlen = tlen; rend = tend;
5134         }
5135         if (!squash) {
5136                 if ((!rlen && !del) || t == r ||
5137                     (tlen == rlen && memEQ((char *)t, (char *)r, tlen)))
5138                 {
5139                     o->op_private |= OPpTRANS_IDENTICAL;
5140                 }
5141         }
5142
5143         while (t < tend || tfirst <= tlast) {
5144             /* see if we need more "t" chars */
5145             if (tfirst > tlast) {
5146                 tfirst = (I32)utf8n_to_uvchr(t, tend - t, &ulen, flags);
5147                 t += ulen;
5148                 if (t < tend && *t == ILLEGAL_UTF8_BYTE) {      /* illegal utf8 val indicates range */
5149                     t++;
5150                     tlast = (I32)utf8n_to_uvchr(t, tend - t, &ulen, flags);
5151                     t += ulen;
5152                 }
5153                 else
5154                     tlast = tfirst;
5155             }
5156
5157             /* now see if we need more "r" chars */
5158             if (rfirst > rlast) {
5159                 if (r < rend) {
5160                     rfirst = (I32)utf8n_to_uvchr(r, rend - r, &ulen, flags);
5161                     r += ulen;
5162                     if (r < rend && *r == ILLEGAL_UTF8_BYTE) {  /* illegal utf8 val indicates range */
5163                         r++;
5164                         rlast = (I32)utf8n_to_uvchr(r, rend - r, &ulen, flags);
5165                         r += ulen;
5166                     }
5167                     else
5168                         rlast = rfirst;
5169                 }
5170                 else {
5171                     if (!havefinal++)
5172                         final = rlast;
5173                     rfirst = rlast = 0xffffffff;
5174                 }
5175             }
5176
5177             /* now see which range will peter our first, if either. */
5178             tdiff = tlast - tfirst;
5179             rdiff = rlast - rfirst;
5180             tcount += tdiff + 1;
5181             rcount += rdiff + 1;
5182
5183             if (tdiff <= rdiff)
5184                 diff = tdiff;
5185             else
5186                 diff = rdiff;
5187
5188             if (rfirst == 0xffffffff) {
5189                 diff = tdiff;   /* oops, pretend rdiff is infinite */
5190                 if (diff > 0)
5191                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t%04lx\tXXXX\n",
5192                                    (long)tfirst, (long)tlast);
5193                 else
5194                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t\tXXXX\n", (long)tfirst);
5195             }
5196             else {
5197                 if (diff > 0)
5198                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t%04lx\t%04lx\n",
5199                                    (long)tfirst, (long)(tfirst + diff),
5200                                    (long)rfirst);
5201                 else
5202                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t\t%04lx\n",
5203                                    (long)tfirst, (long)rfirst);
5204
5205                 if (rfirst + diff > max)
5206                     max = rfirst + diff;
5207                 if (!grows)
5208                     grows = (tfirst < rfirst &&
5209                              UNISKIP(tfirst) < UNISKIP(rfirst + diff));
5210                 rfirst += diff + 1;
5211             }
5212             tfirst += diff + 1;
5213         }
5214
5215         none = ++max;
5216         if (del)
5217             del = ++max;
5218
5219         if (max > 0xffff)
5220             bits = 32;
5221         else if (max > 0xff)
5222             bits = 16;
5223         else
5224             bits = 8;
5225
5226         swash = MUTABLE_SV(swash_init("utf8", "", listsv, bits, none));
5227 #ifdef USE_ITHREADS
5228         cPADOPo->op_padix = pad_alloc(OP_TRANS, SVf_READONLY);
5229         SvREFCNT_dec(PAD_SVl(cPADOPo->op_padix));
5230         PAD_SETSV(cPADOPo->op_padix, swash);
5231         SvPADTMP_on(swash);
5232         SvREADONLY_on(swash);
5233 #else
5234         cSVOPo->op_sv = swash;
5235 #endif
5236         SvREFCNT_dec(listsv);
5237         SvREFCNT_dec(transv);
5238
5239         if (!del && havefinal && rlen)
5240             (void)hv_store(MUTABLE_HV(SvRV(swash)), "FINAL", 5,
5241                            newSVuv((UV)final), 0);
5242
5243         Safefree(tsave);
5244         Safefree(rsave);
5245
5246         tlen = tcount;
5247         rlen = rcount;
5248         if (r < rend)
5249             rlen++;
5250         else if (rlast == 0xffffffff)
5251             rlen = 0;
5252
5253         goto warnins;
5254     }
5255
5256     tbl = (short*)PerlMemShared_calloc(
5257         (o->op_private & OPpTRANS_COMPLEMENT) &&
5258             !(o->op_private & OPpTRANS_DELETE) ? 258 : 256,
5259         sizeof(short));
5260     cPVOPo->op_pv = (char*)tbl;
5261     if (complement) {
5262         for (i = 0; i < (I32)tlen; i++)
5263             tbl[t[i]] = -1;
5264         for (i = 0, j = 0; i < 256; i++) {
5265             if (!tbl[i]) {
5266                 if (j >= (I32)rlen) {
5267                     if (del)
5268                         tbl[i] = -2;
5269                     else if (rlen)
5270                         tbl[i] = r[j-1];
5271                     else
5272                         tbl[i] = (short)i;
5273                 }
5274                 else {
5275                     if (i < 128 && r[j] >= 128)
5276                         grows = 1;
5277                     tbl[i] = r[j++];
5278                 }
5279             }
5280         }
5281         if (!del) {
5282             if (!rlen) {
5283                 j = rlen;
5284                 if (!squash)
5285                     o->op_private |= OPpTRANS_IDENTICAL;
5286             }
5287             else if (j >= (I32)rlen)
5288                 j = rlen - 1;
5289             else {
5290                 tbl = 
5291                     (short *)
5292                     PerlMemShared_realloc(tbl,
5293                                           (0x101+rlen-j) * sizeof(short));
5294                 cPVOPo->op_pv = (char*)tbl;
5295             }
5296             tbl[0x100] = (short)(rlen - j);
5297             for (i=0; i < (I32)rlen - j; i++)
5298                 tbl[0x101+i] = r[j+i];
5299         }
5300     }
5301     else {
5302         if (!rlen && !del) {
5303             r = t; rlen = tlen;
5304             if (!squash)
5305                 o->op_private |= OPpTRANS_IDENTICAL;
5306         }
5307         else if (!squash && rlen == tlen && memEQ((char*)t, (char*)r, tlen)) {
5308             o->op_private |= OPpTRANS_IDENTICAL;
5309         }
5310         for (i = 0; i < 256; i++)
5311             tbl[i] = -1;
5312         for (i = 0, j = 0; i < (I32)tlen; i++,j++) {
5313             if (j >= (I32)rlen) {
5314                 if (del) {
5315                     if (tbl[t[i]] == -1)
5316                         tbl[t[i]] = -2;
5317                     continue;
5318                 }
5319                 --j;
5320             }
5321             if (tbl[t[i]] == -1) {
5322                 if (t[i] < 128 && r[j] >= 128)
5323                     grows = 1;
5324                 tbl[t[i]] = r[j];
5325             }
5326         }
5327     }
5328
5329   warnins:
5330     if(del && rlen == tlen) {
5331         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Useless use of /d modifier in transliteration operator"); 
5332     } else if(rlen > tlen && !complement) {
5333         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Replacement list is longer than search list");
5334     }
5335
5336     if (grows)
5337         o->op_private |= OPpTRANS_GROWS;
5338     op_free(expr);
5339     op_free(repl);
5340
5341     return o;
5342 }
5343
5344 /*
5345 =for apidoc Am|OP *|newPMOP|I32 type|I32 flags
5346
5347 Constructs, checks, and returns an op of any pattern matching type.
5348 I<type> is the opcode.  I<flags> gives the eight bits of C<op_flags>
5349 and, shifted up eight bits, the eight bits of C<op_private>.
5350
5351 =cut
5352 */
5353
5354 OP *
5355 Perl_newPMOP(pTHX_ I32 type, I32 flags)
5356 {
5357     dVAR;
5358     PMOP *pmop;
5359
5360     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PMOP
5361         || type == OP_CUSTOM);
5362
5363     NewOp(1101, pmop, 1, PMOP);
5364     CHANGE_TYPE(pmop, type);
5365     pmop->op_flags = (U8)flags;
5366     pmop->op_private = (U8)(0 | (flags >> 8));
5367     if (PL_opargs[type] & OA_RETSCALAR)
5368         scalar((OP *)pmop);
5369
5370     if (PL_hints & HINT_RE_TAINT)
5371         pmop->op_pmflags |= PMf_RETAINT;
5372 #ifdef USE_LOCALE_CTYPE
5373     if (IN_LC_COMPILETIME(LC_CTYPE)) {
5374         set_regex_charset(&(pmop->op_pmflags), REGEX_LOCALE_CHARSET);
5375     }
5376     else
5377 #endif
5378          if (IN_UNI_8_BIT) {
5379         set_regex_charset(&(pmop->op_pmflags), REGEX_UNICODE_CHARSET);
5380     }
5381     if (PL_hints & HINT_RE_FLAGS) {
5382         SV *reflags = Perl_refcounted_he_fetch_pvn(aTHX_
5383          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags"), 0, 0
5384         );
5385         if (reflags && SvOK(reflags)) pmop->op_pmflags |= SvIV(reflags);
5386         reflags = Perl_refcounted_he_fetch_pvn(aTHX_
5387          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags_charset"), 0, 0
5388         );
5389         if (reflags && SvOK(reflags)) {
5390             set_regex_charset(&(pmop->op_pmflags), (regex_charset)SvIV(reflags));
5391         }
5392     }
5393
5394
5395 #ifdef USE_ITHREADS
5396     assert(SvPOK(PL_regex_pad[0]));
5397     if (SvCUR(PL_regex_pad[0])) {
5398         /* Pop off the "packed" IV from the end.  */
5399         SV *const repointer_list = PL_regex_pad[0];
5400         const char *p = SvEND(repointer_list) - sizeof(IV);
5401         const IV offset = *((IV*)p);
5402
5403         assert(SvCUR(repointer_list) % sizeof(IV) == 0);
5404
5405         SvEND_set(repointer_list, p);
5406
5407         pmop->op_pmoffset = offset;
5408         /* This slot should be free, so assert this:  */
5409         assert(PL_regex_pad[offset] == &PL_sv_undef);
5410     } else {
5411         SV * const repointer = &PL_sv_undef;
5412         av_push(PL_regex_padav, repointer);
5413         pmop->op_pmoffset = av_tindex(PL_regex_padav);
5414         PL_regex_pad = AvARRAY(PL_regex_padav);
5415     }
5416 #endif
5417
5418     return CHECKOP(type, pmop);
5419 }
5420
5421 static void
5422 S_set_haseval(pTHX)
5423 {
5424     PADOFFSET i = 1;
5425     PL_cv_has_eval = 1;
5426     /* Any pad names in scope are potentially lvalues.  */
5427     for (; i < PadnamelistMAXNAMED(PL_comppad_name); i++) {
5428         PADNAME *pn = PAD_COMPNAME_SV(i);
5429         if (!pn || !PadnameLEN(pn))
5430             continue;
5431         if (PadnameOUTER(pn) || PadnameIN_SCOPE(pn, PL_cop_seqmax))
5432             S_mark_padname_lvalue(aTHX_ pn);
5433     }
5434 }
5435
5436 /* Given some sort of match op o, and an expression expr containing a
5437  * pattern, either compile expr into a regex and attach it to o (if it's
5438  * constant), or convert expr into a runtime regcomp op sequence (if it's
5439  * not)
5440  *
5441  * isreg indicates that the pattern is part of a regex construct, eg
5442  * $x =~ /pattern/ or split /pattern/, as opposed to $x =~ $pattern or
5443  * split "pattern", which aren't. In the former case, expr will be a list
5444  * if the pattern contains more than one term (eg /a$b/).
5445  *
5446  * When the pattern has been compiled within a new anon CV (for
5447  * qr/(?{...})/ ), then floor indicates the savestack level just before
5448  * the new sub was created
5449  */
5450
5451 OP *
5452 Perl_pmruntime(pTHX_ OP *o, OP *expr, OP *repl, bool isreg, I32 floor)
5453 {
5454     PMOP *pm;
5455     LOGOP *rcop;
5456     I32 repl_has_vars = 0;
5457     bool is_trans = (o->op_type == OP_TRANS || o->op_type == OP_TRANSR);
5458     bool is_compiletime;
5459     bool has_code;
5460
5461     PERL_ARGS_ASSERT_PMRUNTIME;
5462
5463     if (is_trans) {
5464         return pmtrans(o, expr, repl);
5465     }
5466
5467     /* find whether we have any runtime or code elements;
5468      * at the same time, temporarily set the op_next of each DO block;
5469      * then when we LINKLIST, this will cause the DO blocks to be excluded
5470      * from the op_next chain (and from having LINKLIST recursively
5471      * applied to them). We fix up the DOs specially later */
5472
5473     is_compiletime = 1;
5474     has_code = 0;
5475     if (expr->op_type == OP_LIST) {
5476         OP *o;
5477         for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
5478             if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)) {
5479                 has_code = 1;
5480                 assert(!o->op_next);
5481                 if (UNLIKELY(!OpHAS_SIBLING(o))) {
5482                     assert(PL_parser && PL_parser->error_count);
5483                     /* This can happen with qr/ (?{(^{})/.  Just fake up
5484                        the op we were expecting to see, to avoid crashing
5485                        elsewhere.  */
5486                     op_sibling_splice(expr, o, 0,
5487                                       newSVOP(OP_CONST, 0, &PL_sv_no));
5488                 }
5489                 o->op_next = OpSIBLING(o);
5490             }
5491             else if (o->op_type != OP_CONST && o->op_type != OP_PUSHMARK)
5492                 is_compiletime = 0;
5493         }
5494     }
5495     else if (expr->op_type != OP_CONST)
5496         is_compiletime = 0;
5497
5498     LINKLIST(expr);
5499
5500     /* fix up DO blocks; treat each one as a separate little sub;
5501      * also, mark any arrays as LIST/REF */
5502
5503     if (expr->op_type == OP_LIST) {
5504         OP *o;
5505         for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
5506
5507             if (o->op_type == OP_PADAV || o->op_type == OP_RV2AV) {
5508                 assert( !(o->op_flags  & OPf_WANT));
5509                 /* push the array rather than its contents. The regex
5510                  * engine will retrieve and join the elements later */
5511                 o->op_flags |= (OPf_WANT_LIST | OPf_REF);
5512                 continue;
5513             }
5514
5515             if (!(o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)))
5516                 continue;
5517             o->op_next = NULL; /* undo temporary hack from above */
5518             scalar(o);
5519             LINKLIST(o);
5520             if (cLISTOPo->op_first->op_type == OP_LEAVE) {
5521                 LISTOP *leaveop = cLISTOPx(cLISTOPo->op_first);
5522                 /* skip ENTER */
5523                 assert(leaveop->op_first->op_type == OP_ENTER);
5524                 assert(OpHAS_SIBLING(leaveop->op_first));
5525                 o->op_next = OpSIBLING(leaveop->op_first);
5526                 /* skip leave */
5527                 assert(leaveop->op_flags & OPf_KIDS);
5528                 assert(leaveop->op_last->op_next == (OP*)leaveop);
5529                 leaveop->op_next = NULL; /* stop on last op */
5530                 op_null((OP*)leaveop);
5531             }
5532             else {
5533                 /* skip SCOPE */
5534                 OP *scope = cLISTOPo->op_first;
5535                 assert(scope->op_type == OP_SCOPE);
5536                 assert(scope->op_flags & OPf_KIDS);
5537                 scope->op_next = NULL; /* stop on last op */
5538                 op_null(scope);
5539             }
5540             /* have to peep the DOs individually as we've removed it from
5541              * the op_next chain */
5542             CALL_PEEP(o);
5543             S_prune_chain_head(&(o->op_next));
5544             if (is_compiletime)
5545                 /* runtime finalizes as part of finalizing whole tree */
5546                 finalize_optree(o);
5547         }
5548     }
5549     else if (expr->op_type == OP_PADAV || expr->op_type == OP_RV2AV) {
5550         assert( !(expr->op_flags  & OPf_WANT));
5551         /* push the array rather than its contents. The regex
5552          * engine will retrieve and join the elements later */
5553         expr->op_flags |= (OPf_WANT_LIST | OPf_REF);
5554     }
5555
5556     PL_hints |= HINT_BLOCK_SCOPE;
5557     pm = (PMOP*)o;
5558     assert(floor==0 || (pm->op_pmflags & PMf_HAS_CV));
5559
5560     if (is_compiletime) {
5561         U32 rx_flags = pm->op_pmflags & RXf_PMf_COMPILETIME;
5562         regexp_engine const *eng = current_re_engine();
5563
5564         if (o->op_flags & OPf_SPECIAL)
5565             rx_flags |= RXf_SPLIT;
5566
5567         if (!has_code || !eng->op_comp) {
5568             /* compile-time simple constant pattern */
5569
5570             if ((pm->op_pmflags & PMf_HAS_CV) && !has_code) {
5571                 /* whoops! we guessed that a qr// had a code block, but we
5572                  * were wrong (e.g. /[(?{}]/ ). Throw away the PL_compcv
5573                  * that isn't required now. Note that we have to be pretty
5574                  * confident that nothing used that CV's pad while the
5575                  * regex was parsed, except maybe op targets for \Q etc.
5576                  * If there were any op targets, though, they should have
5577                  * been stolen by constant folding.
5578                  */
5579 #ifdef DEBUGGING
5580                 SSize_t i = 0;
5581                 assert(PadnamelistMAXNAMED(PL_comppad_name) == 0);
5582                 while (++i <= AvFILLp(PL_comppad)) {
5583                     assert(!PL_curpad[i]);
5584                 }
5585 #endif
5586                 /* But we know that one op is using this CV's slab. */
5587                 cv_forget_slab(PL_compcv);
5588                 LEAVE_SCOPE(floor);
5589                 pm->op_pmflags &= ~PMf_HAS_CV;
5590             }
5591
5592             PM_SETRE(pm,
5593                 eng->op_comp
5594                     ? eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
5595                                         rx_flags, pm->op_pmflags)
5596                     : Perl_re_op_compile(aTHX_ NULL, 0, expr, eng, NULL, NULL,
5597                                         rx_flags, pm->op_pmflags)
5598             );
5599             op_free(expr);
5600         }
5601         else {
5602             /* compile-time pattern that includes literal code blocks */
5603             REGEXP* re = eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
5604                         rx_flags,
5605                         (pm->op_pmflags |
5606                             ((PL_hints & HINT_RE_EVAL) ? PMf_USE_RE_EVAL : 0))
5607                     );
5608             PM_SETRE(pm, re);
5609             if (pm->op_pmflags & PMf_HAS_CV) {
5610                 CV *cv;
5611                 /* this QR op (and the anon sub we embed it in) is never
5612                  * actually executed. It's just a placeholder where we can
5613                  * squirrel away expr in op_code_list without the peephole
5614                  * optimiser etc processing it for a second time */
5615                 OP *qr = newPMOP(OP_QR, 0);
5616                 ((PMOP*)qr)->op_code_list = expr;
5617
5618                 /* handle the implicit sub{} wrapped round the qr/(?{..})/ */
5619                 SvREFCNT_inc_simple_void(PL_compcv);
5620                 cv = newATTRSUB(floor, 0, NULL, NULL, qr);
5621                 ReANY(re)->qr_anoncv = cv;
5622
5623                 /* attach the anon CV to the pad so that
5624                  * pad_fixup_inner_anons() can find it */
5625                 (void)pad_add_anon(cv, o->op_type);
5626                 SvREFCNT_inc_simple_void(cv);
5627             }
5628             else {
5629                 pm->op_code_list = expr;
5630             }
5631         }
5632     }
5633     else {
5634         /* runtime pattern: build chain of regcomp etc ops */
5635         bool reglist;
5636         PADOFFSET cv_targ = 0;
5637
5638         reglist = isreg && expr->op_type == OP_LIST;
5639         if (reglist)
5640             op_null(expr);
5641
5642         if (has_code) {
5643             pm->op_code_list = expr;
5644             /* don't free op_code_list; its ops are embedded elsewhere too */
5645             pm->op_pmflags |= PMf_CODELIST_PRIVATE;
5646         }
5647
5648         if (o->op_flags & OPf_SPECIAL)
5649             pm->op_pmflags |= PMf_SPLIT;
5650
5651         /* the OP_REGCMAYBE is a placeholder in the non-threaded case
5652          * to allow its op_next to be pointed past the regcomp and
5653          * preceding stacking ops;
5654          * OP_REGCRESET is there to reset taint before executing the
5655          * stacking ops */
5656         if (pm->op_pmflags & PMf_KEEP || TAINTING_get)
5657             expr = newUNOP((TAINTING_get ? OP_REGCRESET : OP_REGCMAYBE),0,expr);
5658
5659         if (pm->op_pmflags & PMf_HAS_CV) {
5660             /* we have a runtime qr with literal code. This means
5661              * that the qr// has been wrapped in a new CV, which
5662              * means that runtime consts, vars etc will have been compiled
5663              * against a new pad. So... we need to execute those ops
5664              * within the environment of the new CV. So wrap them in a call
5665              * to a new anon sub. i.e. for
5666              *
5667              *     qr/a$b(?{...})/,
5668              *
5669              * we build an anon sub that looks like
5670              *
5671              *     sub { "a", $b, '(?{...})' }
5672              *
5673              * and call it, passing the returned list to regcomp.
5674              * Or to put it another way, the list of ops that get executed
5675              * are:
5676              *
5677              *     normal              PMf_HAS_CV
5678              *     ------              -------------------
5679              *                         pushmark (for regcomp)
5680              *                         pushmark (for entersub)
5681              *                         anoncode
5682              *                         srefgen
5683              *                         entersub
5684              *     regcreset                  regcreset
5685              *     pushmark                   pushmark
5686              *     const("a")                 const("a")
5687              *     gvsv(b)                    gvsv(b)
5688              *     const("(?{...})")          const("(?{...})")
5689              *                                leavesub
5690              *     regcomp             regcomp
5691              */
5692
5693             SvREFCNT_inc_simple_void(PL_compcv);
5694             CvLVALUE_on(PL_compcv);
5695             /* these lines are just an unrolled newANONATTRSUB */
5696             expr = newSVOP(OP_ANONCODE, 0,
5697                     MUTABLE_SV(newATTRSUB(floor, 0, NULL, NULL, expr)));
5698             cv_targ = expr->op_targ;
5699             expr = newUNOP(OP_REFGEN, 0, expr);
5700
5701             expr = list(force_list(newUNOP(OP_ENTERSUB, 0, scalar(expr)), 1));
5702         }
5703
5704         rcop = S_alloc_LOGOP(aTHX_ OP_REGCOMP, scalar(expr), o);
5705         rcop->op_flags |=  ((PL_hints & HINT_RE_EVAL) ? OPf_SPECIAL : 0)
5706                            | (reglist ? OPf_STACKED : 0);
5707         rcop->op_targ = cv_targ;
5708
5709         /* /$x/ may cause an eval, since $x might be qr/(?{..})/  */
5710         if (PL_hints & HINT_RE_EVAL)
5711             S_set_haseval(aTHX);
5712
5713         /* establish postfix order */
5714         if (expr->op_type == OP_REGCRESET || expr->op_type == OP_REGCMAYBE) {
5715             LINKLIST(expr);
5716             rcop->op_next = expr;
5717             ((UNOP*)expr)->op_first->op_next = (OP*)rcop;
5718         }
5719         else {
5720             rcop->op_next = LINKLIST(expr);
5721             expr->op_next = (OP*)rcop;
5722         }
5723
5724         op_prepend_elem(o->op_type, scalar((OP*)rcop), o);
5725     }
5726
5727     if (repl) {
5728         OP *curop = repl;
5729         bool konst;
5730         /* If we are looking at s//.../e with a single statement, get past
5731            the implicit do{}. */
5732         if (curop->op_type == OP_NULL && curop->op_flags & OPf_KIDS
5733              && cUNOPx(curop)->op_first->op_type == OP_SCOPE
5734              && cUNOPx(curop)->op_first->op_flags & OPf_KIDS)
5735          {
5736             OP *sib;
5737             OP *kid = cUNOPx(cUNOPx(curop)->op_first)->op_first;
5738             if (kid->op_type == OP_NULL && (sib = OpSIBLING(kid))
5739              && !OpHAS_SIBLING(sib))
5740                 curop = sib;
5741         }
5742         if (curop->op_type == OP_CONST)
5743             konst = TRUE;
5744         else if (( (curop->op_type == OP_RV2SV ||
5745                     curop->op_type == OP_RV2AV ||
5746                     curop->op_type == OP_RV2HV ||
5747                     curop->op_type == OP_RV2GV)
5748                    && cUNOPx(curop)->op_first
5749                    && cUNOPx(curop)->op_first->op_type == OP_GV )
5750                 || curop->op_type == OP_PADSV
5751                 || curop->op_type == OP_PADAV
5752                 || curop->op_type == OP_PADHV
5753                 || curop->op_type == OP_PADANY) {
5754             repl_has_vars = 1;
5755             konst = TRUE;
5756         }
5757         else konst = FALSE;
5758         if (konst
5759             && !(repl_has_vars
5760                  && (!PM_GETRE(pm)
5761                      || !RX_PRELEN(PM_GETRE(pm))
5762                      || RX_EXTFLAGS(PM_GETRE(pm)) & RXf_EVAL_SEEN)))
5763         {
5764             pm->op_pmflags |= PMf_CONST;        /* const for long enough */
5765             op_prepend_elem(o->op_type, scalar(repl), o);
5766         }
5767         else {
5768             rcop = S_alloc_LOGOP(aTHX_ OP_SUBSTCONT, scalar(repl), o);
5769             rcop->op_private = 1;
5770
5771             /* establish postfix order */
5772             rcop->op_next = LINKLIST(repl);
5773             repl->op_next = (OP*)rcop;
5774
5775             pm->op_pmreplrootu.op_pmreplroot = scalar((OP*)rcop);
5776             assert(!(pm->op_pmflags & PMf_ONCE));
5777             pm->op_pmstashstartu.op_pmreplstart = LINKLIST(rcop);
5778             rcop->op_next = 0;
5779         }
5780     }
5781
5782     return (OP*)pm;
5783 }
5784
5785 /*
5786 =for apidoc Am|OP *|newSVOP|I32 type|I32 flags|SV *sv
5787
5788 Constructs, checks, and returns an op of any type that involves an
5789 embedded SV.  I<type> is the opcode.  I<flags> gives the eight bits
5790 of C<op_flags>.  I<sv> gives the SV to embed in the op; this function
5791 takes ownership of one reference to it.
5792
5793 =cut
5794 */
5795
5796 OP *
5797 Perl_newSVOP(pTHX_ I32 type, I32 flags, SV *sv)
5798 {
5799     dVAR;
5800     SVOP *svop;
5801
5802     PERL_ARGS_ASSERT_NEWSVOP;
5803
5804     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
5805         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
5806         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
5807         || type == OP_CUSTOM);
5808
5809     NewOp(1101, svop, 1, SVOP);
5810     CHANGE_TYPE(svop, type);
5811     svop->op_sv = sv;
5812     svop->op_next = (OP*)svop;
5813     svop->op_flags = (U8)flags;
5814     svop->op_private = (U8)(0 | (flags >> 8));
5815     if (PL_opargs[type] & OA_RETSCALAR)
5816         scalar((OP*)svop);
5817     if (PL_opargs[type] & OA_TARGET)
5818         svop->op_targ = pad_alloc(type, SVs_PADTMP);
5819     return CHECKOP(type, svop);
5820 }
5821
5822 /*
5823 =for apidoc Am|OP *|newDEFSVOP|
5824
5825 Constructs and returns an op to access C<$_>, either as a lexical
5826 variable (if declared as C<my $_>) in the current scope, or the
5827 global C<$_>.
5828
5829 =cut
5830 */
5831
5832 OP *
5833 Perl_newDEFSVOP(pTHX)
5834 {
5835     const PADOFFSET offset = pad_findmy_pvs("$_", 0);
5836     if (offset == NOT_IN_PAD || PAD_COMPNAME_FLAGS_isOUR(offset)) {
5837         return newSVREF(newGVOP(OP_GV, 0, PL_defgv));
5838     }
5839     else {
5840         OP * const o = newOP(OP_PADSV, 0);
5841         o->op_targ = offset;
5842         return o;
5843     }
5844 }
5845
5846 #ifdef USE_ITHREADS
5847
5848 /*
5849 =for apidoc Am|OP *|newPADOP|I32 type|I32 flags|SV *sv
5850
5851 Constructs, checks, and returns an op of any type that involves a
5852 reference to a pad element.  I<type> is the opcode.  I<flags> gives the
5853 eight bits of C<op_flags>.  A pad slot is automatically allocated, and
5854 is populated with I<sv>; this function takes ownership of one reference
5855 to it.
5856
5857 This function only exists if Perl has been compiled to use ithreads.
5858
5859 =cut
5860 */
5861
5862 OP *
5863 Perl_newPADOP(pTHX_ I32 type, I32 flags, SV *sv)
5864 {
5865     dVAR;
5866     PADOP *padop;
5867
5868     PERL_ARGS_ASSERT_NEWPADOP;
5869
5870     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
5871         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
5872         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
5873         || type == OP_CUSTOM);
5874
5875     NewOp(1101, padop, 1, PADOP);
5876     CHANGE_TYPE(padop, type);
5877     padop->op_padix =
5878         pad_alloc(type, isGV(sv) ? SVf_READONLY : SVs_PADTMP);
5879     SvREFCNT_dec(PAD_SVl(padop->op_padix));
5880     PAD_SETSV(padop->op_padix, sv);
5881     assert(sv);
5882     padop->op_next = (OP*)padop;
5883     padop->op_flags = (U8)flags;
5884     if (PL_opargs[type] & OA_RETSCALAR)
5885         scalar((OP*)padop);
5886     if (PL_opargs[type] & OA_TARGET)
5887         padop->op_targ = pad_alloc(type, SVs_PADTMP);
5888     return CHECKOP(type, padop);
5889 }
5890
5891 #endif /* USE_ITHREADS */
5892
5893 /*
5894 =for apidoc Am|OP *|newGVOP|I32 type|I32 flags|GV *gv
5895
5896 Constructs, checks, and returns an op of any type that involves an
5897 embedded reference to a GV.  I<type> is the opcode.  I<flags> gives the
5898 eight bits of C<op_flags>.  I<gv> identifies the GV that the op should
5899 reference; calling this function does not transfer ownership of any
5900 reference to it.
5901
5902 =cut
5903 */
5904
5905 OP *
5906 Perl_newGVOP(pTHX_ I32 type, I32 flags, GV *gv)
5907 {
5908     PERL_ARGS_ASSERT_NEWGVOP;
5909
5910 #ifdef USE_ITHREADS
5911     return newPADOP(type, flags, SvREFCNT_inc_simple_NN(gv));
5912 #else
5913     return newSVOP(type, flags, SvREFCNT_inc_simple_NN(gv));
5914 #endif
5915 }
5916
5917 /*
5918 =for apidoc Am|OP *|newPVOP|I32 type|I32 flags|char *pv
5919
5920 Constructs, checks, and returns an op of any type that involves an
5921 embedded C-level pointer (PV).  I<type> is the opcode.  I<flags> gives
5922 the eight bits of C<op_flags>.  I<pv> supplies the C-level pointer, which
5923 must have been allocated using C<PerlMemShared_malloc>; the memory will
5924 be freed when the op is destroyed.
5925
5926 =cut
5927 */
5928
5929 OP *
5930 Perl_newPVOP(pTHX_ I32 type, I32 flags, char *pv)
5931 {
5932     dVAR;
5933     const bool utf8 = cBOOL(flags & SVf_UTF8);
5934     PVOP *pvop;
5935
5936     flags &= ~SVf_UTF8;
5937
5938     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
5939         || type == OP_RUNCV || type == OP_CUSTOM
5940         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
5941
5942     NewOp(1101, pvop, 1, PVOP);
5943     CHANGE_TYPE(pvop, type);
5944     pvop->op_pv = pv;
5945     pvop->op_next = (OP*)pvop;
5946     pvop->op_flags = (U8)flags;
5947     pvop->op_private = utf8 ? OPpPV_IS_UTF8 : 0;
5948     if (PL_opargs[type] & OA_RETSCALAR)
5949         scalar((OP*)pvop);
5950     if (PL_opargs[type] & OA_TARGET)
5951         pvop->op_targ = pad_alloc(type, SVs_PADTMP);
5952     return CHECKOP(type, pvop);
5953 }
5954
5955 void
5956 Perl_package(pTHX_ OP *o)
5957 {
5958     SV *const sv = cSVOPo->op_sv;
5959
5960     PERL_ARGS_ASSERT_PACKAGE;
5961
5962     SAVEGENERICSV(PL_curstash);
5963     save_item(PL_curstname);
5964
5965     PL_curstash = (HV *)SvREFCNT_inc(gv_stashsv(sv, GV_ADD));
5966
5967     sv_setsv(PL_curstname, sv);
5968
5969     PL_hints |= HINT_BLOCK_SCOPE;
5970     PL_parser->copline = NOLINE;
5971
5972     op_free(o);
5973 }
5974
5975 void
5976 Perl_package_version( pTHX_ OP *v )
5977 {
5978     U32 savehints = PL_hints;
5979     PERL_ARGS_ASSERT_PACKAGE_VERSION;
5980     PL_hints &= ~HINT_STRICT_VARS;
5981     sv_setsv( GvSV(gv_fetchpvs("VERSION", GV_ADDMULTI, SVt_PV)), cSVOPx(v)->op_sv );
5982     PL_hints = savehints;
5983     op_free(v);
5984 }
5985
5986 void
5987 Perl_utilize(pTHX_ int aver, I32 floor, OP *version, OP *idop, OP *arg)
5988 {
5989     OP *pack;
5990     OP *imop;
5991     OP *veop;
5992     SV *use_version = NULL;
5993
5994     PERL_ARGS_ASSERT_UTILIZE;
5995
5996     if (idop->op_type != OP_CONST)
5997         Perl_croak(aTHX_ "Module name must be constant");
5998
5999     veop = NULL;
6000
6001     if (version) {
6002         SV * const vesv = ((SVOP*)version)->op_sv;
6003
6004         if (!arg && !SvNIOKp(vesv)) {
6005             arg = version;
6006         }
6007         else {
6008             OP *pack;
6009             SV *meth;
6010
6011             if (version->op_type != OP_CONST || !SvNIOKp(vesv))
6012                 Perl_croak(aTHX_ "Version number must be a constant number");
6013
6014             /* Make copy of idop so we don't free it twice */
6015             pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
6016
6017             /* Fake up a method call to VERSION */
6018             meth = newSVpvs_share("VERSION");
6019             veop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
6020                             op_append_elem(OP_LIST,
6021                                         op_prepend_elem(OP_LIST, pack, version),
6022                                         newMETHOP_named(OP_METHOD_NAMED, 0, meth)));
6023         }
6024     }
6025
6026     /* Fake up an import/unimport */
6027     if (arg && arg->op_type == OP_STUB) {
6028         imop = arg;             /* no import on explicit () */
6029     }
6030     else if (SvNIOKp(((SVOP*)idop)->op_sv)) {
6031         imop = NULL;            /* use 5.0; */
6032         if (aver)
6033             use_version = ((SVOP*)idop)->op_sv;
6034         else
6035             idop->op_private |= OPpCONST_NOVER;
6036     }
6037     else {
6038         SV *meth;
6039
6040         /* Make copy of idop so we don't free it twice */
6041         pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
6042
6043         /* Fake up a method call to import/unimport */
6044         meth = aver
6045             ? newSVpvs_share("import") : newSVpvs_share("unimport");
6046         imop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
6047                        op_append_elem(OP_LIST,
6048                                    op_prepend_elem(OP_LIST, pack, arg),
6049                                    newMETHOP_named(OP_METHOD_NAMED, 0, meth)
6050                        ));
6051     }
6052
6053     /* Fake up the BEGIN {}, which does its thing immediately. */
6054     newATTRSUB(floor,
6055         newSVOP(OP_CONST, 0, newSVpvs_share("BEGIN")),
6056         NULL,
6057         NULL,
6058         op_append_elem(OP_LINESEQ,
6059             op_append_elem(OP_LINESEQ,
6060                 newSTATEOP(0, NULL, newUNOP(OP_REQUIRE, 0, idop)),
6061                 newSTATEOP(0, NULL, veop)),
6062             newSTATEOP(0, NULL, imop) ));
6063
6064     if (use_version) {
6065         /* Enable the
6066          * feature bundle that corresponds to the required version. */
6067         use_version = sv_2mortal(new_version(use_version));
6068         S_enable_feature_bundle(aTHX_ use_version);
6069
6070         /* If a version >= 5.11.0 is requested, strictures are on by default! */
6071         if (vcmp(use_version,
6072                  sv_2mortal(upg_version(newSVnv(5.011000), FALSE))) >= 0) {
6073             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
6074                 PL_hints |= HINT_STRICT_REFS;
6075             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
6076                 PL_hints |= HINT_STRICT_SUBS;
6077             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
6078                 PL_hints |= HINT_STRICT_VARS;
6079         }
6080         /* otherwise they are off */
6081         else {
6082             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
6083                 PL_hints &= ~HINT_STRICT_REFS;
6084             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
6085                 PL_hints &= ~HINT_STRICT_SUBS;
6086             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
6087                 PL_hints &= ~HINT_STRICT_VARS;
6088         }
6089     }
6090
6091     /* The "did you use incorrect case?" warning used to be here.
6092      * The problem is that on case-insensitive filesystems one
6093      * might get false positives for "use" (and "require"):
6094      * "use Strict" or "require CARP" will work.  This causes
6095      * portability problems for the script: in case-strict
6096      * filesystems the script will stop working.
6097      *
6098      * The "incorrect case" warning checked whether "use Foo"
6099      * imported "Foo" to your namespace, but that is wrong, too:
6100      * there is no requirement nor promise in the language that
6101      * a Foo.pm should or would contain anything in package "Foo".
6102      *
6103      * There is very little Configure-wise that can be done, either:
6104      * the case-sensitivity of the build filesystem of Perl does not
6105      * help in guessing the case-sensitivity of the runtime environment.
6106      */
6107
6108     PL_hints |= HINT_BLOCK_SCOPE;
6109     PL_parser->copline = NOLINE;
6110     COP_SEQMAX_INC; /* Purely for B::*'s benefit */
6111 }
6112
6113 /*
6114 =head1 Embedding Functions
6115
6116 =for apidoc load_module
6117
6118 Loads the module whose name is pointed to by the string part of name.
6119 Note that the actual module name, not its filename, should be given.
6120 Eg, "Foo::Bar" instead of "Foo/Bar.pm".  flags can be any of
6121 PERL_LOADMOD_DENY, PERL_LOADMOD_NOIMPORT, or PERL_LOADMOD_IMPORT_OPS
6122 (or 0 for no flags).  ver, if specified
6123 and not NULL, provides version semantics
6124 similar to C<use Foo::Bar VERSION>.  The optional trailing SV*
6125 arguments can be used to specify arguments to the module's import()
6126 method, similar to C<use Foo::Bar VERSION LIST>.  They must be
6127 terminated with a final NULL pointer.  Note that this list can only
6128 be omitted when the PERL_LOADMOD_NOIMPORT flag has been used.
6129 Otherwise at least a single NULL pointer to designate the default
6130 import list is required.
6131
6132 The reference count for each specified C<SV*> parameter is decremented.
6133
6134 =cut */
6135
6136 void
6137 Perl_load_module(pTHX_ U32 flags, SV *name, SV *ver, ...)
6138 {
6139     va_list args;
6140
6141     PERL_ARGS_ASSERT_LOAD_MODULE;
6142
6143     va_start(args, ver);
6144     vload_module(flags, name, ver, &args);
6145     va_end(args);
6146 }
6147
6148 #ifdef PERL_IMPLICIT_CONTEXT
6149 void
6150 Perl_load_module_nocontext(U32 flags, SV *name, SV *ver, ...)
6151 {
6152     dTHX;
6153     va_list args;
6154     PERL_ARGS_ASSERT_LOAD_MODULE_NOCONTEXT;
6155     va_start(args, ver);
6156     vload_module(flags, name, ver, &args);
6157     va_end(args);
6158 }
6159 #endif
6160
6161 void
6162 Perl_vload_module(pTHX_ U32 flags, SV *name, SV *ver, va_list *args)
6163 {
6164     OP *veop, *imop;
6165     OP * const modname = newSVOP(OP_CONST, 0, name);
6166
6167     PERL_ARGS_ASSERT_VLOAD_MODULE;
6168
6169     modname->op_private |= OPpCONST_BARE;
6170     if (ver) {
6171         veop = newSVOP(OP_CONST, 0, ver);
6172     }
6173     else
6174         veop = NULL;
6175     if (flags & PERL_LOADMOD_NOIMPORT) {
6176         imop = sawparens(newNULLLIST());
6177     }
6178     else if (flags & PERL_LOADMOD_IMPORT_OPS) {
6179         imop = va_arg(*args, OP*);
6180     }
6181     else {
6182         SV *sv;
6183         imop = NULL;
6184         sv = va_arg(*args, SV*);
6185         while (sv) {
6186             imop = op_append_elem(OP_LIST, imop, newSVOP(OP_CONST, 0, sv));
6187             sv = va_arg(*args, SV*);
6188         }
6189     }
6190
6191     /* utilize() fakes up a BEGIN { require ..; import ... }, so make sure
6192      * that it has a PL_parser to play with while doing that, and also
6193      * that it doesn't mess with any existing parser, by creating a tmp
6194      * new parser with lex_start(). This won't actually be used for much,
6195      * since pp_require() will create another parser for the real work.
6196      * The ENTER/LEAVE pair protect callers from any side effects of use.  */
6197
6198     ENTER;
6199     SAVEVPTR(PL_curcop);
6200     lex_start(NULL, NULL, LEX_START_SAME_FILTER);
6201     utilize(!(flags & PERL_LOADMOD_DENY), start_subparse(FALSE, 0),
6202             veop, modname, imop);
6203     LEAVE;
6204 }
6205
6206 PERL_STATIC_INLINE OP *
6207 S_new_entersubop(pTHX_ GV *gv, OP *arg)
6208 {
6209     return newUNOP(OP_ENTERSUB, OPf_STACKED,
6210                    newLISTOP(OP_LIST, 0, arg,
6211                              newUNOP(OP_RV2CV, 0,
6212                                      newGVOP(OP_GV, 0, gv))));
6213 }
6214
6215 OP *
6216 Perl_dofile(pTHX_ OP *term, I32 force_builtin)
6217 {
6218     OP *doop;
6219     GV *gv;
6220
6221     PERL_ARGS_ASSERT_DOFILE;
6222
6223     if (!force_builtin && (gv = gv_override("do", 2))) {
6224         doop = S_new_entersubop(aTHX_ gv, term);
6225     }
6226     else {
6227         doop = newUNOP(OP_DOFILE, 0, scalar(term));
6228     }
6229     return doop;
6230 }
6231
6232 /*
6233 =head1 Optree construction
6234
6235 =for apidoc Am|OP *|newSLICEOP|I32 flags|OP *subscript|OP *listval
6236
6237 Constructs, checks, and returns an C<lslice> (list slice) op.  I<flags>
6238 gives the eight bits of C<op_flags>, except that C<OPf_KIDS> will
6239 be set automatically, and, shifted up eight bits, the eight bits of
6240 C<op_private>, except that the bit with value 1 or 2 is automatically
6241 set as required.  I<listval> and I<subscript> supply the parameters of
6242 the slice; they are consumed by this function and become part of the
6243 constructed op tree.
6244
6245 =cut
6246 */
6247
6248 OP *
6249 Perl_newSLICEOP(pTHX_ I32 flags, OP *subscript, OP *listval)
6250 {
6251     return newBINOP(OP_LSLICE, flags,
6252             list(force_list(subscript, 1)),
6253             list(force_list(listval,   1)) );
6254 }
6255
6256 #define ASSIGN_LIST   1
6257 #define ASSIGN_REF    2
6258
6259 STATIC I32
6260 S_assignment_type(pTHX_ const OP *o)
6261 {
6262     unsigned type;
6263     U8 flags;
6264     U8 ret;
6265
6266     if (!o)
6267         return TRUE;
6268
6269     if ((o->op_type == OP_NULL) && (o->op_flags & OPf_KIDS))
6270         o = cUNOPo->op_first;
6271
6272     flags = o->op_flags;
6273     type = o->op_type;
6274     if (type == OP_COND_EXPR) {
6275         OP * const sib = OpSIBLING(cLOGOPo->op_first);
6276         const I32 t = assignment_type(sib);
6277         const I32 f = assignment_type(OpSIBLING(sib));
6278
6279         if (t == ASSIGN_LIST && f == ASSIGN_LIST)
6280             return ASSIGN_LIST;
6281         if ((t == ASSIGN_LIST) ^ (f == ASSIGN_LIST))
6282             yyerror("Assignment to both a list and a scalar");
6283         return FALSE;
6284     }
6285
6286     if (type == OP_SREFGEN)
6287     {
6288         OP * const kid = cUNOPx(cUNOPo->op_first)->op_first;
6289         type = kid->op_type;
6290         flags |= kid->op_flags;
6291         if (!(flags & OPf_PARENS)
6292           && (kid->op_type == OP_RV2AV || kid->op_type == OP_PADAV ||
6293               kid->op_type == OP_RV2HV || kid->op_type == OP_PADHV ))
6294             return ASSIGN_REF;
6295         ret = ASSIGN_REF;
6296     }
6297     else ret = 0;
6298
6299     if (type == OP_LIST &&
6300         (flags & OPf_WANT) == OPf_WANT_SCALAR &&
6301         o->op_private & OPpLVAL_INTRO)
6302         return ret;
6303
6304     if (type == OP_LIST || flags & OPf_PARENS ||
6305         type == OP_RV2AV || type == OP_RV2HV ||
6306         type == OP_ASLICE || type == OP_HSLICE ||
6307         type == OP_KVASLICE || type == OP_KVHSLICE || type == OP_REFGEN)
6308         return TRUE;
6309
6310     if (type == OP_PADAV || type == OP_PADHV)
6311         return TRUE;
6312
6313     if (type == OP_RV2SV)
6314         return ret;
6315
6316     return ret;
6317 }
6318
6319 /*
6320   Helper function for newASSIGNOP to detect commonality between the
6321   lhs and the rhs.  (It is actually called very indirectly.  newASSIGNOP
6322   flags the op and the peephole optimizer calls this helper function
6323   if the flag is set.)  Marks all variables with PL_generation.  If it
6324   returns TRUE the assignment must be able to handle common variables.
6325
6326   PL_generation sorcery:
6327   An assignment like ($a,$b) = ($c,$d) is easier than
6328   ($a,$b) = ($c,$a), since there is no need for temporary vars.
6329   To detect whether there are common vars, the global var
6330   PL_generation is incremented for each assign op we compile.
6331   Then, while compiling the assign op, we run through all the
6332   variables on both sides of the assignment, setting a spare slot
6333   in each of them to PL_generation.  If any of them already have
6334   that value, we know we've got commonality.  Also, if the
6335   generation number is already set to PERL_INT_MAX, then
6336   the variable is involved in aliasing, so we also have
6337   potential commonality in that case.  We could use a
6338   single bit marker, but then we'd have to make 2 passes, first
6339   to clear the flag, then to test and set it.  And that
6340   wouldn't help with aliasing, either.  To find somewhere
6341   to store these values, evil chicanery is done with SvUVX().
6342 */
6343 PERL_STATIC_INLINE bool
6344 S_aassign_common_vars(pTHX_ OP* o)
6345 {
6346     OP *curop;
6347     for (curop = cUNOPo->op_first; curop; curop = OpSIBLING(curop)) {
6348         if (PL_opargs[curop->op_type] & OA_DANGEROUS) {
6349             if (curop->op_type == OP_GV || curop->op_type == OP_GVSV
6350              || curop->op_type == OP_AELEMFAST) {
6351                 GV *gv = cGVOPx_gv(curop);
6352                 if (gv == PL_defgv
6353                     || (int)GvASSIGN_GENERATION(gv) == PL_generation)
6354                     return TRUE;
6355                 GvASSIGN_GENERATION_set(gv, PL_generation);
6356             }
6357             else if (curop->op_type == OP_PADSV ||
6358                 curop->op_type == OP_PADAV ||
6359                 curop->op_type == OP_PADHV ||
6360                 curop->op_type == OP_AELEMFAST_LEX ||
6361                 curop->op_type == OP_PADANY)
6362                 {
6363                   padcheck:
6364                     if (PAD_COMPNAME_GEN(curop->op_targ)
6365                         == (STRLEN)PL_generation
6366                      || PAD_COMPNAME_GEN(curop->op_targ) == PERL_INT_MAX)
6367                         return TRUE;
6368                     PAD_COMPNAME_GEN_set(curop->op_targ, PL_generation);
6369
6370                 }
6371             else if (curop->op_type == OP_RV2CV)
6372                 return TRUE;
6373             else if (curop->op_type == OP_RV2SV ||
6374                 curop->op_type == OP_RV2AV ||
6375                 curop->op_type == OP_RV2HV ||
6376                 curop->op_type == OP_RV2GV) {
6377                 if (cUNOPx(curop)->op_first->op_type != OP_GV)  /* funny deref? */
6378                     return TRUE;
6379             }
6380             else if (curop->op_type == OP_PUSHRE) {
6381                 GV *const gv =
6382 #ifdef USE_ITHREADS
6383                     ((PMOP*)curop)->op_pmreplrootu.op_pmtargetoff
6384                         ? MUTABLE_GV(PAD_SVl(((PMOP*)curop)->op_pmreplrootu.op_pmtargetoff))
6385                         : NULL;
6386 #else
6387                     ((PMOP*)curop)->op_pmreplrootu.op_pmtargetgv;
6388 #endif
6389                 if (gv) {
6390                     if (gv == PL_defgv
6391                         || (int)GvASSIGN_GENERATION(gv) == PL_generation)
6392                         return TRUE;
6393                     GvASSIGN_GENERATION_set(gv, PL_generation);
6394                 }
6395                 else if (curop->op_targ)
6396                     goto padcheck;
6397             }
6398             else if (curop->op_type == OP_PADRANGE)
6399                 /* Ignore padrange; checking its siblings is sufficient. */
6400                 continue;
6401             else
6402                 return TRUE;
6403         }
6404         else if (PL_opargs[curop->op_type] & OA_TARGLEX
6405               && curop->op_private & OPpTARGET_MY)
6406             goto padcheck;
6407
6408         if (curop->op_flags & OPf_KIDS) {
6409             if (aassign_common_vars(curop))
6410                 return TRUE;
6411         }
6412     }
6413     return FALSE;
6414 }
6415
6416 /* This variant only handles lexical aliases.  It is called when
6417    newASSIGNOP decides that we don’t have any common vars, as lexical ali-
6418    ases trump that decision.  */
6419 PERL_STATIC_INLINE bool
6420 S_aassign_common_vars_aliases_only(pTHX_ OP *o)
6421 {
6422     OP *curop;
6423     for (curop = cUNOPo->op_first; curop; curop = OpSIBLING(curop)) {
6424         if ((curop->op_type == OP_PADSV ||
6425              curop->op_type == OP_PADAV ||
6426              curop->op_type == OP_PADHV ||
6427              curop->op_type == OP_AELEMFAST_LEX ||
6428              curop->op_type == OP_PADANY ||
6429              (  PL_opargs[curop->op_type] & OA_TARGLEX
6430              && curop->op_private & OPpTARGET_MY  ))
6431            && PAD_COMPNAME_GEN(curop->op_targ) == PERL_INT_MAX)
6432             return TRUE;
6433
6434         if (curop->op_type == OP_PUSHRE && curop->op_targ
6435          && PAD_COMPNAME_GEN(curop->op_targ) == PERL_INT_MAX)
6436             return TRUE;
6437
6438         if (curop->op_flags & OPf_KIDS) {
6439             if (S_aassign_common_vars_aliases_only(aTHX_ curop))
6440                 return TRUE;
6441         }
6442     }
6443     return FALSE;
6444 }
6445
6446 /*
6447 =for apidoc Am|OP *|newASSIGNOP|I32 flags|OP *left|I32 optype|OP *right
6448
6449 Constructs, checks, and returns an assignment op.  I<left> and I<right>
6450 supply the parameters of the assignment; they are consumed by this
6451 function and become part of the constructed op tree.
6452
6453 If I<optype> is C<OP_ANDASSIGN>, C<OP_ORASSIGN>, or C<OP_DORASSIGN>, then
6454 a suitable conditional optree is constructed.  If I<optype> is the opcode
6455 of a binary operator, such as C<OP_BIT_OR>, then an op is constructed that
6456 performs the binary operation and assigns the result to the left argument.
6457 Either way, if I<optype> is non-zero then I<flags> has no effect.
6458
6459 If I<optype> is zero, then a plain scalar or list assignment is
6460 constructed.  Which type of assignment it is is automatically determined.
6461 I<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
6462 will be set automatically, and, shifted up eight bits, the eight bits
6463 of C<op_private>, except that the bit with value 1 or 2 is automatically
6464 set as required.
6465
6466 =cut
6467 */
6468
6469 OP *
6470 Perl_newASSIGNOP(pTHX_ I32 flags, OP *left, I32 optype, OP *right)
6471 {
6472     OP *o;
6473     I32 assign_type;
6474
6475     if (optype) {
6476         if (optype == OP_ANDASSIGN || optype == OP_ORASSIGN || optype == OP_DORASSIGN) {
6477             return newLOGOP(optype, 0,
6478                 op_lvalue(scalar(left), optype),
6479                 newUNOP(OP_SASSIGN, 0, scalar(right)));
6480         }
6481         else {
6482             return newBINOP(optype, OPf_STACKED,
6483                 op_lvalue(scalar(left), optype), scalar(right));
6484         }
6485     }
6486
6487     if ((assign_type = assignment_type(left)) == ASSIGN_LIST) {
6488         static const char no_list_state[] = "Initialization of state variables"
6489             " in list context currently forbidden";
6490         OP *curop;
6491         bool maybe_common_vars = TRUE;
6492
6493         if (left->op_type == OP_ASLICE || left->op_type == OP_HSLICE)
6494             left->op_private &= ~ OPpSLICEWARNING;
6495
6496         PL_modcount = 0;
6497         left = op_lvalue(left, OP_AASSIGN);
6498         curop = list(force_list(left, 1));
6499         o = newBINOP(OP_AASSIGN, flags, list(force_list(right, 1)), curop);
6500         o->op_private = (U8)(0 | (flags >> 8));
6501
6502         if (OP_TYPE_IS_OR_WAS(left, OP_LIST))
6503         {
6504             OP* lop = ((LISTOP*)left)->op_first;
6505             maybe_common_vars = FALSE;
6506             while (lop) {
6507                 if (lop->op_type == OP_PADSV ||
6508                     lop->op_type == OP_PADAV ||
6509                     lop->op_type == OP_PADHV ||
6510                     lop->op_type == OP_PADANY) {
6511                     if (!(lop->op_private & OPpLVAL_INTRO))
6512                         maybe_common_vars = TRUE;
6513
6514                     if (lop->op_private & OPpPAD_STATE) {
6515                         if (left->op_private & OPpLVAL_INTRO) {
6516                             /* Each variable in state($a, $b, $c) = ... */
6517                         }
6518                         else {
6519                             /* Each state variable in
6520                                (state $a, my $b, our $c, $d, undef) = ... */
6521                         }
6522                         yyerror(no_list_state);
6523                     } else {
6524                         /* Each my variable in
6525                            (state $a, my $b, our $c, $d, undef) = ... */
6526                     }
6527                 } else if (lop->op_type == OP_UNDEF ||
6528                            OP_TYPE_IS_OR_WAS(lop, OP_PUSHMARK)) {
6529                     /* undef may be interesting in
6530                        (state $a, undef, state $c) */
6531                 } else {
6532                     /* Other ops in the list. */
6533                     maybe_common_vars = TRUE;
6534                 }
6535                 lop = OpSIBLING(lop);
6536             }
6537         }
6538         else if ((left->op_private & OPpLVAL_INTRO)
6539                 && (   left->op_type == OP_PADSV
6540                     || left->op_type == OP_PADAV
6541                     || left->op_type == OP_PADHV
6542                     || left->op_type == OP_PADANY))
6543         {
6544             if (left->op_type == OP_PADSV) maybe_common_vars = FALSE;
6545             if (left->op_private & OPpPAD_STATE) {
6546                 /* All single variable list context state assignments, hence
6547                    state ($a) = ...
6548                    (state $a) = ...
6549                    state @a = ...
6550                    state (@a) = ...
6551                    (state @a) = ...
6552                    state %a = ...
6553                    state (%a) = ...
6554                    (state %a) = ...
6555                 */
6556                 yyerror(no_list_state);
6557             }
6558         }
6559
6560         if (maybe_common_vars) {
6561                 /* The peephole optimizer will do the full check and pos-
6562                    sibly turn this off.  */
6563                 o->op_private |= OPpASSIGN_COMMON;
6564         }
6565
6566         if (right && right->op_type == OP_SPLIT
6567          && !(right->op_flags & OPf_STACKED)) {
6568             OP* tmpop = ((LISTOP*)right)->op_first;
6569             PMOP * const pm = (PMOP*)tmpop;
6570             assert (tmpop && (tmpop->op_type == OP_PUSHRE));
6571             if (
6572 #ifdef USE_ITHREADS
6573                     !pm->op_pmreplrootu.op_pmtargetoff
6574 #else
6575                     !pm->op_pmreplrootu.op_pmtargetgv
6576 #endif
6577                  && !pm->op_targ
6578                 ) {
6579                     if (!(left->op_private & OPpLVAL_INTRO) &&
6580                         ( (left->op_type == OP_RV2AV &&
6581                           (tmpop=((UNOP*)left)->op_first)->op_type==OP_GV)
6582                         || left->op_type == OP_PADAV )
6583                         ) {
6584                         if (tmpop != (OP *)pm) {
6585 #ifdef USE_ITHREADS
6586                           pm->op_pmreplrootu.op_pmtargetoff
6587                             = cPADOPx(tmpop)->op_padix;
6588                           cPADOPx(tmpop)->op_padix = 0; /* steal it */
6589 #else
6590                           pm->op_pmreplrootu.op_pmtargetgv
6591                             = MUTABLE_GV(cSVOPx(tmpop)->op_sv);
6592                           cSVOPx(tmpop)->op_sv = NULL;  /* steal it */
6593 #endif
6594                           right->op_private |=
6595                             left->op_private & OPpOUR_INTRO;
6596                         }
6597                         else {
6598                             pm->op_targ = left->op_targ;
6599                             left->op_targ = 0; /* filch it */
6600                         }
6601                       detach_split:
6602                         tmpop = cUNOPo->op_first;       /* to list (nulled) */
6603                         tmpop = ((UNOP*)tmpop)->op_first; /* to pushmark */
6604                         /* detach rest of siblings from o subtree,
6605                          * and free subtree */
6606                         op_sibling_splice(cUNOPo->op_first, tmpop, -1, NULL);
6607                         op_free(o);                     /* blow off assign */
6608                         right->op_flags &= ~OPf_WANT;
6609                                 /* "I don't know and I don't care." */
6610                         return right;
6611                     }
6612                     else if (left->op_type == OP_RV2AV
6613                           || left->op_type == OP_PADAV)
6614                     {
6615                         /* Detach the array.  */
6616 #ifdef DEBUGGING
6617                         OP * const ary =
6618 #endif
6619                         op_sibling_splice(cBINOPo->op_last,
6620                                           cUNOPx(cBINOPo->op_last)
6621                                                 ->op_first, 1, NULL);
6622                         assert(ary == left);
6623                         /* Attach it to the split.  */
6624                         op_sibling_splice(right, cLISTOPx(right)->op_last,
6625                                           0, left);
6626                         right->op_flags |= OPf_STACKED;
6627                         /* Detach split and expunge aassign as above.  */
6628                         goto detach_split;
6629                     }
6630                     else if (PL_modcount < RETURN_UNLIMITED_NUMBER &&
6631                             ((LISTOP*)right)->op_last->op_type == OP_CONST)
6632                     {
6633                         SV ** const svp =
6634                             &((SVOP*)((LISTOP*)right)->op_last)->op_sv;
6635                         SV * const sv = *svp;
6636                         if (SvIOK(sv) && SvIVX(sv) == 0)
6637                         {
6638                           if (right->op_private & OPpSPLIT_IMPLIM) {
6639                             /* our own SV, created in ck_split */
6640                             SvREADONLY_off(sv);
6641                             sv_setiv(sv, PL_modcount+1);
6642                           }
6643                           else {
6644                             /* SV may belong to someone else */
6645                             SvREFCNT_dec(sv);
6646                             *svp = newSViv(PL_modcount+1);
6647                           }
6648                         }
6649                     }
6650             }
6651         }
6652         return o;
6653     }
6654     if (assign_type == ASSIGN_REF)
6655         return newBINOP(OP_REFASSIGN, flags, scalar(right), left);
6656     if (!right)
6657         right = newOP(OP_UNDEF, 0);
6658     if (right->op_type == OP_READLINE) {
6659         right->op_flags |= OPf_STACKED;
6660         return newBINOP(OP_NULL, flags, op_lvalue(scalar(left), OP_SASSIGN),
6661                 scalar(right));
6662     }
6663     else {
6664         o = newBINOP(OP_SASSIGN, flags,
6665             scalar(right), op_lvalue(scalar(left), OP_SASSIGN) );
6666     }
6667     return o;
6668 }
6669
6670 /*
6671 =for apidoc Am|OP *|newSTATEOP|I32 flags|char *label|OP *o
6672
6673 Constructs a state op (COP).  The state op is normally a C<nextstate> op,
6674 but will be a C<dbstate> op if debugging is enabled for currently-compiled
6675 code.  The state op is populated from C<PL_curcop> (or C<PL_compiling>).
6676 If I<label> is non-null, it supplies the name of a label to attach to
6677 the state op; this function takes ownership of the memory pointed at by
6678 I<label>, and will free it.  I<flags> gives the eight bits of C<op_flags>
6679 for the state op.
6680
6681 If I<o> is null, the state op is returned.  Otherwise the state op is
6682 combined with I<o> into a C<lineseq> list op, which is returned.  I<o>
6683 is consumed by this function and becomes part of the returned op tree.
6684
6685 =cut
6686 */
6687
6688 OP *
6689 Perl_newSTATEOP(pTHX_ I32 flags, char *label, OP *o)
6690 {
6691     dVAR;
6692     const U32 seq = intro_my();
6693     const U32 utf8 = flags & SVf_UTF8;
6694     COP *cop;
6695
6696     PL_parser->parsed_sub = 0;
6697
6698     flags &= ~SVf_UTF8;
6699
6700     NewOp(1101, cop, 1, COP);
6701     if (PERLDB_LINE && CopLINE(PL_curcop) && PL_curstash != PL_debstash) {
6702         CHANGE_TYPE(cop, OP_DBSTATE);
6703     }
6704     else {
6705         CHANGE_TYPE(cop, OP_NEXTSTATE);
6706     }
6707     cop->op_flags = (U8)flags;
6708     CopHINTS_set(cop, PL_hints);
6709 #ifdef VMS
6710     if (VMSISH_HUSHED) cop->op_private |= OPpHUSH_VMSISH;
6711 #endif
6712     cop->op_next = (OP*)cop;
6713
6714     cop->cop_seq = seq;
6715     cop->cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
6716     CopHINTHASH_set(cop, cophh_copy(CopHINTHASH_get(PL_curcop)));
6717     if (label) {
6718         Perl_cop_store_label(aTHX_ cop, label, strlen(label), utf8);
6719
6720         PL_hints |= HINT_BLOCK_SCOPE;
6721         /* It seems that we need to defer freeing this pointer, as other parts
6722            of the grammar end up wanting to copy it after this op has been
6723            created. */
6724         SAVEFREEPV(label);
6725     }
6726
6727     if (PL_parser->preambling != NOLINE) {
6728         CopLINE_set(cop, PL_parser->preambling);
6729         PL_parser->copline = NOLINE;
6730     }
6731     else if (PL_parser->copline == NOLINE)
6732         CopLINE_set(cop, CopLINE(PL_curcop));
6733     else {
6734         CopLINE_set(cop, PL_parser->copline);
6735         PL_parser->copline = NOLINE;
6736     }
6737 #ifdef USE_ITHREADS
6738     CopFILE_set(cop, CopFILE(PL_curcop));       /* XXX share in a pvtable? */
6739 #else
6740     CopFILEGV_set(cop, CopFILEGV(PL_curcop));
6741 #endif
6742     CopSTASH_set(cop, PL_curstash);
6743
6744     if (cop->op_type == OP_DBSTATE) {
6745         /* this line can have a breakpoint - store the cop in IV */
6746         AV *av = CopFILEAVx(PL_curcop);
6747         if (av) {
6748             SV * const * const svp = av_fetch(av, CopLINE(cop), FALSE);
6749             if (svp && *svp != &PL_sv_undef ) {
6750                 (void)SvIOK_on(*svp);
6751                 SvIV_set(*svp, PTR2IV(cop));
6752             }
6753         }
6754     }
6755
6756     if (flags & OPf_SPECIAL)
6757         op_null((OP*)cop);
6758     return op_prepend_elem(OP_LINESEQ, (OP*)cop, o);
6759 }
6760
6761 /*
6762 =for apidoc Am|OP *|newLOGOP|I32 type|I32 flags|OP *first|OP *other
6763
6764 Constructs, checks, and returns a logical (flow control) op.  I<type>
6765 is the opcode.  I<flags> gives the eight bits of C<op_flags>, except
6766 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
6767 the eight bits of C<op_private>, except that the bit with value 1 is
6768 automatically set.  I<first> supplies the expression controlling the
6769 flow, and I<other> supplies the side (alternate) chain of ops; they are
6770 consumed by this function and become part of the constructed op tree.
6771
6772 =cut
6773 */
6774
6775 OP *
6776 Perl_newLOGOP(pTHX_ I32 type, I32 flags, OP *first, OP *other)
6777 {
6778     PERL_ARGS_ASSERT_NEWLOGOP;
6779
6780     return new_logop(type, flags, &first, &other);
6781 }
6782
6783 STATIC OP *
6784 S_search_const(pTHX_ OP *o)
6785 {
6786     PERL_ARGS_ASSERT_SEARCH_CONST;
6787
6788     switch (o->op_type) {
6789         case OP_CONST:
6790             return o;
6791         case OP_NULL:
6792             if (o->op_flags & OPf_KIDS)
6793                 return search_const(cUNOPo->op_first);
6794             break;
6795         case OP_LEAVE:
6796         case OP_SCOPE:
6797         case OP_LINESEQ:
6798         {
6799             OP *kid;
6800             if (!(o->op_flags & OPf_KIDS))
6801                 return NULL;
6802             kid = cLISTOPo->op_first;
6803             do {
6804                 switch (kid->op_type) {
6805                     case OP_ENTER:
6806                     case OP_NULL:
6807                     case OP_NEXTSTATE:
6808                         kid = OpSIBLING(kid);
6809                         break;
6810                     default:
6811                         if (kid != cLISTOPo->op_last)
6812                             return NULL;
6813                         goto last;
6814                 }
6815             } while (kid);
6816             if (!kid)
6817                 kid = cLISTOPo->op_last;
6818           last:
6819             return search_const(kid);
6820         }
6821     }
6822
6823     return NULL;
6824 }
6825
6826 STATIC OP *
6827 S_new_logop(pTHX_ I32 type, I32 flags, OP** firstp, OP** otherp)
6828 {
6829     dVAR;
6830     LOGOP *logop;
6831     OP *o;
6832     OP *first;
6833     OP *other;
6834     OP *cstop = NULL;
6835     int prepend_not = 0;
6836
6837     PERL_ARGS_ASSERT_NEW_LOGOP;
6838
6839     first = *firstp;
6840     other = *otherp;
6841
6842     /* [perl #59802]: Warn about things like "return $a or $b", which
6843        is parsed as "(return $a) or $b" rather than "return ($a or
6844        $b)".  NB: This also applies to xor, which is why we do it
6845        here.
6846      */
6847     switch (first->op_type) {
6848     case OP_NEXT:
6849     case OP_LAST:
6850     case OP_REDO:
6851         /* XXX: Perhaps we should emit a stronger warning for these.
6852            Even with the high-precedence operator they don't seem to do
6853            anything sensible.
6854
6855            But until we do, fall through here.
6856          */
6857     case OP_RETURN:
6858     case OP_EXIT:
6859     case OP_DIE:
6860     case OP_GOTO:
6861         /* XXX: Currently we allow people to "shoot themselves in the
6862            foot" by explicitly writing "(return $a) or $b".
6863
6864            Warn unless we are looking at the result from folding or if
6865            the programmer explicitly grouped the operators like this.
6866            The former can occur with e.g.
6867
6868                 use constant FEATURE => ( $] >= ... );
6869                 sub { not FEATURE and return or do_stuff(); }
6870          */
6871         if (!first->op_folded && !(first->op_flags & OPf_PARENS))
6872             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
6873                            "Possible precedence issue with control flow operator");
6874         /* XXX: Should we optimze this to "return $a;" (i.e. remove
6875            the "or $b" part)?
6876         */
6877         break;
6878     }
6879
6880     if (type == OP_XOR)         /* Not short circuit, but here by precedence. */
6881         return newBINOP(type, flags, scalar(first), scalar(other));
6882
6883     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOGOP
6884         || type == OP_CUSTOM);
6885
6886     scalarboolean(first);
6887     /* optimize AND and OR ops that have NOTs as children */
6888     if (first->op_type == OP_NOT
6889         && (first->op_flags & OPf_KIDS)
6890         && ((first->op_flags & OPf_SPECIAL) /* unless ($x) { } */
6891             || (other->op_type == OP_NOT))  /* if (!$x && !$y) { } */
6892         ) {
6893         if (type == OP_AND || type == OP_OR) {
6894             if (type == OP_AND)
6895                 type = OP_OR;
6896             else
6897                 type = OP_AND;
6898             op_null(first);
6899             if (other->op_type == OP_NOT) { /* !a AND|OR !b => !(a OR|AND b) */
6900                 op_null(other);
6901                 prepend_not = 1; /* prepend a NOT op later */
6902             }
6903         }
6904     }
6905     /* search for a constant op that could let us fold the test */
6906     if ((cstop = search_const(first))) {
6907         if (cstop->op_private & OPpCONST_STRICT)
6908             no_bareword_allowed(cstop);
6909         else if ((cstop->op_private & OPpCONST_BARE))
6910                 Perl_ck_warner(aTHX_ packWARN(WARN_BAREWORD), "Bareword found in conditional");
6911         if ((type == OP_AND &&  SvTRUE(((SVOP*)cstop)->op_sv)) ||
6912             (type == OP_OR  && !SvTRUE(((SVOP*)cstop)->op_sv)) ||
6913             (type == OP_DOR && !SvOK(((SVOP*)cstop)->op_sv))) {
6914             *firstp = NULL;
6915             if (other->op_type == OP_CONST)
6916                 other->op_private |= OPpCONST_SHORTCIRCUIT;
6917             op_free(first);
6918             if (other->op_type == OP_LEAVE)
6919                 other = newUNOP(OP_NULL, OPf_SPECIAL, other);
6920             else if (other->op_type == OP_MATCH
6921                   || other->op_type == OP_SUBST
6922                   || other->op_type == OP_TRANSR
6923                   || other->op_type == OP_TRANS)
6924                 /* Mark the op as being unbindable with =~ */
6925                 other->op_flags |= OPf_SPECIAL;
6926
6927             other->op_folded = 1;
6928             return other;
6929         }
6930         else {
6931             /* check for C<my $x if 0>, or C<my($x,$y) if 0> */
6932             const OP *o2 = other;
6933             if ( ! (o2->op_type == OP_LIST
6934                     && (( o2 = cUNOPx(o2)->op_first))
6935                     && o2->op_type == OP_PUSHMARK
6936                     && (( o2 = OpSIBLING(o2))) )
6937             )
6938                 o2 = other;
6939             if ((o2->op_type == OP_PADSV || o2->op_type == OP_PADAV
6940                         || o2->op_type == OP_PADHV)
6941                 && o2->op_private & OPpLVAL_INTRO
6942                 && !(o2->op_private & OPpPAD_STATE))
6943             {
6944                 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED),
6945                                  "Deprecated use of my() in false conditional");
6946             }
6947
6948             *otherp = NULL;
6949             if (cstop->op_type == OP_CONST)
6950                 cstop->op_private |= OPpCONST_SHORTCIRCUIT;
6951                 op_free(other);
6952             return first;
6953         }
6954     }
6955     else if ((first->op_flags & OPf_KIDS) && type != OP_DOR
6956         && ckWARN(WARN_MISC)) /* [#24076] Don't warn for <FH> err FOO. */
6957     {
6958         const OP * const k1 = ((UNOP*)first)->op_first;
6959         const OP * const k2 = OpSIBLING(k1);
6960         OPCODE warnop = 0;
6961         switch (first->op_type)
6962         {
6963         case OP_NULL:
6964             if (k2 && k2->op_type == OP_READLINE
6965                   && (k2->op_flags & OPf_STACKED)
6966                   && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
6967             {
6968                 warnop = k2->op_type;
6969             }
6970             break;
6971
6972         case OP_SASSIGN:
6973             if (k1->op_type == OP_READDIR
6974                   || k1->op_type == OP_GLOB
6975                   || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
6976                  || k1->op_type == OP_EACH
6977                  || k1->op_type == OP_AEACH)
6978             {
6979                 warnop = ((k1->op_type == OP_NULL)
6980                           ? (OPCODE)k1->op_targ : k1->op_type);
6981             }
6982             break;
6983         }
6984         if (warnop) {
6985             const line_t oldline = CopLINE(PL_curcop);
6986             /* This ensures that warnings are reported at the first line
6987                of the construction, not the last.  */
6988             CopLINE_set(PL_curcop, PL_parser->copline);
6989             Perl_warner(aTHX_ packWARN(WARN_MISC),
6990                  "Value of %s%s can be \"0\"; test with defined()",
6991                  PL_op_desc[warnop],
6992                  ((warnop == OP_READLINE || warnop == OP_GLOB)
6993                   ? " construct" : "() operator"));
6994             CopLINE_set(PL_curcop, oldline);
6995         }
6996     }
6997
6998     if (!other)
6999         return first;
7000
7001     if (type == OP_ANDASSIGN || type == OP_ORASSIGN || type == OP_DORASSIGN)
7002         other->op_private |= OPpASSIGN_BACKWARDS;  /* other is an OP_SASSIGN */
7003
7004     logop = S_alloc_LOGOP(aTHX_ type, first, LINKLIST(other));
7005     logop->op_flags |= (U8)flags;
7006     logop->op_private = (U8)(1 | (flags >> 8));
7007
7008     /* establish postfix order */
7009     logop->op_next = LINKLIST(first);
7010     first->op_next = (OP*)logop;
7011     assert(!OpHAS_SIBLING(first));
7012     op_sibling_splice((OP*)logop, first, 0, other);
7013
7014     CHECKOP(type,logop);
7015
7016     o = newUNOP(prepend_not ? OP_NOT : OP_NULL,
7017                 PL_opargs[type] & OA_RETSCALAR ? OPf_WANT_SCALAR : 0,
7018                 (OP*)logop);
7019     other->op_next = o;
7020
7021     return o;
7022 }
7023
7024 /*
7025 =for apidoc Am|OP *|newCONDOP|I32 flags|OP *first|OP *trueop|OP *falseop
7026
7027 Constructs, checks, and returns a conditional-expression (C<cond_expr>)
7028 op.  I<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
7029 will be set automatically, and, shifted up eight bits, the eight bits of
7030 C<op_private>, except that the bit with value 1 is automatically set.
7031 I<first> supplies the expression selecting between the two branches,
7032 and I<trueop> and I<falseop> supply the branches; they are consumed by
7033 this function and become part of the constructed op tree.
7034
7035 =cut
7036 */
7037
7038 OP *
7039 Perl_newCONDOP(pTHX_ I32 flags, OP *first, OP *trueop, OP *falseop)
7040 {
7041     dVAR;
7042     LOGOP *logop;
7043     OP *start;
7044     OP *o;
7045     OP *cstop;
7046
7047     PERL_ARGS_ASSERT_NEWCONDOP;
7048
7049     if (!falseop)
7050         return newLOGOP(OP_AND, 0, first, trueop);
7051     if (!trueop)
7052         return newLOGOP(OP_OR, 0, first, falseop);
7053
7054     scalarboolean(first);
7055     if ((cstop = search_const(first))) {
7056         /* Left or right arm of the conditional?  */
7057         const bool left = SvTRUE(((SVOP*)cstop)->op_sv);
7058         OP *live = left ? trueop : falseop;
7059         OP *const dead = left ? falseop : trueop;
7060         if (cstop->op_private & OPpCONST_BARE &&
7061             cstop->op_private & OPpCONST_STRICT) {
7062             no_bareword_allowed(cstop);
7063         }
7064         op_free(first);
7065         op_free(dead);
7066         if (live->op_type == OP_LEAVE)
7067             live = newUNOP(OP_NULL, OPf_SPECIAL, live);
7068         else if (live->op_type == OP_MATCH || live->op_type == OP_SUBST
7069               || live->op_type == OP_TRANS || live->op_type == OP_TRANSR)
7070             /* Mark the op as being unbindable with =~ */
7071             live->op_flags |= OPf_SPECIAL;
7072         live->op_folded = 1;
7073         return live;
7074     }
7075     logop = S_alloc_LOGOP(aTHX_ OP_COND_EXPR, first, LINKLIST(trueop));
7076     logop->op_flags |= (U8)flags;
7077     logop->op_private = (U8)(1 | (flags >> 8));
7078     logop->op_next = LINKLIST(falseop);
7079
7080     CHECKOP(OP_COND_EXPR, /* that's logop->op_type */
7081             logop);
7082
7083     /* establish postfix order */
7084     start = LINKLIST(first);
7085     first->op_next = (OP*)logop;
7086
7087     /* make first, trueop, falseop siblings */
7088     op_sibling_splice((OP*)logop, first,  0, trueop);
7089     op_sibling_splice((OP*)logop, trueop, 0, falseop);
7090
7091     o = newUNOP(OP_NULL, 0, (OP*)logop);
7092
7093     trueop->op_next = falseop->op_next = o;
7094
7095     o->op_next = start;
7096     return o;
7097 }
7098
7099 /*
7100 =for apidoc Am|OP *|newRANGE|I32 flags|OP *left|OP *right
7101
7102 Constructs and returns a C<range> op, with subordinate C<flip> and
7103 C<flop> ops.  I<flags> gives the eight bits of C<op_flags> for the
7104 C<flip> op and, shifted up eight bits, the eight bits of C<op_private>
7105 for both the C<flip> and C<range> ops, except that the bit with value
7106 1 is automatically set.  I<left> and I<right> supply the expressions
7107 controlling the endpoints of the range; they are consumed by this function
7108 and become part of the constructed op tree.
7109
7110 =cut
7111 */
7112
7113 OP *
7114 Perl_newRANGE(pTHX_ I32 flags, OP *left, OP *right)
7115 {
7116     LOGOP *range;
7117     OP *flip;
7118     OP *flop;
7119     OP *leftstart;
7120     OP *o;
7121
7122     PERL_ARGS_ASSERT_NEWRANGE;
7123
7124     range = S_alloc_LOGOP(aTHX_ OP_RANGE, left, LINKLIST(right));
7125     range->op_flags = OPf_KIDS;
7126     leftstart = LINKLIST(left);
7127     range->op_private = (U8)(1 | (flags >> 8));
7128
7129     /* make left and right siblings */
7130     op_sibling_splice((OP*)range, left, 0, right);
7131
7132     range->op_next = (OP*)range;
7133     flip = newUNOP(OP_FLIP, flags, (OP*)range);
7134     flop = newUNOP(OP_FLOP, 0, flip);
7135     o = newUNOP(OP_NULL, 0, flop);
7136     LINKLIST(flop);
7137     range->op_next = leftstart;
7138
7139     left->op_next = flip;
7140     right->op_next = flop;
7141
7142     range->op_targ =
7143         pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);
7144     sv_upgrade(PAD_SV(range->op_targ), SVt_PVNV);
7145     flip->op_targ =
7146         pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);;
7147     sv_upgrade(PAD_SV(flip->op_targ), SVt_PVNV);
7148     SvPADTMP_on(PAD_SV(flip->op_targ));
7149
7150     flip->op_private =  left->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
7151     flop->op_private = right->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
7152
7153     /* check barewords before they might be optimized aways */
7154     if (flip->op_private && cSVOPx(left)->op_private & OPpCONST_STRICT)
7155         no_bareword_allowed(left);
7156     if (flop->op_private && cSVOPx(right)->op_private & OPpCONST_STRICT)
7157         no_bareword_allowed(right);
7158
7159     flip->op_next = o;
7160     if (!flip->op_private || !flop->op_private)
7161         LINKLIST(o);            /* blow off optimizer unless constant */
7162
7163     return o;
7164 }
7165
7166 /*
7167 =for apidoc Am|OP *|newLOOPOP|I32 flags|I32 debuggable|OP *expr|OP *block
7168
7169 Constructs, checks, and returns an op tree expressing a loop.  This is
7170 only a loop in the control flow through the op tree; it does not have
7171 the heavyweight loop structure that allows exiting the loop by C<last>
7172 and suchlike.  I<flags> gives the eight bits of C<op_flags> for the
7173 top-level op, except that some bits will be set automatically as required.
7174 I<expr> supplies the expression controlling loop iteration, and I<block>
7175 supplies the body of the loop; they are consumed by this function and
7176 become part of the constructed op tree.  I<debuggable> is currently
7177 unused and should always be 1.
7178
7179 =cut
7180 */
7181
7182 OP *
7183 Perl_newLOOPOP(pTHX_ I32 flags, I32 debuggable, OP *expr, OP *block)
7184 {
7185     OP* listop;
7186     OP* o;
7187     const bool once = block && block->op_flags & OPf_SPECIAL &&
7188                       block->op_type == OP_NULL;
7189
7190     PERL_UNUSED_ARG(debuggable);
7191
7192     if (expr) {
7193         if (once && (
7194               (expr->op_type == OP_CONST && !SvTRUE(((SVOP*)expr)->op_sv))
7195            || (  expr->op_type == OP_NOT
7196               && cUNOPx(expr)->op_first->op_type == OP_CONST
7197               && SvTRUE(cSVOPx_sv(cUNOPx(expr)->op_first))
7198               )
7199            ))
7200             /* Return the block now, so that S_new_logop does not try to
7201                fold it away. */
7202             return block;       /* do {} while 0 does once */
7203         if (expr->op_type == OP_READLINE
7204             || expr->op_type == OP_READDIR
7205             || expr->op_type == OP_GLOB
7206             || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
7207             || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
7208             expr = newUNOP(OP_DEFINED, 0,
7209                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
7210         } else if (expr->op_flags & OPf_KIDS) {
7211             const OP * const k1 = ((UNOP*)expr)->op_first;
7212             const OP * const k2 = k1 ? OpSIBLING(k1) : NULL;
7213             switch (expr->op_type) {
7214               case OP_NULL:
7215                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
7216                       && (k2->op_flags & OPf_STACKED)
7217                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
7218                     expr = newUNOP(OP_DEFINED, 0, expr);
7219                 break;
7220
7221               case OP_SASSIGN:
7222                 if (k1 && (k1->op_type == OP_READDIR
7223                       || k1->op_type == OP_GLOB
7224                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
7225                      || k1->op_type == OP_EACH
7226                      || k1->op_type == OP_AEACH))
7227                     expr = newUNOP(OP_DEFINED, 0, expr);
7228                 break;
7229             }
7230         }
7231     }
7232
7233     /* if block is null, the next op_append_elem() would put UNSTACK, a scalar
7234      * op, in listop. This is wrong. [perl #27024] */
7235     if (!block)
7236         block = newOP(OP_NULL, 0);
7237     listop = op_append_elem(OP_LINESEQ, block, newOP(OP_UNSTACK, 0));
7238     o = new_logop(OP_AND, 0, &expr, &listop);
7239
7240     if (once) {
7241         ASSUME(listop);
7242     }
7243
7244     if (listop)
7245         ((LISTOP*)listop)->op_last->op_next = LINKLIST(o);
7246
7247     if (once && o != listop)
7248     {
7249         assert(cUNOPo->op_first->op_type == OP_AND
7250             || cUNOPo->op_first->op_type == OP_OR);
7251         o->op_next = ((LOGOP*)cUNOPo->op_first)->op_other;
7252     }
7253
7254     if (o == listop)
7255         o = newUNOP(OP_NULL, 0, o);     /* or do {} while 1 loses outer block */
7256
7257     o->op_flags |= flags;
7258     o = op_scope(o);
7259     o->op_flags |= OPf_SPECIAL; /* suppress POPBLOCK curpm restoration*/
7260     return o;
7261 }
7262
7263 /*
7264 =for apidoc Am|OP *|newWHILEOP|I32 flags|I32 debuggable|LOOP *loop|OP *expr|OP *block|OP *cont|I32 has_my
7265
7266 Constructs, checks, and returns an op tree expressing a C<while> loop.
7267 This is a heavyweight loop, with structure that allows exiting the loop
7268 by C<last> and suchlike.
7269
7270 I<loop> is an optional preconstructed C<enterloop> op to use in the
7271 loop; if it is null then a suitable op will be constructed automatically.
7272 I<expr> supplies the loop's controlling expression.  I<block> supplies the
7273 main body of the loop, and I<cont> optionally supplies a C<continue> block
7274 that operates as a second half of the body.  All of these optree inputs
7275 are consumed by this function and become part of the constructed op tree.
7276
7277 I<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
7278 op and, shifted up eight bits, the eight bits of C<op_private> for
7279 the C<leaveloop> op, except that (in both cases) some bits will be set
7280 automatically.  I<debuggable> is currently unused and should always be 1.
7281 I<has_my> can be supplied as true to force the
7282 loop body to be enclosed in its own scope.
7283
7284 =cut
7285 */
7286
7287 OP *
7288 Perl_newWHILEOP(pTHX_ I32 flags, I32 debuggable, LOOP *loop,
7289         OP *expr, OP *block, OP *cont, I32 has_my)
7290 {
7291     dVAR;
7292     OP *redo;
7293     OP *next = NULL;
7294     OP *listop;
7295     OP *o;
7296     U8 loopflags = 0;
7297
7298     PERL_UNUSED_ARG(debuggable);
7299
7300     if (expr) {
7301         if (expr->op_type == OP_READLINE
7302          || expr->op_type == OP_READDIR
7303          || expr->op_type == OP_GLOB
7304          || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
7305                      || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
7306             expr = newUNOP(OP_DEFINED, 0,
7307                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
7308         } else if (expr->op_flags & OPf_KIDS) {
7309             const OP * const k1 = ((UNOP*)expr)->op_first;
7310             const OP * const k2 = (k1) ? OpSIBLING(k1) : NULL;
7311             switch (expr->op_type) {
7312               case OP_NULL:
7313                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
7314                       && (k2->op_flags & OPf_STACKED)
7315                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
7316                     expr = newUNOP(OP_DEFINED, 0, expr);
7317                 break;
7318
7319               case OP_SASSIGN:
7320                 if (k1 && (k1->op_type == OP_READDIR
7321                       || k1->op_type == OP_GLOB
7322                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
7323                      || k1->op_type == OP_EACH
7324                      || k1->op_type == OP_AEACH))
7325                     expr = newUNOP(OP_DEFINED, 0, expr);
7326                 break;
7327             }
7328         }
7329     }
7330
7331     if (!block)
7332         block = newOP(OP_NULL, 0);
7333     else if (cont || has_my) {
7334         block = op_scope(block);
7335     }
7336
7337     if (cont) {
7338         next = LINKLIST(cont);
7339     }
7340     if (expr) {
7341         OP * const unstack = newOP(OP_UNSTACK, 0);
7342         if (!next)
7343             next = unstack;
7344         cont = op_append_elem(OP_LINESEQ, cont, unstack);
7345     }
7346
7347     assert(block);
7348     listop = op_append_list(OP_LINESEQ, block, cont);
7349     assert(listop);
7350     redo = LINKLIST(listop);
7351
7352     if (expr) {
7353         scalar(listop);
7354         o = new_logop(OP_AND, 0, &expr, &listop);
7355         if (o == expr && o->op_type == OP_CONST && !SvTRUE(cSVOPo->op_sv)) {
7356             op_free((OP*)loop);
7357             return expr;                /* listop already freed by new_logop */
7358         }
7359         if (listop)
7360             ((LISTOP*)listop)->op_last->op_next =
7361                 (o == listop ? redo : LINKLIST(o));
7362     }
7363     else
7364         o = listop;
7365
7366     if (!loop) {
7367         NewOp(1101,loop,1,LOOP);
7368         CHANGE_TYPE(loop, OP_ENTERLOOP);
7369         loop->op_private = 0;
7370         loop->op_next = (OP*)loop;
7371     }
7372
7373     o = newBINOP(OP_LEAVELOOP, 0, (OP*)loop, o);
7374
7375     loop->op_redoop = redo;
7376     loop->op_lastop = o;
7377     o->op_private |= loopflags;
7378
7379     if (next)
7380         loop->op_nextop = next;
7381     else
7382         loop->op_nextop = o;
7383
7384     o->op_flags |= flags;
7385     o->op_private |= (flags >> 8);
7386     return o;
7387 }
7388
7389 /*
7390 =for apidoc Am|OP *|newFOROP|I32 flags|OP *sv|OP *expr|OP *block|OP *cont
7391
7392 Constructs, checks, and returns an op tree expressing a C<foreach>
7393 loop (iteration through a list of values).  This is a heavyweight loop,
7394 with structure that allows exiting the loop by C<last> and suchlike.
7395
7396 I<sv> optionally supplies the variable that will be aliased to each
7397 item in turn; if null, it defaults to C<$_> (either lexical or global).
7398 I<expr> supplies the list of values to iterate over.  I<block> supplies
7399 the main body of the loop, and I<cont> optionally supplies a C<continue>
7400 block that operates as a second half of the body.  All of these optree
7401 inputs are consumed by this function and become part of the constructed
7402 op tree.
7403
7404 I<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
7405 op and, shifted up eight bits, the eight bits of C<op_private> for
7406 the C<leaveloop> op, except that (in both cases) some bits will be set
7407 automatically.
7408
7409 =cut
7410 */
7411
7412 OP *
7413 Perl_newFOROP(pTHX_ I32 flags, OP *sv, OP *expr, OP *block, OP *cont)
7414 {
7415     dVAR;
7416     LOOP *loop;
7417     OP *wop;
7418     PADOFFSET padoff = 0;
7419     I32 iterflags = 0;
7420     I32 iterpflags = 0;
7421
7422     PERL_ARGS_ASSERT_NEWFOROP;
7423
7424     if (sv) {
7425         if (sv->op_type == OP_RV2SV) {  /* symbol table variable */
7426             iterpflags = sv->op_private & OPpOUR_INTRO; /* for our $x () */
7427             CHANGE_TYPE(sv, OP_RV2GV);
7428
7429             /* The op_type check is needed to prevent a possible segfault
7430              * if the loop variable is undeclared and 'strict vars' is in
7431              * effect. This is illegal but is nonetheless parsed, so we
7432              * may reach this point with an OP_CONST where we're expecting
7433              * an OP_GV.
7434              */
7435             if (cUNOPx(sv)->op_first->op_type == OP_GV
7436              && cGVOPx_gv(cUNOPx(sv)->op_first) == PL_defgv)
7437                 iterpflags |= OPpITER_DEF;
7438         }
7439         else if (sv->op_type == OP_PADSV) { /* private variable */
7440             iterpflags = sv->op_private & OPpLVAL_INTRO; /* for my $x () */
7441             padoff = sv->op_targ;
7442             sv->op_targ = 0;
7443             op_free(sv);
7444             sv = NULL;
7445             PAD_COMPNAME_GEN_set(padoff, PERL_INT_MAX);
7446         }
7447         else if (sv->op_type == OP_NULL && sv->op_targ == OP_SREFGEN)
7448             NOOP;
7449         else
7450             Perl_croak(aTHX_ "Can't use %s for loop variable", PL_op_desc[sv->op_type]);
7451         if (padoff) {
7452             PADNAME * const pn = PAD_COMPNAME(padoff);
7453             const char * const name = PadnamePV(pn);
7454
7455             if (PadnameLEN(pn) == 2 && name[0] == '$' && name[1] == '_')
7456                 iterpflags |= OPpITER_DEF;
7457         }
7458     }
7459     else {
7460         const PADOFFSET offset = pad_findmy_pvs("$_", 0);
7461         if (offset == NOT_IN_PAD || PAD_COMPNAME_FLAGS_isOUR(offset)) {
7462             sv = newGVOP(OP_GV, 0, PL_defgv);
7463         }
7464         else {
7465             padoff = offset;
7466         }
7467         iterpflags |= OPpITER_DEF;
7468     }
7469
7470     if (expr->op_type == OP_RV2AV || expr->op_type == OP_PADAV) {
7471         expr = op_lvalue(force_list(scalar(ref(expr, OP_ITER)), 1), OP_GREPSTART);
7472         iterflags |= OPf_STACKED;
7473     }
7474     else if (expr->op_type == OP_NULL &&
7475              (expr->op_flags & OPf_KIDS) &&
7476              ((BINOP*)expr)->op_first->op_type == OP_FLOP)
7477     {
7478         /* Basically turn for($x..$y) into the same as for($x,$y), but we
7479          * set the STACKED flag to indicate that these values are to be
7480          * treated as min/max values by 'pp_enteriter'.
7481          */
7482         const UNOP* const flip = (UNOP*)((UNOP*)((BINOP*)expr)->op_first)->op_first;
7483         LOGOP* const range = (LOGOP*) flip->op_first;
7484         OP* const left  = range->op_first;
7485         OP* const right = OpSIBLING(left);
7486         LISTOP* listop;
7487
7488         range->op_flags &= ~OPf_KIDS;
7489         /* detach range's children */
7490         op_sibling_splice((OP*)range, NULL, -1, NULL);
7491
7492         listop = (LISTOP*)newLISTOP(OP_LIST, 0, left, right);
7493         listop->op_first->op_next = range->op_next;
7494         left->op_next = range->op_other;
7495         right->op_next = (OP*)listop;
7496         listop->op_next = listop->op_first;
7497
7498         op_free(expr);
7499         expr = (OP*)(listop);
7500         op_null(expr);
7501         iterflags |= OPf_STACKED;
7502     }
7503     else {
7504         expr = op_lvalue(force_list(expr, 1), OP_GREPSTART);
7505     }
7506
7507     loop = (LOOP*)list(op_convert_list(OP_ENTERITER, iterflags,
7508                                op_append_elem(OP_LIST, expr, scalar(sv))));
7509     assert(!loop->op_next);
7510     /* for my  $x () sets OPpLVAL_INTRO;
7511      * for our $x () sets OPpOUR_INTRO */
7512     loop->op_private = (U8)iterpflags;
7513     if (loop->op_slabbed
7514      && DIFF(loop, OpSLOT(loop)->opslot_next)
7515          < SIZE_TO_PSIZE(sizeof(LOOP)))
7516     {
7517         LOOP *tmp;
7518         NewOp(1234,tmp,1,LOOP);
7519         Copy(loop,tmp,1,LISTOP);
7520 #ifdef PERL_OP_PARENT
7521         assert(loop->op_last->op_sibling == (OP*)loop);
7522         loop->op_last->op_sibling = (OP*)tmp; /*point back to new parent */
7523 #endif
7524         S_op_destroy(aTHX_ (OP*)loop);
7525         loop = tmp;
7526     }
7527     else if (!loop->op_slabbed)
7528     {
7529         loop = (LOOP*)PerlMemShared_realloc(loop, sizeof(LOOP));
7530 #ifdef PERL_OP_PARENT
7531         loop->op_last->op_sibling = (OP *)loop;
7532 #endif
7533     }
7534     loop->op_targ = padoff;
7535     wop = newWHILEOP(flags, 1, loop, newOP(OP_ITER, 0), block, cont, 0);
7536     return wop;
7537 }
7538
7539 /*
7540 =for apidoc Am|OP *|newLOOPEX|I32 type|OP *label
7541
7542 Constructs, checks, and returns a loop-exiting op (such as C<goto>
7543 or C<last>).  I<type> is the opcode.  I<label> supplies the parameter
7544 determining the target of the op; it is consumed by this function and
7545 becomes part of the constructed op tree.
7546
7547 =cut
7548 */
7549
7550 OP*
7551 Perl_newLOOPEX(pTHX_ I32 type, OP *label)
7552 {
7553     OP *o = NULL;
7554
7555     PERL_ARGS_ASSERT_NEWLOOPEX;
7556
7557     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
7558         || type == OP_CUSTOM);
7559
7560     if (type != OP_GOTO) {
7561         /* "last()" means "last" */
7562         if (label->op_type == OP_STUB && (label->op_flags & OPf_PARENS)) {
7563             o = newOP(type, OPf_SPECIAL);
7564         }
7565     }
7566     else {
7567         /* Check whether it's going to be a goto &function */
7568         if (label->op_type == OP_ENTERSUB
7569                 && !(label->op_flags & OPf_STACKED))
7570             label = newUNOP(OP_REFGEN, 0, op_lvalue(label, OP_REFGEN));
7571     }
7572
7573     /* Check for a constant argument */
7574     if (label->op_type == OP_CONST) {
7575             SV * const sv = ((SVOP *)label)->op_sv;
7576             STRLEN l;
7577             const char *s = SvPV_const(sv,l);
7578             if (l == strlen(s)) {
7579                 o = newPVOP(type,
7580                             SvUTF8(((SVOP*)label)->op_sv),
7581                             savesharedpv(
7582                                 SvPV_nolen_const(((SVOP*)label)->op_sv)));
7583             }
7584     }
7585     
7586     /* If we have already created an op, we do not need the label. */
7587     if (o)
7588                 op_free(label);
7589     else o = newUNOP(type, OPf_STACKED, label);
7590
7591     PL_hints |= HINT_BLOCK_SCOPE;
7592     return o;
7593 }
7594
7595 /* if the condition is a literal array or hash
7596    (or @{ ... } etc), make a reference to it.
7597  */
7598 STATIC OP *
7599 S_ref_array_or_hash(pTHX_ OP *cond)
7600 {
7601     if (cond
7602     && (cond->op_type == OP_RV2AV
7603     ||  cond->op_type == OP_PADAV
7604     ||  cond->op_type == OP_RV2HV
7605     ||  cond->op_type == OP_PADHV))
7606
7607         return newUNOP(OP_REFGEN, 0, op_lvalue(cond, OP_REFGEN));
7608
7609     else if(cond
7610     && (cond->op_type == OP_ASLICE
7611     ||  cond->op_type == OP_KVASLICE
7612     ||  cond->op_type == OP_HSLICE
7613     ||  cond->op_type == OP_KVHSLICE)) {
7614
7615         /* anonlist now needs a list from this op, was previously used in
7616          * scalar context */
7617         cond->op_flags |= ~(OPf_WANT_SCALAR | OPf_REF);
7618         cond->op_flags |= OPf_WANT_LIST;
7619
7620         return newANONLIST(op_lvalue(cond, OP_ANONLIST));
7621     }
7622
7623     else
7624         return cond;
7625 }
7626
7627 /* These construct the optree fragments representing given()
7628    and when() blocks.
7629
7630    entergiven and enterwhen are LOGOPs; the op_other pointer
7631    points up to the associated leave op. We need this so we
7632    can put it in the context and make break/continue work.
7633    (Also, of course, pp_enterwhen will jump straight to
7634    op_other if the match fails.)
7635  */
7636
7637 STATIC OP *
7638 S_newGIVWHENOP(pTHX_ OP *cond, OP *block,
7639                    I32 enter_opcode, I32 leave_opcode,
7640                    PADOFFSET entertarg)
7641 {
7642     dVAR;
7643     LOGOP *enterop;
7644     OP *o;
7645
7646     PERL_ARGS_ASSERT_NEWGIVWHENOP;
7647
7648     enterop = S_alloc_LOGOP(aTHX_ enter_opcode, block, NULL);
7649     enterop->op_targ = ((entertarg == NOT_IN_PAD) ? 0 : entertarg);
7650     enterop->op_private = 0;
7651
7652     o = newUNOP(leave_opcode, 0, (OP *) enterop);
7653
7654     if (cond) {
7655         /* prepend cond if we have one */
7656         op_sibling_splice((OP*)enterop, NULL, 0, scalar(cond));
7657
7658         o->op_next = LINKLIST(cond);
7659         cond->op_next = (OP *) enterop;
7660     }
7661     else {
7662         /* This is a default {} block */
7663         enterop->op_flags |= OPf_SPECIAL;
7664         o      ->op_flags |= OPf_SPECIAL;
7665
7666         o->op_next = (OP *) enterop;
7667     }
7668
7669     CHECKOP(enter_opcode, enterop); /* Currently does nothing, since
7670                                        entergiven and enterwhen both
7671                                        use ck_null() */
7672
7673     enterop->op_next = LINKLIST(block);
7674     block->op_next = enterop->op_other = o;
7675
7676     return o;
7677 }
7678
7679 /* Does this look like a boolean operation? For these purposes
7680    a boolean operation is:
7681      - a subroutine call [*]
7682      - a logical connective
7683      - a comparison operator
7684      - a filetest operator, with the exception of -s -M -A -C
7685      - defined(), exists() or eof()
7686      - /$re/ or $foo =~ /$re/
7687    
7688    [*] possibly surprising
7689  */
7690 STATIC bool
7691 S_looks_like_bool(pTHX_ const OP *o)
7692 {
7693     PERL_ARGS_ASSERT_LOOKS_LIKE_BOOL;
7694
7695     switch(o->op_type) {
7696         case OP_OR:
7697         case OP_DOR:
7698             return looks_like_bool(cLOGOPo->op_first);
7699
7700         case OP_AND:
7701         {
7702             OP* sibl = OpSIBLING(cLOGOPo->op_first);
7703             ASSUME(sibl);
7704             return (
7705                 looks_like_bool(cLOGOPo->op_first)
7706              && looks_like_bool(sibl));
7707         }
7708
7709         case OP_NULL:
7710         case OP_SCALAR:
7711             return (
7712                 o->op_flags & OPf_KIDS
7713             && looks_like_bool(cUNOPo->op_first));
7714
7715         case OP_ENTERSUB:
7716
7717         case OP_NOT:    case OP_XOR:
7718
7719         case OP_EQ:     case OP_NE:     case OP_LT:
7720         case OP_GT:     case OP_LE:     case OP_GE:
7721
7722         case OP_I_EQ:   case OP_I_NE:   case OP_I_LT:
7723         case OP_I_GT:   case OP_I_LE:   case OP_I_GE:
7724
7725         case OP_SEQ:    case OP_SNE:    case OP_SLT:
7726         case OP_SGT:    case OP_SLE:    case OP_SGE:
7727         
7728         case OP_SMARTMATCH:
7729         
7730         case OP_FTRREAD:  case OP_FTRWRITE: case OP_FTREXEC:
7731         case OP_FTEREAD:  case OP_FTEWRITE: case OP_FTEEXEC:
7732         case OP_FTIS:     case OP_FTEOWNED: case OP_FTROWNED:
7733         case OP_FTZERO:   case OP_FTSOCK:   case OP_FTCHR:
7734         case OP_FTBLK:    case OP_FTFILE:   case OP_FTDIR:
7735         case OP_FTPIPE:   case OP_FTLINK:   case OP_FTSUID:
7736         case OP_FTSGID:   case OP_FTSVTX:   case OP_FTTTY:
7737         case OP_FTTEXT:   case OP_FTBINARY:
7738         
7739         case OP_DEFINED: case OP_EXISTS:
7740         case OP_MATCH:   case OP_EOF:
7741
7742         case OP_FLOP:
7743
7744             return TRUE;
7745         
7746         case OP_CONST:
7747             /* Detect comparisons that have been optimized away */
7748             if (cSVOPo->op_sv == &PL_sv_yes
7749             ||  cSVOPo->op_sv == &PL_sv_no)
7750             
7751                 return TRUE;
7752             else
7753                 return FALSE;
7754
7755         /* FALLTHROUGH */
7756         default:
7757             return FALSE;
7758     }
7759 }
7760
7761 /*
7762 =for apidoc Am|OP *|newGIVENOP|OP *cond|OP *block|PADOFFSET defsv_off
7763
7764 Constructs, checks, and returns an op tree expressing a C<given> block.
7765 I<cond> supplies the expression that will be locally assigned to a lexical
7766 variable, and I<block> supplies the body of the C<given> construct; they
7767 are consumed by this function and become part of the constructed op tree.
7768 I<defsv_off> is the pad offset of the scalar lexical variable that will
7769 be affected.  If it is 0, the global $_ will be used.
7770
7771 =cut
7772 */
7773
7774 OP *
7775 Perl_newGIVENOP(pTHX_ OP *cond, OP *block, PADOFFSET defsv_off)
7776 {
7777     PERL_ARGS_ASSERT_NEWGIVENOP;
7778     return newGIVWHENOP(
7779         ref_array_or_hash(cond),
7780         block,
7781         OP_ENTERGIVEN, OP_LEAVEGIVEN,
7782         defsv_off);
7783 }
7784
7785 /*
7786 =for apidoc Am|OP *|newWHENOP|OP *cond|OP *block
7787
7788 Constructs, checks, and returns an op tree expressing a C<when> block.
7789 I<cond> supplies the test expression, and I<block> supplies the block
7790 that will be executed if the test evaluates to true; they are consumed
7791 by this function and become part of the constructed op tree.  I<cond>
7792 will be interpreted DWIMically, often as a comparison against C<$_>,
7793 and may be null to generate a C<default> block.
7794
7795 =cut
7796 */
7797
7798 OP *
7799 Perl_newWHENOP(pTHX_ OP *cond, OP *block)
7800 {
7801     const bool cond_llb = (!cond || looks_like_bool(cond));
7802     OP *cond_op;
7803
7804     PERL_ARGS_ASSERT_NEWWHENOP;
7805
7806     if (cond_llb)
7807         cond_op = cond;
7808     else {
7809         cond_op = newBINOP(OP_SMARTMATCH, OPf_SPECIAL,
7810                 newDEFSVOP(),
7811                 scalar(ref_array_or_hash(cond)));
7812     }
7813     
7814     return newGIVWHENOP(cond_op, block, OP_ENTERWHEN, OP_LEAVEWHEN, 0);
7815 }
7816
7817 /* must not conflict with SVf_UTF8 */
7818 #define CV_CKPROTO_CURSTASH     0x1
7819
7820 void
7821 Perl_cv_ckproto_len_flags(pTHX_ const CV *cv, const GV *gv, const char *p,
7822                     const STRLEN len, const U32 flags)
7823 {
7824     SV *name = NULL, *msg;
7825     const char * cvp = SvROK(cv)
7826                         ? SvTYPE(SvRV_const(cv)) == SVt_PVCV
7827                            ? (cv = (const CV *)SvRV_const(cv), CvPROTO(cv))
7828                            : ""
7829                         : CvPROTO(cv);
7830     STRLEN clen = CvPROTOLEN(cv), plen = len;
7831
7832     PERL_ARGS_ASSERT_CV_CKPROTO_LEN_FLAGS;
7833
7834     if (p == NULL && cvp == NULL)
7835         return;
7836
7837     if (!ckWARN_d(WARN_PROTOTYPE))
7838         return;
7839
7840     if (p && cvp) {
7841         p = S_strip_spaces(aTHX_ p, &plen);
7842         cvp = S_strip_spaces(aTHX_ cvp, &clen);
7843         if ((flags & SVf_UTF8) == SvUTF8(cv)) {
7844             if (plen == clen && memEQ(cvp, p, plen))
7845                 return;
7846         } else {
7847             if (flags & SVf_UTF8) {
7848                 if (bytes_cmp_utf8((const U8 *)cvp, clen, (const U8 *)p, plen) == 0)
7849                     return;
7850             }
7851             else {
7852                 if (bytes_cmp_utf8((const U8 *)p, plen, (const U8 *)cvp, clen) == 0)
7853                     return;
7854             }
7855         }
7856     }
7857
7858     msg = sv_newmortal();
7859
7860     if (gv)
7861     {
7862         if (isGV(gv))
7863             gv_efullname3(name = sv_newmortal(), gv, NULL);
7864         else if (SvPOK(gv) && *SvPVX((SV *)gv) == '&')
7865             name = newSVpvn_flags(SvPVX((SV *)gv)+1, SvCUR(gv)-1, SvUTF8(gv)|SVs_TEMP);
7866         else if (flags & CV_CKPROTO_CURSTASH || SvROK(gv)) {
7867             name = sv_2mortal(newSVhek(HvNAME_HEK(PL_curstash)));
7868             sv_catpvs(name, "::");
7869             if (SvROK(gv)) {
7870                 assert (SvTYPE(SvRV_const(gv)) == SVt_PVCV);
7871                 assert (CvNAMED(SvRV_const(gv)));
7872                 sv_cathek(name, CvNAME_HEK(MUTABLE_CV(SvRV_const(gv))));
7873             }
7874             else sv_catsv(name, (SV *)gv);
7875         }
7876         else name = (SV *)gv;
7877     }
7878     sv_setpvs(msg, "Prototype mismatch:");
7879     if (name)
7880         Perl_sv_catpvf(aTHX_ msg, " sub %"SVf, SVfARG(name));
7881     if (cvp)
7882         Perl_sv_catpvf(aTHX_ msg, " (%"UTF8f")", 
7883             UTF8fARG(SvUTF8(cv),clen,cvp)
7884         );
7885     else
7886         sv_catpvs(msg, ": none");
7887     sv_catpvs(msg, " vs ");
7888     if (p)
7889         Perl_sv_catpvf(aTHX_ msg, "(%"UTF8f")", UTF8fARG(flags & SVf_UTF8,len,p));
7890     else
7891         sv_catpvs(msg, "none");
7892     Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE), "%"SVf, SVfARG(msg));
7893 }
7894
7895 static void const_sv_xsub(pTHX_ CV* cv);
7896 static void const_av_xsub(pTHX_ CV* cv);
7897
7898 /*
7899
7900 =head1 Optree Manipulation Functions
7901
7902 =for apidoc cv_const_sv
7903
7904 If C<cv> is a constant sub eligible for inlining, returns the constant
7905 value returned by the sub.  Otherwise, returns NULL.
7906
7907 Constant subs can be created with C<newCONSTSUB> or as described in
7908 L<perlsub/"Constant Functions">.
7909
7910 =cut
7911 */
7912 SV *
7913 Perl_cv_const_sv(const CV *const cv)
7914 {
7915     SV *sv;
7916     if (!cv)
7917         return NULL;
7918     if (!(SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM))
7919         return NULL;
7920     sv = CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
7921     if (sv && SvTYPE(sv) == SVt_PVAV) return NULL;
7922     return sv;
7923 }
7924
7925 SV *
7926 Perl_cv_const_sv_or_av(const CV * const cv)
7927 {
7928     if (!cv)
7929         return NULL;
7930     if (SvROK(cv)) return SvRV((SV *)cv);
7931     assert (SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM);
7932     return CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
7933 }
7934
7935 /* op_const_sv:  examine an optree to determine whether it's in-lineable.
7936  * Can be called in 2 ways:
7937  *
7938  * !allow_lex
7939  *      look for a single OP_CONST with attached value: return the value
7940  *
7941  * allow_lex && !CvCONST(cv);
7942  *
7943  *      examine the clone prototype, and if contains only a single
7944  *      OP_CONST, return the value; or if it contains a single PADSV ref-
7945  *      erencing an outer lexical, turn on CvCONST to indicate the CV is
7946  *      a candidate for "constizing" at clone time, and return NULL.
7947  */
7948
7949 static SV *
7950 S_op_const_sv(pTHX_ const OP *o, CV *cv, bool allow_lex)
7951 {
7952     SV *sv = NULL;
7953     bool padsv = FALSE;
7954
7955     assert(o);
7956     assert(cv);
7957
7958     for (; o; o = o->op_next) {
7959         const OPCODE type = o->op_type;
7960
7961         if (type == OP_NEXTSTATE || type == OP_LINESEQ
7962              || type == OP_NULL
7963              || type == OP_PUSHMARK)
7964                 continue;
7965         if (type == OP_DBSTATE)
7966                 continue;
7967         if (type == OP_LEAVESUB)
7968             break;
7969         if (sv)
7970             return NULL;
7971         if (type == OP_CONST && cSVOPo->op_sv)
7972             sv = cSVOPo->op_sv;
7973         else if (type == OP_UNDEF && !o->op_private) {
7974             sv = newSV(0);
7975             SAVEFREESV(sv);
7976         }
7977         else if (allow_lex && type == OP_PADSV) {
7978                 if (PAD_COMPNAME_FLAGS(o->op_targ) & PADNAMEt_OUTER)
7979                 {
7980                     sv = &PL_sv_undef; /* an arbitrary non-null value */
7981                     padsv = TRUE;
7982                 }
7983                 else
7984                     return NULL;
7985         }
7986         else {
7987             return NULL;
7988         }
7989     }
7990     if (padsv) {
7991         CvCONST_on(cv);
7992         return NULL;
7993     }
7994     return sv;
7995 }
7996
7997 static bool
7998 S_already_defined(pTHX_ CV *const cv, OP * const block, OP * const o,
7999                         PADNAME * const name, SV ** const const_svp)
8000 {
8001     assert (cv);
8002     assert (o || name);
8003     assert (const_svp);
8004     if ((!block
8005          )) {
8006         if (CvFLAGS(PL_compcv)) {
8007             /* might have had built-in attrs applied */
8008             const bool pureperl = !CvISXSUB(cv) && CvROOT(cv);
8009             if (CvLVALUE(PL_compcv) && ! CvLVALUE(cv) && pureperl
8010              && ckWARN(WARN_MISC))
8011             {
8012                 /* protect against fatal warnings leaking compcv */
8013                 SAVEFREESV(PL_compcv);
8014                 Perl_warner(aTHX_ packWARN(WARN_MISC), "lvalue attribute ignored after the subroutine has been defined");
8015                 SvREFCNT_inc_simple_void_NN(PL_compcv);
8016             }
8017             CvFLAGS(cv) |=
8018                 (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS
8019                   & ~(CVf_LVALUE * pureperl));
8020         }
8021         return FALSE;
8022     }
8023
8024     /* redundant check for speed: */
8025     if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
8026         const line_t oldline = CopLINE(PL_curcop);
8027         SV *namesv = o
8028             ? cSVOPo->op_sv
8029             : sv_2mortal(newSVpvn_utf8(
8030                 PadnamePV(name)+1,PadnameLEN(name)-1, PadnameUTF8(name)
8031               ));
8032         if (PL_parser && PL_parser->copline != NOLINE)
8033             /* This ensures that warnings are reported at the first
8034                line of a redefinition, not the last.  */
8035             CopLINE_set(PL_curcop, PL_parser->copline);
8036         /* protect against fatal warnings leaking compcv */
8037         SAVEFREESV(PL_compcv);
8038         report_redefined_cv(namesv, cv, const_svp);
8039         SvREFCNT_inc_simple_void_NN(PL_compcv);
8040         CopLINE_set(PL_curcop, oldline);
8041     }
8042     SAVEFREESV(cv);
8043     return TRUE;
8044 }
8045
8046 CV *
8047 Perl_newMYSUB(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs, OP *block)
8048 {
8049     CV **spot;
8050     SV **svspot;
8051     const char *ps;
8052     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
8053     U32 ps_utf8 = 0;
8054     CV *cv = NULL;
8055     CV *compcv = PL_compcv;
8056     SV *const_sv;
8057     PADNAME *name;
8058     PADOFFSET pax = o->op_targ;
8059     CV *outcv = CvOUTSIDE(PL_compcv);
8060     CV *clonee = NULL;
8061     HEK *hek = NULL;
8062     bool reusable = FALSE;
8063     OP *start = NULL;
8064 #ifdef PERL_DEBUG_READONLY_OPS
8065     OPSLAB *slab = NULL;
8066 #endif
8067
8068     PERL_ARGS_ASSERT_NEWMYSUB;
8069
8070     /* Find the pad slot for storing the new sub.
8071        We cannot use PL_comppad, as it is the pad owned by the new sub.  We
8072        need to look in CvOUTSIDE and find the pad belonging to the enclos-
8073        ing sub.  And then we need to dig deeper if this is a lexical from
8074        outside, as in:
8075            my sub foo; sub { sub foo { } }
8076      */
8077    redo:
8078     name = PadlistNAMESARRAY(CvPADLIST(outcv))[pax];
8079     if (PadnameOUTER(name) && PARENT_PAD_INDEX(name)) {
8080         pax = PARENT_PAD_INDEX(name);
8081         outcv = CvOUTSIDE(outcv);
8082         assert(outcv);
8083         goto redo;
8084     }
8085     svspot =
8086         &PadARRAY(PadlistARRAY(CvPADLIST(outcv))
8087                         [CvDEPTH(outcv) ? CvDEPTH(outcv) : 1])[pax];
8088     spot = (CV **)svspot;
8089
8090     if (!(PL_parser && PL_parser->error_count))
8091         move_proto_attr(&proto, &attrs, (GV *)PadnameSV(name));
8092
8093     if (proto) {
8094         assert(proto->op_type == OP_CONST);
8095         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
8096         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
8097     }
8098     else
8099         ps = NULL;
8100
8101     if (proto)
8102         SAVEFREEOP(proto);
8103     if (attrs)
8104         SAVEFREEOP(attrs);
8105
8106     if (PL_parser && PL_parser->error_count) {
8107         op_free(block);
8108         SvREFCNT_dec(PL_compcv);
8109         PL_compcv = 0;
8110         goto done;
8111     }
8112
8113     if (CvDEPTH(outcv) && CvCLONE(compcv)) {
8114         cv = *spot;
8115         svspot = (SV **)(spot = &clonee);
8116     }
8117     else if (PadnameIsSTATE(name) || CvDEPTH(outcv))
8118         cv = *spot;
8119     else {
8120         assert (SvTYPE(*spot) == SVt_PVCV);
8121         if (CvNAMED(*spot))
8122             hek = CvNAME_HEK(*spot);
8123         else {
8124             dVAR;
8125             U32 hash;
8126             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
8127             CvNAME_HEK_set(*spot, hek =
8128                 share_hek(
8129                     PadnamePV(name)+1,
8130                     (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
8131                     hash
8132                 )
8133             );
8134             CvLEXICAL_on(*spot);
8135         }
8136         cv = PadnamePROTOCV(name);
8137         svspot = (SV **)(spot = &PadnamePROTOCV(name));
8138     }
8139
8140     if (block) {
8141         /* This makes sub {}; work as expected.  */
8142         if (block->op_type == OP_STUB) {
8143             const line_t l = PL_parser->copline;
8144             op_free(block);
8145             block = newSTATEOP(0, NULL, 0);
8146             PL_parser->copline = l;
8147         }
8148         block = CvLVALUE(compcv)
8149              || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv))
8150                    ? newUNOP(OP_LEAVESUBLV, 0,
8151                              op_lvalue(scalarseq(block), OP_LEAVESUBLV))
8152                    : newUNOP(OP_LEAVESUB, 0, scalarseq(block));
8153         start = LINKLIST(block);
8154         block->op_next = 0;
8155     }
8156
8157     if (!block || !ps || *ps || attrs
8158         || CvLVALUE(compcv)
8159         )
8160         const_sv = NULL;
8161     else
8162         const_sv = S_op_const_sv(aTHX_ start, compcv, FALSE);
8163
8164     if (cv) {
8165         const bool exists = CvROOT(cv) || CvXSUB(cv);
8166
8167         /* if the subroutine doesn't exist and wasn't pre-declared
8168          * with a prototype, assume it will be AUTOLOADed,
8169          * skipping the prototype check
8170          */
8171         if (exists || SvPOK(cv))
8172             cv_ckproto_len_flags(cv, (GV *)PadnameSV(name), ps, ps_len,
8173                                  ps_utf8);
8174         /* already defined? */
8175         if (exists) {
8176             if (S_already_defined(aTHX_ cv,block,NULL,name,&const_sv))
8177                 cv = NULL;
8178             else {
8179                 if (attrs) goto attrs;
8180                 /* just a "sub foo;" when &foo is already defined */
8181                 SAVEFREESV(compcv);
8182                 goto done;
8183             }
8184         }
8185         else if (CvDEPTH(outcv) && CvCLONE(compcv)) {
8186             cv = NULL;
8187             reusable = TRUE;
8188         }
8189     }
8190     if (const_sv) {
8191         SvREFCNT_inc_simple_void_NN(const_sv);
8192         SvFLAGS(const_sv) |= SVs_PADTMP;
8193         if (cv) {
8194             assert(!CvROOT(cv) && !CvCONST(cv));
8195             cv_forget_slab(cv);
8196         }
8197         else {
8198             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
8199             CvFILE_set_from_cop(cv, PL_curcop);
8200             CvSTASH_set(cv, PL_curstash);
8201             *spot = cv;
8202         }
8203         sv_setpvs(MUTABLE_SV(cv), "");  /* prototype is "" */
8204         CvXSUBANY(cv).any_ptr = const_sv;
8205         CvXSUB(cv) = const_sv_xsub;
8206         CvCONST_on(cv);
8207         CvISXSUB_on(cv);
8208         PoisonPADLIST(cv);
8209         CvFLAGS(cv) |= CvMETHOD(compcv);
8210         op_free(block);
8211         SvREFCNT_dec(compcv);
8212         PL_compcv = NULL;
8213         goto setname;
8214     }
8215     /* Checking whether outcv is CvOUTSIDE(compcv) is not sufficient to
8216        determine whether this sub definition is in the same scope as its
8217        declaration.  If this sub definition is inside an inner named pack-
8218        age sub (my sub foo; sub bar { sub foo { ... } }), outcv points to
8219        the package sub.  So check PadnameOUTER(name) too.
8220      */
8221     if (outcv == CvOUTSIDE(compcv) && !PadnameOUTER(name)) { 
8222         assert(!CvWEAKOUTSIDE(compcv));
8223         SvREFCNT_dec(CvOUTSIDE(compcv));
8224         CvWEAKOUTSIDE_on(compcv);
8225     }
8226     /* XXX else do we have a circular reference? */
8227     if (cv) {   /* must reuse cv in case stub is referenced elsewhere */
8228         /* transfer PL_compcv to cv */
8229         if (block
8230         ) {
8231             cv_flags_t preserved_flags =
8232                 CvFLAGS(cv) & (CVf_BUILTIN_ATTRS|CVf_NAMED);
8233             PADLIST *const temp_padl = CvPADLIST(cv);
8234             CV *const temp_cv = CvOUTSIDE(cv);
8235             const cv_flags_t other_flags =
8236                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
8237             OP * const cvstart = CvSTART(cv);
8238
8239             SvPOK_off(cv);
8240             CvFLAGS(cv) =
8241                 CvFLAGS(compcv) | preserved_flags;
8242             CvOUTSIDE(cv) = CvOUTSIDE(compcv);
8243             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(compcv);
8244             CvPADLIST_set(cv, CvPADLIST(compcv));
8245             CvOUTSIDE(compcv) = temp_cv;
8246             CvPADLIST_set(compcv, temp_padl);
8247             CvSTART(cv) = CvSTART(compcv);
8248             CvSTART(compcv) = cvstart;
8249             CvFLAGS(compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
8250             CvFLAGS(compcv) |= other_flags;
8251
8252             if (CvFILE(cv) && CvDYNFILE(cv)) {
8253                 Safefree(CvFILE(cv));
8254             }
8255
8256             /* inner references to compcv must be fixed up ... */
8257             pad_fixup_inner_anons(CvPADLIST(cv), compcv, cv);
8258             if (PERLDB_INTER)/* Advice debugger on the new sub. */
8259               ++PL_sub_generation;
8260         }
8261         else {
8262             /* Might have had built-in attributes applied -- propagate them. */
8263             CvFLAGS(cv) |= (CvFLAGS(compcv) & CVf_BUILTIN_ATTRS);
8264         }
8265         /* ... before we throw it away */
8266         SvREFCNT_dec(compcv);
8267         PL_compcv = compcv = cv;
8268     }
8269     else {
8270         cv = compcv;
8271         *spot = cv;
8272     }
8273    setname:
8274     CvLEXICAL_on(cv);
8275     if (!CvNAME_HEK(cv)) {
8276         if (hek) (void)share_hek_hek(hek);
8277         else {
8278             dVAR;
8279             U32 hash;
8280             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
8281             hek = share_hek(PadnamePV(name)+1,
8282                       (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
8283                       hash);
8284         }
8285         CvNAME_HEK_set(cv, hek);
8286     }
8287     if (const_sv) goto clone;
8288
8289     CvFILE_set_from_cop(cv, PL_curcop);
8290     CvSTASH_set(cv, PL_curstash);
8291
8292     if (ps) {
8293         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
8294         if ( ps_utf8 ) SvUTF8_on(MUTABLE_SV(cv));
8295     }
8296
8297     if (!block)
8298         goto attrs;
8299
8300     /* If we assign an optree to a PVCV, then we've defined a subroutine that
8301        the debugger could be able to set a breakpoint in, so signal to
8302        pp_entereval that it should not throw away any saved lines at scope
8303        exit.  */
8304        
8305     PL_breakable_sub_gen++;
8306     CvROOT(cv) = block;
8307     CvROOT(cv)->op_private |= OPpREFCOUNTED;
8308     OpREFCNT_set(CvROOT(cv), 1);
8309     /* The cv no longer needs to hold a refcount on the slab, as CvROOT
8310        itself has a refcount. */
8311     CvSLABBED_off(cv);
8312     OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
8313 #ifdef PERL_DEBUG_READONLY_OPS
8314     slab = (OPSLAB *)CvSTART(cv);
8315 #endif
8316     CvSTART(cv) = start;
8317     CALL_PEEP(start);
8318     finalize_optree(CvROOT(cv));
8319     S_prune_chain_head(&CvSTART(cv));
8320
8321     /* now that optimizer has done its work, adjust pad values */
8322
8323     pad_tidy(CvCLONE(cv) ? padtidy_SUBCLONE : padtidy_SUB);
8324
8325   attrs:
8326     if (attrs) {
8327         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
8328         apply_attrs(PL_curstash, MUTABLE_SV(cv), attrs);
8329     }
8330
8331     if (block) {
8332         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
8333             SV * const tmpstr = sv_newmortal();
8334             GV * const db_postponed = gv_fetchpvs("DB::postponed",
8335                                                   GV_ADDMULTI, SVt_PVHV);
8336             HV *hv;
8337             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
8338                                           CopFILE(PL_curcop),
8339                                           (long)PL_subline,
8340                                           (long)CopLINE(PL_curcop));
8341             if (HvNAME_HEK(PL_curstash)) {
8342                 sv_sethek(tmpstr, HvNAME_HEK(PL_curstash));
8343                 sv_catpvs(tmpstr, "::");
8344             }
8345             else sv_setpvs(tmpstr, "__ANON__::");
8346             sv_catpvn_flags(tmpstr, PadnamePV(name)+1, PadnameLEN(name)-1,
8347                             PadnameUTF8(name) ? SV_CATUTF8 : SV_CATBYTES);
8348             (void)hv_store(GvHV(PL_DBsub), SvPVX_const(tmpstr),
8349                     SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr), sv, 0);
8350             hv = GvHVn(db_postponed);
8351             if (HvTOTALKEYS(hv) > 0 && hv_exists(hv, SvPVX_const(tmpstr), SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr))) {
8352                 CV * const pcv = GvCV(db_postponed);
8353                 if (pcv) {
8354                     dSP;
8355                     PUSHMARK(SP);
8356                     XPUSHs(tmpstr);
8357                     PUTBACK;
8358                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
8359                 }
8360             }
8361         }
8362     }
8363
8364   clone:
8365     if (clonee) {
8366         assert(CvDEPTH(outcv));
8367         spot = (CV **)
8368             &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[CvDEPTH(outcv)])[pax];
8369         if (reusable) cv_clone_into(clonee, *spot);
8370         else *spot = cv_clone(clonee);
8371         SvREFCNT_dec_NN(clonee);
8372         cv = *spot;
8373     }
8374     if (CvDEPTH(outcv) && !reusable && PadnameIsSTATE(name)) {
8375         PADOFFSET depth = CvDEPTH(outcv);
8376         while (--depth) {
8377             SV *oldcv;
8378             svspot = &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[depth])[pax];
8379             oldcv = *svspot;
8380             *svspot = SvREFCNT_inc_simple_NN(cv);
8381             SvREFCNT_dec(oldcv);
8382         }
8383     }
8384
8385   done:
8386     if (PL_parser)
8387         PL_parser->copline = NOLINE;
8388     LEAVE_SCOPE(floor);
8389 #ifdef PERL_DEBUG_READONLY_OPS
8390     if (slab)
8391         Slab_to_ro(slab);
8392 #endif
8393     if (o) op_free(o);
8394     return cv;
8395 }
8396
8397 /* _x = extended */
8398 CV *
8399 Perl_newATTRSUB_x(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs,
8400                             OP *block, bool o_is_gv)
8401 {
8402     GV *gv;
8403     const char *ps;
8404     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
8405     U32 ps_utf8 = 0;
8406     CV *cv = NULL;
8407     SV *const_sv;
8408     const bool ec = PL_parser && PL_parser->error_count;
8409     /* If the subroutine has no body, no attributes, and no builtin attributes
8410        then it's just a sub declaration, and we may be able to get away with
8411        storing with a placeholder scalar in the symbol table, rather than a
8412        full CV.  If anything is present then it will take a full CV to
8413        store it.  */
8414     const I32 gv_fetch_flags
8415         = ec ? GV_NOADD_NOINIT :
8416         (block || attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS))
8417         ? GV_ADDMULTI : GV_ADDMULTI | GV_NOINIT;
8418     STRLEN namlen = 0;
8419     const char * const name =
8420          o ? SvPV_const(o_is_gv ? (SV *)o : cSVOPo->op_sv, namlen) : NULL;
8421     bool has_name;
8422     bool name_is_utf8 = o && !o_is_gv && SvUTF8(cSVOPo->op_sv);
8423     bool evanescent = FALSE;
8424     OP *start = NULL;
8425 #ifdef PERL_DEBUG_READONLY_OPS
8426     OPSLAB *slab = NULL;
8427 #endif
8428
8429     if (o_is_gv) {
8430         gv = (GV*)o;
8431         o = NULL;
8432         has_name = TRUE;
8433     } else if (name) {
8434         /* Try to optimise and avoid creating a GV.  Instead, the CV’s name
8435            hek and CvSTASH pointer together can imply the GV.  If the name
8436            contains a package name, then GvSTASH(CvGV(cv)) may differ from
8437            CvSTASH, so forego the optimisation if we find any.
8438            Also, we may be called from load_module at run time, so
8439            PL_curstash (which sets CvSTASH) may not point to the stash the
8440            sub is stored in.  */
8441         const I32 flags =
8442            ec ? GV_NOADD_NOINIT
8443               :   PL_curstash != CopSTASH(PL_curcop)
8444                || memchr(name, ':', namlen) || memchr(name, '\'', namlen)
8445                     ? gv_fetch_flags
8446                     : GV_ADDMULTI | GV_NOINIT | GV_NOTQUAL;
8447         gv = gv_fetchsv(cSVOPo->op_sv, flags, SVt_PVCV);
8448         has_name = TRUE;
8449     } else if (PERLDB_NAMEANON && CopLINE(PL_curcop)) {
8450         SV * const sv = sv_newmortal();
8451         Perl_sv_setpvf(aTHX_ sv, "%s[%s:%"IVdf"]",
8452                        PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
8453                        CopFILE(PL_curcop), (IV)CopLINE(PL_curcop));
8454         gv = gv_fetchsv(sv, gv_fetch_flags, SVt_PVCV);
8455         has_name = TRUE;
8456     } else if (PL_curstash) {
8457         gv = gv_fetchpvs("__ANON__", gv_fetch_flags, SVt_PVCV);
8458         has_name = FALSE;
8459     } else {
8460         gv = gv_fetchpvs("__ANON__::__ANON__", gv_fetch_flags, SVt_PVCV);
8461         has_name = FALSE;
8462     }
8463     if (!ec)
8464         move_proto_attr(&proto, &attrs,
8465                         isGV(gv) ? gv : (GV *)cSVOPo->op_sv);
8466
8467     if (proto) {
8468         assert(proto->op_type == OP_CONST);
8469         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
8470         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
8471     }
8472     else
8473         ps = NULL;
8474
8475     if (o)
8476         SAVEFREEOP(o);
8477     if (proto)
8478         SAVEFREEOP(proto);
8479     if (attrs)
8480         SAVEFREEOP(attrs);
8481
8482     if (ec) {
8483         op_free(block);
8484         if (name) SvREFCNT_dec(PL_compcv);
8485         else cv = PL_compcv;
8486         PL_compcv = 0;
8487         if (name && block) {
8488             const char *s = strrchr(name, ':');
8489             s = s ? s+1 : name;
8490             if (strEQ(s, "BEGIN")) {
8491                 if (PL_in_eval & EVAL_KEEPERR)
8492                     Perl_croak_nocontext("BEGIN not safe after errors--compilation aborted");
8493                 else {
8494                     SV * const errsv = ERRSV;
8495                     /* force display of errors found but not reported */
8496                     sv_catpvs(errsv, "BEGIN not safe after errors--compilation aborted");
8497                     Perl_croak_nocontext("%"SVf, SVfARG(errsv));
8498                 }
8499             }
8500         }
8501         goto done;
8502     }
8503
8504     if (!block && SvTYPE(gv) != SVt_PVGV) {
8505       /* If we are not defining a new sub and the existing one is not a
8506          full GV + CV... */
8507       if (attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS)) {
8508         /* We are applying attributes to an existing sub, so we need it
8509            upgraded if it is a constant.  */
8510         if (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)
8511             gv_init_pvn(gv, PL_curstash, name, namlen,
8512                         SVf_UTF8 * name_is_utf8);
8513       }
8514       else {                    /* Maybe prototype now, and had at maximum
8515                                    a prototype or const/sub ref before.  */
8516         if (SvTYPE(gv) > SVt_NULL) {
8517             cv_ckproto_len_flags((const CV *)gv,
8518                                  o ? (const GV *)cSVOPo->op_sv : NULL, ps,
8519                                  ps_len, ps_utf8);
8520         }
8521         if (!SvROK(gv)) {
8522           if (ps) {
8523             sv_setpvn(MUTABLE_SV(gv), ps, ps_len);
8524             if ( ps_utf8 ) SvUTF8_on(MUTABLE_SV(gv));
8525           }
8526           else
8527             sv_setiv(MUTABLE_SV(gv), -1);
8528         }
8529
8530         SvREFCNT_dec(PL_compcv);
8531         cv = PL_compcv = NULL;
8532         goto done;
8533       }
8534     }
8535
8536     cv = (!name || (isGV(gv) && GvCVGEN(gv)))
8537         ? NULL
8538         : isGV(gv)
8539             ? GvCV(gv)
8540             : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
8541                 ? (CV *)SvRV(gv)
8542                 : NULL;
8543
8544     if (block) {
8545         /* This makes sub {}; work as expected.  */
8546         if (block->op_type == OP_STUB) {
8547             const line_t l = PL_parser->copline;
8548             op_free(block);
8549             block = newSTATEOP(0, NULL, 0);
8550             PL_parser->copline = l;
8551         }
8552         block = CvLVALUE(PL_compcv)
8553              || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv)
8554                     && (!isGV(gv) || !GvASSUMECV(gv)))
8555                    ? newUNOP(OP_LEAVESUBLV, 0,
8556                              op_lvalue(scalarseq(block), OP_LEAVESUBLV))
8557                    : newUNOP(OP_LEAVESUB, 0, scalarseq(block));
8558         start = LINKLIST(block);
8559         block->op_next = 0;
8560     }
8561
8562     if (!block || !ps || *ps || attrs
8563         || CvLVALUE(PL_compcv)
8564         )
8565         const_sv = NULL;
8566     else
8567         const_sv =
8568             S_op_const_sv(aTHX_ start, PL_compcv, cBOOL(CvCLONE(PL_compcv)));
8569
8570     if (SvPOK(gv) || (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)) {
8571         assert (block);
8572         cv_ckproto_len_flags((const CV *)gv,
8573                              o ? (const GV *)cSVOPo->op_sv : NULL, ps,
8574                              ps_len, ps_utf8|CV_CKPROTO_CURSTASH);
8575         if (SvROK(gv)) {
8576             /* All the other code for sub redefinition warnings expects the
8577                clobbered sub to be a CV.  Instead of making all those code
8578                paths more complex, just inline the RV version here.  */
8579             const line_t oldline = CopLINE(PL_curcop);
8580             assert(IN_PERL_COMPILETIME);
8581             if (PL_parser && PL_parser->copline != NOLINE)
8582                 /* This ensures that warnings are reported at the first
8583                    line of a redefinition, not the last.  */
8584                 CopLINE_set(PL_curcop, PL_parser->copline);
8585             /* protect against fatal warnings leaking compcv */
8586             SAVEFREESV(PL_compcv);
8587
8588             if (ckWARN(WARN_REDEFINE)
8589              || (  ckWARN_d(WARN_REDEFINE)
8590                 && (  !const_sv || SvRV(gv) == const_sv
8591                    || sv_cmp(SvRV(gv), const_sv)  )))
8592                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
8593                           "Constant subroutine %"SVf" redefined",
8594                           SVfARG(cSVOPo->op_sv));
8595
8596             SvREFCNT_inc_simple_void_NN(PL_compcv);
8597             CopLINE_set(PL_curcop, oldline);
8598             SvREFCNT_dec(SvRV(gv));
8599         }
8600     }
8601
8602     if (cv) {
8603         const bool exists = CvROOT(cv) || CvXSUB(cv);
8604
8605         /* if the subroutine doesn't exist and wasn't pre-declared
8606          * with a prototype, assume it will be AUTOLOADed,
8607          * skipping the prototype check
8608          */
8609         if (exists || SvPOK(cv))
8610             cv_ckproto_len_flags(cv, gv, ps, ps_len, ps_utf8);
8611         /* already defined (or promised)? */
8612         if (exists || (isGV(gv) && GvASSUMECV(gv))) {
8613             if (S_already_defined(aTHX_ cv, block, o, NULL, &const_sv))
8614                 cv = NULL;
8615             else {
8616                 if (attrs) goto attrs;
8617                 /* just a "sub foo;" when &foo is already defined */
8618                 SAVEFREESV(PL_compcv);
8619                 goto done;
8620             }
8621         }
8622     }
8623     if (const_sv) {
8624         SvREFCNT_inc_simple_void_NN(const_sv);
8625         SvFLAGS(const_sv) |= SVs_PADTMP;
8626         if (cv) {
8627             assert(!CvROOT(cv) && !CvCONST(cv));
8628             cv_forget_slab(cv);
8629             sv_setpvs(MUTABLE_SV(cv), "");  /* prototype is "" */
8630             CvXSUBANY(cv).any_ptr = const_sv;
8631             CvXSUB(cv) = const_sv_xsub;
8632             CvCONST_on(cv);
8633             CvISXSUB_on(cv);
8634             PoisonPADLIST(cv);
8635             CvFLAGS(cv) |= CvMETHOD(PL_compcv);
8636         }
8637         else {
8638             if (isGV(gv) || CvMETHOD(PL_compcv)) {
8639                 if (name && isGV(gv))
8640                     GvCV_set(gv, NULL);
8641                 cv = newCONSTSUB_flags(
8642                     NULL, name, namlen, name_is_utf8 ? SVf_UTF8 : 0,
8643                     const_sv
8644                 );
8645                 CvFLAGS(cv) |= CvMETHOD(PL_compcv);
8646             }
8647             else {
8648                 if (!SvROK(gv)) {
8649                     SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
8650                     prepare_SV_for_RV((SV *)gv);
8651                     SvOK_off((SV *)gv);
8652                     SvROK_on(gv);
8653                 }
8654                 SvRV_set(gv, const_sv);
8655             }
8656         }
8657         op_free(block);
8658         SvREFCNT_dec(PL_compcv);
8659         PL_compcv = NULL;
8660         goto done;
8661     }
8662     if (cv) {                           /* must reuse cv if autoloaded */
8663         /* transfer PL_compcv to cv */
8664         if (block
8665         ) {
8666             cv_flags_t existing_builtin_attrs = CvFLAGS(cv) & CVf_BUILTIN_ATTRS;
8667             PADLIST *const temp_av = CvPADLIST(cv);
8668             CV *const temp_cv = CvOUTSIDE(cv);
8669             const cv_flags_t other_flags =
8670                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
8671             OP * const cvstart = CvSTART(cv);
8672
8673             if (isGV(gv)) {
8674                 CvGV_set(cv,gv);
8675                 assert(!CvCVGV_RC(cv));
8676                 assert(CvGV(cv) == gv);
8677             }
8678             else {
8679                 dVAR;
8680                 U32 hash;
8681                 PERL_HASH(hash, name, namlen);
8682                 CvNAME_HEK_set(cv,
8683                                share_hek(name,
8684                                          name_is_utf8
8685                                             ? -(SSize_t)namlen
8686                                             :  (SSize_t)namlen,
8687                                          hash));
8688             }
8689
8690             SvPOK_off(cv);
8691             CvFLAGS(cv) = CvFLAGS(PL_compcv) | existing_builtin_attrs
8692                                              | CvNAMED(cv);
8693             CvOUTSIDE(cv) = CvOUTSIDE(PL_compcv);
8694             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(PL_compcv);
8695             CvPADLIST_set(cv,CvPADLIST(PL_compcv));
8696             CvOUTSIDE(PL_compcv) = temp_cv;
8697             CvPADLIST_set(PL_compcv, temp_av);
8698             CvSTART(cv) = CvSTART(PL_compcv);
8699             CvSTART(PL_compcv) = cvstart;
8700             CvFLAGS(PL_compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
8701             CvFLAGS(PL_compcv) |= other_flags;
8702
8703             if (CvFILE(cv) && CvDYNFILE(cv)) {
8704                 Safefree(CvFILE(cv));
8705     }
8706             CvFILE_set_from_cop(cv, PL_curcop);
8707             CvSTASH_set(cv, PL_curstash);
8708
8709             /* inner references to PL_compcv must be fixed up ... */
8710             pad_fixup_inner_anons(CvPADLIST(cv), PL_compcv, cv);
8711             if (PERLDB_INTER)/* Advice debugger on the new sub. */
8712               ++PL_sub_generation;
8713         }
8714         else {
8715             /* Might have had built-in attributes applied -- propagate them. */
8716             CvFLAGS(cv) |= (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS);
8717         }
8718         /* ... before we throw it away */
8719         SvREFCNT_dec(PL_compcv);
8720         PL_compcv = cv;
8721     }
8722     else {
8723         cv = PL_compcv;
8724         if (name && isGV(gv)) {
8725             GvCV_set(gv, cv);
8726             GvCVGEN(gv) = 0;
8727             if (HvENAME_HEK(GvSTASH(gv)))
8728                 /* sub Foo::bar { (shift)+1 } */
8729                 gv_method_changed(gv);
8730         }
8731         else if (name) {
8732             if (!SvROK(gv)) {
8733                 SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
8734                 prepare_SV_for_RV((SV *)gv);
8735                 SvOK_off((SV *)gv);
8736                 SvROK_on(gv);
8737             }
8738             SvRV_set(gv, (SV *)cv);
8739         }
8740     }
8741     if (!CvHASGV(cv)) {
8742         if (isGV(gv)) CvGV_set(cv, gv);
8743         else {
8744             dVAR;
8745             U32 hash;
8746             PERL_HASH(hash, name, namlen);
8747             CvNAME_HEK_set(cv, share_hek(name,
8748                                          name_is_utf8
8749                                             ? -(SSize_t)namlen
8750                                             :  (SSize_t)namlen,
8751                                          hash));
8752         }
8753         CvFILE_set_from_cop(cv, PL_curcop);
8754         CvSTASH_set(cv, PL_curstash);
8755     }
8756
8757     if (ps) {
8758         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
8759         if ( ps_utf8 ) SvUTF8_on(MUTABLE_SV(cv));
8760     }
8761
8762     if (!block)
8763         goto attrs;
8764
8765     /* If we assign an optree to a PVCV, then we've defined a subroutine that
8766        the debugger could be able to set a breakpoint in, so signal to
8767        pp_entereval that it should not throw away any saved lines at scope
8768        exit.  */
8769        
8770     PL_breakable_sub_gen++;
8771     CvROOT(cv) = block;
8772     CvROOT(cv)->op_private |= OPpREFCOUNTED;
8773     OpREFCNT_set(CvROOT(cv), 1);
8774     /* The cv no longer needs to hold a refcount on the slab, as CvROOT
8775        itself has a refcount. */
8776     CvSLABBED_off(cv);
8777     OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
8778 #ifdef PERL_DEBUG_READONLY_OPS
8779     slab = (OPSLAB *)CvSTART(cv);
8780 #endif
8781     CvSTART(cv) = start;
8782     CALL_PEEP(start);
8783     finalize_optree(CvROOT(cv));
8784     S_prune_chain_head(&CvSTART(cv));
8785
8786     /* now that optimizer has done its work, adjust pad values */
8787
8788     pad_tidy(CvCLONE(cv) ? padtidy_SUBCLONE : padtidy_SUB);
8789
8790   attrs:
8791     if (attrs) {
8792         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
8793         HV *stash = name && !CvNAMED(cv) && GvSTASH(CvGV(cv))
8794                         ? GvSTASH(CvGV(cv))
8795                         : PL_curstash;
8796         if (!name) SAVEFREESV(cv);
8797         apply_attrs(stash, MUTABLE_SV(cv), attrs);
8798         if (!name) SvREFCNT_inc_simple_void_NN(cv);
8799     }
8800
8801     if (block && has_name) {
8802         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
8803             SV * const tmpstr = cv_name(cv,NULL,0);
8804             GV * const db_postponed = gv_fetchpvs("DB::postponed",
8805                                                   GV_ADDMULTI, SVt_PVHV);
8806             HV *hv;
8807             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
8808                                           CopFILE(PL_curcop),
8809                                           (long)PL_subline,
8810                                           (long)CopLINE(PL_curcop));
8811             (void)hv_store(GvHV(PL_DBsub), SvPVX_const(tmpstr),
8812                     SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr), sv, 0);
8813             hv = GvHVn(db_postponed);
8814             if (HvTOTALKEYS(hv) > 0 && hv_exists(hv, SvPVX_const(tmpstr), SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr))) {
8815                 CV * const pcv = GvCV(db_postponed);
8816                 if (pcv) {
8817                     dSP;
8818                     PUSHMARK(SP);
8819                     XPUSHs(tmpstr);
8820                     PUTBACK;
8821                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
8822                 }
8823             }
8824         }
8825
8826         if (name) {
8827             if (PL_parser && PL_parser->error_count)
8828                 clear_special_blocks(name, gv, cv);
8829             else
8830                 evanescent =
8831                     process_special_blocks(floor, name, gv, cv);
8832         }
8833     }
8834
8835   done:
8836     if (PL_parser)
8837         PL_parser->copline = NOLINE;
8838     LEAVE_SCOPE(floor);
8839     if (!evanescent) {
8840 #ifdef PERL_DEBUG_READONLY_OPS
8841       if (slab)
8842         Slab_to_ro(slab);
8843 #endif
8844       if (cv && name && CvOUTSIDE(cv) && !CvEVAL(CvOUTSIDE(cv)))
8845         pad_add_weakref(cv);
8846     }
8847     return cv;
8848 }
8849
8850 STATIC void
8851 S_clear_special_blocks(pTHX_ const char *const fullname,
8852                        GV *const gv, CV *const cv) {
8853     const char *colon;
8854     const char *name;
8855
8856     PERL_ARGS_ASSERT_CLEAR_SPECIAL_BLOCKS;
8857
8858     colon = strrchr(fullname,':');
8859     name = colon ? colon + 1 : fullname;
8860
8861     if ((*name == 'B' && strEQ(name, "BEGIN"))
8862         || (*name == 'E' && strEQ(name, "END"))
8863         || (*name == 'U' && strEQ(name, "UNITCHECK"))
8864         || (*name == 'C' && strEQ(name, "CHECK"))
8865         || (*name == 'I' && strEQ(name, "INIT"))) {
8866         if (!isGV(gv)) {
8867             (void)CvGV(cv);
8868             assert(isGV(gv));
8869         }
8870         GvCV_set(gv, NULL);
8871         SvREFCNT_dec_NN(MUTABLE_SV(cv));
8872     }
8873 }
8874
8875 /* Returns true if the sub has been freed.  */
8876 STATIC bool
8877 S_process_special_blocks(pTHX_ I32 floor, const char *const fullname,
8878                          GV *const gv,
8879                          CV *const cv)
8880 {
8881     const char *const colon = strrchr(fullname,':');
8882     const char *const name = colon ? colon + 1 : fullname;
8883
8884     PERL_ARGS_ASSERT_PROCESS_SPECIAL_BLOCKS;
8885
8886     if (*name == 'B') {
8887         if (strEQ(name, "BEGIN")) {
8888             const I32 oldscope = PL_scopestack_ix;
8889             dSP;
8890             (void)CvGV(cv);
8891             if (floor) LEAVE_SCOPE(floor);
8892             ENTER;
8893             PUSHSTACKi(PERLSI_REQUIRE);
8894             SAVECOPFILE(&PL_compiling);
8895             SAVECOPLINE(&PL_compiling);
8896             SAVEVPTR(PL_curcop);
8897
8898             DEBUG_x( dump_sub(gv) );
8899             Perl_av_create_and_push(aTHX_ &PL_beginav, MUTABLE_SV(cv));
8900             GvCV_set(gv,0);             /* cv has been hijacked */
8901             call_list(oldscope, PL_beginav);
8902
8903             POPSTACK;
8904             LEAVE;
8905             return !PL_savebegin;
8906         }
8907         else
8908             return FALSE;
8909     } else {
8910         if (*name == 'E') {
8911             if strEQ(name, "END") {
8912                 DEBUG_x( dump_sub(gv) );
8913                 Perl_av_create_and_unshift_one(aTHX_ &PL_endav, MUTABLE_SV(cv));
8914             } else
8915                 return FALSE;
8916         } else if (*name == 'U') {
8917             if (strEQ(name, "UNITCHECK")) {
8918                 /* It's never too late to run a unitcheck block */
8919                 Perl_av_create_and_unshift_one(aTHX_ &PL_unitcheckav, MUTABLE_SV(cv));
8920             }
8921             else
8922                 return FALSE;
8923         } else if (*name == 'C') {
8924             if (strEQ(name, "CHECK")) {
8925                 if (PL_main_start)
8926                     /* diag_listed_as: Too late to run %s block */
8927                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
8928                                    "Too late to run CHECK block");
8929                 Perl_av_create_and_unshift_one(aTHX_ &PL_checkav, MUTABLE_SV(cv));
8930             }
8931             else
8932                 return FALSE;
8933         } else if (*name == 'I') {
8934             if (strEQ(name, "INIT")) {
8935                 if (PL_main_start)
8936                     /* diag_listed_as: Too late to run %s block */
8937                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
8938                                    "Too late to run INIT block");
8939                 Perl_av_create_and_push(aTHX_ &PL_initav, MUTABLE_SV(cv));
8940             }
8941             else
8942                 return FALSE;
8943         } else
8944             return FALSE;
8945         DEBUG_x( dump_sub(gv) );
8946         (void)CvGV(cv);
8947         GvCV_set(gv,0);         /* cv has been hijacked */
8948         return FALSE;
8949     }
8950 }
8951
8952 /*
8953 =for apidoc newCONSTSUB
8954
8955 See L</newCONSTSUB_flags>.
8956
8957 =cut
8958 */
8959
8960 CV *
8961 Perl_newCONSTSUB(pTHX_ HV *stash, const char *name, SV *sv)
8962 {
8963     return newCONSTSUB_flags(stash, name, name ? strlen(name) : 0, 0, sv);
8964 }
8965
8966 /*
8967 =for apidoc newCONSTSUB_flags
8968
8969 Creates a constant sub equivalent to Perl C<sub FOO () { 123 }> which is
8970 eligible for inlining at compile-time.
8971
8972 Currently, the only useful value for C<flags> is SVf_UTF8.
8973
8974 The newly created subroutine takes ownership of a reference to the passed in
8975 SV.
8976
8977 Passing NULL for SV creates a constant sub equivalent to C<sub BAR () {}>,
8978 which won't be called if used as a destructor, but will suppress the overhead
8979 of a call to C<AUTOLOAD>.  (This form, however, isn't eligible for inlining at
8980 compile time.)
8981
8982 =cut
8983 */
8984
8985 CV *
8986 Perl_newCONSTSUB_flags(pTHX_ HV *stash, const char *name, STRLEN len,
8987                              U32 flags, SV *sv)
8988 {
8989     CV* cv;
8990     const char *const file = CopFILE(PL_curcop);
8991
8992     ENTER;
8993
8994     if (IN_PERL_RUNTIME) {
8995         /* at runtime, it's not safe to manipulate PL_curcop: it may be
8996          * an op shared between threads. Use a non-shared COP for our
8997          * dirty work */
8998          SAVEVPTR(PL_curcop);
8999          SAVECOMPILEWARNINGS();
9000          PL_compiling.cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
9001          PL_curcop = &PL_compiling;
9002     }
9003     SAVECOPLINE(PL_curcop);
9004     CopLINE_set(PL_curcop, PL_parser ? PL_parser->copline : NOLINE);
9005
9006     SAVEHINTS();
9007     PL_hints &= ~HINT_BLOCK_SCOPE;
9008
9009     if (stash) {
9010         SAVEGENERICSV(PL_curstash);
9011         PL_curstash = (HV *)SvREFCNT_inc_simple_NN(stash);
9012     }
9013
9014     /* Protect sv against leakage caused by fatal warnings. */
9015     if (sv) SAVEFREESV(sv);
9016
9017     /* file becomes the CvFILE. For an XS, it's usually static storage,
9018        and so doesn't get free()d.  (It's expected to be from the C pre-
9019        processor __FILE__ directive). But we need a dynamically allocated one,
9020        and we need it to get freed.  */
9021     cv = newXS_len_flags(name, len,
9022                          sv && SvTYPE(sv) == SVt_PVAV
9023                              ? const_av_xsub
9024                              : const_sv_xsub,
9025                          file ? file : "", "",
9026                          &sv, XS_DYNAMIC_FILENAME | flags);
9027     CvXSUBANY(cv).any_ptr = SvREFCNT_inc_simple(sv);
9028     CvCONST_on(cv);
9029
9030     LEAVE;
9031
9032     return cv;
9033 }
9034
9035 /*
9036 =for apidoc U||newXS
9037
9038 Used by C<xsubpp> to hook up XSUBs as Perl subs.  I<filename> needs to be
9039 static storage, as it is used directly as CvFILE(), without a copy being made.
9040
9041 =cut
9042 */
9043
9044 CV *
9045 Perl_newXS(pTHX_ const char *name, XSUBADDR_t subaddr, const char *filename)
9046 {
9047     PERL_ARGS_ASSERT_NEWXS;
9048     return newXS_len_flags(
9049         name, name ? strlen(name) : 0, subaddr, filename, NULL, NULL, 0
9050     );
9051 }
9052
9053 CV *
9054 Perl_newXS_flags(pTHX_ const char *name, XSUBADDR_t subaddr,
9055                  const char *const filename, const char *const proto,
9056                  U32 flags)
9057 {
9058     PERL_ARGS_ASSERT_NEWXS_FLAGS;
9059     return newXS_len_flags(
9060        name, name ? strlen(name) : 0, subaddr, filename, proto, NULL, flags
9061     );
9062 }
9063
9064 CV *
9065 Perl_newXS_deffile(pTHX_ const char *name, XSUBADDR_t subaddr)
9066 {
9067     PERL_ARGS_ASSERT_NEWXS_DEFFILE;
9068     return newXS_len_flags(
9069         name, name ? strlen(name) : 0, subaddr, NULL, NULL, NULL, 0
9070     );
9071 }
9072
9073 CV *
9074 Perl_newXS_len_flags(pTHX_ const char *name, STRLEN len,
9075                            XSUBADDR_t subaddr, const char *const filename,
9076                            const char *const proto, SV **const_svp,
9077                            U32 flags)
9078 {
9079     CV *cv;
9080     bool interleave = FALSE;
9081
9082     PERL_ARGS_ASSERT_NEWXS_LEN_FLAGS;
9083     if (!subaddr)
9084         Perl_croak_nocontext("panic: no address for '%s' in '%s'",
9085             name, filename ? filename : PL_xsubfilename);
9086     {
9087         GV * const gv = gv_fetchpvn(
9088                             name ? name : PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
9089                             name ? len : PL_curstash ? sizeof("__ANON__") - 1:
9090                                 sizeof("__ANON__::__ANON__") - 1,
9091                             GV_ADDMULTI | flags, SVt_PVCV);
9092
9093         if ((cv = (name ? GvCV(gv) : NULL))) {
9094             if (GvCVGEN(gv)) {
9095                 /* just a cached method */
9096                 SvREFCNT_dec(cv);
9097                 cv = NULL;
9098             }
9099             else if (CvROOT(cv) || CvXSUB(cv) || GvASSUMECV(gv)) {
9100                 /* already defined (or promised) */
9101                 /* Redundant check that allows us to avoid creating an SV
9102                    most of the time: */
9103                 if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
9104                     report_redefined_cv(newSVpvn_flags(
9105                                          name,len,(flags&SVf_UTF8)|SVs_TEMP
9106                                         ),
9107                                         cv, const_svp);
9108                 }
9109                 interleave = TRUE;
9110                 ENTER;
9111                 SAVEFREESV(cv);
9112                 cv = NULL;
9113             }
9114         }
9115     
9116         if (cv)                         /* must reuse cv if autoloaded */
9117             cv_undef(cv);
9118         else {
9119             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
9120             if (name) {
9121                 GvCV_set(gv,cv);
9122                 GvCVGEN(gv) = 0;
9123                 if (HvENAME_HEK(GvSTASH(gv)))
9124                     gv_method_changed(gv); /* newXS */
9125             }
9126         }
9127
9128         CvGV_set(cv, gv);
9129         if(filename) {
9130             (void)gv_fetchfile(filename);
9131             assert(!CvDYNFILE(cv)); /* cv_undef should have turned it off */
9132             if (flags & XS_DYNAMIC_FILENAME) {
9133                 CvDYNFILE_on(cv);
9134                 CvFILE(cv) = savepv(filename);
9135             } else {
9136             /* NOTE: not copied, as it is expected to be an external constant string */
9137                 CvFILE(cv) = (char *)filename;
9138             }
9139         } else {
9140             assert((flags & XS_DYNAMIC_FILENAME) == 0 && PL_xsubfilename);
9141             CvFILE(cv) = (char*)PL_xsubfilename;
9142         }
9143         CvISXSUB_on(cv);
9144         CvXSUB(cv) = subaddr;
9145 #ifndef PERL_IMPLICIT_CONTEXT
9146         CvHSCXT(cv) = &PL_stack_sp;
9147 #else
9148         PoisonPADLIST(cv);
9149 #endif
9150
9151         if (name)
9152             process_special_blocks(0, name, gv, cv);
9153         else
9154             CvANON_on(cv);
9155     } /* <- not a conditional branch */
9156
9157
9158     sv_setpv(MUTABLE_SV(cv), proto);
9159     if (interleave) LEAVE;
9160     return cv;
9161 }
9162
9163 CV *
9164 Perl_newSTUB(pTHX_ GV *gv, bool fake)
9165 {
9166     CV *cv = MUTABLE_CV(newSV_type(SVt_PVCV));
9167     GV *cvgv;
9168     PERL_ARGS_ASSERT_NEWSTUB;
9169     assert(!GvCVu(gv));
9170     GvCV_set(gv, cv);
9171     GvCVGEN(gv) = 0;
9172     if (!fake && HvENAME_HEK(GvSTASH(gv)))
9173         gv_method_changed(gv);
9174     if (SvFAKE(gv)) {
9175         cvgv = gv_fetchsv((SV *)gv, GV_ADDMULTI, SVt_PVCV);
9176         SvFAKE_off(cvgv);
9177     }
9178     else cvgv = gv;
9179     CvGV_set(cv, cvgv);
9180     CvFILE_set_from_cop(cv, PL_curcop);
9181     CvSTASH_set(cv, PL_curstash);
9182     GvMULTI_on(gv);
9183     return cv;
9184 }
9185
9186 void
9187 Perl_newFORM(pTHX_ I32 floor, OP *o, OP *block)
9188 {
9189     CV *cv;
9190
9191     GV *gv;
9192
9193     if (PL_parser && PL_parser->error_count) {
9194         op_free(block);
9195         goto finish;
9196     }
9197
9198     gv = o
9199         ? gv_fetchsv(cSVOPo->op_sv, GV_ADD, SVt_PVFM)
9200         : gv_fetchpvs("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVFM);
9201
9202     GvMULTI_on(gv);
9203     if ((cv = GvFORM(gv))) {
9204         if (ckWARN(WARN_REDEFINE)) {
9205             const line_t oldline = CopLINE(PL_curcop);
9206             if (PL_parser && PL_parser->copline != NOLINE)
9207                 CopLINE_set(PL_curcop, PL_parser->copline);
9208             if (o) {
9209                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
9210                             "Format %"SVf" redefined", SVfARG(cSVOPo->op_sv));
9211             } else {
9212                 /* diag_listed_as: Format %s redefined */
9213                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
9214                             "Format STDOUT redefined");
9215             }
9216             CopLINE_set(PL_curcop, oldline);
9217         }
9218         SvREFCNT_dec(cv);
9219     }
9220     cv = PL_compcv;
9221     GvFORM(gv) = (CV *)SvREFCNT_inc_simple_NN(cv);
9222     CvGV_set(cv, gv);
9223     CvFILE_set_from_cop(cv, PL_curcop);
9224
9225
9226     pad_tidy(padtidy_FORMAT);
9227     CvROOT(cv) = newUNOP(OP_LEAVEWRITE, 0, scalarseq(block));
9228     CvROOT(cv)->op_private |= OPpREFCOUNTED;
9229     OpREFCNT_set(CvROOT(cv), 1);
9230     CvSTART(cv) = LINKLIST(CvROOT(cv));
9231     CvROOT(cv)->op_next = 0;
9232     CALL_PEEP(CvSTART(cv));
9233     finalize_optree(CvROOT(cv));
9234     S_prune_chain_head(&CvSTART(cv));
9235     cv_forget_slab(cv);
9236
9237   finish:
9238     op_free(o);
9239     if (PL_parser)
9240         PL_parser->copline = NOLINE;
9241     LEAVE_SCOPE(floor);
9242     PL_compiling.cop_seq = 0;
9243 }
9244
9245 OP *
9246 Perl_newANONLIST(pTHX_ OP *o)
9247 {
9248     return op_convert_list(OP_ANONLIST, OPf_SPECIAL, o);
9249 }
9250
9251 OP *
9252 Perl_newANONHASH(pTHX_ OP *o)
9253 {
9254     return op_convert_list(OP_ANONHASH, OPf_SPECIAL, o);
9255 }
9256
9257 OP *
9258 Perl_newANONSUB(pTHX_ I32 floor, OP *proto, OP *block)
9259 {
9260     return newANONATTRSUB(floor, proto, NULL, block);
9261 }
9262
9263 OP *
9264 Perl_newANONATTRSUB(pTHX_ I32 floor, OP *proto, OP *attrs, OP *block)
9265 {
9266     SV * const cv = MUTABLE_SV(newATTRSUB(floor, 0, proto, attrs, block));
9267     OP * anoncode = 
9268         newSVOP(OP_ANONCODE, 0,
9269                 cv);
9270     if (CvANONCONST(cv))
9271         anoncode = newUNOP(OP_ANONCONST, 0,
9272                            op_convert_list(OP_ENTERSUB,
9273                                            OPf_STACKED|OPf_WANT_SCALAR,
9274                                            anoncode));
9275     return newUNOP(OP_REFGEN, 0, anoncode);
9276 }
9277
9278 OP *
9279 Perl_oopsAV(pTHX_ OP *o)
9280 {
9281     dVAR;
9282
9283     PERL_ARGS_ASSERT_OOPSAV;
9284
9285     switch (o->op_type) {
9286     case OP_PADSV:
9287     case OP_PADHV:
9288         CHANGE_TYPE(o, OP_PADAV);
9289         return ref(o, OP_RV2AV);
9290
9291     case OP_RV2SV:
9292     case OP_RV2HV:
9293         CHANGE_TYPE(o, OP_RV2AV);
9294         ref(o, OP_RV2AV);
9295         break;
9296
9297     default:
9298         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsAV");
9299         break;
9300     }
9301     return o;
9302 }
9303
9304 OP *
9305 Perl_oopsHV(pTHX_ OP *o)
9306 {
9307     dVAR;
9308
9309     PERL_ARGS_ASSERT_OOPSHV;
9310
9311     switch (o->op_type) {
9312     case OP_PADSV:
9313     case OP_PADAV:
9314         CHANGE_TYPE(o, OP_PADHV);
9315         return ref(o, OP_RV2HV);
9316
9317     case OP_RV2SV:
9318     case OP_RV2AV:
9319         CHANGE_TYPE(o, OP_RV2HV);
9320         ref(o, OP_RV2HV);
9321         break;
9322
9323     default:
9324         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsHV");
9325         break;
9326     }
9327     return o;
9328 }
9329
9330 OP *
9331 Perl_newAVREF(pTHX_ OP *o)
9332 {
9333     dVAR;
9334
9335     PERL_ARGS_ASSERT_NEWAVREF;
9336
9337     if (o->op_type == OP_PADANY) {
9338         CHANGE_TYPE(o, OP_PADAV);
9339         return o;
9340     }
9341     else if ((o->op_type == OP_RV2AV || o->op_type == OP_PADAV)) {
9342         Perl_croak(aTHX_ "Can't use an array as a reference");
9343     }
9344     return newUNOP(OP_RV2AV, 0, scalar(o));
9345 }
9346
9347 OP *
9348 Perl_newGVREF(pTHX_ I32 type, OP *o)
9349 {
9350     if (type == OP_MAPSTART || type == OP_GREPSTART || type == OP_SORT)
9351         return newUNOP(OP_NULL, 0, o);
9352     return ref(newUNOP(OP_RV2GV, OPf_REF, o), type);
9353 }
9354
9355 OP *
9356 Perl_newHVREF(pTHX_ OP *o)
9357 {
9358     dVAR;
9359
9360     PERL_ARGS_ASSERT_NEWHVREF;
9361
9362     if (o->op_type == OP_PADANY) {
9363         CHANGE_TYPE(o, OP_PADHV);
9364         return o;
9365     }
9366     else if ((o->op_type == OP_RV2HV || o->op_type == OP_PADHV)) {
9367         Perl_croak(aTHX_ "Can't use a hash as a reference");
9368     }
9369     return newUNOP(OP_RV2HV, 0, scalar(o));
9370 }
9371
9372 OP *
9373 Perl_newCVREF(pTHX_ I32 flags, OP *o)
9374 {
9375     if (o->op_type == OP_PADANY) {
9376         dVAR;
9377         CHANGE_TYPE(o, OP_PADCV);
9378     }
9379     return newUNOP(OP_RV2CV, flags, scalar(o));
9380 }
9381
9382 OP *
9383 Perl_newSVREF(pTHX_ OP *o)
9384 {
9385     dVAR;
9386
9387     PERL_ARGS_ASSERT_NEWSVREF;
9388
9389     if (o->op_type == OP_PADANY) {
9390         CHANGE_TYPE(o, OP_PADSV);
9391         scalar(o);
9392         return o;
9393     }
9394     return newUNOP(OP_RV2SV, 0, scalar(o));
9395 }
9396
9397 /* Check routines. See the comments at the top of this file for details
9398  * on when these are called */
9399
9400 OP *
9401 Perl_ck_anoncode(pTHX_ OP *o)
9402 {
9403     PERL_ARGS_ASSERT_CK_ANONCODE;
9404
9405     cSVOPo->op_targ = pad_add_anon((CV*)cSVOPo->op_sv, o->op_type);
9406     cSVOPo->op_sv = NULL;
9407     return o;
9408 }
9409
9410 static void
9411 S_io_hints(pTHX_ OP *o)
9412 {
9413 #if O_BINARY != 0 || O_TEXT != 0
9414     HV * const table =
9415         PL_hints & HINT_LOCALIZE_HH ? GvHV(PL_hintgv) : NULL;;
9416     if (table) {
9417         SV **svp = hv_fetchs(table, "open_IN", FALSE);
9418         if (svp && *svp) {
9419             STRLEN len = 0;
9420             const char *d = SvPV_const(*svp, len);
9421             const I32 mode = mode_from_discipline(d, len);
9422             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
9423 #  if O_BINARY != 0
9424             if (mode & O_BINARY)
9425                 o->op_private |= OPpOPEN_IN_RAW;
9426 #  endif
9427 #  if O_TEXT != 0
9428             if (mode & O_TEXT)
9429                 o->op_private |= OPpOPEN_IN_CRLF;
9430 #  endif
9431         }
9432
9433         svp = hv_fetchs(table, "open_OUT", FALSE);
9434         if (svp && *svp) {
9435             STRLEN len = 0;
9436             const char *d = SvPV_const(*svp, len);
9437             const I32 mode = mode_from_discipline(d, len);
9438             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
9439 #  if O_BINARY != 0
9440             if (mode & O_BINARY)
9441                 o->op_private |= OPpOPEN_OUT_RAW;
9442 #  endif
9443 #  if O_TEXT != 0
9444             if (mode & O_TEXT)
9445                 o->op_private |= OPpOPEN_OUT_CRLF;
9446 #  endif
9447         }
9448     }
9449 #else
9450     PERL_UNUSED_CONTEXT;
9451     PERL_UNUSED_ARG(o);
9452 #endif
9453 }
9454
9455 OP *
9456 Perl_ck_backtick(pTHX_ OP *o)
9457 {
9458     GV *gv;
9459     OP *newop = NULL;
9460     OP *sibl;
9461     PERL_ARGS_ASSERT_CK_BACKTICK;
9462     /* qx and `` have a null pushmark; CORE::readpipe has only one kid. */
9463     if (o->op_flags & OPf_KIDS && (sibl = OpSIBLING(cUNOPo->op_first))
9464      && (gv = gv_override("readpipe",8)))
9465     {
9466         /* detach rest of siblings from o and its first child */
9467         op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
9468         newop = S_new_entersubop(aTHX_ gv, sibl);
9469     }
9470     else if (!(o->op_flags & OPf_KIDS))
9471         newop = newUNOP(OP_BACKTICK, 0, newDEFSVOP());
9472     if (newop) {
9473         op_free(o);
9474         return newop;
9475     }
9476     S_io_hints(aTHX_ o);
9477     return o;
9478 }
9479
9480 OP *
9481 Perl_ck_bitop(pTHX_ OP *o)
9482 {
9483     PERL_ARGS_ASSERT_CK_BITOP;
9484
9485     o->op_private = (U8)(PL_hints & HINT_INTEGER);
9486
9487     if (o->op_type == OP_NBIT_OR     || o->op_type == OP_SBIT_OR
9488      || o->op_type == OP_NBIT_XOR    || o->op_type == OP_SBIT_XOR
9489      || o->op_type == OP_NBIT_AND    || o->op_type == OP_SBIT_AND
9490      || o->op_type == OP_NCOMPLEMENT || o->op_type == OP_SCOMPLEMENT)
9491         Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__BITWISE),
9492                               "The bitwise feature is experimental");
9493     if (!(o->op_flags & OPf_STACKED) /* Not an assignment */
9494             && OP_IS_INFIX_BIT(o->op_type))
9495     {
9496         const OP * const left = cBINOPo->op_first;
9497         const OP * const right = OpSIBLING(left);
9498         if ((OP_IS_NUMCOMPARE(left->op_type) &&
9499                 (left->op_flags & OPf_PARENS) == 0) ||
9500             (OP_IS_NUMCOMPARE(right->op_type) &&
9501                 (right->op_flags & OPf_PARENS) == 0))
9502             Perl_ck_warner(aTHX_ packWARN(WARN_PRECEDENCE),
9503                           "Possible precedence problem on bitwise %s operator",
9504                            o->op_type ==  OP_BIT_OR
9505                          ||o->op_type == OP_NBIT_OR  ? "|"
9506                         :  o->op_type ==  OP_BIT_AND
9507                          ||o->op_type == OP_NBIT_AND ? "&"
9508                         :  o->op_type ==  OP_BIT_XOR
9509                          ||o->op_type == OP_NBIT_XOR ? "^"
9510                         :  o->op_type == OP_SBIT_OR  ? "|."
9511                         :  o->op_type == OP_SBIT_AND ? "&." : "^."
9512                            );
9513     }
9514     return o;
9515 }
9516
9517 PERL_STATIC_INLINE bool
9518 is_dollar_bracket(pTHX_ const OP * const o)
9519 {
9520     const OP *kid;
9521     PERL_UNUSED_CONTEXT;
9522     return o->op_type == OP_RV2SV && o->op_flags & OPf_KIDS
9523         && (kid = cUNOPx(o)->op_first)
9524         && kid->op_type == OP_GV
9525         && strEQ(GvNAME(cGVOPx_gv(kid)), "[");
9526 }
9527
9528 OP *
9529 Perl_ck_cmp(pTHX_ OP *o)
9530 {
9531     PERL_ARGS_ASSERT_CK_CMP;
9532     if (ckWARN(WARN_SYNTAX)) {
9533         const OP *kid = cUNOPo->op_first;
9534         if (kid &&
9535             (
9536                 (   is_dollar_bracket(aTHX_ kid)
9537                  && OpSIBLING(kid) && OpSIBLING(kid)->op_type == OP_CONST
9538                 )
9539              || (   kid->op_type == OP_CONST
9540                  && (kid = OpSIBLING(kid)) && is_dollar_bracket(aTHX_ kid)
9541                 )
9542            )
9543         )
9544             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
9545                         "$[ used in %s (did you mean $] ?)", OP_DESC(o));
9546     }
9547     return o;
9548 }
9549
9550 OP *
9551 Perl_ck_concat(pTHX_ OP *o)
9552 {
9553     const OP * const kid = cUNOPo->op_first;
9554
9555     PERL_ARGS_ASSERT_CK_CONCAT;
9556     PERL_UNUSED_CONTEXT;
9557
9558     if (kid->op_type == OP_CONCAT && !(kid->op_private & OPpTARGET_MY) &&
9559             !(kUNOP->op_first->op_flags & OPf_MOD))
9560         o->op_flags |= OPf_STACKED;
9561     return o;
9562 }
9563
9564 OP *
9565 Perl_ck_spair(pTHX_ OP *o)
9566 {
9567     dVAR;
9568
9569     PERL_ARGS_ASSERT_CK_SPAIR;
9570
9571     if (o->op_flags & OPf_KIDS) {
9572         OP* newop;
9573         OP* kid;
9574         OP* kidkid;
9575         const OPCODE type = o->op_type;
9576         o = modkids(ck_fun(o), type);
9577         kid    = cUNOPo->op_first;
9578         kidkid = kUNOP->op_first;
9579         newop = OpSIBLING(kidkid);
9580         if (newop) {
9581             const OPCODE type = newop->op_type;
9582             if (OpHAS_SIBLING(newop))
9583                 return o;
9584             if (o->op_type == OP_REFGEN
9585              && (  type == OP_RV2CV
9586                 || (  !(newop->op_flags & OPf_PARENS)
9587                    && (  type == OP_RV2AV || type == OP_PADAV
9588                       || type == OP_RV2HV || type == OP_PADHV))))
9589                 NOOP; /* OK (allow srefgen for \@a and \%h) */
9590             else if (OP_GIMME(newop,0) != G_SCALAR)
9591                 return o;
9592         }
9593         /* excise first sibling */
9594         op_sibling_splice(kid, NULL, 1, NULL);
9595         op_free(kidkid);
9596     }
9597     /* transforms OP_REFGEN into OP_SREFGEN, OP_CHOP into OP_SCHOP,
9598      * and OP_CHOMP into OP_SCHOMP */
9599     o->op_ppaddr = PL_ppaddr[++o->op_type];
9600     return ck_fun(o);
9601 }
9602
9603 OP *
9604 Perl_ck_delete(pTHX_ OP *o)
9605 {
9606     PERL_ARGS_ASSERT_CK_DELETE;
9607
9608     o = ck_fun(o);
9609     o->op_private = 0;
9610     if (o->op_flags & OPf_KIDS) {
9611         OP * const kid = cUNOPo->op_first;
9612         switch (kid->op_type) {
9613         case OP_ASLICE:
9614             o->op_flags |= OPf_SPECIAL;
9615             /* FALLTHROUGH */
9616         case OP_HSLICE:
9617             o->op_private |= OPpSLICE;
9618             break;
9619         case OP_AELEM:
9620             o->op_flags |= OPf_SPECIAL;
9621             /* FALLTHROUGH */
9622         case OP_HELEM:
9623             break;
9624         case OP_KVASLICE:
9625             Perl_croak(aTHX_ "delete argument is index/value array slice,"
9626                              " use array slice");
9627         case OP_KVHSLICE:
9628             Perl_croak(aTHX_ "delete argument is key/value hash slice, use"
9629                              " hash slice");
9630         default:
9631             Perl_croak(aTHX_ "delete argument is not a HASH or ARRAY "
9632                              "element or slice");
9633         }
9634         if (kid->op_private & OPpLVAL_INTRO)
9635             o->op_private |= OPpLVAL_INTRO;
9636         op_null(kid);
9637     }
9638     return o;
9639 }
9640
9641 OP *
9642 Perl_ck_eof(pTHX_ OP *o)
9643 {
9644     PERL_ARGS_ASSERT_CK_EOF;
9645
9646     if (o->op_flags & OPf_KIDS) {
9647         OP *kid;
9648         if (cLISTOPo->op_first->op_type == OP_STUB) {
9649             OP * const newop
9650                 = newUNOP(o->op_type, OPf_SPECIAL, newGVOP(OP_GV, 0, PL_argvgv));
9651             op_free(o);
9652             o = newop;
9653         }
9654         o = ck_fun(o);
9655         kid = cLISTOPo->op_first;
9656         if (kid->op_type == OP_RV2GV)
9657             kid->op_private |= OPpALLOW_FAKE;
9658     }
9659     return o;
9660 }
9661
9662 OP *
9663 Perl_ck_eval(pTHX_ OP *o)
9664 {
9665     dVAR;
9666
9667     PERL_ARGS_ASSERT_CK_EVAL;
9668
9669     PL_hints |= HINT_BLOCK_SCOPE;
9670     if (o->op_flags & OPf_KIDS) {
9671         SVOP * const kid = (SVOP*)cUNOPo->op_first;
9672         assert(kid);
9673
9674         if (o->op_type == OP_ENTERTRY) {
9675             LOGOP *enter;
9676
9677             /* cut whole sibling chain free from o */
9678             op_sibling_splice(o, NULL, -1, NULL);
9679             op_free(o);
9680
9681             enter = S_alloc_LOGOP(aTHX_ OP_ENTERTRY, NULL, NULL);
9682
9683             /* establish postfix order */
9684             enter->op_next = (OP*)enter;
9685
9686             o = op_prepend_elem(OP_LINESEQ, (OP*)enter, (OP*)kid);
9687             CHANGE_TYPE(o, OP_LEAVETRY);
9688             enter->op_other = o;
9689             return o;
9690         }
9691         else {
9692             scalar((OP*)kid);
9693             S_set_haseval(aTHX);
9694         }
9695     }
9696     else {
9697         const U8 priv = o->op_private;
9698         op_free(o);
9699         /* the newUNOP will recursively call ck_eval(), which will handle
9700          * all the stuff at the end of this function, like adding
9701          * OP_HINTSEVAL
9702          */
9703         return newUNOP(OP_ENTEREVAL, priv <<8, newDEFSVOP());
9704     }
9705     o->op_targ = (PADOFFSET)PL_hints;
9706     if (o->op_private & OPpEVAL_BYTES) o->op_targ &= ~HINT_UTF8;
9707     if ((PL_hints & HINT_LOCALIZE_HH) != 0
9708      && !(o->op_private & OPpEVAL_COPHH) && GvHV(PL_hintgv)) {
9709         /* Store a copy of %^H that pp_entereval can pick up. */
9710         OP *hhop = newSVOP(OP_HINTSEVAL, 0,
9711                            MUTABLE_SV(hv_copy_hints_hv(GvHV(PL_hintgv))));
9712         /* append hhop to only child  */
9713         op_sibling_splice(o, cUNOPo->op_first, 0, hhop);
9714
9715         o->op_private |= OPpEVAL_HAS_HH;
9716     }
9717     if (!(o->op_private & OPpEVAL_BYTES)
9718          && FEATURE_UNIEVAL_IS_ENABLED)
9719             o->op_private |= OPpEVAL_UNICODE;
9720     return o;
9721 }
9722
9723 OP *
9724 Perl_ck_exec(pTHX_ OP *o)
9725 {
9726     PERL_ARGS_ASSERT_CK_EXEC;
9727
9728     if (o->op_flags & OPf_STACKED) {
9729         OP *kid;
9730         o = ck_fun(o);
9731         kid = OpSIBLING(cUNOPo->op_first);
9732         if (kid->op_type == OP_RV2GV)
9733             op_null(kid);
9734     }
9735     else
9736         o = listkids(o);
9737     return o;
9738 }
9739
9740 OP *
9741 Perl_ck_exists(pTHX_ OP *o)
9742 {
9743     PERL_ARGS_ASSERT_CK_EXISTS;
9744
9745     o = ck_fun(o);
9746     if (o->op_flags & OPf_KIDS) {
9747         OP * const kid = cUNOPo->op_first;
9748         if (kid->op_type == OP_ENTERSUB) {
9749             (void) ref(kid, o->op_type);
9750             if (kid->op_type != OP_RV2CV
9751                         && !(PL_parser && PL_parser->error_count))
9752                 Perl_croak(aTHX_
9753                           "exists argument is not a subroutine name");
9754             o->op_private |= OPpEXISTS_SUB;
9755         }
9756         else if (kid->op_type == OP_AELEM)
9757             o->op_flags |= OPf_SPECIAL;
9758         else if (kid->op_type != OP_HELEM)
9759             Perl_croak(aTHX_ "exists argument is not a HASH or ARRAY "
9760                              "element or a subroutine");
9761         op_null(kid);
9762     }
9763     return o;
9764 }
9765
9766 OP *
9767 Perl_ck_rvconst(pTHX_ OP *o)
9768 {
9769     dVAR;
9770     SVOP * const kid = (SVOP*)cUNOPo->op_first;
9771
9772     PERL_ARGS_ASSERT_CK_RVCONST;
9773
9774     o->op_private |= (PL_hints & HINT_STRICT_REFS);
9775
9776     if (kid->op_type == OP_CONST) {
9777         int iscv;
9778         GV *gv;
9779         SV * const kidsv = kid->op_sv;
9780
9781         /* Is it a constant from cv_const_sv()? */
9782         if ((SvROK(kidsv) || isGV_with_GP(kidsv)) && SvREADONLY(kidsv)) {
9783             return o;
9784         }
9785         if (SvTYPE(kidsv) == SVt_PVAV) return o;
9786         if ((o->op_private & HINT_STRICT_REFS) && (kid->op_private & OPpCONST_BARE)) {
9787             const char *badthing;
9788             switch (o->op_type) {
9789             case OP_RV2SV:
9790                 badthing = "a SCALAR";
9791                 break;
9792             case OP_RV2AV:
9793                 badthing = "an ARRAY";
9794                 break;
9795             case OP_RV2HV:
9796                 badthing = "a HASH";
9797                 break;
9798             default:
9799                 badthing = NULL;
9800                 break;
9801             }
9802             if (badthing)
9803                 Perl_croak(aTHX_
9804                            "Can't use bareword (\"%"SVf"\") as %s ref while \"strict refs\" in use",
9805                            SVfARG(kidsv), badthing);
9806         }
9807         /*
9808          * This is a little tricky.  We only want to add the symbol if we
9809          * didn't add it in the lexer.  Otherwise we get duplicate strict
9810          * warnings.  But if we didn't add it in the lexer, we must at
9811          * least pretend like we wanted to add it even if it existed before,
9812          * or we get possible typo warnings.  OPpCONST_ENTERED says
9813          * whether the lexer already added THIS instance of this symbol.
9814          */
9815         iscv = o->op_type == OP_RV2CV ? GV_NOEXPAND|GV_ADDMULTI : 0;
9816         gv = gv_fetchsv(kidsv,
9817                 o->op_type == OP_RV2CV
9818                         && o->op_private & OPpMAY_RETURN_CONSTANT
9819                     ? GV_NOEXPAND
9820                     : iscv | !(kid->op_private & OPpCONST_ENTERED),
9821                 iscv
9822                     ? SVt_PVCV
9823                     : o->op_type == OP_RV2SV
9824                         ? SVt_PV
9825                         : o->op_type == OP_RV2AV
9826                             ? SVt_PVAV
9827                             : o->op_type == OP_RV2HV
9828                                 ? SVt_PVHV
9829                                 : SVt_PVGV);
9830         if (gv) {
9831             if (!isGV(gv)) {
9832                 assert(iscv);
9833                 assert(SvROK(gv));
9834                 if (!(o->op_private & OPpMAY_RETURN_CONSTANT)
9835                   && SvTYPE(SvRV(gv)) != SVt_PVCV)
9836                     gv_fetchsv(kidsv, GV_ADDMULTI, SVt_PVCV);
9837             }
9838             CHANGE_TYPE(kid, OP_GV);
9839             SvREFCNT_dec(kid->op_sv);
9840 #ifdef USE_ITHREADS
9841             /* XXX hack: dependence on sizeof(PADOP) <= sizeof(SVOP) */
9842             STATIC_ASSERT_STMT(sizeof(PADOP) <= sizeof(SVOP));
9843             kPADOP->op_padix = pad_alloc(OP_GV, SVf_READONLY);
9844             SvREFCNT_dec(PAD_SVl(kPADOP->op_padix));
9845             PAD_SETSV(kPADOP->op_padix, MUTABLE_SV(SvREFCNT_inc_simple_NN(gv)));
9846 #else
9847             kid->op_sv = SvREFCNT_inc_simple_NN(gv);
9848 #endif
9849             kid->op_private = 0;
9850             /* FAKE globs in the symbol table cause weird bugs (#77810) */
9851             SvFAKE_off(gv);
9852         }
9853     }
9854     return o;
9855 }
9856
9857 OP *
9858 Perl_ck_ftst(pTHX_ OP *o)
9859 {
9860     dVAR;
9861     const I32 type = o->op_type;
9862
9863     PERL_ARGS_ASSERT_CK_FTST;
9864
9865     if (o->op_flags & OPf_REF) {
9866         NOOP;
9867     }
9868     else if (o->op_flags & OPf_KIDS && cUNOPo->op_first->op_type != OP_STUB) {
9869         SVOP * const kid = (SVOP*)cUNOPo->op_first;
9870         const OPCODE kidtype = kid->op_type;
9871
9872         if (kidtype == OP_CONST && (kid->op_private & OPpCONST_BARE)
9873          && !kid->op_folded) {
9874             OP * const newop = newGVOP(type, OPf_REF,
9875                 gv_fetchsv(kid->op_sv, GV_ADD, SVt_PVIO));
9876             op_free(o);
9877             return newop;
9878         }
9879         if ((PL_hints & HINT_FILETEST_ACCESS) && OP_IS_FILETEST_ACCESS(o->op_type))
9880             o->op_private |= OPpFT_ACCESS;
9881         if (type != OP_STAT && type != OP_LSTAT
9882             && PL_check[kidtype] == Perl_ck_ftst
9883             && kidtype != OP_STAT && kidtype != OP_LSTAT
9884         ) {
9885             o->op_private |= OPpFT_STACKED;
9886             kid->op_private |= OPpFT_STACKING;
9887             if (kidtype == OP_FTTTY && (
9888                    !(kid->op_private & OPpFT_STACKED)
9889                 || kid->op_private & OPpFT_AFTER_t
9890                ))
9891                 o->op_private |= OPpFT_AFTER_t;
9892         }
9893     }
9894     else {
9895         op_free(o);
9896         if (type == OP_FTTTY)
9897             o = newGVOP(type, OPf_REF, PL_stdingv);
9898         else
9899             o = newUNOP(type, 0, newDEFSVOP());
9900     }
9901     return o;
9902 }
9903
9904 OP *
9905 Perl_ck_fun(pTHX_ OP *o)
9906 {
9907     const int type = o->op_type;
9908     I32 oa = PL_opargs[type] >> OASHIFT;
9909
9910     PERL_ARGS_ASSERT_CK_FUN;
9911
9912     if (o->op_flags & OPf_STACKED) {
9913         if ((oa & OA_OPTIONAL) && (oa >> 4) && !((oa >> 4) & OA_OPTIONAL))
9914             oa &= ~OA_OPTIONAL;
9915         else
9916             return no_fh_allowed(o);
9917     }
9918
9919     if (o->op_flags & OPf_KIDS) {
9920         OP *prev_kid = NULL;
9921         OP *kid = cLISTOPo->op_first;
9922         I32 numargs = 0;
9923         bool seen_optional = FALSE;
9924
9925         if (kid->op_type == OP_PUSHMARK ||
9926             (kid->op_type == OP_NULL && kid->op_targ == OP_PUSHMARK))
9927         {
9928             prev_kid = kid;
9929             kid = OpSIBLING(kid);
9930         }
9931         if (kid && kid->op_type == OP_COREARGS) {
9932             bool optional = FALSE;
9933             while (oa) {
9934                 numargs++;
9935                 if (oa & OA_OPTIONAL) optional = TRUE;
9936                 oa = oa >> 4;
9937             }
9938             if (optional) o->op_private |= numargs;
9939             return o;
9940         }
9941
9942         while (oa) {
9943             if (oa & OA_OPTIONAL || (oa & 7) == OA_LIST) {
9944                 if (!kid && !seen_optional && PL_opargs[type] & OA_DEFGV) {
9945                     kid = newDEFSVOP();
9946                     /* append kid to chain */
9947                     op_sibling_splice(o, prev_kid, 0, kid);
9948                 }
9949                 seen_optional = TRUE;
9950             }
9951             if (!kid) break;
9952
9953             numargs++;
9954             switch (oa & 7) {
9955             case OA_SCALAR:
9956                 /* list seen where single (scalar) arg expected? */
9957                 if (numargs == 1 && !(oa >> 4)
9958                     && kid->op_type == OP_LIST && type != OP_SCALAR)
9959                 {
9960                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
9961                 }
9962                 if (type != OP_DELETE) scalar(kid);
9963                 break;
9964             case OA_LIST:
9965                 if (oa < 16) {
9966                     kid = 0;
9967                     continue;
9968                 }
9969                 else
9970                     list(kid);
9971                 break;
9972             case OA_AVREF:
9973                 if ((type == OP_PUSH || type == OP_UNSHIFT)
9974                     && !OpHAS_SIBLING(kid))
9975                     Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
9976                                    "Useless use of %s with no values",
9977                                    PL_op_desc[type]);
9978
9979                 if (kid->op_type == OP_CONST
9980                       && (  !SvROK(cSVOPx_sv(kid)) 
9981                          || SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV  )
9982                         )
9983                     bad_type_pv(numargs, "array", o, kid);
9984                 /* Defer checks to run-time if we have a scalar arg */
9985                 if (kid->op_type == OP_RV2AV || kid->op_type == OP_PADAV)
9986                     op_lvalue(kid, type);
9987                 else {
9988                     scalar(kid);
9989                     /* diag_listed_as: push on reference is experimental */
9990                     Perl_ck_warner_d(aTHX_
9991                                      packWARN(WARN_EXPERIMENTAL__AUTODEREF),
9992                                     "%s on reference is experimental",
9993                                      PL_op_desc[type]);
9994                 }
9995                 break;
9996             case OA_HVREF:
9997                 if (kid->op_type != OP_RV2HV && kid->op_type != OP_PADHV)
9998                     bad_type_pv(numargs, "hash", o, kid);
9999                 op_lvalue(kid, type);
10000                 break;
10001             case OA_CVREF:
10002                 {
10003                     /* replace kid with newop in chain */
10004                     OP * const newop =
10005                         S_op_sibling_newUNOP(aTHX_ o, prev_kid, OP_NULL, 0);
10006                     newop->op_next = newop;
10007                     kid = newop;
10008                 }
10009                 break;
10010             case OA_FILEREF:
10011                 if (kid->op_type != OP_GV && kid->op_type != OP_RV2GV) {
10012                     if (kid->op_type == OP_CONST &&
10013                         (kid->op_private & OPpCONST_BARE))
10014                     {
10015                         OP * const newop = newGVOP(OP_GV, 0,
10016                             gv_fetchsv(((SVOP*)kid)->op_sv, GV_ADD, SVt_PVIO));
10017                         /* replace kid with newop in chain */
10018                         op_sibling_splice(o, prev_kid, 1, newop);
10019                         op_free(kid);
10020                         kid = newop;
10021                     }
10022                     else if (kid->op_type == OP_READLINE) {
10023                         /* neophyte patrol: open(<FH>), close(<FH>) etc. */
10024                         bad_type_pv(numargs, "HANDLE", o, kid);
10025                     }
10026                     else {
10027                         I32 flags = OPf_SPECIAL;
10028                         I32 priv = 0;
10029                         PADOFFSET targ = 0;
10030
10031                         /* is this op a FH constructor? */
10032                         if (is_handle_constructor(o,numargs)) {
10033                             const char *name = NULL;
10034                             STRLEN len = 0;
10035                             U32 name_utf8 = 0;
10036                             bool want_dollar = TRUE;
10037
10038                             flags = 0;
10039                             /* Set a flag to tell rv2gv to vivify
10040                              * need to "prove" flag does not mean something
10041                              * else already - NI-S 1999/05/07
10042                              */
10043                             priv = OPpDEREF;
10044                             if (kid->op_type == OP_PADSV) {
10045                                 PADNAME * const pn
10046                                     = PAD_COMPNAME_SV(kid->op_targ);
10047                                 name = PadnamePV (pn);
10048                                 len  = PadnameLEN(pn);
10049                                 name_utf8 = PadnameUTF8(pn);
10050                             }
10051                             else if (kid->op_type == OP_RV2SV
10052                                      && kUNOP->op_first->op_type == OP_GV)
10053                             {
10054                                 GV * const gv = cGVOPx_gv(kUNOP->op_first);
10055                                 name = GvNAME(gv);
10056                                 len = GvNAMELEN(gv);
10057                                 name_utf8 = GvNAMEUTF8(gv) ? SVf_UTF8 : 0;
10058                             }
10059                             else if (kid->op_type == OP_AELEM
10060                                      || kid->op_type == OP_HELEM)
10061                             {
10062                                  OP *firstop;
10063                                  OP *op = ((BINOP*)kid)->op_first;
10064                                  name = NULL;
10065                                  if (op) {
10066                                       SV *tmpstr = NULL;
10067                                       const char * const a =
10068                                            kid->op_type == OP_AELEM ?
10069                                            "[]" : "{}";
10070                                       if (((op->op_type == OP_RV2AV) ||
10071                                            (op->op_type == OP_RV2HV)) &&
10072                                           (firstop = ((UNOP*)op)->op_first) &&
10073                                           (firstop->op_type == OP_GV)) {
10074                                            /* packagevar $a[] or $h{} */
10075                                            GV * const gv = cGVOPx_gv(firstop);
10076                                            if (gv)
10077                                                 tmpstr =
10078                                                      Perl_newSVpvf(aTHX_
10079                                                                    "%s%c...%c",
10080                                                                    GvNAME(gv),
10081                                                                    a[0], a[1]);
10082                                       }
10083                                       else if (op->op_type == OP_PADAV
10084                                                || op->op_type == OP_PADHV) {
10085                                            /* lexicalvar $a[] or $h{} */
10086                                            const char * const padname =
10087                                                 PAD_COMPNAME_PV(op->op_targ);
10088                                            if (padname)
10089                                                 tmpstr =
10090                                                      Perl_newSVpvf(aTHX_
10091                                                                    "%s%c...%c",
10092                                                                    padname + 1,
10093                                                                    a[0], a[1]);
10094                                       }
10095                                       if (tmpstr) {
10096                                            name = SvPV_const(tmpstr, len);
10097                                            name_utf8 = SvUTF8(tmpstr);
10098                                            sv_2mortal(tmpstr);
10099                                       }
10100                                  }
10101                                  if (!name) {
10102                                       name = "__ANONIO__";
10103                                       len = 10;
10104                                       want_dollar = FALSE;
10105                                  }
10106                                  op_lvalue(kid, type);
10107                             }
10108                             if (name) {
10109                                 SV *namesv;
10110                                 targ = pad_alloc(OP_RV2GV, SVf_READONLY);
10111                                 namesv = PAD_SVl(targ);
10112                                 if (want_dollar && *name != '$')
10113                                     sv_setpvs(namesv, "$");
10114                                 else
10115                                     sv_setpvs(namesv, "");
10116                                 sv_catpvn(namesv, name, len);
10117                                 if ( name_utf8 ) SvUTF8_on(namesv);
10118                             }
10119                         }
10120                         scalar(kid);
10121                         kid = S_op_sibling_newUNOP(aTHX_ o, prev_kid,
10122                                     OP_RV2GV, flags);
10123                         kid->op_targ = targ;
10124                         kid->op_private |= priv;
10125                     }
10126                 }
10127                 scalar(kid);
10128                 break;
10129             case OA_SCALARREF:
10130                 if ((type == OP_UNDEF || type == OP_POS)
10131                     && numargs == 1 && !(oa >> 4)
10132                     && kid->op_type == OP_LIST)
10133                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
10134                 op_lvalue(scalar(kid), type);
10135                 break;
10136             }
10137             oa >>= 4;
10138             prev_kid = kid;
10139             kid = OpSIBLING(kid);
10140         }
10141         /* FIXME - should the numargs or-ing move after the too many
10142          * arguments check? */
10143         o->op_private |= numargs;
10144         if (kid)
10145             return too_many_arguments_pv(o,OP_DESC(o), 0);
10146         listkids(o);
10147     }
10148     else if (PL_opargs[type] & OA_DEFGV) {
10149         /* Ordering of these two is important to keep f_map.t passing.  */
10150         op_free(o);
10151         return newUNOP(type, 0, newDEFSVOP());
10152     }
10153
10154     if (oa) {
10155         while (oa & OA_OPTIONAL)
10156             oa >>= 4;
10157         if (oa && oa != OA_LIST)
10158             return too_few_arguments_pv(o,OP_DESC(o), 0);
10159     }
10160     return o;
10161 }
10162
10163 OP *
10164 Perl_ck_glob(pTHX_ OP *o)
10165 {
10166     GV *gv;
10167
10168     PERL_ARGS_ASSERT_CK_GLOB;
10169
10170     o = ck_fun(o);
10171     if ((o->op_flags & OPf_KIDS) && !OpHAS_SIBLING(cLISTOPo->op_first))
10172         op_append_elem(OP_GLOB, o, newDEFSVOP()); /* glob() => glob($_) */
10173
10174     if (!(o->op_flags & OPf_SPECIAL) && (gv = gv_override("glob", 4)))
10175     {
10176         /* convert
10177          *     glob
10178          *       \ null - const(wildcard)
10179          * into
10180          *     null
10181          *       \ enter
10182          *            \ list
10183          *                 \ mark - glob - rv2cv
10184          *                             |        \ gv(CORE::GLOBAL::glob)
10185          *                             |
10186          *                              \ null - const(wildcard)
10187          */
10188         o->op_flags |= OPf_SPECIAL;
10189         o->op_targ = pad_alloc(OP_GLOB, SVs_PADTMP);
10190         o = S_new_entersubop(aTHX_ gv, o);
10191         o = newUNOP(OP_NULL, 0, o);
10192         o->op_targ = OP_GLOB; /* hint at what it used to be: eg in newWHILEOP */
10193         return o;
10194     }
10195     else o->op_flags &= ~OPf_SPECIAL;
10196 #if !defined(PERL_EXTERNAL_GLOB)
10197     if (!PL_globhook) {
10198         ENTER;
10199         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
10200                                newSVpvs("File::Glob"), NULL, NULL, NULL);
10201         LEAVE;
10202     }
10203 #endif /* !PERL_EXTERNAL_GLOB */
10204     gv = (GV *)newSV(0);
10205     gv_init(gv, 0, "", 0, 0);
10206     gv_IOadd(gv);
10207     op_append_elem(OP_GLOB, o, newGVOP(OP_GV, 0, gv));
10208     SvREFCNT_dec_NN(gv); /* newGVOP increased it */
10209     scalarkids(o);
10210     return o;
10211 }
10212
10213 OP *
10214 Perl_ck_grep(pTHX_ OP *o)
10215 {
10216     LOGOP *gwop;
10217     OP *kid;
10218     const OPCODE type = o->op_type == OP_GREPSTART ? OP_GREPWHILE : OP_MAPWHILE;
10219     PADOFFSET offset;
10220
10221     PERL_ARGS_ASSERT_CK_GREP;
10222
10223     /* don't allocate gwop here, as we may leak it if PL_parser->error_count > 0 */
10224
10225     if (o->op_flags & OPf_STACKED) {
10226         kid = cUNOPx(OpSIBLING(cLISTOPo->op_first))->op_first;
10227         if (kid->op_type != OP_SCOPE && kid->op_type != OP_LEAVE)
10228             return no_fh_allowed(o);
10229         o->op_flags &= ~OPf_STACKED;
10230     }
10231     kid = OpSIBLING(cLISTOPo->op_first);
10232     if (type == OP_MAPWHILE)
10233         list(kid);
10234     else
10235         scalar(kid);
10236     o = ck_fun(o);
10237     if (PL_parser && PL_parser->error_count)
10238         return o;
10239     kid = OpSIBLING(cLISTOPo->op_first);
10240     if (kid->op_type != OP_NULL)
10241         Perl_croak(aTHX_ "panic: ck_grep, type=%u", (unsigned) kid->op_type);
10242     kid = kUNOP->op_first;
10243
10244     gwop = S_alloc_LOGOP(aTHX_ type, o, LINKLIST(kid));
10245     kid->op_next = (OP*)gwop;
10246     offset = pad_findmy_pvs("$_", 0);
10247     if (offset == NOT_IN_PAD || PAD_COMPNAME_FLAGS_isOUR(offset)) {
10248         o->op_private = gwop->op_private = 0;
10249         gwop->op_targ = pad_alloc(type, SVs_PADTMP);
10250     }
10251     else {
10252         o->op_private = gwop->op_private = OPpGREP_LEX;
10253         gwop->op_targ = o->op_targ = offset;
10254     }
10255
10256     kid = OpSIBLING(cLISTOPo->op_first);
10257     for (kid = OpSIBLING(kid); kid; kid = OpSIBLING(kid))
10258         op_lvalue(kid, OP_GREPSTART);
10259
10260     return (OP*)gwop;
10261 }
10262
10263 OP *
10264 Perl_ck_index(pTHX_ OP *o)
10265 {
10266     PERL_ARGS_ASSERT_CK_INDEX;
10267
10268     if (o->op_flags & OPf_KIDS) {
10269         OP *kid = OpSIBLING(cLISTOPo->op_first);        /* get past pushmark */
10270         if (kid)
10271             kid = OpSIBLING(kid);                       /* get past "big" */
10272         if (kid && kid->op_type == OP_CONST) {
10273             const bool save_taint = TAINT_get;
10274             SV *sv = kSVOP->op_sv;
10275             if ((!SvPOK(sv) || SvNIOKp(sv)) && SvOK(sv) && !SvROK(sv)) {
10276                 sv = newSV(0);
10277                 sv_copypv(sv, kSVOP->op_sv);
10278                 SvREFCNT_dec_NN(kSVOP->op_sv);
10279                 kSVOP->op_sv = sv;
10280             }
10281             if (SvOK(sv)) fbm_compile(sv, 0);
10282             TAINT_set(save_taint);
10283 #ifdef NO_TAINT_SUPPORT
10284             PERL_UNUSED_VAR(save_taint);
10285 #endif
10286         }
10287     }
10288     return ck_fun(o);
10289 }
10290
10291 OP *
10292 Perl_ck_lfun(pTHX_ OP *o)
10293 {
10294     const OPCODE type = o->op_type;
10295
10296     PERL_ARGS_ASSERT_CK_LFUN;
10297
10298     return modkids(ck_fun(o), type);
10299 }
10300
10301 OP *
10302 Perl_ck_defined(pTHX_ OP *o)            /* 19990527 MJD */
10303 {
10304     PERL_ARGS_ASSERT_CK_DEFINED;
10305
10306     if ((o->op_flags & OPf_KIDS)) {
10307         switch (cUNOPo->op_first->op_type) {
10308         case OP_RV2AV:
10309         case OP_PADAV:
10310             Perl_croak(aTHX_ "Can't use 'defined(@array)'"
10311                              " (Maybe you should just omit the defined()?)");
10312         break;
10313         case OP_RV2HV:
10314         case OP_PADHV:
10315             Perl_croak(aTHX_ "Can't use 'defined(%%hash)'"
10316                              " (Maybe you should just omit the defined()?)");
10317             break;
10318         default:
10319             /* no warning */
10320             break;
10321         }
10322     }
10323     return ck_rfun(o);
10324 }
10325
10326 OP *
10327 Perl_ck_readline(pTHX_ OP *o)
10328 {
10329     PERL_ARGS_ASSERT_CK_READLINE;
10330
10331     if (o->op_flags & OPf_KIDS) {
10332          OP *kid = cLISTOPo->op_first;
10333          if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
10334     }
10335     else {
10336         OP * const newop
10337             = newUNOP(OP_READLINE, 0, newGVOP(OP_GV, 0, PL_argvgv));
10338         op_free(o);
10339         return newop;
10340     }
10341     return o;
10342 }
10343
10344 OP *
10345 Perl_ck_rfun(pTHX_ OP *o)
10346 {
10347     const OPCODE type = o->op_type;
10348
10349     PERL_ARGS_ASSERT_CK_RFUN;
10350
10351     return refkids(ck_fun(o), type);
10352 }
10353
10354 OP *
10355 Perl_ck_listiob(pTHX_ OP *o)
10356 {
10357     OP *kid;
10358
10359     PERL_ARGS_ASSERT_CK_LISTIOB;
10360
10361     kid = cLISTOPo->op_first;
10362     if (!kid) {
10363         o = force_list(o, 1);
10364         kid = cLISTOPo->op_first;
10365     }
10366     if (kid->op_type == OP_PUSHMARK)
10367         kid = OpSIBLING(kid);
10368     if (kid && o->op_flags & OPf_STACKED)
10369         kid = OpSIBLING(kid);
10370     else if (kid && !OpHAS_SIBLING(kid)) {              /* print HANDLE; */
10371         if (kid->op_type == OP_CONST && kid->op_private & OPpCONST_BARE
10372          && !kid->op_folded) {
10373             o->op_flags |= OPf_STACKED; /* make it a filehandle */
10374             scalar(kid);
10375             /* replace old const op with new OP_RV2GV parent */
10376             kid = S_op_sibling_newUNOP(aTHX_ o, cLISTOPo->op_first,
10377                                         OP_RV2GV, OPf_REF);
10378             kid = OpSIBLING(kid);
10379         }
10380     }
10381
10382     if (!kid)
10383         op_append_elem(o->op_type, o, newDEFSVOP());
10384
10385     if (o->op_type == OP_PRTF) return modkids(listkids(o), OP_PRTF);
10386     return listkids(o);
10387 }
10388
10389 OP *
10390 Perl_ck_smartmatch(pTHX_ OP *o)
10391 {
10392     dVAR;
10393     PERL_ARGS_ASSERT_CK_SMARTMATCH;
10394     if (0 == (o->op_flags & OPf_SPECIAL)) {
10395         OP *first  = cBINOPo->op_first;
10396         OP *second = OpSIBLING(first);
10397         
10398         /* Implicitly take a reference to an array or hash */
10399
10400         /* remove the original two siblings, then add back the
10401          * (possibly different) first and second sibs.
10402          */
10403         op_sibling_splice(o, NULL, 1, NULL);
10404         op_sibling_splice(o, NULL, 1, NULL);
10405         first  = ref_array_or_hash(first);
10406         second = ref_array_or_hash(second);
10407         op_sibling_splice(o, NULL, 0, second);
10408         op_sibling_splice(o, NULL, 0, first);
10409         
10410         /* Implicitly take a reference to a regular expression */
10411         if (first->op_type == OP_MATCH) {
10412             CHANGE_TYPE(first, OP_QR);
10413         }
10414         if (second->op_type == OP_MATCH) {
10415             CHANGE_TYPE(second, OP_QR);
10416         }
10417     }
10418     
10419     return o;
10420 }
10421
10422
10423 static OP *
10424 S_maybe_targlex(pTHX_ OP *o)
10425 {
10426     OP * const kid = cLISTOPo->op_first;
10427     /* has a disposable target? */
10428     if ((PL_opargs[kid->op_type] & OA_TARGLEX)
10429         && !(kid->op_flags & OPf_STACKED)
10430         /* Cannot steal the second time! */
10431         && !(kid->op_private & OPpTARGET_MY)
10432         )
10433     {
10434         OP * const kkid = OpSIBLING(kid);
10435
10436         /* Can just relocate the target. */
10437         if (kkid && kkid->op_type == OP_PADSV
10438             && (!(kkid->op_private & OPpLVAL_INTRO)
10439                || kkid->op_private & OPpPAD_STATE))
10440         {
10441             kid->op_targ = kkid->op_targ;
10442             kkid->op_targ = 0;
10443             /* Now we do not need PADSV and SASSIGN.
10444              * Detach kid and free the rest. */
10445             op_sibling_splice(o, NULL, 1, NULL);
10446             op_free(o);
10447             kid->op_private |= OPpTARGET_MY;    /* Used for context settings */
10448             return kid;
10449         }
10450     }
10451     return o;
10452 }
10453
10454 OP *
10455 Perl_ck_sassign(pTHX_ OP *o)
10456 {
10457     dVAR;
10458     OP * const kid = cLISTOPo->op_first;
10459
10460     PERL_ARGS_ASSERT_CK_SASSIGN;
10461
10462     if (OpHAS_SIBLING(kid)) {
10463         OP *kkid = OpSIBLING(kid);
10464         /* For state variable assignment with attributes, kkid is a list op
10465            whose op_last is a padsv. */
10466         if ((kkid->op_type == OP_PADSV ||
10467              (OP_TYPE_IS_OR_WAS(kkid, OP_LIST) &&
10468               (kkid = cLISTOPx(kkid)->op_last)->op_type == OP_PADSV
10469              )
10470             )
10471                 && (kkid->op_private & (OPpLVAL_INTRO|OPpPAD_STATE))
10472                     == (OPpLVAL_INTRO|OPpPAD_STATE)) {
10473             const PADOFFSET target = kkid->op_targ;
10474             OP *const other = newOP(OP_PADSV,
10475                                     kkid->op_flags
10476                                     | ((kkid->op_private & ~OPpLVAL_INTRO) << 8));
10477             OP *const first = newOP(OP_NULL, 0);
10478             OP *const nullop =
10479                 newCONDOP(0, first, S_maybe_targlex(aTHX_ o), other);
10480             OP *const condop = first->op_next;
10481
10482             CHANGE_TYPE(condop, OP_ONCE);
10483             other->op_targ = target;
10484             nullop->op_flags |= OPf_WANT_SCALAR;
10485
10486             /* Store the initializedness of state vars in a separate
10487                pad entry.  */
10488             condop->op_targ =
10489               pad_add_name_pvn("$",1,padadd_NO_DUP_CHECK|padadd_STATE,0,0);
10490             /* hijacking PADSTALE for uninitialized state variables */
10491             SvPADSTALE_on(PAD_SVl(condop->op_targ));
10492
10493             return nullop;
10494         }
10495     }
10496     return S_maybe_targlex(aTHX_ o);
10497 }
10498
10499 OP *
10500 Perl_ck_match(pTHX_ OP *o)
10501 {
10502     PERL_ARGS_ASSERT_CK_MATCH;
10503
10504     if (o->op_type != OP_QR && PL_compcv) {
10505         const PADOFFSET offset = pad_findmy_pvs("$_", 0);
10506         if (offset != NOT_IN_PAD && !(PAD_COMPNAME_FLAGS_isOUR(offset))) {
10507             o->op_targ = offset;
10508             o->op_private |= OPpTARGET_MY;
10509         }
10510     }
10511     if (o->op_type == OP_MATCH || o->op_type == OP_QR)
10512         o->op_private |= OPpRUNTIME;
10513     return o;
10514 }
10515
10516 OP *
10517 Perl_ck_method(pTHX_ OP *o)
10518 {
10519     SV *sv, *methsv, *rclass;
10520     const char* method;
10521     char* compatptr;
10522     int utf8;
10523     STRLEN len, nsplit = 0, i;
10524     OP* new_op;
10525     OP * const kid = cUNOPo->op_first;
10526
10527     PERL_ARGS_ASSERT_CK_METHOD;
10528     if (kid->op_type != OP_CONST) return o;
10529
10530     sv = kSVOP->op_sv;
10531
10532     /* replace ' with :: */
10533     while ((compatptr = strchr(SvPVX(sv), '\''))) {
10534         *compatptr = ':';
10535         sv_insert(sv, compatptr - SvPVX_const(sv), 0, ":", 1);
10536     }
10537
10538     method = SvPVX_const(sv);
10539     len = SvCUR(sv);
10540     utf8 = SvUTF8(sv) ? -1 : 1;
10541
10542     for (i = len - 1; i > 0; --i) if (method[i] == ':') {
10543         nsplit = i+1;
10544         break;
10545     }
10546
10547     methsv = newSVpvn_share(method+nsplit, utf8*(len - nsplit), 0);
10548
10549     if (!nsplit) { /* $proto->method() */
10550         op_free(o);
10551         return newMETHOP_named(OP_METHOD_NAMED, 0, methsv);
10552     }
10553
10554     if (nsplit == 7 && memEQ(method, "SUPER::", nsplit)) { /* $proto->SUPER::method() */
10555         op_free(o);
10556         return newMETHOP_named(OP_METHOD_SUPER, 0, methsv);
10557     }
10558
10559     /* $proto->MyClass::method() and $proto->MyClass::SUPER::method() */
10560     if (nsplit >= 9 && strnEQ(method+nsplit-9, "::SUPER::", 9)) {
10561         rclass = newSVpvn_share(method, utf8*(nsplit-9), 0);
10562         new_op = newMETHOP_named(OP_METHOD_REDIR_SUPER, 0, methsv);
10563     } else {
10564         rclass = newSVpvn_share(method, utf8*(nsplit-2), 0);
10565         new_op = newMETHOP_named(OP_METHOD_REDIR, 0, methsv);
10566     }
10567 #ifdef USE_ITHREADS
10568     op_relocate_sv(&rclass, &cMETHOPx(new_op)->op_rclass_targ);
10569 #else
10570     cMETHOPx(new_op)->op_rclass_sv = rclass;
10571 #endif
10572     op_free(o);
10573     return new_op;
10574 }
10575
10576 OP *
10577 Perl_ck_null(pTHX_ OP *o)
10578 {
10579     PERL_ARGS_ASSERT_CK_NULL;
10580     PERL_UNUSED_CONTEXT;
10581     return o;
10582 }
10583
10584 OP *
10585 Perl_ck_open(pTHX_ OP *o)
10586 {
10587     PERL_ARGS_ASSERT_CK_OPEN;
10588
10589     S_io_hints(aTHX_ o);
10590     {
10591          /* In case of three-arg dup open remove strictness
10592           * from the last arg if it is a bareword. */
10593          OP * const first = cLISTOPx(o)->op_first; /* The pushmark. */
10594          OP * const last  = cLISTOPx(o)->op_last;  /* The bareword. */
10595          OP *oa;
10596          const char *mode;
10597
10598          if ((last->op_type == OP_CONST) &&             /* The bareword. */
10599              (last->op_private & OPpCONST_BARE) &&
10600              (last->op_private & OPpCONST_STRICT) &&
10601              (oa = OpSIBLING(first)) &&         /* The fh. */
10602              (oa = OpSIBLING(oa)) &&                    /* The mode. */
10603              (oa->op_type == OP_CONST) &&
10604              SvPOK(((SVOP*)oa)->op_sv) &&
10605              (mode = SvPVX_const(((SVOP*)oa)->op_sv)) &&
10606              mode[0] == '>' && mode[1] == '&' &&        /* A dup open. */
10607              (last == OpSIBLING(oa)))                   /* The bareword. */
10608               last->op_private &= ~OPpCONST_STRICT;
10609     }
10610     return ck_fun(o);
10611 }
10612
10613 OP *
10614 Perl_ck_prototype(pTHX_ OP *o)
10615 {
10616     PERL_ARGS_ASSERT_CK_PROTOTYPE;
10617     if (!(o->op_flags & OPf_KIDS)) {
10618         op_free(o);
10619         return newUNOP(OP_PROTOTYPE, 0, newDEFSVOP());
10620     }
10621     return o;
10622 }
10623
10624 OP *
10625 Perl_ck_refassign(pTHX_ OP *o)
10626 {
10627     OP * const right = cLISTOPo->op_first;
10628     OP * const left = OpSIBLING(right);
10629     OP *varop = cUNOPx(cUNOPx(left)->op_first)->op_first;
10630     bool stacked = 0;
10631
10632     PERL_ARGS_ASSERT_CK_REFASSIGN;
10633     assert (left);
10634     assert (left->op_type == OP_SREFGEN);
10635
10636     o->op_private = varop->op_private & (OPpLVAL_INTRO|OPpPAD_STATE);
10637
10638     switch (varop->op_type) {
10639     case OP_PADAV:
10640         o->op_private |= OPpLVREF_AV;
10641         goto settarg;
10642     case OP_PADHV:
10643         o->op_private |= OPpLVREF_HV;
10644     case OP_PADSV:
10645       settarg:
10646         o->op_targ = varop->op_targ;
10647         varop->op_targ = 0;
10648         PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
10649         break;
10650     case OP_RV2AV:
10651         o->op_private |= OPpLVREF_AV;
10652         goto checkgv;
10653         NOT_REACHED; /* NOTREACHED */
10654     case OP_RV2HV:
10655         o->op_private |= OPpLVREF_HV;
10656         /* FALLTHROUGH */
10657     case OP_RV2SV:
10658       checkgv:
10659         if (cUNOPx(varop)->op_first->op_type != OP_GV) goto bad;
10660       detach_and_stack:
10661         /* Point varop to its GV kid, detached.  */
10662         varop = op_sibling_splice(varop, NULL, -1, NULL);
10663         stacked = TRUE;
10664         break;
10665     case OP_RV2CV: {
10666         OP * const kidparent =
10667             cUNOPx(cUNOPx(varop)->op_first)->op_first->op_sibling;
10668         OP * const kid = cUNOPx(kidparent)->op_first;
10669         o->op_private |= OPpLVREF_CV;
10670         if (kid->op_type == OP_GV) {
10671             varop = kidparent;
10672             goto detach_and_stack;
10673         }
10674         if (kid->op_type != OP_PADCV)   goto bad;
10675         o->op_targ = kid->op_targ;
10676         kid->op_targ = 0;
10677         break;
10678     }
10679     case OP_AELEM:
10680     case OP_HELEM:
10681         o->op_private |= OPpLVREF_ELEM;
10682         op_null(varop);
10683         stacked = TRUE;
10684         /* Detach varop.  */
10685         op_sibling_splice(cUNOPx(left)->op_first, NULL, -1, NULL);
10686         break;
10687     default:
10688       bad:
10689         /* diag_listed_as: Can't modify reference to %s in %s assignment */
10690         yyerror(Perl_form(aTHX_ "Can't modify reference to %s in scalar "
10691                                 "assignment",
10692                                  OP_DESC(varop)));
10693         return o;
10694     }
10695     if (!FEATURE_REFALIASING_IS_ENABLED)
10696         Perl_croak(aTHX_
10697                   "Experimental aliasing via reference not enabled");
10698     Perl_ck_warner_d(aTHX_
10699                      packWARN(WARN_EXPERIMENTAL__REFALIASING),
10700                     "Aliasing via reference is experimental");
10701     if (stacked) {
10702         o->op_flags |= OPf_STACKED;
10703         op_sibling_splice(o, right, 1, varop);
10704     }
10705     else {
10706         o->op_flags &=~ OPf_STACKED;
10707         op_sibling_splice(o, right, 1, NULL);
10708     }
10709     op_free(left);
10710     return o;
10711 }
10712
10713 OP *
10714 Perl_ck_repeat(pTHX_ OP *o)
10715 {
10716     PERL_ARGS_ASSERT_CK_REPEAT;
10717
10718     if (cBINOPo->op_first->op_flags & OPf_PARENS) {
10719         OP* kids;
10720         o->op_private |= OPpREPEAT_DOLIST;
10721         kids = op_sibling_splice(o, NULL, 1, NULL); /* detach first kid */
10722         kids = force_list(kids, 1); /* promote it to a list */
10723         op_sibling_splice(o, NULL, 0, kids); /* and add back */
10724     }
10725     else
10726         scalar(o);
10727     return o;
10728 }
10729
10730 OP *
10731 Perl_ck_require(pTHX_ OP *o)
10732 {
10733     GV* gv;
10734
10735     PERL_ARGS_ASSERT_CK_REQUIRE;
10736
10737     if (o->op_flags & OPf_KIDS) {       /* Shall we supply missing .pm? */
10738         SVOP * const kid = (SVOP*)cUNOPo->op_first;
10739         HEK *hek;
10740         U32 hash;
10741         char *s;
10742         STRLEN len;
10743         if (kid->op_type == OP_CONST) {
10744           SV * const sv = kid->op_sv;
10745           U32 const was_readonly = SvREADONLY(sv);
10746           if (kid->op_private & OPpCONST_BARE) {
10747             dVAR;
10748             const char *end;
10749
10750             if (was_readonly) {
10751                     SvREADONLY_off(sv);
10752             }   
10753             if (SvIsCOW(sv)) sv_force_normal_flags(sv, 0);
10754
10755             s = SvPVX(sv);
10756             len = SvCUR(sv);
10757             end = s + len;
10758             for (; s < end; s++) {
10759                 if (*s == ':' && s[1] == ':') {
10760                     *s = '/';
10761                     Move(s+2, s+1, end - s - 1, char);
10762                     --end;
10763                 }
10764             }
10765             SvEND_set(sv, end);
10766             sv_catpvs(sv, ".pm");
10767             PERL_HASH(hash, SvPVX(sv), SvCUR(sv));
10768             hek = share_hek(SvPVX(sv),
10769                             (SSize_t)SvCUR(sv) * (SvUTF8(sv) ? -1 : 1),
10770                             hash);
10771             sv_sethek(sv, hek);
10772             unshare_hek(hek);
10773             SvFLAGS(sv) |= was_readonly;
10774           }
10775           else if (SvPOK(sv) && !SvNIOK(sv) && !SvGMAGICAL(sv)) {
10776             s = SvPV(sv, len);
10777             if (SvREFCNT(sv) > 1) {
10778                 kid->op_sv = newSVpvn_share(
10779                     s, SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len, 0);
10780                 SvREFCNT_dec_NN(sv);
10781             }
10782             else {
10783                 dVAR;
10784                 if (was_readonly) SvREADONLY_off(sv);
10785                 PERL_HASH(hash, s, len);
10786                 hek = share_hek(s,
10787                                 SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len,
10788                                 hash);
10789                 sv_sethek(sv, hek);
10790                 unshare_hek(hek);
10791                 SvFLAGS(sv) |= was_readonly;
10792             }
10793           }
10794         }
10795     }
10796
10797     if (!(o->op_flags & OPf_SPECIAL) /* Wasn't written as CORE::require */
10798         /* handle override, if any */
10799      && (gv = gv_override("require", 7))) {
10800         OP *kid, *newop;
10801         if (o->op_flags & OPf_KIDS) {
10802             kid = cUNOPo->op_first;
10803             op_sibling_splice(o, NULL, -1, NULL);
10804         }
10805         else {
10806             kid = newDEFSVOP();
10807         }
10808         op_free(o);
10809         newop = S_new_entersubop(aTHX_ gv, kid);
10810         return newop;
10811     }
10812
10813     return ck_fun(o);
10814 }
10815
10816 OP *
10817 Perl_ck_return(pTHX_ OP *o)
10818 {
10819     OP *kid;
10820
10821     PERL_ARGS_ASSERT_CK_RETURN;
10822
10823     kid = OpSIBLING(cLISTOPo->op_first);
10824     if (CvLVALUE(PL_compcv)) {
10825         for (; kid; kid = OpSIBLING(kid))
10826             op_lvalue(kid, OP_LEAVESUBLV);
10827     }
10828
10829     return o;
10830 }
10831
10832 OP *
10833 Perl_ck_select(pTHX_ OP *o)
10834 {
10835     dVAR;
10836     OP* kid;
10837
10838     PERL_ARGS_ASSERT_CK_SELECT;
10839
10840     if (o->op_flags & OPf_KIDS) {
10841         kid = OpSIBLING(cLISTOPo->op_first);     /* get past pushmark */
10842         if (kid && OpHAS_SIBLING(kid)) {
10843             CHANGE_TYPE(o, OP_SSELECT);
10844             o = ck_fun(o);
10845             return fold_constants(op_integerize(op_std_init(o)));
10846         }
10847     }
10848     o = ck_fun(o);
10849     kid = OpSIBLING(cLISTOPo->op_first);    /* get past pushmark */
10850     if (kid && kid->op_type == OP_RV2GV)
10851         kid->op_private &= ~HINT_STRICT_REFS;
10852     return o;
10853 }
10854
10855 OP *
10856 Perl_ck_shift(pTHX_ OP *o)
10857 {
10858     const I32 type = o->op_type;
10859
10860     PERL_ARGS_ASSERT_CK_SHIFT;
10861
10862     if (!(o->op_flags & OPf_KIDS)) {
10863         OP *argop;
10864
10865         if (!CvUNIQUE(PL_compcv)) {
10866             o->op_flags |= OPf_SPECIAL;
10867             return o;
10868         }
10869
10870         argop = newUNOP(OP_RV2AV, 0, scalar(newGVOP(OP_GV, 0, PL_argvgv)));
10871         op_free(o);
10872         return newUNOP(type, 0, scalar(argop));
10873     }
10874     return scalar(ck_fun(o));
10875 }
10876
10877 OP *
10878 Perl_ck_sort(pTHX_ OP *o)
10879 {
10880     OP *firstkid;
10881     OP *kid;
10882     HV * const hinthv =
10883         PL_hints & HINT_LOCALIZE_HH ? GvHV(PL_hintgv) : NULL;
10884     U8 stacked;
10885
10886     PERL_ARGS_ASSERT_CK_SORT;
10887
10888     if (hinthv) {
10889             SV ** const svp = hv_fetchs(hinthv, "sort", FALSE);
10890             if (svp) {
10891                 const I32 sorthints = (I32)SvIV(*svp);
10892                 if ((sorthints & HINT_SORT_QUICKSORT) != 0)
10893                     o->op_private |= OPpSORT_QSORT;
10894                 if ((sorthints & HINT_SORT_STABLE) != 0)
10895                     o->op_private |= OPpSORT_STABLE;
10896             }
10897     }
10898
10899     if (o->op_flags & OPf_STACKED)
10900         simplify_sort(o);
10901     firstkid = OpSIBLING(cLISTOPo->op_first);           /* get past pushmark */
10902
10903     if ((stacked = o->op_flags & OPf_STACKED)) {        /* may have been cleared */
10904         OP *kid = cUNOPx(firstkid)->op_first;           /* get past null */
10905
10906         /* if the first arg is a code block, process it and mark sort as
10907          * OPf_SPECIAL */
10908         if (kid->op_type == OP_SCOPE || kid->op_type == OP_LEAVE) {
10909             LINKLIST(kid);
10910             if (kid->op_type == OP_LEAVE)
10911                     op_null(kid);                       /* wipe out leave */
10912             /* Prevent execution from escaping out of the sort block. */
10913             kid->op_next = 0;
10914
10915             /* provide scalar context for comparison function/block */
10916             kid = scalar(firstkid);
10917             kid->op_next = kid;
10918             o->op_flags |= OPf_SPECIAL;
10919         }
10920         else if (kid->op_type == OP_CONST
10921               && kid->op_private & OPpCONST_BARE) {
10922             char tmpbuf[256];
10923             STRLEN len;
10924             PADOFFSET off;
10925             const char * const name = SvPV(kSVOP_sv, len);
10926             *tmpbuf = '&';
10927             assert (len < 256);
10928             Copy(name, tmpbuf+1, len, char);
10929             off = pad_findmy_pvn(tmpbuf, len+1, SvUTF8(kSVOP_sv));
10930             if (off != NOT_IN_PAD) {
10931                 if (PAD_COMPNAME_FLAGS_isOUR(off)) {
10932                     SV * const fq =
10933                         newSVhek(HvNAME_HEK(PAD_COMPNAME_OURSTASH(off)));
10934                     sv_catpvs(fq, "::");
10935                     sv_catsv(fq, kSVOP_sv);
10936                     SvREFCNT_dec_NN(kSVOP_sv);
10937                     kSVOP->op_sv = fq;
10938                 }
10939                 else {
10940                     OP * const padop = newOP(OP_PADCV, 0);
10941                     padop->op_targ = off;
10942                     cUNOPx(firstkid)->op_first = padop;
10943 #ifdef PERL_OP_PARENT
10944                     padop->op_sibling = firstkid;
10945 #endif
10946                     op_free(kid);
10947                 }
10948             }
10949         }
10950
10951         firstkid = OpSIBLING(firstkid);
10952     }
10953
10954     for (kid = firstkid; kid; kid = OpSIBLING(kid)) {
10955         /* provide list context for arguments */
10956         list(kid);
10957         if (stacked)
10958             op_lvalue(kid, OP_GREPSTART);
10959     }
10960
10961     return o;
10962 }
10963
10964 /* for sort { X } ..., where X is one of
10965  *   $a <=> $b, $b <= $a, $a cmp $b, $b cmp $a
10966  * elide the second child of the sort (the one containing X),
10967  * and set these flags as appropriate
10968         OPpSORT_NUMERIC;
10969         OPpSORT_INTEGER;
10970         OPpSORT_DESCEND;
10971  * Also, check and warn on lexical $a, $b.
10972  */
10973
10974 STATIC void
10975 S_simplify_sort(pTHX_ OP *o)
10976 {
10977     OP *kid = OpSIBLING(cLISTOPo->op_first);    /* get past pushmark */
10978     OP *k;
10979     int descending;
10980     GV *gv;
10981     const char *gvname;
10982     bool have_scopeop;
10983
10984     PERL_ARGS_ASSERT_SIMPLIFY_SORT;
10985
10986     kid = kUNOP->op_first;                              /* get past null */
10987     if (!(have_scopeop = kid->op_type == OP_SCOPE)
10988      && kid->op_type != OP_LEAVE)
10989         return;
10990     kid = kLISTOP->op_last;                             /* get past scope */
10991     switch(kid->op_type) {
10992         case OP_NCMP:
10993         case OP_I_NCMP:
10994         case OP_SCMP:
10995             if (!have_scopeop) goto padkids;
10996             break;
10997         default:
10998             return;
10999     }
11000     k = kid;                                            /* remember this node*/
11001     if (kBINOP->op_first->op_type != OP_RV2SV
11002      || kBINOP->op_last ->op_type != OP_RV2SV)
11003     {
11004         /*
11005            Warn about my($a) or my($b) in a sort block, *if* $a or $b is
11006            then used in a comparison.  This catches most, but not
11007            all cases.  For instance, it catches
11008                sort { my($a); $a <=> $b }
11009            but not
11010                sort { my($a); $a < $b ? -1 : $a == $b ? 0 : 1; }
11011            (although why you'd do that is anyone's guess).
11012         */
11013
11014        padkids:
11015         if (!ckWARN(WARN_SYNTAX)) return;
11016         kid = kBINOP->op_first;
11017         do {
11018             if (kid->op_type == OP_PADSV) {
11019                 PADNAME * const name = PAD_COMPNAME(kid->op_targ);
11020                 if (PadnameLEN(name) == 2 && *PadnamePV(name) == '$'
11021                  && (  PadnamePV(name)[1] == 'a'
11022                     || PadnamePV(name)[1] == 'b'  ))
11023                     /* diag_listed_as: "my %s" used in sort comparison */
11024                     Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
11025                                      "\"%s %s\" used in sort comparison",
11026                                       PadnameIsSTATE(name)
11027                                         ? "state"
11028                                         : "my",
11029                                       PadnamePV(name));
11030             }
11031         } while ((kid = OpSIBLING(kid)));
11032         return;
11033     }
11034     kid = kBINOP->op_first;                             /* get past cmp */
11035     if (kUNOP->op_first->op_type != OP_GV)
11036         return;
11037     kid = kUNOP->op_first;                              /* get past rv2sv */
11038     gv = kGVOP_gv;
11039     if (GvSTASH(gv) != PL_curstash)
11040         return;
11041     gvname = GvNAME(gv);
11042     if (*gvname == 'a' && gvname[1] == '\0')
11043         descending = 0;
11044     else if (*gvname == 'b' && gvname[1] == '\0')
11045         descending = 1;
11046     else
11047         return;
11048
11049     kid = k;                                            /* back to cmp */
11050     /* already checked above that it is rv2sv */
11051     kid = kBINOP->op_last;                              /* down to 2nd arg */
11052     if (kUNOP->op_first->op_type != OP_GV)
11053         return;
11054     kid = kUNOP->op_first;                              /* get past rv2sv */
11055     gv = kGVOP_gv;
11056     if (GvSTASH(gv) != PL_curstash)
11057         return;
11058     gvname = GvNAME(gv);
11059     if ( descending
11060          ? !(*gvname == 'a' && gvname[1] == '\0')
11061          : !(*gvname == 'b' && gvname[1] == '\0'))
11062         return;
11063     o->op_flags &= ~(OPf_STACKED | OPf_SPECIAL);
11064     if (descending)
11065         o->op_private |= OPpSORT_DESCEND;
11066     if (k->op_type == OP_NCMP)
11067         o->op_private |= OPpSORT_NUMERIC;
11068     if (k->op_type == OP_I_NCMP)
11069         o->op_private |= OPpSORT_NUMERIC | OPpSORT_INTEGER;
11070     kid = OpSIBLING(cLISTOPo->op_first);
11071     /* cut out and delete old block (second sibling) */
11072     op_sibling_splice(o, cLISTOPo->op_first, 1, NULL);
11073     op_free(kid);
11074 }
11075
11076 OP *
11077 Perl_ck_split(pTHX_ OP *o)
11078 {
11079     dVAR;
11080     OP *kid;
11081
11082     PERL_ARGS_ASSERT_CK_SPLIT;
11083
11084     if (o->op_flags & OPf_STACKED)
11085         return no_fh_allowed(o);
11086
11087     kid = cLISTOPo->op_first;
11088     if (kid->op_type != OP_NULL)
11089         Perl_croak(aTHX_ "panic: ck_split, type=%u", (unsigned) kid->op_type);
11090     /* delete leading NULL node, then add a CONST if no other nodes */
11091     op_sibling_splice(o, NULL, 1,
11092         OpHAS_SIBLING(kid) ? NULL : newSVOP(OP_CONST, 0, newSVpvs(" ")));
11093     op_free(kid);
11094     kid = cLISTOPo->op_first;
11095
11096     if (kid->op_type != OP_MATCH || kid->op_flags & OPf_STACKED) {
11097         /* remove kid, and replace with new optree */
11098         op_sibling_splice(o, NULL, 1, NULL);
11099         /* OPf_SPECIAL is used to trigger split " " behavior */
11100         kid = pmruntime( newPMOP(OP_MATCH, OPf_SPECIAL), kid, NULL, 0, 0);
11101         op_sibling_splice(o, NULL, 0, kid);
11102     }
11103     CHANGE_TYPE(kid, OP_PUSHRE);
11104     /* target implies @ary=..., so wipe it */
11105     kid->op_targ = 0;
11106     scalar(kid);
11107     if (((PMOP *)kid)->op_pmflags & PMf_GLOBAL) {
11108       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
11109                      "Use of /g modifier is meaningless in split");
11110     }
11111
11112     if (!OpHAS_SIBLING(kid))
11113         op_append_elem(OP_SPLIT, o, newDEFSVOP());
11114
11115     kid = OpSIBLING(kid);
11116     assert(kid);
11117     scalar(kid);
11118
11119     if (!OpHAS_SIBLING(kid))
11120     {
11121         op_append_elem(OP_SPLIT, o, newSVOP(OP_CONST, 0, newSViv(0)));
11122         o->op_private |= OPpSPLIT_IMPLIM;
11123     }
11124     assert(OpHAS_SIBLING(kid));
11125
11126     kid = OpSIBLING(kid);
11127     scalar(kid);
11128
11129     if (OpHAS_SIBLING(kid))
11130         return too_many_arguments_pv(o,OP_DESC(o), 0);
11131
11132     return o;
11133 }
11134
11135 OP *
11136 Perl_ck_stringify(pTHX_ OP *o)
11137 {
11138     OP * const kid = OpSIBLING(cUNOPo->op_first);
11139     PERL_ARGS_ASSERT_CK_STRINGIFY;
11140     if (kid->op_type == OP_JOIN || kid->op_type == OP_QUOTEMETA
11141      || kid->op_type == OP_LC   || kid->op_type == OP_LCFIRST
11142      || kid->op_type == OP_UC   || kid->op_type == OP_UCFIRST)
11143     {
11144         assert(!OpHAS_SIBLING(kid));
11145         op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
11146         op_free(o);
11147         return kid;
11148     }
11149     return ck_fun(o);
11150 }
11151         
11152 OP *
11153 Perl_ck_join(pTHX_ OP *o)
11154 {
11155     OP * const kid = OpSIBLING(cLISTOPo->op_first);
11156
11157     PERL_ARGS_ASSERT_CK_JOIN;
11158
11159     if (kid && kid->op_type == OP_MATCH) {
11160         if (ckWARN(WARN_SYNTAX)) {
11161             const REGEXP *re = PM_GETRE(kPMOP);
11162             const SV *msg = re
11163                     ? newSVpvn_flags( RX_PRECOMP_const(re), RX_PRELEN(re),
11164                                             SVs_TEMP | ( RX_UTF8(re) ? SVf_UTF8 : 0 ) )
11165                     : newSVpvs_flags( "STRING", SVs_TEMP );
11166             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
11167                         "/%"SVf"/ should probably be written as \"%"SVf"\"",
11168                         SVfARG(msg), SVfARG(msg));
11169         }
11170     }
11171     if (kid
11172      && (kid->op_type == OP_CONST /* an innocent, unsuspicious separator */
11173         || (kid->op_type == OP_PADSV && !(kid->op_private & OPpLVAL_INTRO))
11174         || (  kid->op_type==OP_RV2SV && kUNOP->op_first->op_type == OP_GV
11175            && !(kid->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))))
11176     {
11177         const OP * const bairn = OpSIBLING(kid); /* the list */
11178         if (bairn && !OpHAS_SIBLING(bairn) /* single-item list */
11179          && OP_GIMME(bairn,0) == G_SCALAR)
11180         {
11181             OP * const ret = op_convert_list(OP_STRINGIFY, OPf_FOLDED,
11182                                      op_sibling_splice(o, kid, 1, NULL));
11183             op_free(o);
11184             return ret;
11185         }
11186     }
11187
11188     return ck_fun(o);
11189 }
11190
11191 /*
11192 =for apidoc Am|CV *|rv2cv_op_cv|OP *cvop|U32 flags
11193
11194 Examines an op, which is expected to identify a subroutine at runtime,
11195 and attempts to determine at compile time which subroutine it identifies.
11196 This is normally used during Perl compilation to determine whether
11197 a prototype can be applied to a function call.  I<cvop> is the op
11198 being considered, normally an C<rv2cv> op.  A pointer to the identified
11199 subroutine is returned, if it could be determined statically, and a null
11200 pointer is returned if it was not possible to determine statically.
11201
11202 Currently, the subroutine can be identified statically if the RV that the
11203 C<rv2cv> is to operate on is provided by a suitable C<gv> or C<const> op.
11204 A C<gv> op is suitable if the GV's CV slot is populated.  A C<const> op is
11205 suitable if the constant value must be an RV pointing to a CV.  Details of
11206 this process may change in future versions of Perl.  If the C<rv2cv> op
11207 has the C<OPpENTERSUB_AMPER> flag set then no attempt is made to identify
11208 the subroutine statically: this flag is used to suppress compile-time
11209 magic on a subroutine call, forcing it to use default runtime behaviour.
11210
11211 If I<flags> has the bit C<RV2CVOPCV_MARK_EARLY> set, then the handling
11212 of a GV reference is modified.  If a GV was examined and its CV slot was
11213 found to be empty, then the C<gv> op has the C<OPpEARLY_CV> flag set.
11214 If the op is not optimised away, and the CV slot is later populated with
11215 a subroutine having a prototype, that flag eventually triggers the warning
11216 "called too early to check prototype".
11217
11218 If I<flags> has the bit C<RV2CVOPCV_RETURN_NAME_GV> set, then instead
11219 of returning a pointer to the subroutine it returns a pointer to the
11220 GV giving the most appropriate name for the subroutine in this context.
11221 Normally this is just the C<CvGV> of the subroutine, but for an anonymous
11222 (C<CvANON>) subroutine that is referenced through a GV it will be the
11223 referencing GV.  The resulting C<GV*> is cast to C<CV*> to be returned.
11224 A null pointer is returned as usual if there is no statically-determinable
11225 subroutine.
11226
11227 =cut
11228 */
11229
11230 /* shared by toke.c:yylex */
11231 CV *
11232 Perl_find_lexical_cv(pTHX_ PADOFFSET off)
11233 {
11234     PADNAME *name = PAD_COMPNAME(off);
11235     CV *compcv = PL_compcv;
11236     while (PadnameOUTER(name)) {
11237         assert(PARENT_PAD_INDEX(name));
11238         compcv = CvOUTSIDE(PL_compcv);
11239         name = PadlistNAMESARRAY(CvPADLIST(compcv))
11240                 [off = PARENT_PAD_INDEX(name)];
11241     }
11242     assert(!PadnameIsOUR(name));
11243     if (!PadnameIsSTATE(name) && PadnamePROTOCV(name)) {
11244         return PadnamePROTOCV(name);
11245     }
11246     return (CV *)AvARRAY(PadlistARRAY(CvPADLIST(compcv))[1])[off];
11247 }
11248
11249 CV *
11250 Perl_rv2cv_op_cv(pTHX_ OP *cvop, U32 flags)
11251 {
11252     OP *rvop;
11253     CV *cv;
11254     GV *gv;
11255     PERL_ARGS_ASSERT_RV2CV_OP_CV;
11256     if (flags & ~RV2CVOPCV_FLAG_MASK)
11257         Perl_croak(aTHX_ "panic: rv2cv_op_cv bad flags %x", (unsigned)flags);
11258     if (cvop->op_type != OP_RV2CV)
11259         return NULL;
11260     if (cvop->op_private & OPpENTERSUB_AMPER)
11261         return NULL;
11262     if (!(cvop->op_flags & OPf_KIDS))
11263         return NULL;
11264     rvop = cUNOPx(cvop)->op_first;
11265     switch (rvop->op_type) {
11266         case OP_GV: {
11267             gv = cGVOPx_gv(rvop);
11268             if (!isGV(gv)) {
11269                 if (SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV) {
11270                     cv = MUTABLE_CV(SvRV(gv));
11271                     gv = NULL;
11272                     break;
11273                 }
11274                 if (flags & RV2CVOPCV_RETURN_STUB)
11275                     return (CV *)gv;
11276                 else return NULL;
11277             }
11278             cv = GvCVu(gv);
11279             if (!cv) {
11280                 if (flags & RV2CVOPCV_MARK_EARLY)
11281                     rvop->op_private |= OPpEARLY_CV;
11282                 return NULL;
11283             }
11284         } break;
11285         case OP_CONST: {
11286             SV *rv = cSVOPx_sv(rvop);
11287             if (!SvROK(rv))
11288                 return NULL;
11289             cv = (CV*)SvRV(rv);
11290             gv = NULL;
11291         } break;
11292         case OP_PADCV: {
11293             cv = find_lexical_cv(rvop->op_targ);
11294             gv = NULL;
11295         } break;
11296         default: {
11297             return NULL;
11298         } NOT_REACHED; /* NOTREACHED */
11299     }
11300     if (SvTYPE((SV*)cv) != SVt_PVCV)
11301         return NULL;
11302     if (flags & (RV2CVOPCV_RETURN_NAME_GV|RV2CVOPCV_MAYBE_NAME_GV)) {
11303         if ((!CvANON(cv) || !gv) && !CvLEXICAL(cv)
11304          && ((flags & RV2CVOPCV_RETURN_NAME_GV) || !CvNAMED(cv)))
11305             gv = CvGV(cv);
11306         return (CV*)gv;
11307     } else {
11308         return cv;
11309     }
11310 }
11311
11312 /*
11313 =for apidoc Am|OP *|ck_entersub_args_list|OP *entersubop
11314
11315 Performs the default fixup of the arguments part of an C<entersub>
11316 op tree.  This consists of applying list context to each of the
11317 argument ops.  This is the standard treatment used on a call marked
11318 with C<&>, or a method call, or a call through a subroutine reference,
11319 or any other call where the callee can't be identified at compile time,
11320 or a call where the callee has no prototype.
11321
11322 =cut
11323 */
11324
11325 OP *
11326 Perl_ck_entersub_args_list(pTHX_ OP *entersubop)
11327 {
11328     OP *aop;
11329     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_LIST;
11330     aop = cUNOPx(entersubop)->op_first;
11331     if (!OpHAS_SIBLING(aop))
11332         aop = cUNOPx(aop)->op_first;
11333     for (aop = OpSIBLING(aop); OpHAS_SIBLING(aop); aop = OpSIBLING(aop)) {
11334         list(aop);
11335         op_lvalue(aop, OP_ENTERSUB);
11336     }
11337     return entersubop;
11338 }
11339
11340 /*
11341 =for apidoc Am|OP *|ck_entersub_args_proto|OP *entersubop|GV *namegv|SV *protosv
11342
11343 Performs the fixup of the arguments part of an C<entersub> op tree
11344 based on a subroutine prototype.  This makes various modifications to
11345 the argument ops, from applying context up to inserting C<refgen> ops,
11346 and checking the number and syntactic types of arguments, as directed by
11347 the prototype.  This is the standard treatment used on a subroutine call,
11348 not marked with C<&>, where the callee can be identified at compile time
11349 and has a prototype.
11350
11351 I<protosv> supplies the subroutine prototype to be applied to the call.
11352 It may be a normal defined scalar, of which the string value will be used.
11353 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
11354 that has been cast to C<SV*>) which has a prototype.  The prototype
11355 supplied, in whichever form, does not need to match the actual callee
11356 referenced by the op tree.
11357
11358 If the argument ops disagree with the prototype, for example by having
11359 an unacceptable number of arguments, a valid op tree is returned anyway.
11360 The error is reflected in the parser state, normally resulting in a single
11361 exception at the top level of parsing which covers all the compilation
11362 errors that occurred.  In the error message, the callee is referred to
11363 by the name defined by the I<namegv> parameter.
11364
11365 =cut
11366 */
11367
11368 OP *
11369 Perl_ck_entersub_args_proto(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
11370 {
11371     STRLEN proto_len;
11372     const char *proto, *proto_end;
11373     OP *aop, *prev, *cvop, *parent;
11374     int optional = 0;
11375     I32 arg = 0;
11376     I32 contextclass = 0;
11377     const char *e = NULL;
11378     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO;
11379     if (SvTYPE(protosv) == SVt_PVCV ? !SvPOK(protosv) : !SvOK(protosv))
11380         Perl_croak(aTHX_ "panic: ck_entersub_args_proto CV with no proto, "
11381                    "flags=%lx", (unsigned long) SvFLAGS(protosv));
11382     if (SvTYPE(protosv) == SVt_PVCV)
11383          proto = CvPROTO(protosv), proto_len = CvPROTOLEN(protosv);
11384     else proto = SvPV(protosv, proto_len);
11385     proto = S_strip_spaces(aTHX_ proto, &proto_len);
11386     proto_end = proto + proto_len;
11387     parent = entersubop;
11388     aop = cUNOPx(entersubop)->op_first;
11389     if (!OpHAS_SIBLING(aop)) {
11390         parent = aop;
11391         aop = cUNOPx(aop)->op_first;
11392     }
11393     prev = aop;
11394     aop = OpSIBLING(aop);
11395     for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
11396     while (aop != cvop) {
11397         OP* o3 = aop;
11398
11399         if (proto >= proto_end)
11400         {
11401             SV * const namesv = cv_name((CV *)namegv, NULL, 0);
11402             yyerror_pv(Perl_form(aTHX_ "Too many arguments for %"SVf,
11403                                         SVfARG(namesv)), SvUTF8(namesv));
11404             return entersubop;
11405         }
11406
11407         switch (*proto) {
11408             case ';':
11409                 optional = 1;
11410                 proto++;
11411                 continue;
11412             case '_':
11413                 /* _ must be at the end */
11414                 if (proto[1] && !strchr(";@%", proto[1]))
11415                     goto oops;
11416                 /* FALLTHROUGH */
11417             case '$':
11418                 proto++;
11419                 arg++;
11420                 scalar(aop);
11421                 break;
11422             case '%':
11423             case '@':
11424                 list(aop);
11425                 arg++;
11426                 break;
11427             case '&':
11428                 proto++;
11429                 arg++;
11430                 if (o3->op_type != OP_SREFGEN
11431                  || (  cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
11432                         != OP_ANONCODE
11433                     && cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
11434                         != OP_RV2CV))
11435                     bad_type_gv(arg, namegv, o3,
11436                             arg == 1 ? "block or sub {}" : "sub {}");
11437                 break;
11438             case '*':
11439                 /* '*' allows any scalar type, including bareword */
11440                 proto++;
11441                 arg++;
11442                 if (o3->op_type == OP_RV2GV)
11443                     goto wrapref;       /* autoconvert GLOB -> GLOBref */
11444                 else if (o3->op_type == OP_CONST)
11445                     o3->op_private &= ~OPpCONST_STRICT;
11446                 scalar(aop);
11447                 break;
11448             case '+':
11449                 proto++;
11450                 arg++;
11451                 if (o3->op_type == OP_RV2AV ||
11452                     o3->op_type == OP_PADAV ||
11453                     o3->op_type == OP_RV2HV ||
11454                     o3->op_type == OP_PADHV
11455                 ) {
11456                     goto wrapref;
11457                 }
11458                 scalar(aop);
11459                 break;
11460             case '[': case ']':
11461                 goto oops;
11462
11463             case '\\':
11464                 proto++;
11465                 arg++;
11466             again:
11467                 switch (*proto++) {
11468                     case '[':
11469                         if (contextclass++ == 0) {
11470                             e = strchr(proto, ']');
11471                             if (!e || e == proto)
11472                                 goto oops;
11473                         }
11474                         else
11475                             goto oops;
11476                         goto again;
11477
11478                     case ']':
11479                         if (contextclass) {
11480                             const char *p = proto;
11481                             const char *const end = proto;
11482                             contextclass = 0;
11483                             while (*--p != '[')
11484                                 /* \[$] accepts any scalar lvalue */
11485                                 if (*p == '$'
11486                                  && Perl_op_lvalue_flags(aTHX_
11487                                      scalar(o3),
11488                                      OP_READ, /* not entersub */
11489                                      OP_LVALUE_NO_CROAK
11490                                     )) goto wrapref;
11491                             bad_type_gv(arg, namegv, o3,
11492                                     Perl_form(aTHX_ "one of %.*s",(int)(end - p), p));
11493                         } else
11494                             goto oops;
11495                         break;
11496                     case '*':
11497                         if (o3->op_type == OP_RV2GV)
11498                             goto wrapref;
11499                         if (!contextclass)
11500                             bad_type_gv(arg, namegv, o3, "symbol");
11501                         break;
11502                     case '&':
11503                         if (o3->op_type == OP_ENTERSUB
11504                          && !(o3->op_flags & OPf_STACKED))
11505                             goto wrapref;
11506                         if (!contextclass)
11507                             bad_type_gv(arg, namegv, o3, "subroutine");
11508                         break;
11509                     case '$':
11510                         if (o3->op_type == OP_RV2SV ||
11511                                 o3->op_type == OP_PADSV ||
11512                                 o3->op_type == OP_HELEM ||
11513                                 o3->op_type == OP_AELEM)
11514                             goto wrapref;
11515                         if (!contextclass) {
11516                             /* \$ accepts any scalar lvalue */
11517                             if (Perl_op_lvalue_flags(aTHX_
11518                                     scalar(o3),
11519                                     OP_READ,  /* not entersub */
11520                                     OP_LVALUE_NO_CROAK
11521                                )) goto wrapref;
11522                             bad_type_gv(arg, namegv, o3, "scalar");
11523                         }
11524                         break;
11525                     case '@':
11526                         if (o3->op_type == OP_RV2AV ||
11527                                 o3->op_type == OP_PADAV)
11528                         {
11529                             o3->op_flags &=~ OPf_PARENS;
11530                             goto wrapref;
11531                         }
11532                         if (!contextclass)
11533                             bad_type_gv(arg, namegv, o3, "array");
11534                         break;
11535                     case '%':
11536                         if (o3->op_type == OP_RV2HV ||
11537                                 o3->op_type == OP_PADHV)
11538                         {
11539                             o3->op_flags &=~ OPf_PARENS;
11540                             goto wrapref;
11541                         }
11542                         if (!contextclass)
11543                             bad_type_gv(arg, namegv, o3, "hash");
11544                         break;
11545                     wrapref:
11546                             aop = S_op_sibling_newUNOP(aTHX_ parent, prev,
11547                                                 OP_REFGEN, 0);
11548                         if (contextclass && e) {
11549                             proto = e + 1;
11550                             contextclass = 0;
11551                         }
11552                         break;
11553                     default: goto oops;
11554                 }
11555                 if (contextclass)
11556                     goto again;
11557                 break;
11558             case ' ':
11559                 proto++;
11560                 continue;
11561             default:
11562             oops: {
11563                 Perl_croak(aTHX_ "Malformed prototype for %"SVf": %"SVf,
11564                                   SVfARG(cv_name((CV *)namegv, NULL, 0)),
11565                                   SVfARG(protosv));
11566             }
11567         }
11568
11569         op_lvalue(aop, OP_ENTERSUB);
11570         prev = aop;
11571         aop = OpSIBLING(aop);
11572     }
11573     if (aop == cvop && *proto == '_') {
11574         /* generate an access to $_ */
11575         op_sibling_splice(parent, prev, 0, newDEFSVOP());
11576     }
11577     if (!optional && proto_end > proto &&
11578         (*proto != '@' && *proto != '%' && *proto != ';' && *proto != '_'))
11579     {
11580         SV * const namesv = cv_name((CV *)namegv, NULL, 0);
11581         yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %"SVf,
11582                                     SVfARG(namesv)), SvUTF8(namesv));
11583     }
11584     return entersubop;
11585 }
11586
11587 /*
11588 =for apidoc Am|OP *|ck_entersub_args_proto_or_list|OP *entersubop|GV *namegv|SV *protosv
11589
11590 Performs the fixup of the arguments part of an C<entersub> op tree either
11591 based on a subroutine prototype or using default list-context processing.
11592 This is the standard treatment used on a subroutine call, not marked
11593 with C<&>, where the callee can be identified at compile time.
11594
11595 I<protosv> supplies the subroutine prototype to be applied to the call,
11596 or indicates that there is no prototype.  It may be a normal scalar,
11597 in which case if it is defined then the string value will be used
11598 as a prototype, and if it is undefined then there is no prototype.
11599 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
11600 that has been cast to C<SV*>), of which the prototype will be used if it
11601 has one.  The prototype (or lack thereof) supplied, in whichever form,
11602 does not need to match the actual callee referenced by the op tree.
11603
11604 If the argument ops disagree with the prototype, for example by having
11605 an unacceptable number of arguments, a valid op tree is returned anyway.
11606 The error is reflected in the parser state, normally resulting in a single
11607 exception at the top level of parsing which covers all the compilation
11608 errors that occurred.  In the error message, the callee is referred to
11609 by the name defined by the I<namegv> parameter.
11610
11611 =cut
11612 */
11613
11614 OP *
11615 Perl_ck_entersub_args_proto_or_list(pTHX_ OP *entersubop,
11616         GV *namegv, SV *protosv)
11617 {
11618     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO_OR_LIST;
11619     if (SvTYPE(protosv) == SVt_PVCV ? SvPOK(protosv) : SvOK(protosv))
11620         return ck_entersub_args_proto(entersubop, namegv, protosv);
11621     else
11622         return ck_entersub_args_list(entersubop);
11623 }
11624
11625 OP *
11626 Perl_ck_entersub_args_core(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
11627 {
11628     int opnum = SvTYPE(protosv) == SVt_PVCV ? 0 : (int)SvUV(protosv);
11629     OP *aop = cUNOPx(entersubop)->op_first;
11630
11631     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_CORE;
11632
11633     if (!opnum) {
11634         OP *cvop;
11635         if (!OpHAS_SIBLING(aop))
11636             aop = cUNOPx(aop)->op_first;
11637         aop = OpSIBLING(aop);
11638         for (cvop = aop; OpSIBLING(cvop); cvop = OpSIBLING(cvop)) ;
11639         if (aop != cvop)
11640             (void)too_many_arguments_pv(entersubop, GvNAME(namegv), 0);
11641         
11642         op_free(entersubop);
11643         switch(GvNAME(namegv)[2]) {
11644         case 'F': return newSVOP(OP_CONST, 0,
11645                                         newSVpv(CopFILE(PL_curcop),0));
11646         case 'L': return newSVOP(
11647                            OP_CONST, 0,
11648                            Perl_newSVpvf(aTHX_
11649                              "%"IVdf, (IV)CopLINE(PL_curcop)
11650                            )
11651                          );
11652         case 'P': return newSVOP(OP_CONST, 0,
11653                                    (PL_curstash
11654                                      ? newSVhek(HvNAME_HEK(PL_curstash))
11655                                      : &PL_sv_undef
11656                                    )
11657                                 );
11658         }
11659         NOT_REACHED; /* NOTREACHED */
11660     }
11661     else {
11662         OP *prev, *cvop, *first, *parent;
11663         U32 flags = 0;
11664
11665         parent = entersubop;
11666         if (!OpHAS_SIBLING(aop)) {
11667             parent = aop;
11668             aop = cUNOPx(aop)->op_first;
11669         }
11670         
11671         first = prev = aop;
11672         aop = OpSIBLING(aop);
11673         /* find last sibling */
11674         for (cvop = aop;
11675              OpHAS_SIBLING(cvop);
11676              prev = cvop, cvop = OpSIBLING(cvop))
11677             ;
11678         if (!(cvop->op_private & OPpENTERSUB_NOPAREN)
11679             /* Usually, OPf_SPECIAL on an op with no args means that it had
11680              * parens, but these have their own meaning for that flag: */
11681             && opnum != OP_VALUES && opnum != OP_KEYS && opnum != OP_EACH
11682             && opnum != OP_DELETE && opnum != OP_EXISTS)
11683                 flags |= OPf_SPECIAL;
11684         /* excise cvop from end of sibling chain */
11685         op_sibling_splice(parent, prev, 1, NULL);
11686         op_free(cvop);
11687         if (aop == cvop) aop = NULL;
11688
11689         /* detach remaining siblings from the first sibling, then
11690          * dispose of original optree */
11691
11692         if (aop)
11693             op_sibling_splice(parent, first, -1, NULL);
11694         op_free(entersubop);
11695
11696         if (opnum == OP_ENTEREVAL
11697          && GvNAMELEN(namegv)==9 && strnEQ(GvNAME(namegv), "evalbytes", 9))
11698             flags |= OPpEVAL_BYTES <<8;
11699         
11700         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
11701         case OA_UNOP:
11702         case OA_BASEOP_OR_UNOP:
11703         case OA_FILESTATOP:
11704             return aop ? newUNOP(opnum,flags,aop) : newOP(opnum,flags);
11705         case OA_BASEOP:
11706             if (aop) {
11707                     (void)too_many_arguments_pv(aop, GvNAME(namegv), 0);
11708                 op_free(aop);
11709             }
11710             return opnum == OP_RUNCV
11711                 ? newPVOP(OP_RUNCV,0,NULL)
11712                 : newOP(opnum,0);
11713         default:
11714             return op_convert_list(opnum,0,aop);
11715         }
11716     }
11717     NOT_REACHED; /* NOTREACHED */
11718     return entersubop;
11719 }
11720
11721 /*
11722 =for apidoc Am|void|cv_get_call_checker|CV *cv|Perl_call_checker *ckfun_p|SV **ckobj_p
11723
11724 Retrieves the function that will be used to fix up a call to I<cv>.
11725 Specifically, the function is applied to an C<entersub> op tree for a
11726 subroutine call, not marked with C<&>, where the callee can be identified
11727 at compile time as I<cv>.
11728
11729 The C-level function pointer is returned in I<*ckfun_p>, and an SV
11730 argument for it is returned in I<*ckobj_p>.  The function is intended
11731 to be called in this manner:
11732
11733     entersubop = (*ckfun_p)(aTHX_ entersubop, namegv, (*ckobj_p));
11734
11735 In this call, I<entersubop> is a pointer to the C<entersub> op,
11736 which may be replaced by the check function, and I<namegv> is a GV
11737 supplying the name that should be used by the check function to refer
11738 to the callee of the C<entersub> op if it needs to emit any diagnostics.
11739 It is permitted to apply the check function in non-standard situations,
11740 such as to a call to a different subroutine or to a method call.
11741
11742 By default, the function is
11743 L<Perl_ck_entersub_args_proto_or_list|/ck_entersub_args_proto_or_list>,
11744 and the SV parameter is I<cv> itself.  This implements standard
11745 prototype processing.  It can be changed, for a particular subroutine,
11746 by L</cv_set_call_checker>.
11747
11748 =cut
11749 */
11750
11751 static void
11752 S_cv_get_call_checker(CV *cv, Perl_call_checker *ckfun_p, SV **ckobj_p,
11753                       U8 *flagsp)
11754 {
11755     MAGIC *callmg;
11756     callmg = SvMAGICAL((SV*)cv) ? mg_find((SV*)cv, PERL_MAGIC_checkcall) : NULL;
11757     if (callmg) {
11758         *ckfun_p = DPTR2FPTR(Perl_call_checker, callmg->mg_ptr);
11759         *ckobj_p = callmg->mg_obj;
11760         if (flagsp) *flagsp = callmg->mg_flags;
11761     } else {
11762         *ckfun_p = Perl_ck_entersub_args_proto_or_list;
11763         *ckobj_p = (SV*)cv;
11764         if (flagsp) *flagsp = 0;
11765     }
11766 }
11767
11768 void
11769 Perl_cv_get_call_checker(pTHX_ CV *cv, Perl_call_checker *ckfun_p, SV **ckobj_p)
11770 {
11771     PERL_ARGS_ASSERT_CV_GET_CALL_CHECKER;
11772     PERL_UNUSED_CONTEXT;
11773     S_cv_get_call_checker(cv, ckfun_p, ckobj_p, NULL);
11774 }
11775
11776 /*
11777 =for apidoc Am|void|cv_set_call_checker_flags|CV *cv|Perl_call_checker ckfun|SV *ckobj|U32 flags
11778
11779 Sets the function that will be used to fix up a call to I<cv>.
11780 Specifically, the function is applied to an C<entersub> op tree for a
11781 subroutine call, not marked with C<&>, where the callee can be identified
11782 at compile time as I<cv>.
11783
11784 The C-level function pointer is supplied in I<ckfun>, and an SV argument
11785 for it is supplied in I<ckobj>.  The function should be defined like this:
11786
11787     STATIC OP * ckfun(pTHX_ OP *op, GV *namegv, SV *ckobj)
11788
11789 It is intended to be called in this manner:
11790
11791     entersubop = ckfun(aTHX_ entersubop, namegv, ckobj);
11792
11793 In this call, I<entersubop> is a pointer to the C<entersub> op,
11794 which may be replaced by the check function, and I<namegv> supplies
11795 the name that should be used by the check function to refer
11796 to the callee of the C<entersub> op if it needs to emit any diagnostics.
11797 It is permitted to apply the check function in non-standard situations,
11798 such as to a call to a different subroutine or to a method call.
11799
11800 I<namegv> may not actually be a GV.  For efficiency, perl may pass a
11801 CV or other SV instead.  Whatever is passed can be used as the first
11802 argument to L</cv_name>.  You can force perl to pass a GV by including
11803 C<CALL_CHECKER_REQUIRE_GV> in the I<flags>.
11804
11805 The current setting for a particular CV can be retrieved by
11806 L</cv_get_call_checker>.
11807
11808 =for apidoc Am|void|cv_set_call_checker|CV *cv|Perl_call_checker ckfun|SV *ckobj
11809
11810 The original form of L</cv_set_call_checker_flags>, which passes it the
11811 C<CALL_CHECKER_REQUIRE_GV> flag for backward-compatibility.
11812
11813 =cut
11814 */
11815
11816 void
11817 Perl_cv_set_call_checker(pTHX_ CV *cv, Perl_call_checker ckfun, SV *ckobj)
11818 {
11819     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER;
11820     cv_set_call_checker_flags(cv, ckfun, ckobj, CALL_CHECKER_REQUIRE_GV);
11821 }
11822
11823 void
11824 Perl_cv_set_call_checker_flags(pTHX_ CV *cv, Perl_call_checker ckfun,
11825                                      SV *ckobj, U32 flags)
11826 {
11827     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER_FLAGS;
11828     if (ckfun == Perl_ck_entersub_args_proto_or_list && ckobj == (SV*)cv) {
11829         if (SvMAGICAL((SV*)cv))
11830             mg_free_type((SV*)cv, PERL_MAGIC_checkcall);
11831     } else {
11832         MAGIC *callmg;
11833         sv_magic((SV*)cv, &PL_sv_undef, PERL_MAGIC_checkcall, NULL, 0);
11834         callmg = mg_find((SV*)cv, PERL_MAGIC_checkcall);
11835         assert(callmg);
11836         if (callmg->mg_flags & MGf_REFCOUNTED) {
11837             SvREFCNT_dec(callmg->mg_obj);
11838             callmg->mg_flags &= ~MGf_REFCOUNTED;
11839         }
11840         callmg->mg_ptr = FPTR2DPTR(char *, ckfun);
11841         callmg->mg_obj = ckobj;
11842         if (ckobj != (SV*)cv) {
11843             SvREFCNT_inc_simple_void_NN(ckobj);
11844             callmg->mg_flags |= MGf_REFCOUNTED;
11845         }
11846         callmg->mg_flags = (callmg->mg_flags &~ MGf_REQUIRE_GV)
11847                          | (U8)(flags & MGf_REQUIRE_GV) | MGf_COPY;
11848     }
11849 }
11850
11851 static void
11852 S_entersub_alloc_targ(pTHX_ OP * const o)
11853 {
11854     o->op_targ = pad_alloc(OP_ENTERSUB, SVs_PADTMP);
11855     o->op_private |= OPpENTERSUB_HASTARG;
11856 }
11857
11858 OP *
11859 Perl_ck_subr(pTHX_ OP *o)
11860 {
11861     OP *aop, *cvop;
11862     CV *cv;
11863     GV *namegv;
11864     SV **const_class = NULL;
11865
11866     PERL_ARGS_ASSERT_CK_SUBR;
11867
11868     aop = cUNOPx(o)->op_first;
11869     if (!OpHAS_SIBLING(aop))
11870         aop = cUNOPx(aop)->op_first;
11871     aop = OpSIBLING(aop);
11872     for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
11873     cv = rv2cv_op_cv(cvop, RV2CVOPCV_MARK_EARLY);
11874     namegv = cv ? (GV*)rv2cv_op_cv(cvop, RV2CVOPCV_MAYBE_NAME_GV) : NULL;
11875
11876     o->op_private &= ~1;
11877     o->op_private |= (PL_hints & HINT_STRICT_REFS);
11878     if (PERLDB_SUB && PL_curstash != PL_debstash)
11879         o->op_private |= OPpENTERSUB_DB;
11880     switch (cvop->op_type) {
11881         case OP_RV2CV:
11882             o->op_private |= (cvop->op_private & OPpENTERSUB_AMPER);
11883             op_null(cvop);
11884             break;
11885         case OP_METHOD:
11886         case OP_METHOD_NAMED:
11887         case OP_METHOD_SUPER:
11888         case OP_METHOD_REDIR:
11889         case OP_METHOD_REDIR_SUPER:
11890             if (aop->op_type == OP_CONST) {
11891                 aop->op_private &= ~OPpCONST_STRICT;
11892                 const_class = &cSVOPx(aop)->op_sv;
11893             }
11894             else if (aop->op_type == OP_LIST) {
11895                 OP * const sib = OpSIBLING(((UNOP*)aop)->op_first);
11896                 if (sib && sib->op_type == OP_CONST) {
11897                     sib->op_private &= ~OPpCONST_STRICT;
11898                     const_class = &cSVOPx(sib)->op_sv;
11899                 }
11900             }
11901             /* make class name a shared cow string to speedup method calls */
11902             /* constant string might be replaced with object, f.e. bigint */
11903             if (const_class && SvPOK(*const_class)) {
11904                 STRLEN len;
11905                 const char* str = SvPV(*const_class, len);
11906                 if (len) {
11907                     SV* const shared = newSVpvn_share(
11908                         str, SvUTF8(*const_class)
11909                                     ? -(SSize_t)len : (SSize_t)len,
11910                         0
11911                     );
11912                     SvREFCNT_dec(*const_class);
11913                     *const_class = shared;
11914                 }
11915             }
11916             break;
11917     }
11918
11919     if (!cv) {
11920         S_entersub_alloc_targ(aTHX_ o);
11921         return ck_entersub_args_list(o);
11922     } else {
11923         Perl_call_checker ckfun;
11924         SV *ckobj;
11925         U8 flags;
11926         S_cv_get_call_checker(cv, &ckfun, &ckobj, &flags);
11927         if (CvISXSUB(cv) || !CvROOT(cv))
11928             S_entersub_alloc_targ(aTHX_ o);
11929         if (!namegv) {
11930             /* The original call checker API guarantees that a GV will be
11931                be provided with the right name.  So, if the old API was
11932                used (or the REQUIRE_GV flag was passed), we have to reify
11933                the CV’s GV, unless this is an anonymous sub.  This is not
11934                ideal for lexical subs, as its stringification will include
11935                the package.  But it is the best we can do.  */
11936             if (flags & MGf_REQUIRE_GV) {
11937                 if (!CvANON(cv) && (!CvNAMED(cv) || CvNAME_HEK(cv)))
11938                     namegv = CvGV(cv);
11939             }
11940             else namegv = MUTABLE_GV(cv);
11941             /* After a syntax error in a lexical sub, the cv that
11942                rv2cv_op_cv returns may be a nameless stub. */
11943             if (!namegv) return ck_entersub_args_list(o);
11944
11945         }
11946         return ckfun(aTHX_ o, namegv, ckobj);
11947     }
11948 }
11949
11950 OP *
11951 Perl_ck_svconst(pTHX_ OP *o)
11952 {
11953     SV * const sv = cSVOPo->op_sv;
11954     PERL_ARGS_ASSERT_CK_SVCONST;
11955     PERL_UNUSED_CONTEXT;
11956 #ifdef PERL_OLD_COPY_ON_WRITE
11957     if (SvIsCOW(sv)) sv_force_normal(sv);
11958 #elif defined(PERL_NEW_COPY_ON_WRITE)
11959     /* Since the read-only flag may be used to protect a string buffer, we
11960        cannot do copy-on-write with existing read-only scalars that are not
11961        already copy-on-write scalars.  To allow $_ = "hello" to do COW with
11962        that constant, mark the constant as COWable here, if it is not
11963        already read-only. */
11964     if (!SvREADONLY(sv) && !SvIsCOW(sv) && SvCANCOW(sv)) {
11965         SvIsCOW_on(sv);
11966         CowREFCNT(sv) = 0;
11967 # ifdef PERL_DEBUG_READONLY_COW
11968         sv_buf_to_ro(sv);
11969 # endif
11970     }
11971 #endif
11972     SvREADONLY_on(sv);
11973     return o;
11974 }
11975
11976 OP *
11977 Perl_ck_trunc(pTHX_ OP *o)
11978 {
11979     PERL_ARGS_ASSERT_CK_TRUNC;
11980
11981     if (o->op_flags & OPf_KIDS) {
11982         SVOP *kid = (SVOP*)cUNOPo->op_first;
11983
11984         if (kid->op_type == OP_NULL)
11985             kid = (SVOP*)OpSIBLING(kid);
11986         if (kid && kid->op_type == OP_CONST &&
11987             (kid->op_private & OPpCONST_BARE) &&
11988             !kid->op_folded)
11989         {
11990             o->op_flags |= OPf_SPECIAL;
11991             kid->op_private &= ~OPpCONST_STRICT;
11992         }
11993     }
11994     return ck_fun(o);
11995 }
11996
11997 OP *
11998 Perl_ck_substr(pTHX_ OP *o)
11999 {
12000     PERL_ARGS_ASSERT_CK_SUBSTR;
12001
12002     o = ck_fun(o);
12003     if ((o->op_flags & OPf_KIDS) && (o->op_private == 4)) {
12004         OP *kid = cLISTOPo->op_first;
12005
12006         if (kid->op_type == OP_NULL)
12007             kid = OpSIBLING(kid);
12008         if (kid)
12009             kid->op_flags |= OPf_MOD;
12010
12011     }
12012     return o;
12013 }
12014
12015 OP *
12016 Perl_ck_tell(pTHX_ OP *o)
12017 {
12018     PERL_ARGS_ASSERT_CK_TELL;
12019     o = ck_fun(o);
12020     if (o->op_flags & OPf_KIDS) {
12021      OP *kid = cLISTOPo->op_first;
12022      if (kid->op_type == OP_NULL && OpHAS_SIBLING(kid)) kid = OpSIBLING(kid);
12023      if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
12024     }
12025     return o;
12026 }
12027
12028 OP *
12029 Perl_ck_each(pTHX_ OP *o)
12030 {
12031     dVAR;
12032     OP *kid = o->op_flags & OPf_KIDS ? cUNOPo->op_first : NULL;
12033     const unsigned orig_type  = o->op_type;
12034     const unsigned array_type = orig_type == OP_EACH ? OP_AEACH
12035                               : orig_type == OP_KEYS ? OP_AKEYS : OP_AVALUES;
12036     const unsigned ref_type   = orig_type == OP_EACH ? OP_REACH
12037                               : orig_type == OP_KEYS ? OP_RKEYS : OP_RVALUES;
12038
12039     PERL_ARGS_ASSERT_CK_EACH;
12040
12041     if (kid) {
12042         switch (kid->op_type) {
12043             case OP_PADHV:
12044             case OP_RV2HV:
12045                 break;
12046             case OP_PADAV:
12047             case OP_RV2AV:
12048                 CHANGE_TYPE(o, array_type);
12049                 break;
12050             case OP_CONST:
12051                 if (kid->op_private == OPpCONST_BARE
12052                  || !SvROK(cSVOPx_sv(kid))
12053                  || (  SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV
12054                     && SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVHV  )
12055                    )
12056                     /* we let ck_fun handle it */
12057                     break;
12058             default:
12059                 CHANGE_TYPE(o, ref_type);
12060                 scalar(kid);
12061         }
12062     }
12063     /* if treating as a reference, defer additional checks to runtime */
12064     if (o->op_type == ref_type) {
12065         /* diag_listed_as: keys on reference is experimental */
12066         Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__AUTODEREF),
12067                               "%s is experimental", PL_op_desc[ref_type]);
12068         return o;
12069     }
12070     return ck_fun(o);
12071 }
12072
12073 OP *
12074 Perl_ck_length(pTHX_ OP *o)
12075 {
12076     PERL_ARGS_ASSERT_CK_LENGTH;
12077
12078     o = ck_fun(o);
12079
12080     if (ckWARN(WARN_SYNTAX)) {
12081         const OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : NULL;
12082
12083         if (kid) {
12084             SV *name = NULL;
12085             const bool hash = kid->op_type == OP_PADHV
12086                            || kid->op_type == OP_RV2HV;
12087             switch (kid->op_type) {
12088                 case OP_PADHV:
12089                 case OP_PADAV:
12090                 case OP_RV2HV:
12091                 case OP_RV2AV:
12092                     name = S_op_varname(aTHX_ kid);
12093                     break;
12094                 default:
12095                     return o;
12096             }
12097             if (name)
12098                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
12099                     "length() used on %"SVf" (did you mean \"scalar(%s%"SVf
12100                     ")\"?)",
12101                     SVfARG(name), hash ? "keys " : "", SVfARG(name)
12102                 );
12103             else if (hash)
12104      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
12105                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
12106                     "length() used on %%hash (did you mean \"scalar(keys %%hash)\"?)");
12107             else
12108      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
12109                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
12110                     "length() used on @array (did you mean \"scalar(@array)\"?)");
12111         }
12112     }
12113
12114     return o;
12115 }
12116
12117 /* Check for in place reverse and sort assignments like "@a = reverse @a"
12118    and modify the optree to make them work inplace */
12119
12120 STATIC void
12121 S_inplace_aassign(pTHX_ OP *o) {
12122
12123     OP *modop, *modop_pushmark;
12124     OP *oright;
12125     OP *oleft, *oleft_pushmark;
12126
12127     PERL_ARGS_ASSERT_INPLACE_AASSIGN;
12128
12129     assert((o->op_flags & OPf_WANT) == OPf_WANT_VOID);
12130
12131     assert(cUNOPo->op_first->op_type == OP_NULL);
12132     modop_pushmark = cUNOPx(cUNOPo->op_first)->op_first;
12133     assert(modop_pushmark->op_type == OP_PUSHMARK);
12134     modop = OpSIBLING(modop_pushmark);
12135
12136     if (modop->op_type != OP_SORT && modop->op_type != OP_REVERSE)
12137         return;
12138
12139     /* no other operation except sort/reverse */
12140     if (OpHAS_SIBLING(modop))
12141         return;
12142
12143     assert(cUNOPx(modop)->op_first->op_type == OP_PUSHMARK);
12144     if (!(oright = OpSIBLING(cUNOPx(modop)->op_first))) return;
12145
12146     if (modop->op_flags & OPf_STACKED) {
12147         /* skip sort subroutine/block */
12148         assert(oright->op_type == OP_NULL);
12149         oright = OpSIBLING(oright);
12150     }
12151
12152     assert(OpSIBLING(cUNOPo->op_first)->op_type == OP_NULL);
12153     oleft_pushmark = cUNOPx(OpSIBLING(cUNOPo->op_first))->op_first;
12154     assert(oleft_pushmark->op_type == OP_PUSHMARK);
12155     oleft = OpSIBLING(oleft_pushmark);
12156
12157     /* Check the lhs is an array */
12158     if (!oleft ||
12159         (oleft->op_type != OP_RV2AV && oleft->op_type != OP_PADAV)
12160         || OpHAS_SIBLING(oleft)
12161         || (oleft->op_private & OPpLVAL_INTRO)
12162     )
12163         return;
12164
12165     /* Only one thing on the rhs */
12166     if (OpHAS_SIBLING(oright))
12167         return;
12168
12169     /* check the array is the same on both sides */
12170     if (oleft->op_type == OP_RV2AV) {
12171         if (oright->op_type != OP_RV2AV
12172             || !cUNOPx(oright)->op_first
12173             || cUNOPx(oright)->op_first->op_type != OP_GV
12174             || cUNOPx(oleft )->op_first->op_type != OP_GV
12175             || cGVOPx_gv(cUNOPx(oleft)->op_first) !=
12176                cGVOPx_gv(cUNOPx(oright)->op_first)
12177         )
12178             return;
12179     }
12180     else if (oright->op_type != OP_PADAV
12181         || oright->op_targ != oleft->op_targ
12182     )
12183         return;
12184
12185     /* This actually is an inplace assignment */
12186
12187     modop->op_private |= OPpSORT_INPLACE;
12188
12189     /* transfer MODishness etc from LHS arg to RHS arg */
12190     oright->op_flags = oleft->op_flags;
12191
12192     /* remove the aassign op and the lhs */
12193     op_null(o);
12194     op_null(oleft_pushmark);
12195     if (oleft->op_type == OP_RV2AV && cUNOPx(oleft)->op_first)
12196         op_null(cUNOPx(oleft)->op_first);
12197     op_null(oleft);
12198 }
12199
12200
12201
12202 /* S_maybe_multideref(): given an op_next chain of ops beginning at 'start'
12203  * that potentially represent a series of one or more aggregate derefs
12204  * (such as $a->[1]{$key}), examine the chain, and if appropriate, convert
12205  * the whole chain to a single OP_MULTIDEREF op (maybe with a few
12206  * additional ops left in too).
12207  *
12208  * The caller will have already verified that the first few ops in the
12209  * chain following 'start' indicate a multideref candidate, and will have
12210  * set 'orig_o' to the point further on in the chain where the first index
12211  * expression (if any) begins.  'orig_action' specifies what type of
12212  * beginning has already been determined by the ops between start..orig_o
12213  * (e.g.  $lex_ary[], $pkg_ary->{}, expr->[], etc).
12214  *
12215  * 'hints' contains any hints flags that need adding (currently just
12216  * OPpHINT_STRICT_REFS) as found in any rv2av/hv skipped by the caller.
12217  */
12218
12219 void
12220 S_maybe_multideref(pTHX_ OP *start, OP *orig_o, UV orig_action, U8 hints)
12221 {
12222     dVAR;
12223     int pass;
12224     UNOP_AUX_item *arg_buf = NULL;
12225     bool reset_start_targ  = FALSE; /* start->op_targ needs zeroing */
12226     int index_skip         = -1;    /* don't output index arg on this action */
12227
12228     /* similar to regex compiling, do two passes; the first pass
12229      * determines whether the op chain is convertible and calculates the
12230      * buffer size; the second pass populates the buffer and makes any
12231      * changes necessary to ops (such as moving consts to the pad on
12232      * threaded builds).
12233      *
12234      * NB: for things like Coverity, note that both passes take the same
12235      * path through the logic tree (except for 'if (pass)' bits), since
12236      * both passes are following the same op_next chain; and in
12237      * particular, if it would return early on the second pass, it would
12238      * already have returned early on the first pass.
12239      */
12240     for (pass = 0; pass < 2; pass++) {
12241         OP *o                = orig_o;
12242         UV action            = orig_action;
12243         OP *first_elem_op    = NULL;  /* first seen aelem/helem */
12244         OP *top_op           = NULL;  /* highest [ah]elem/exists/del/rv2[ah]v */
12245         int action_count     = 0;     /* number of actions seen so far */
12246         int action_ix        = 0;     /* action_count % (actions per IV) */
12247         bool next_is_hash    = FALSE; /* is the next lookup to be a hash? */
12248         bool is_last         = FALSE; /* no more derefs to follow */
12249         bool maybe_aelemfast = FALSE; /* we can replace with aelemfast? */
12250         UNOP_AUX_item *arg     = arg_buf;
12251         UNOP_AUX_item *action_ptr = arg_buf;
12252
12253         if (pass)
12254             action_ptr->uv = 0;
12255         arg++;
12256
12257         switch (action) {
12258         case MDEREF_HV_gvsv_vivify_rv2hv_helem:
12259         case MDEREF_HV_gvhv_helem:
12260             next_is_hash = TRUE;
12261             /* FALLTHROUGH */
12262         case MDEREF_AV_gvsv_vivify_rv2av_aelem:
12263         case MDEREF_AV_gvav_aelem:
12264             if (pass) {
12265 #ifdef USE_ITHREADS
12266                 arg->pad_offset = cPADOPx(start)->op_padix;
12267                 /* stop it being swiped when nulled */
12268                 cPADOPx(start)->op_padix = 0;
12269 #else
12270                 arg->sv = cSVOPx(start)->op_sv;
12271                 cSVOPx(start)->op_sv = NULL;
12272 #endif
12273             }
12274             arg++;
12275             break;
12276
12277         case MDEREF_HV_padhv_helem:
12278         case MDEREF_HV_padsv_vivify_rv2hv_helem:
12279             next_is_hash = TRUE;
12280             /* FALLTHROUGH */
12281         case MDEREF_AV_padav_aelem:
12282         case MDEREF_AV_padsv_vivify_rv2av_aelem:
12283             if (pass) {
12284                 arg->pad_offset = start->op_targ;
12285                 /* we skip setting op_targ = 0 for now, since the intact
12286                  * OP_PADXV is needed by S_check_hash_fields_and_hekify */
12287                 reset_start_targ = TRUE;
12288             }
12289             arg++;
12290             break;
12291
12292         case MDEREF_HV_pop_rv2hv_helem:
12293             next_is_hash = TRUE;
12294             /* FALLTHROUGH */
12295         case MDEREF_AV_pop_rv2av_aelem:
12296             break;
12297
12298         default:
12299             NOT_REACHED; /* NOTREACHED */
12300             return;
12301         }
12302
12303         while (!is_last) {
12304             /* look for another (rv2av/hv; get index;
12305              * aelem/helem/exists/delele) sequence */
12306
12307             OP *kid;
12308             bool is_deref;
12309             bool ok;
12310             UV index_type = MDEREF_INDEX_none;
12311
12312             if (action_count) {
12313                 /* if this is not the first lookup, consume the rv2av/hv  */
12314
12315                 /* for N levels of aggregate lookup, we normally expect
12316                  * that the first N-1 [ah]elem ops will be flagged as
12317                  * /DEREF (so they autovivifiy if necessary), and the last
12318                  * lookup op not to be.
12319                  * For other things (like @{$h{k1}{k2}}) extra scope or
12320                  * leave ops can appear, so abandon the effort in that
12321                  * case */
12322                 if (o->op_type != OP_RV2AV && o->op_type != OP_RV2HV)
12323                     return;
12324
12325                 /* rv2av or rv2hv sKR/1 */
12326
12327                 ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
12328                                             |OPf_REF|OPf_MOD|OPf_SPECIAL)));
12329                 if (o->op_flags != (OPf_WANT_SCALAR|OPf_KIDS|OPf_REF))
12330                     return;
12331
12332                 /* at this point, we wouldn't expect any of these
12333                  * possible private flags:
12334                  * OPpMAYBE_LVSUB, OPpOUR_INTRO, OPpLVAL_INTRO
12335                  * OPpTRUEBOOL, OPpMAYBE_TRUEBOOL (rv2hv only)
12336                  */
12337                 ASSUME(!(o->op_private &
12338                     ~(OPpHINT_STRICT_REFS|OPpARG1_MASK|OPpSLICEWARNING)));
12339
12340                 hints = (o->op_private & OPpHINT_STRICT_REFS);
12341
12342                 /* make sure the type of the previous /DEREF matches the
12343                  * type of the next lookup */
12344                 ASSUME(o->op_type == (next_is_hash ? OP_RV2HV : OP_RV2AV));
12345                 top_op = o;
12346
12347                 action = next_is_hash
12348                             ? MDEREF_HV_vivify_rv2hv_helem
12349                             : MDEREF_AV_vivify_rv2av_aelem;
12350                 o = o->op_next;
12351             }
12352
12353             /* if this is the second pass, and we're at the depth where
12354              * previously we encountered a non-simple index expression,
12355              * stop processing the index at this point */
12356             if (action_count != index_skip) {
12357
12358                 /* look for one or more simple ops that return an array
12359                  * index or hash key */
12360
12361                 switch (o->op_type) {
12362                 case OP_PADSV:
12363                     /* it may be a lexical var index */
12364                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_PARENS
12365                                             |OPf_REF|OPf_MOD|OPf_SPECIAL)));
12366                     ASSUME(!(o->op_private &
12367                             ~(OPpPAD_STATE|OPpDEREF|OPpLVAL_INTRO)));
12368
12369                     if (   OP_GIMME(o,0) == G_SCALAR
12370                         && !(o->op_flags & (OPf_REF|OPf_MOD))
12371                         && o->op_private == 0)
12372                     {
12373                         if (pass)
12374                             arg->pad_offset = o->op_targ;
12375                         arg++;
12376                         index_type = MDEREF_INDEX_padsv;
12377                         o = o->op_next;
12378                     }
12379                     break;
12380
12381                 case OP_CONST:
12382                     if (next_is_hash) {
12383                         /* it's a constant hash index */
12384                         if (!(SvFLAGS(cSVOPo_sv) & (SVf_IOK|SVf_NOK|SVf_POK)))
12385                             /* "use constant foo => FOO; $h{+foo}" for
12386                              * some weird FOO, can leave you with constants
12387                              * that aren't simple strings. It's not worth
12388                              * the extra hassle for those edge cases */
12389                             break;
12390
12391                         if (pass) {
12392                             UNOP *rop = NULL;
12393                             OP * helem_op = o->op_next;
12394
12395                             ASSUME(   helem_op->op_type == OP_HELEM
12396                                    || helem_op->op_type == OP_NULL);
12397                             if (helem_op->op_type == OP_HELEM) {
12398                                 rop = (UNOP*)(((BINOP*)helem_op)->op_first);
12399                                 if (   helem_op->op_private & OPpLVAL_INTRO
12400                                     || rop->op_type != OP_RV2HV
12401                                 )
12402                                     rop = NULL;
12403                             }
12404                             S_check_hash_fields_and_hekify(aTHX_ rop, cSVOPo);
12405
12406 #ifdef USE_ITHREADS
12407                             /* Relocate sv to the pad for thread safety */
12408                             op_relocate_sv(&cSVOPo->op_sv, &o->op_targ);
12409                             arg->pad_offset = o->op_targ;
12410                             o->op_targ = 0;
12411 #else
12412                             arg->sv = cSVOPx_sv(o);
12413 #endif
12414                         }
12415                     }
12416                     else {
12417                         /* it's a constant array index */
12418                         IV iv;
12419                         SV *ix_sv = cSVOPo->op_sv;
12420                         if (!SvIOK(ix_sv))
12421                             break;
12422                         iv = SvIV(ix_sv);
12423
12424                         if (   action_count == 0
12425                             && iv >= -128
12426                             && iv <= 127
12427                             && (   action == MDEREF_AV_padav_aelem
12428                                 || action == MDEREF_AV_gvav_aelem)
12429                         )
12430                             maybe_aelemfast = TRUE;
12431
12432                         if (pass) {
12433                             arg->iv = iv;
12434                             SvREFCNT_dec_NN(cSVOPo->op_sv);
12435                         }
12436                     }
12437                     if (pass)
12438                         /* we've taken ownership of the SV */
12439                         cSVOPo->op_sv = NULL;
12440                     arg++;
12441                     index_type = MDEREF_INDEX_const;
12442                     o = o->op_next;
12443                     break;
12444
12445                 case OP_GV:
12446                     /* it may be a package var index */
12447
12448                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_SPECIAL)));
12449                     ASSUME(!(o->op_private & ~(OPpEARLY_CV)));
12450                     if (  (o->op_flags &~ OPf_SPECIAL) != OPf_WANT_SCALAR
12451                         || o->op_private != 0
12452                     )
12453                         break;
12454
12455                     kid = o->op_next;
12456                     if (kid->op_type != OP_RV2SV)
12457                         break;
12458
12459                     ASSUME(!(kid->op_flags &
12460                             ~(OPf_WANT|OPf_KIDS|OPf_MOD|OPf_REF
12461                              |OPf_SPECIAL|OPf_PARENS)));
12462                     ASSUME(!(kid->op_private &
12463                                     ~(OPpARG1_MASK
12464                                      |OPpHINT_STRICT_REFS|OPpOUR_INTRO
12465                                      |OPpDEREF|OPpLVAL_INTRO)));
12466                     if(   (kid->op_flags &~ OPf_PARENS)
12467                             != (OPf_WANT_SCALAR|OPf_KIDS)
12468                        || (kid->op_private & ~(OPpARG1_MASK|HINT_STRICT_REFS))
12469                     )
12470                         break;
12471
12472                     if (pass) {
12473 #ifdef USE_ITHREADS
12474                         arg->pad_offset = cPADOPx(o)->op_padix;
12475                         /* stop it being swiped when nulled */
12476                         cPADOPx(o)->op_padix = 0;
12477 #else
12478                         arg->sv = cSVOPx(o)->op_sv;
12479                         cSVOPo->op_sv = NULL;
12480 #endif
12481                     }
12482                     arg++;
12483                     index_type = MDEREF_INDEX_gvsv;
12484                     o = kid->op_next;
12485                     break;
12486
12487                 } /* switch */
12488             } /* action_count != index_skip */
12489
12490             action |= index_type;
12491
12492
12493             /* at this point we have either:
12494              *   * detected what looks like a simple index expression,
12495              *     and expect the next op to be an [ah]elem, or
12496              *     an nulled  [ah]elem followed by a delete or exists;
12497              *  * found a more complex expression, so something other
12498              *    than the above follows.
12499              */
12500
12501             /* possibly an optimised away [ah]elem (where op_next is
12502              * exists or delete) */
12503             if (o->op_type == OP_NULL)
12504                 o = o->op_next;
12505
12506             /* at this point we're looking for an OP_AELEM, OP_HELEM,
12507              * OP_EXISTS or OP_DELETE */
12508
12509             /* if something like arybase (a.k.a $[ ) is in scope,
12510              * abandon optimisation attempt */
12511             if (  (o->op_type == OP_AELEM || o->op_type == OP_HELEM)
12512                && PL_check[o->op_type] != Perl_ck_null)
12513                 return;
12514
12515             if (   o->op_type != OP_AELEM
12516                 || (o->op_private &
12517                       (OPpLVAL_INTRO|OPpLVAL_DEFER|OPpDEREF|OPpMAYBE_LVSUB))
12518                 )
12519                 maybe_aelemfast = FALSE;
12520
12521             /* look for aelem/helem/exists/delete. If it's not the last elem
12522              * lookup, it *must* have OPpDEREF_AV/HV, but not many other
12523              * flags; if it's the last, then it mustn't have
12524              * OPpDEREF_AV/HV, but may have lots of other flags, like
12525              * OPpLVAL_INTRO etc
12526              */
12527
12528             if (   index_type == MDEREF_INDEX_none
12529                 || (   o->op_type != OP_AELEM  && o->op_type != OP_HELEM
12530                     && o->op_type != OP_EXISTS && o->op_type != OP_DELETE)
12531             )
12532                 ok = FALSE;
12533             else {
12534                 /* we have aelem/helem/exists/delete with valid simple index */
12535
12536                 is_deref =    (o->op_type == OP_AELEM || o->op_type == OP_HELEM)
12537                            && (   (o->op_private & OPpDEREF) == OPpDEREF_AV
12538                                || (o->op_private & OPpDEREF) == OPpDEREF_HV);
12539
12540                 if (is_deref) {
12541                     ASSUME(!(o->op_flags &
12542                                  ~(OPf_WANT|OPf_KIDS|OPf_MOD|OPf_PARENS)));
12543                     ASSUME(!(o->op_private & ~(OPpARG2_MASK|OPpDEREF)));
12544
12545                     ok =    (o->op_flags &~ OPf_PARENS)
12546                                == (OPf_WANT_SCALAR|OPf_KIDS|OPf_MOD)
12547                          && !(o->op_private & ~(OPpDEREF|OPpARG2_MASK));
12548                 }
12549                 else if (o->op_type == OP_EXISTS) {
12550                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
12551                                 |OPf_REF|OPf_MOD|OPf_SPECIAL)));
12552                     ASSUME(!(o->op_private & ~(OPpARG1_MASK|OPpEXISTS_SUB)));
12553                     ok =  !(o->op_private & ~OPpARG1_MASK);
12554                 }
12555                 else if (o->op_type == OP_DELETE) {
12556                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
12557                                 |OPf_REF|OPf_MOD|OPf_SPECIAL)));
12558                     ASSUME(!(o->op_private &
12559                                     ~(OPpARG1_MASK|OPpSLICE|OPpLVAL_INTRO)));
12560                     /* don't handle slices or 'local delete'; the latter
12561                      * is fairly rare, and has a complex runtime */
12562                     ok =  !(o->op_private & ~OPpARG1_MASK);
12563                     if (OP_TYPE_IS_OR_WAS(cUNOPo->op_first, OP_AELEM))
12564                         /* skip handling run-tome error */
12565                         ok = (ok && cBOOL(o->op_flags & OPf_SPECIAL));
12566                 }
12567                 else {
12568                     ASSUME(o->op_type == OP_AELEM || o->op_type == OP_HELEM);
12569                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_MOD
12570                                             |OPf_PARENS|OPf_REF|OPf_SPECIAL)));
12571                     ASSUME(!(o->op_private & ~(OPpARG2_MASK|OPpMAYBE_LVSUB
12572                                     |OPpLVAL_DEFER|OPpDEREF|OPpLVAL_INTRO)));
12573                     ok = (o->op_private & OPpDEREF) != OPpDEREF_SV;
12574                 }
12575             }
12576
12577             if (ok) {
12578                 if (!first_elem_op)
12579                     first_elem_op = o;
12580                 top_op = o;
12581                 if (is_deref) {
12582                     next_is_hash = cBOOL((o->op_private & OPpDEREF) == OPpDEREF_HV);
12583                     o = o->op_next;
12584                 }
12585                 else {
12586                     is_last = TRUE;
12587                     action |= MDEREF_FLAG_last;
12588                 }
12589             }
12590             else {
12591                 /* at this point we have something that started
12592                  * promisingly enough (with rv2av or whatever), but failed
12593                  * to find a simple index followed by an
12594                  * aelem/helem/exists/delete. If this is the first action,
12595                  * give up; but if we've already seen at least one
12596                  * aelem/helem, then keep them and add a new action with
12597                  * MDEREF_INDEX_none, which causes it to do the vivify
12598                  * from the end of the previous lookup, and do the deref,
12599                  * but stop at that point. So $a[0][expr] will do one
12600                  * av_fetch, vivify and deref, then continue executing at
12601                  * expr */
12602                 if (!action_count)
12603                     return;
12604                 is_last = TRUE;
12605                 index_skip = action_count;
12606                 action |= MDEREF_FLAG_last;
12607             }
12608
12609             if (pass)
12610                 action_ptr->uv |= (action << (action_ix * MDEREF_SHIFT));
12611             action_ix++;
12612             action_count++;
12613             /* if there's no space for the next action, create a new slot
12614              * for it *before* we start adding args for that action */
12615             if ((action_ix + 1) * MDEREF_SHIFT > UVSIZE*8) {
12616                 action_ptr = arg;
12617                 if (pass)
12618                     arg->uv = 0;
12619                 arg++;
12620                 action_ix = 0;
12621             }
12622         } /* while !is_last */
12623
12624         /* success! */
12625
12626         if (pass) {
12627             OP *mderef;
12628             OP *p, *q;
12629
12630             mderef = newUNOP_AUX(OP_MULTIDEREF, 0, NULL, arg_buf);
12631             if (index_skip == -1) {
12632                 mderef->op_flags = o->op_flags
12633                         & (OPf_WANT|OPf_MOD|(next_is_hash ? OPf_SPECIAL : 0));
12634                 if (o->op_type == OP_EXISTS)
12635                     mderef->op_private = OPpMULTIDEREF_EXISTS;
12636                 else if (o->op_type == OP_DELETE)
12637                     mderef->op_private = OPpMULTIDEREF_DELETE;
12638                 else
12639                     mderef->op_private = o->op_private
12640                         & (OPpMAYBE_LVSUB|OPpLVAL_DEFER|OPpLVAL_INTRO);
12641             }
12642             /* accumulate strictness from every level (although I don't think
12643              * they can actually vary) */
12644             mderef->op_private |= hints;
12645
12646             /* integrate the new multideref op into the optree and the
12647              * op_next chain.
12648              *
12649              * In general an op like aelem or helem has two child
12650              * sub-trees: the aggregate expression (a_expr) and the
12651              * index expression (i_expr):
12652              *
12653              *     aelem
12654              *       |
12655              *     a_expr - i_expr
12656              *
12657              * The a_expr returns an AV or HV, while the i-expr returns an
12658              * index. In general a multideref replaces most or all of a
12659              * multi-level tree, e.g.
12660              *
12661              *     exists
12662              *       |
12663              *     ex-aelem
12664              *       |
12665              *     rv2av  - i_expr1
12666              *       |
12667              *     helem
12668              *       |
12669              *     rv2hv  - i_expr2
12670              *       |
12671              *     aelem
12672              *       |
12673              *     a_expr - i_expr3
12674              *
12675              * With multideref, all the i_exprs will be simple vars or
12676              * constants, except that i_expr1 may be arbitrary in the case
12677              * of MDEREF_INDEX_none.
12678              *
12679              * The bottom-most a_expr will be either:
12680              *   1) a simple var (so padXv or gv+rv2Xv);
12681              *   2) a simple scalar var dereferenced (e.g. $r->[0]):
12682              *      so a simple var with an extra rv2Xv;
12683              *   3) or an arbitrary expression.
12684              *
12685              * 'start', the first op in the execution chain, will point to
12686              *   1),2): the padXv or gv op;
12687              *   3):    the rv2Xv which forms the last op in the a_expr
12688              *          execution chain, and the top-most op in the a_expr
12689              *          subtree.
12690              *
12691              * For all cases, the 'start' node is no longer required,
12692              * but we can't free it since one or more external nodes
12693              * may point to it. E.g. consider
12694              *     $h{foo} = $a ? $b : $c
12695              * Here, both the op_next and op_other branches of the
12696              * cond_expr point to the gv[*h] of the hash expression, so
12697              * we can't free the 'start' op.
12698              *
12699              * For expr->[...], we need to save the subtree containing the
12700              * expression; for the other cases, we just need to save the
12701              * start node.
12702              * So in all cases, we null the start op and keep it around by
12703              * making it the child of the multideref op; for the expr->
12704              * case, the expr will be a subtree of the start node.
12705              *
12706              * So in the simple 1,2 case the  optree above changes to
12707              *
12708              *     ex-exists
12709              *       |
12710              *     multideref
12711              *       |
12712              *     ex-gv (or ex-padxv)
12713              *
12714              *  with the op_next chain being
12715              *
12716              *  -> ex-gv -> multideref -> op-following-ex-exists ->
12717              *
12718              *  In the 3 case, we have
12719              *
12720              *     ex-exists
12721              *       |
12722              *     multideref
12723              *       |
12724              *     ex-rv2xv
12725              *       |
12726              *    rest-of-a_expr
12727              *      subtree
12728              *
12729              *  and
12730              *
12731              *  -> rest-of-a_expr subtree ->
12732              *    ex-rv2xv -> multideref -> op-following-ex-exists ->
12733              *
12734              *
12735              * Where the last i_expr is non-simple (i.e. MDEREF_INDEX_none,
12736              * e.g. $a[0]{foo}[$x+1], the next rv2xv is nulled and the
12737              * multideref attached as the child, e.g.
12738              *
12739              *     exists
12740              *       |
12741              *     ex-aelem
12742              *       |
12743              *     ex-rv2av  - i_expr1
12744              *       |
12745              *     multideref
12746              *       |
12747              *     ex-whatever
12748              *
12749              */
12750
12751             /* if we free this op, don't free the pad entry */
12752             if (reset_start_targ)
12753                 start->op_targ = 0;
12754
12755
12756             /* Cut the bit we need to save out of the tree and attach to
12757              * the multideref op, then free the rest of the tree */
12758
12759             /* find parent of node to be detached (for use by splice) */
12760             p = first_elem_op;
12761             if (   orig_action == MDEREF_AV_pop_rv2av_aelem
12762                 || orig_action == MDEREF_HV_pop_rv2hv_helem)
12763             {
12764                 /* there is an arbitrary expression preceding us, e.g.
12765                  * expr->[..]? so we need to save the 'expr' subtree */
12766                 if (p->op_type == OP_EXISTS || p->op_type == OP_DELETE)
12767                     p = cUNOPx(p)->op_first;
12768                 ASSUME(   start->op_type == OP_RV2AV
12769                        || start->op_type == OP_RV2HV);
12770             }
12771             else {
12772                 /* either a padXv or rv2Xv+gv, maybe with an ex-Xelem
12773                  * above for exists/delete. */
12774                 while (   (p->op_flags & OPf_KIDS)
12775                        && cUNOPx(p)->op_first != start
12776                 )
12777                     p = cUNOPx(p)->op_first;
12778             }
12779             ASSUME(cUNOPx(p)->op_first == start);
12780
12781             /* detach from main tree, and re-attach under the multideref */
12782             op_sibling_splice(mderef, NULL, 0,
12783                     op_sibling_splice(p, NULL, 1, NULL));
12784             op_null(start);
12785
12786             start->op_next = mderef;
12787
12788             mderef->op_next = index_skip == -1 ? o->op_next : o;
12789
12790             /* excise and free the original tree, and replace with
12791              * the multideref op */
12792             p = op_sibling_splice(top_op, NULL, -1, mderef);
12793             while (p) {
12794                 q = OpSIBLING(p);
12795                 op_free(p);
12796                 p = q;
12797             }
12798             op_null(top_op);
12799         }
12800         else {
12801             Size_t size = arg - arg_buf;
12802
12803             if (maybe_aelemfast && action_count == 1)
12804                 return;
12805
12806             arg_buf = (UNOP_AUX_item*)PerlMemShared_malloc(
12807                                 sizeof(UNOP_AUX_item) * (size + 1));
12808             /* for dumping etc: store the length in a hidden first slot;
12809              * we set the op_aux pointer to the second slot */
12810             arg_buf->uv = size;
12811             arg_buf++;
12812         }
12813     } /* for (pass = ...) */
12814 }
12815
12816
12817
12818 /* mechanism for deferring recursion in rpeep() */
12819
12820 #define MAX_DEFERRED 4
12821
12822 #define DEFER(o) \
12823   STMT_START { \
12824     if (defer_ix == (MAX_DEFERRED-1)) { \
12825         OP **defer = defer_queue[defer_base]; \
12826         CALL_RPEEP(*defer); \
12827         S_prune_chain_head(defer); \
12828         defer_base = (defer_base + 1) % MAX_DEFERRED; \
12829         defer_ix--; \
12830     } \
12831     defer_queue[(defer_base + ++defer_ix) % MAX_DEFERRED] = &(o); \
12832   } STMT_END
12833
12834 #define IS_AND_OP(o)   (o->op_type == OP_AND)
12835 #define IS_OR_OP(o)    (o->op_type == OP_OR)
12836
12837
12838 /* A peephole optimizer.  We visit the ops in the order they're to execute.
12839  * See the comments at the top of this file for more details about when
12840  * peep() is called */
12841
12842 void
12843 Perl_rpeep(pTHX_ OP *o)
12844 {
12845     dVAR;
12846     OP* oldop = NULL;
12847     OP* oldoldop = NULL;
12848     OP** defer_queue[MAX_DEFERRED]; /* small queue of deferred branches */
12849     int defer_base = 0;
12850     int defer_ix = -1;
12851     OP *fop;
12852     OP *sop;
12853
12854     if (!o || o->op_opt)
12855         return;
12856     ENTER;
12857     SAVEOP();
12858     SAVEVPTR(PL_curcop);
12859     for (;; o = o->op_next) {
12860         if (o && o->op_opt)
12861             o = NULL;
12862         if (!o) {
12863             while (defer_ix >= 0) {
12864                 OP **defer =
12865                         defer_queue[(defer_base + defer_ix--) % MAX_DEFERRED];
12866                 CALL_RPEEP(*defer);
12867                 S_prune_chain_head(defer);
12868             }
12869             break;
12870         }
12871
12872       redo:
12873         /* By default, this op has now been optimised. A couple of cases below
12874            clear this again.  */
12875         o->op_opt = 1;
12876         PL_op = o;
12877
12878         /* look for a series of 1 or more aggregate derefs, e.g.
12879          *   $a[1]{foo}[$i]{$k}
12880          * and replace with a single OP_MULTIDEREF op.
12881          * Each index must be either a const, or a simple variable,
12882          *
12883          * First, look for likely combinations of starting ops,
12884          * corresponding to (global and lexical variants of)
12885          *     $a[...]   $h{...}
12886          *     $r->[...] $r->{...}
12887          *     (preceding expression)->[...]
12888          *     (preceding expression)->{...}
12889          * and if so, call maybe_multideref() to do a full inspection
12890          * of the op chain and if appropriate, replace with an
12891          * OP_MULTIDEREF
12892          */
12893         {
12894             UV action;
12895             OP *o2 = o;
12896             U8 hints = 0;
12897
12898             switch (o2->op_type) {
12899             case OP_GV:
12900                 /* $pkg[..]   :   gv[*pkg]
12901                  * $pkg->[...]:   gv[*pkg]; rv2sv sKM/DREFAV */
12902
12903                 /* Fail if there are new op flag combinations that we're
12904                  * not aware of, rather than:
12905                  *  * silently failing to optimise, or
12906                  *  * silently optimising the flag away.
12907                  * If this ASSUME starts failing, examine what new flag
12908                  * has been added to the op, and decide whether the
12909                  * optimisation should still occur with that flag, then
12910                  * update the code accordingly. This applies to all the
12911                  * other ASSUMEs in the block of code too.
12912                  */
12913                 ASSUME(!(o2->op_flags &
12914                             ~(OPf_WANT|OPf_MOD|OPf_PARENS|OPf_SPECIAL)));
12915                 ASSUME(!(o2->op_private & ~OPpEARLY_CV));
12916
12917                 o2 = o2->op_next;
12918
12919                 if (o2->op_type == OP_RV2AV) {
12920                     action = MDEREF_AV_gvav_aelem;
12921                     goto do_deref;
12922                 }
12923
12924                 if (o2->op_type == OP_RV2HV) {
12925                     action = MDEREF_HV_gvhv_helem;
12926                     goto do_deref;
12927                 }
12928
12929                 if (o2->op_type != OP_RV2SV)
12930                     break;
12931
12932                 /* at this point we've seen gv,rv2sv, so the only valid
12933                  * construct left is $pkg->[] or $pkg->{} */
12934
12935                 ASSUME(!(o2->op_flags & OPf_STACKED));
12936                 if ((o2->op_flags & (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
12937                             != (OPf_WANT_SCALAR|OPf_MOD))
12938                     break;
12939
12940                 ASSUME(!(o2->op_private & ~(OPpARG1_MASK|HINT_STRICT_REFS
12941                                     |OPpOUR_INTRO|OPpDEREF|OPpLVAL_INTRO)));
12942                 if (o2->op_private & (OPpOUR_INTRO|OPpLVAL_INTRO))
12943                     break;
12944                 if (   (o2->op_private & OPpDEREF) != OPpDEREF_AV
12945                     && (o2->op_private & OPpDEREF) != OPpDEREF_HV)
12946                     break;
12947
12948                 o2 = o2->op_next;
12949                 if (o2->op_type == OP_RV2AV) {
12950                     action = MDEREF_AV_gvsv_vivify_rv2av_aelem;
12951                     goto do_deref;
12952                 }
12953                 if (o2->op_type == OP_RV2HV) {
12954                     action = MDEREF_HV_gvsv_vivify_rv2hv_helem;
12955                     goto do_deref;
12956                 }
12957                 break;
12958
12959             case OP_PADSV:
12960                 /* $lex->[...]: padsv[$lex] sM/DREFAV */
12961
12962                 ASSUME(!(o2->op_flags &
12963                     ~(OPf_WANT|OPf_PARENS|OPf_REF|OPf_MOD|OPf_SPECIAL)));
12964                 if ((o2->op_flags &
12965                         (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
12966                      != (OPf_WANT_SCALAR|OPf_MOD))
12967                     break;
12968
12969                 ASSUME(!(o2->op_private &
12970                                 ~(OPpPAD_STATE|OPpDEREF|OPpLVAL_INTRO)));
12971                 /* skip if state or intro, or not a deref */
12972                 if (      o2->op_private != OPpDEREF_AV
12973                        && o2->op_private != OPpDEREF_HV)
12974                     break;
12975
12976                 o2 = o2->op_next;
12977                 if (o2->op_type == OP_RV2AV) {
12978                     action = MDEREF_AV_padsv_vivify_rv2av_aelem;
12979                     goto do_deref;
12980                 }
12981                 if (o2->op_type == OP_RV2HV) {
12982                     action = MDEREF_HV_padsv_vivify_rv2hv_helem;
12983                     goto do_deref;
12984                 }
12985                 break;
12986
12987             case OP_PADAV:
12988             case OP_PADHV:
12989                 /*    $lex[..]:  padav[@lex:1,2] sR *
12990                  * or $lex{..}:  padhv[%lex:1,2] sR */
12991                 ASSUME(!(o2->op_flags & ~(OPf_WANT|OPf_MOD|OPf_PARENS|
12992                                             OPf_REF|OPf_SPECIAL)));
12993                 if ((o2->op_flags &
12994                         (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
12995                      != (OPf_WANT_SCALAR|OPf_REF))
12996                     break;
12997                 if (o2->op_flags != (OPf_WANT_SCALAR|OPf_REF))
12998                     break;
12999                 /* OPf_PARENS isn't currently used in this case;
13000                  * if that changes, let us know! */
13001                 ASSUME(!(o2->op_flags & OPf_PARENS));
13002
13003                 /* at this point, we wouldn't expect any of the remaining
13004                  * possible private flags:
13005                  * OPpPAD_STATE, OPpLVAL_INTRO, OPpTRUEBOOL,
13006                  * OPpMAYBE_TRUEBOOL, OPpMAYBE_LVSUB
13007                  *
13008                  * OPpSLICEWARNING shouldn't affect runtime
13009                  */
13010                 ASSUME(!(o2->op_private & ~(OPpSLICEWARNING)));
13011
13012                 action = o2->op_type == OP_PADAV
13013                             ? MDEREF_AV_padav_aelem
13014                             : MDEREF_HV_padhv_helem;
13015                 o2 = o2->op_next;
13016                 S_maybe_multideref(aTHX_ o, o2, action, 0);
13017                 break;
13018
13019
13020             case OP_RV2AV:
13021             case OP_RV2HV:
13022                 action = o2->op_type == OP_RV2AV
13023                             ? MDEREF_AV_pop_rv2av_aelem
13024                             : MDEREF_HV_pop_rv2hv_helem;
13025                 /* FALLTHROUGH */
13026             do_deref:
13027                 /* (expr)->[...]:  rv2av sKR/1;
13028                  * (expr)->{...}:  rv2hv sKR/1; */
13029
13030                 ASSUME(o2->op_type == OP_RV2AV || o2->op_type == OP_RV2HV);
13031
13032                 ASSUME(!(o2->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
13033                                 |OPf_REF|OPf_MOD|OPf_STACKED|OPf_SPECIAL)));
13034                 if (o2->op_flags != (OPf_WANT_SCALAR|OPf_KIDS|OPf_REF))
13035                     break;
13036
13037                 /* at this point, we wouldn't expect any of these
13038                  * possible private flags:
13039                  * OPpMAYBE_LVSUB, OPpLVAL_INTRO
13040                  * OPpTRUEBOOL, OPpMAYBE_TRUEBOOL, (rv2hv only)
13041                  */
13042                 ASSUME(!(o2->op_private &
13043                     ~(OPpHINT_STRICT_REFS|OPpARG1_MASK|OPpSLICEWARNING
13044                      |OPpOUR_INTRO)));
13045                 hints |= (o2->op_private & OPpHINT_STRICT_REFS);
13046
13047                 o2 = o2->op_next;
13048
13049                 S_maybe_multideref(aTHX_ o, o2, action, hints);
13050                 break;
13051
13052             default:
13053                 break;
13054             }
13055         }
13056
13057
13058         switch (o->op_type) {
13059         case OP_DBSTATE:
13060             PL_curcop = ((COP*)o);              /* for warnings */
13061             break;
13062         case OP_NEXTSTATE:
13063             PL_curcop = ((COP*)o);              /* for warnings */
13064
13065             /* Optimise a "return ..." at the end of a sub to just be "...".
13066              * This saves 2 ops. Before:
13067              * 1  <;> nextstate(main 1 -e:1) v ->2
13068              * 4  <@> return K ->5
13069              * 2    <0> pushmark s ->3
13070              * -    <1> ex-rv2sv sK/1 ->4
13071              * 3      <#> gvsv[*cat] s ->4
13072              *
13073              * After:
13074              * -  <@> return K ->-
13075              * -    <0> pushmark s ->2
13076              * -    <1> ex-rv2sv sK/1 ->-
13077              * 2      <$> gvsv(*cat) s ->3
13078              */
13079             {
13080                 OP *next = o->op_next;
13081                 OP *sibling = OpSIBLING(o);
13082                 if (   OP_TYPE_IS(next, OP_PUSHMARK)
13083                     && OP_TYPE_IS(sibling, OP_RETURN)
13084                     && OP_TYPE_IS(sibling->op_next, OP_LINESEQ)
13085                     && ( OP_TYPE_IS(sibling->op_next->op_next, OP_LEAVESUB)
13086                        ||OP_TYPE_IS(sibling->op_next->op_next,
13087                                     OP_LEAVESUBLV))
13088                     && cUNOPx(sibling)->op_first == next
13089                     && OpHAS_SIBLING(next) && OpSIBLING(next)->op_next
13090                     && next->op_next
13091                 ) {
13092                     /* Look through the PUSHMARK's siblings for one that
13093                      * points to the RETURN */
13094                     OP *top = OpSIBLING(next);
13095                     while (top && top->op_next) {
13096                         if (top->op_next == sibling) {
13097                             top->op_next = sibling->op_next;
13098                             o->op_next = next->op_next;
13099                             break;
13100                         }
13101                         top = OpSIBLING(top);
13102                     }
13103                 }
13104             }
13105
13106             /* Optimise 'my $x; my $y;' into 'my ($x, $y);'
13107              *
13108              * This latter form is then suitable for conversion into padrange
13109              * later on. Convert:
13110              *
13111              *   nextstate1 -> padop1 -> nextstate2 -> padop2 -> nextstate3
13112              *
13113              * into:
13114              *
13115              *   nextstate1 ->     listop     -> nextstate3
13116              *                 /            \
13117              *         pushmark -> padop1 -> padop2
13118              */
13119             if (o->op_next && (
13120                     o->op_next->op_type == OP_PADSV
13121                  || o->op_next->op_type == OP_PADAV
13122                  || o->op_next->op_type == OP_PADHV
13123                 )
13124                 && !(o->op_next->op_private & ~OPpLVAL_INTRO)
13125                 && o->op_next->op_next && o->op_next->op_next->op_type == OP_NEXTSTATE
13126                 && o->op_next->op_next->op_next && (
13127                     o->op_next->op_next->op_next->op_type == OP_PADSV
13128                  || o->op_next->op_next->op_next->op_type == OP_PADAV
13129                  || o->op_next->op_next->op_next->op_type == OP_PADHV
13130                 )
13131                 && !(o->op_next->op_next->op_next->op_private & ~OPpLVAL_INTRO)
13132                 && o->op_next->op_next->op_next->op_next && o->op_next->op_next->op_next->op_next->op_type == OP_NEXTSTATE
13133                 && (!CopLABEL((COP*)o)) /* Don't mess with labels */
13134                 && (!CopLABEL((COP*)o->op_next->op_next)) /* ... */
13135             ) {
13136                 OP *pad1, *ns2, *pad2, *ns3, *newop, *newpm;
13137
13138                 pad1 =    o->op_next;
13139                 ns2  = pad1->op_next;
13140                 pad2 =  ns2->op_next;
13141                 ns3  = pad2->op_next;
13142
13143                 /* we assume here that the op_next chain is the same as
13144                  * the op_sibling chain */
13145                 assert(OpSIBLING(o)    == pad1);
13146                 assert(OpSIBLING(pad1) == ns2);
13147                 assert(OpSIBLING(ns2)  == pad2);
13148                 assert(OpSIBLING(pad2) == ns3);
13149
13150                 /* create new listop, with children consisting of:
13151                  * a new pushmark, pad1, pad2. */
13152                 OpSIBLING_set(pad2, NULL);
13153                 newop = newLISTOP(OP_LIST, 0, pad1, pad2);
13154                 newop->op_flags |= OPf_PARENS;
13155                 newop->op_flags = (newop->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
13156                 newpm = cUNOPx(newop)->op_first; /* pushmark */
13157
13158                 /* Kill nextstate2 between padop1/padop2 */
13159                 op_free(ns2);
13160
13161                 o    ->op_next = newpm;
13162                 newpm->op_next = pad1;
13163                 pad1 ->op_next = pad2;
13164                 pad2 ->op_next = newop; /* listop */
13165                 newop->op_next = ns3;
13166
13167                 OpSIBLING_set(o, newop);
13168                 OpSIBLING_set(newop, ns3);
13169                 newop->op_lastsib = 0;
13170
13171                 newop->op_flags = (newop->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
13172
13173                 /* Ensure pushmark has this flag if padops do */
13174                 if (pad1->op_flags & OPf_MOD && pad2->op_flags & OPf_MOD) {
13175                     o->op_next->op_flags |= OPf_MOD;
13176                 }
13177
13178                 break;
13179             }
13180
13181             /* Two NEXTSTATEs in a row serve no purpose. Except if they happen
13182                to carry two labels. For now, take the easier option, and skip
13183                this optimisation if the first NEXTSTATE has a label.  */
13184             if (!CopLABEL((COP*)o) && !PERLDB_NOOPT) {
13185                 OP *nextop = o->op_next;
13186                 while (nextop && nextop->op_type == OP_NULL)
13187                     nextop = nextop->op_next;
13188
13189                 if (nextop && (nextop->op_type == OP_NEXTSTATE)) {
13190                     op_null(o);
13191                     if (oldop)
13192                         oldop->op_next = nextop;
13193                     /* Skip (old)oldop assignment since the current oldop's
13194                        op_next already points to the next op.  */
13195                     continue;
13196                 }
13197             }
13198             break;
13199
13200         case OP_CONCAT:
13201             if (o->op_next && o->op_next->op_type == OP_STRINGIFY) {
13202                 if (o->op_next->op_private & OPpTARGET_MY) {
13203                     if (o->op_flags & OPf_STACKED) /* chained concats */
13204                         break; /* ignore_optimization */
13205                     else {
13206                         /* assert(PL_opargs[o->op_type] & OA_TARGLEX); */
13207                         o->op_targ = o->op_next->op_targ;
13208                         o->op_next->op_targ = 0;
13209                         o->op_private |= OPpTARGET_MY;
13210                     }
13211                 }
13212                 op_null(o->op_next);
13213             }
13214             break;
13215         case OP_STUB:
13216             if ((o->op_flags & OPf_WANT) != OPf_WANT_LIST) {
13217                 break; /* Scalar stub must produce undef.  List stub is noop */
13218             }
13219             goto nothin;
13220         case OP_NULL:
13221             if (o->op_targ == OP_NEXTSTATE
13222                 || o->op_targ == OP_DBSTATE)
13223             {
13224                 PL_curcop = ((COP*)o);
13225             }
13226             /* XXX: We avoid setting op_seq here to prevent later calls
13227                to rpeep() from mistakenly concluding that optimisation
13228                has already occurred. This doesn't fix the real problem,
13229                though (See 20010220.007). AMS 20010719 */
13230             /* op_seq functionality is now replaced by op_opt */
13231             o->op_opt = 0;
13232             /* FALLTHROUGH */
13233         case OP_SCALAR:
13234         case OP_LINESEQ:
13235         case OP_SCOPE:
13236         nothin:
13237             if (oldop) {
13238                 oldop->op_next = o->op_next;
13239                 o->op_opt = 0;
13240                 continue;
13241             }
13242             break;
13243
13244         case OP_PUSHMARK:
13245
13246             /* Given
13247                  5 repeat/DOLIST
13248                  3   ex-list
13249                  1     pushmark
13250                  2     scalar or const
13251                  4   const[0]
13252                convert repeat into a stub with no kids.
13253              */
13254             if (o->op_next->op_type == OP_CONST
13255              || (  o->op_next->op_type == OP_PADSV
13256                 && !(o->op_next->op_private & OPpLVAL_INTRO))
13257              || (  o->op_next->op_type == OP_GV
13258                 && o->op_next->op_next->op_type == OP_RV2SV
13259                 && !(o->op_next->op_next->op_private
13260                         & (OPpLVAL_INTRO|OPpOUR_INTRO))))
13261             {
13262                 const OP *kid = o->op_next->op_next;
13263                 if (o->op_next->op_type == OP_GV)
13264                    kid = kid->op_next;
13265                 /* kid is now the ex-list.  */
13266                 if (kid->op_type == OP_NULL
13267                  && (kid = kid->op_next)->op_type == OP_CONST
13268                     /* kid is now the repeat count.  */
13269                  && kid->op_next->op_type == OP_REPEAT
13270                  && kid->op_next->op_private & OPpREPEAT_DOLIST
13271                  && (kid->op_next->op_flags & OPf_WANT) == OPf_WANT_LIST
13272                  && SvIOK(kSVOP_sv) && SvIVX(kSVOP_sv) == 0)
13273                 {
13274                     o = kid->op_next; /* repeat */
13275                     assert(oldop);
13276                     oldop->op_next = o;
13277                     op_free(cBINOPo->op_first);
13278                     op_free(cBINOPo->op_last );
13279                     o->op_flags &=~ OPf_KIDS;
13280                     /* stub is a baseop; repeat is a binop */
13281                     STATIC_ASSERT_STMT(sizeof(OP) <= sizeof(BINOP));
13282                     CHANGE_TYPE(o, OP_STUB);
13283                     o->op_private = 0;
13284                     break;
13285                 }
13286             }
13287
13288             /* Convert a series of PAD ops for my vars plus support into a
13289              * single padrange op. Basically
13290              *
13291              *    pushmark -> pad[ahs]v -> pad[ahs]?v -> ... -> (list) -> rest
13292              *
13293              * becomes, depending on circumstances, one of
13294              *
13295              *    padrange  ----------------------------------> (list) -> rest
13296              *    padrange  --------------------------------------------> rest
13297              *
13298              * where all the pad indexes are sequential and of the same type
13299              * (INTRO or not).
13300              * We convert the pushmark into a padrange op, then skip
13301              * any other pad ops, and possibly some trailing ops.
13302              * Note that we don't null() the skipped ops, to make it
13303              * easier for Deparse to undo this optimisation (and none of
13304              * the skipped ops are holding any resourses). It also makes
13305              * it easier for find_uninit_var(), as it can just ignore
13306              * padrange, and examine the original pad ops.
13307              */
13308         {
13309             OP *p;
13310             OP *followop = NULL; /* the op that will follow the padrange op */
13311             U8 count = 0;
13312             U8 intro = 0;
13313             PADOFFSET base = 0; /* init only to stop compiler whining */
13314             bool gvoid = 0;     /* init only to stop compiler whining */
13315             bool defav = 0;  /* seen (...) = @_ */
13316             bool reuse = 0;  /* reuse an existing padrange op */
13317
13318             /* look for a pushmark -> gv[_] -> rv2av */
13319
13320             {
13321                 OP *rv2av, *q;
13322                 p = o->op_next;
13323                 if (   p->op_type == OP_GV
13324                     && cGVOPx_gv(p) == PL_defgv
13325                     && (rv2av = p->op_next)
13326                     && rv2av->op_type == OP_RV2AV
13327                     && !(rv2av->op_flags & OPf_REF)
13328                     && !(rv2av->op_private & (OPpLVAL_INTRO|OPpMAYBE_LVSUB))
13329                     && ((rv2av->op_flags & OPf_WANT) == OPf_WANT_LIST)
13330                 ) {
13331                     q = rv2av->op_next;
13332                     if (q->op_type == OP_NULL)
13333                         q = q->op_next;
13334                     if (q->op_type == OP_PUSHMARK) {
13335                         defav = 1;
13336                         p = q;
13337                     }
13338                 }
13339             }
13340             if (!defav) {
13341                 p = o;
13342             }
13343
13344             /* scan for PAD ops */
13345
13346             for (p = p->op_next; p; p = p->op_next) {
13347                 if (p->op_type == OP_NULL)
13348                     continue;
13349
13350                 if ((     p->op_type != OP_PADSV
13351                        && p->op_type != OP_PADAV
13352                        && p->op_type != OP_PADHV
13353                     )
13354                       /* any private flag other than INTRO? e.g. STATE */
13355                    || (p->op_private & ~OPpLVAL_INTRO)
13356                 )
13357                     break;
13358
13359                 /* let $a[N] potentially be optimised into AELEMFAST_LEX
13360                  * instead */
13361                 if (   p->op_type == OP_PADAV
13362                     && p->op_next
13363                     && p->op_next->op_type == OP_CONST
13364                     && p->op_next->op_next
13365                     && p->op_next->op_next->op_type == OP_AELEM
13366                 )
13367                     break;
13368
13369                 /* for 1st padop, note what type it is and the range
13370                  * start; for the others, check that it's the same type
13371                  * and that the targs are contiguous */
13372                 if (count == 0) {
13373                     intro = (p->op_private & OPpLVAL_INTRO);
13374                     base = p->op_targ;
13375                     gvoid = OP_GIMME(p,0) == G_VOID;
13376                 }
13377                 else {
13378                     if ((p->op_private & OPpLVAL_INTRO) != intro)
13379                         break;
13380                     /* Note that you'd normally  expect targs to be
13381                      * contiguous in my($a,$b,$c), but that's not the case
13382                      * when external modules start doing things, e.g.
13383                      i* Function::Parameters */
13384                     if (p->op_targ != base + count)
13385                         break;
13386                     assert(p->op_targ == base + count);
13387                     /* Either all the padops or none of the padops should
13388                        be in void context.  Since we only do the optimisa-
13389                        tion for av/hv when the aggregate itself is pushed
13390                        on to the stack (one item), there is no need to dis-
13391                        tinguish list from scalar context.  */
13392                     if (gvoid != (OP_GIMME(p,0) == G_VOID))
13393                         break;
13394                 }
13395
13396                 /* for AV, HV, only when we're not flattening */
13397                 if (   p->op_type != OP_PADSV
13398                     && !gvoid
13399                     && !(p->op_flags & OPf_REF)
13400                 )
13401                     break;
13402
13403                 if (count >= OPpPADRANGE_COUNTMASK)
13404                     break;
13405
13406                 /* there's a biggest base we can fit into a
13407                  * SAVEt_CLEARPADRANGE in pp_padrange */
13408                 if (intro && base >
13409                         (UV_MAX >> (OPpPADRANGE_COUNTSHIFT+SAVE_TIGHT_SHIFT)))
13410                     break;
13411
13412                 /* Success! We've got another valid pad op to optimise away */
13413                 count++;
13414                 followop = p->op_next;
13415             }
13416
13417             if (count < 1 || (count == 1 && !defav))
13418                 break;
13419
13420             /* pp_padrange in specifically compile-time void context
13421              * skips pushing a mark and lexicals; in all other contexts
13422              * (including unknown till runtime) it pushes a mark and the
13423              * lexicals. We must be very careful then, that the ops we
13424              * optimise away would have exactly the same effect as the
13425              * padrange.
13426              * In particular in void context, we can only optimise to
13427              * a padrange if see see the complete sequence
13428              *     pushmark, pad*v, ...., list
13429              * which has the net effect of of leaving the markstack as it
13430              * was.  Not pushing on to the stack (whereas padsv does touch
13431              * the stack) makes no difference in void context.
13432              */
13433             assert(followop);
13434             if (gvoid) {
13435                 if (followop->op_type == OP_LIST
13436                         && OP_GIMME(followop,0) == G_VOID
13437                    )
13438                 {
13439                     followop = followop->op_next; /* skip OP_LIST */
13440
13441                     /* consolidate two successive my(...);'s */
13442
13443                     if (   oldoldop
13444                         && oldoldop->op_type == OP_PADRANGE
13445                         && (oldoldop->op_flags & OPf_WANT) == OPf_WANT_VOID
13446                         && (oldoldop->op_private & OPpLVAL_INTRO) == intro
13447                         && !(oldoldop->op_flags & OPf_SPECIAL)
13448                     ) {
13449                         U8 old_count;
13450                         assert(oldoldop->op_next == oldop);
13451                         assert(   oldop->op_type == OP_NEXTSTATE
13452                                || oldop->op_type == OP_DBSTATE);
13453                         assert(oldop->op_next == o);
13454
13455                         old_count
13456                             = (oldoldop->op_private & OPpPADRANGE_COUNTMASK);
13457
13458                        /* Do not assume pad offsets for $c and $d are con-
13459                           tiguous in
13460                             my ($a,$b,$c);
13461                             my ($d,$e,$f);
13462                         */
13463                         if (  oldoldop->op_targ + old_count == base
13464                            && old_count < OPpPADRANGE_COUNTMASK - count) {
13465                             base = oldoldop->op_targ;
13466                             count += old_count;
13467                             reuse = 1;
13468                         }
13469                     }
13470
13471                     /* if there's any immediately following singleton
13472                      * my var's; then swallow them and the associated
13473                      * nextstates; i.e.
13474                      *    my ($a,$b); my $c; my $d;
13475                      * is treated as
13476                      *    my ($a,$b,$c,$d);
13477                      */
13478
13479                     while (    ((p = followop->op_next))
13480                             && (  p->op_type == OP_PADSV
13481                                || p->op_type == OP_PADAV
13482                                || p->op_type == OP_PADHV)
13483                             && (p->op_flags & OPf_WANT) == OPf_WANT_VOID
13484                             && (p->op_private & OPpLVAL_INTRO) == intro
13485                             && !(p->op_private & ~OPpLVAL_INTRO)
13486                             && p->op_next
13487                             && (   p->op_next->op_type == OP_NEXTSTATE
13488                                 || p->op_next->op_type == OP_DBSTATE)
13489                             && count < OPpPADRANGE_COUNTMASK
13490                             && base + count == p->op_targ
13491                     ) {
13492                         count++;
13493                         followop = p->op_next;
13494                     }
13495                 }
13496                 else
13497                     break;
13498             }
13499
13500             if (reuse) {
13501                 assert(oldoldop->op_type == OP_PADRANGE);
13502                 oldoldop->op_next = followop;
13503                 oldoldop->op_private = (intro | count);
13504                 o = oldoldop;
13505                 oldop = NULL;
13506                 oldoldop = NULL;
13507             }
13508             else {
13509                 /* Convert the pushmark into a padrange.
13510                  * To make Deparse easier, we guarantee that a padrange was
13511                  * *always* formerly a pushmark */
13512                 assert(o->op_type == OP_PUSHMARK);
13513                 o->op_next = followop;
13514                 CHANGE_TYPE(o, OP_PADRANGE);
13515                 o->op_targ = base;
13516                 /* bit 7: INTRO; bit 6..0: count */
13517                 o->op_private = (intro | count);
13518                 o->op_flags = ((o->op_flags & ~(OPf_WANT|OPf_SPECIAL))
13519                               | gvoid * OPf_WANT_VOID
13520                               | (defav ? OPf_SPECIAL : 0));
13521             }
13522             break;
13523         }
13524
13525         case OP_PADAV:
13526         case OP_PADSV:
13527         case OP_PADHV:
13528         /* Skip over state($x) in void context.  */
13529         if (oldop && o->op_private == (OPpPAD_STATE|OPpLVAL_INTRO)
13530          && (o->op_flags & OPf_WANT) == OPf_WANT_VOID)
13531         {
13532             oldop->op_next = o->op_next;
13533             goto redo_nextstate;
13534         }
13535         if (o->op_type != OP_PADAV)
13536             break;
13537         /* FALLTHROUGH */
13538         case OP_GV:
13539             if (o->op_type == OP_PADAV || o->op_next->op_type == OP_RV2AV) {
13540                 OP* const pop = (o->op_type == OP_PADAV) ?
13541                             o->op_next : o->op_next->op_next;
13542                 IV i;
13543                 if (pop && pop->op_type == OP_CONST &&
13544                     ((PL_op = pop->op_next)) &&
13545                     pop->op_next->op_type == OP_AELEM &&
13546                     !(pop->op_next->op_private &
13547                       (OPpLVAL_INTRO|OPpLVAL_DEFER|OPpDEREF|OPpMAYBE_LVSUB)) &&
13548                     (i = SvIV(((SVOP*)pop)->op_sv)) >= -128 && i <= 127)
13549                 {
13550                     GV *gv;
13551                     if (cSVOPx(pop)->op_private & OPpCONST_STRICT)
13552                         no_bareword_allowed(pop);
13553                     if (o->op_type == OP_GV)
13554                         op_null(o->op_next);
13555                     op_null(pop->op_next);
13556                     op_null(pop);
13557                     o->op_flags |= pop->op_next->op_flags & OPf_MOD;
13558                     o->op_next = pop->op_next->op_next;
13559                     o->op_ppaddr = PL_ppaddr[OP_AELEMFAST];
13560                     o->op_private = (U8)i;
13561                     if (o->op_type == OP_GV) {
13562                         gv = cGVOPo_gv;
13563                         GvAVn(gv);
13564                         o->op_type = OP_AELEMFAST;
13565                     }
13566                     else
13567                         o->op_type = OP_AELEMFAST_LEX;
13568                 }
13569                 if (o->op_type != OP_GV)
13570                     break;
13571             }
13572
13573             /* Remove $foo from the op_next chain in void context.  */
13574             if (oldop
13575              && (  o->op_next->op_type == OP_RV2SV
13576                 || o->op_next->op_type == OP_RV2AV
13577                 || o->op_next->op_type == OP_RV2HV  )
13578              && (o->op_next->op_flags & OPf_WANT) == OPf_WANT_VOID
13579              && !(o->op_next->op_private & OPpLVAL_INTRO))
13580             {
13581                 oldop->op_next = o->op_next->op_next;
13582                 /* Reprocess the previous op if it is a nextstate, to
13583                    allow double-nextstate optimisation.  */
13584               redo_nextstate:
13585                 if (oldop->op_type == OP_NEXTSTATE) {
13586                     oldop->op_opt = 0;
13587                     o = oldop;
13588                     oldop = oldoldop;
13589                     oldoldop = NULL;
13590                     goto redo;
13591                 }
13592                 o = oldop;
13593             }
13594             else if (o->op_next->op_type == OP_RV2SV) {
13595                 if (!(o->op_next->op_private & OPpDEREF)) {
13596                     op_null(o->op_next);
13597                     o->op_private |= o->op_next->op_private & (OPpLVAL_INTRO
13598                                                                | OPpOUR_INTRO);
13599                     o->op_next = o->op_next->op_next;
13600                     CHANGE_TYPE(o, OP_GVSV);
13601                 }
13602             }
13603             else if (o->op_next->op_type == OP_READLINE
13604                     && o->op_next->op_next->op_type == OP_CONCAT
13605                     && (o->op_next->op_next->op_flags & OPf_STACKED))
13606             {
13607                 /* Turn "$a .= <FH>" into an OP_RCATLINE. AMS 20010917 */
13608                 CHANGE_TYPE(o, OP_RCATLINE);
13609                 o->op_flags |= OPf_STACKED;
13610                 op_null(o->op_next->op_next);
13611                 op_null(o->op_next);
13612             }
13613
13614             break;
13615         
13616 #define HV_OR_SCALARHV(op)                                   \
13617     (  (op)->op_type == OP_PADHV || (op)->op_type == OP_RV2HV \
13618        ? (op)                                                  \
13619        : (op)->op_type == OP_SCALAR && (op)->op_flags & OPf_KIDS \
13620        && (  cUNOPx(op)->op_first->op_type == OP_PADHV          \
13621           || cUNOPx(op)->op_first->op_type == OP_RV2HV)          \
13622          ? cUNOPx(op)->op_first                                   \
13623          : NULL)
13624
13625         case OP_NOT:
13626             if ((fop = HV_OR_SCALARHV(cUNOP->op_first)))
13627                 fop->op_private |= OPpTRUEBOOL;
13628             break;
13629
13630         case OP_AND:
13631         case OP_OR:
13632         case OP_DOR:
13633             fop = cLOGOP->op_first;
13634             sop = OpSIBLING(fop);
13635             while (cLOGOP->op_other->op_type == OP_NULL)
13636                 cLOGOP->op_other = cLOGOP->op_other->op_next;
13637             while (o->op_next && (   o->op_type == o->op_next->op_type
13638                                   || o->op_next->op_type == OP_NULL))
13639                 o->op_next = o->op_next->op_next;
13640
13641             /* if we're an OR and our next is a AND in void context, we'll
13642                follow it's op_other on short circuit, same for reverse.
13643                We can't do this with OP_DOR since if it's true, its return
13644                value is the underlying value which must be evaluated
13645                by the next op */
13646             if (o->op_next &&
13647                 (
13648                     (IS_AND_OP(o) && IS_OR_OP(o->op_next))
13649                  || (IS_OR_OP(o) && IS_AND_OP(o->op_next))
13650                 )
13651                 && (o->op_next->op_flags & OPf_WANT) == OPf_WANT_VOID
13652             ) {
13653                 o->op_next = ((LOGOP*)o->op_next)->op_other;
13654             }
13655             DEFER(cLOGOP->op_other);
13656           
13657             o->op_opt = 1;
13658             fop = HV_OR_SCALARHV(fop);
13659             if (sop) sop = HV_OR_SCALARHV(sop);
13660             if (fop || sop
13661             ){  
13662                 OP * nop = o;
13663                 OP * lop = o;
13664                 if (!((nop->op_flags & OPf_WANT) == OPf_WANT_VOID)) {
13665                     while (nop && nop->op_next) {
13666                         switch (nop->op_next->op_type) {
13667                             case OP_NOT:
13668                             case OP_AND:
13669                             case OP_OR:
13670                             case OP_DOR:
13671                                 lop = nop = nop->op_next;
13672                                 break;
13673                             case OP_NULL:
13674                                 nop = nop->op_next;
13675                                 break;
13676                             default:
13677                                 nop = NULL;
13678                                 break;
13679                         }
13680                     }            
13681                 }
13682                 if (fop) {
13683                     if (  (lop->op_flags & OPf_WANT) == OPf_WANT_VOID
13684                       || o->op_type == OP_AND  )
13685                         fop->op_private |= OPpTRUEBOOL;
13686                     else if (!(lop->op_flags & OPf_WANT))
13687                         fop->op_private |= OPpMAYBE_TRUEBOOL;
13688                 }
13689                 if (  (lop->op_flags & OPf_WANT) == OPf_WANT_VOID
13690                    && sop)
13691                     sop->op_private |= OPpTRUEBOOL;
13692             }                  
13693             
13694             
13695             break;
13696         
13697         case OP_COND_EXPR:
13698             if ((fop = HV_OR_SCALARHV(cLOGOP->op_first)))
13699                 fop->op_private |= OPpTRUEBOOL;
13700 #undef HV_OR_SCALARHV
13701             /* GERONIMO! */ /* FALLTHROUGH */
13702
13703         case OP_MAPWHILE:
13704         case OP_GREPWHILE:
13705         case OP_ANDASSIGN:
13706         case OP_ORASSIGN:
13707         case OP_DORASSIGN:
13708         case OP_RANGE:
13709         case OP_ONCE:
13710             while (cLOGOP->op_other->op_type == OP_NULL)
13711                 cLOGOP->op_other = cLOGOP->op_other->op_next;
13712             DEFER(cLOGOP->op_other);
13713             break;
13714
13715         case OP_ENTERLOOP:
13716         case OP_ENTERITER:
13717             while (cLOOP->op_redoop->op_type == OP_NULL)
13718                 cLOOP->op_redoop = cLOOP->op_redoop->op_next;
13719             while (cLOOP->op_nextop->op_type == OP_NULL)
13720                 cLOOP->op_nextop = cLOOP->op_nextop->op_next;
13721             while (cLOOP->op_lastop->op_type == OP_NULL)
13722                 cLOOP->op_lastop = cLOOP->op_lastop->op_next;
13723             /* a while(1) loop doesn't have an op_next that escapes the
13724              * loop, so we have to explicitly follow the op_lastop to
13725              * process the rest of the code */
13726             DEFER(cLOOP->op_lastop);
13727             break;
13728
13729         case OP_ENTERTRY:
13730             assert(cLOGOPo->op_other->op_type == OP_LEAVETRY);
13731             DEFER(cLOGOPo->op_other);
13732             break;
13733
13734         case OP_SUBST:
13735             assert(!(cPMOP->op_pmflags & PMf_ONCE));
13736             while (cPMOP->op_pmstashstartu.op_pmreplstart &&
13737                    cPMOP->op_pmstashstartu.op_pmreplstart->op_type == OP_NULL)
13738                 cPMOP->op_pmstashstartu.op_pmreplstart
13739                     = cPMOP->op_pmstashstartu.op_pmreplstart->op_next;
13740             DEFER(cPMOP->op_pmstashstartu.op_pmreplstart);
13741             break;
13742
13743         case OP_SORT: {
13744             OP *oright;
13745
13746             if (o->op_flags & OPf_SPECIAL) {
13747                 /* first arg is a code block */
13748                 OP * const nullop = OpSIBLING(cLISTOP->op_first);
13749                 OP * kid          = cUNOPx(nullop)->op_first;
13750
13751                 assert(nullop->op_type == OP_NULL);
13752                 assert(kid->op_type == OP_SCOPE
13753                  || (kid->op_type == OP_NULL && kid->op_targ == OP_LEAVE));
13754                 /* since OP_SORT doesn't have a handy op_other-style
13755                  * field that can point directly to the start of the code
13756                  * block, store it in the otherwise-unused op_next field
13757                  * of the top-level OP_NULL. This will be quicker at
13758                  * run-time, and it will also allow us to remove leading
13759                  * OP_NULLs by just messing with op_nexts without
13760                  * altering the basic op_first/op_sibling layout. */
13761                 kid = kLISTOP->op_first;
13762                 assert(
13763                       (kid->op_type == OP_NULL
13764                       && (  kid->op_targ == OP_NEXTSTATE
13765                          || kid->op_targ == OP_DBSTATE  ))
13766                     || kid->op_type == OP_STUB
13767                     || kid->op_type == OP_ENTER);
13768                 nullop->op_next = kLISTOP->op_next;
13769                 DEFER(nullop->op_next);
13770             }
13771
13772             /* check that RHS of sort is a single plain array */
13773             oright = cUNOPo->op_first;
13774             if (!oright || oright->op_type != OP_PUSHMARK)
13775                 break;
13776
13777             if (o->op_private & OPpSORT_INPLACE)
13778                 break;
13779
13780             /* reverse sort ... can be optimised.  */
13781             if (!OpHAS_SIBLING(cUNOPo)) {
13782                 /* Nothing follows us on the list. */
13783                 OP * const reverse = o->op_next;
13784
13785                 if (reverse->op_type == OP_REVERSE &&
13786                     (reverse->op_flags & OPf_WANT) == OPf_WANT_LIST) {
13787                     OP * const pushmark = cUNOPx(reverse)->op_first;
13788                     if (pushmark && (pushmark->op_type == OP_PUSHMARK)
13789                         && (OpSIBLING(cUNOPx(pushmark)) == o)) {
13790                         /* reverse -> pushmark -> sort */
13791                         o->op_private |= OPpSORT_REVERSE;
13792                         op_null(reverse);
13793                         pushmark->op_next = oright->op_next;
13794                         op_null(oright);
13795                     }
13796                 }
13797             }
13798
13799             break;
13800         }
13801
13802         case OP_REVERSE: {
13803             OP *ourmark, *theirmark, *ourlast, *iter, *expushmark, *rv2av;
13804             OP *gvop = NULL;
13805             LISTOP *enter, *exlist;
13806
13807             if (o->op_private & OPpSORT_INPLACE)
13808                 break;
13809
13810             enter = (LISTOP *) o->op_next;
13811             if (!enter)
13812                 break;
13813             if (enter->op_type == OP_NULL) {
13814                 enter = (LISTOP *) enter->op_next;
13815                 if (!enter)
13816                     break;
13817             }
13818             /* for $a (...) will have OP_GV then OP_RV2GV here.
13819                for (...) just has an OP_GV.  */
13820             if (enter->op_type == OP_GV) {
13821                 gvop = (OP *) enter;
13822                 enter = (LISTOP *) enter->op_next;
13823                 if (!enter)
13824                     break;
13825                 if (enter->op_type == OP_RV2GV) {
13826                   enter = (LISTOP *) enter->op_next;
13827                   if (!enter)
13828                     break;
13829                 }
13830             }
13831
13832             if (enter->op_type != OP_ENTERITER)
13833                 break;
13834
13835             iter = enter->op_next;
13836             if (!iter || iter->op_type != OP_ITER)
13837                 break;
13838             
13839             expushmark = enter->op_first;
13840             if (!expushmark || expushmark->op_type != OP_NULL
13841                 || expushmark->op_targ != OP_PUSHMARK)
13842                 break;
13843
13844             exlist = (LISTOP *) OpSIBLING(expushmark);
13845             if (!exlist || exlist->op_type != OP_NULL
13846                 || exlist->op_targ != OP_LIST)
13847                 break;
13848
13849             if (exlist->op_last != o) {
13850                 /* Mmm. Was expecting to point back to this op.  */
13851                 break;
13852             }
13853             theirmark = exlist->op_first;
13854             if (!theirmark || theirmark->op_type != OP_PUSHMARK)
13855                 break;
13856
13857             if (OpSIBLING(theirmark) != o) {
13858                 /* There's something between the mark and the reverse, eg
13859                    for (1, reverse (...))
13860                    so no go.  */
13861                 break;
13862             }
13863
13864             ourmark = ((LISTOP *)o)->op_first;
13865             if (!ourmark || ourmark->op_type != OP_PUSHMARK)
13866                 break;
13867
13868             ourlast = ((LISTOP *)o)->op_last;
13869             if (!ourlast || ourlast->op_next != o)
13870                 break;
13871
13872             rv2av = OpSIBLING(ourmark);
13873             if (rv2av && rv2av->op_type == OP_RV2AV && !OpHAS_SIBLING(rv2av)
13874                 && rv2av->op_flags == (OPf_WANT_LIST | OPf_KIDS)
13875                 && enter->op_flags == (OPf_WANT_LIST | OPf_KIDS)) {
13876                 /* We're just reversing a single array.  */
13877                 rv2av->op_flags = OPf_WANT_SCALAR | OPf_KIDS | OPf_REF;
13878                 enter->op_flags |= OPf_STACKED;
13879             }
13880
13881             /* We don't have control over who points to theirmark, so sacrifice
13882                ours.  */
13883             theirmark->op_next = ourmark->op_next;
13884             theirmark->op_flags = ourmark->op_flags;
13885             ourlast->op_next = gvop ? gvop : (OP *) enter;
13886             op_null(ourmark);
13887             op_null(o);
13888             enter->op_private |= OPpITER_REVERSED;
13889             iter->op_private |= OPpITER_REVERSED;
13890             
13891             break;
13892         }
13893
13894         case OP_QR:
13895         case OP_MATCH:
13896             if (!(cPMOP->op_pmflags & PMf_ONCE)) {
13897                 assert (!cPMOP->op_pmstashstartu.op_pmreplstart);
13898             }
13899             break;
13900
13901         case OP_RUNCV:
13902             if (!(o->op_private & OPpOFFBYONE) && !CvCLONE(PL_compcv)
13903              && (!CvANON(PL_compcv) || (!PL_cv_has_eval && !PL_perldb)))
13904             {
13905                 SV *sv;
13906                 if (CvEVAL(PL_compcv)) sv = &PL_sv_undef;
13907                 else {
13908                     sv = newRV((SV *)PL_compcv);
13909                     sv_rvweaken(sv);
13910                     SvREADONLY_on(sv);
13911                 }
13912                 CHANGE_TYPE(o, OP_CONST);
13913                 o->op_flags |= OPf_SPECIAL;
13914                 cSVOPo->op_sv = sv;
13915             }
13916             break;
13917
13918         case OP_SASSIGN:
13919             if (OP_GIMME(o,0) == G_VOID
13920              || (  o->op_next->op_type == OP_LINESEQ
13921                 && (  o->op_next->op_next->op_type == OP_LEAVESUB
13922                    || (  o->op_next->op_next->op_type == OP_RETURN
13923                       && !CvLVALUE(PL_compcv)))))
13924             {
13925                 OP *right = cBINOP->op_first;
13926                 if (right) {
13927                     /*   sassign
13928                     *      RIGHT
13929                     *      substr
13930                     *         pushmark
13931                     *         arg1
13932                     *         arg2
13933                     *         ...
13934                     * becomes
13935                     *
13936                     *  ex-sassign
13937                     *     substr
13938                     *        pushmark
13939                     *        RIGHT
13940                     *        arg1
13941                     *        arg2
13942                     *        ...
13943                     */
13944                     OP *left = OpSIBLING(right);
13945                     if (left->op_type == OP_SUBSTR
13946                          && (left->op_private & 7) < 4) {
13947                         op_null(o);
13948                         /* cut out right */
13949                         op_sibling_splice(o, NULL, 1, NULL);
13950                         /* and insert it as second child of OP_SUBSTR */
13951                         op_sibling_splice(left, cBINOPx(left)->op_first, 0,
13952                                     right);
13953                         left->op_private |= OPpSUBSTR_REPL_FIRST;
13954                         left->op_flags =
13955                             (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
13956                     }
13957                 }
13958             }
13959             break;
13960
13961         case OP_AASSIGN:
13962             /* We do the common-vars check here, rather than in newASSIGNOP
13963                (as formerly), so that all lexical vars that get aliased are
13964                marked as such before we do the check.  */
13965             /* There can’t be common vars if the lhs is a stub.  */
13966             if (OpSIBLING(cLISTOPx(cBINOPo->op_last)->op_first)
13967                     == cLISTOPx(cBINOPo->op_last)->op_last
13968              && cLISTOPx(cBINOPo->op_last)->op_last->op_type == OP_STUB)
13969             {
13970                 o->op_private &=~ OPpASSIGN_COMMON;
13971                 break;
13972             }
13973             if (o->op_private & OPpASSIGN_COMMON) {
13974                  /* See the comment before S_aassign_common_vars concerning
13975                     PL_generation sorcery.  */
13976                 PL_generation++;
13977                 if (!aassign_common_vars(o))
13978                     o->op_private &=~ OPpASSIGN_COMMON;
13979             }
13980             else if (S_aassign_common_vars_aliases_only(aTHX_ o))
13981                 o->op_private |= OPpASSIGN_COMMON;
13982             break;
13983
13984         case OP_CUSTOM: {
13985             Perl_cpeep_t cpeep = 
13986                 XopENTRYCUSTOM(o, xop_peep);
13987             if (cpeep)
13988                 cpeep(aTHX_ o, oldop);
13989             break;
13990         }
13991             
13992         }
13993         /* did we just null the current op? If so, re-process it to handle
13994          * eliding "empty" ops from the chain */
13995         if (o->op_type == OP_NULL && oldop && oldop->op_next == o) {
13996             o->op_opt = 0;
13997             o = oldop;
13998         }
13999         else {
14000             oldoldop = oldop;
14001             oldop = o;
14002         }
14003     }
14004     LEAVE;
14005 }
14006
14007 void
14008 Perl_peep(pTHX_ OP *o)
14009 {
14010     CALL_RPEEP(o);
14011 }
14012
14013 /*
14014 =head1 Custom Operators
14015
14016 =for apidoc Ao||custom_op_xop
14017 Return the XOP structure for a given custom op.  This macro should be
14018 considered internal to OP_NAME and the other access macros: use them instead.
14019 This macro does call a function.  Prior
14020 to 5.19.6, this was implemented as a
14021 function.
14022
14023 =cut
14024 */
14025
14026 XOPRETANY
14027 Perl_custom_op_get_field(pTHX_ const OP *o, const xop_flags_enum field)
14028 {
14029     SV *keysv;
14030     HE *he = NULL;
14031     XOP *xop;
14032
14033     static const XOP xop_null = { 0, 0, 0, 0, 0 };
14034
14035     PERL_ARGS_ASSERT_CUSTOM_OP_GET_FIELD;
14036     assert(o->op_type == OP_CUSTOM);
14037
14038     /* This is wrong. It assumes a function pointer can be cast to IV,
14039      * which isn't guaranteed, but this is what the old custom OP code
14040      * did. In principle it should be safer to Copy the bytes of the
14041      * pointer into a PV: since the new interface is hidden behind
14042      * functions, this can be changed later if necessary.  */
14043     /* Change custom_op_xop if this ever happens */
14044     keysv = sv_2mortal(newSViv(PTR2IV(o->op_ppaddr)));
14045
14046     if (PL_custom_ops)
14047         he = hv_fetch_ent(PL_custom_ops, keysv, 0, 0);
14048
14049     /* assume noone will have just registered a desc */
14050     if (!he && PL_custom_op_names &&
14051         (he = hv_fetch_ent(PL_custom_op_names, keysv, 0, 0))
14052     ) {
14053         const char *pv;
14054         STRLEN l;
14055
14056         /* XXX does all this need to be shared mem? */
14057         Newxz(xop, 1, XOP);
14058         pv = SvPV(HeVAL(he), l);
14059         XopENTRY_set(xop, xop_name, savepvn(pv, l));
14060         if (PL_custom_op_descs &&
14061             (he = hv_fetch_ent(PL_custom_op_descs, keysv, 0, 0))
14062         ) {
14063             pv = SvPV(HeVAL(he), l);
14064             XopENTRY_set(xop, xop_desc, savepvn(pv, l));
14065         }
14066         Perl_custom_op_register(aTHX_ o->op_ppaddr, xop);
14067     }
14068     else {
14069         if (!he)
14070             xop = (XOP *)&xop_null;
14071         else
14072             xop = INT2PTR(XOP *, SvIV(HeVAL(he)));
14073     }
14074     {
14075         XOPRETANY any;
14076         if(field == XOPe_xop_ptr) {
14077             any.xop_ptr = xop;
14078         } else {
14079             const U32 flags = XopFLAGS(xop);
14080             if(flags & field) {
14081                 switch(field) {
14082                 case XOPe_xop_name:
14083                     any.xop_name = xop->xop_name;
14084                     break;
14085                 case XOPe_xop_desc:
14086                     any.xop_desc = xop->xop_desc;
14087                     break;
14088                 case XOPe_xop_class:
14089                     any.xop_class = xop->xop_class;
14090                     break;
14091                 case XOPe_xop_peep:
14092                     any.xop_peep = xop->xop_peep;
14093                     break;
14094                 default:
14095                     NOT_REACHED; /* NOTREACHED */
14096                     break;
14097                 }
14098             } else {
14099                 switch(field) {
14100                 case XOPe_xop_name:
14101                     any.xop_name = XOPd_xop_name;
14102                     break;
14103                 case XOPe_xop_desc:
14104                     any.xop_desc = XOPd_xop_desc;
14105                     break;
14106                 case XOPe_xop_class:
14107                     any.xop_class = XOPd_xop_class;
14108                     break;
14109                 case XOPe_xop_peep:
14110                     any.xop_peep = XOPd_xop_peep;
14111                     break;
14112                 default:
14113                     NOT_REACHED; /* NOTREACHED */
14114                     break;
14115                 }
14116             }
14117         }
14118         /* Some gcc releases emit a warning for this function:
14119          * op.c: In function 'Perl_custom_op_get_field':
14120          * op.c:...: warning: 'any.xop_name' may be used uninitialized in this function [-Wmaybe-uninitialized]
14121          * Whether this is true, is currently unknown. */
14122         return any;
14123     }
14124 }
14125
14126 /*
14127 =for apidoc Ao||custom_op_register
14128 Register a custom op.  See L<perlguts/"Custom Operators">.
14129
14130 =cut
14131 */
14132
14133 void
14134 Perl_custom_op_register(pTHX_ Perl_ppaddr_t ppaddr, const XOP *xop)
14135 {
14136     SV *keysv;
14137
14138     PERL_ARGS_ASSERT_CUSTOM_OP_REGISTER;
14139
14140     /* see the comment in custom_op_xop */
14141     keysv = sv_2mortal(newSViv(PTR2IV(ppaddr)));
14142
14143     if (!PL_custom_ops)
14144         PL_custom_ops = newHV();
14145
14146     if (!hv_store_ent(PL_custom_ops, keysv, newSViv(PTR2IV(xop)), 0))
14147         Perl_croak(aTHX_ "panic: can't register custom OP %s", xop->xop_name);
14148 }
14149
14150 /*
14151
14152 =for apidoc core_prototype
14153
14154 This function assigns the prototype of the named core function to C<sv>, or
14155 to a new mortal SV if C<sv> is NULL.  It returns the modified C<sv>, or
14156 NULL if the core function has no prototype.  C<code> is a code as returned
14157 by C<keyword()>.  It must not be equal to 0.
14158
14159 =cut
14160 */
14161
14162 SV *
14163 Perl_core_prototype(pTHX_ SV *sv, const char *name, const int code,
14164                           int * const opnum)
14165 {
14166     int i = 0, n = 0, seen_question = 0, defgv = 0;
14167     I32 oa;
14168 #define MAX_ARGS_OP ((sizeof(I32) - 1) * 2)
14169     char str[ MAX_ARGS_OP * 2 + 2 ]; /* One ';', one '\0' */
14170     bool nullret = FALSE;
14171
14172     PERL_ARGS_ASSERT_CORE_PROTOTYPE;
14173
14174     assert (code);
14175
14176     if (!sv) sv = sv_newmortal();
14177
14178 #define retsetpvs(x,y) sv_setpvs(sv, x); if(opnum) *opnum=(y); return sv
14179
14180     switch (code < 0 ? -code : code) {
14181     case KEY_and   : case KEY_chop: case KEY_chomp:
14182     case KEY_cmp   : case KEY_defined: case KEY_delete: case KEY_exec  :
14183     case KEY_exists: case KEY_eq     : case KEY_ge    : case KEY_goto  :
14184     case KEY_grep  : case KEY_gt     : case KEY_last  : case KEY_le    :
14185     case KEY_lt    : case KEY_map    : case KEY_ne    : case KEY_next  :
14186     case KEY_or    : case KEY_print  : case KEY_printf: case KEY_qr    :
14187     case KEY_redo  : case KEY_require: case KEY_return: case KEY_say   :
14188     case KEY_select: case KEY_sort   : case KEY_split : case KEY_system:
14189     case KEY_x     : case KEY_xor    :
14190         if (!opnum) return NULL; nullret = TRUE; goto findopnum;
14191     case KEY_glob:    retsetpvs("_;", OP_GLOB);
14192     case KEY_keys:    retsetpvs("+", OP_KEYS);
14193     case KEY_values:  retsetpvs("+", OP_VALUES);
14194     case KEY_each:    retsetpvs("+", OP_EACH);
14195     case KEY_push:    retsetpvs("+@", OP_PUSH);
14196     case KEY_unshift: retsetpvs("+@", OP_UNSHIFT);
14197     case KEY_pop:     retsetpvs(";+", OP_POP);
14198     case KEY_shift:   retsetpvs(";+", OP_SHIFT);
14199     case KEY_pos:     retsetpvs(";\\[$*]", OP_POS);
14200     case KEY_splice:
14201         retsetpvs("+;$$@", OP_SPLICE);
14202     case KEY___FILE__: case KEY___LINE__: case KEY___PACKAGE__:
14203         retsetpvs("", 0);
14204     case KEY_evalbytes:
14205         name = "entereval"; break;
14206     case KEY_readpipe:
14207         name = "backtick";
14208     }
14209
14210 #undef retsetpvs
14211
14212   findopnum:
14213     while (i < MAXO) {  /* The slow way. */
14214         if (strEQ(name, PL_op_name[i])
14215             || strEQ(name, PL_op_desc[i]))
14216         {
14217             if (nullret) { assert(opnum); *opnum = i; return NULL; }
14218             goto found;
14219         }
14220         i++;
14221     }
14222     return NULL;
14223   found:
14224     defgv = PL_opargs[i] & OA_DEFGV;
14225     oa = PL_opargs[i] >> OASHIFT;
14226     while (oa) {
14227         if (oa & OA_OPTIONAL && !seen_question && (
14228               !defgv || (oa & (OA_OPTIONAL - 1)) == OA_FILEREF
14229         )) {
14230             seen_question = 1;
14231             str[n++] = ';';
14232         }
14233         if ((oa & (OA_OPTIONAL - 1)) >= OA_AVREF
14234             && (oa & (OA_OPTIONAL - 1)) <= OA_SCALARREF
14235             /* But globs are already references (kinda) */
14236             && (oa & (OA_OPTIONAL - 1)) != OA_FILEREF
14237         ) {
14238             str[n++] = '\\';
14239         }
14240         if ((oa & (OA_OPTIONAL - 1)) == OA_SCALARREF
14241          && !scalar_mod_type(NULL, i)) {
14242             str[n++] = '[';
14243             str[n++] = '$';
14244             str[n++] = '@';
14245             str[n++] = '%';
14246             if (i == OP_LOCK || i == OP_UNDEF) str[n++] = '&';
14247             str[n++] = '*';
14248             str[n++] = ']';
14249         }
14250         else str[n++] = ("?$@@%&*$")[oa & (OA_OPTIONAL - 1)];
14251         if (oa & OA_OPTIONAL && defgv && str[n-1] == '$') {
14252             str[n-1] = '_'; defgv = 0;
14253         }
14254         oa = oa >> 4;
14255     }
14256     if (code == -KEY_not || code == -KEY_getprotobynumber) str[n++] = ';';
14257     str[n++] = '\0';
14258     sv_setpvn(sv, str, n - 1);
14259     if (opnum) *opnum = i;
14260     return sv;
14261 }
14262
14263 OP *
14264 Perl_coresub_op(pTHX_ SV * const coreargssv, const int code,
14265                       const int opnum)
14266 {
14267     OP * const argop = newSVOP(OP_COREARGS,0,coreargssv);
14268     OP *o;
14269
14270     PERL_ARGS_ASSERT_CORESUB_OP;
14271
14272     switch(opnum) {
14273     case 0:
14274         return op_append_elem(OP_LINESEQ,
14275                        argop,
14276                        newSLICEOP(0,
14277                                   newSVOP(OP_CONST, 0, newSViv(-code % 3)),
14278                                   newOP(OP_CALLER,0)
14279                        )
14280                );
14281     case OP_SELECT: /* which represents OP_SSELECT as well */
14282         if (code)
14283             return newCONDOP(
14284                          0,
14285                          newBINOP(OP_GT, 0,
14286                                   newAVREF(newGVOP(OP_GV, 0, PL_defgv)),
14287                                   newSVOP(OP_CONST, 0, newSVuv(1))
14288                                  ),
14289                          coresub_op(newSVuv((UV)OP_SSELECT), 0,
14290                                     OP_SSELECT),
14291                          coresub_op(coreargssv, 0, OP_SELECT)
14292                    );
14293         /* FALLTHROUGH */
14294     default:
14295         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
14296         case OA_BASEOP:
14297             return op_append_elem(
14298                         OP_LINESEQ, argop,
14299                         newOP(opnum,
14300                               opnum == OP_WANTARRAY || opnum == OP_RUNCV
14301                                 ? OPpOFFBYONE << 8 : 0)
14302                    );
14303         case OA_BASEOP_OR_UNOP:
14304             if (opnum == OP_ENTEREVAL) {
14305                 o = newUNOP(OP_ENTEREVAL,OPpEVAL_COPHH<<8,argop);
14306                 if (code == -KEY_evalbytes) o->op_private |= OPpEVAL_BYTES;
14307             }
14308             else o = newUNOP(opnum,0,argop);
14309             if (opnum == OP_CALLER) o->op_private |= OPpOFFBYONE;
14310             else {
14311           onearg:
14312               if (is_handle_constructor(o, 1))
14313                 argop->op_private |= OPpCOREARGS_DEREF1;
14314               if (scalar_mod_type(NULL, opnum))
14315                 argop->op_private |= OPpCOREARGS_SCALARMOD;
14316             }
14317             return o;
14318         default:
14319             o = op_convert_list(opnum,OPf_SPECIAL*(opnum == OP_GLOB),argop);
14320             if (is_handle_constructor(o, 2))
14321                 argop->op_private |= OPpCOREARGS_DEREF2;
14322             if (opnum == OP_SUBSTR) {
14323                 o->op_private |= OPpMAYBE_LVSUB;
14324                 return o;
14325             }
14326             else goto onearg;
14327         }
14328     }
14329 }
14330
14331 void
14332 Perl_report_redefined_cv(pTHX_ const SV *name, const CV *old_cv,
14333                                SV * const *new_const_svp)
14334 {
14335     const char *hvname;
14336     bool is_const = !!CvCONST(old_cv);
14337     SV *old_const_sv = is_const ? cv_const_sv(old_cv) : NULL;
14338
14339     PERL_ARGS_ASSERT_REPORT_REDEFINED_CV;
14340
14341     if (is_const && new_const_svp && old_const_sv == *new_const_svp)
14342         return;
14343         /* They are 2 constant subroutines generated from
14344            the same constant. This probably means that
14345            they are really the "same" proxy subroutine
14346            instantiated in 2 places. Most likely this is
14347            when a constant is exported twice.  Don't warn.
14348         */
14349     if (
14350         (ckWARN(WARN_REDEFINE)
14351          && !(
14352                 CvGV(old_cv) && GvSTASH(CvGV(old_cv))
14353              && HvNAMELEN(GvSTASH(CvGV(old_cv))) == 7
14354              && (hvname = HvNAME(GvSTASH(CvGV(old_cv))),
14355                  strEQ(hvname, "autouse"))
14356              )
14357         )
14358      || (is_const
14359          && ckWARN_d(WARN_REDEFINE)
14360          && (!new_const_svp || sv_cmp(old_const_sv, *new_const_svp))
14361         )
14362     )
14363         Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
14364                           is_const
14365                             ? "Constant subroutine %"SVf" redefined"
14366                             : "Subroutine %"SVf" redefined",
14367                           SVfARG(name));
14368 }
14369
14370 /*
14371 =head1 Hook manipulation
14372
14373 These functions provide convenient and thread-safe means of manipulating
14374 hook variables.
14375
14376 =cut
14377 */
14378
14379 /*
14380 =for apidoc Am|void|wrap_op_checker|Optype opcode|Perl_check_t new_checker|Perl_check_t *old_checker_p
14381
14382 Puts a C function into the chain of check functions for a specified op
14383 type.  This is the preferred way to manipulate the L</PL_check> array.
14384 I<opcode> specifies which type of op is to be affected.  I<new_checker>
14385 is a pointer to the C function that is to be added to that opcode's
14386 check chain, and I<old_checker_p> points to the storage location where a
14387 pointer to the next function in the chain will be stored.  The value of
14388 I<new_pointer> is written into the L</PL_check> array, while the value
14389 previously stored there is written to I<*old_checker_p>.
14390
14391 The function should be defined like this:
14392
14393     static OP *new_checker(pTHX_ OP *op) { ... }
14394
14395 It is intended to be called in this manner:
14396
14397     new_checker(aTHX_ op)
14398
14399 I<old_checker_p> should be defined like this:
14400
14401     static Perl_check_t old_checker_p;
14402
14403 L</PL_check> is global to an entire process, and a module wishing to
14404 hook op checking may find itself invoked more than once per process,
14405 typically in different threads.  To handle that situation, this function
14406 is idempotent.  The location I<*old_checker_p> must initially (once
14407 per process) contain a null pointer.  A C variable of static duration
14408 (declared at file scope, typically also marked C<static> to give
14409 it internal linkage) will be implicitly initialised appropriately,
14410 if it does not have an explicit initialiser.  This function will only
14411 actually modify the check chain if it finds I<*old_checker_p> to be null.
14412 This function is also thread safe on the small scale.  It uses appropriate
14413 locking to avoid race conditions in accessing L</PL_check>.
14414
14415 When this function is called, the function referenced by I<new_checker>
14416 must be ready to be called, except for I<*old_checker_p> being unfilled.
14417 In a threading situation, I<new_checker> may be called immediately,
14418 even before this function has returned.  I<*old_checker_p> will always
14419 be appropriately set before I<new_checker> is called.  If I<new_checker>
14420 decides not to do anything special with an op that it is given (which
14421 is the usual case for most uses of op check hooking), it must chain the
14422 check function referenced by I<*old_checker_p>.
14423
14424 If you want to influence compilation of calls to a specific subroutine,
14425 then use L</cv_set_call_checker> rather than hooking checking of all
14426 C<entersub> ops.
14427
14428 =cut
14429 */
14430
14431 void
14432 Perl_wrap_op_checker(pTHX_ Optype opcode,
14433     Perl_check_t new_checker, Perl_check_t *old_checker_p)
14434 {
14435     dVAR;
14436
14437     PERL_UNUSED_CONTEXT;
14438     PERL_ARGS_ASSERT_WRAP_OP_CHECKER;
14439     if (*old_checker_p) return;
14440     OP_CHECK_MUTEX_LOCK;
14441     if (!*old_checker_p) {
14442         *old_checker_p = PL_check[opcode];
14443         PL_check[opcode] = new_checker;
14444     }
14445     OP_CHECK_MUTEX_UNLOCK;
14446 }
14447
14448 #include "XSUB.h"
14449
14450 /* Efficient sub that returns a constant scalar value. */
14451 static void
14452 const_sv_xsub(pTHX_ CV* cv)
14453 {
14454     dXSARGS;
14455     SV *const sv = MUTABLE_SV(XSANY.any_ptr);
14456     PERL_UNUSED_ARG(items);
14457     if (!sv) {
14458         XSRETURN(0);
14459     }
14460     EXTEND(sp, 1);
14461     ST(0) = sv;
14462     XSRETURN(1);
14463 }
14464
14465 static void
14466 const_av_xsub(pTHX_ CV* cv)
14467 {
14468     dXSARGS;
14469     AV * const av = MUTABLE_AV(XSANY.any_ptr);
14470     SP -= items;
14471     assert(av);
14472 #ifndef DEBUGGING
14473     if (!av) {
14474         XSRETURN(0);
14475     }
14476 #endif
14477     if (SvRMAGICAL(av))
14478         Perl_croak(aTHX_ "Magical list constants are not supported");
14479     if (GIMME_V != G_ARRAY) {
14480         EXTEND(SP, 1);
14481         ST(0) = sv_2mortal(newSViv((IV)AvFILLp(av)+1));
14482         XSRETURN(1);
14483     }
14484     EXTEND(SP, AvFILLp(av)+1);
14485     Copy(AvARRAY(av), &ST(0), AvFILLp(av)+1, SV *);
14486     XSRETURN(AvFILLp(av)+1);
14487 }
14488
14489 /*
14490  * Local variables:
14491  * c-indentation-style: bsd
14492  * c-basic-offset: 4
14493  * indent-tabs-mode: nil
14494  * End:
14495  *
14496  * ex: set ts=8 sts=4 sw=4 et:
14497  */