This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
infnan: add nan_signaling_set
[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         return;
2735     }
2736     CHANGE_TYPE(o, OP_LVREF);
2737     o->op_private &=
2738         OPpLVAL_INTRO|OPpLVREF_ELEM|OPpLVREF_TYPE|OPpPAD_STATE;
2739     if (type == OP_ENTERLOOP)
2740         o->op_private |= OPpLVREF_ITER;
2741 }
2742
2743 OP *
2744 Perl_op_lvalue_flags(pTHX_ OP *o, I32 type, U32 flags)
2745 {
2746     dVAR;
2747     OP *kid;
2748     /* -1 = error on localize, 0 = ignore localize, 1 = ok to localize */
2749     int localize = -1;
2750
2751     if (!o || (PL_parser && PL_parser->error_count))
2752         return o;
2753
2754     if ((o->op_private & OPpTARGET_MY)
2755         && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
2756     {
2757         return o;
2758     }
2759
2760     assert( (o->op_flags & OPf_WANT) != OPf_WANT_VOID );
2761
2762     if (type == OP_PRTF || type == OP_SPRINTF) type = OP_ENTERSUB;
2763
2764     switch (o->op_type) {
2765     case OP_UNDEF:
2766         PL_modcount++;
2767         return o;
2768     case OP_STUB:
2769         if ((o->op_flags & OPf_PARENS))
2770             break;
2771         goto nomod;
2772     case OP_ENTERSUB:
2773         if ((type == OP_UNDEF || type == OP_REFGEN || type == OP_LOCK) &&
2774             !(o->op_flags & OPf_STACKED)) {
2775             CHANGE_TYPE(o, OP_RV2CV);           /* entersub => rv2cv */
2776             assert(cUNOPo->op_first->op_type == OP_NULL);
2777             op_null(((LISTOP*)cUNOPo->op_first)->op_first);/* disable pushmark */
2778             break;
2779         }
2780         else {                          /* lvalue subroutine call */
2781             o->op_private |= OPpLVAL_INTRO;
2782             PL_modcount = RETURN_UNLIMITED_NUMBER;
2783             if (type == OP_GREPSTART || type == OP_ENTERSUB
2784              || type == OP_REFGEN    || type == OP_LEAVESUBLV) {
2785                 /* Potential lvalue context: */
2786                 o->op_private |= OPpENTERSUB_INARGS;
2787                 break;
2788             }
2789             else {                      /* Compile-time error message: */
2790                 OP *kid = cUNOPo->op_first;
2791                 CV *cv;
2792                 GV *gv;
2793
2794                 if (kid->op_type != OP_PUSHMARK) {
2795                     if (kid->op_type != OP_NULL || kid->op_targ != OP_LIST)
2796                         Perl_croak(aTHX_
2797                                 "panic: unexpected lvalue entersub "
2798                                 "args: type/targ %ld:%"UVuf,
2799                                 (long)kid->op_type, (UV)kid->op_targ);
2800                     kid = kLISTOP->op_first;
2801                 }
2802                 while (OpHAS_SIBLING(kid))
2803                     kid = OpSIBLING(kid);
2804                 if (!(kid->op_type == OP_NULL && kid->op_targ == OP_RV2CV)) {
2805                     break;      /* Postpone until runtime */
2806                 }
2807
2808                 kid = kUNOP->op_first;
2809                 if (kid->op_type == OP_NULL && kid->op_targ == OP_RV2SV)
2810                     kid = kUNOP->op_first;
2811                 if (kid->op_type == OP_NULL)
2812                     Perl_croak(aTHX_
2813                                "Unexpected constant lvalue entersub "
2814                                "entry via type/targ %ld:%"UVuf,
2815                                (long)kid->op_type, (UV)kid->op_targ);
2816                 if (kid->op_type != OP_GV) {
2817                     break;
2818                 }
2819
2820                 gv = kGVOP_gv;
2821                 cv = isGV(gv)
2822                     ? GvCV(gv)
2823                     : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
2824                         ? MUTABLE_CV(SvRV(gv))
2825                         : NULL;
2826                 if (!cv)
2827                     break;
2828                 if (CvLVALUE(cv))
2829                     break;
2830             }
2831         }
2832         /* FALLTHROUGH */
2833     default:
2834       nomod:
2835         if (flags & OP_LVALUE_NO_CROAK) return NULL;
2836         /* grep, foreach, subcalls, refgen */
2837         if (type == OP_GREPSTART || type == OP_ENTERSUB
2838          || type == OP_REFGEN    || type == OP_LEAVESUBLV)
2839             break;
2840         yyerror(Perl_form(aTHX_ "Can't modify %s in %s",
2841                      (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)
2842                       ? "do block"
2843                       : (o->op_type == OP_ENTERSUB
2844                         ? "non-lvalue subroutine call"
2845                         : OP_DESC(o))),
2846                      type ? PL_op_desc[type] : "local"));
2847         return o;
2848
2849     case OP_PREINC:
2850     case OP_PREDEC:
2851     case OP_POW:
2852     case OP_MULTIPLY:
2853     case OP_DIVIDE:
2854     case OP_MODULO:
2855     case OP_ADD:
2856     case OP_SUBTRACT:
2857     case OP_CONCAT:
2858     case OP_LEFT_SHIFT:
2859     case OP_RIGHT_SHIFT:
2860     case OP_BIT_AND:
2861     case OP_BIT_XOR:
2862     case OP_BIT_OR:
2863     case OP_I_MULTIPLY:
2864     case OP_I_DIVIDE:
2865     case OP_I_MODULO:
2866     case OP_I_ADD:
2867     case OP_I_SUBTRACT:
2868         if (!(o->op_flags & OPf_STACKED))
2869             goto nomod;
2870         PL_modcount++;
2871         break;
2872
2873     case OP_REPEAT:
2874         if (o->op_flags & OPf_STACKED) {
2875             PL_modcount++;
2876             break;
2877         }
2878         if (!(o->op_private & OPpREPEAT_DOLIST))
2879             goto nomod;
2880         else {
2881             const I32 mods = PL_modcount;
2882             modkids(cBINOPo->op_first, type);
2883             if (type != OP_AASSIGN)
2884                 goto nomod;
2885             kid = cBINOPo->op_last;
2886             if (kid->op_type == OP_CONST && SvIOK(kSVOP_sv)) {
2887                 const IV iv = SvIV(kSVOP_sv);
2888                 if (PL_modcount != RETURN_UNLIMITED_NUMBER)
2889                     PL_modcount =
2890                         mods + (PL_modcount - mods) * (iv < 0 ? 0 : iv);
2891             }
2892             else
2893                 PL_modcount = RETURN_UNLIMITED_NUMBER;
2894         }
2895         break;
2896
2897     case OP_COND_EXPR:
2898         localize = 1;
2899         for (kid = OpSIBLING(cUNOPo->op_first); kid; kid = OpSIBLING(kid))
2900             op_lvalue(kid, type);
2901         break;
2902
2903     case OP_RV2AV:
2904     case OP_RV2HV:
2905         if (type == OP_REFGEN && o->op_flags & OPf_PARENS) {
2906            PL_modcount = RETURN_UNLIMITED_NUMBER;
2907             return o;           /* Treat \(@foo) like ordinary list. */
2908         }
2909         /* FALLTHROUGH */
2910     case OP_RV2GV:
2911         if (scalar_mod_type(o, type))
2912             goto nomod;
2913         ref(cUNOPo->op_first, o->op_type);
2914         /* FALLTHROUGH */
2915     case OP_ASLICE:
2916     case OP_HSLICE:
2917         localize = 1;
2918         /* FALLTHROUGH */
2919     case OP_AASSIGN:
2920         /* Do not apply the lvsub flag for rv2[ah]v in scalar context.  */
2921         if (type == OP_LEAVESUBLV && (
2922                 (o->op_type != OP_RV2AV && o->op_type != OP_RV2HV)
2923              || (o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
2924            ))
2925             o->op_private |= OPpMAYBE_LVSUB;
2926         /* FALLTHROUGH */
2927     case OP_NEXTSTATE:
2928     case OP_DBSTATE:
2929        PL_modcount = RETURN_UNLIMITED_NUMBER;
2930         break;
2931     case OP_KVHSLICE:
2932     case OP_KVASLICE:
2933         if (type == OP_LEAVESUBLV)
2934             o->op_private |= OPpMAYBE_LVSUB;
2935         goto nomod;
2936     case OP_AV2ARYLEN:
2937         PL_hints |= HINT_BLOCK_SCOPE;
2938         if (type == OP_LEAVESUBLV)
2939             o->op_private |= OPpMAYBE_LVSUB;
2940         PL_modcount++;
2941         break;
2942     case OP_RV2SV:
2943         ref(cUNOPo->op_first, o->op_type);
2944         localize = 1;
2945         /* FALLTHROUGH */
2946     case OP_GV:
2947         PL_hints |= HINT_BLOCK_SCOPE;
2948         /* FALLTHROUGH */
2949     case OP_SASSIGN:
2950     case OP_ANDASSIGN:
2951     case OP_ORASSIGN:
2952     case OP_DORASSIGN:
2953         PL_modcount++;
2954         break;
2955
2956     case OP_AELEMFAST:
2957     case OP_AELEMFAST_LEX:
2958         localize = -1;
2959         PL_modcount++;
2960         break;
2961
2962     case OP_PADAV:
2963     case OP_PADHV:
2964        PL_modcount = RETURN_UNLIMITED_NUMBER;
2965         if (type == OP_REFGEN && o->op_flags & OPf_PARENS)
2966             return o;           /* Treat \(@foo) like ordinary list. */
2967         if (scalar_mod_type(o, type))
2968             goto nomod;
2969         if ((o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
2970           && type == OP_LEAVESUBLV)
2971             o->op_private |= OPpMAYBE_LVSUB;
2972         /* FALLTHROUGH */
2973     case OP_PADSV:
2974         PL_modcount++;
2975         if (!type) /* local() */
2976             Perl_croak(aTHX_ "Can't localize lexical variable %"PNf,
2977                               PNfARG(PAD_COMPNAME(o->op_targ)));
2978         if (!(o->op_private & OPpLVAL_INTRO)
2979          || (  type != OP_SASSIGN && type != OP_AASSIGN
2980             && PadnameIsSTATE(PAD_COMPNAME_SV(o->op_targ))  ))
2981             S_mark_padname_lvalue(aTHX_ PAD_COMPNAME_SV(o->op_targ));
2982         break;
2983
2984     case OP_PUSHMARK:
2985         localize = 0;
2986         break;
2987
2988     case OP_KEYS:
2989     case OP_RKEYS:
2990         if (type != OP_SASSIGN && type != OP_LEAVESUBLV)
2991             goto nomod;
2992         goto lvalue_func;
2993     case OP_SUBSTR:
2994         if (o->op_private == 4) /* don't allow 4 arg substr as lvalue */
2995             goto nomod;
2996         /* FALLTHROUGH */
2997     case OP_POS:
2998     case OP_VEC:
2999       lvalue_func:
3000         if (type == OP_LEAVESUBLV)
3001             o->op_private |= OPpMAYBE_LVSUB;
3002         if (o->op_flags & OPf_KIDS)
3003             op_lvalue(OpSIBLING(cBINOPo->op_first), type);
3004         break;
3005
3006     case OP_AELEM:
3007     case OP_HELEM:
3008         ref(cBINOPo->op_first, o->op_type);
3009         if (type == OP_ENTERSUB &&
3010              !(o->op_private & (OPpLVAL_INTRO | OPpDEREF)))
3011             o->op_private |= OPpLVAL_DEFER;
3012         if (type == OP_LEAVESUBLV)
3013             o->op_private |= OPpMAYBE_LVSUB;
3014         localize = 1;
3015         PL_modcount++;
3016         break;
3017
3018     case OP_LEAVE:
3019     case OP_LEAVELOOP:
3020         o->op_private |= OPpLVALUE;
3021         /* FALLTHROUGH */
3022     case OP_SCOPE:
3023     case OP_ENTER:
3024     case OP_LINESEQ:
3025         localize = 0;
3026         if (o->op_flags & OPf_KIDS)
3027             op_lvalue(cLISTOPo->op_last, type);
3028         break;
3029
3030     case OP_NULL:
3031         localize = 0;
3032         if (o->op_flags & OPf_SPECIAL)          /* do BLOCK */
3033             goto nomod;
3034         else if (!(o->op_flags & OPf_KIDS))
3035             break;
3036         if (o->op_targ != OP_LIST) {
3037             op_lvalue(cBINOPo->op_first, type);
3038             break;
3039         }
3040         /* FALLTHROUGH */
3041     case OP_LIST:
3042         localize = 0;
3043         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
3044             /* elements might be in void context because the list is
3045                in scalar context or because they are attribute sub calls */
3046             if ( (kid->op_flags & OPf_WANT) != OPf_WANT_VOID )
3047                 op_lvalue(kid, type);
3048         break;
3049
3050     case OP_COREARGS:
3051         return o;
3052
3053     case OP_AND:
3054     case OP_OR:
3055         if (type == OP_LEAVESUBLV
3056          || !S_vivifies(cLOGOPo->op_first->op_type))
3057             op_lvalue(cLOGOPo->op_first, type);
3058         if (type == OP_LEAVESUBLV
3059          || !S_vivifies(OpSIBLING(cLOGOPo->op_first)->op_type))
3060             op_lvalue(OpSIBLING(cLOGOPo->op_first), type);
3061         goto nomod;
3062
3063     case OP_SREFGEN:
3064         if (type != OP_AASSIGN && type != OP_SASSIGN
3065          && type != OP_ENTERLOOP)
3066             goto nomod;
3067         /* Don’t bother applying lvalue context to the ex-list.  */
3068         kid = cUNOPx(cUNOPo->op_first)->op_first;
3069         assert (!OpHAS_SIBLING(kid));
3070         goto kid_2lvref;
3071     case OP_REFGEN:
3072         if (type != OP_AASSIGN) goto nomod;
3073         kid = cUNOPo->op_first;
3074       kid_2lvref:
3075         {
3076             const U8 ec = PL_parser ? PL_parser->error_count : 0;
3077             S_lvref(aTHX_ kid, type);
3078             if (!PL_parser || PL_parser->error_count == ec) {
3079                 if (!FEATURE_REFALIASING_IS_ENABLED)
3080                     Perl_croak(aTHX_
3081                        "Experimental aliasing via reference not enabled");
3082                 Perl_ck_warner_d(aTHX_
3083                                  packWARN(WARN_EXPERIMENTAL__REFALIASING),
3084                                 "Aliasing via reference is experimental");
3085             }
3086         }
3087         if (o->op_type == OP_REFGEN)
3088             op_null(cUNOPx(cUNOPo->op_first)->op_first); /* pushmark */
3089         op_null(o);
3090         return o;
3091
3092     case OP_SPLIT:
3093         kid = cLISTOPo->op_first;
3094         if (kid && kid->op_type == OP_PUSHRE &&
3095                 (  kid->op_targ
3096                 || o->op_flags & OPf_STACKED
3097 #ifdef USE_ITHREADS
3098                 || ((PMOP*)kid)->op_pmreplrootu.op_pmtargetoff
3099 #else
3100                 || ((PMOP*)kid)->op_pmreplrootu.op_pmtargetgv
3101 #endif
3102         )) {
3103             /* This is actually @array = split.  */
3104             PL_modcount = RETURN_UNLIMITED_NUMBER;
3105             break;
3106         }
3107         goto nomod;
3108
3109     case OP_SCALAR:
3110         op_lvalue(cUNOPo->op_first, OP_ENTERSUB);
3111         goto nomod;
3112     }
3113
3114     /* [20011101.069] File test operators interpret OPf_REF to mean that
3115        their argument is a filehandle; thus \stat(".") should not set
3116        it. AMS 20011102 */
3117     if (type == OP_REFGEN &&
3118         PL_check[o->op_type] == Perl_ck_ftst)
3119         return o;
3120
3121     if (type != OP_LEAVESUBLV)
3122         o->op_flags |= OPf_MOD;
3123
3124     if (type == OP_AASSIGN || type == OP_SASSIGN)
3125         o->op_flags |= OPf_SPECIAL|OPf_REF;
3126     else if (!type) { /* local() */
3127         switch (localize) {
3128         case 1:
3129             o->op_private |= OPpLVAL_INTRO;
3130             o->op_flags &= ~OPf_SPECIAL;
3131             PL_hints |= HINT_BLOCK_SCOPE;
3132             break;
3133         case 0:
3134             break;
3135         case -1:
3136             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
3137                            "Useless localization of %s", OP_DESC(o));
3138         }
3139     }
3140     else if (type != OP_GREPSTART && type != OP_ENTERSUB
3141              && type != OP_LEAVESUBLV)
3142         o->op_flags |= OPf_REF;
3143     return o;
3144 }
3145
3146 STATIC bool
3147 S_scalar_mod_type(const OP *o, I32 type)
3148 {
3149     switch (type) {
3150     case OP_POS:
3151     case OP_SASSIGN:
3152         if (o && o->op_type == OP_RV2GV)
3153             return FALSE;
3154         /* FALLTHROUGH */
3155     case OP_PREINC:
3156     case OP_PREDEC:
3157     case OP_POSTINC:
3158     case OP_POSTDEC:
3159     case OP_I_PREINC:
3160     case OP_I_PREDEC:
3161     case OP_I_POSTINC:
3162     case OP_I_POSTDEC:
3163     case OP_POW:
3164     case OP_MULTIPLY:
3165     case OP_DIVIDE:
3166     case OP_MODULO:
3167     case OP_REPEAT:
3168     case OP_ADD:
3169     case OP_SUBTRACT:
3170     case OP_I_MULTIPLY:
3171     case OP_I_DIVIDE:
3172     case OP_I_MODULO:
3173     case OP_I_ADD:
3174     case OP_I_SUBTRACT:
3175     case OP_LEFT_SHIFT:
3176     case OP_RIGHT_SHIFT:
3177     case OP_BIT_AND:
3178     case OP_BIT_XOR:
3179     case OP_BIT_OR:
3180     case OP_CONCAT:
3181     case OP_SUBST:
3182     case OP_TRANS:
3183     case OP_TRANSR:
3184     case OP_READ:
3185     case OP_SYSREAD:
3186     case OP_RECV:
3187     case OP_ANDASSIGN:
3188     case OP_ORASSIGN:
3189     case OP_DORASSIGN:
3190         return TRUE;
3191     default:
3192         return FALSE;
3193     }
3194 }
3195
3196 STATIC bool
3197 S_is_handle_constructor(const OP *o, I32 numargs)
3198 {
3199     PERL_ARGS_ASSERT_IS_HANDLE_CONSTRUCTOR;
3200
3201     switch (o->op_type) {
3202     case OP_PIPE_OP:
3203     case OP_SOCKPAIR:
3204         if (numargs == 2)
3205             return TRUE;
3206         /* FALLTHROUGH */
3207     case OP_SYSOPEN:
3208     case OP_OPEN:
3209     case OP_SELECT:             /* XXX c.f. SelectSaver.pm */
3210     case OP_SOCKET:
3211     case OP_OPEN_DIR:
3212     case OP_ACCEPT:
3213         if (numargs == 1)
3214             return TRUE;
3215         /* FALLTHROUGH */
3216     default:
3217         return FALSE;
3218     }
3219 }
3220
3221 static OP *
3222 S_refkids(pTHX_ OP *o, I32 type)
3223 {
3224     if (o && o->op_flags & OPf_KIDS) {
3225         OP *kid;
3226         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
3227             ref(kid, type);
3228     }
3229     return o;
3230 }
3231
3232 OP *
3233 Perl_doref(pTHX_ OP *o, I32 type, bool set_op_ref)
3234 {
3235     dVAR;
3236     OP *kid;
3237
3238     PERL_ARGS_ASSERT_DOREF;
3239
3240     if (!o || (PL_parser && PL_parser->error_count))
3241         return o;
3242
3243     switch (o->op_type) {
3244     case OP_ENTERSUB:
3245         if ((type == OP_EXISTS || type == OP_DEFINED) &&
3246             !(o->op_flags & OPf_STACKED)) {
3247             CHANGE_TYPE(o, OP_RV2CV);             /* entersub => rv2cv */
3248             assert(cUNOPo->op_first->op_type == OP_NULL);
3249             op_null(((LISTOP*)cUNOPo->op_first)->op_first);     /* disable pushmark */
3250             o->op_flags |= OPf_SPECIAL;
3251         }
3252         else if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV){
3253             o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
3254                               : type == OP_RV2HV ? OPpDEREF_HV
3255                               : OPpDEREF_SV);
3256             o->op_flags |= OPf_MOD;
3257         }
3258
3259         break;
3260
3261     case OP_COND_EXPR:
3262         for (kid = OpSIBLING(cUNOPo->op_first); kid; kid = OpSIBLING(kid))
3263             doref(kid, type, set_op_ref);
3264         break;
3265     case OP_RV2SV:
3266         if (type == OP_DEFINED)
3267             o->op_flags |= OPf_SPECIAL;         /* don't create GV */
3268         doref(cUNOPo->op_first, o->op_type, set_op_ref);
3269         /* FALLTHROUGH */
3270     case OP_PADSV:
3271         if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
3272             o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
3273                               : type == OP_RV2HV ? OPpDEREF_HV
3274                               : OPpDEREF_SV);
3275             o->op_flags |= OPf_MOD;
3276         }
3277         break;
3278
3279     case OP_RV2AV:
3280     case OP_RV2HV:
3281         if (set_op_ref)
3282             o->op_flags |= OPf_REF;
3283         /* FALLTHROUGH */
3284     case OP_RV2GV:
3285         if (type == OP_DEFINED)
3286             o->op_flags |= OPf_SPECIAL;         /* don't create GV */
3287         doref(cUNOPo->op_first, o->op_type, set_op_ref);
3288         break;
3289
3290     case OP_PADAV:
3291     case OP_PADHV:
3292         if (set_op_ref)
3293             o->op_flags |= OPf_REF;
3294         break;
3295
3296     case OP_SCALAR:
3297     case OP_NULL:
3298         if (!(o->op_flags & OPf_KIDS) || type == OP_DEFINED)
3299             break;
3300         doref(cBINOPo->op_first, type, set_op_ref);
3301         break;
3302     case OP_AELEM:
3303     case OP_HELEM:
3304         doref(cBINOPo->op_first, o->op_type, set_op_ref);
3305         if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
3306             o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
3307                               : type == OP_RV2HV ? OPpDEREF_HV
3308                               : OPpDEREF_SV);
3309             o->op_flags |= OPf_MOD;
3310         }
3311         break;
3312
3313     case OP_SCOPE:
3314     case OP_LEAVE:
3315         set_op_ref = FALSE;
3316         /* FALLTHROUGH */
3317     case OP_ENTER:
3318     case OP_LIST:
3319         if (!(o->op_flags & OPf_KIDS))
3320             break;
3321         doref(cLISTOPo->op_last, type, set_op_ref);
3322         break;
3323     default:
3324         break;
3325     }
3326     return scalar(o);
3327
3328 }
3329
3330 STATIC OP *
3331 S_dup_attrlist(pTHX_ OP *o)
3332 {
3333     OP *rop;
3334
3335     PERL_ARGS_ASSERT_DUP_ATTRLIST;
3336
3337     /* An attrlist is either a simple OP_CONST or an OP_LIST with kids,
3338      * where the first kid is OP_PUSHMARK and the remaining ones
3339      * are OP_CONST.  We need to push the OP_CONST values.
3340      */
3341     if (o->op_type == OP_CONST)
3342         rop = newSVOP(OP_CONST, o->op_flags, SvREFCNT_inc_NN(cSVOPo->op_sv));
3343     else {
3344         assert((o->op_type == OP_LIST) && (o->op_flags & OPf_KIDS));
3345         rop = NULL;
3346         for (o = cLISTOPo->op_first; o; o = OpSIBLING(o)) {
3347             if (o->op_type == OP_CONST)
3348                 rop = op_append_elem(OP_LIST, rop,
3349                                   newSVOP(OP_CONST, o->op_flags,
3350                                           SvREFCNT_inc_NN(cSVOPo->op_sv)));
3351         }
3352     }
3353     return rop;
3354 }
3355
3356 STATIC void
3357 S_apply_attrs(pTHX_ HV *stash, SV *target, OP *attrs)
3358 {
3359     SV * const stashsv = stash ? newSVhek(HvNAME_HEK(stash)) : &PL_sv_no;
3360
3361     PERL_ARGS_ASSERT_APPLY_ATTRS;
3362
3363     /* fake up C<use attributes $pkg,$rv,@attrs> */
3364
3365 #define ATTRSMODULE "attributes"
3366 #define ATTRSMODULE_PM "attributes.pm"
3367
3368     Perl_load_module(aTHX_ PERL_LOADMOD_IMPORT_OPS,
3369                          newSVpvs(ATTRSMODULE),
3370                          NULL,
3371                          op_prepend_elem(OP_LIST,
3372                                       newSVOP(OP_CONST, 0, stashsv),
3373                                       op_prepend_elem(OP_LIST,
3374                                                    newSVOP(OP_CONST, 0,
3375                                                            newRV(target)),
3376                                                    dup_attrlist(attrs))));
3377 }
3378
3379 STATIC void
3380 S_apply_attrs_my(pTHX_ HV *stash, OP *target, OP *attrs, OP **imopsp)
3381 {
3382     OP *pack, *imop, *arg;
3383     SV *meth, *stashsv, **svp;
3384
3385     PERL_ARGS_ASSERT_APPLY_ATTRS_MY;
3386
3387     if (!attrs)
3388         return;
3389
3390     assert(target->op_type == OP_PADSV ||
3391            target->op_type == OP_PADHV ||
3392            target->op_type == OP_PADAV);
3393
3394     /* Ensure that attributes.pm is loaded. */
3395     /* Don't force the C<use> if we don't need it. */
3396     svp = hv_fetchs(GvHVn(PL_incgv), ATTRSMODULE_PM, FALSE);
3397     if (svp && *svp != &PL_sv_undef)
3398         NOOP;   /* already in %INC */
3399     else
3400         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
3401                                newSVpvs(ATTRSMODULE), NULL);
3402
3403     /* Need package name for method call. */
3404     pack = newSVOP(OP_CONST, 0, newSVpvs(ATTRSMODULE));
3405
3406     /* Build up the real arg-list. */
3407     stashsv = stash ? newSVhek(HvNAME_HEK(stash)) : &PL_sv_no;
3408
3409     arg = newOP(OP_PADSV, 0);
3410     arg->op_targ = target->op_targ;
3411     arg = op_prepend_elem(OP_LIST,
3412                        newSVOP(OP_CONST, 0, stashsv),
3413                        op_prepend_elem(OP_LIST,
3414                                     newUNOP(OP_REFGEN, 0,
3415                                             op_lvalue(arg, OP_REFGEN)),
3416                                     dup_attrlist(attrs)));
3417
3418     /* Fake up a method call to import */
3419     meth = newSVpvs_share("import");
3420     imop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL|OPf_WANT_VOID,
3421                    op_append_elem(OP_LIST,
3422                                op_prepend_elem(OP_LIST, pack, arg),
3423                                newMETHOP_named(OP_METHOD_NAMED, 0, meth)));
3424
3425     /* Combine the ops. */
3426     *imopsp = op_append_elem(OP_LIST, *imopsp, imop);
3427 }
3428
3429 /*
3430 =notfor apidoc apply_attrs_string
3431
3432 Attempts to apply a list of attributes specified by the C<attrstr> and
3433 C<len> arguments to the subroutine identified by the C<cv> argument which
3434 is expected to be associated with the package identified by the C<stashpv>
3435 argument (see L<attributes>).  It gets this wrong, though, in that it
3436 does not correctly identify the boundaries of the individual attribute
3437 specifications within C<attrstr>.  This is not really intended for the
3438 public API, but has to be listed here for systems such as AIX which
3439 need an explicit export list for symbols.  (It's called from XS code
3440 in support of the C<ATTRS:> keyword from F<xsubpp>.)  Patches to fix it
3441 to respect attribute syntax properly would be welcome.
3442
3443 =cut
3444 */
3445
3446 void
3447 Perl_apply_attrs_string(pTHX_ const char *stashpv, CV *cv,
3448                         const char *attrstr, STRLEN len)
3449 {
3450     OP *attrs = NULL;
3451
3452     PERL_ARGS_ASSERT_APPLY_ATTRS_STRING;
3453
3454     if (!len) {
3455         len = strlen(attrstr);
3456     }
3457
3458     while (len) {
3459         for (; isSPACE(*attrstr) && len; --len, ++attrstr) ;
3460         if (len) {
3461             const char * const sstr = attrstr;
3462             for (; !isSPACE(*attrstr) && len; --len, ++attrstr) ;
3463             attrs = op_append_elem(OP_LIST, attrs,
3464                                 newSVOP(OP_CONST, 0,
3465                                         newSVpvn(sstr, attrstr-sstr)));
3466         }
3467     }
3468
3469     Perl_load_module(aTHX_ PERL_LOADMOD_IMPORT_OPS,
3470                      newSVpvs(ATTRSMODULE),
3471                      NULL, op_prepend_elem(OP_LIST,
3472                                   newSVOP(OP_CONST, 0, newSVpv(stashpv,0)),
3473                                   op_prepend_elem(OP_LIST,
3474                                                newSVOP(OP_CONST, 0,
3475                                                        newRV(MUTABLE_SV(cv))),
3476                                                attrs)));
3477 }
3478
3479 STATIC void
3480 S_move_proto_attr(pTHX_ OP **proto, OP **attrs, const GV * name)
3481 {
3482     OP *new_proto = NULL;
3483     STRLEN pvlen;
3484     char *pv;
3485     OP *o;
3486
3487     PERL_ARGS_ASSERT_MOVE_PROTO_ATTR;
3488
3489     if (!*attrs)
3490         return;
3491
3492     o = *attrs;
3493     if (o->op_type == OP_CONST) {
3494         pv = SvPV(cSVOPo_sv, pvlen);
3495         if (pvlen >= 10 && memEQ(pv, "prototype(", 10)) {
3496             SV * const tmpsv = newSVpvn_flags(pv + 10, pvlen - 11, SvUTF8(cSVOPo_sv));
3497             SV ** const tmpo = cSVOPx_svp(o);
3498             SvREFCNT_dec(cSVOPo_sv);
3499             *tmpo = tmpsv;
3500             new_proto = o;
3501             *attrs = NULL;
3502         }
3503     } else if (o->op_type == OP_LIST) {
3504         OP * lasto;
3505         assert(o->op_flags & OPf_KIDS);
3506         lasto = cLISTOPo->op_first;
3507         assert(lasto->op_type == OP_PUSHMARK);
3508         for (o = OpSIBLING(lasto); o; o = OpSIBLING(o)) {
3509             if (o->op_type == OP_CONST) {
3510                 pv = SvPV(cSVOPo_sv, pvlen);
3511                 if (pvlen >= 10 && memEQ(pv, "prototype(", 10)) {
3512                     SV * const tmpsv = newSVpvn_flags(pv + 10, pvlen - 11, SvUTF8(cSVOPo_sv));
3513                     SV ** const tmpo = cSVOPx_svp(o);
3514                     SvREFCNT_dec(cSVOPo_sv);
3515                     *tmpo = tmpsv;
3516                     if (new_proto && ckWARN(WARN_MISC)) {
3517                         STRLEN new_len;
3518                         const char * newp = SvPV(cSVOPo_sv, new_len);
3519                         Perl_warner(aTHX_ packWARN(WARN_MISC),
3520                             "Attribute prototype(%"UTF8f") discards earlier prototype attribute in same sub",
3521                             UTF8fARG(SvUTF8(cSVOPo_sv), new_len, newp));
3522                         op_free(new_proto);
3523                     }
3524                     else if (new_proto)
3525                         op_free(new_proto);
3526                     new_proto = o;
3527                     /* excise new_proto from the list */
3528                     op_sibling_splice(*attrs, lasto, 1, NULL);
3529                     o = lasto;
3530                     continue;
3531                 }
3532             }
3533             lasto = o;
3534         }
3535         /* If the list is now just the PUSHMARK, scrap the whole thing; otherwise attributes.xs
3536            would get pulled in with no real need */
3537         if (!OpHAS_SIBLING(cLISTOPx(*attrs)->op_first)) {
3538             op_free(*attrs);
3539             *attrs = NULL;
3540         }
3541     }
3542
3543     if (new_proto) {
3544         SV *svname;
3545         if (isGV(name)) {
3546             svname = sv_newmortal();
3547             gv_efullname3(svname, name, NULL);
3548         }
3549         else if (SvPOK(name) && *SvPVX((SV *)name) == '&')
3550             svname = newSVpvn_flags(SvPVX((SV *)name)+1, SvCUR(name)-1, SvUTF8(name)|SVs_TEMP);
3551         else
3552             svname = (SV *)name;
3553         if (ckWARN(WARN_ILLEGALPROTO))
3554             (void)validate_proto(svname, cSVOPx_sv(new_proto), TRUE);
3555         if (*proto && ckWARN(WARN_PROTOTYPE)) {
3556             STRLEN old_len, new_len;
3557             const char * oldp = SvPV(cSVOPx_sv(*proto), old_len);
3558             const char * newp = SvPV(cSVOPx_sv(new_proto), new_len);
3559
3560             Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
3561                 "Prototype '%"UTF8f"' overridden by attribute 'prototype(%"UTF8f")'"
3562                 " in %"SVf,
3563                 UTF8fARG(SvUTF8(cSVOPx_sv(*proto)), old_len, oldp),
3564                 UTF8fARG(SvUTF8(cSVOPx_sv(new_proto)), new_len, newp),
3565                 SVfARG(svname));
3566         }
3567         if (*proto)
3568             op_free(*proto);
3569         *proto = new_proto;
3570     }
3571 }
3572
3573 static void
3574 S_cant_declare(pTHX_ OP *o)
3575 {
3576     if (o->op_type == OP_NULL
3577      && (o->op_flags & (OPf_SPECIAL|OPf_KIDS)) == OPf_KIDS)
3578         o = cUNOPo->op_first;
3579     yyerror(Perl_form(aTHX_ "Can't declare %s in \"%s\"",
3580                              o->op_type == OP_NULL
3581                                && o->op_flags & OPf_SPECIAL
3582                                  ? "do block"
3583                                  : OP_DESC(o),
3584                              PL_parser->in_my == KEY_our   ? "our"   :
3585                              PL_parser->in_my == KEY_state ? "state" :
3586                                                              "my"));
3587 }
3588
3589 STATIC OP *
3590 S_my_kid(pTHX_ OP *o, OP *attrs, OP **imopsp)
3591 {
3592     I32 type;
3593     const bool stately = PL_parser && PL_parser->in_my == KEY_state;
3594
3595     PERL_ARGS_ASSERT_MY_KID;
3596
3597     if (!o || (PL_parser && PL_parser->error_count))
3598         return o;
3599
3600     type = o->op_type;
3601
3602     if (type == OP_LIST) {
3603         OP *kid;
3604         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
3605             my_kid(kid, attrs, imopsp);
3606         return o;
3607     } else if (type == OP_UNDEF || type == OP_STUB) {
3608         return o;
3609     } else if (type == OP_RV2SV ||      /* "our" declaration */
3610                type == OP_RV2AV ||
3611                type == OP_RV2HV) { /* XXX does this let anything illegal in? */
3612         if (cUNOPo->op_first->op_type != OP_GV) { /* MJD 20011224 */
3613             S_cant_declare(aTHX_ o);
3614         } else if (attrs) {
3615             GV * const gv = cGVOPx_gv(cUNOPo->op_first);
3616             assert(PL_parser);
3617             PL_parser->in_my = FALSE;
3618             PL_parser->in_my_stash = NULL;
3619             apply_attrs(GvSTASH(gv),
3620                         (type == OP_RV2SV ? GvSV(gv) :
3621                          type == OP_RV2AV ? MUTABLE_SV(GvAV(gv)) :
3622                          type == OP_RV2HV ? MUTABLE_SV(GvHV(gv)) : MUTABLE_SV(gv)),
3623                         attrs);
3624         }
3625         o->op_private |= OPpOUR_INTRO;
3626         return o;
3627     }
3628     else if (type != OP_PADSV &&
3629              type != OP_PADAV &&
3630              type != OP_PADHV &&
3631              type != OP_PUSHMARK)
3632     {
3633         S_cant_declare(aTHX_ o);
3634         return o;
3635     }
3636     else if (attrs && type != OP_PUSHMARK) {
3637         HV *stash;
3638
3639         assert(PL_parser);
3640         PL_parser->in_my = FALSE;
3641         PL_parser->in_my_stash = NULL;
3642
3643         /* check for C<my Dog $spot> when deciding package */
3644         stash = PAD_COMPNAME_TYPE(o->op_targ);
3645         if (!stash)
3646             stash = PL_curstash;
3647         apply_attrs_my(stash, o, attrs, imopsp);
3648     }
3649     o->op_flags |= OPf_MOD;
3650     o->op_private |= OPpLVAL_INTRO;
3651     if (stately)
3652         o->op_private |= OPpPAD_STATE;
3653     return o;
3654 }
3655
3656 OP *
3657 Perl_my_attrs(pTHX_ OP *o, OP *attrs)
3658 {
3659     OP *rops;
3660     int maybe_scalar = 0;
3661
3662     PERL_ARGS_ASSERT_MY_ATTRS;
3663
3664 /* [perl #17376]: this appears to be premature, and results in code such as
3665    C< our(%x); > executing in list mode rather than void mode */
3666 #if 0
3667     if (o->op_flags & OPf_PARENS)
3668         list(o);
3669     else
3670         maybe_scalar = 1;
3671 #else
3672     maybe_scalar = 1;
3673 #endif
3674     if (attrs)
3675         SAVEFREEOP(attrs);
3676     rops = NULL;
3677     o = my_kid(o, attrs, &rops);
3678     if (rops) {
3679         if (maybe_scalar && o->op_type == OP_PADSV) {
3680             o = scalar(op_append_list(OP_LIST, rops, o));
3681             o->op_private |= OPpLVAL_INTRO;
3682         }
3683         else {
3684             /* The listop in rops might have a pushmark at the beginning,
3685                which will mess up list assignment. */
3686             LISTOP * const lrops = (LISTOP *)rops; /* for brevity */
3687             if (rops->op_type == OP_LIST && 
3688                 lrops->op_first && lrops->op_first->op_type == OP_PUSHMARK)
3689             {
3690                 OP * const pushmark = lrops->op_first;
3691                 /* excise pushmark */
3692                 op_sibling_splice(rops, NULL, 1, NULL);
3693                 op_free(pushmark);
3694             }
3695             o = op_append_list(OP_LIST, o, rops);
3696         }
3697     }
3698     PL_parser->in_my = FALSE;
3699     PL_parser->in_my_stash = NULL;
3700     return o;
3701 }
3702
3703 OP *
3704 Perl_sawparens(pTHX_ OP *o)
3705 {
3706     PERL_UNUSED_CONTEXT;
3707     if (o)
3708         o->op_flags |= OPf_PARENS;
3709     return o;
3710 }
3711
3712 OP *
3713 Perl_bind_match(pTHX_ I32 type, OP *left, OP *right)
3714 {
3715     OP *o;
3716     bool ismatchop = 0;
3717     const OPCODE ltype = left->op_type;
3718     const OPCODE rtype = right->op_type;
3719
3720     PERL_ARGS_ASSERT_BIND_MATCH;
3721
3722     if ( (ltype == OP_RV2AV || ltype == OP_RV2HV || ltype == OP_PADAV
3723           || ltype == OP_PADHV) && ckWARN(WARN_MISC))
3724     {
3725       const char * const desc
3726           = PL_op_desc[(
3727                           rtype == OP_SUBST || rtype == OP_TRANS
3728                        || rtype == OP_TRANSR
3729                        )
3730                        ? (int)rtype : OP_MATCH];
3731       const bool isary = ltype == OP_RV2AV || ltype == OP_PADAV;
3732       SV * const name =
3733         S_op_varname(aTHX_ left);
3734       if (name)
3735         Perl_warner(aTHX_ packWARN(WARN_MISC),
3736              "Applying %s to %"SVf" will act on scalar(%"SVf")",
3737              desc, SVfARG(name), SVfARG(name));
3738       else {
3739         const char * const sample = (isary
3740              ? "@array" : "%hash");
3741         Perl_warner(aTHX_ packWARN(WARN_MISC),
3742              "Applying %s to %s will act on scalar(%s)",
3743              desc, sample, sample);
3744       }
3745     }
3746
3747     if (rtype == OP_CONST &&
3748         cSVOPx(right)->op_private & OPpCONST_BARE &&
3749         cSVOPx(right)->op_private & OPpCONST_STRICT)
3750     {
3751         no_bareword_allowed(right);
3752     }
3753
3754     /* !~ doesn't make sense with /r, so error on it for now */
3755     if (rtype == OP_SUBST && (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT) &&
3756         type == OP_NOT)
3757         /* diag_listed_as: Using !~ with %s doesn't make sense */
3758         yyerror("Using !~ with s///r doesn't make sense");
3759     if (rtype == OP_TRANSR && type == OP_NOT)
3760         /* diag_listed_as: Using !~ with %s doesn't make sense */
3761         yyerror("Using !~ with tr///r doesn't make sense");
3762
3763     ismatchop = (rtype == OP_MATCH ||
3764                  rtype == OP_SUBST ||
3765                  rtype == OP_TRANS || rtype == OP_TRANSR)
3766              && !(right->op_flags & OPf_SPECIAL);
3767     if (ismatchop && right->op_private & OPpTARGET_MY) {
3768         right->op_targ = 0;
3769         right->op_private &= ~OPpTARGET_MY;
3770     }
3771     if (!(right->op_flags & OPf_STACKED) && !right->op_targ && ismatchop) {
3772         if (left->op_type == OP_PADSV
3773          && !(left->op_private & OPpLVAL_INTRO))
3774         {
3775             right->op_targ = left->op_targ;
3776             op_free(left);
3777             o = right;
3778         }
3779         else {
3780             right->op_flags |= OPf_STACKED;
3781             if (rtype != OP_MATCH && rtype != OP_TRANSR &&
3782             ! (rtype == OP_TRANS &&
3783                right->op_private & OPpTRANS_IDENTICAL) &&
3784             ! (rtype == OP_SUBST &&
3785                (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT)))
3786                 left = op_lvalue(left, rtype);
3787             if (right->op_type == OP_TRANS || right->op_type == OP_TRANSR)
3788                 o = newBINOP(OP_NULL, OPf_STACKED, scalar(left), right);
3789             else
3790                 o = op_prepend_elem(rtype, scalar(left), right);
3791         }
3792         if (type == OP_NOT)
3793             return newUNOP(OP_NOT, 0, scalar(o));
3794         return o;
3795     }
3796     else
3797         return bind_match(type, left,
3798                 pmruntime(newPMOP(OP_MATCH, 0), right, NULL, 0, 0));
3799 }
3800
3801 OP *
3802 Perl_invert(pTHX_ OP *o)
3803 {
3804     if (!o)
3805         return NULL;
3806     return newUNOP(OP_NOT, OPf_SPECIAL, scalar(o));
3807 }
3808
3809 /*
3810 =for apidoc Amx|OP *|op_scope|OP *o
3811
3812 Wraps up an op tree with some additional ops so that at runtime a dynamic
3813 scope will be created.  The original ops run in the new dynamic scope,
3814 and then, provided that they exit normally, the scope will be unwound.
3815 The additional ops used to create and unwind the dynamic scope will
3816 normally be an C<enter>/C<leave> pair, but a C<scope> op may be used
3817 instead if the ops are simple enough to not need the full dynamic scope
3818 structure.
3819
3820 =cut
3821 */
3822
3823 OP *
3824 Perl_op_scope(pTHX_ OP *o)
3825 {
3826     dVAR;
3827     if (o) {
3828         if (o->op_flags & OPf_PARENS || PERLDB_NOOPT || TAINTING_get) {
3829             o = op_prepend_elem(OP_LINESEQ, newOP(OP_ENTER, 0), o);
3830             CHANGE_TYPE(o, OP_LEAVE);
3831         }
3832         else if (o->op_type == OP_LINESEQ) {
3833             OP *kid;
3834             CHANGE_TYPE(o, OP_SCOPE);
3835             kid = ((LISTOP*)o)->op_first;
3836             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) {
3837                 op_null(kid);
3838
3839                 /* The following deals with things like 'do {1 for 1}' */
3840                 kid = OpSIBLING(kid);
3841                 if (kid &&
3842                     (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE))
3843                     op_null(kid);
3844             }
3845         }
3846         else
3847             o = newLISTOP(OP_SCOPE, 0, o, NULL);
3848     }
3849     return o;
3850 }
3851
3852 OP *
3853 Perl_op_unscope(pTHX_ OP *o)
3854 {
3855     if (o && o->op_type == OP_LINESEQ) {
3856         OP *kid = cLISTOPo->op_first;
3857         for(; kid; kid = OpSIBLING(kid))
3858             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE)
3859                 op_null(kid);
3860     }
3861     return o;
3862 }
3863
3864 /*
3865 =for apidoc Am|int|block_start|int full
3866
3867 Handles compile-time scope entry.
3868 Arranges for hints to be restored on block
3869 exit and also handles pad sequence numbers to make lexical variables scope
3870 right.  Returns a savestack index for use with C<block_end>.
3871
3872 =cut
3873 */
3874
3875 int
3876 Perl_block_start(pTHX_ int full)
3877 {
3878     const int retval = PL_savestack_ix;
3879
3880     PL_compiling.cop_seq = PL_cop_seqmax;
3881     COP_SEQMAX_INC;
3882     pad_block_start(full);
3883     SAVEHINTS();
3884     PL_hints &= ~HINT_BLOCK_SCOPE;
3885     SAVECOMPILEWARNINGS();
3886     PL_compiling.cop_warnings = DUP_WARNINGS(PL_compiling.cop_warnings);
3887     SAVEI32(PL_compiling.cop_seq);
3888     PL_compiling.cop_seq = 0;
3889
3890     CALL_BLOCK_HOOKS(bhk_start, full);
3891
3892     return retval;
3893 }
3894
3895 /*
3896 =for apidoc Am|OP *|block_end|I32 floor|OP *seq
3897
3898 Handles compile-time scope exit.  I<floor>
3899 is the savestack index returned by
3900 C<block_start>, and I<seq> is the body of the block.  Returns the block,
3901 possibly modified.
3902
3903 =cut
3904 */
3905
3906 OP*
3907 Perl_block_end(pTHX_ I32 floor, OP *seq)
3908 {
3909     const int needblockscope = PL_hints & HINT_BLOCK_SCOPE;
3910     OP* retval = scalarseq(seq);
3911     OP *o;
3912
3913     /* XXX Is the null PL_parser check necessary here? */
3914     assert(PL_parser); /* Let’s find out under debugging builds.  */
3915     if (PL_parser && PL_parser->parsed_sub) {
3916         o = newSTATEOP(0, NULL, NULL);
3917         op_null(o);
3918         retval = op_append_elem(OP_LINESEQ, retval, o);
3919     }
3920
3921     CALL_BLOCK_HOOKS(bhk_pre_end, &retval);
3922
3923     LEAVE_SCOPE(floor);
3924     if (needblockscope)
3925         PL_hints |= HINT_BLOCK_SCOPE; /* propagate out */
3926     o = pad_leavemy();
3927
3928     if (o) {
3929         /* pad_leavemy has created a sequence of introcv ops for all my
3930            subs declared in the block.  We have to replicate that list with
3931            clonecv ops, to deal with this situation:
3932
3933                sub {
3934                    my sub s1;
3935                    my sub s2;
3936                    sub s1 { state sub foo { \&s2 } }
3937                }->()
3938
3939            Originally, I was going to have introcv clone the CV and turn
3940            off the stale flag.  Since &s1 is declared before &s2, the
3941            introcv op for &s1 is executed (on sub entry) before the one for
3942            &s2.  But the &foo sub inside &s1 (which is cloned when &s1 is
3943            cloned, since it is a state sub) closes over &s2 and expects
3944            to see it in its outer CV’s pad.  If the introcv op clones &s1,
3945            then &s2 is still marked stale.  Since &s1 is not active, and
3946            &foo closes over &s1’s implicit entry for &s2, we get a â€˜Varia-
3947            ble will not stay shared’ warning.  Because it is the same stub
3948            that will be used when the introcv op for &s2 is executed, clos-
3949            ing over it is safe.  Hence, we have to turn off the stale flag
3950            on all lexical subs in the block before we clone any of them.
3951            Hence, having introcv clone the sub cannot work.  So we create a
3952            list of ops like this:
3953
3954                lineseq
3955                   |
3956                   +-- introcv
3957                   |
3958                   +-- introcv
3959                   |
3960                   +-- introcv
3961                   |
3962                   .
3963                   .
3964                   .
3965                   |
3966                   +-- clonecv
3967                   |
3968                   +-- clonecv
3969                   |
3970                   +-- clonecv
3971                   |
3972                   .
3973                   .
3974                   .
3975          */
3976         OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : o;
3977         OP * const last = o->op_flags & OPf_KIDS ? cLISTOPo->op_last : o;
3978         for (;; kid = OpSIBLING(kid)) {
3979             OP *newkid = newOP(OP_CLONECV, 0);
3980             newkid->op_targ = kid->op_targ;
3981             o = op_append_elem(OP_LINESEQ, o, newkid);
3982             if (kid == last) break;
3983         }
3984         retval = op_prepend_elem(OP_LINESEQ, o, retval);
3985     }
3986
3987     CALL_BLOCK_HOOKS(bhk_post_end, &retval);
3988
3989     return retval;
3990 }
3991
3992 /*
3993 =head1 Compile-time scope hooks
3994
3995 =for apidoc Aox||blockhook_register
3996
3997 Register a set of hooks to be called when the Perl lexical scope changes
3998 at compile time.  See L<perlguts/"Compile-time scope hooks">.
3999
4000 =cut
4001 */
4002
4003 void
4004 Perl_blockhook_register(pTHX_ BHK *hk)
4005 {
4006     PERL_ARGS_ASSERT_BLOCKHOOK_REGISTER;
4007
4008     Perl_av_create_and_push(aTHX_ &PL_blockhooks, newSViv(PTR2IV(hk)));
4009 }
4010
4011 void
4012 Perl_newPROG(pTHX_ OP *o)
4013 {
4014     PERL_ARGS_ASSERT_NEWPROG;
4015
4016     if (PL_in_eval) {
4017         PERL_CONTEXT *cx;
4018         I32 i;
4019         if (PL_eval_root)
4020                 return;
4021         PL_eval_root = newUNOP(OP_LEAVEEVAL,
4022                                ((PL_in_eval & EVAL_KEEPERR)
4023                                 ? OPf_SPECIAL : 0), o);
4024
4025         cx = &cxstack[cxstack_ix];
4026         assert(CxTYPE(cx) == CXt_EVAL);
4027
4028         if ((cx->blk_gimme & G_WANT) == G_VOID)
4029             scalarvoid(PL_eval_root);
4030         else if ((cx->blk_gimme & G_WANT) == G_ARRAY)
4031             list(PL_eval_root);
4032         else
4033             scalar(PL_eval_root);
4034
4035         PL_eval_start = op_linklist(PL_eval_root);
4036         PL_eval_root->op_private |= OPpREFCOUNTED;
4037         OpREFCNT_set(PL_eval_root, 1);
4038         PL_eval_root->op_next = 0;
4039         i = PL_savestack_ix;
4040         SAVEFREEOP(o);
4041         ENTER;
4042         CALL_PEEP(PL_eval_start);
4043         finalize_optree(PL_eval_root);
4044         S_prune_chain_head(&PL_eval_start);
4045         LEAVE;
4046         PL_savestack_ix = i;
4047     }
4048     else {
4049         if (o->op_type == OP_STUB) {
4050             /* This block is entered if nothing is compiled for the main
4051                program. This will be the case for an genuinely empty main
4052                program, or one which only has BEGIN blocks etc, so already
4053                run and freed.
4054
4055                Historically (5.000) the guard above was !o. However, commit
4056                f8a08f7b8bd67b28 (Jun 2001), integrated to blead as
4057                c71fccf11fde0068, changed perly.y so that newPROG() is now
4058                called with the output of block_end(), which returns a new
4059                OP_STUB for the case of an empty optree. ByteLoader (and
4060                maybe other things) also take this path, because they set up
4061                PL_main_start and PL_main_root directly, without generating an
4062                optree.
4063
4064                If the parsing the main program aborts (due to parse errors,
4065                or due to BEGIN or similar calling exit), then newPROG()
4066                isn't even called, and hence this code path and its cleanups
4067                are skipped. This shouldn't make a make a difference:
4068                * a non-zero return from perl_parse is a failure, and
4069                  perl_destruct() should be called immediately.
4070                * however, if exit(0) is called during the parse, then
4071                  perl_parse() returns 0, and perl_run() is called. As
4072                  PL_main_start will be NULL, perl_run() will return
4073                  promptly, and the exit code will remain 0.
4074             */
4075
4076             PL_comppad_name = 0;
4077             PL_compcv = 0;
4078             S_op_destroy(aTHX_ o);
4079             return;
4080         }
4081         PL_main_root = op_scope(sawparens(scalarvoid(o)));
4082         PL_curcop = &PL_compiling;
4083         PL_main_start = LINKLIST(PL_main_root);
4084         PL_main_root->op_private |= OPpREFCOUNTED;
4085         OpREFCNT_set(PL_main_root, 1);
4086         PL_main_root->op_next = 0;
4087         CALL_PEEP(PL_main_start);
4088         finalize_optree(PL_main_root);
4089         S_prune_chain_head(&PL_main_start);
4090         cv_forget_slab(PL_compcv);
4091         PL_compcv = 0;
4092
4093         /* Register with debugger */
4094         if (PERLDB_INTER) {
4095             CV * const cv = get_cvs("DB::postponed", 0);
4096             if (cv) {
4097                 dSP;
4098                 PUSHMARK(SP);
4099                 XPUSHs(MUTABLE_SV(CopFILEGV(&PL_compiling)));
4100                 PUTBACK;
4101                 call_sv(MUTABLE_SV(cv), G_DISCARD);
4102             }
4103         }
4104     }
4105 }
4106
4107 OP *
4108 Perl_localize(pTHX_ OP *o, I32 lex)
4109 {
4110     PERL_ARGS_ASSERT_LOCALIZE;
4111
4112     if (o->op_flags & OPf_PARENS)
4113 /* [perl #17376]: this appears to be premature, and results in code such as
4114    C< our(%x); > executing in list mode rather than void mode */
4115 #if 0
4116         list(o);
4117 #else
4118         NOOP;
4119 #endif
4120     else {
4121         if ( PL_parser->bufptr > PL_parser->oldbufptr
4122             && PL_parser->bufptr[-1] == ','
4123             && ckWARN(WARN_PARENTHESIS))
4124         {
4125             char *s = PL_parser->bufptr;
4126             bool sigil = FALSE;
4127
4128             /* some heuristics to detect a potential error */
4129             while (*s && (strchr(", \t\n", *s)))
4130                 s++;
4131
4132             while (1) {
4133                 if (*s && strchr("@$%*", *s) && *++s
4134                        && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s))) {
4135                     s++;
4136                     sigil = TRUE;
4137                     while (*s && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s)))
4138                         s++;
4139                     while (*s && (strchr(", \t\n", *s)))
4140                         s++;
4141                 }
4142                 else
4143                     break;
4144             }
4145             if (sigil && (*s == ';' || *s == '=')) {
4146                 Perl_warner(aTHX_ packWARN(WARN_PARENTHESIS),
4147                                 "Parentheses missing around \"%s\" list",
4148                                 lex
4149                                     ? (PL_parser->in_my == KEY_our
4150                                         ? "our"
4151                                         : PL_parser->in_my == KEY_state
4152                                             ? "state"
4153                                             : "my")
4154                                     : "local");
4155             }
4156         }
4157     }
4158     if (lex)
4159         o = my(o);
4160     else
4161         o = op_lvalue(o, OP_NULL);              /* a bit kludgey */
4162     PL_parser->in_my = FALSE;
4163     PL_parser->in_my_stash = NULL;
4164     return o;
4165 }
4166
4167 OP *
4168 Perl_jmaybe(pTHX_ OP *o)
4169 {
4170     PERL_ARGS_ASSERT_JMAYBE;
4171
4172     if (o->op_type == OP_LIST) {
4173         OP * const o2
4174             = newSVREF(newGVOP(OP_GV, 0, gv_fetchpvs(";", GV_ADD|GV_NOTQUAL, SVt_PV)));
4175         o = op_convert_list(OP_JOIN, 0, op_prepend_elem(OP_LIST, o2, o));
4176     }
4177     return o;
4178 }
4179
4180 PERL_STATIC_INLINE OP *
4181 S_op_std_init(pTHX_ OP *o)
4182 {
4183     I32 type = o->op_type;
4184
4185     PERL_ARGS_ASSERT_OP_STD_INIT;
4186
4187     if (PL_opargs[type] & OA_RETSCALAR)
4188         scalar(o);
4189     if (PL_opargs[type] & OA_TARGET && !o->op_targ)
4190         o->op_targ = pad_alloc(type, SVs_PADTMP);
4191
4192     return o;
4193 }
4194
4195 PERL_STATIC_INLINE OP *
4196 S_op_integerize(pTHX_ OP *o)
4197 {
4198     I32 type = o->op_type;
4199
4200     PERL_ARGS_ASSERT_OP_INTEGERIZE;
4201
4202     /* integerize op. */
4203     if ((PL_opargs[type] & OA_OTHERINT) && (PL_hints & HINT_INTEGER))
4204     {
4205         dVAR;
4206         o->op_ppaddr = PL_ppaddr[++(o->op_type)];
4207     }
4208
4209     if (type == OP_NEGATE)
4210         /* XXX might want a ck_negate() for this */
4211         cUNOPo->op_first->op_private &= ~OPpCONST_STRICT;
4212
4213     return o;
4214 }
4215
4216 static OP *
4217 S_fold_constants(pTHX_ OP *o)
4218 {
4219     dVAR;
4220     OP * VOL curop;
4221     OP *newop;
4222     VOL I32 type = o->op_type;
4223     bool is_stringify;
4224     SV * VOL sv = NULL;
4225     int ret = 0;
4226     I32 oldscope;
4227     OP *old_next;
4228     SV * const oldwarnhook = PL_warnhook;
4229     SV * const olddiehook  = PL_diehook;
4230     COP not_compiling;
4231     U8 oldwarn = PL_dowarn;
4232     dJMPENV;
4233
4234     PERL_ARGS_ASSERT_FOLD_CONSTANTS;
4235
4236     if (!(PL_opargs[type] & OA_FOLDCONST))
4237         goto nope;
4238
4239     switch (type) {
4240     case OP_UCFIRST:
4241     case OP_LCFIRST:
4242     case OP_UC:
4243     case OP_LC:
4244     case OP_FC:
4245 #ifdef USE_LOCALE_CTYPE
4246         if (IN_LC_COMPILETIME(LC_CTYPE))
4247             goto nope;
4248 #endif
4249         break;
4250     case OP_SLT:
4251     case OP_SGT:
4252     case OP_SLE:
4253     case OP_SGE:
4254     case OP_SCMP:
4255 #ifdef USE_LOCALE_COLLATE
4256         if (IN_LC_COMPILETIME(LC_COLLATE))
4257             goto nope;
4258 #endif
4259         break;
4260     case OP_SPRINTF:
4261         /* XXX what about the numeric ops? */
4262 #ifdef USE_LOCALE_NUMERIC
4263         if (IN_LC_COMPILETIME(LC_NUMERIC))
4264             goto nope;
4265 #endif
4266         break;
4267     case OP_PACK:
4268         if (!OpHAS_SIBLING(cLISTOPo->op_first)
4269           || OpSIBLING(cLISTOPo->op_first)->op_type != OP_CONST)
4270             goto nope;
4271         {
4272             SV * const sv = cSVOPx_sv(OpSIBLING(cLISTOPo->op_first));
4273             if (!SvPOK(sv) || SvGMAGICAL(sv)) goto nope;
4274             {
4275                 const char *s = SvPVX_const(sv);
4276                 while (s < SvEND(sv)) {
4277                     if (isALPHA_FOLD_EQ(*s, 'p')) goto nope;
4278                     s++;
4279                 }
4280             }
4281         }
4282         break;
4283     case OP_REPEAT:
4284         if (o->op_private & OPpREPEAT_DOLIST) goto nope;
4285         break;
4286     case OP_SREFGEN:
4287         if (cUNOPx(cUNOPo->op_first)->op_first->op_type != OP_CONST
4288          || SvPADTMP(cSVOPx_sv(cUNOPx(cUNOPo->op_first)->op_first)))
4289             goto nope;
4290     }
4291
4292     if (PL_parser && PL_parser->error_count)
4293         goto nope;              /* Don't try to run w/ errors */
4294
4295     for (curop = LINKLIST(o); curop != o; curop = LINKLIST(curop)) {
4296         const OPCODE type = curop->op_type;
4297         if ((type != OP_CONST || (curop->op_private & OPpCONST_BARE)) &&
4298             type != OP_LIST &&
4299             type != OP_SCALAR &&
4300             type != OP_NULL &&
4301             type != OP_PUSHMARK)
4302         {
4303             goto nope;
4304         }
4305     }
4306
4307     curop = LINKLIST(o);
4308     old_next = o->op_next;
4309     o->op_next = 0;
4310     PL_op = curop;
4311
4312     oldscope = PL_scopestack_ix;
4313     create_eval_scope(G_FAKINGEVAL);
4314
4315     /* Verify that we don't need to save it:  */
4316     assert(PL_curcop == &PL_compiling);
4317     StructCopy(&PL_compiling, &not_compiling, COP);
4318     PL_curcop = &not_compiling;
4319     /* The above ensures that we run with all the correct hints of the
4320        currently compiling COP, but that IN_PERL_RUNTIME is true. */
4321     assert(IN_PERL_RUNTIME);
4322     PL_warnhook = PERL_WARNHOOK_FATAL;
4323     PL_diehook  = NULL;
4324     JMPENV_PUSH(ret);
4325
4326     /* Effective $^W=1.  */
4327     if ( ! (PL_dowarn & G_WARN_ALL_MASK))
4328         PL_dowarn |= G_WARN_ON;
4329
4330     switch (ret) {
4331     case 0:
4332         CALLRUNOPS(aTHX);
4333         sv = *(PL_stack_sp--);
4334         if (o->op_targ && sv == PAD_SV(o->op_targ)) {   /* grab pad temp? */
4335             pad_swipe(o->op_targ,  FALSE);
4336         }
4337         else if (SvTEMP(sv)) {                  /* grab mortal temp? */
4338             SvREFCNT_inc_simple_void(sv);
4339             SvTEMP_off(sv);
4340         }
4341         else { assert(SvIMMORTAL(sv)); }
4342         break;
4343     case 3:
4344         /* Something tried to die.  Abandon constant folding.  */
4345         /* Pretend the error never happened.  */
4346         CLEAR_ERRSV();
4347         o->op_next = old_next;
4348         break;
4349     default:
4350         JMPENV_POP;
4351         /* Don't expect 1 (setjmp failed) or 2 (something called my_exit)  */
4352         PL_warnhook = oldwarnhook;
4353         PL_diehook  = olddiehook;
4354         /* XXX note that this croak may fail as we've already blown away
4355          * the stack - eg any nested evals */
4356         Perl_croak(aTHX_ "panic: fold_constants JMPENV_PUSH returned %d", ret);
4357     }
4358     JMPENV_POP;
4359     PL_dowarn   = oldwarn;
4360     PL_warnhook = oldwarnhook;
4361     PL_diehook  = olddiehook;
4362     PL_curcop = &PL_compiling;
4363
4364     if (PL_scopestack_ix > oldscope)
4365         delete_eval_scope();
4366
4367     if (ret)
4368         goto nope;
4369
4370     /* OP_STRINGIFY and constant folding are used to implement qq.
4371        Here the constant folding is an implementation detail that we
4372        want to hide.  If the stringify op is itself already marked
4373        folded, however, then it is actually a folded join.  */
4374     is_stringify = type == OP_STRINGIFY && !o->op_folded;
4375     op_free(o);
4376     assert(sv);
4377     if (is_stringify)
4378         SvPADTMP_off(sv);
4379     else if (!SvIMMORTAL(sv)) {
4380         SvPADTMP_on(sv);
4381         SvREADONLY_on(sv);
4382     }
4383     newop = newSVOP(OP_CONST, 0, MUTABLE_SV(sv));
4384     if (!is_stringify) newop->op_folded = 1;
4385     return newop;
4386
4387  nope:
4388     return o;
4389 }
4390
4391 static OP *
4392 S_gen_constant_list(pTHX_ OP *o)
4393 {
4394     dVAR;
4395     OP *curop;
4396     const SSize_t oldtmps_floor = PL_tmps_floor;
4397     SV **svp;
4398     AV *av;
4399
4400     list(o);
4401     if (PL_parser && PL_parser->error_count)
4402         return o;               /* Don't attempt to run with errors */
4403
4404     curop = LINKLIST(o);
4405     o->op_next = 0;
4406     CALL_PEEP(curop);
4407     S_prune_chain_head(&curop);
4408     PL_op = curop;
4409     Perl_pp_pushmark(aTHX);
4410     CALLRUNOPS(aTHX);
4411     PL_op = curop;
4412     assert (!(curop->op_flags & OPf_SPECIAL));
4413     assert(curop->op_type == OP_RANGE);
4414     Perl_pp_anonlist(aTHX);
4415     PL_tmps_floor = oldtmps_floor;
4416
4417     CHANGE_TYPE(o, OP_RV2AV);
4418     o->op_flags &= ~OPf_REF;    /* treat \(1..2) like an ordinary list */
4419     o->op_flags |= OPf_PARENS;  /* and flatten \(1..2,3) */
4420     o->op_opt = 0;              /* needs to be revisited in rpeep() */
4421     av = (AV *)SvREFCNT_inc_NN(*PL_stack_sp--);
4422
4423     /* replace subtree with an OP_CONST */
4424     curop = ((UNOP*)o)->op_first;
4425     op_sibling_splice(o, NULL, -1, newSVOP(OP_CONST, 0, (SV *)av));
4426     op_free(curop);
4427
4428     if (AvFILLp(av) != -1)
4429         for (svp = AvARRAY(av) + AvFILLp(av); svp >= AvARRAY(av); --svp)
4430         {
4431             SvPADTMP_on(*svp);
4432             SvREADONLY_on(*svp);
4433         }
4434     LINKLIST(o);
4435     return list(o);
4436 }
4437
4438 /*
4439 =head1 Optree Manipulation Functions
4440 */
4441
4442 /* List constructors */
4443
4444 /*
4445 =for apidoc Am|OP *|op_append_elem|I32 optype|OP *first|OP *last
4446
4447 Append an item to the list of ops contained directly within a list-type
4448 op, returning the lengthened list.  I<first> is the list-type op,
4449 and I<last> is the op to append to the list.  I<optype> specifies the
4450 intended opcode for the list.  If I<first> is not already a list of the
4451 right type, it will be upgraded into one.  If either I<first> or I<last>
4452 is null, the other is returned unchanged.
4453
4454 =cut
4455 */
4456
4457 OP *
4458 Perl_op_append_elem(pTHX_ I32 type, OP *first, OP *last)
4459 {
4460     if (!first)
4461         return last;
4462
4463     if (!last)
4464         return first;
4465
4466     if (first->op_type != (unsigned)type
4467         || (type == OP_LIST && (first->op_flags & OPf_PARENS)))
4468     {
4469         return newLISTOP(type, 0, first, last);
4470     }
4471
4472     op_sibling_splice(first, ((LISTOP*)first)->op_last, 0, last);
4473     first->op_flags |= OPf_KIDS;
4474     return first;
4475 }
4476
4477 /*
4478 =for apidoc Am|OP *|op_append_list|I32 optype|OP *first|OP *last
4479
4480 Concatenate the lists of ops contained directly within two list-type ops,
4481 returning the combined list.  I<first> and I<last> are the list-type ops
4482 to concatenate.  I<optype> specifies the intended opcode for the list.
4483 If either I<first> or I<last> is not already a list of the right type,
4484 it will be upgraded into one.  If either I<first> or I<last> is null,
4485 the other is returned unchanged.
4486
4487 =cut
4488 */
4489
4490 OP *
4491 Perl_op_append_list(pTHX_ I32 type, OP *first, OP *last)
4492 {
4493     if (!first)
4494         return last;
4495
4496     if (!last)
4497         return first;
4498
4499     if (first->op_type != (unsigned)type)
4500         return op_prepend_elem(type, first, last);
4501
4502     if (last->op_type != (unsigned)type)
4503         return op_append_elem(type, first, last);
4504
4505     ((LISTOP*)first)->op_last->op_lastsib = 0;
4506     OpSIBLING_set(((LISTOP*)first)->op_last, ((LISTOP*)last)->op_first);
4507     ((LISTOP*)first)->op_last = ((LISTOP*)last)->op_last;
4508     ((LISTOP*)first)->op_last->op_lastsib = 1;
4509 #ifdef PERL_OP_PARENT
4510     ((LISTOP*)first)->op_last->op_sibling = first;
4511 #endif
4512     first->op_flags |= (last->op_flags & OPf_KIDS);
4513
4514
4515     S_op_destroy(aTHX_ last);
4516
4517     return first;
4518 }
4519
4520 /*
4521 =for apidoc Am|OP *|op_prepend_elem|I32 optype|OP *first|OP *last
4522
4523 Prepend an item to the list of ops contained directly within a list-type
4524 op, returning the lengthened list.  I<first> is the op to prepend to the
4525 list, and I<last> is the list-type op.  I<optype> specifies the intended
4526 opcode for the list.  If I<last> is not already a list of the right type,
4527 it will be upgraded into one.  If either I<first> or I<last> is null,
4528 the other is returned unchanged.
4529
4530 =cut
4531 */
4532
4533 OP *
4534 Perl_op_prepend_elem(pTHX_ I32 type, OP *first, OP *last)
4535 {
4536     if (!first)
4537         return last;
4538
4539     if (!last)
4540         return first;
4541
4542     if (last->op_type == (unsigned)type) {
4543         if (type == OP_LIST) {  /* already a PUSHMARK there */
4544             /* insert 'first' after pushmark */
4545             op_sibling_splice(last, cLISTOPx(last)->op_first, 0, first);
4546             if (!(first->op_flags & OPf_PARENS))
4547                 last->op_flags &= ~OPf_PARENS;
4548         }
4549         else
4550             op_sibling_splice(last, NULL, 0, first);
4551         last->op_flags |= OPf_KIDS;
4552         return last;
4553     }
4554
4555     return newLISTOP(type, 0, first, last);
4556 }
4557
4558 /*
4559 =for apidoc Am|OP *|op_convert_list|I32 type|I32 flags|OP *o
4560
4561 Converts I<o> into a list op if it is not one already, and then converts it
4562 into the specified I<type>, calling its check function, allocating a target if
4563 it needs one, and folding constants.
4564
4565 A list-type op is usually constructed one kid at a time via C<newLISTOP>,
4566 C<op_prepend_elem> and C<op_append_elem>.  Then finally it is passed to
4567 C<op_convert_list> to make it the right type.
4568
4569 =cut
4570 */
4571
4572 OP *
4573 Perl_op_convert_list(pTHX_ I32 type, I32 flags, OP *o)
4574 {
4575     dVAR;
4576     if (type < 0) type = -type, flags |= OPf_SPECIAL;
4577     if (!o || o->op_type != OP_LIST)
4578         o = force_list(o, 0);
4579     else
4580         o->op_flags &= ~OPf_WANT;
4581
4582     if (!(PL_opargs[type] & OA_MARK))
4583         op_null(cLISTOPo->op_first);
4584     else {
4585         OP * const kid2 = OpSIBLING(cLISTOPo->op_first);
4586         if (kid2 && kid2->op_type == OP_COREARGS) {
4587             op_null(cLISTOPo->op_first);
4588             kid2->op_private |= OPpCOREARGS_PUSHMARK;
4589         }
4590     }
4591
4592     CHANGE_TYPE(o, type);
4593     o->op_flags |= flags;
4594     if (flags & OPf_FOLDED)
4595         o->op_folded = 1;
4596
4597     o = CHECKOP(type, o);
4598     if (o->op_type != (unsigned)type)
4599         return o;
4600
4601     return fold_constants(op_integerize(op_std_init(o)));
4602 }
4603
4604 /* Constructors */
4605
4606
4607 /*
4608 =head1 Optree construction
4609
4610 =for apidoc Am|OP *|newNULLLIST
4611
4612 Constructs, checks, and returns a new C<stub> op, which represents an
4613 empty list expression.
4614
4615 =cut
4616 */
4617
4618 OP *
4619 Perl_newNULLLIST(pTHX)
4620 {
4621     return newOP(OP_STUB, 0);
4622 }
4623
4624 /* promote o and any siblings to be a list if its not already; i.e.
4625  *
4626  *  o - A - B
4627  *
4628  * becomes
4629  *
4630  *  list
4631  *    |
4632  *  pushmark - o - A - B
4633  *
4634  * If nullit it true, the list op is nulled.
4635  */
4636
4637 static OP *
4638 S_force_list(pTHX_ OP *o, bool nullit)
4639 {
4640     if (!o || o->op_type != OP_LIST) {
4641         OP *rest = NULL;
4642         if (o) {
4643             /* manually detach any siblings then add them back later */
4644             rest = OpSIBLING(o);
4645             OpSIBLING_set(o, NULL);
4646             o->op_lastsib = 1;
4647         }
4648         o = newLISTOP(OP_LIST, 0, o, NULL);
4649         if (rest)
4650             op_sibling_splice(o, cLISTOPo->op_last, 0, rest);
4651     }
4652     if (nullit)
4653         op_null(o);
4654     return o;
4655 }
4656
4657 /*
4658 =for apidoc Am|OP *|newLISTOP|I32 type|I32 flags|OP *first|OP *last
4659
4660 Constructs, checks, and returns an op of any list type.  I<type> is
4661 the opcode.  I<flags> gives the eight bits of C<op_flags>, except that
4662 C<OPf_KIDS> will be set automatically if required.  I<first> and I<last>
4663 supply up to two ops to be direct children of the list op; they are
4664 consumed by this function and become part of the constructed op tree.
4665
4666 For most list operators, the check function expects all the kid ops to be
4667 present already, so calling C<newLISTOP(OP_JOIN, ...)> (e.g.,) is not
4668 appropriate.  What you want to do in that case is create an op of type
4669 OP_LIST, append more children to it, and then call L</op_convert_list>.
4670 See L</op_convert_list> for more information.
4671
4672
4673 =cut
4674 */
4675
4676 OP *
4677 Perl_newLISTOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
4678 {
4679     dVAR;
4680     LISTOP *listop;
4681
4682     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LISTOP
4683         || type == OP_CUSTOM);
4684
4685     NewOp(1101, listop, 1, LISTOP);
4686
4687     CHANGE_TYPE(listop, type);
4688     if (first || last)
4689         flags |= OPf_KIDS;
4690     listop->op_flags = (U8)flags;
4691
4692     if (!last && first)
4693         last = first;
4694     else if (!first && last)
4695         first = last;
4696     else if (first)
4697         OpSIBLING_set(first, last);
4698     listop->op_first = first;
4699     listop->op_last = last;
4700     if (type == OP_LIST) {
4701         OP* const pushop = newOP(OP_PUSHMARK, 0);
4702         pushop->op_lastsib = 0;
4703         OpSIBLING_set(pushop, first);
4704         listop->op_first = pushop;
4705         listop->op_flags |= OPf_KIDS;
4706         if (!last)
4707             listop->op_last = pushop;
4708     }
4709     if (first)
4710         first->op_lastsib = 0;
4711     if (listop->op_last) {
4712         listop->op_last->op_lastsib = 1;
4713 #ifdef PERL_OP_PARENT
4714         listop->op_last->op_sibling = (OP*)listop;
4715 #endif
4716     }
4717
4718     return CHECKOP(type, listop);
4719 }
4720
4721 /*
4722 =for apidoc Am|OP *|newOP|I32 type|I32 flags
4723
4724 Constructs, checks, and returns an op of any base type (any type that
4725 has no extra fields).  I<type> is the opcode.  I<flags> gives the
4726 eight bits of C<op_flags>, and, shifted up eight bits, the eight bits
4727 of C<op_private>.
4728
4729 =cut
4730 */
4731
4732 OP *
4733 Perl_newOP(pTHX_ I32 type, I32 flags)
4734 {
4735     dVAR;
4736     OP *o;
4737
4738     if (type == -OP_ENTEREVAL) {
4739         type = OP_ENTEREVAL;
4740         flags |= OPpEVAL_BYTES<<8;
4741     }
4742
4743     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP
4744         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
4745         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
4746         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
4747
4748     NewOp(1101, o, 1, OP);
4749     CHANGE_TYPE(o, type);
4750     o->op_flags = (U8)flags;
4751
4752     o->op_next = o;
4753     o->op_private = (U8)(0 | (flags >> 8));
4754     if (PL_opargs[type] & OA_RETSCALAR)
4755         scalar(o);
4756     if (PL_opargs[type] & OA_TARGET)
4757         o->op_targ = pad_alloc(type, SVs_PADTMP);
4758     return CHECKOP(type, o);
4759 }
4760
4761 /*
4762 =for apidoc Am|OP *|newUNOP|I32 type|I32 flags|OP *first
4763
4764 Constructs, checks, and returns an op of any unary type.  I<type> is
4765 the opcode.  I<flags> gives the eight bits of C<op_flags>, except that
4766 C<OPf_KIDS> will be set automatically if required, and, shifted up eight
4767 bits, the eight bits of C<op_private>, except that the bit with value 1
4768 is automatically set.  I<first> supplies an optional op to be the direct
4769 child of the unary op; it is consumed by this function and become part
4770 of the constructed op tree.
4771
4772 =cut
4773 */
4774
4775 OP *
4776 Perl_newUNOP(pTHX_ I32 type, I32 flags, OP *first)
4777 {
4778     dVAR;
4779     UNOP *unop;
4780
4781     if (type == -OP_ENTEREVAL) {
4782         type = OP_ENTEREVAL;
4783         flags |= OPpEVAL_BYTES<<8;
4784     }
4785
4786     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP
4787         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
4788         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
4789         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
4790         || type == OP_SASSIGN
4791         || type == OP_ENTERTRY
4792         || type == OP_CUSTOM
4793         || type == OP_NULL );
4794
4795     if (!first)
4796         first = newOP(OP_STUB, 0);
4797     if (PL_opargs[type] & OA_MARK)
4798         first = force_list(first, 1);
4799
4800     NewOp(1101, unop, 1, UNOP);
4801     CHANGE_TYPE(unop, type);
4802     unop->op_first = first;
4803     unop->op_flags = (U8)(flags | OPf_KIDS);
4804     unop->op_private = (U8)(1 | (flags >> 8));
4805
4806 #ifdef PERL_OP_PARENT
4807     if (!OpHAS_SIBLING(first)) /* true unless weird syntax error */
4808         first->op_sibling = (OP*)unop;
4809 #endif
4810
4811     unop = (UNOP*) CHECKOP(type, unop);
4812     if (unop->op_next)
4813         return (OP*)unop;
4814
4815     return fold_constants(op_integerize(op_std_init((OP *) unop)));
4816 }
4817
4818 /*
4819 =for apidoc newUNOP_AUX
4820
4821 Similar to C<newUNOP>, but creates an UNOP_AUX struct instead, with op_aux
4822 initialised to aux
4823
4824 =cut
4825 */
4826
4827 OP *
4828 Perl_newUNOP_AUX(pTHX_ I32 type, I32 flags, OP *first, UNOP_AUX_item *aux)
4829 {
4830     dVAR;
4831     UNOP_AUX *unop;
4832
4833     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP_AUX
4834         || type == OP_CUSTOM);
4835
4836     NewOp(1101, unop, 1, UNOP_AUX);
4837     unop->op_type = (OPCODE)type;
4838     unop->op_ppaddr = PL_ppaddr[type];
4839     unop->op_first = first;
4840     unop->op_flags = (U8)(flags | (first ? OPf_KIDS : 0));
4841     unop->op_private = (U8)((first ? 1 : 0) | (flags >> 8));
4842     unop->op_aux = aux;
4843
4844 #ifdef PERL_OP_PARENT
4845     if (first && !OpHAS_SIBLING(first)) /* true unless weird syntax error */
4846         first->op_sibling = (OP*)unop;
4847 #endif
4848
4849     unop = (UNOP_AUX*) CHECKOP(type, unop);
4850
4851     return op_std_init((OP *) unop);
4852 }
4853
4854 /*
4855 =for apidoc Am|OP *|newMETHOP|I32 type|I32 flags|OP *first
4856
4857 Constructs, checks, and returns an op of method type with a method name
4858 evaluated at runtime.  I<type> is the opcode.  I<flags> gives the eight
4859 bits of C<op_flags>, except that C<OPf_KIDS> will be set automatically,
4860 and, shifted up eight bits, the eight bits of C<op_private>, except that
4861 the bit with value 1 is automatically set.  I<dynamic_meth> supplies an
4862 op which evaluates method name; it is consumed by this function and
4863 become part of the constructed op tree.
4864 Supported optypes: OP_METHOD.
4865
4866 =cut
4867 */
4868
4869 static OP*
4870 S_newMETHOP_internal(pTHX_ I32 type, I32 flags, OP* dynamic_meth, SV* const_meth) {
4871     dVAR;
4872     METHOP *methop;
4873
4874     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_METHOP
4875         || type == OP_CUSTOM);
4876
4877     NewOp(1101, methop, 1, METHOP);
4878     if (dynamic_meth) {
4879         if (PL_opargs[type] & OA_MARK) dynamic_meth = force_list(dynamic_meth, 1);
4880         methop->op_flags = (U8)(flags | OPf_KIDS);
4881         methop->op_u.op_first = dynamic_meth;
4882         methop->op_private = (U8)(1 | (flags >> 8));
4883
4884 #ifdef PERL_OP_PARENT
4885         if (!OpHAS_SIBLING(dynamic_meth))
4886             dynamic_meth->op_sibling = (OP*)methop;
4887 #endif
4888     }
4889     else {
4890         assert(const_meth);
4891         methop->op_flags = (U8)(flags & ~OPf_KIDS);
4892         methop->op_u.op_meth_sv = const_meth;
4893         methop->op_private = (U8)(0 | (flags >> 8));
4894         methop->op_next = (OP*)methop;
4895     }
4896
4897 #ifdef USE_ITHREADS
4898     methop->op_rclass_targ = 0;
4899 #else
4900     methop->op_rclass_sv = NULL;
4901 #endif
4902
4903     CHANGE_TYPE(methop, type);
4904     return CHECKOP(type, methop);
4905 }
4906
4907 OP *
4908 Perl_newMETHOP (pTHX_ I32 type, I32 flags, OP* dynamic_meth) {
4909     PERL_ARGS_ASSERT_NEWMETHOP;
4910     return newMETHOP_internal(type, flags, dynamic_meth, NULL);
4911 }
4912
4913 /*
4914 =for apidoc Am|OP *|newMETHOP_named|I32 type|I32 flags|SV *const_meth
4915
4916 Constructs, checks, and returns an op of method type with a constant
4917 method name.  I<type> is the opcode.  I<flags> gives the eight bits of
4918 C<op_flags>, and, shifted up eight bits, the eight bits of
4919 C<op_private>.  I<const_meth> supplies a constant method name;
4920 it must be a shared COW string.
4921 Supported optypes: OP_METHOD_NAMED.
4922
4923 =cut
4924 */
4925
4926 OP *
4927 Perl_newMETHOP_named (pTHX_ I32 type, I32 flags, SV* const_meth) {
4928     PERL_ARGS_ASSERT_NEWMETHOP_NAMED;
4929     return newMETHOP_internal(type, flags, NULL, const_meth);
4930 }
4931
4932 /*
4933 =for apidoc Am|OP *|newBINOP|I32 type|I32 flags|OP *first|OP *last
4934
4935 Constructs, checks, and returns an op of any binary type.  I<type>
4936 is the opcode.  I<flags> gives the eight bits of C<op_flags>, except
4937 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
4938 the eight bits of C<op_private>, except that the bit with value 1 or
4939 2 is automatically set as required.  I<first> and I<last> supply up to
4940 two ops to be the direct children of the binary op; they are consumed
4941 by this function and become part of the constructed op tree.
4942
4943 =cut
4944 */
4945
4946 OP *
4947 Perl_newBINOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
4948 {
4949     dVAR;
4950     BINOP *binop;
4951
4952     ASSUME((PL_opargs[type] & OA_CLASS_MASK) == OA_BINOP
4953         || type == OP_SASSIGN || type == OP_NULL || type == OP_CUSTOM);
4954
4955     NewOp(1101, binop, 1, BINOP);
4956
4957     if (!first)
4958         first = newOP(OP_NULL, 0);
4959
4960     CHANGE_TYPE(binop, type);
4961     binop->op_first = first;
4962     binop->op_flags = (U8)(flags | OPf_KIDS);
4963     if (!last) {
4964         last = first;
4965         binop->op_private = (U8)(1 | (flags >> 8));
4966     }
4967     else {
4968         binop->op_private = (U8)(2 | (flags >> 8));
4969         OpSIBLING_set(first, last);
4970         first->op_lastsib = 0;
4971     }
4972
4973 #ifdef PERL_OP_PARENT
4974     if (!OpHAS_SIBLING(last)) /* true unless weird syntax error */
4975         last->op_sibling = (OP*)binop;
4976 #endif
4977
4978     binop->op_last = OpSIBLING(binop->op_first);
4979 #ifdef PERL_OP_PARENT
4980     if (binop->op_last)
4981         binop->op_last->op_sibling = (OP*)binop;
4982 #endif
4983
4984     binop = (BINOP*)CHECKOP(type, binop);
4985     if (binop->op_next || binop->op_type != (OPCODE)type)
4986         return (OP*)binop;
4987
4988     return fold_constants(op_integerize(op_std_init((OP *)binop)));
4989 }
4990
4991 static int uvcompare(const void *a, const void *b)
4992     __attribute__nonnull__(1)
4993     __attribute__nonnull__(2)
4994     __attribute__pure__;
4995 static int uvcompare(const void *a, const void *b)
4996 {
4997     if (*((const UV *)a) < (*(const UV *)b))
4998         return -1;
4999     if (*((const UV *)a) > (*(const UV *)b))
5000         return 1;
5001     if (*((const UV *)a+1) < (*(const UV *)b+1))
5002         return -1;
5003     if (*((const UV *)a+1) > (*(const UV *)b+1))
5004         return 1;
5005     return 0;
5006 }
5007
5008 static OP *
5009 S_pmtrans(pTHX_ OP *o, OP *expr, OP *repl)
5010 {
5011     SV * const tstr = ((SVOP*)expr)->op_sv;
5012     SV * const rstr =
5013                               ((SVOP*)repl)->op_sv;
5014     STRLEN tlen;
5015     STRLEN rlen;
5016     const U8 *t = (U8*)SvPV_const(tstr, tlen);
5017     const U8 *r = (U8*)SvPV_const(rstr, rlen);
5018     I32 i;
5019     I32 j;
5020     I32 grows = 0;
5021     short *tbl;
5022
5023     const I32 complement = o->op_private & OPpTRANS_COMPLEMENT;
5024     const I32 squash     = o->op_private & OPpTRANS_SQUASH;
5025     I32 del              = o->op_private & OPpTRANS_DELETE;
5026     SV* swash;
5027
5028     PERL_ARGS_ASSERT_PMTRANS;
5029
5030     PL_hints |= HINT_BLOCK_SCOPE;
5031
5032     if (SvUTF8(tstr))
5033         o->op_private |= OPpTRANS_FROM_UTF;
5034
5035     if (SvUTF8(rstr))
5036         o->op_private |= OPpTRANS_TO_UTF;
5037
5038     if (o->op_private & (OPpTRANS_FROM_UTF|OPpTRANS_TO_UTF)) {
5039         SV* const listsv = newSVpvs("# comment\n");
5040         SV* transv = NULL;
5041         const U8* tend = t + tlen;
5042         const U8* rend = r + rlen;
5043         STRLEN ulen;
5044         UV tfirst = 1;
5045         UV tlast = 0;
5046         IV tdiff;
5047         STRLEN tcount = 0;
5048         UV rfirst = 1;
5049         UV rlast = 0;
5050         IV rdiff;
5051         STRLEN rcount = 0;
5052         IV diff;
5053         I32 none = 0;
5054         U32 max = 0;
5055         I32 bits;
5056         I32 havefinal = 0;
5057         U32 final = 0;
5058         const I32 from_utf  = o->op_private & OPpTRANS_FROM_UTF;
5059         const I32 to_utf    = o->op_private & OPpTRANS_TO_UTF;
5060         U8* tsave = NULL;
5061         U8* rsave = NULL;
5062         const U32 flags = UTF8_ALLOW_DEFAULT;
5063
5064         if (!from_utf) {
5065             STRLEN len = tlen;
5066             t = tsave = bytes_to_utf8(t, &len);
5067             tend = t + len;
5068         }
5069         if (!to_utf && rlen) {
5070             STRLEN len = rlen;
5071             r = rsave = bytes_to_utf8(r, &len);
5072             rend = r + len;
5073         }
5074
5075 /* There is a snag with this code on EBCDIC: scan_const() in toke.c has
5076  * encoded chars in native encoding which makes ranges in the EBCDIC 0..255
5077  * odd.  */
5078
5079         if (complement) {
5080             U8 tmpbuf[UTF8_MAXBYTES+1];
5081             UV *cp;
5082             UV nextmin = 0;
5083             Newx(cp, 2*tlen, UV);
5084             i = 0;
5085             transv = newSVpvs("");
5086             while (t < tend) {
5087                 cp[2*i] = utf8n_to_uvchr(t, tend-t, &ulen, flags);
5088                 t += ulen;
5089                 if (t < tend && *t == ILLEGAL_UTF8_BYTE) {
5090                     t++;
5091                     cp[2*i+1] = utf8n_to_uvchr(t, tend-t, &ulen, flags);
5092                     t += ulen;
5093                 }
5094                 else {
5095                  cp[2*i+1] = cp[2*i];
5096                 }
5097                 i++;
5098             }
5099             qsort(cp, i, 2*sizeof(UV), uvcompare);
5100             for (j = 0; j < i; j++) {
5101                 UV  val = cp[2*j];
5102                 diff = val - nextmin;
5103                 if (diff > 0) {
5104                     t = uvchr_to_utf8(tmpbuf,nextmin);
5105                     sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
5106                     if (diff > 1) {
5107                         U8  range_mark = ILLEGAL_UTF8_BYTE;
5108                         t = uvchr_to_utf8(tmpbuf, val - 1);
5109                         sv_catpvn(transv, (char *)&range_mark, 1);
5110                         sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
5111                     }
5112                 }
5113                 val = cp[2*j+1];
5114                 if (val >= nextmin)
5115                     nextmin = val + 1;
5116             }
5117             t = uvchr_to_utf8(tmpbuf,nextmin);
5118             sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
5119             {
5120                 U8 range_mark = ILLEGAL_UTF8_BYTE;
5121                 sv_catpvn(transv, (char *)&range_mark, 1);
5122             }
5123             t = uvchr_to_utf8(tmpbuf, 0x7fffffff);
5124             sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
5125             t = (const U8*)SvPVX_const(transv);
5126             tlen = SvCUR(transv);
5127             tend = t + tlen;
5128             Safefree(cp);
5129         }
5130         else if (!rlen && !del) {
5131             r = t; rlen = tlen; rend = tend;
5132         }
5133         if (!squash) {
5134                 if ((!rlen && !del) || t == r ||
5135                     (tlen == rlen && memEQ((char *)t, (char *)r, tlen)))
5136                 {
5137                     o->op_private |= OPpTRANS_IDENTICAL;
5138                 }
5139         }
5140
5141         while (t < tend || tfirst <= tlast) {
5142             /* see if we need more "t" chars */
5143             if (tfirst > tlast) {
5144                 tfirst = (I32)utf8n_to_uvchr(t, tend - t, &ulen, flags);
5145                 t += ulen;
5146                 if (t < tend && *t == ILLEGAL_UTF8_BYTE) {      /* illegal utf8 val indicates range */
5147                     t++;
5148                     tlast = (I32)utf8n_to_uvchr(t, tend - t, &ulen, flags);
5149                     t += ulen;
5150                 }
5151                 else
5152                     tlast = tfirst;
5153             }
5154
5155             /* now see if we need more "r" chars */
5156             if (rfirst > rlast) {
5157                 if (r < rend) {
5158                     rfirst = (I32)utf8n_to_uvchr(r, rend - r, &ulen, flags);
5159                     r += ulen;
5160                     if (r < rend && *r == ILLEGAL_UTF8_BYTE) {  /* illegal utf8 val indicates range */
5161                         r++;
5162                         rlast = (I32)utf8n_to_uvchr(r, rend - r, &ulen, flags);
5163                         r += ulen;
5164                     }
5165                     else
5166                         rlast = rfirst;
5167                 }
5168                 else {
5169                     if (!havefinal++)
5170                         final = rlast;
5171                     rfirst = rlast = 0xffffffff;
5172                 }
5173             }
5174
5175             /* now see which range will peter our first, if either. */
5176             tdiff = tlast - tfirst;
5177             rdiff = rlast - rfirst;
5178             tcount += tdiff + 1;
5179             rcount += rdiff + 1;
5180
5181             if (tdiff <= rdiff)
5182                 diff = tdiff;
5183             else
5184                 diff = rdiff;
5185
5186             if (rfirst == 0xffffffff) {
5187                 diff = tdiff;   /* oops, pretend rdiff is infinite */
5188                 if (diff > 0)
5189                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t%04lx\tXXXX\n",
5190                                    (long)tfirst, (long)tlast);
5191                 else
5192                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t\tXXXX\n", (long)tfirst);
5193             }
5194             else {
5195                 if (diff > 0)
5196                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t%04lx\t%04lx\n",
5197                                    (long)tfirst, (long)(tfirst + diff),
5198                                    (long)rfirst);
5199                 else
5200                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t\t%04lx\n",
5201                                    (long)tfirst, (long)rfirst);
5202
5203                 if (rfirst + diff > max)
5204                     max = rfirst + diff;
5205                 if (!grows)
5206                     grows = (tfirst < rfirst &&
5207                              UNISKIP(tfirst) < UNISKIP(rfirst + diff));
5208                 rfirst += diff + 1;
5209             }
5210             tfirst += diff + 1;
5211         }
5212
5213         none = ++max;
5214         if (del)
5215             del = ++max;
5216
5217         if (max > 0xffff)
5218             bits = 32;
5219         else if (max > 0xff)
5220             bits = 16;
5221         else
5222             bits = 8;
5223
5224         swash = MUTABLE_SV(swash_init("utf8", "", listsv, bits, none));
5225 #ifdef USE_ITHREADS
5226         cPADOPo->op_padix = pad_alloc(OP_TRANS, SVf_READONLY);
5227         SvREFCNT_dec(PAD_SVl(cPADOPo->op_padix));
5228         PAD_SETSV(cPADOPo->op_padix, swash);
5229         SvPADTMP_on(swash);
5230         SvREADONLY_on(swash);
5231 #else
5232         cSVOPo->op_sv = swash;
5233 #endif
5234         SvREFCNT_dec(listsv);
5235         SvREFCNT_dec(transv);
5236
5237         if (!del && havefinal && rlen)
5238             (void)hv_store(MUTABLE_HV(SvRV(swash)), "FINAL", 5,
5239                            newSVuv((UV)final), 0);
5240
5241         Safefree(tsave);
5242         Safefree(rsave);
5243
5244         tlen = tcount;
5245         rlen = rcount;
5246         if (r < rend)
5247             rlen++;
5248         else if (rlast == 0xffffffff)
5249             rlen = 0;
5250
5251         goto warnins;
5252     }
5253
5254     tbl = (short*)PerlMemShared_calloc(
5255         (o->op_private & OPpTRANS_COMPLEMENT) &&
5256             !(o->op_private & OPpTRANS_DELETE) ? 258 : 256,
5257         sizeof(short));
5258     cPVOPo->op_pv = (char*)tbl;
5259     if (complement) {
5260         for (i = 0; i < (I32)tlen; i++)
5261             tbl[t[i]] = -1;
5262         for (i = 0, j = 0; i < 256; i++) {
5263             if (!tbl[i]) {
5264                 if (j >= (I32)rlen) {
5265                     if (del)
5266                         tbl[i] = -2;
5267                     else if (rlen)
5268                         tbl[i] = r[j-1];
5269                     else
5270                         tbl[i] = (short)i;
5271                 }
5272                 else {
5273                     if (i < 128 && r[j] >= 128)
5274                         grows = 1;
5275                     tbl[i] = r[j++];
5276                 }
5277             }
5278         }
5279         if (!del) {
5280             if (!rlen) {
5281                 j = rlen;
5282                 if (!squash)
5283                     o->op_private |= OPpTRANS_IDENTICAL;
5284             }
5285             else if (j >= (I32)rlen)
5286                 j = rlen - 1;
5287             else {
5288                 tbl = 
5289                     (short *)
5290                     PerlMemShared_realloc(tbl,
5291                                           (0x101+rlen-j) * sizeof(short));
5292                 cPVOPo->op_pv = (char*)tbl;
5293             }
5294             tbl[0x100] = (short)(rlen - j);
5295             for (i=0; i < (I32)rlen - j; i++)
5296                 tbl[0x101+i] = r[j+i];
5297         }
5298     }
5299     else {
5300         if (!rlen && !del) {
5301             r = t; rlen = tlen;
5302             if (!squash)
5303                 o->op_private |= OPpTRANS_IDENTICAL;
5304         }
5305         else if (!squash && rlen == tlen && memEQ((char*)t, (char*)r, tlen)) {
5306             o->op_private |= OPpTRANS_IDENTICAL;
5307         }
5308         for (i = 0; i < 256; i++)
5309             tbl[i] = -1;
5310         for (i = 0, j = 0; i < (I32)tlen; i++,j++) {
5311             if (j >= (I32)rlen) {
5312                 if (del) {
5313                     if (tbl[t[i]] == -1)
5314                         tbl[t[i]] = -2;
5315                     continue;
5316                 }
5317                 --j;
5318             }
5319             if (tbl[t[i]] == -1) {
5320                 if (t[i] < 128 && r[j] >= 128)
5321                     grows = 1;
5322                 tbl[t[i]] = r[j];
5323             }
5324         }
5325     }
5326
5327   warnins:
5328     if(del && rlen == tlen) {
5329         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Useless use of /d modifier in transliteration operator"); 
5330     } else if(rlen > tlen && !complement) {
5331         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Replacement list is longer than search list");
5332     }
5333
5334     if (grows)
5335         o->op_private |= OPpTRANS_GROWS;
5336     op_free(expr);
5337     op_free(repl);
5338
5339     return o;
5340 }
5341
5342 /*
5343 =for apidoc Am|OP *|newPMOP|I32 type|I32 flags
5344
5345 Constructs, checks, and returns an op of any pattern matching type.
5346 I<type> is the opcode.  I<flags> gives the eight bits of C<op_flags>
5347 and, shifted up eight bits, the eight bits of C<op_private>.
5348
5349 =cut
5350 */
5351
5352 OP *
5353 Perl_newPMOP(pTHX_ I32 type, I32 flags)
5354 {
5355     dVAR;
5356     PMOP *pmop;
5357
5358     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PMOP
5359         || type == OP_CUSTOM);
5360
5361     NewOp(1101, pmop, 1, PMOP);
5362     CHANGE_TYPE(pmop, type);
5363     pmop->op_flags = (U8)flags;
5364     pmop->op_private = (U8)(0 | (flags >> 8));
5365     if (PL_opargs[type] & OA_RETSCALAR)
5366         scalar((OP *)pmop);
5367
5368     if (PL_hints & HINT_RE_TAINT)
5369         pmop->op_pmflags |= PMf_RETAINT;
5370 #ifdef USE_LOCALE_CTYPE
5371     if (IN_LC_COMPILETIME(LC_CTYPE)) {
5372         set_regex_charset(&(pmop->op_pmflags), REGEX_LOCALE_CHARSET);
5373     }
5374     else
5375 #endif
5376          if (IN_UNI_8_BIT) {
5377         set_regex_charset(&(pmop->op_pmflags), REGEX_UNICODE_CHARSET);
5378     }
5379     if (PL_hints & HINT_RE_FLAGS) {
5380         SV *reflags = Perl_refcounted_he_fetch_pvn(aTHX_
5381          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags"), 0, 0
5382         );
5383         if (reflags && SvOK(reflags)) pmop->op_pmflags |= SvIV(reflags);
5384         reflags = Perl_refcounted_he_fetch_pvn(aTHX_
5385          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags_charset"), 0, 0
5386         );
5387         if (reflags && SvOK(reflags)) {
5388             set_regex_charset(&(pmop->op_pmflags), (regex_charset)SvIV(reflags));
5389         }
5390     }
5391
5392
5393 #ifdef USE_ITHREADS
5394     assert(SvPOK(PL_regex_pad[0]));
5395     if (SvCUR(PL_regex_pad[0])) {
5396         /* Pop off the "packed" IV from the end.  */
5397         SV *const repointer_list = PL_regex_pad[0];
5398         const char *p = SvEND(repointer_list) - sizeof(IV);
5399         const IV offset = *((IV*)p);
5400
5401         assert(SvCUR(repointer_list) % sizeof(IV) == 0);
5402
5403         SvEND_set(repointer_list, p);
5404
5405         pmop->op_pmoffset = offset;
5406         /* This slot should be free, so assert this:  */
5407         assert(PL_regex_pad[offset] == &PL_sv_undef);
5408     } else {
5409         SV * const repointer = &PL_sv_undef;
5410         av_push(PL_regex_padav, repointer);
5411         pmop->op_pmoffset = av_tindex(PL_regex_padav);
5412         PL_regex_pad = AvARRAY(PL_regex_padav);
5413     }
5414 #endif
5415
5416     return CHECKOP(type, pmop);
5417 }
5418
5419 static void
5420 S_set_haseval(pTHX)
5421 {
5422     PADOFFSET i = 1;
5423     PL_cv_has_eval = 1;
5424     /* Any pad names in scope are potentially lvalues.  */
5425     for (; i < PadnamelistMAXNAMED(PL_comppad_name); i++) {
5426         PADNAME *pn = PAD_COMPNAME_SV(i);
5427         if (!pn || !PadnameLEN(pn))
5428             continue;
5429         if (PadnameOUTER(pn) || PadnameIN_SCOPE(pn, PL_cop_seqmax))
5430             S_mark_padname_lvalue(aTHX_ pn);
5431     }
5432 }
5433
5434 /* Given some sort of match op o, and an expression expr containing a
5435  * pattern, either compile expr into a regex and attach it to o (if it's
5436  * constant), or convert expr into a runtime regcomp op sequence (if it's
5437  * not)
5438  *
5439  * isreg indicates that the pattern is part of a regex construct, eg
5440  * $x =~ /pattern/ or split /pattern/, as opposed to $x =~ $pattern or
5441  * split "pattern", which aren't. In the former case, expr will be a list
5442  * if the pattern contains more than one term (eg /a$b/).
5443  *
5444  * When the pattern has been compiled within a new anon CV (for
5445  * qr/(?{...})/ ), then floor indicates the savestack level just before
5446  * the new sub was created
5447  */
5448
5449 OP *
5450 Perl_pmruntime(pTHX_ OP *o, OP *expr, OP *repl, bool isreg, I32 floor)
5451 {
5452     PMOP *pm;
5453     LOGOP *rcop;
5454     I32 repl_has_vars = 0;
5455     bool is_trans = (o->op_type == OP_TRANS || o->op_type == OP_TRANSR);
5456     bool is_compiletime;
5457     bool has_code;
5458
5459     PERL_ARGS_ASSERT_PMRUNTIME;
5460
5461     if (is_trans) {
5462         return pmtrans(o, expr, repl);
5463     }
5464
5465     /* find whether we have any runtime or code elements;
5466      * at the same time, temporarily set the op_next of each DO block;
5467      * then when we LINKLIST, this will cause the DO blocks to be excluded
5468      * from the op_next chain (and from having LINKLIST recursively
5469      * applied to them). We fix up the DOs specially later */
5470
5471     is_compiletime = 1;
5472     has_code = 0;
5473     if (expr->op_type == OP_LIST) {
5474         OP *o;
5475         for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
5476             if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)) {
5477                 has_code = 1;
5478                 assert(!o->op_next);
5479                 if (UNLIKELY(!OpHAS_SIBLING(o))) {
5480                     assert(PL_parser && PL_parser->error_count);
5481                     /* This can happen with qr/ (?{(^{})/.  Just fake up
5482                        the op we were expecting to see, to avoid crashing
5483                        elsewhere.  */
5484                     op_sibling_splice(expr, o, 0,
5485                                       newSVOP(OP_CONST, 0, &PL_sv_no));
5486                 }
5487                 o->op_next = OpSIBLING(o);
5488             }
5489             else if (o->op_type != OP_CONST && o->op_type != OP_PUSHMARK)
5490                 is_compiletime = 0;
5491         }
5492     }
5493     else if (expr->op_type != OP_CONST)
5494         is_compiletime = 0;
5495
5496     LINKLIST(expr);
5497
5498     /* fix up DO blocks; treat each one as a separate little sub;
5499      * also, mark any arrays as LIST/REF */
5500
5501     if (expr->op_type == OP_LIST) {
5502         OP *o;
5503         for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
5504
5505             if (o->op_type == OP_PADAV || o->op_type == OP_RV2AV) {
5506                 assert( !(o->op_flags  & OPf_WANT));
5507                 /* push the array rather than its contents. The regex
5508                  * engine will retrieve and join the elements later */
5509                 o->op_flags |= (OPf_WANT_LIST | OPf_REF);
5510                 continue;
5511             }
5512
5513             if (!(o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)))
5514                 continue;
5515             o->op_next = NULL; /* undo temporary hack from above */
5516             scalar(o);
5517             LINKLIST(o);
5518             if (cLISTOPo->op_first->op_type == OP_LEAVE) {
5519                 LISTOP *leaveop = cLISTOPx(cLISTOPo->op_first);
5520                 /* skip ENTER */
5521                 assert(leaveop->op_first->op_type == OP_ENTER);
5522                 assert(OpHAS_SIBLING(leaveop->op_first));
5523                 o->op_next = OpSIBLING(leaveop->op_first);
5524                 /* skip leave */
5525                 assert(leaveop->op_flags & OPf_KIDS);
5526                 assert(leaveop->op_last->op_next == (OP*)leaveop);
5527                 leaveop->op_next = NULL; /* stop on last op */
5528                 op_null((OP*)leaveop);
5529             }
5530             else {
5531                 /* skip SCOPE */
5532                 OP *scope = cLISTOPo->op_first;
5533                 assert(scope->op_type == OP_SCOPE);
5534                 assert(scope->op_flags & OPf_KIDS);
5535                 scope->op_next = NULL; /* stop on last op */
5536                 op_null(scope);
5537             }
5538             /* have to peep the DOs individually as we've removed it from
5539              * the op_next chain */
5540             CALL_PEEP(o);
5541             S_prune_chain_head(&(o->op_next));
5542             if (is_compiletime)
5543                 /* runtime finalizes as part of finalizing whole tree */
5544                 finalize_optree(o);
5545         }
5546     }
5547     else if (expr->op_type == OP_PADAV || expr->op_type == OP_RV2AV) {
5548         assert( !(expr->op_flags  & OPf_WANT));
5549         /* push the array rather than its contents. The regex
5550          * engine will retrieve and join the elements later */
5551         expr->op_flags |= (OPf_WANT_LIST | OPf_REF);
5552     }
5553
5554     PL_hints |= HINT_BLOCK_SCOPE;
5555     pm = (PMOP*)o;
5556     assert(floor==0 || (pm->op_pmflags & PMf_HAS_CV));
5557
5558     if (is_compiletime) {
5559         U32 rx_flags = pm->op_pmflags & RXf_PMf_COMPILETIME;
5560         regexp_engine const *eng = current_re_engine();
5561
5562         if (o->op_flags & OPf_SPECIAL)
5563             rx_flags |= RXf_SPLIT;
5564
5565         if (!has_code || !eng->op_comp) {
5566             /* compile-time simple constant pattern */
5567
5568             if ((pm->op_pmflags & PMf_HAS_CV) && !has_code) {
5569                 /* whoops! we guessed that a qr// had a code block, but we
5570                  * were wrong (e.g. /[(?{}]/ ). Throw away the PL_compcv
5571                  * that isn't required now. Note that we have to be pretty
5572                  * confident that nothing used that CV's pad while the
5573                  * regex was parsed, except maybe op targets for \Q etc.
5574                  * If there were any op targets, though, they should have
5575                  * been stolen by constant folding.
5576                  */
5577 #ifdef DEBUGGING
5578                 SSize_t i = 0;
5579                 assert(PadnamelistMAXNAMED(PL_comppad_name) == 0);
5580                 while (++i <= AvFILLp(PL_comppad)) {
5581                     assert(!PL_curpad[i]);
5582                 }
5583 #endif
5584                 /* But we know that one op is using this CV's slab. */
5585                 cv_forget_slab(PL_compcv);
5586                 LEAVE_SCOPE(floor);
5587                 pm->op_pmflags &= ~PMf_HAS_CV;
5588             }
5589
5590             PM_SETRE(pm,
5591                 eng->op_comp
5592                     ? eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
5593                                         rx_flags, pm->op_pmflags)
5594                     : Perl_re_op_compile(aTHX_ NULL, 0, expr, eng, NULL, NULL,
5595                                         rx_flags, pm->op_pmflags)
5596             );
5597             op_free(expr);
5598         }
5599         else {
5600             /* compile-time pattern that includes literal code blocks */
5601             REGEXP* re = eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
5602                         rx_flags,
5603                         (pm->op_pmflags |
5604                             ((PL_hints & HINT_RE_EVAL) ? PMf_USE_RE_EVAL : 0))
5605                     );
5606             PM_SETRE(pm, re);
5607             if (pm->op_pmflags & PMf_HAS_CV) {
5608                 CV *cv;
5609                 /* this QR op (and the anon sub we embed it in) is never
5610                  * actually executed. It's just a placeholder where we can
5611                  * squirrel away expr in op_code_list without the peephole
5612                  * optimiser etc processing it for a second time */
5613                 OP *qr = newPMOP(OP_QR, 0);
5614                 ((PMOP*)qr)->op_code_list = expr;
5615
5616                 /* handle the implicit sub{} wrapped round the qr/(?{..})/ */
5617                 SvREFCNT_inc_simple_void(PL_compcv);
5618                 cv = newATTRSUB(floor, 0, NULL, NULL, qr);
5619                 ReANY(re)->qr_anoncv = cv;
5620
5621                 /* attach the anon CV to the pad so that
5622                  * pad_fixup_inner_anons() can find it */
5623                 (void)pad_add_anon(cv, o->op_type);
5624                 SvREFCNT_inc_simple_void(cv);
5625             }
5626             else {
5627                 pm->op_code_list = expr;
5628             }
5629         }
5630     }
5631     else {
5632         /* runtime pattern: build chain of regcomp etc ops */
5633         bool reglist;
5634         PADOFFSET cv_targ = 0;
5635
5636         reglist = isreg && expr->op_type == OP_LIST;
5637         if (reglist)
5638             op_null(expr);
5639
5640         if (has_code) {
5641             pm->op_code_list = expr;
5642             /* don't free op_code_list; its ops are embedded elsewhere too */
5643             pm->op_pmflags |= PMf_CODELIST_PRIVATE;
5644         }
5645
5646         if (o->op_flags & OPf_SPECIAL)
5647             pm->op_pmflags |= PMf_SPLIT;
5648
5649         /* the OP_REGCMAYBE is a placeholder in the non-threaded case
5650          * to allow its op_next to be pointed past the regcomp and
5651          * preceding stacking ops;
5652          * OP_REGCRESET is there to reset taint before executing the
5653          * stacking ops */
5654         if (pm->op_pmflags & PMf_KEEP || TAINTING_get)
5655             expr = newUNOP((TAINTING_get ? OP_REGCRESET : OP_REGCMAYBE),0,expr);
5656
5657         if (pm->op_pmflags & PMf_HAS_CV) {
5658             /* we have a runtime qr with literal code. This means
5659              * that the qr// has been wrapped in a new CV, which
5660              * means that runtime consts, vars etc will have been compiled
5661              * against a new pad. So... we need to execute those ops
5662              * within the environment of the new CV. So wrap them in a call
5663              * to a new anon sub. i.e. for
5664              *
5665              *     qr/a$b(?{...})/,
5666              *
5667              * we build an anon sub that looks like
5668              *
5669              *     sub { "a", $b, '(?{...})' }
5670              *
5671              * and call it, passing the returned list to regcomp.
5672              * Or to put it another way, the list of ops that get executed
5673              * are:
5674              *
5675              *     normal              PMf_HAS_CV
5676              *     ------              -------------------
5677              *                         pushmark (for regcomp)
5678              *                         pushmark (for entersub)
5679              *                         anoncode
5680              *                         srefgen
5681              *                         entersub
5682              *     regcreset                  regcreset
5683              *     pushmark                   pushmark
5684              *     const("a")                 const("a")
5685              *     gvsv(b)                    gvsv(b)
5686              *     const("(?{...})")          const("(?{...})")
5687              *                                leavesub
5688              *     regcomp             regcomp
5689              */
5690
5691             SvREFCNT_inc_simple_void(PL_compcv);
5692             CvLVALUE_on(PL_compcv);
5693             /* these lines are just an unrolled newANONATTRSUB */
5694             expr = newSVOP(OP_ANONCODE, 0,
5695                     MUTABLE_SV(newATTRSUB(floor, 0, NULL, NULL, expr)));
5696             cv_targ = expr->op_targ;
5697             expr = newUNOP(OP_REFGEN, 0, expr);
5698
5699             expr = list(force_list(newUNOP(OP_ENTERSUB, 0, scalar(expr)), 1));
5700         }
5701
5702         rcop = S_alloc_LOGOP(aTHX_ OP_REGCOMP, scalar(expr), o);
5703         rcop->op_flags |=  ((PL_hints & HINT_RE_EVAL) ? OPf_SPECIAL : 0)
5704                            | (reglist ? OPf_STACKED : 0);
5705         rcop->op_targ = cv_targ;
5706
5707         /* /$x/ may cause an eval, since $x might be qr/(?{..})/  */
5708         if (PL_hints & HINT_RE_EVAL)
5709             S_set_haseval(aTHX);
5710
5711         /* establish postfix order */
5712         if (expr->op_type == OP_REGCRESET || expr->op_type == OP_REGCMAYBE) {
5713             LINKLIST(expr);
5714             rcop->op_next = expr;
5715             ((UNOP*)expr)->op_first->op_next = (OP*)rcop;
5716         }
5717         else {
5718             rcop->op_next = LINKLIST(expr);
5719             expr->op_next = (OP*)rcop;
5720         }
5721
5722         op_prepend_elem(o->op_type, scalar((OP*)rcop), o);
5723     }
5724
5725     if (repl) {
5726         OP *curop = repl;
5727         bool konst;
5728         /* If we are looking at s//.../e with a single statement, get past
5729            the implicit do{}. */
5730         if (curop->op_type == OP_NULL && curop->op_flags & OPf_KIDS
5731              && cUNOPx(curop)->op_first->op_type == OP_SCOPE
5732              && cUNOPx(curop)->op_first->op_flags & OPf_KIDS)
5733          {
5734             OP *sib;
5735             OP *kid = cUNOPx(cUNOPx(curop)->op_first)->op_first;
5736             if (kid->op_type == OP_NULL && (sib = OpSIBLING(kid))
5737              && !OpHAS_SIBLING(sib))
5738                 curop = sib;
5739         }
5740         if (curop->op_type == OP_CONST)
5741             konst = TRUE;
5742         else if (( (curop->op_type == OP_RV2SV ||
5743                     curop->op_type == OP_RV2AV ||
5744                     curop->op_type == OP_RV2HV ||
5745                     curop->op_type == OP_RV2GV)
5746                    && cUNOPx(curop)->op_first
5747                    && cUNOPx(curop)->op_first->op_type == OP_GV )
5748                 || curop->op_type == OP_PADSV
5749                 || curop->op_type == OP_PADAV
5750                 || curop->op_type == OP_PADHV
5751                 || curop->op_type == OP_PADANY) {
5752             repl_has_vars = 1;
5753             konst = TRUE;
5754         }
5755         else konst = FALSE;
5756         if (konst
5757             && !(repl_has_vars
5758                  && (!PM_GETRE(pm)
5759                      || !RX_PRELEN(PM_GETRE(pm))
5760                      || RX_EXTFLAGS(PM_GETRE(pm)) & RXf_EVAL_SEEN)))
5761         {
5762             pm->op_pmflags |= PMf_CONST;        /* const for long enough */
5763             op_prepend_elem(o->op_type, scalar(repl), o);
5764         }
5765         else {
5766             rcop = S_alloc_LOGOP(aTHX_ OP_SUBSTCONT, scalar(repl), o);
5767             rcop->op_private = 1;
5768
5769             /* establish postfix order */
5770             rcop->op_next = LINKLIST(repl);
5771             repl->op_next = (OP*)rcop;
5772
5773             pm->op_pmreplrootu.op_pmreplroot = scalar((OP*)rcop);
5774             assert(!(pm->op_pmflags & PMf_ONCE));
5775             pm->op_pmstashstartu.op_pmreplstart = LINKLIST(rcop);
5776             rcop->op_next = 0;
5777         }
5778     }
5779
5780     return (OP*)pm;
5781 }
5782
5783 /*
5784 =for apidoc Am|OP *|newSVOP|I32 type|I32 flags|SV *sv
5785
5786 Constructs, checks, and returns an op of any type that involves an
5787 embedded SV.  I<type> is the opcode.  I<flags> gives the eight bits
5788 of C<op_flags>.  I<sv> gives the SV to embed in the op; this function
5789 takes ownership of one reference to it.
5790
5791 =cut
5792 */
5793
5794 OP *
5795 Perl_newSVOP(pTHX_ I32 type, I32 flags, SV *sv)
5796 {
5797     dVAR;
5798     SVOP *svop;
5799
5800     PERL_ARGS_ASSERT_NEWSVOP;
5801
5802     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
5803         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
5804         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
5805         || type == OP_CUSTOM);
5806
5807     NewOp(1101, svop, 1, SVOP);
5808     CHANGE_TYPE(svop, type);
5809     svop->op_sv = sv;
5810     svop->op_next = (OP*)svop;
5811     svop->op_flags = (U8)flags;
5812     svop->op_private = (U8)(0 | (flags >> 8));
5813     if (PL_opargs[type] & OA_RETSCALAR)
5814         scalar((OP*)svop);
5815     if (PL_opargs[type] & OA_TARGET)
5816         svop->op_targ = pad_alloc(type, SVs_PADTMP);
5817     return CHECKOP(type, svop);
5818 }
5819
5820 /*
5821 =for apidoc Am|OP *|newDEFSVOP|
5822
5823 Constructs and returns an op to access C<$_>, either as a lexical
5824 variable (if declared as C<my $_>) in the current scope, or the
5825 global C<$_>.
5826
5827 =cut
5828 */
5829
5830 OP *
5831 Perl_newDEFSVOP(pTHX)
5832 {
5833     const PADOFFSET offset = pad_findmy_pvs("$_", 0);
5834     if (offset == NOT_IN_PAD || PAD_COMPNAME_FLAGS_isOUR(offset)) {
5835         return newSVREF(newGVOP(OP_GV, 0, PL_defgv));
5836     }
5837     else {
5838         OP * const o = newOP(OP_PADSV, 0);
5839         o->op_targ = offset;
5840         return o;
5841     }
5842 }
5843
5844 #ifdef USE_ITHREADS
5845
5846 /*
5847 =for apidoc Am|OP *|newPADOP|I32 type|I32 flags|SV *sv
5848
5849 Constructs, checks, and returns an op of any type that involves a
5850 reference to a pad element.  I<type> is the opcode.  I<flags> gives the
5851 eight bits of C<op_flags>.  A pad slot is automatically allocated, and
5852 is populated with I<sv>; this function takes ownership of one reference
5853 to it.
5854
5855 This function only exists if Perl has been compiled to use ithreads.
5856
5857 =cut
5858 */
5859
5860 OP *
5861 Perl_newPADOP(pTHX_ I32 type, I32 flags, SV *sv)
5862 {
5863     dVAR;
5864     PADOP *padop;
5865
5866     PERL_ARGS_ASSERT_NEWPADOP;
5867
5868     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
5869         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
5870         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
5871         || type == OP_CUSTOM);
5872
5873     NewOp(1101, padop, 1, PADOP);
5874     CHANGE_TYPE(padop, type);
5875     padop->op_padix =
5876         pad_alloc(type, isGV(sv) ? SVf_READONLY : SVs_PADTMP);
5877     SvREFCNT_dec(PAD_SVl(padop->op_padix));
5878     PAD_SETSV(padop->op_padix, sv);
5879     assert(sv);
5880     padop->op_next = (OP*)padop;
5881     padop->op_flags = (U8)flags;
5882     if (PL_opargs[type] & OA_RETSCALAR)
5883         scalar((OP*)padop);
5884     if (PL_opargs[type] & OA_TARGET)
5885         padop->op_targ = pad_alloc(type, SVs_PADTMP);
5886     return CHECKOP(type, padop);
5887 }
5888
5889 #endif /* USE_ITHREADS */
5890
5891 /*
5892 =for apidoc Am|OP *|newGVOP|I32 type|I32 flags|GV *gv
5893
5894 Constructs, checks, and returns an op of any type that involves an
5895 embedded reference to a GV.  I<type> is the opcode.  I<flags> gives the
5896 eight bits of C<op_flags>.  I<gv> identifies the GV that the op should
5897 reference; calling this function does not transfer ownership of any
5898 reference to it.
5899
5900 =cut
5901 */
5902
5903 OP *
5904 Perl_newGVOP(pTHX_ I32 type, I32 flags, GV *gv)
5905 {
5906     PERL_ARGS_ASSERT_NEWGVOP;
5907
5908 #ifdef USE_ITHREADS
5909     return newPADOP(type, flags, SvREFCNT_inc_simple_NN(gv));
5910 #else
5911     return newSVOP(type, flags, SvREFCNT_inc_simple_NN(gv));
5912 #endif
5913 }
5914
5915 /*
5916 =for apidoc Am|OP *|newPVOP|I32 type|I32 flags|char *pv
5917
5918 Constructs, checks, and returns an op of any type that involves an
5919 embedded C-level pointer (PV).  I<type> is the opcode.  I<flags> gives
5920 the eight bits of C<op_flags>.  I<pv> supplies the C-level pointer, which
5921 must have been allocated using C<PerlMemShared_malloc>; the memory will
5922 be freed when the op is destroyed.
5923
5924 =cut
5925 */
5926
5927 OP *
5928 Perl_newPVOP(pTHX_ I32 type, I32 flags, char *pv)
5929 {
5930     dVAR;
5931     const bool utf8 = cBOOL(flags & SVf_UTF8);
5932     PVOP *pvop;
5933
5934     flags &= ~SVf_UTF8;
5935
5936     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
5937         || type == OP_RUNCV || type == OP_CUSTOM
5938         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
5939
5940     NewOp(1101, pvop, 1, PVOP);
5941     CHANGE_TYPE(pvop, type);
5942     pvop->op_pv = pv;
5943     pvop->op_next = (OP*)pvop;
5944     pvop->op_flags = (U8)flags;
5945     pvop->op_private = utf8 ? OPpPV_IS_UTF8 : 0;
5946     if (PL_opargs[type] & OA_RETSCALAR)
5947         scalar((OP*)pvop);
5948     if (PL_opargs[type] & OA_TARGET)
5949         pvop->op_targ = pad_alloc(type, SVs_PADTMP);
5950     return CHECKOP(type, pvop);
5951 }
5952
5953 void
5954 Perl_package(pTHX_ OP *o)
5955 {
5956     SV *const sv = cSVOPo->op_sv;
5957
5958     PERL_ARGS_ASSERT_PACKAGE;
5959
5960     SAVEGENERICSV(PL_curstash);
5961     save_item(PL_curstname);
5962
5963     PL_curstash = (HV *)SvREFCNT_inc(gv_stashsv(sv, GV_ADD));
5964
5965     sv_setsv(PL_curstname, sv);
5966
5967     PL_hints |= HINT_BLOCK_SCOPE;
5968     PL_parser->copline = NOLINE;
5969
5970     op_free(o);
5971 }
5972
5973 void
5974 Perl_package_version( pTHX_ OP *v )
5975 {
5976     U32 savehints = PL_hints;
5977     PERL_ARGS_ASSERT_PACKAGE_VERSION;
5978     PL_hints &= ~HINT_STRICT_VARS;
5979     sv_setsv( GvSV(gv_fetchpvs("VERSION", GV_ADDMULTI, SVt_PV)), cSVOPx(v)->op_sv );
5980     PL_hints = savehints;
5981     op_free(v);
5982 }
5983
5984 void
5985 Perl_utilize(pTHX_ int aver, I32 floor, OP *version, OP *idop, OP *arg)
5986 {
5987     OP *pack;
5988     OP *imop;
5989     OP *veop;
5990     SV *use_version = NULL;
5991
5992     PERL_ARGS_ASSERT_UTILIZE;
5993
5994     if (idop->op_type != OP_CONST)
5995         Perl_croak(aTHX_ "Module name must be constant");
5996
5997     veop = NULL;
5998
5999     if (version) {
6000         SV * const vesv = ((SVOP*)version)->op_sv;
6001
6002         if (!arg && !SvNIOKp(vesv)) {
6003             arg = version;
6004         }
6005         else {
6006             OP *pack;
6007             SV *meth;
6008
6009             if (version->op_type != OP_CONST || !SvNIOKp(vesv))
6010                 Perl_croak(aTHX_ "Version number must be a constant number");
6011
6012             /* Make copy of idop so we don't free it twice */
6013             pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
6014
6015             /* Fake up a method call to VERSION */
6016             meth = newSVpvs_share("VERSION");
6017             veop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
6018                             op_append_elem(OP_LIST,
6019                                         op_prepend_elem(OP_LIST, pack, version),
6020                                         newMETHOP_named(OP_METHOD_NAMED, 0, meth)));
6021         }
6022     }
6023
6024     /* Fake up an import/unimport */
6025     if (arg && arg->op_type == OP_STUB) {
6026         imop = arg;             /* no import on explicit () */
6027     }
6028     else if (SvNIOKp(((SVOP*)idop)->op_sv)) {
6029         imop = NULL;            /* use 5.0; */
6030         if (aver)
6031             use_version = ((SVOP*)idop)->op_sv;
6032         else
6033             idop->op_private |= OPpCONST_NOVER;
6034     }
6035     else {
6036         SV *meth;
6037
6038         /* Make copy of idop so we don't free it twice */
6039         pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
6040
6041         /* Fake up a method call to import/unimport */
6042         meth = aver
6043             ? newSVpvs_share("import") : newSVpvs_share("unimport");
6044         imop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
6045                        op_append_elem(OP_LIST,
6046                                    op_prepend_elem(OP_LIST, pack, arg),
6047                                    newMETHOP_named(OP_METHOD_NAMED, 0, meth)
6048                        ));
6049     }
6050
6051     /* Fake up the BEGIN {}, which does its thing immediately. */
6052     newATTRSUB(floor,
6053         newSVOP(OP_CONST, 0, newSVpvs_share("BEGIN")),
6054         NULL,
6055         NULL,
6056         op_append_elem(OP_LINESEQ,
6057             op_append_elem(OP_LINESEQ,
6058                 newSTATEOP(0, NULL, newUNOP(OP_REQUIRE, 0, idop)),
6059                 newSTATEOP(0, NULL, veop)),
6060             newSTATEOP(0, NULL, imop) ));
6061
6062     if (use_version) {
6063         /* Enable the
6064          * feature bundle that corresponds to the required version. */
6065         use_version = sv_2mortal(new_version(use_version));
6066         S_enable_feature_bundle(aTHX_ use_version);
6067
6068         /* If a version >= 5.11.0 is requested, strictures are on by default! */
6069         if (vcmp(use_version,
6070                  sv_2mortal(upg_version(newSVnv(5.011000), FALSE))) >= 0) {
6071             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
6072                 PL_hints |= HINT_STRICT_REFS;
6073             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
6074                 PL_hints |= HINT_STRICT_SUBS;
6075             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
6076                 PL_hints |= HINT_STRICT_VARS;
6077         }
6078         /* otherwise they are off */
6079         else {
6080             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
6081                 PL_hints &= ~HINT_STRICT_REFS;
6082             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
6083                 PL_hints &= ~HINT_STRICT_SUBS;
6084             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
6085                 PL_hints &= ~HINT_STRICT_VARS;
6086         }
6087     }
6088
6089     /* The "did you use incorrect case?" warning used to be here.
6090      * The problem is that on case-insensitive filesystems one
6091      * might get false positives for "use" (and "require"):
6092      * "use Strict" or "require CARP" will work.  This causes
6093      * portability problems for the script: in case-strict
6094      * filesystems the script will stop working.
6095      *
6096      * The "incorrect case" warning checked whether "use Foo"
6097      * imported "Foo" to your namespace, but that is wrong, too:
6098      * there is no requirement nor promise in the language that
6099      * a Foo.pm should or would contain anything in package "Foo".
6100      *
6101      * There is very little Configure-wise that can be done, either:
6102      * the case-sensitivity of the build filesystem of Perl does not
6103      * help in guessing the case-sensitivity of the runtime environment.
6104      */
6105
6106     PL_hints |= HINT_BLOCK_SCOPE;
6107     PL_parser->copline = NOLINE;
6108     COP_SEQMAX_INC; /* Purely for B::*'s benefit */
6109 }
6110
6111 /*
6112 =head1 Embedding Functions
6113
6114 =for apidoc load_module
6115
6116 Loads the module whose name is pointed to by the string part of name.
6117 Note that the actual module name, not its filename, should be given.
6118 Eg, "Foo::Bar" instead of "Foo/Bar.pm".  flags can be any of
6119 PERL_LOADMOD_DENY, PERL_LOADMOD_NOIMPORT, or PERL_LOADMOD_IMPORT_OPS
6120 (or 0 for no flags).  ver, if specified
6121 and not NULL, provides version semantics
6122 similar to C<use Foo::Bar VERSION>.  The optional trailing SV*
6123 arguments can be used to specify arguments to the module's import()
6124 method, similar to C<use Foo::Bar VERSION LIST>.  They must be
6125 terminated with a final NULL pointer.  Note that this list can only
6126 be omitted when the PERL_LOADMOD_NOIMPORT flag has been used.
6127 Otherwise at least a single NULL pointer to designate the default
6128 import list is required.
6129
6130 The reference count for each specified C<SV*> parameter is decremented.
6131
6132 =cut */
6133
6134 void
6135 Perl_load_module(pTHX_ U32 flags, SV *name, SV *ver, ...)
6136 {
6137     va_list args;
6138
6139     PERL_ARGS_ASSERT_LOAD_MODULE;
6140
6141     va_start(args, ver);
6142     vload_module(flags, name, ver, &args);
6143     va_end(args);
6144 }
6145
6146 #ifdef PERL_IMPLICIT_CONTEXT
6147 void
6148 Perl_load_module_nocontext(U32 flags, SV *name, SV *ver, ...)
6149 {
6150     dTHX;
6151     va_list args;
6152     PERL_ARGS_ASSERT_LOAD_MODULE_NOCONTEXT;
6153     va_start(args, ver);
6154     vload_module(flags, name, ver, &args);
6155     va_end(args);
6156 }
6157 #endif
6158
6159 void
6160 Perl_vload_module(pTHX_ U32 flags, SV *name, SV *ver, va_list *args)
6161 {
6162     OP *veop, *imop;
6163     OP * const modname = newSVOP(OP_CONST, 0, name);
6164
6165     PERL_ARGS_ASSERT_VLOAD_MODULE;
6166
6167     modname->op_private |= OPpCONST_BARE;
6168     if (ver) {
6169         veop = newSVOP(OP_CONST, 0, ver);
6170     }
6171     else
6172         veop = NULL;
6173     if (flags & PERL_LOADMOD_NOIMPORT) {
6174         imop = sawparens(newNULLLIST());
6175     }
6176     else if (flags & PERL_LOADMOD_IMPORT_OPS) {
6177         imop = va_arg(*args, OP*);
6178     }
6179     else {
6180         SV *sv;
6181         imop = NULL;
6182         sv = va_arg(*args, SV*);
6183         while (sv) {
6184             imop = op_append_elem(OP_LIST, imop, newSVOP(OP_CONST, 0, sv));
6185             sv = va_arg(*args, SV*);
6186         }
6187     }
6188
6189     /* utilize() fakes up a BEGIN { require ..; import ... }, so make sure
6190      * that it has a PL_parser to play with while doing that, and also
6191      * that it doesn't mess with any existing parser, by creating a tmp
6192      * new parser with lex_start(). This won't actually be used for much,
6193      * since pp_require() will create another parser for the real work.
6194      * The ENTER/LEAVE pair protect callers from any side effects of use.  */
6195
6196     ENTER;
6197     SAVEVPTR(PL_curcop);
6198     lex_start(NULL, NULL, LEX_START_SAME_FILTER);
6199     utilize(!(flags & PERL_LOADMOD_DENY), start_subparse(FALSE, 0),
6200             veop, modname, imop);
6201     LEAVE;
6202 }
6203
6204 PERL_STATIC_INLINE OP *
6205 S_new_entersubop(pTHX_ GV *gv, OP *arg)
6206 {
6207     return newUNOP(OP_ENTERSUB, OPf_STACKED,
6208                    newLISTOP(OP_LIST, 0, arg,
6209                              newUNOP(OP_RV2CV, 0,
6210                                      newGVOP(OP_GV, 0, gv))));
6211 }
6212
6213 OP *
6214 Perl_dofile(pTHX_ OP *term, I32 force_builtin)
6215 {
6216     OP *doop;
6217     GV *gv;
6218
6219     PERL_ARGS_ASSERT_DOFILE;
6220
6221     if (!force_builtin && (gv = gv_override("do", 2))) {
6222         doop = S_new_entersubop(aTHX_ gv, term);
6223     }
6224     else {
6225         doop = newUNOP(OP_DOFILE, 0, scalar(term));
6226     }
6227     return doop;
6228 }
6229
6230 /*
6231 =head1 Optree construction
6232
6233 =for apidoc Am|OP *|newSLICEOP|I32 flags|OP *subscript|OP *listval
6234
6235 Constructs, checks, and returns an C<lslice> (list slice) op.  I<flags>
6236 gives the eight bits of C<op_flags>, except that C<OPf_KIDS> will
6237 be set automatically, and, shifted up eight bits, the eight bits of
6238 C<op_private>, except that the bit with value 1 or 2 is automatically
6239 set as required.  I<listval> and I<subscript> supply the parameters of
6240 the slice; they are consumed by this function and become part of the
6241 constructed op tree.
6242
6243 =cut
6244 */
6245
6246 OP *
6247 Perl_newSLICEOP(pTHX_ I32 flags, OP *subscript, OP *listval)
6248 {
6249     return newBINOP(OP_LSLICE, flags,
6250             list(force_list(subscript, 1)),
6251             list(force_list(listval,   1)) );
6252 }
6253
6254 #define ASSIGN_LIST   1
6255 #define ASSIGN_REF    2
6256
6257 STATIC I32
6258 S_assignment_type(pTHX_ const OP *o)
6259 {
6260     unsigned type;
6261     U8 flags;
6262     U8 ret;
6263
6264     if (!o)
6265         return TRUE;
6266
6267     if ((o->op_type == OP_NULL) && (o->op_flags & OPf_KIDS))
6268         o = cUNOPo->op_first;
6269
6270     flags = o->op_flags;
6271     type = o->op_type;
6272     if (type == OP_COND_EXPR) {
6273         OP * const sib = OpSIBLING(cLOGOPo->op_first);
6274         const I32 t = assignment_type(sib);
6275         const I32 f = assignment_type(OpSIBLING(sib));
6276
6277         if (t == ASSIGN_LIST && f == ASSIGN_LIST)
6278             return ASSIGN_LIST;
6279         if ((t == ASSIGN_LIST) ^ (f == ASSIGN_LIST))
6280             yyerror("Assignment to both a list and a scalar");
6281         return FALSE;
6282     }
6283
6284     if (type == OP_SREFGEN)
6285     {
6286         OP * const kid = cUNOPx(cUNOPo->op_first)->op_first;
6287         type = kid->op_type;
6288         flags |= kid->op_flags;
6289         if (!(flags & OPf_PARENS)
6290           && (kid->op_type == OP_RV2AV || kid->op_type == OP_PADAV ||
6291               kid->op_type == OP_RV2HV || kid->op_type == OP_PADHV ))
6292             return ASSIGN_REF;
6293         ret = ASSIGN_REF;
6294     }
6295     else ret = 0;
6296
6297     if (type == OP_LIST &&
6298         (flags & OPf_WANT) == OPf_WANT_SCALAR &&
6299         o->op_private & OPpLVAL_INTRO)
6300         return ret;
6301
6302     if (type == OP_LIST || flags & OPf_PARENS ||
6303         type == OP_RV2AV || type == OP_RV2HV ||
6304         type == OP_ASLICE || type == OP_HSLICE ||
6305         type == OP_KVASLICE || type == OP_KVHSLICE || type == OP_REFGEN)
6306         return TRUE;
6307
6308     if (type == OP_PADAV || type == OP_PADHV)
6309         return TRUE;
6310
6311     if (type == OP_RV2SV)
6312         return ret;
6313
6314     return ret;
6315 }
6316
6317 /*
6318   Helper function for newASSIGNOP to detect commonality between the
6319   lhs and the rhs.  (It is actually called very indirectly.  newASSIGNOP
6320   flags the op and the peephole optimizer calls this helper function
6321   if the flag is set.)  Marks all variables with PL_generation.  If it
6322   returns TRUE the assignment must be able to handle common variables.
6323
6324   PL_generation sorcery:
6325   An assignment like ($a,$b) = ($c,$d) is easier than
6326   ($a,$b) = ($c,$a), since there is no need for temporary vars.
6327   To detect whether there are common vars, the global var
6328   PL_generation is incremented for each assign op we compile.
6329   Then, while compiling the assign op, we run through all the
6330   variables on both sides of the assignment, setting a spare slot
6331   in each of them to PL_generation.  If any of them already have
6332   that value, we know we've got commonality.  Also, if the
6333   generation number is already set to PERL_INT_MAX, then
6334   the variable is involved in aliasing, so we also have
6335   potential commonality in that case.  We could use a
6336   single bit marker, but then we'd have to make 2 passes, first
6337   to clear the flag, then to test and set it.  And that
6338   wouldn't help with aliasing, either.  To find somewhere
6339   to store these values, evil chicanery is done with SvUVX().
6340 */
6341 PERL_STATIC_INLINE bool
6342 S_aassign_common_vars(pTHX_ OP* o)
6343 {
6344     OP *curop;
6345     for (curop = cUNOPo->op_first; curop; curop = OpSIBLING(curop)) {
6346         if (PL_opargs[curop->op_type] & OA_DANGEROUS) {
6347             if (curop->op_type == OP_GV || curop->op_type == OP_GVSV
6348              || curop->op_type == OP_AELEMFAST) {
6349                 GV *gv = cGVOPx_gv(curop);
6350                 if (gv == PL_defgv
6351                     || (int)GvASSIGN_GENERATION(gv) == PL_generation)
6352                     return TRUE;
6353                 GvASSIGN_GENERATION_set(gv, PL_generation);
6354             }
6355             else if (curop->op_type == OP_PADSV ||
6356                 curop->op_type == OP_PADAV ||
6357                 curop->op_type == OP_PADHV ||
6358                 curop->op_type == OP_AELEMFAST_LEX ||
6359                 curop->op_type == OP_PADANY)
6360                 {
6361                   padcheck:
6362                     if (PAD_COMPNAME_GEN(curop->op_targ)
6363                         == (STRLEN)PL_generation
6364                      || PAD_COMPNAME_GEN(curop->op_targ) == PERL_INT_MAX)
6365                         return TRUE;
6366                     PAD_COMPNAME_GEN_set(curop->op_targ, PL_generation);
6367
6368                 }
6369             else if (curop->op_type == OP_RV2CV)
6370                 return TRUE;
6371             else if (curop->op_type == OP_RV2SV ||
6372                 curop->op_type == OP_RV2AV ||
6373                 curop->op_type == OP_RV2HV ||
6374                 curop->op_type == OP_RV2GV) {
6375                 if (cUNOPx(curop)->op_first->op_type != OP_GV)  /* funny deref? */
6376                     return TRUE;
6377             }
6378             else if (curop->op_type == OP_PUSHRE) {
6379                 GV *const gv =
6380 #ifdef USE_ITHREADS
6381                     ((PMOP*)curop)->op_pmreplrootu.op_pmtargetoff
6382                         ? MUTABLE_GV(PAD_SVl(((PMOP*)curop)->op_pmreplrootu.op_pmtargetoff))
6383                         : NULL;
6384 #else
6385                     ((PMOP*)curop)->op_pmreplrootu.op_pmtargetgv;
6386 #endif
6387                 if (gv) {
6388                     if (gv == PL_defgv
6389                         || (int)GvASSIGN_GENERATION(gv) == PL_generation)
6390                         return TRUE;
6391                     GvASSIGN_GENERATION_set(gv, PL_generation);
6392                 }
6393                 else if (curop->op_targ)
6394                     goto padcheck;
6395             }
6396             else if (curop->op_type == OP_PADRANGE)
6397                 /* Ignore padrange; checking its siblings is sufficient. */
6398                 continue;
6399             else
6400                 return TRUE;
6401         }
6402         else if (PL_opargs[curop->op_type] & OA_TARGLEX
6403               && curop->op_private & OPpTARGET_MY)
6404             goto padcheck;
6405
6406         if (curop->op_flags & OPf_KIDS) {
6407             if (aassign_common_vars(curop))
6408                 return TRUE;
6409         }
6410     }
6411     return FALSE;
6412 }
6413
6414 /* This variant only handles lexical aliases.  It is called when
6415    newASSIGNOP decides that we don’t have any common vars, as lexical ali-
6416    ases trump that decision.  */
6417 PERL_STATIC_INLINE bool
6418 S_aassign_common_vars_aliases_only(pTHX_ OP *o)
6419 {
6420     OP *curop;
6421     for (curop = cUNOPo->op_first; curop; curop = OpSIBLING(curop)) {
6422         if ((curop->op_type == OP_PADSV ||
6423              curop->op_type == OP_PADAV ||
6424              curop->op_type == OP_PADHV ||
6425              curop->op_type == OP_AELEMFAST_LEX ||
6426              curop->op_type == OP_PADANY ||
6427              (  PL_opargs[curop->op_type] & OA_TARGLEX
6428              && curop->op_private & OPpTARGET_MY  ))
6429            && PAD_COMPNAME_GEN(curop->op_targ) == PERL_INT_MAX)
6430             return TRUE;
6431
6432         if (curop->op_type == OP_PUSHRE && curop->op_targ
6433          && PAD_COMPNAME_GEN(curop->op_targ) == PERL_INT_MAX)
6434             return TRUE;
6435
6436         if (curop->op_flags & OPf_KIDS) {
6437             if (S_aassign_common_vars_aliases_only(aTHX_ curop))
6438                 return TRUE;
6439         }
6440     }
6441     return FALSE;
6442 }
6443
6444 /*
6445 =for apidoc Am|OP *|newASSIGNOP|I32 flags|OP *left|I32 optype|OP *right
6446
6447 Constructs, checks, and returns an assignment op.  I<left> and I<right>
6448 supply the parameters of the assignment; they are consumed by this
6449 function and become part of the constructed op tree.
6450
6451 If I<optype> is C<OP_ANDASSIGN>, C<OP_ORASSIGN>, or C<OP_DORASSIGN>, then
6452 a suitable conditional optree is constructed.  If I<optype> is the opcode
6453 of a binary operator, such as C<OP_BIT_OR>, then an op is constructed that
6454 performs the binary operation and assigns the result to the left argument.
6455 Either way, if I<optype> is non-zero then I<flags> has no effect.
6456
6457 If I<optype> is zero, then a plain scalar or list assignment is
6458 constructed.  Which type of assignment it is is automatically determined.
6459 I<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
6460 will be set automatically, and, shifted up eight bits, the eight bits
6461 of C<op_private>, except that the bit with value 1 or 2 is automatically
6462 set as required.
6463
6464 =cut
6465 */
6466
6467 OP *
6468 Perl_newASSIGNOP(pTHX_ I32 flags, OP *left, I32 optype, OP *right)
6469 {
6470     OP *o;
6471     I32 assign_type;
6472
6473     if (optype) {
6474         if (optype == OP_ANDASSIGN || optype == OP_ORASSIGN || optype == OP_DORASSIGN) {
6475             return newLOGOP(optype, 0,
6476                 op_lvalue(scalar(left), optype),
6477                 newUNOP(OP_SASSIGN, 0, scalar(right)));
6478         }
6479         else {
6480             return newBINOP(optype, OPf_STACKED,
6481                 op_lvalue(scalar(left), optype), scalar(right));
6482         }
6483     }
6484
6485     if ((assign_type = assignment_type(left)) == ASSIGN_LIST) {
6486         static const char no_list_state[] = "Initialization of state variables"
6487             " in list context currently forbidden";
6488         OP *curop;
6489         bool maybe_common_vars = TRUE;
6490
6491         if (left->op_type == OP_ASLICE || left->op_type == OP_HSLICE)
6492             left->op_private &= ~ OPpSLICEWARNING;
6493
6494         PL_modcount = 0;
6495         left = op_lvalue(left, OP_AASSIGN);
6496         curop = list(force_list(left, 1));
6497         o = newBINOP(OP_AASSIGN, flags, list(force_list(right, 1)), curop);
6498         o->op_private = (U8)(0 | (flags >> 8));
6499
6500         if (OP_TYPE_IS_OR_WAS(left, OP_LIST))
6501         {
6502             OP* lop = ((LISTOP*)left)->op_first;
6503             maybe_common_vars = FALSE;
6504             while (lop) {
6505                 if (lop->op_type == OP_PADSV ||
6506                     lop->op_type == OP_PADAV ||
6507                     lop->op_type == OP_PADHV ||
6508                     lop->op_type == OP_PADANY) {
6509                     if (!(lop->op_private & OPpLVAL_INTRO))
6510                         maybe_common_vars = TRUE;
6511
6512                     if (lop->op_private & OPpPAD_STATE) {
6513                         if (left->op_private & OPpLVAL_INTRO) {
6514                             /* Each variable in state($a, $b, $c) = ... */
6515                         }
6516                         else {
6517                             /* Each state variable in
6518                                (state $a, my $b, our $c, $d, undef) = ... */
6519                         }
6520                         yyerror(no_list_state);
6521                     } else {
6522                         /* Each my variable in
6523                            (state $a, my $b, our $c, $d, undef) = ... */
6524                     }
6525                 } else if (lop->op_type == OP_UNDEF ||
6526                            OP_TYPE_IS_OR_WAS(lop, OP_PUSHMARK)) {
6527                     /* undef may be interesting in
6528                        (state $a, undef, state $c) */
6529                 } else {
6530                     /* Other ops in the list. */
6531                     maybe_common_vars = TRUE;
6532                 }
6533                 lop = OpSIBLING(lop);
6534             }
6535         }
6536         else if ((left->op_private & OPpLVAL_INTRO)
6537                 && (   left->op_type == OP_PADSV
6538                     || left->op_type == OP_PADAV
6539                     || left->op_type == OP_PADHV
6540                     || left->op_type == OP_PADANY))
6541         {
6542             if (left->op_type == OP_PADSV) maybe_common_vars = FALSE;
6543             if (left->op_private & OPpPAD_STATE) {
6544                 /* All single variable list context state assignments, hence
6545                    state ($a) = ...
6546                    (state $a) = ...
6547                    state @a = ...
6548                    state (@a) = ...
6549                    (state @a) = ...
6550                    state %a = ...
6551                    state (%a) = ...
6552                    (state %a) = ...
6553                 */
6554                 yyerror(no_list_state);
6555             }
6556         }
6557
6558         if (maybe_common_vars) {
6559                 /* The peephole optimizer will do the full check and pos-
6560                    sibly turn this off.  */
6561                 o->op_private |= OPpASSIGN_COMMON;
6562         }
6563
6564         if (right && right->op_type == OP_SPLIT
6565          && !(right->op_flags & OPf_STACKED)) {
6566             OP* tmpop = ((LISTOP*)right)->op_first;
6567             PMOP * const pm = (PMOP*)tmpop;
6568             assert (tmpop && (tmpop->op_type == OP_PUSHRE));
6569             if (
6570 #ifdef USE_ITHREADS
6571                     !pm->op_pmreplrootu.op_pmtargetoff
6572 #else
6573                     !pm->op_pmreplrootu.op_pmtargetgv
6574 #endif
6575                  && !pm->op_targ
6576                 ) {
6577                     if (!(left->op_private & OPpLVAL_INTRO) &&
6578                         ( (left->op_type == OP_RV2AV &&
6579                           (tmpop=((UNOP*)left)->op_first)->op_type==OP_GV)
6580                         || left->op_type == OP_PADAV )
6581                         ) {
6582                         if (tmpop != (OP *)pm) {
6583 #ifdef USE_ITHREADS
6584                           pm->op_pmreplrootu.op_pmtargetoff
6585                             = cPADOPx(tmpop)->op_padix;
6586                           cPADOPx(tmpop)->op_padix = 0; /* steal it */
6587 #else
6588                           pm->op_pmreplrootu.op_pmtargetgv
6589                             = MUTABLE_GV(cSVOPx(tmpop)->op_sv);
6590                           cSVOPx(tmpop)->op_sv = NULL;  /* steal it */
6591 #endif
6592                           right->op_private |=
6593                             left->op_private & OPpOUR_INTRO;
6594                         }
6595                         else {
6596                             pm->op_targ = left->op_targ;
6597                             left->op_targ = 0; /* filch it */
6598                         }
6599                       detach_split:
6600                         tmpop = cUNOPo->op_first;       /* to list (nulled) */
6601                         tmpop = ((UNOP*)tmpop)->op_first; /* to pushmark */
6602                         /* detach rest of siblings from o subtree,
6603                          * and free subtree */
6604                         op_sibling_splice(cUNOPo->op_first, tmpop, -1, NULL);
6605                         op_free(o);                     /* blow off assign */
6606                         right->op_flags &= ~OPf_WANT;
6607                                 /* "I don't know and I don't care." */
6608                         return right;
6609                     }
6610                     else if (left->op_type == OP_RV2AV
6611                           || left->op_type == OP_PADAV)
6612                     {
6613                         /* Detach the array.  */
6614 #ifdef DEBUGGING
6615                         OP * const ary =
6616 #endif
6617                         op_sibling_splice(cBINOPo->op_last,
6618                                           cUNOPx(cBINOPo->op_last)
6619                                                 ->op_first, 1, NULL);
6620                         assert(ary == left);
6621                         /* Attach it to the split.  */
6622                         op_sibling_splice(right, cLISTOPx(right)->op_last,
6623                                           0, left);
6624                         right->op_flags |= OPf_STACKED;
6625                         /* Detach split and expunge aassign as above.  */
6626                         goto detach_split;
6627                     }
6628                     else if (PL_modcount < RETURN_UNLIMITED_NUMBER &&
6629                             ((LISTOP*)right)->op_last->op_type == OP_CONST)
6630                     {
6631                         SV ** const svp =
6632                             &((SVOP*)((LISTOP*)right)->op_last)->op_sv;
6633                         SV * const sv = *svp;
6634                         if (SvIOK(sv) && SvIVX(sv) == 0)
6635                         {
6636                           if (right->op_private & OPpSPLIT_IMPLIM) {
6637                             /* our own SV, created in ck_split */
6638                             SvREADONLY_off(sv);
6639                             sv_setiv(sv, PL_modcount+1);
6640                           }
6641                           else {
6642                             /* SV may belong to someone else */
6643                             SvREFCNT_dec(sv);
6644                             *svp = newSViv(PL_modcount+1);
6645                           }
6646                         }
6647                     }
6648             }
6649         }
6650         return o;
6651     }
6652     if (assign_type == ASSIGN_REF)
6653         return newBINOP(OP_REFASSIGN, flags, scalar(right), left);
6654     if (!right)
6655         right = newOP(OP_UNDEF, 0);
6656     if (right->op_type == OP_READLINE) {
6657         right->op_flags |= OPf_STACKED;
6658         return newBINOP(OP_NULL, flags, op_lvalue(scalar(left), OP_SASSIGN),
6659                 scalar(right));
6660     }
6661     else {
6662         o = newBINOP(OP_SASSIGN, flags,
6663             scalar(right), op_lvalue(scalar(left), OP_SASSIGN) );
6664     }
6665     return o;
6666 }
6667
6668 /*
6669 =for apidoc Am|OP *|newSTATEOP|I32 flags|char *label|OP *o
6670
6671 Constructs a state op (COP).  The state op is normally a C<nextstate> op,
6672 but will be a C<dbstate> op if debugging is enabled for currently-compiled
6673 code.  The state op is populated from C<PL_curcop> (or C<PL_compiling>).
6674 If I<label> is non-null, it supplies the name of a label to attach to
6675 the state op; this function takes ownership of the memory pointed at by
6676 I<label>, and will free it.  I<flags> gives the eight bits of C<op_flags>
6677 for the state op.
6678
6679 If I<o> is null, the state op is returned.  Otherwise the state op is
6680 combined with I<o> into a C<lineseq> list op, which is returned.  I<o>
6681 is consumed by this function and becomes part of the returned op tree.
6682
6683 =cut
6684 */
6685
6686 OP *
6687 Perl_newSTATEOP(pTHX_ I32 flags, char *label, OP *o)
6688 {
6689     dVAR;
6690     const U32 seq = intro_my();
6691     const U32 utf8 = flags & SVf_UTF8;
6692     COP *cop;
6693
6694     PL_parser->parsed_sub = 0;
6695
6696     flags &= ~SVf_UTF8;
6697
6698     NewOp(1101, cop, 1, COP);
6699     if (PERLDB_LINE && CopLINE(PL_curcop) && PL_curstash != PL_debstash) {
6700         CHANGE_TYPE(cop, OP_DBSTATE);
6701     }
6702     else {
6703         CHANGE_TYPE(cop, OP_NEXTSTATE);
6704     }
6705     cop->op_flags = (U8)flags;
6706     CopHINTS_set(cop, PL_hints);
6707 #ifdef VMS
6708     if (VMSISH_HUSHED) cop->op_private |= OPpHUSH_VMSISH;
6709 #endif
6710     cop->op_next = (OP*)cop;
6711
6712     cop->cop_seq = seq;
6713     cop->cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
6714     CopHINTHASH_set(cop, cophh_copy(CopHINTHASH_get(PL_curcop)));
6715     if (label) {
6716         Perl_cop_store_label(aTHX_ cop, label, strlen(label), utf8);
6717
6718         PL_hints |= HINT_BLOCK_SCOPE;
6719         /* It seems that we need to defer freeing this pointer, as other parts
6720            of the grammar end up wanting to copy it after this op has been
6721            created. */
6722         SAVEFREEPV(label);
6723     }
6724
6725     if (PL_parser->preambling != NOLINE) {
6726         CopLINE_set(cop, PL_parser->preambling);
6727         PL_parser->copline = NOLINE;
6728     }
6729     else if (PL_parser->copline == NOLINE)
6730         CopLINE_set(cop, CopLINE(PL_curcop));
6731     else {
6732         CopLINE_set(cop, PL_parser->copline);
6733         PL_parser->copline = NOLINE;
6734     }
6735 #ifdef USE_ITHREADS
6736     CopFILE_set(cop, CopFILE(PL_curcop));       /* XXX share in a pvtable? */
6737 #else
6738     CopFILEGV_set(cop, CopFILEGV(PL_curcop));
6739 #endif
6740     CopSTASH_set(cop, PL_curstash);
6741
6742     if (cop->op_type == OP_DBSTATE) {
6743         /* this line can have a breakpoint - store the cop in IV */
6744         AV *av = CopFILEAVx(PL_curcop);
6745         if (av) {
6746             SV * const * const svp = av_fetch(av, CopLINE(cop), FALSE);
6747             if (svp && *svp != &PL_sv_undef ) {
6748                 (void)SvIOK_on(*svp);
6749                 SvIV_set(*svp, PTR2IV(cop));
6750             }
6751         }
6752     }
6753
6754     if (flags & OPf_SPECIAL)
6755         op_null((OP*)cop);
6756     return op_prepend_elem(OP_LINESEQ, (OP*)cop, o);
6757 }
6758
6759 /*
6760 =for apidoc Am|OP *|newLOGOP|I32 type|I32 flags|OP *first|OP *other
6761
6762 Constructs, checks, and returns a logical (flow control) op.  I<type>
6763 is the opcode.  I<flags> gives the eight bits of C<op_flags>, except
6764 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
6765 the eight bits of C<op_private>, except that the bit with value 1 is
6766 automatically set.  I<first> supplies the expression controlling the
6767 flow, and I<other> supplies the side (alternate) chain of ops; they are
6768 consumed by this function and become part of the constructed op tree.
6769
6770 =cut
6771 */
6772
6773 OP *
6774 Perl_newLOGOP(pTHX_ I32 type, I32 flags, OP *first, OP *other)
6775 {
6776     PERL_ARGS_ASSERT_NEWLOGOP;
6777
6778     return new_logop(type, flags, &first, &other);
6779 }
6780
6781 STATIC OP *
6782 S_search_const(pTHX_ OP *o)
6783 {
6784     PERL_ARGS_ASSERT_SEARCH_CONST;
6785
6786     switch (o->op_type) {
6787         case OP_CONST:
6788             return o;
6789         case OP_NULL:
6790             if (o->op_flags & OPf_KIDS)
6791                 return search_const(cUNOPo->op_first);
6792             break;
6793         case OP_LEAVE:
6794         case OP_SCOPE:
6795         case OP_LINESEQ:
6796         {
6797             OP *kid;
6798             if (!(o->op_flags & OPf_KIDS))
6799                 return NULL;
6800             kid = cLISTOPo->op_first;
6801             do {
6802                 switch (kid->op_type) {
6803                     case OP_ENTER:
6804                     case OP_NULL:
6805                     case OP_NEXTSTATE:
6806                         kid = OpSIBLING(kid);
6807                         break;
6808                     default:
6809                         if (kid != cLISTOPo->op_last)
6810                             return NULL;
6811                         goto last;
6812                 }
6813             } while (kid);
6814             if (!kid)
6815                 kid = cLISTOPo->op_last;
6816           last:
6817             return search_const(kid);
6818         }
6819     }
6820
6821     return NULL;
6822 }
6823
6824 STATIC OP *
6825 S_new_logop(pTHX_ I32 type, I32 flags, OP** firstp, OP** otherp)
6826 {
6827     dVAR;
6828     LOGOP *logop;
6829     OP *o;
6830     OP *first;
6831     OP *other;
6832     OP *cstop = NULL;
6833     int prepend_not = 0;
6834
6835     PERL_ARGS_ASSERT_NEW_LOGOP;
6836
6837     first = *firstp;
6838     other = *otherp;
6839
6840     /* [perl #59802]: Warn about things like "return $a or $b", which
6841        is parsed as "(return $a) or $b" rather than "return ($a or
6842        $b)".  NB: This also applies to xor, which is why we do it
6843        here.
6844      */
6845     switch (first->op_type) {
6846     case OP_NEXT:
6847     case OP_LAST:
6848     case OP_REDO:
6849         /* XXX: Perhaps we should emit a stronger warning for these.
6850            Even with the high-precedence operator they don't seem to do
6851            anything sensible.
6852
6853            But until we do, fall through here.
6854          */
6855     case OP_RETURN:
6856     case OP_EXIT:
6857     case OP_DIE:
6858     case OP_GOTO:
6859         /* XXX: Currently we allow people to "shoot themselves in the
6860            foot" by explicitly writing "(return $a) or $b".
6861
6862            Warn unless we are looking at the result from folding or if
6863            the programmer explicitly grouped the operators like this.
6864            The former can occur with e.g.
6865
6866                 use constant FEATURE => ( $] >= ... );
6867                 sub { not FEATURE and return or do_stuff(); }
6868          */
6869         if (!first->op_folded && !(first->op_flags & OPf_PARENS))
6870             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
6871                            "Possible precedence issue with control flow operator");
6872         /* XXX: Should we optimze this to "return $a;" (i.e. remove
6873            the "or $b" part)?
6874         */
6875         break;
6876     }
6877
6878     if (type == OP_XOR)         /* Not short circuit, but here by precedence. */
6879         return newBINOP(type, flags, scalar(first), scalar(other));
6880
6881     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOGOP
6882         || type == OP_CUSTOM);
6883
6884     scalarboolean(first);
6885     /* optimize AND and OR ops that have NOTs as children */
6886     if (first->op_type == OP_NOT
6887         && (first->op_flags & OPf_KIDS)
6888         && ((first->op_flags & OPf_SPECIAL) /* unless ($x) { } */
6889             || (other->op_type == OP_NOT))  /* if (!$x && !$y) { } */
6890         ) {
6891         if (type == OP_AND || type == OP_OR) {
6892             if (type == OP_AND)
6893                 type = OP_OR;
6894             else
6895                 type = OP_AND;
6896             op_null(first);
6897             if (other->op_type == OP_NOT) { /* !a AND|OR !b => !(a OR|AND b) */
6898                 op_null(other);
6899                 prepend_not = 1; /* prepend a NOT op later */
6900             }
6901         }
6902     }
6903     /* search for a constant op that could let us fold the test */
6904     if ((cstop = search_const(first))) {
6905         if (cstop->op_private & OPpCONST_STRICT)
6906             no_bareword_allowed(cstop);
6907         else if ((cstop->op_private & OPpCONST_BARE))
6908                 Perl_ck_warner(aTHX_ packWARN(WARN_BAREWORD), "Bareword found in conditional");
6909         if ((type == OP_AND &&  SvTRUE(((SVOP*)cstop)->op_sv)) ||
6910             (type == OP_OR  && !SvTRUE(((SVOP*)cstop)->op_sv)) ||
6911             (type == OP_DOR && !SvOK(((SVOP*)cstop)->op_sv))) {
6912             *firstp = NULL;
6913             if (other->op_type == OP_CONST)
6914                 other->op_private |= OPpCONST_SHORTCIRCUIT;
6915             op_free(first);
6916             if (other->op_type == OP_LEAVE)
6917                 other = newUNOP(OP_NULL, OPf_SPECIAL, other);
6918             else if (other->op_type == OP_MATCH
6919                   || other->op_type == OP_SUBST
6920                   || other->op_type == OP_TRANSR
6921                   || other->op_type == OP_TRANS)
6922                 /* Mark the op as being unbindable with =~ */
6923                 other->op_flags |= OPf_SPECIAL;
6924
6925             other->op_folded = 1;
6926             return other;
6927         }
6928         else {
6929             /* check for C<my $x if 0>, or C<my($x,$y) if 0> */
6930             const OP *o2 = other;
6931             if ( ! (o2->op_type == OP_LIST
6932                     && (( o2 = cUNOPx(o2)->op_first))
6933                     && o2->op_type == OP_PUSHMARK
6934                     && (( o2 = OpSIBLING(o2))) )
6935             )
6936                 o2 = other;
6937             if ((o2->op_type == OP_PADSV || o2->op_type == OP_PADAV
6938                         || o2->op_type == OP_PADHV)
6939                 && o2->op_private & OPpLVAL_INTRO
6940                 && !(o2->op_private & OPpPAD_STATE))
6941             {
6942                 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED),
6943                                  "Deprecated use of my() in false conditional");
6944             }
6945
6946             *otherp = NULL;
6947             if (cstop->op_type == OP_CONST)
6948                 cstop->op_private |= OPpCONST_SHORTCIRCUIT;
6949                 op_free(other);
6950             return first;
6951         }
6952     }
6953     else if ((first->op_flags & OPf_KIDS) && type != OP_DOR
6954         && ckWARN(WARN_MISC)) /* [#24076] Don't warn for <FH> err FOO. */
6955     {
6956         const OP * const k1 = ((UNOP*)first)->op_first;
6957         const OP * const k2 = OpSIBLING(k1);
6958         OPCODE warnop = 0;
6959         switch (first->op_type)
6960         {
6961         case OP_NULL:
6962             if (k2 && k2->op_type == OP_READLINE
6963                   && (k2->op_flags & OPf_STACKED)
6964                   && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
6965             {
6966                 warnop = k2->op_type;
6967             }
6968             break;
6969
6970         case OP_SASSIGN:
6971             if (k1->op_type == OP_READDIR
6972                   || k1->op_type == OP_GLOB
6973                   || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
6974                  || k1->op_type == OP_EACH
6975                  || k1->op_type == OP_AEACH)
6976             {
6977                 warnop = ((k1->op_type == OP_NULL)
6978                           ? (OPCODE)k1->op_targ : k1->op_type);
6979             }
6980             break;
6981         }
6982         if (warnop) {
6983             const line_t oldline = CopLINE(PL_curcop);
6984             /* This ensures that warnings are reported at the first line
6985                of the construction, not the last.  */
6986             CopLINE_set(PL_curcop, PL_parser->copline);
6987             Perl_warner(aTHX_ packWARN(WARN_MISC),
6988                  "Value of %s%s can be \"0\"; test with defined()",
6989                  PL_op_desc[warnop],
6990                  ((warnop == OP_READLINE || warnop == OP_GLOB)
6991                   ? " construct" : "() operator"));
6992             CopLINE_set(PL_curcop, oldline);
6993         }
6994     }
6995
6996     if (!other)
6997         return first;
6998
6999     if (type == OP_ANDASSIGN || type == OP_ORASSIGN || type == OP_DORASSIGN)
7000         other->op_private |= OPpASSIGN_BACKWARDS;  /* other is an OP_SASSIGN */
7001
7002     logop = S_alloc_LOGOP(aTHX_ type, first, LINKLIST(other));
7003     logop->op_flags |= (U8)flags;
7004     logop->op_private = (U8)(1 | (flags >> 8));
7005
7006     /* establish postfix order */
7007     logop->op_next = LINKLIST(first);
7008     first->op_next = (OP*)logop;
7009     assert(!OpHAS_SIBLING(first));
7010     op_sibling_splice((OP*)logop, first, 0, other);
7011
7012     CHECKOP(type,logop);
7013
7014     o = newUNOP(prepend_not ? OP_NOT : OP_NULL,
7015                 PL_opargs[type] & OA_RETSCALAR ? OPf_WANT_SCALAR : 0,
7016                 (OP*)logop);
7017     other->op_next = o;
7018
7019     return o;
7020 }
7021
7022 /*
7023 =for apidoc Am|OP *|newCONDOP|I32 flags|OP *first|OP *trueop|OP *falseop
7024
7025 Constructs, checks, and returns a conditional-expression (C<cond_expr>)
7026 op.  I<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
7027 will be set automatically, and, shifted up eight bits, the eight bits of
7028 C<op_private>, except that the bit with value 1 is automatically set.
7029 I<first> supplies the expression selecting between the two branches,
7030 and I<trueop> and I<falseop> supply the branches; they are consumed by
7031 this function and become part of the constructed op tree.
7032
7033 =cut
7034 */
7035
7036 OP *
7037 Perl_newCONDOP(pTHX_ I32 flags, OP *first, OP *trueop, OP *falseop)
7038 {
7039     dVAR;
7040     LOGOP *logop;
7041     OP *start;
7042     OP *o;
7043     OP *cstop;
7044
7045     PERL_ARGS_ASSERT_NEWCONDOP;
7046
7047     if (!falseop)
7048         return newLOGOP(OP_AND, 0, first, trueop);
7049     if (!trueop)
7050         return newLOGOP(OP_OR, 0, first, falseop);
7051
7052     scalarboolean(first);
7053     if ((cstop = search_const(first))) {
7054         /* Left or right arm of the conditional?  */
7055         const bool left = SvTRUE(((SVOP*)cstop)->op_sv);
7056         OP *live = left ? trueop : falseop;
7057         OP *const dead = left ? falseop : trueop;
7058         if (cstop->op_private & OPpCONST_BARE &&
7059             cstop->op_private & OPpCONST_STRICT) {
7060             no_bareword_allowed(cstop);
7061         }
7062         op_free(first);
7063         op_free(dead);
7064         if (live->op_type == OP_LEAVE)
7065             live = newUNOP(OP_NULL, OPf_SPECIAL, live);
7066         else if (live->op_type == OP_MATCH || live->op_type == OP_SUBST
7067               || live->op_type == OP_TRANS || live->op_type == OP_TRANSR)
7068             /* Mark the op as being unbindable with =~ */
7069             live->op_flags |= OPf_SPECIAL;
7070         live->op_folded = 1;
7071         return live;
7072     }
7073     logop = S_alloc_LOGOP(aTHX_ OP_COND_EXPR, first, LINKLIST(trueop));
7074     logop->op_flags |= (U8)flags;
7075     logop->op_private = (U8)(1 | (flags >> 8));
7076     logop->op_next = LINKLIST(falseop);
7077
7078     CHECKOP(OP_COND_EXPR, /* that's logop->op_type */
7079             logop);
7080
7081     /* establish postfix order */
7082     start = LINKLIST(first);
7083     first->op_next = (OP*)logop;
7084
7085     /* make first, trueop, falseop siblings */
7086     op_sibling_splice((OP*)logop, first,  0, trueop);
7087     op_sibling_splice((OP*)logop, trueop, 0, falseop);
7088
7089     o = newUNOP(OP_NULL, 0, (OP*)logop);
7090
7091     trueop->op_next = falseop->op_next = o;
7092
7093     o->op_next = start;
7094     return o;
7095 }
7096
7097 /*
7098 =for apidoc Am|OP *|newRANGE|I32 flags|OP *left|OP *right
7099
7100 Constructs and returns a C<range> op, with subordinate C<flip> and
7101 C<flop> ops.  I<flags> gives the eight bits of C<op_flags> for the
7102 C<flip> op and, shifted up eight bits, the eight bits of C<op_private>
7103 for both the C<flip> and C<range> ops, except that the bit with value
7104 1 is automatically set.  I<left> and I<right> supply the expressions
7105 controlling the endpoints of the range; they are consumed by this function
7106 and become part of the constructed op tree.
7107
7108 =cut
7109 */
7110
7111 OP *
7112 Perl_newRANGE(pTHX_ I32 flags, OP *left, OP *right)
7113 {
7114     LOGOP *range;
7115     OP *flip;
7116     OP *flop;
7117     OP *leftstart;
7118     OP *o;
7119
7120     PERL_ARGS_ASSERT_NEWRANGE;
7121
7122     range = S_alloc_LOGOP(aTHX_ OP_RANGE, left, LINKLIST(right));
7123     range->op_flags = OPf_KIDS;
7124     leftstart = LINKLIST(left);
7125     range->op_private = (U8)(1 | (flags >> 8));
7126
7127     /* make left and right siblings */
7128     op_sibling_splice((OP*)range, left, 0, right);
7129
7130     range->op_next = (OP*)range;
7131     flip = newUNOP(OP_FLIP, flags, (OP*)range);
7132     flop = newUNOP(OP_FLOP, 0, flip);
7133     o = newUNOP(OP_NULL, 0, flop);
7134     LINKLIST(flop);
7135     range->op_next = leftstart;
7136
7137     left->op_next = flip;
7138     right->op_next = flop;
7139
7140     range->op_targ =
7141         pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);
7142     sv_upgrade(PAD_SV(range->op_targ), SVt_PVNV);
7143     flip->op_targ =
7144         pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);;
7145     sv_upgrade(PAD_SV(flip->op_targ), SVt_PVNV);
7146     SvPADTMP_on(PAD_SV(flip->op_targ));
7147
7148     flip->op_private =  left->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
7149     flop->op_private = right->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
7150
7151     /* check barewords before they might be optimized aways */
7152     if (flip->op_private && cSVOPx(left)->op_private & OPpCONST_STRICT)
7153         no_bareword_allowed(left);
7154     if (flop->op_private && cSVOPx(right)->op_private & OPpCONST_STRICT)
7155         no_bareword_allowed(right);
7156
7157     flip->op_next = o;
7158     if (!flip->op_private || !flop->op_private)
7159         LINKLIST(o);            /* blow off optimizer unless constant */
7160
7161     return o;
7162 }
7163
7164 /*
7165 =for apidoc Am|OP *|newLOOPOP|I32 flags|I32 debuggable|OP *expr|OP *block
7166
7167 Constructs, checks, and returns an op tree expressing a loop.  This is
7168 only a loop in the control flow through the op tree; it does not have
7169 the heavyweight loop structure that allows exiting the loop by C<last>
7170 and suchlike.  I<flags> gives the eight bits of C<op_flags> for the
7171 top-level op, except that some bits will be set automatically as required.
7172 I<expr> supplies the expression controlling loop iteration, and I<block>
7173 supplies the body of the loop; they are consumed by this function and
7174 become part of the constructed op tree.  I<debuggable> is currently
7175 unused and should always be 1.
7176
7177 =cut
7178 */
7179
7180 OP *
7181 Perl_newLOOPOP(pTHX_ I32 flags, I32 debuggable, OP *expr, OP *block)
7182 {
7183     OP* listop;
7184     OP* o;
7185     const bool once = block && block->op_flags & OPf_SPECIAL &&
7186                       block->op_type == OP_NULL;
7187
7188     PERL_UNUSED_ARG(debuggable);
7189
7190     if (expr) {
7191         if (once && (
7192               (expr->op_type == OP_CONST && !SvTRUE(((SVOP*)expr)->op_sv))
7193            || (  expr->op_type == OP_NOT
7194               && cUNOPx(expr)->op_first->op_type == OP_CONST
7195               && SvTRUE(cSVOPx_sv(cUNOPx(expr)->op_first))
7196               )
7197            ))
7198             /* Return the block now, so that S_new_logop does not try to
7199                fold it away. */
7200             return block;       /* do {} while 0 does once */
7201         if (expr->op_type == OP_READLINE
7202             || expr->op_type == OP_READDIR
7203             || expr->op_type == OP_GLOB
7204             || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
7205             || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
7206             expr = newUNOP(OP_DEFINED, 0,
7207                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
7208         } else if (expr->op_flags & OPf_KIDS) {
7209             const OP * const k1 = ((UNOP*)expr)->op_first;
7210             const OP * const k2 = k1 ? OpSIBLING(k1) : NULL;
7211             switch (expr->op_type) {
7212               case OP_NULL:
7213                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
7214                       && (k2->op_flags & OPf_STACKED)
7215                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
7216                     expr = newUNOP(OP_DEFINED, 0, expr);
7217                 break;
7218
7219               case OP_SASSIGN:
7220                 if (k1 && (k1->op_type == OP_READDIR
7221                       || k1->op_type == OP_GLOB
7222                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
7223                      || k1->op_type == OP_EACH
7224                      || k1->op_type == OP_AEACH))
7225                     expr = newUNOP(OP_DEFINED, 0, expr);
7226                 break;
7227             }
7228         }
7229     }
7230
7231     /* if block is null, the next op_append_elem() would put UNSTACK, a scalar
7232      * op, in listop. This is wrong. [perl #27024] */
7233     if (!block)
7234         block = newOP(OP_NULL, 0);
7235     listop = op_append_elem(OP_LINESEQ, block, newOP(OP_UNSTACK, 0));
7236     o = new_logop(OP_AND, 0, &expr, &listop);
7237
7238     if (once) {
7239         ASSUME(listop);
7240     }
7241
7242     if (listop)
7243         ((LISTOP*)listop)->op_last->op_next = LINKLIST(o);
7244
7245     if (once && o != listop)
7246     {
7247         assert(cUNOPo->op_first->op_type == OP_AND
7248             || cUNOPo->op_first->op_type == OP_OR);
7249         o->op_next = ((LOGOP*)cUNOPo->op_first)->op_other;
7250     }
7251
7252     if (o == listop)
7253         o = newUNOP(OP_NULL, 0, o);     /* or do {} while 1 loses outer block */
7254
7255     o->op_flags |= flags;
7256     o = op_scope(o);
7257     o->op_flags |= OPf_SPECIAL; /* suppress POPBLOCK curpm restoration*/
7258     return o;
7259 }
7260
7261 /*
7262 =for apidoc Am|OP *|newWHILEOP|I32 flags|I32 debuggable|LOOP *loop|OP *expr|OP *block|OP *cont|I32 has_my
7263
7264 Constructs, checks, and returns an op tree expressing a C<while> loop.
7265 This is a heavyweight loop, with structure that allows exiting the loop
7266 by C<last> and suchlike.
7267
7268 I<loop> is an optional preconstructed C<enterloop> op to use in the
7269 loop; if it is null then a suitable op will be constructed automatically.
7270 I<expr> supplies the loop's controlling expression.  I<block> supplies the
7271 main body of the loop, and I<cont> optionally supplies a C<continue> block
7272 that operates as a second half of the body.  All of these optree inputs
7273 are consumed by this function and become part of the constructed op tree.
7274
7275 I<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
7276 op and, shifted up eight bits, the eight bits of C<op_private> for
7277 the C<leaveloop> op, except that (in both cases) some bits will be set
7278 automatically.  I<debuggable> is currently unused and should always be 1.
7279 I<has_my> can be supplied as true to force the
7280 loop body to be enclosed in its own scope.
7281
7282 =cut
7283 */
7284
7285 OP *
7286 Perl_newWHILEOP(pTHX_ I32 flags, I32 debuggable, LOOP *loop,
7287         OP *expr, OP *block, OP *cont, I32 has_my)
7288 {
7289     dVAR;
7290     OP *redo;
7291     OP *next = NULL;
7292     OP *listop;
7293     OP *o;
7294     U8 loopflags = 0;
7295
7296     PERL_UNUSED_ARG(debuggable);
7297
7298     if (expr) {
7299         if (expr->op_type == OP_READLINE
7300          || expr->op_type == OP_READDIR
7301          || expr->op_type == OP_GLOB
7302          || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
7303                      || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
7304             expr = newUNOP(OP_DEFINED, 0,
7305                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
7306         } else if (expr->op_flags & OPf_KIDS) {
7307             const OP * const k1 = ((UNOP*)expr)->op_first;
7308             const OP * const k2 = (k1) ? OpSIBLING(k1) : NULL;
7309             switch (expr->op_type) {
7310               case OP_NULL:
7311                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
7312                       && (k2->op_flags & OPf_STACKED)
7313                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
7314                     expr = newUNOP(OP_DEFINED, 0, expr);
7315                 break;
7316
7317               case OP_SASSIGN:
7318                 if (k1 && (k1->op_type == OP_READDIR
7319                       || k1->op_type == OP_GLOB
7320                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
7321                      || k1->op_type == OP_EACH
7322                      || k1->op_type == OP_AEACH))
7323                     expr = newUNOP(OP_DEFINED, 0, expr);
7324                 break;
7325             }
7326         }
7327     }
7328
7329     if (!block)
7330         block = newOP(OP_NULL, 0);
7331     else if (cont || has_my) {
7332         block = op_scope(block);
7333     }
7334
7335     if (cont) {
7336         next = LINKLIST(cont);
7337     }
7338     if (expr) {
7339         OP * const unstack = newOP(OP_UNSTACK, 0);
7340         if (!next)
7341             next = unstack;
7342         cont = op_append_elem(OP_LINESEQ, cont, unstack);
7343     }
7344
7345     assert(block);
7346     listop = op_append_list(OP_LINESEQ, block, cont);
7347     assert(listop);
7348     redo = LINKLIST(listop);
7349
7350     if (expr) {
7351         scalar(listop);
7352         o = new_logop(OP_AND, 0, &expr, &listop);
7353         if (o == expr && o->op_type == OP_CONST && !SvTRUE(cSVOPo->op_sv)) {
7354             op_free((OP*)loop);
7355             return expr;                /* listop already freed by new_logop */
7356         }
7357         if (listop)
7358             ((LISTOP*)listop)->op_last->op_next =
7359                 (o == listop ? redo : LINKLIST(o));
7360     }
7361     else
7362         o = listop;
7363
7364     if (!loop) {
7365         NewOp(1101,loop,1,LOOP);
7366         CHANGE_TYPE(loop, OP_ENTERLOOP);
7367         loop->op_private = 0;
7368         loop->op_next = (OP*)loop;
7369     }
7370
7371     o = newBINOP(OP_LEAVELOOP, 0, (OP*)loop, o);
7372
7373     loop->op_redoop = redo;
7374     loop->op_lastop = o;
7375     o->op_private |= loopflags;
7376
7377     if (next)
7378         loop->op_nextop = next;
7379     else
7380         loop->op_nextop = o;
7381
7382     o->op_flags |= flags;
7383     o->op_private |= (flags >> 8);
7384     return o;
7385 }
7386
7387 /*
7388 =for apidoc Am|OP *|newFOROP|I32 flags|OP *sv|OP *expr|OP *block|OP *cont
7389
7390 Constructs, checks, and returns an op tree expressing a C<foreach>
7391 loop (iteration through a list of values).  This is a heavyweight loop,
7392 with structure that allows exiting the loop by C<last> and suchlike.
7393
7394 I<sv> optionally supplies the variable that will be aliased to each
7395 item in turn; if null, it defaults to C<$_> (either lexical or global).
7396 I<expr> supplies the list of values to iterate over.  I<block> supplies
7397 the main body of the loop, and I<cont> optionally supplies a C<continue>
7398 block that operates as a second half of the body.  All of these optree
7399 inputs are consumed by this function and become part of the constructed
7400 op tree.
7401
7402 I<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
7403 op and, shifted up eight bits, the eight bits of C<op_private> for
7404 the C<leaveloop> op, except that (in both cases) some bits will be set
7405 automatically.
7406
7407 =cut
7408 */
7409
7410 OP *
7411 Perl_newFOROP(pTHX_ I32 flags, OP *sv, OP *expr, OP *block, OP *cont)
7412 {
7413     dVAR;
7414     LOOP *loop;
7415     OP *wop;
7416     PADOFFSET padoff = 0;
7417     I32 iterflags = 0;
7418     I32 iterpflags = 0;
7419
7420     PERL_ARGS_ASSERT_NEWFOROP;
7421
7422     if (sv) {
7423         if (sv->op_type == OP_RV2SV) {  /* symbol table variable */
7424             iterpflags = sv->op_private & OPpOUR_INTRO; /* for our $x () */
7425             CHANGE_TYPE(sv, OP_RV2GV);
7426
7427             /* The op_type check is needed to prevent a possible segfault
7428              * if the loop variable is undeclared and 'strict vars' is in
7429              * effect. This is illegal but is nonetheless parsed, so we
7430              * may reach this point with an OP_CONST where we're expecting
7431              * an OP_GV.
7432              */
7433             if (cUNOPx(sv)->op_first->op_type == OP_GV
7434              && cGVOPx_gv(cUNOPx(sv)->op_first) == PL_defgv)
7435                 iterpflags |= OPpITER_DEF;
7436         }
7437         else if (sv->op_type == OP_PADSV) { /* private variable */
7438             iterpflags = sv->op_private & OPpLVAL_INTRO; /* for my $x () */
7439             padoff = sv->op_targ;
7440             sv->op_targ = 0;
7441             op_free(sv);
7442             sv = NULL;
7443             PAD_COMPNAME_GEN_set(padoff, PERL_INT_MAX);
7444         }
7445         else if (sv->op_type == OP_NULL && sv->op_targ == OP_SREFGEN)
7446             NOOP;
7447         else
7448             Perl_croak(aTHX_ "Can't use %s for loop variable", PL_op_desc[sv->op_type]);
7449         if (padoff) {
7450             PADNAME * const pn = PAD_COMPNAME(padoff);
7451             const char * const name = PadnamePV(pn);
7452
7453             if (PadnameLEN(pn) == 2 && name[0] == '$' && name[1] == '_')
7454                 iterpflags |= OPpITER_DEF;
7455         }
7456     }
7457     else {
7458         const PADOFFSET offset = pad_findmy_pvs("$_", 0);
7459         if (offset == NOT_IN_PAD || PAD_COMPNAME_FLAGS_isOUR(offset)) {
7460             sv = newGVOP(OP_GV, 0, PL_defgv);
7461         }
7462         else {
7463             padoff = offset;
7464         }
7465         iterpflags |= OPpITER_DEF;
7466     }
7467
7468     if (expr->op_type == OP_RV2AV || expr->op_type == OP_PADAV) {
7469         expr = op_lvalue(force_list(scalar(ref(expr, OP_ITER)), 1), OP_GREPSTART);
7470         iterflags |= OPf_STACKED;
7471     }
7472     else if (expr->op_type == OP_NULL &&
7473              (expr->op_flags & OPf_KIDS) &&
7474              ((BINOP*)expr)->op_first->op_type == OP_FLOP)
7475     {
7476         /* Basically turn for($x..$y) into the same as for($x,$y), but we
7477          * set the STACKED flag to indicate that these values are to be
7478          * treated as min/max values by 'pp_enteriter'.
7479          */
7480         const UNOP* const flip = (UNOP*)((UNOP*)((BINOP*)expr)->op_first)->op_first;
7481         LOGOP* const range = (LOGOP*) flip->op_first;
7482         OP* const left  = range->op_first;
7483         OP* const right = OpSIBLING(left);
7484         LISTOP* listop;
7485
7486         range->op_flags &= ~OPf_KIDS;
7487         /* detach range's children */
7488         op_sibling_splice((OP*)range, NULL, -1, NULL);
7489
7490         listop = (LISTOP*)newLISTOP(OP_LIST, 0, left, right);
7491         listop->op_first->op_next = range->op_next;
7492         left->op_next = range->op_other;
7493         right->op_next = (OP*)listop;
7494         listop->op_next = listop->op_first;
7495
7496         op_free(expr);
7497         expr = (OP*)(listop);
7498         op_null(expr);
7499         iterflags |= OPf_STACKED;
7500     }
7501     else {
7502         expr = op_lvalue(force_list(expr, 1), OP_GREPSTART);
7503     }
7504
7505     loop = (LOOP*)list(op_convert_list(OP_ENTERITER, iterflags,
7506                                op_append_elem(OP_LIST, expr, scalar(sv))));
7507     assert(!loop->op_next);
7508     /* for my  $x () sets OPpLVAL_INTRO;
7509      * for our $x () sets OPpOUR_INTRO */
7510     loop->op_private = (U8)iterpflags;
7511     if (loop->op_slabbed
7512      && DIFF(loop, OpSLOT(loop)->opslot_next)
7513          < SIZE_TO_PSIZE(sizeof(LOOP)))
7514     {
7515         LOOP *tmp;
7516         NewOp(1234,tmp,1,LOOP);
7517         Copy(loop,tmp,1,LISTOP);
7518 #ifdef PERL_OP_PARENT
7519         assert(loop->op_last->op_sibling == (OP*)loop);
7520         loop->op_last->op_sibling = (OP*)tmp; /*point back to new parent */
7521 #endif
7522         S_op_destroy(aTHX_ (OP*)loop);
7523         loop = tmp;
7524     }
7525     else if (!loop->op_slabbed)
7526     {
7527         loop = (LOOP*)PerlMemShared_realloc(loop, sizeof(LOOP));
7528 #ifdef PERL_OP_PARENT
7529         loop->op_last->op_sibling = (OP *)loop;
7530 #endif
7531     }
7532     loop->op_targ = padoff;
7533     wop = newWHILEOP(flags, 1, loop, newOP(OP_ITER, 0), block, cont, 0);
7534     return wop;
7535 }
7536
7537 /*
7538 =for apidoc Am|OP *|newLOOPEX|I32 type|OP *label
7539
7540 Constructs, checks, and returns a loop-exiting op (such as C<goto>
7541 or C<last>).  I<type> is the opcode.  I<label> supplies the parameter
7542 determining the target of the op; it is consumed by this function and
7543 becomes part of the constructed op tree.
7544
7545 =cut
7546 */
7547
7548 OP*
7549 Perl_newLOOPEX(pTHX_ I32 type, OP *label)
7550 {
7551     OP *o = NULL;
7552
7553     PERL_ARGS_ASSERT_NEWLOOPEX;
7554
7555     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
7556         || type == OP_CUSTOM);
7557
7558     if (type != OP_GOTO) {
7559         /* "last()" means "last" */
7560         if (label->op_type == OP_STUB && (label->op_flags & OPf_PARENS)) {
7561             o = newOP(type, OPf_SPECIAL);
7562         }
7563     }
7564     else {
7565         /* Check whether it's going to be a goto &function */
7566         if (label->op_type == OP_ENTERSUB
7567                 && !(label->op_flags & OPf_STACKED))
7568             label = newUNOP(OP_REFGEN, 0, op_lvalue(label, OP_REFGEN));
7569     }
7570
7571     /* Check for a constant argument */
7572     if (label->op_type == OP_CONST) {
7573             SV * const sv = ((SVOP *)label)->op_sv;
7574             STRLEN l;
7575             const char *s = SvPV_const(sv,l);
7576             if (l == strlen(s)) {
7577                 o = newPVOP(type,
7578                             SvUTF8(((SVOP*)label)->op_sv),
7579                             savesharedpv(
7580                                 SvPV_nolen_const(((SVOP*)label)->op_sv)));
7581             }
7582     }
7583     
7584     /* If we have already created an op, we do not need the label. */
7585     if (o)
7586                 op_free(label);
7587     else o = newUNOP(type, OPf_STACKED, label);
7588
7589     PL_hints |= HINT_BLOCK_SCOPE;
7590     return o;
7591 }
7592
7593 /* if the condition is a literal array or hash
7594    (or @{ ... } etc), make a reference to it.
7595  */
7596 STATIC OP *
7597 S_ref_array_or_hash(pTHX_ OP *cond)
7598 {
7599     if (cond
7600     && (cond->op_type == OP_RV2AV
7601     ||  cond->op_type == OP_PADAV
7602     ||  cond->op_type == OP_RV2HV
7603     ||  cond->op_type == OP_PADHV))
7604
7605         return newUNOP(OP_REFGEN, 0, op_lvalue(cond, OP_REFGEN));
7606
7607     else if(cond
7608     && (cond->op_type == OP_ASLICE
7609     ||  cond->op_type == OP_KVASLICE
7610     ||  cond->op_type == OP_HSLICE
7611     ||  cond->op_type == OP_KVHSLICE)) {
7612
7613         /* anonlist now needs a list from this op, was previously used in
7614          * scalar context */
7615         cond->op_flags |= ~(OPf_WANT_SCALAR | OPf_REF);
7616         cond->op_flags |= OPf_WANT_LIST;
7617
7618         return newANONLIST(op_lvalue(cond, OP_ANONLIST));
7619     }
7620
7621     else
7622         return cond;
7623 }
7624
7625 /* These construct the optree fragments representing given()
7626    and when() blocks.
7627
7628    entergiven and enterwhen are LOGOPs; the op_other pointer
7629    points up to the associated leave op. We need this so we
7630    can put it in the context and make break/continue work.
7631    (Also, of course, pp_enterwhen will jump straight to
7632    op_other if the match fails.)
7633  */
7634
7635 STATIC OP *
7636 S_newGIVWHENOP(pTHX_ OP *cond, OP *block,
7637                    I32 enter_opcode, I32 leave_opcode,
7638                    PADOFFSET entertarg)
7639 {
7640     dVAR;
7641     LOGOP *enterop;
7642     OP *o;
7643
7644     PERL_ARGS_ASSERT_NEWGIVWHENOP;
7645
7646     enterop = S_alloc_LOGOP(aTHX_ enter_opcode, block, NULL);
7647     enterop->op_targ = ((entertarg == NOT_IN_PAD) ? 0 : entertarg);
7648     enterop->op_private = 0;
7649
7650     o = newUNOP(leave_opcode, 0, (OP *) enterop);
7651
7652     if (cond) {
7653         /* prepend cond if we have one */
7654         op_sibling_splice((OP*)enterop, NULL, 0, scalar(cond));
7655
7656         o->op_next = LINKLIST(cond);
7657         cond->op_next = (OP *) enterop;
7658     }
7659     else {
7660         /* This is a default {} block */
7661         enterop->op_flags |= OPf_SPECIAL;
7662         o      ->op_flags |= OPf_SPECIAL;
7663
7664         o->op_next = (OP *) enterop;
7665     }
7666
7667     CHECKOP(enter_opcode, enterop); /* Currently does nothing, since
7668                                        entergiven and enterwhen both
7669                                        use ck_null() */
7670
7671     enterop->op_next = LINKLIST(block);
7672     block->op_next = enterop->op_other = o;
7673
7674     return o;
7675 }
7676
7677 /* Does this look like a boolean operation? For these purposes
7678    a boolean operation is:
7679      - a subroutine call [*]
7680      - a logical connective
7681      - a comparison operator
7682      - a filetest operator, with the exception of -s -M -A -C
7683      - defined(), exists() or eof()
7684      - /$re/ or $foo =~ /$re/
7685    
7686    [*] possibly surprising
7687  */
7688 STATIC bool
7689 S_looks_like_bool(pTHX_ const OP *o)
7690 {
7691     PERL_ARGS_ASSERT_LOOKS_LIKE_BOOL;
7692
7693     switch(o->op_type) {
7694         case OP_OR:
7695         case OP_DOR:
7696             return looks_like_bool(cLOGOPo->op_first);
7697
7698         case OP_AND:
7699         {
7700             OP* sibl = OpSIBLING(cLOGOPo->op_first);
7701             ASSUME(sibl);
7702             return (
7703                 looks_like_bool(cLOGOPo->op_first)
7704              && looks_like_bool(sibl));
7705         }
7706
7707         case OP_NULL:
7708         case OP_SCALAR:
7709             return (
7710                 o->op_flags & OPf_KIDS
7711             && looks_like_bool(cUNOPo->op_first));
7712
7713         case OP_ENTERSUB:
7714
7715         case OP_NOT:    case OP_XOR:
7716
7717         case OP_EQ:     case OP_NE:     case OP_LT:
7718         case OP_GT:     case OP_LE:     case OP_GE:
7719
7720         case OP_I_EQ:   case OP_I_NE:   case OP_I_LT:
7721         case OP_I_GT:   case OP_I_LE:   case OP_I_GE:
7722
7723         case OP_SEQ:    case OP_SNE:    case OP_SLT:
7724         case OP_SGT:    case OP_SLE:    case OP_SGE:
7725         
7726         case OP_SMARTMATCH:
7727         
7728         case OP_FTRREAD:  case OP_FTRWRITE: case OP_FTREXEC:
7729         case OP_FTEREAD:  case OP_FTEWRITE: case OP_FTEEXEC:
7730         case OP_FTIS:     case OP_FTEOWNED: case OP_FTROWNED:
7731         case OP_FTZERO:   case OP_FTSOCK:   case OP_FTCHR:
7732         case OP_FTBLK:    case OP_FTFILE:   case OP_FTDIR:
7733         case OP_FTPIPE:   case OP_FTLINK:   case OP_FTSUID:
7734         case OP_FTSGID:   case OP_FTSVTX:   case OP_FTTTY:
7735         case OP_FTTEXT:   case OP_FTBINARY:
7736         
7737         case OP_DEFINED: case OP_EXISTS:
7738         case OP_MATCH:   case OP_EOF:
7739
7740         case OP_FLOP:
7741
7742             return TRUE;
7743         
7744         case OP_CONST:
7745             /* Detect comparisons that have been optimized away */
7746             if (cSVOPo->op_sv == &PL_sv_yes
7747             ||  cSVOPo->op_sv == &PL_sv_no)
7748             
7749                 return TRUE;
7750             else
7751                 return FALSE;
7752
7753         /* FALLTHROUGH */
7754         default:
7755             return FALSE;
7756     }
7757 }
7758
7759 /*
7760 =for apidoc Am|OP *|newGIVENOP|OP *cond|OP *block|PADOFFSET defsv_off
7761
7762 Constructs, checks, and returns an op tree expressing a C<given> block.
7763 I<cond> supplies the expression that will be locally assigned to a lexical
7764 variable, and I<block> supplies the body of the C<given> construct; they
7765 are consumed by this function and become part of the constructed op tree.
7766 I<defsv_off> is the pad offset of the scalar lexical variable that will
7767 be affected.  If it is 0, the global $_ will be used.
7768
7769 =cut
7770 */
7771
7772 OP *
7773 Perl_newGIVENOP(pTHX_ OP *cond, OP *block, PADOFFSET defsv_off)
7774 {
7775     PERL_ARGS_ASSERT_NEWGIVENOP;
7776     return newGIVWHENOP(
7777         ref_array_or_hash(cond),
7778         block,
7779         OP_ENTERGIVEN, OP_LEAVEGIVEN,
7780         defsv_off);
7781 }
7782
7783 /*
7784 =for apidoc Am|OP *|newWHENOP|OP *cond|OP *block
7785
7786 Constructs, checks, and returns an op tree expressing a C<when> block.
7787 I<cond> supplies the test expression, and I<block> supplies the block
7788 that will be executed if the test evaluates to true; they are consumed
7789 by this function and become part of the constructed op tree.  I<cond>
7790 will be interpreted DWIMically, often as a comparison against C<$_>,
7791 and may be null to generate a C<default> block.
7792
7793 =cut
7794 */
7795
7796 OP *
7797 Perl_newWHENOP(pTHX_ OP *cond, OP *block)
7798 {
7799     const bool cond_llb = (!cond || looks_like_bool(cond));
7800     OP *cond_op;
7801
7802     PERL_ARGS_ASSERT_NEWWHENOP;
7803
7804     if (cond_llb)
7805         cond_op = cond;
7806     else {
7807         cond_op = newBINOP(OP_SMARTMATCH, OPf_SPECIAL,
7808                 newDEFSVOP(),
7809                 scalar(ref_array_or_hash(cond)));
7810     }
7811     
7812     return newGIVWHENOP(cond_op, block, OP_ENTERWHEN, OP_LEAVEWHEN, 0);
7813 }
7814
7815 /* must not conflict with SVf_UTF8 */
7816 #define CV_CKPROTO_CURSTASH     0x1
7817
7818 void
7819 Perl_cv_ckproto_len_flags(pTHX_ const CV *cv, const GV *gv, const char *p,
7820                     const STRLEN len, const U32 flags)
7821 {
7822     SV *name = NULL, *msg;
7823     const char * cvp = SvROK(cv)
7824                         ? SvTYPE(SvRV_const(cv)) == SVt_PVCV
7825                            ? (cv = (const CV *)SvRV_const(cv), CvPROTO(cv))
7826                            : ""
7827                         : CvPROTO(cv);
7828     STRLEN clen = CvPROTOLEN(cv), plen = len;
7829
7830     PERL_ARGS_ASSERT_CV_CKPROTO_LEN_FLAGS;
7831
7832     if (p == NULL && cvp == NULL)
7833         return;
7834
7835     if (!ckWARN_d(WARN_PROTOTYPE))
7836         return;
7837
7838     if (p && cvp) {
7839         p = S_strip_spaces(aTHX_ p, &plen);
7840         cvp = S_strip_spaces(aTHX_ cvp, &clen);
7841         if ((flags & SVf_UTF8) == SvUTF8(cv)) {
7842             if (plen == clen && memEQ(cvp, p, plen))
7843                 return;
7844         } else {
7845             if (flags & SVf_UTF8) {
7846                 if (bytes_cmp_utf8((const U8 *)cvp, clen, (const U8 *)p, plen) == 0)
7847                     return;
7848             }
7849             else {
7850                 if (bytes_cmp_utf8((const U8 *)p, plen, (const U8 *)cvp, clen) == 0)
7851                     return;
7852             }
7853         }
7854     }
7855
7856     msg = sv_newmortal();
7857
7858     if (gv)
7859     {
7860         if (isGV(gv))
7861             gv_efullname3(name = sv_newmortal(), gv, NULL);
7862         else if (SvPOK(gv) && *SvPVX((SV *)gv) == '&')
7863             name = newSVpvn_flags(SvPVX((SV *)gv)+1, SvCUR(gv)-1, SvUTF8(gv)|SVs_TEMP);
7864         else if (flags & CV_CKPROTO_CURSTASH || SvROK(gv)) {
7865             name = sv_2mortal(newSVhek(HvNAME_HEK(PL_curstash)));
7866             sv_catpvs(name, "::");
7867             if (SvROK(gv)) {
7868                 assert (SvTYPE(SvRV_const(gv)) == SVt_PVCV);
7869                 assert (CvNAMED(SvRV_const(gv)));
7870                 sv_cathek(name, CvNAME_HEK(MUTABLE_CV(SvRV_const(gv))));
7871             }
7872             else sv_catsv(name, (SV *)gv);
7873         }
7874         else name = (SV *)gv;
7875     }
7876     sv_setpvs(msg, "Prototype mismatch:");
7877     if (name)
7878         Perl_sv_catpvf(aTHX_ msg, " sub %"SVf, SVfARG(name));
7879     if (cvp)
7880         Perl_sv_catpvf(aTHX_ msg, " (%"UTF8f")", 
7881             UTF8fARG(SvUTF8(cv),clen,cvp)
7882         );
7883     else
7884         sv_catpvs(msg, ": none");
7885     sv_catpvs(msg, " vs ");
7886     if (p)
7887         Perl_sv_catpvf(aTHX_ msg, "(%"UTF8f")", UTF8fARG(flags & SVf_UTF8,len,p));
7888     else
7889         sv_catpvs(msg, "none");
7890     Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE), "%"SVf, SVfARG(msg));
7891 }
7892
7893 static void const_sv_xsub(pTHX_ CV* cv);
7894 static void const_av_xsub(pTHX_ CV* cv);
7895
7896 /*
7897
7898 =head1 Optree Manipulation Functions
7899
7900 =for apidoc cv_const_sv
7901
7902 If C<cv> is a constant sub eligible for inlining, returns the constant
7903 value returned by the sub.  Otherwise, returns NULL.
7904
7905 Constant subs can be created with C<newCONSTSUB> or as described in
7906 L<perlsub/"Constant Functions">.
7907
7908 =cut
7909 */
7910 SV *
7911 Perl_cv_const_sv(const CV *const cv)
7912 {
7913     SV *sv;
7914     if (!cv)
7915         return NULL;
7916     if (!(SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM))
7917         return NULL;
7918     sv = CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
7919     if (sv && SvTYPE(sv) == SVt_PVAV) return NULL;
7920     return sv;
7921 }
7922
7923 SV *
7924 Perl_cv_const_sv_or_av(const CV * const cv)
7925 {
7926     if (!cv)
7927         return NULL;
7928     if (SvROK(cv)) return SvRV((SV *)cv);
7929     assert (SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM);
7930     return CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
7931 }
7932
7933 /* op_const_sv:  examine an optree to determine whether it's in-lineable.
7934  * Can be called in 2 ways:
7935  *
7936  * !allow_lex
7937  *      look for a single OP_CONST with attached value: return the value
7938  *
7939  * allow_lex && !CvCONST(cv);
7940  *
7941  *      examine the clone prototype, and if contains only a single
7942  *      OP_CONST, return the value; or if it contains a single PADSV ref-
7943  *      erencing an outer lexical, turn on CvCONST to indicate the CV is
7944  *      a candidate for "constizing" at clone time, and return NULL.
7945  */
7946
7947 static SV *
7948 S_op_const_sv(pTHX_ const OP *o, CV *cv, bool allow_lex)
7949 {
7950     SV *sv = NULL;
7951     bool padsv = FALSE;
7952
7953     assert(o);
7954     assert(cv);
7955
7956     for (; o; o = o->op_next) {
7957         const OPCODE type = o->op_type;
7958
7959         if (type == OP_NEXTSTATE || type == OP_LINESEQ
7960              || type == OP_NULL
7961              || type == OP_PUSHMARK)
7962                 continue;
7963         if (type == OP_DBSTATE)
7964                 continue;
7965         if (type == OP_LEAVESUB)
7966             break;
7967         if (sv)
7968             return NULL;
7969         if (type == OP_CONST && cSVOPo->op_sv)
7970             sv = cSVOPo->op_sv;
7971         else if (type == OP_UNDEF && !o->op_private) {
7972             sv = newSV(0);
7973             SAVEFREESV(sv);
7974         }
7975         else if (allow_lex && type == OP_PADSV) {
7976                 if (PAD_COMPNAME_FLAGS(o->op_targ) & PADNAMEt_OUTER)
7977                 {
7978                     sv = &PL_sv_undef; /* an arbitrary non-null value */
7979                     padsv = TRUE;
7980                 }
7981                 else
7982                     return NULL;
7983         }
7984         else {
7985             return NULL;
7986         }
7987     }
7988     if (padsv) {
7989         CvCONST_on(cv);
7990         return NULL;
7991     }
7992     return sv;
7993 }
7994
7995 static bool
7996 S_already_defined(pTHX_ CV *const cv, OP * const block, OP * const o,
7997                         PADNAME * const name, SV ** const const_svp)
7998 {
7999     assert (cv);
8000     assert (o || name);
8001     assert (const_svp);
8002     if ((!block
8003          )) {
8004         if (CvFLAGS(PL_compcv)) {
8005             /* might have had built-in attrs applied */
8006             const bool pureperl = !CvISXSUB(cv) && CvROOT(cv);
8007             if (CvLVALUE(PL_compcv) && ! CvLVALUE(cv) && pureperl
8008              && ckWARN(WARN_MISC))
8009             {
8010                 /* protect against fatal warnings leaking compcv */
8011                 SAVEFREESV(PL_compcv);
8012                 Perl_warner(aTHX_ packWARN(WARN_MISC), "lvalue attribute ignored after the subroutine has been defined");
8013                 SvREFCNT_inc_simple_void_NN(PL_compcv);
8014             }
8015             CvFLAGS(cv) |=
8016                 (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS
8017                   & ~(CVf_LVALUE * pureperl));
8018         }
8019         return FALSE;
8020     }
8021
8022     /* redundant check for speed: */
8023     if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
8024         const line_t oldline = CopLINE(PL_curcop);
8025         SV *namesv = o
8026             ? cSVOPo->op_sv
8027             : sv_2mortal(newSVpvn_utf8(
8028                 PadnamePV(name)+1,PadnameLEN(name)-1, PadnameUTF8(name)
8029               ));
8030         if (PL_parser && PL_parser->copline != NOLINE)
8031             /* This ensures that warnings are reported at the first
8032                line of a redefinition, not the last.  */
8033             CopLINE_set(PL_curcop, PL_parser->copline);
8034         /* protect against fatal warnings leaking compcv */
8035         SAVEFREESV(PL_compcv);
8036         report_redefined_cv(namesv, cv, const_svp);
8037         SvREFCNT_inc_simple_void_NN(PL_compcv);
8038         CopLINE_set(PL_curcop, oldline);
8039     }
8040     SAVEFREESV(cv);
8041     return TRUE;
8042 }
8043
8044 CV *
8045 Perl_newMYSUB(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs, OP *block)
8046 {
8047     CV **spot;
8048     SV **svspot;
8049     const char *ps;
8050     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
8051     U32 ps_utf8 = 0;
8052     CV *cv = NULL;
8053     CV *compcv = PL_compcv;
8054     SV *const_sv;
8055     PADNAME *name;
8056     PADOFFSET pax = o->op_targ;
8057     CV *outcv = CvOUTSIDE(PL_compcv);
8058     CV *clonee = NULL;
8059     HEK *hek = NULL;
8060     bool reusable = FALSE;
8061     OP *start = NULL;
8062 #ifdef PERL_DEBUG_READONLY_OPS
8063     OPSLAB *slab = NULL;
8064 #endif
8065
8066     PERL_ARGS_ASSERT_NEWMYSUB;
8067
8068     /* Find the pad slot for storing the new sub.
8069        We cannot use PL_comppad, as it is the pad owned by the new sub.  We
8070        need to look in CvOUTSIDE and find the pad belonging to the enclos-
8071        ing sub.  And then we need to dig deeper if this is a lexical from
8072        outside, as in:
8073            my sub foo; sub { sub foo { } }
8074      */
8075    redo:
8076     name = PadlistNAMESARRAY(CvPADLIST(outcv))[pax];
8077     if (PadnameOUTER(name) && PARENT_PAD_INDEX(name)) {
8078         pax = PARENT_PAD_INDEX(name);
8079         outcv = CvOUTSIDE(outcv);
8080         assert(outcv);
8081         goto redo;
8082     }
8083     svspot =
8084         &PadARRAY(PadlistARRAY(CvPADLIST(outcv))
8085                         [CvDEPTH(outcv) ? CvDEPTH(outcv) : 1])[pax];
8086     spot = (CV **)svspot;
8087
8088     if (!(PL_parser && PL_parser->error_count))
8089         move_proto_attr(&proto, &attrs, (GV *)PadnameSV(name));
8090
8091     if (proto) {
8092         assert(proto->op_type == OP_CONST);
8093         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
8094         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
8095     }
8096     else
8097         ps = NULL;
8098
8099     if (proto)
8100         SAVEFREEOP(proto);
8101     if (attrs)
8102         SAVEFREEOP(attrs);
8103
8104     if (PL_parser && PL_parser->error_count) {
8105         op_free(block);
8106         SvREFCNT_dec(PL_compcv);
8107         PL_compcv = 0;
8108         goto done;
8109     }
8110
8111     if (CvDEPTH(outcv) && CvCLONE(compcv)) {
8112         cv = *spot;
8113         svspot = (SV **)(spot = &clonee);
8114     }
8115     else if (PadnameIsSTATE(name) || CvDEPTH(outcv))
8116         cv = *spot;
8117     else {
8118         assert (SvTYPE(*spot) == SVt_PVCV);
8119         if (CvNAMED(*spot))
8120             hek = CvNAME_HEK(*spot);
8121         else {
8122             dVAR;
8123             U32 hash;
8124             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
8125             CvNAME_HEK_set(*spot, hek =
8126                 share_hek(
8127                     PadnamePV(name)+1,
8128                     (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
8129                     hash
8130                 )
8131             );
8132             CvLEXICAL_on(*spot);
8133         }
8134         cv = PadnamePROTOCV(name);
8135         svspot = (SV **)(spot = &PadnamePROTOCV(name));
8136     }
8137
8138     if (block) {
8139         /* This makes sub {}; work as expected.  */
8140         if (block->op_type == OP_STUB) {
8141             const line_t l = PL_parser->copline;
8142             op_free(block);
8143             block = newSTATEOP(0, NULL, 0);
8144             PL_parser->copline = l;
8145         }
8146         block = CvLVALUE(compcv)
8147              || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv))
8148                    ? newUNOP(OP_LEAVESUBLV, 0,
8149                              op_lvalue(scalarseq(block), OP_LEAVESUBLV))
8150                    : newUNOP(OP_LEAVESUB, 0, scalarseq(block));
8151         start = LINKLIST(block);
8152         block->op_next = 0;
8153     }
8154
8155     if (!block || !ps || *ps || attrs
8156         || CvLVALUE(compcv)
8157         )
8158         const_sv = NULL;
8159     else
8160         const_sv = S_op_const_sv(aTHX_ start, compcv, FALSE);
8161
8162     if (cv) {
8163         const bool exists = CvROOT(cv) || CvXSUB(cv);
8164
8165         /* if the subroutine doesn't exist and wasn't pre-declared
8166          * with a prototype, assume it will be AUTOLOADed,
8167          * skipping the prototype check
8168          */
8169         if (exists || SvPOK(cv))
8170             cv_ckproto_len_flags(cv, (GV *)PadnameSV(name), ps, ps_len,
8171                                  ps_utf8);
8172         /* already defined? */
8173         if (exists) {
8174             if (S_already_defined(aTHX_ cv,block,NULL,name,&const_sv))
8175                 cv = NULL;
8176             else {
8177                 if (attrs) goto attrs;
8178                 /* just a "sub foo;" when &foo is already defined */
8179                 SAVEFREESV(compcv);
8180                 goto done;
8181             }
8182         }
8183         else if (CvDEPTH(outcv) && CvCLONE(compcv)) {
8184             cv = NULL;
8185             reusable = TRUE;
8186         }
8187     }
8188     if (const_sv) {
8189         SvREFCNT_inc_simple_void_NN(const_sv);
8190         SvFLAGS(const_sv) |= SVs_PADTMP;
8191         if (cv) {
8192             assert(!CvROOT(cv) && !CvCONST(cv));
8193             cv_forget_slab(cv);
8194         }
8195         else {
8196             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
8197             CvFILE_set_from_cop(cv, PL_curcop);
8198             CvSTASH_set(cv, PL_curstash);
8199             *spot = cv;
8200         }
8201         sv_setpvs(MUTABLE_SV(cv), "");  /* prototype is "" */
8202         CvXSUBANY(cv).any_ptr = const_sv;
8203         CvXSUB(cv) = const_sv_xsub;
8204         CvCONST_on(cv);
8205         CvISXSUB_on(cv);
8206         PoisonPADLIST(cv);
8207         CvFLAGS(cv) |= CvMETHOD(compcv);
8208         op_free(block);
8209         SvREFCNT_dec(compcv);
8210         PL_compcv = NULL;
8211         goto setname;
8212     }
8213     /* Checking whether outcv is CvOUTSIDE(compcv) is not sufficient to
8214        determine whether this sub definition is in the same scope as its
8215        declaration.  If this sub definition is inside an inner named pack-
8216        age sub (my sub foo; sub bar { sub foo { ... } }), outcv points to
8217        the package sub.  So check PadnameOUTER(name) too.
8218      */
8219     if (outcv == CvOUTSIDE(compcv) && !PadnameOUTER(name)) { 
8220         assert(!CvWEAKOUTSIDE(compcv));
8221         SvREFCNT_dec(CvOUTSIDE(compcv));
8222         CvWEAKOUTSIDE_on(compcv);
8223     }
8224     /* XXX else do we have a circular reference? */
8225     if (cv) {   /* must reuse cv in case stub is referenced elsewhere */
8226         /* transfer PL_compcv to cv */
8227         if (block
8228         ) {
8229             cv_flags_t preserved_flags =
8230                 CvFLAGS(cv) & (CVf_BUILTIN_ATTRS|CVf_NAMED);
8231             PADLIST *const temp_padl = CvPADLIST(cv);
8232             CV *const temp_cv = CvOUTSIDE(cv);
8233             const cv_flags_t other_flags =
8234                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
8235             OP * const cvstart = CvSTART(cv);
8236
8237             SvPOK_off(cv);
8238             CvFLAGS(cv) =
8239                 CvFLAGS(compcv) | preserved_flags;
8240             CvOUTSIDE(cv) = CvOUTSIDE(compcv);
8241             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(compcv);
8242             CvPADLIST_set(cv, CvPADLIST(compcv));
8243             CvOUTSIDE(compcv) = temp_cv;
8244             CvPADLIST_set(compcv, temp_padl);
8245             CvSTART(cv) = CvSTART(compcv);
8246             CvSTART(compcv) = cvstart;
8247             CvFLAGS(compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
8248             CvFLAGS(compcv) |= other_flags;
8249
8250             if (CvFILE(cv) && CvDYNFILE(cv)) {
8251                 Safefree(CvFILE(cv));
8252             }
8253
8254             /* inner references to compcv must be fixed up ... */
8255             pad_fixup_inner_anons(CvPADLIST(cv), compcv, cv);
8256             if (PERLDB_INTER)/* Advice debugger on the new sub. */
8257               ++PL_sub_generation;
8258         }
8259         else {
8260             /* Might have had built-in attributes applied -- propagate them. */
8261             CvFLAGS(cv) |= (CvFLAGS(compcv) & CVf_BUILTIN_ATTRS);
8262         }
8263         /* ... before we throw it away */
8264         SvREFCNT_dec(compcv);
8265         PL_compcv = compcv = cv;
8266     }
8267     else {
8268         cv = compcv;
8269         *spot = cv;
8270     }
8271    setname:
8272     CvLEXICAL_on(cv);
8273     if (!CvNAME_HEK(cv)) {
8274         if (hek) (void)share_hek_hek(hek);
8275         else {
8276             dVAR;
8277             U32 hash;
8278             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
8279             hek = share_hek(PadnamePV(name)+1,
8280                       (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
8281                       hash);
8282         }
8283         CvNAME_HEK_set(cv, hek);
8284     }
8285     if (const_sv) goto clone;
8286
8287     CvFILE_set_from_cop(cv, PL_curcop);
8288     CvSTASH_set(cv, PL_curstash);
8289
8290     if (ps) {
8291         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
8292         if ( ps_utf8 ) SvUTF8_on(MUTABLE_SV(cv));
8293     }
8294
8295     if (!block)
8296         goto attrs;
8297
8298     /* If we assign an optree to a PVCV, then we've defined a subroutine that
8299        the debugger could be able to set a breakpoint in, so signal to
8300        pp_entereval that it should not throw away any saved lines at scope
8301        exit.  */
8302        
8303     PL_breakable_sub_gen++;
8304     CvROOT(cv) = block;
8305     CvROOT(cv)->op_private |= OPpREFCOUNTED;
8306     OpREFCNT_set(CvROOT(cv), 1);
8307     /* The cv no longer needs to hold a refcount on the slab, as CvROOT
8308        itself has a refcount. */
8309     CvSLABBED_off(cv);
8310     OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
8311 #ifdef PERL_DEBUG_READONLY_OPS
8312     slab = (OPSLAB *)CvSTART(cv);
8313 #endif
8314     CvSTART(cv) = start;
8315     CALL_PEEP(start);
8316     finalize_optree(CvROOT(cv));
8317     S_prune_chain_head(&CvSTART(cv));
8318
8319     /* now that optimizer has done its work, adjust pad values */
8320
8321     pad_tidy(CvCLONE(cv) ? padtidy_SUBCLONE : padtidy_SUB);
8322
8323   attrs:
8324     if (attrs) {
8325         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
8326         apply_attrs(PL_curstash, MUTABLE_SV(cv), attrs);
8327     }
8328
8329     if (block) {
8330         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
8331             SV * const tmpstr = sv_newmortal();
8332             GV * const db_postponed = gv_fetchpvs("DB::postponed",
8333                                                   GV_ADDMULTI, SVt_PVHV);
8334             HV *hv;
8335             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
8336                                           CopFILE(PL_curcop),
8337                                           (long)PL_subline,
8338                                           (long)CopLINE(PL_curcop));
8339             if (HvNAME_HEK(PL_curstash)) {
8340                 sv_sethek(tmpstr, HvNAME_HEK(PL_curstash));
8341                 sv_catpvs(tmpstr, "::");
8342             }
8343             else sv_setpvs(tmpstr, "__ANON__::");
8344             sv_catpvn_flags(tmpstr, PadnamePV(name)+1, PadnameLEN(name)-1,
8345                             PadnameUTF8(name) ? SV_CATUTF8 : SV_CATBYTES);
8346             (void)hv_store(GvHV(PL_DBsub), SvPVX_const(tmpstr),
8347                     SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr), sv, 0);
8348             hv = GvHVn(db_postponed);
8349             if (HvTOTALKEYS(hv) > 0 && hv_exists(hv, SvPVX_const(tmpstr), SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr))) {
8350                 CV * const pcv = GvCV(db_postponed);
8351                 if (pcv) {
8352                     dSP;
8353                     PUSHMARK(SP);
8354                     XPUSHs(tmpstr);
8355                     PUTBACK;
8356                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
8357                 }
8358             }
8359         }
8360     }
8361
8362   clone:
8363     if (clonee) {
8364         assert(CvDEPTH(outcv));
8365         spot = (CV **)
8366             &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[CvDEPTH(outcv)])[pax];
8367         if (reusable) cv_clone_into(clonee, *spot);
8368         else *spot = cv_clone(clonee);
8369         SvREFCNT_dec_NN(clonee);
8370         cv = *spot;
8371     }
8372     if (CvDEPTH(outcv) && !reusable && PadnameIsSTATE(name)) {
8373         PADOFFSET depth = CvDEPTH(outcv);
8374         while (--depth) {
8375             SV *oldcv;
8376             svspot = &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[depth])[pax];
8377             oldcv = *svspot;
8378             *svspot = SvREFCNT_inc_simple_NN(cv);
8379             SvREFCNT_dec(oldcv);
8380         }
8381     }
8382
8383   done:
8384     if (PL_parser)
8385         PL_parser->copline = NOLINE;
8386     LEAVE_SCOPE(floor);
8387 #ifdef PERL_DEBUG_READONLY_OPS
8388     if (slab)
8389         Slab_to_ro(slab);
8390 #endif
8391     if (o) op_free(o);
8392     return cv;
8393 }
8394
8395 /* _x = extended */
8396 CV *
8397 Perl_newATTRSUB_x(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs,
8398                             OP *block, bool o_is_gv)
8399 {
8400     GV *gv;
8401     const char *ps;
8402     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
8403     U32 ps_utf8 = 0;
8404     CV *cv = NULL;
8405     SV *const_sv;
8406     const bool ec = PL_parser && PL_parser->error_count;
8407     /* If the subroutine has no body, no attributes, and no builtin attributes
8408        then it's just a sub declaration, and we may be able to get away with
8409        storing with a placeholder scalar in the symbol table, rather than a
8410        full CV.  If anything is present then it will take a full CV to
8411        store it.  */
8412     const I32 gv_fetch_flags
8413         = ec ? GV_NOADD_NOINIT :
8414         (block || attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS))
8415         ? GV_ADDMULTI : GV_ADDMULTI | GV_NOINIT;
8416     STRLEN namlen = 0;
8417     const char * const name =
8418          o ? SvPV_const(o_is_gv ? (SV *)o : cSVOPo->op_sv, namlen) : NULL;
8419     bool has_name;
8420     bool name_is_utf8 = o && !o_is_gv && SvUTF8(cSVOPo->op_sv);
8421     bool evanescent = FALSE;
8422     OP *start = NULL;
8423 #ifdef PERL_DEBUG_READONLY_OPS
8424     OPSLAB *slab = NULL;
8425 #endif
8426
8427     if (o_is_gv) {
8428         gv = (GV*)o;
8429         o = NULL;
8430         has_name = TRUE;
8431     } else if (name) {
8432         /* Try to optimise and avoid creating a GV.  Instead, the CV’s name
8433            hek and CvSTASH pointer together can imply the GV.  If the name
8434            contains a package name, then GvSTASH(CvGV(cv)) may differ from
8435            CvSTASH, so forego the optimisation if we find any.
8436            Also, we may be called from load_module at run time, so
8437            PL_curstash (which sets CvSTASH) may not point to the stash the
8438            sub is stored in.  */
8439         const I32 flags =
8440            ec ? GV_NOADD_NOINIT
8441               :   PL_curstash != CopSTASH(PL_curcop)
8442                || memchr(name, ':', namlen) || memchr(name, '\'', namlen)
8443                     ? gv_fetch_flags
8444                     : GV_ADDMULTI | GV_NOINIT | GV_NOTQUAL;
8445         gv = gv_fetchsv(cSVOPo->op_sv, flags, SVt_PVCV);
8446         has_name = TRUE;
8447     } else if (PERLDB_NAMEANON && CopLINE(PL_curcop)) {
8448         SV * const sv = sv_newmortal();
8449         Perl_sv_setpvf(aTHX_ sv, "%s[%s:%"IVdf"]",
8450                        PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
8451                        CopFILE(PL_curcop), (IV)CopLINE(PL_curcop));
8452         gv = gv_fetchsv(sv, gv_fetch_flags, SVt_PVCV);
8453         has_name = TRUE;
8454     } else if (PL_curstash) {
8455         gv = gv_fetchpvs("__ANON__", gv_fetch_flags, SVt_PVCV);
8456         has_name = FALSE;
8457     } else {
8458         gv = gv_fetchpvs("__ANON__::__ANON__", gv_fetch_flags, SVt_PVCV);
8459         has_name = FALSE;
8460     }
8461     if (!ec)
8462         move_proto_attr(&proto, &attrs,
8463                         isGV(gv) ? gv : (GV *)cSVOPo->op_sv);
8464
8465     if (proto) {
8466         assert(proto->op_type == OP_CONST);
8467         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
8468         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
8469     }
8470     else
8471         ps = NULL;
8472
8473     if (o)
8474         SAVEFREEOP(o);
8475     if (proto)
8476         SAVEFREEOP(proto);
8477     if (attrs)
8478         SAVEFREEOP(attrs);
8479
8480     if (ec) {
8481         op_free(block);
8482         if (name) SvREFCNT_dec(PL_compcv);
8483         else cv = PL_compcv;
8484         PL_compcv = 0;
8485         if (name && block) {
8486             const char *s = strrchr(name, ':');
8487             s = s ? s+1 : name;
8488             if (strEQ(s, "BEGIN")) {
8489                 if (PL_in_eval & EVAL_KEEPERR)
8490                     Perl_croak_nocontext("BEGIN not safe after errors--compilation aborted");
8491                 else {
8492                     SV * const errsv = ERRSV;
8493                     /* force display of errors found but not reported */
8494                     sv_catpvs(errsv, "BEGIN not safe after errors--compilation aborted");
8495                     Perl_croak_nocontext("%"SVf, SVfARG(errsv));
8496                 }
8497             }
8498         }
8499         goto done;
8500     }
8501
8502     if (!block && SvTYPE(gv) != SVt_PVGV) {
8503       /* If we are not defining a new sub and the existing one is not a
8504          full GV + CV... */
8505       if (attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS)) {
8506         /* We are applying attributes to an existing sub, so we need it
8507            upgraded if it is a constant.  */
8508         if (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)
8509             gv_init_pvn(gv, PL_curstash, name, namlen,
8510                         SVf_UTF8 * name_is_utf8);
8511       }
8512       else {                    /* Maybe prototype now, and had at maximum
8513                                    a prototype or const/sub ref before.  */
8514         if (SvTYPE(gv) > SVt_NULL) {
8515             cv_ckproto_len_flags((const CV *)gv,
8516                                  o ? (const GV *)cSVOPo->op_sv : NULL, ps,
8517                                  ps_len, ps_utf8);
8518         }
8519         if (!SvROK(gv)) {
8520           if (ps) {
8521             sv_setpvn(MUTABLE_SV(gv), ps, ps_len);
8522             if ( ps_utf8 ) SvUTF8_on(MUTABLE_SV(gv));
8523           }
8524           else
8525             sv_setiv(MUTABLE_SV(gv), -1);
8526         }
8527
8528         SvREFCNT_dec(PL_compcv);
8529         cv = PL_compcv = NULL;
8530         goto done;
8531       }
8532     }
8533
8534     cv = (!name || (isGV(gv) && GvCVGEN(gv)))
8535         ? NULL
8536         : isGV(gv)
8537             ? GvCV(gv)
8538             : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
8539                 ? (CV *)SvRV(gv)
8540                 : NULL;
8541
8542     if (block) {
8543         /* This makes sub {}; work as expected.  */
8544         if (block->op_type == OP_STUB) {
8545             const line_t l = PL_parser->copline;
8546             op_free(block);
8547             block = newSTATEOP(0, NULL, 0);
8548             PL_parser->copline = l;
8549         }
8550         block = CvLVALUE(PL_compcv)
8551              || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv)
8552                     && (!isGV(gv) || !GvASSUMECV(gv)))
8553                    ? newUNOP(OP_LEAVESUBLV, 0,
8554                              op_lvalue(scalarseq(block), OP_LEAVESUBLV))
8555                    : newUNOP(OP_LEAVESUB, 0, scalarseq(block));
8556         start = LINKLIST(block);
8557         block->op_next = 0;
8558     }
8559
8560     if (!block || !ps || *ps || attrs
8561         || CvLVALUE(PL_compcv)
8562         )
8563         const_sv = NULL;
8564     else
8565         const_sv =
8566             S_op_const_sv(aTHX_ start, PL_compcv, cBOOL(CvCLONE(PL_compcv)));
8567
8568     if (SvPOK(gv) || (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)) {
8569         assert (block);
8570         cv_ckproto_len_flags((const CV *)gv,
8571                              o ? (const GV *)cSVOPo->op_sv : NULL, ps,
8572                              ps_len, ps_utf8|CV_CKPROTO_CURSTASH);
8573         if (SvROK(gv)) {
8574             /* All the other code for sub redefinition warnings expects the
8575                clobbered sub to be a CV.  Instead of making all those code
8576                paths more complex, just inline the RV version here.  */
8577             const line_t oldline = CopLINE(PL_curcop);
8578             assert(IN_PERL_COMPILETIME);
8579             if (PL_parser && PL_parser->copline != NOLINE)
8580                 /* This ensures that warnings are reported at the first
8581                    line of a redefinition, not the last.  */
8582                 CopLINE_set(PL_curcop, PL_parser->copline);
8583             /* protect against fatal warnings leaking compcv */
8584             SAVEFREESV(PL_compcv);
8585
8586             if (ckWARN(WARN_REDEFINE)
8587              || (  ckWARN_d(WARN_REDEFINE)
8588                 && (  !const_sv || SvRV(gv) == const_sv
8589                    || sv_cmp(SvRV(gv), const_sv)  )))
8590                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
8591                           "Constant subroutine %"SVf" redefined",
8592                           SVfARG(cSVOPo->op_sv));
8593
8594             SvREFCNT_inc_simple_void_NN(PL_compcv);
8595             CopLINE_set(PL_curcop, oldline);
8596             SvREFCNT_dec(SvRV(gv));
8597         }
8598     }
8599
8600     if (cv) {
8601         const bool exists = CvROOT(cv) || CvXSUB(cv);
8602
8603         /* if the subroutine doesn't exist and wasn't pre-declared
8604          * with a prototype, assume it will be AUTOLOADed,
8605          * skipping the prototype check
8606          */
8607         if (exists || SvPOK(cv))
8608             cv_ckproto_len_flags(cv, gv, ps, ps_len, ps_utf8);
8609         /* already defined (or promised)? */
8610         if (exists || (isGV(gv) && GvASSUMECV(gv))) {
8611             if (S_already_defined(aTHX_ cv, block, o, NULL, &const_sv))
8612                 cv = NULL;
8613             else {
8614                 if (attrs) goto attrs;
8615                 /* just a "sub foo;" when &foo is already defined */
8616                 SAVEFREESV(PL_compcv);
8617                 goto done;
8618             }
8619         }
8620     }
8621     if (const_sv) {
8622         SvREFCNT_inc_simple_void_NN(const_sv);
8623         SvFLAGS(const_sv) |= SVs_PADTMP;
8624         if (cv) {
8625             assert(!CvROOT(cv) && !CvCONST(cv));
8626             cv_forget_slab(cv);
8627             sv_setpvs(MUTABLE_SV(cv), "");  /* prototype is "" */
8628             CvXSUBANY(cv).any_ptr = const_sv;
8629             CvXSUB(cv) = const_sv_xsub;
8630             CvCONST_on(cv);
8631             CvISXSUB_on(cv);
8632             PoisonPADLIST(cv);
8633             CvFLAGS(cv) |= CvMETHOD(PL_compcv);
8634         }
8635         else {
8636             if (isGV(gv) || CvMETHOD(PL_compcv)) {
8637                 if (name && isGV(gv))
8638                     GvCV_set(gv, NULL);
8639                 cv = newCONSTSUB_flags(
8640                     NULL, name, namlen, name_is_utf8 ? SVf_UTF8 : 0,
8641                     const_sv
8642                 );
8643                 CvFLAGS(cv) |= CvMETHOD(PL_compcv);
8644             }
8645             else {
8646                 if (!SvROK(gv)) {
8647                     SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
8648                     prepare_SV_for_RV((SV *)gv);
8649                     SvOK_off((SV *)gv);
8650                     SvROK_on(gv);
8651                 }
8652                 SvRV_set(gv, const_sv);
8653             }
8654         }
8655         op_free(block);
8656         SvREFCNT_dec(PL_compcv);
8657         PL_compcv = NULL;
8658         goto done;
8659     }
8660     if (cv) {                           /* must reuse cv if autoloaded */
8661         /* transfer PL_compcv to cv */
8662         if (block
8663         ) {
8664             cv_flags_t existing_builtin_attrs = CvFLAGS(cv) & CVf_BUILTIN_ATTRS;
8665             PADLIST *const temp_av = CvPADLIST(cv);
8666             CV *const temp_cv = CvOUTSIDE(cv);
8667             const cv_flags_t other_flags =
8668                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
8669             OP * const cvstart = CvSTART(cv);
8670
8671             if (isGV(gv)) {
8672                 CvGV_set(cv,gv);
8673                 assert(!CvCVGV_RC(cv));
8674                 assert(CvGV(cv) == gv);
8675             }
8676             else {
8677                 dVAR;
8678                 U32 hash;
8679                 PERL_HASH(hash, name, namlen);
8680                 CvNAME_HEK_set(cv,
8681                                share_hek(name,
8682                                          name_is_utf8
8683                                             ? -(SSize_t)namlen
8684                                             :  (SSize_t)namlen,
8685                                          hash));
8686             }
8687
8688             SvPOK_off(cv);
8689             CvFLAGS(cv) = CvFLAGS(PL_compcv) | existing_builtin_attrs
8690                                              | CvNAMED(cv);
8691             CvOUTSIDE(cv) = CvOUTSIDE(PL_compcv);
8692             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(PL_compcv);
8693             CvPADLIST_set(cv,CvPADLIST(PL_compcv));
8694             CvOUTSIDE(PL_compcv) = temp_cv;
8695             CvPADLIST_set(PL_compcv, temp_av);
8696             CvSTART(cv) = CvSTART(PL_compcv);
8697             CvSTART(PL_compcv) = cvstart;
8698             CvFLAGS(PL_compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
8699             CvFLAGS(PL_compcv) |= other_flags;
8700
8701             if (CvFILE(cv) && CvDYNFILE(cv)) {
8702                 Safefree(CvFILE(cv));
8703     }
8704             CvFILE_set_from_cop(cv, PL_curcop);
8705             CvSTASH_set(cv, PL_curstash);
8706
8707             /* inner references to PL_compcv must be fixed up ... */
8708             pad_fixup_inner_anons(CvPADLIST(cv), PL_compcv, cv);
8709             if (PERLDB_INTER)/* Advice debugger on the new sub. */
8710               ++PL_sub_generation;
8711         }
8712         else {
8713             /* Might have had built-in attributes applied -- propagate them. */
8714             CvFLAGS(cv) |= (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS);
8715         }
8716         /* ... before we throw it away */
8717         SvREFCNT_dec(PL_compcv);
8718         PL_compcv = cv;
8719     }
8720     else {
8721         cv = PL_compcv;
8722         if (name && isGV(gv)) {
8723             GvCV_set(gv, cv);
8724             GvCVGEN(gv) = 0;
8725             if (HvENAME_HEK(GvSTASH(gv)))
8726                 /* sub Foo::bar { (shift)+1 } */
8727                 gv_method_changed(gv);
8728         }
8729         else if (name) {
8730             if (!SvROK(gv)) {
8731                 SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
8732                 prepare_SV_for_RV((SV *)gv);
8733                 SvOK_off((SV *)gv);
8734                 SvROK_on(gv);
8735             }
8736             SvRV_set(gv, (SV *)cv);
8737         }
8738     }
8739     if (!CvHASGV(cv)) {
8740         if (isGV(gv)) CvGV_set(cv, gv);
8741         else {
8742             dVAR;
8743             U32 hash;
8744             PERL_HASH(hash, name, namlen);
8745             CvNAME_HEK_set(cv, share_hek(name,
8746                                          name_is_utf8
8747                                             ? -(SSize_t)namlen
8748                                             :  (SSize_t)namlen,
8749                                          hash));
8750         }
8751         CvFILE_set_from_cop(cv, PL_curcop);
8752         CvSTASH_set(cv, PL_curstash);
8753     }
8754
8755     if (ps) {
8756         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
8757         if ( ps_utf8 ) SvUTF8_on(MUTABLE_SV(cv));
8758     }
8759
8760     if (!block)
8761         goto attrs;
8762
8763     /* If we assign an optree to a PVCV, then we've defined a subroutine that
8764        the debugger could be able to set a breakpoint in, so signal to
8765        pp_entereval that it should not throw away any saved lines at scope
8766        exit.  */
8767        
8768     PL_breakable_sub_gen++;
8769     CvROOT(cv) = block;
8770     CvROOT(cv)->op_private |= OPpREFCOUNTED;
8771     OpREFCNT_set(CvROOT(cv), 1);
8772     /* The cv no longer needs to hold a refcount on the slab, as CvROOT
8773        itself has a refcount. */
8774     CvSLABBED_off(cv);
8775     OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
8776 #ifdef PERL_DEBUG_READONLY_OPS
8777     slab = (OPSLAB *)CvSTART(cv);
8778 #endif
8779     CvSTART(cv) = start;
8780     CALL_PEEP(start);
8781     finalize_optree(CvROOT(cv));
8782     S_prune_chain_head(&CvSTART(cv));
8783
8784     /* now that optimizer has done its work, adjust pad values */
8785
8786     pad_tidy(CvCLONE(cv) ? padtidy_SUBCLONE : padtidy_SUB);
8787
8788   attrs:
8789     if (attrs) {
8790         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
8791         HV *stash = name && !CvNAMED(cv) && GvSTASH(CvGV(cv))
8792                         ? GvSTASH(CvGV(cv))
8793                         : PL_curstash;
8794         if (!name) SAVEFREESV(cv);
8795         apply_attrs(stash, MUTABLE_SV(cv), attrs);
8796         if (!name) SvREFCNT_inc_simple_void_NN(cv);
8797     }
8798
8799     if (block && has_name) {
8800         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
8801             SV * const tmpstr = cv_name(cv,NULL,0);
8802             GV * const db_postponed = gv_fetchpvs("DB::postponed",
8803                                                   GV_ADDMULTI, SVt_PVHV);
8804             HV *hv;
8805             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
8806                                           CopFILE(PL_curcop),
8807                                           (long)PL_subline,
8808                                           (long)CopLINE(PL_curcop));
8809             (void)hv_store(GvHV(PL_DBsub), SvPVX_const(tmpstr),
8810                     SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr), sv, 0);
8811             hv = GvHVn(db_postponed);
8812             if (HvTOTALKEYS(hv) > 0 && hv_exists(hv, SvPVX_const(tmpstr), SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr))) {
8813                 CV * const pcv = GvCV(db_postponed);
8814                 if (pcv) {
8815                     dSP;
8816                     PUSHMARK(SP);
8817                     XPUSHs(tmpstr);
8818                     PUTBACK;
8819                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
8820                 }
8821             }
8822         }
8823
8824         if (name) {
8825             if (PL_parser && PL_parser->error_count)
8826                 clear_special_blocks(name, gv, cv);
8827             else
8828                 evanescent =
8829                     process_special_blocks(floor, name, gv, cv);
8830         }
8831     }
8832
8833   done:
8834     if (PL_parser)
8835         PL_parser->copline = NOLINE;
8836     LEAVE_SCOPE(floor);
8837     if (!evanescent) {
8838 #ifdef PERL_DEBUG_READONLY_OPS
8839       if (slab)
8840         Slab_to_ro(slab);
8841 #endif
8842       if (cv && name && CvOUTSIDE(cv) && !CvEVAL(CvOUTSIDE(cv)))
8843         pad_add_weakref(cv);
8844     }
8845     return cv;
8846 }
8847
8848 STATIC void
8849 S_clear_special_blocks(pTHX_ const char *const fullname,
8850                        GV *const gv, CV *const cv) {
8851     const char *colon;
8852     const char *name;
8853
8854     PERL_ARGS_ASSERT_CLEAR_SPECIAL_BLOCKS;
8855
8856     colon = strrchr(fullname,':');
8857     name = colon ? colon + 1 : fullname;
8858
8859     if ((*name == 'B' && strEQ(name, "BEGIN"))
8860         || (*name == 'E' && strEQ(name, "END"))
8861         || (*name == 'U' && strEQ(name, "UNITCHECK"))
8862         || (*name == 'C' && strEQ(name, "CHECK"))
8863         || (*name == 'I' && strEQ(name, "INIT"))) {
8864         if (!isGV(gv)) {
8865             (void)CvGV(cv);
8866             assert(isGV(gv));
8867         }
8868         GvCV_set(gv, NULL);
8869         SvREFCNT_dec_NN(MUTABLE_SV(cv));
8870     }
8871 }
8872
8873 /* Returns true if the sub has been freed.  */
8874 STATIC bool
8875 S_process_special_blocks(pTHX_ I32 floor, const char *const fullname,
8876                          GV *const gv,
8877                          CV *const cv)
8878 {
8879     const char *const colon = strrchr(fullname,':');
8880     const char *const name = colon ? colon + 1 : fullname;
8881
8882     PERL_ARGS_ASSERT_PROCESS_SPECIAL_BLOCKS;
8883
8884     if (*name == 'B') {
8885         if (strEQ(name, "BEGIN")) {
8886             const I32 oldscope = PL_scopestack_ix;
8887             dSP;
8888             (void)CvGV(cv);
8889             if (floor) LEAVE_SCOPE(floor);
8890             ENTER;
8891             PUSHSTACKi(PERLSI_REQUIRE);
8892             SAVECOPFILE(&PL_compiling);
8893             SAVECOPLINE(&PL_compiling);
8894             SAVEVPTR(PL_curcop);
8895
8896             DEBUG_x( dump_sub(gv) );
8897             Perl_av_create_and_push(aTHX_ &PL_beginav, MUTABLE_SV(cv));
8898             GvCV_set(gv,0);             /* cv has been hijacked */
8899             call_list(oldscope, PL_beginav);
8900
8901             POPSTACK;
8902             LEAVE;
8903             return !PL_savebegin;
8904         }
8905         else
8906             return FALSE;
8907     } else {
8908         if (*name == 'E') {
8909             if strEQ(name, "END") {
8910                 DEBUG_x( dump_sub(gv) );
8911                 Perl_av_create_and_unshift_one(aTHX_ &PL_endav, MUTABLE_SV(cv));
8912             } else
8913                 return FALSE;
8914         } else if (*name == 'U') {
8915             if (strEQ(name, "UNITCHECK")) {
8916                 /* It's never too late to run a unitcheck block */
8917                 Perl_av_create_and_unshift_one(aTHX_ &PL_unitcheckav, MUTABLE_SV(cv));
8918             }
8919             else
8920                 return FALSE;
8921         } else if (*name == 'C') {
8922             if (strEQ(name, "CHECK")) {
8923                 if (PL_main_start)
8924                     /* diag_listed_as: Too late to run %s block */
8925                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
8926                                    "Too late to run CHECK block");
8927                 Perl_av_create_and_unshift_one(aTHX_ &PL_checkav, MUTABLE_SV(cv));
8928             }
8929             else
8930                 return FALSE;
8931         } else if (*name == 'I') {
8932             if (strEQ(name, "INIT")) {
8933                 if (PL_main_start)
8934                     /* diag_listed_as: Too late to run %s block */
8935                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
8936                                    "Too late to run INIT block");
8937                 Perl_av_create_and_push(aTHX_ &PL_initav, MUTABLE_SV(cv));
8938             }
8939             else
8940                 return FALSE;
8941         } else
8942             return FALSE;
8943         DEBUG_x( dump_sub(gv) );
8944         (void)CvGV(cv);
8945         GvCV_set(gv,0);         /* cv has been hijacked */
8946         return FALSE;
8947     }
8948 }
8949
8950 /*
8951 =for apidoc newCONSTSUB
8952
8953 See L</newCONSTSUB_flags>.
8954
8955 =cut
8956 */
8957
8958 CV *
8959 Perl_newCONSTSUB(pTHX_ HV *stash, const char *name, SV *sv)
8960 {
8961     return newCONSTSUB_flags(stash, name, name ? strlen(name) : 0, 0, sv);
8962 }
8963
8964 /*
8965 =for apidoc newCONSTSUB_flags
8966
8967 Creates a constant sub equivalent to Perl C<sub FOO () { 123 }> which is
8968 eligible for inlining at compile-time.
8969
8970 Currently, the only useful value for C<flags> is SVf_UTF8.
8971
8972 The newly created subroutine takes ownership of a reference to the passed in
8973 SV.
8974
8975 Passing NULL for SV creates a constant sub equivalent to C<sub BAR () {}>,
8976 which won't be called if used as a destructor, but will suppress the overhead
8977 of a call to C<AUTOLOAD>.  (This form, however, isn't eligible for inlining at
8978 compile time.)
8979
8980 =cut
8981 */
8982
8983 CV *
8984 Perl_newCONSTSUB_flags(pTHX_ HV *stash, const char *name, STRLEN len,
8985                              U32 flags, SV *sv)
8986 {
8987     CV* cv;
8988     const char *const file = CopFILE(PL_curcop);
8989
8990     ENTER;
8991
8992     if (IN_PERL_RUNTIME) {
8993         /* at runtime, it's not safe to manipulate PL_curcop: it may be
8994          * an op shared between threads. Use a non-shared COP for our
8995          * dirty work */
8996          SAVEVPTR(PL_curcop);
8997          SAVECOMPILEWARNINGS();
8998          PL_compiling.cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
8999          PL_curcop = &PL_compiling;
9000     }
9001     SAVECOPLINE(PL_curcop);
9002     CopLINE_set(PL_curcop, PL_parser ? PL_parser->copline : NOLINE);
9003
9004     SAVEHINTS();
9005     PL_hints &= ~HINT_BLOCK_SCOPE;
9006
9007     if (stash) {
9008         SAVEGENERICSV(PL_curstash);
9009         PL_curstash = (HV *)SvREFCNT_inc_simple_NN(stash);
9010     }
9011
9012     /* Protect sv against leakage caused by fatal warnings. */
9013     if (sv) SAVEFREESV(sv);
9014
9015     /* file becomes the CvFILE. For an XS, it's usually static storage,
9016        and so doesn't get free()d.  (It's expected to be from the C pre-
9017        processor __FILE__ directive). But we need a dynamically allocated one,
9018        and we need it to get freed.  */
9019     cv = newXS_len_flags(name, len,
9020                          sv && SvTYPE(sv) == SVt_PVAV
9021                              ? const_av_xsub
9022                              : const_sv_xsub,
9023                          file ? file : "", "",
9024                          &sv, XS_DYNAMIC_FILENAME | flags);
9025     CvXSUBANY(cv).any_ptr = SvREFCNT_inc_simple(sv);
9026     CvCONST_on(cv);
9027
9028     LEAVE;
9029
9030     return cv;
9031 }
9032
9033 /*
9034 =for apidoc U||newXS
9035
9036 Used by C<xsubpp> to hook up XSUBs as Perl subs.  I<filename> needs to be
9037 static storage, as it is used directly as CvFILE(), without a copy being made.
9038
9039 =cut
9040 */
9041
9042 CV *
9043 Perl_newXS(pTHX_ const char *name, XSUBADDR_t subaddr, const char *filename)
9044 {
9045     PERL_ARGS_ASSERT_NEWXS;
9046     return newXS_len_flags(
9047         name, name ? strlen(name) : 0, subaddr, filename, NULL, NULL, 0
9048     );
9049 }
9050
9051 CV *
9052 Perl_newXS_flags(pTHX_ const char *name, XSUBADDR_t subaddr,
9053                  const char *const filename, const char *const proto,
9054                  U32 flags)
9055 {
9056     PERL_ARGS_ASSERT_NEWXS_FLAGS;
9057     return newXS_len_flags(
9058        name, name ? strlen(name) : 0, subaddr, filename, proto, NULL, flags
9059     );
9060 }
9061
9062 CV *
9063 Perl_newXS_deffile(pTHX_ const char *name, XSUBADDR_t subaddr)
9064 {
9065     PERL_ARGS_ASSERT_NEWXS_DEFFILE;
9066     return newXS_len_flags(
9067         name, name ? strlen(name) : 0, subaddr, NULL, NULL, NULL, 0
9068     );
9069 }
9070
9071 CV *
9072 Perl_newXS_len_flags(pTHX_ const char *name, STRLEN len,
9073                            XSUBADDR_t subaddr, const char *const filename,
9074                            const char *const proto, SV **const_svp,
9075                            U32 flags)
9076 {
9077     CV *cv;
9078     bool interleave = FALSE;
9079
9080     PERL_ARGS_ASSERT_NEWXS_LEN_FLAGS;
9081     if (!subaddr)
9082         Perl_croak_nocontext("panic: no address for '%s' in '%s'",
9083             name, filename ? filename : PL_xsubfilename);
9084     {
9085         GV * const gv = gv_fetchpvn(
9086                             name ? name : PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
9087                             name ? len : PL_curstash ? sizeof("__ANON__") - 1:
9088                                 sizeof("__ANON__::__ANON__") - 1,
9089                             GV_ADDMULTI | flags, SVt_PVCV);
9090
9091         if ((cv = (name ? GvCV(gv) : NULL))) {
9092             if (GvCVGEN(gv)) {
9093                 /* just a cached method */
9094                 SvREFCNT_dec(cv);
9095                 cv = NULL;
9096             }
9097             else if (CvROOT(cv) || CvXSUB(cv) || GvASSUMECV(gv)) {
9098                 /* already defined (or promised) */
9099                 /* Redundant check that allows us to avoid creating an SV
9100                    most of the time: */
9101                 if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
9102                     report_redefined_cv(newSVpvn_flags(
9103                                          name,len,(flags&SVf_UTF8)|SVs_TEMP
9104                                         ),
9105                                         cv, const_svp);
9106                 }
9107                 interleave = TRUE;
9108                 ENTER;
9109                 SAVEFREESV(cv);
9110                 cv = NULL;
9111             }
9112         }
9113     
9114         if (cv)                         /* must reuse cv if autoloaded */
9115             cv_undef(cv);
9116         else {
9117             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
9118             if (name) {
9119                 GvCV_set(gv,cv);
9120                 GvCVGEN(gv) = 0;
9121                 if (HvENAME_HEK(GvSTASH(gv)))
9122                     gv_method_changed(gv); /* newXS */
9123             }
9124         }
9125
9126         CvGV_set(cv, gv);
9127         if(filename) {
9128             (void)gv_fetchfile(filename);
9129             assert(!CvDYNFILE(cv)); /* cv_undef should have turned it off */
9130             if (flags & XS_DYNAMIC_FILENAME) {
9131                 CvDYNFILE_on(cv);
9132                 CvFILE(cv) = savepv(filename);
9133             } else {
9134             /* NOTE: not copied, as it is expected to be an external constant string */
9135                 CvFILE(cv) = (char *)filename;
9136             }
9137         } else {
9138             assert((flags & XS_DYNAMIC_FILENAME) == 0 && PL_xsubfilename);
9139             CvFILE(cv) = (char*)PL_xsubfilename;
9140         }
9141         CvISXSUB_on(cv);
9142         CvXSUB(cv) = subaddr;
9143 #ifndef PERL_IMPLICIT_CONTEXT
9144         CvHSCXT(cv) = &PL_stack_sp;
9145 #else
9146         PoisonPADLIST(cv);
9147 #endif
9148
9149         if (name)
9150             process_special_blocks(0, name, gv, cv);
9151         else
9152             CvANON_on(cv);
9153     } /* <- not a conditional branch */
9154
9155
9156     sv_setpv(MUTABLE_SV(cv), proto);
9157     if (interleave) LEAVE;
9158     return cv;
9159 }
9160
9161 CV *
9162 Perl_newSTUB(pTHX_ GV *gv, bool fake)
9163 {
9164     CV *cv = MUTABLE_CV(newSV_type(SVt_PVCV));
9165     GV *cvgv;
9166     PERL_ARGS_ASSERT_NEWSTUB;
9167     assert(!GvCVu(gv));
9168     GvCV_set(gv, cv);
9169     GvCVGEN(gv) = 0;
9170     if (!fake && HvENAME_HEK(GvSTASH(gv)))
9171         gv_method_changed(gv);
9172     if (SvFAKE(gv)) {
9173         cvgv = gv_fetchsv((SV *)gv, GV_ADDMULTI, SVt_PVCV);
9174         SvFAKE_off(cvgv);
9175     }
9176     else cvgv = gv;
9177     CvGV_set(cv, cvgv);
9178     CvFILE_set_from_cop(cv, PL_curcop);
9179     CvSTASH_set(cv, PL_curstash);
9180     GvMULTI_on(gv);
9181     return cv;
9182 }
9183
9184 void
9185 Perl_newFORM(pTHX_ I32 floor, OP *o, OP *block)
9186 {
9187     CV *cv;
9188
9189     GV *gv;
9190
9191     if (PL_parser && PL_parser->error_count) {
9192         op_free(block);
9193         goto finish;
9194     }
9195
9196     gv = o
9197         ? gv_fetchsv(cSVOPo->op_sv, GV_ADD, SVt_PVFM)
9198         : gv_fetchpvs("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVFM);
9199
9200     GvMULTI_on(gv);
9201     if ((cv = GvFORM(gv))) {
9202         if (ckWARN(WARN_REDEFINE)) {
9203             const line_t oldline = CopLINE(PL_curcop);
9204             if (PL_parser && PL_parser->copline != NOLINE)
9205                 CopLINE_set(PL_curcop, PL_parser->copline);
9206             if (o) {
9207                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
9208                             "Format %"SVf" redefined", SVfARG(cSVOPo->op_sv));
9209             } else {
9210                 /* diag_listed_as: Format %s redefined */
9211                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
9212                             "Format STDOUT redefined");
9213             }
9214             CopLINE_set(PL_curcop, oldline);
9215         }
9216         SvREFCNT_dec(cv);
9217     }
9218     cv = PL_compcv;
9219     GvFORM(gv) = (CV *)SvREFCNT_inc_simple_NN(cv);
9220     CvGV_set(cv, gv);
9221     CvFILE_set_from_cop(cv, PL_curcop);
9222
9223
9224     pad_tidy(padtidy_FORMAT);
9225     CvROOT(cv) = newUNOP(OP_LEAVEWRITE, 0, scalarseq(block));
9226     CvROOT(cv)->op_private |= OPpREFCOUNTED;
9227     OpREFCNT_set(CvROOT(cv), 1);
9228     CvSTART(cv) = LINKLIST(CvROOT(cv));
9229     CvROOT(cv)->op_next = 0;
9230     CALL_PEEP(CvSTART(cv));
9231     finalize_optree(CvROOT(cv));
9232     S_prune_chain_head(&CvSTART(cv));
9233     cv_forget_slab(cv);
9234
9235   finish:
9236     op_free(o);
9237     if (PL_parser)
9238         PL_parser->copline = NOLINE;
9239     LEAVE_SCOPE(floor);
9240     PL_compiling.cop_seq = 0;
9241 }
9242
9243 OP *
9244 Perl_newANONLIST(pTHX_ OP *o)
9245 {
9246     return op_convert_list(OP_ANONLIST, OPf_SPECIAL, o);
9247 }
9248
9249 OP *
9250 Perl_newANONHASH(pTHX_ OP *o)
9251 {
9252     return op_convert_list(OP_ANONHASH, OPf_SPECIAL, o);
9253 }
9254
9255 OP *
9256 Perl_newANONSUB(pTHX_ I32 floor, OP *proto, OP *block)
9257 {
9258     return newANONATTRSUB(floor, proto, NULL, block);
9259 }
9260
9261 OP *
9262 Perl_newANONATTRSUB(pTHX_ I32 floor, OP *proto, OP *attrs, OP *block)
9263 {
9264     SV * const cv = MUTABLE_SV(newATTRSUB(floor, 0, proto, attrs, block));
9265     OP * anoncode = 
9266         newSVOP(OP_ANONCODE, 0,
9267                 cv);
9268     if (CvANONCONST(cv))
9269         anoncode = newUNOP(OP_ANONCONST, 0,
9270                            op_convert_list(OP_ENTERSUB,
9271                                            OPf_STACKED|OPf_WANT_SCALAR,
9272                                            anoncode));
9273     return newUNOP(OP_REFGEN, 0, anoncode);
9274 }
9275
9276 OP *
9277 Perl_oopsAV(pTHX_ OP *o)
9278 {
9279     dVAR;
9280
9281     PERL_ARGS_ASSERT_OOPSAV;
9282
9283     switch (o->op_type) {
9284     case OP_PADSV:
9285     case OP_PADHV:
9286         CHANGE_TYPE(o, OP_PADAV);
9287         return ref(o, OP_RV2AV);
9288
9289     case OP_RV2SV:
9290     case OP_RV2HV:
9291         CHANGE_TYPE(o, OP_RV2AV);
9292         ref(o, OP_RV2AV);
9293         break;
9294
9295     default:
9296         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsAV");
9297         break;
9298     }
9299     return o;
9300 }
9301
9302 OP *
9303 Perl_oopsHV(pTHX_ OP *o)
9304 {
9305     dVAR;
9306
9307     PERL_ARGS_ASSERT_OOPSHV;
9308
9309     switch (o->op_type) {
9310     case OP_PADSV:
9311     case OP_PADAV:
9312         CHANGE_TYPE(o, OP_PADHV);
9313         return ref(o, OP_RV2HV);
9314
9315     case OP_RV2SV:
9316     case OP_RV2AV:
9317         CHANGE_TYPE(o, OP_RV2HV);
9318         ref(o, OP_RV2HV);
9319         break;
9320
9321     default:
9322         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsHV");
9323         break;
9324     }
9325     return o;
9326 }
9327
9328 OP *
9329 Perl_newAVREF(pTHX_ OP *o)
9330 {
9331     dVAR;
9332
9333     PERL_ARGS_ASSERT_NEWAVREF;
9334
9335     if (o->op_type == OP_PADANY) {
9336         CHANGE_TYPE(o, OP_PADAV);
9337         return o;
9338     }
9339     else if ((o->op_type == OP_RV2AV || o->op_type == OP_PADAV)) {
9340         Perl_croak(aTHX_ "Can't use an array as a reference");
9341     }
9342     return newUNOP(OP_RV2AV, 0, scalar(o));
9343 }
9344
9345 OP *
9346 Perl_newGVREF(pTHX_ I32 type, OP *o)
9347 {
9348     if (type == OP_MAPSTART || type == OP_GREPSTART || type == OP_SORT)
9349         return newUNOP(OP_NULL, 0, o);
9350     return ref(newUNOP(OP_RV2GV, OPf_REF, o), type);
9351 }
9352
9353 OP *
9354 Perl_newHVREF(pTHX_ OP *o)
9355 {
9356     dVAR;
9357
9358     PERL_ARGS_ASSERT_NEWHVREF;
9359
9360     if (o->op_type == OP_PADANY) {
9361         CHANGE_TYPE(o, OP_PADHV);
9362         return o;
9363     }
9364     else if ((o->op_type == OP_RV2HV || o->op_type == OP_PADHV)) {
9365         Perl_croak(aTHX_ "Can't use a hash as a reference");
9366     }
9367     return newUNOP(OP_RV2HV, 0, scalar(o));
9368 }
9369
9370 OP *
9371 Perl_newCVREF(pTHX_ I32 flags, OP *o)
9372 {
9373     if (o->op_type == OP_PADANY) {
9374         dVAR;
9375         CHANGE_TYPE(o, OP_PADCV);
9376     }
9377     return newUNOP(OP_RV2CV, flags, scalar(o));
9378 }
9379
9380 OP *
9381 Perl_newSVREF(pTHX_ OP *o)
9382 {
9383     dVAR;
9384
9385     PERL_ARGS_ASSERT_NEWSVREF;
9386
9387     if (o->op_type == OP_PADANY) {
9388         CHANGE_TYPE(o, OP_PADSV);
9389         scalar(o);
9390         return o;
9391     }
9392     return newUNOP(OP_RV2SV, 0, scalar(o));
9393 }
9394
9395 /* Check routines. See the comments at the top of this file for details
9396  * on when these are called */
9397
9398 OP *
9399 Perl_ck_anoncode(pTHX_ OP *o)
9400 {
9401     PERL_ARGS_ASSERT_CK_ANONCODE;
9402
9403     cSVOPo->op_targ = pad_add_anon((CV*)cSVOPo->op_sv, o->op_type);
9404     cSVOPo->op_sv = NULL;
9405     return o;
9406 }
9407
9408 static void
9409 S_io_hints(pTHX_ OP *o)
9410 {
9411 #if O_BINARY != 0 || O_TEXT != 0
9412     HV * const table =
9413         PL_hints & HINT_LOCALIZE_HH ? GvHV(PL_hintgv) : NULL;;
9414     if (table) {
9415         SV **svp = hv_fetchs(table, "open_IN", FALSE);
9416         if (svp && *svp) {
9417             STRLEN len = 0;
9418             const char *d = SvPV_const(*svp, len);
9419             const I32 mode = mode_from_discipline(d, len);
9420             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
9421 #  if O_BINARY != 0
9422             if (mode & O_BINARY)
9423                 o->op_private |= OPpOPEN_IN_RAW;
9424 #  endif
9425 #  if O_TEXT != 0
9426             if (mode & O_TEXT)
9427                 o->op_private |= OPpOPEN_IN_CRLF;
9428 #  endif
9429         }
9430
9431         svp = hv_fetchs(table, "open_OUT", FALSE);
9432         if (svp && *svp) {
9433             STRLEN len = 0;
9434             const char *d = SvPV_const(*svp, len);
9435             const I32 mode = mode_from_discipline(d, len);
9436             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
9437 #  if O_BINARY != 0
9438             if (mode & O_BINARY)
9439                 o->op_private |= OPpOPEN_OUT_RAW;
9440 #  endif
9441 #  if O_TEXT != 0
9442             if (mode & O_TEXT)
9443                 o->op_private |= OPpOPEN_OUT_CRLF;
9444 #  endif
9445         }
9446     }
9447 #else
9448     PERL_UNUSED_CONTEXT;
9449     PERL_UNUSED_ARG(o);
9450 #endif
9451 }
9452
9453 OP *
9454 Perl_ck_backtick(pTHX_ OP *o)
9455 {
9456     GV *gv;
9457     OP *newop = NULL;
9458     OP *sibl;
9459     PERL_ARGS_ASSERT_CK_BACKTICK;
9460     /* qx and `` have a null pushmark; CORE::readpipe has only one kid. */
9461     if (o->op_flags & OPf_KIDS && (sibl = OpSIBLING(cUNOPo->op_first))
9462      && (gv = gv_override("readpipe",8)))
9463     {
9464         /* detach rest of siblings from o and its first child */
9465         op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
9466         newop = S_new_entersubop(aTHX_ gv, sibl);
9467     }
9468     else if (!(o->op_flags & OPf_KIDS))
9469         newop = newUNOP(OP_BACKTICK, 0, newDEFSVOP());
9470     if (newop) {
9471         op_free(o);
9472         return newop;
9473     }
9474     S_io_hints(aTHX_ o);
9475     return o;
9476 }
9477
9478 OP *
9479 Perl_ck_bitop(pTHX_ OP *o)
9480 {
9481     PERL_ARGS_ASSERT_CK_BITOP;
9482
9483     o->op_private = (U8)(PL_hints & HINT_INTEGER);
9484
9485     if (o->op_type == OP_NBIT_OR     || o->op_type == OP_SBIT_OR
9486      || o->op_type == OP_NBIT_XOR    || o->op_type == OP_SBIT_XOR
9487      || o->op_type == OP_NBIT_AND    || o->op_type == OP_SBIT_AND
9488      || o->op_type == OP_NCOMPLEMENT || o->op_type == OP_SCOMPLEMENT)
9489         Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__BITWISE),
9490                               "The bitwise feature is experimental");
9491     if (!(o->op_flags & OPf_STACKED) /* Not an assignment */
9492             && OP_IS_INFIX_BIT(o->op_type))
9493     {
9494         const OP * const left = cBINOPo->op_first;
9495         const OP * const right = OpSIBLING(left);
9496         if ((OP_IS_NUMCOMPARE(left->op_type) &&
9497                 (left->op_flags & OPf_PARENS) == 0) ||
9498             (OP_IS_NUMCOMPARE(right->op_type) &&
9499                 (right->op_flags & OPf_PARENS) == 0))
9500             Perl_ck_warner(aTHX_ packWARN(WARN_PRECEDENCE),
9501                           "Possible precedence problem on bitwise %s operator",
9502                            o->op_type ==  OP_BIT_OR
9503                          ||o->op_type == OP_NBIT_OR  ? "|"
9504                         :  o->op_type ==  OP_BIT_AND
9505                          ||o->op_type == OP_NBIT_AND ? "&"
9506                         :  o->op_type ==  OP_BIT_XOR
9507                          ||o->op_type == OP_NBIT_XOR ? "^"
9508                         :  o->op_type == OP_SBIT_OR  ? "|."
9509                         :  o->op_type == OP_SBIT_AND ? "&." : "^."
9510                            );
9511     }
9512     return o;
9513 }
9514
9515 PERL_STATIC_INLINE bool
9516 is_dollar_bracket(pTHX_ const OP * const o)
9517 {
9518     const OP *kid;
9519     PERL_UNUSED_CONTEXT;
9520     return o->op_type == OP_RV2SV && o->op_flags & OPf_KIDS
9521         && (kid = cUNOPx(o)->op_first)
9522         && kid->op_type == OP_GV
9523         && strEQ(GvNAME(cGVOPx_gv(kid)), "[");
9524 }
9525
9526 OP *
9527 Perl_ck_cmp(pTHX_ OP *o)
9528 {
9529     PERL_ARGS_ASSERT_CK_CMP;
9530     if (ckWARN(WARN_SYNTAX)) {
9531         const OP *kid = cUNOPo->op_first;
9532         if (kid &&
9533             (
9534                 (   is_dollar_bracket(aTHX_ kid)
9535                  && OpSIBLING(kid) && OpSIBLING(kid)->op_type == OP_CONST
9536                 )
9537              || (   kid->op_type == OP_CONST
9538                  && (kid = OpSIBLING(kid)) && is_dollar_bracket(aTHX_ kid)
9539                 )
9540            )
9541         )
9542             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
9543                         "$[ used in %s (did you mean $] ?)", OP_DESC(o));
9544     }
9545     return o;
9546 }
9547
9548 OP *
9549 Perl_ck_concat(pTHX_ OP *o)
9550 {
9551     const OP * const kid = cUNOPo->op_first;
9552
9553     PERL_ARGS_ASSERT_CK_CONCAT;
9554     PERL_UNUSED_CONTEXT;
9555
9556     if (kid->op_type == OP_CONCAT && !(kid->op_private & OPpTARGET_MY) &&
9557             !(kUNOP->op_first->op_flags & OPf_MOD))
9558         o->op_flags |= OPf_STACKED;
9559     return o;
9560 }
9561
9562 OP *
9563 Perl_ck_spair(pTHX_ OP *o)
9564 {
9565     dVAR;
9566
9567     PERL_ARGS_ASSERT_CK_SPAIR;
9568
9569     if (o->op_flags & OPf_KIDS) {
9570         OP* newop;
9571         OP* kid;
9572         OP* kidkid;
9573         const OPCODE type = o->op_type;
9574         o = modkids(ck_fun(o), type);
9575         kid    = cUNOPo->op_first;
9576         kidkid = kUNOP->op_first;
9577         newop = OpSIBLING(kidkid);
9578         if (newop) {
9579             const OPCODE type = newop->op_type;
9580             if (OpHAS_SIBLING(newop))
9581                 return o;
9582             if (o->op_type == OP_REFGEN
9583              && (  type == OP_RV2CV
9584                 || (  !(newop->op_flags & OPf_PARENS)
9585                    && (  type == OP_RV2AV || type == OP_PADAV
9586                       || type == OP_RV2HV || type == OP_PADHV))))
9587                 NOOP; /* OK (allow srefgen for \@a and \%h) */
9588             else if (OP_GIMME(newop,0) != G_SCALAR)
9589                 return o;
9590         }
9591         /* excise first sibling */
9592         op_sibling_splice(kid, NULL, 1, NULL);
9593         op_free(kidkid);
9594     }
9595     /* transforms OP_REFGEN into OP_SREFGEN, OP_CHOP into OP_SCHOP,
9596      * and OP_CHOMP into OP_SCHOMP */
9597     o->op_ppaddr = PL_ppaddr[++o->op_type];
9598     return ck_fun(o);
9599 }
9600
9601 OP *
9602 Perl_ck_delete(pTHX_ OP *o)
9603 {
9604     PERL_ARGS_ASSERT_CK_DELETE;
9605
9606     o = ck_fun(o);
9607     o->op_private = 0;
9608     if (o->op_flags & OPf_KIDS) {
9609         OP * const kid = cUNOPo->op_first;
9610         switch (kid->op_type) {
9611         case OP_ASLICE:
9612             o->op_flags |= OPf_SPECIAL;
9613             /* FALLTHROUGH */
9614         case OP_HSLICE:
9615             o->op_private |= OPpSLICE;
9616             break;
9617         case OP_AELEM:
9618             o->op_flags |= OPf_SPECIAL;
9619             /* FALLTHROUGH */
9620         case OP_HELEM:
9621             break;
9622         case OP_KVASLICE:
9623             Perl_croak(aTHX_ "delete argument is index/value array slice,"
9624                              " use array slice");
9625         case OP_KVHSLICE:
9626             Perl_croak(aTHX_ "delete argument is key/value hash slice, use"
9627                              " hash slice");
9628         default:
9629             Perl_croak(aTHX_ "delete argument is not a HASH or ARRAY "
9630                              "element or slice");
9631         }
9632         if (kid->op_private & OPpLVAL_INTRO)
9633             o->op_private |= OPpLVAL_INTRO;
9634         op_null(kid);
9635     }
9636     return o;
9637 }
9638
9639 OP *
9640 Perl_ck_eof(pTHX_ OP *o)
9641 {
9642     PERL_ARGS_ASSERT_CK_EOF;
9643
9644     if (o->op_flags & OPf_KIDS) {
9645         OP *kid;
9646         if (cLISTOPo->op_first->op_type == OP_STUB) {
9647             OP * const newop
9648                 = newUNOP(o->op_type, OPf_SPECIAL, newGVOP(OP_GV, 0, PL_argvgv));
9649             op_free(o);
9650             o = newop;
9651         }
9652         o = ck_fun(o);
9653         kid = cLISTOPo->op_first;
9654         if (kid->op_type == OP_RV2GV)
9655             kid->op_private |= OPpALLOW_FAKE;
9656     }
9657     return o;
9658 }
9659
9660 OP *
9661 Perl_ck_eval(pTHX_ OP *o)
9662 {
9663     dVAR;
9664
9665     PERL_ARGS_ASSERT_CK_EVAL;
9666
9667     PL_hints |= HINT_BLOCK_SCOPE;
9668     if (o->op_flags & OPf_KIDS) {
9669         SVOP * const kid = (SVOP*)cUNOPo->op_first;
9670         assert(kid);
9671
9672         if (o->op_type == OP_ENTERTRY) {
9673             LOGOP *enter;
9674
9675             /* cut whole sibling chain free from o */
9676             op_sibling_splice(o, NULL, -1, NULL);
9677             op_free(o);
9678
9679             enter = S_alloc_LOGOP(aTHX_ OP_ENTERTRY, NULL, NULL);
9680
9681             /* establish postfix order */
9682             enter->op_next = (OP*)enter;
9683
9684             o = op_prepend_elem(OP_LINESEQ, (OP*)enter, (OP*)kid);
9685             CHANGE_TYPE(o, OP_LEAVETRY);
9686             enter->op_other = o;
9687             return o;
9688         }
9689         else {
9690             scalar((OP*)kid);
9691             S_set_haseval(aTHX);
9692         }
9693     }
9694     else {
9695         const U8 priv = o->op_private;
9696         op_free(o);
9697         /* the newUNOP will recursively call ck_eval(), which will handle
9698          * all the stuff at the end of this function, like adding
9699          * OP_HINTSEVAL
9700          */
9701         return newUNOP(OP_ENTEREVAL, priv <<8, newDEFSVOP());
9702     }
9703     o->op_targ = (PADOFFSET)PL_hints;
9704     if (o->op_private & OPpEVAL_BYTES) o->op_targ &= ~HINT_UTF8;
9705     if ((PL_hints & HINT_LOCALIZE_HH) != 0
9706      && !(o->op_private & OPpEVAL_COPHH) && GvHV(PL_hintgv)) {
9707         /* Store a copy of %^H that pp_entereval can pick up. */
9708         OP *hhop = newSVOP(OP_HINTSEVAL, 0,
9709                            MUTABLE_SV(hv_copy_hints_hv(GvHV(PL_hintgv))));
9710         /* append hhop to only child  */
9711         op_sibling_splice(o, cUNOPo->op_first, 0, hhop);
9712
9713         o->op_private |= OPpEVAL_HAS_HH;
9714     }
9715     if (!(o->op_private & OPpEVAL_BYTES)
9716          && FEATURE_UNIEVAL_IS_ENABLED)
9717             o->op_private |= OPpEVAL_UNICODE;
9718     return o;
9719 }
9720
9721 OP *
9722 Perl_ck_exec(pTHX_ OP *o)
9723 {
9724     PERL_ARGS_ASSERT_CK_EXEC;
9725
9726     if (o->op_flags & OPf_STACKED) {
9727         OP *kid;
9728         o = ck_fun(o);
9729         kid = OpSIBLING(cUNOPo->op_first);
9730         if (kid->op_type == OP_RV2GV)
9731             op_null(kid);
9732     }
9733     else
9734         o = listkids(o);
9735     return o;
9736 }
9737
9738 OP *
9739 Perl_ck_exists(pTHX_ OP *o)
9740 {
9741     PERL_ARGS_ASSERT_CK_EXISTS;
9742
9743     o = ck_fun(o);
9744     if (o->op_flags & OPf_KIDS) {
9745         OP * const kid = cUNOPo->op_first;
9746         if (kid->op_type == OP_ENTERSUB) {
9747             (void) ref(kid, o->op_type);
9748             if (kid->op_type != OP_RV2CV
9749                         && !(PL_parser && PL_parser->error_count))
9750                 Perl_croak(aTHX_
9751                           "exists argument is not a subroutine name");
9752             o->op_private |= OPpEXISTS_SUB;
9753         }
9754         else if (kid->op_type == OP_AELEM)
9755             o->op_flags |= OPf_SPECIAL;
9756         else if (kid->op_type != OP_HELEM)
9757             Perl_croak(aTHX_ "exists argument is not a HASH or ARRAY "
9758                              "element or a subroutine");
9759         op_null(kid);
9760     }
9761     return o;
9762 }
9763
9764 OP *
9765 Perl_ck_rvconst(pTHX_ OP *o)
9766 {
9767     dVAR;
9768     SVOP * const kid = (SVOP*)cUNOPo->op_first;
9769
9770     PERL_ARGS_ASSERT_CK_RVCONST;
9771
9772     o->op_private |= (PL_hints & HINT_STRICT_REFS);
9773
9774     if (kid->op_type == OP_CONST) {
9775         int iscv;
9776         GV *gv;
9777         SV * const kidsv = kid->op_sv;
9778
9779         /* Is it a constant from cv_const_sv()? */
9780         if ((SvROK(kidsv) || isGV_with_GP(kidsv)) && SvREADONLY(kidsv)) {
9781             return o;
9782         }
9783         if (SvTYPE(kidsv) == SVt_PVAV) return o;
9784         if ((o->op_private & HINT_STRICT_REFS) && (kid->op_private & OPpCONST_BARE)) {
9785             const char *badthing;
9786             switch (o->op_type) {
9787             case OP_RV2SV:
9788                 badthing = "a SCALAR";
9789                 break;
9790             case OP_RV2AV:
9791                 badthing = "an ARRAY";
9792                 break;
9793             case OP_RV2HV:
9794                 badthing = "a HASH";
9795                 break;
9796             default:
9797                 badthing = NULL;
9798                 break;
9799             }
9800             if (badthing)
9801                 Perl_croak(aTHX_
9802                            "Can't use bareword (\"%"SVf"\") as %s ref while \"strict refs\" in use",
9803                            SVfARG(kidsv), badthing);
9804         }
9805         /*
9806          * This is a little tricky.  We only want to add the symbol if we
9807          * didn't add it in the lexer.  Otherwise we get duplicate strict
9808          * warnings.  But if we didn't add it in the lexer, we must at
9809          * least pretend like we wanted to add it even if it existed before,
9810          * or we get possible typo warnings.  OPpCONST_ENTERED says
9811          * whether the lexer already added THIS instance of this symbol.
9812          */
9813         iscv = o->op_type == OP_RV2CV ? GV_NOEXPAND|GV_ADDMULTI : 0;
9814         gv = gv_fetchsv(kidsv,
9815                 o->op_type == OP_RV2CV
9816                         && o->op_private & OPpMAY_RETURN_CONSTANT
9817                     ? GV_NOEXPAND
9818                     : iscv | !(kid->op_private & OPpCONST_ENTERED),
9819                 iscv
9820                     ? SVt_PVCV
9821                     : o->op_type == OP_RV2SV
9822                         ? SVt_PV
9823                         : o->op_type == OP_RV2AV
9824                             ? SVt_PVAV
9825                             : o->op_type == OP_RV2HV
9826                                 ? SVt_PVHV
9827                                 : SVt_PVGV);
9828         if (gv) {
9829             if (!isGV(gv)) {
9830                 assert(iscv);
9831                 assert(SvROK(gv));
9832                 if (!(o->op_private & OPpMAY_RETURN_CONSTANT)
9833                   && SvTYPE(SvRV(gv)) != SVt_PVCV)
9834                     gv_fetchsv(kidsv, GV_ADDMULTI, SVt_PVCV);
9835             }
9836             CHANGE_TYPE(kid, OP_GV);
9837             SvREFCNT_dec(kid->op_sv);
9838 #ifdef USE_ITHREADS
9839             /* XXX hack: dependence on sizeof(PADOP) <= sizeof(SVOP) */
9840             STATIC_ASSERT_STMT(sizeof(PADOP) <= sizeof(SVOP));
9841             kPADOP->op_padix = pad_alloc(OP_GV, SVf_READONLY);
9842             SvREFCNT_dec(PAD_SVl(kPADOP->op_padix));
9843             PAD_SETSV(kPADOP->op_padix, MUTABLE_SV(SvREFCNT_inc_simple_NN(gv)));
9844 #else
9845             kid->op_sv = SvREFCNT_inc_simple_NN(gv);
9846 #endif
9847             kid->op_private = 0;
9848             /* FAKE globs in the symbol table cause weird bugs (#77810) */
9849             SvFAKE_off(gv);
9850         }
9851     }
9852     return o;
9853 }
9854
9855 OP *
9856 Perl_ck_ftst(pTHX_ OP *o)
9857 {
9858     dVAR;
9859     const I32 type = o->op_type;
9860
9861     PERL_ARGS_ASSERT_CK_FTST;
9862
9863     if (o->op_flags & OPf_REF) {
9864         NOOP;
9865     }
9866     else if (o->op_flags & OPf_KIDS && cUNOPo->op_first->op_type != OP_STUB) {
9867         SVOP * const kid = (SVOP*)cUNOPo->op_first;
9868         const OPCODE kidtype = kid->op_type;
9869
9870         if (kidtype == OP_CONST && (kid->op_private & OPpCONST_BARE)
9871          && !kid->op_folded) {
9872             OP * const newop = newGVOP(type, OPf_REF,
9873                 gv_fetchsv(kid->op_sv, GV_ADD, SVt_PVIO));
9874             op_free(o);
9875             return newop;
9876         }
9877         if ((PL_hints & HINT_FILETEST_ACCESS) && OP_IS_FILETEST_ACCESS(o->op_type))
9878             o->op_private |= OPpFT_ACCESS;
9879         if (PL_check[kidtype] == Perl_ck_ftst
9880                 && kidtype != OP_STAT && kidtype != OP_LSTAT) {
9881             o->op_private |= OPpFT_STACKED;
9882             kid->op_private |= OPpFT_STACKING;
9883             if (kidtype == OP_FTTTY && (
9884                    !(kid->op_private & OPpFT_STACKED)
9885                 || kid->op_private & OPpFT_AFTER_t
9886                ))
9887                 o->op_private |= OPpFT_AFTER_t;
9888         }
9889     }
9890     else {
9891         op_free(o);
9892         if (type == OP_FTTTY)
9893             o = newGVOP(type, OPf_REF, PL_stdingv);
9894         else
9895             o = newUNOP(type, 0, newDEFSVOP());
9896     }
9897     return o;
9898 }
9899
9900 OP *
9901 Perl_ck_fun(pTHX_ OP *o)
9902 {
9903     const int type = o->op_type;
9904     I32 oa = PL_opargs[type] >> OASHIFT;
9905
9906     PERL_ARGS_ASSERT_CK_FUN;
9907
9908     if (o->op_flags & OPf_STACKED) {
9909         if ((oa & OA_OPTIONAL) && (oa >> 4) && !((oa >> 4) & OA_OPTIONAL))
9910             oa &= ~OA_OPTIONAL;
9911         else
9912             return no_fh_allowed(o);
9913     }
9914
9915     if (o->op_flags & OPf_KIDS) {
9916         OP *prev_kid = NULL;
9917         OP *kid = cLISTOPo->op_first;
9918         I32 numargs = 0;
9919         bool seen_optional = FALSE;
9920
9921         if (kid->op_type == OP_PUSHMARK ||
9922             (kid->op_type == OP_NULL && kid->op_targ == OP_PUSHMARK))
9923         {
9924             prev_kid = kid;
9925             kid = OpSIBLING(kid);
9926         }
9927         if (kid && kid->op_type == OP_COREARGS) {
9928             bool optional = FALSE;
9929             while (oa) {
9930                 numargs++;
9931                 if (oa & OA_OPTIONAL) optional = TRUE;
9932                 oa = oa >> 4;
9933             }
9934             if (optional) o->op_private |= numargs;
9935             return o;
9936         }
9937
9938         while (oa) {
9939             if (oa & OA_OPTIONAL || (oa & 7) == OA_LIST) {
9940                 if (!kid && !seen_optional && PL_opargs[type] & OA_DEFGV) {
9941                     kid = newDEFSVOP();
9942                     /* append kid to chain */
9943                     op_sibling_splice(o, prev_kid, 0, kid);
9944                 }
9945                 seen_optional = TRUE;
9946             }
9947             if (!kid) break;
9948
9949             numargs++;
9950             switch (oa & 7) {
9951             case OA_SCALAR:
9952                 /* list seen where single (scalar) arg expected? */
9953                 if (numargs == 1 && !(oa >> 4)
9954                     && kid->op_type == OP_LIST && type != OP_SCALAR)
9955                 {
9956                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
9957                 }
9958                 if (type != OP_DELETE) scalar(kid);
9959                 break;
9960             case OA_LIST:
9961                 if (oa < 16) {
9962                     kid = 0;
9963                     continue;
9964                 }
9965                 else
9966                     list(kid);
9967                 break;
9968             case OA_AVREF:
9969                 if ((type == OP_PUSH || type == OP_UNSHIFT)
9970                     && !OpHAS_SIBLING(kid))
9971                     Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
9972                                    "Useless use of %s with no values",
9973                                    PL_op_desc[type]);
9974
9975                 if (kid->op_type == OP_CONST
9976                       && (  !SvROK(cSVOPx_sv(kid)) 
9977                          || SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV  )
9978                         )
9979                     bad_type_pv(numargs, "array", o, kid);
9980                 /* Defer checks to run-time if we have a scalar arg */
9981                 if (kid->op_type == OP_RV2AV || kid->op_type == OP_PADAV)
9982                     op_lvalue(kid, type);
9983                 else {
9984                     scalar(kid);
9985                     /* diag_listed_as: push on reference is experimental */
9986                     Perl_ck_warner_d(aTHX_
9987                                      packWARN(WARN_EXPERIMENTAL__AUTODEREF),
9988                                     "%s on reference is experimental",
9989                                      PL_op_desc[type]);
9990                 }
9991                 break;
9992             case OA_HVREF:
9993                 if (kid->op_type != OP_RV2HV && kid->op_type != OP_PADHV)
9994                     bad_type_pv(numargs, "hash", o, kid);
9995                 op_lvalue(kid, type);
9996                 break;
9997             case OA_CVREF:
9998                 {
9999                     /* replace kid with newop in chain */
10000                     OP * const newop =
10001                         S_op_sibling_newUNOP(aTHX_ o, prev_kid, OP_NULL, 0);
10002                     newop->op_next = newop;
10003                     kid = newop;
10004                 }
10005                 break;
10006             case OA_FILEREF:
10007                 if (kid->op_type != OP_GV && kid->op_type != OP_RV2GV) {
10008                     if (kid->op_type == OP_CONST &&
10009                         (kid->op_private & OPpCONST_BARE))
10010                     {
10011                         OP * const newop = newGVOP(OP_GV, 0,
10012                             gv_fetchsv(((SVOP*)kid)->op_sv, GV_ADD, SVt_PVIO));
10013                         /* replace kid with newop in chain */
10014                         op_sibling_splice(o, prev_kid, 1, newop);
10015                         op_free(kid);
10016                         kid = newop;
10017                     }
10018                     else if (kid->op_type == OP_READLINE) {
10019                         /* neophyte patrol: open(<FH>), close(<FH>) etc. */
10020                         bad_type_pv(numargs, "HANDLE", o, kid);
10021                     }
10022                     else {
10023                         I32 flags = OPf_SPECIAL;
10024                         I32 priv = 0;
10025                         PADOFFSET targ = 0;
10026
10027                         /* is this op a FH constructor? */
10028                         if (is_handle_constructor(o,numargs)) {
10029                             const char *name = NULL;
10030                             STRLEN len = 0;
10031                             U32 name_utf8 = 0;
10032                             bool want_dollar = TRUE;
10033
10034                             flags = 0;
10035                             /* Set a flag to tell rv2gv to vivify
10036                              * need to "prove" flag does not mean something
10037                              * else already - NI-S 1999/05/07
10038                              */
10039                             priv = OPpDEREF;
10040                             if (kid->op_type == OP_PADSV) {
10041                                 PADNAME * const pn
10042                                     = PAD_COMPNAME_SV(kid->op_targ);
10043                                 name = PadnamePV (pn);
10044                                 len  = PadnameLEN(pn);
10045                                 name_utf8 = PadnameUTF8(pn);
10046                             }
10047                             else if (kid->op_type == OP_RV2SV
10048                                      && kUNOP->op_first->op_type == OP_GV)
10049                             {
10050                                 GV * const gv = cGVOPx_gv(kUNOP->op_first);
10051                                 name = GvNAME(gv);
10052                                 len = GvNAMELEN(gv);
10053                                 name_utf8 = GvNAMEUTF8(gv) ? SVf_UTF8 : 0;
10054                             }
10055                             else if (kid->op_type == OP_AELEM
10056                                      || kid->op_type == OP_HELEM)
10057                             {
10058                                  OP *firstop;
10059                                  OP *op = ((BINOP*)kid)->op_first;
10060                                  name = NULL;
10061                                  if (op) {
10062                                       SV *tmpstr = NULL;
10063                                       const char * const a =
10064                                            kid->op_type == OP_AELEM ?
10065                                            "[]" : "{}";
10066                                       if (((op->op_type == OP_RV2AV) ||
10067                                            (op->op_type == OP_RV2HV)) &&
10068                                           (firstop = ((UNOP*)op)->op_first) &&
10069                                           (firstop->op_type == OP_GV)) {
10070                                            /* packagevar $a[] or $h{} */
10071                                            GV * const gv = cGVOPx_gv(firstop);
10072                                            if (gv)
10073                                                 tmpstr =
10074                                                      Perl_newSVpvf(aTHX_
10075                                                                    "%s%c...%c",
10076                                                                    GvNAME(gv),
10077                                                                    a[0], a[1]);
10078                                       }
10079                                       else if (op->op_type == OP_PADAV
10080                                                || op->op_type == OP_PADHV) {
10081                                            /* lexicalvar $a[] or $h{} */
10082                                            const char * const padname =
10083                                                 PAD_COMPNAME_PV(op->op_targ);
10084                                            if (padname)
10085                                                 tmpstr =
10086                                                      Perl_newSVpvf(aTHX_
10087                                                                    "%s%c...%c",
10088                                                                    padname + 1,
10089                                                                    a[0], a[1]);
10090                                       }
10091                                       if (tmpstr) {
10092                                            name = SvPV_const(tmpstr, len);
10093                                            name_utf8 = SvUTF8(tmpstr);
10094                                            sv_2mortal(tmpstr);
10095                                       }
10096                                  }
10097                                  if (!name) {
10098                                       name = "__ANONIO__";
10099                                       len = 10;
10100                                       want_dollar = FALSE;
10101                                  }
10102                                  op_lvalue(kid, type);
10103                             }
10104                             if (name) {
10105                                 SV *namesv;
10106                                 targ = pad_alloc(OP_RV2GV, SVf_READONLY);
10107                                 namesv = PAD_SVl(targ);
10108                                 if (want_dollar && *name != '$')
10109                                     sv_setpvs(namesv, "$");
10110                                 else
10111                                     sv_setpvs(namesv, "");
10112                                 sv_catpvn(namesv, name, len);
10113                                 if ( name_utf8 ) SvUTF8_on(namesv);
10114                             }
10115                         }
10116                         scalar(kid);
10117                         kid = S_op_sibling_newUNOP(aTHX_ o, prev_kid,
10118                                     OP_RV2GV, flags);
10119                         kid->op_targ = targ;
10120                         kid->op_private |= priv;
10121                     }
10122                 }
10123                 scalar(kid);
10124                 break;
10125             case OA_SCALARREF:
10126                 if ((type == OP_UNDEF || type == OP_POS)
10127                     && numargs == 1 && !(oa >> 4)
10128                     && kid->op_type == OP_LIST)
10129                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
10130                 op_lvalue(scalar(kid), type);
10131                 break;
10132             }
10133             oa >>= 4;
10134             prev_kid = kid;
10135             kid = OpSIBLING(kid);
10136         }
10137         /* FIXME - should the numargs or-ing move after the too many
10138          * arguments check? */
10139         o->op_private |= numargs;
10140         if (kid)
10141             return too_many_arguments_pv(o,OP_DESC(o), 0);
10142         listkids(o);
10143     }
10144     else if (PL_opargs[type] & OA_DEFGV) {
10145         /* Ordering of these two is important to keep f_map.t passing.  */
10146         op_free(o);
10147         return newUNOP(type, 0, newDEFSVOP());
10148     }
10149
10150     if (oa) {
10151         while (oa & OA_OPTIONAL)
10152             oa >>= 4;
10153         if (oa && oa != OA_LIST)
10154             return too_few_arguments_pv(o,OP_DESC(o), 0);
10155     }
10156     return o;
10157 }
10158
10159 OP *
10160 Perl_ck_glob(pTHX_ OP *o)
10161 {
10162     GV *gv;
10163
10164     PERL_ARGS_ASSERT_CK_GLOB;
10165
10166     o = ck_fun(o);
10167     if ((o->op_flags & OPf_KIDS) && !OpHAS_SIBLING(cLISTOPo->op_first))
10168         op_append_elem(OP_GLOB, o, newDEFSVOP()); /* glob() => glob($_) */
10169
10170     if (!(o->op_flags & OPf_SPECIAL) && (gv = gv_override("glob", 4)))
10171     {
10172         /* convert
10173          *     glob
10174          *       \ null - const(wildcard)
10175          * into
10176          *     null
10177          *       \ enter
10178          *            \ list
10179          *                 \ mark - glob - rv2cv
10180          *                             |        \ gv(CORE::GLOBAL::glob)
10181          *                             |
10182          *                              \ null - const(wildcard)
10183          */
10184         o->op_flags |= OPf_SPECIAL;
10185         o->op_targ = pad_alloc(OP_GLOB, SVs_PADTMP);
10186         o = S_new_entersubop(aTHX_ gv, o);
10187         o = newUNOP(OP_NULL, 0, o);
10188         o->op_targ = OP_GLOB; /* hint at what it used to be: eg in newWHILEOP */
10189         return o;
10190     }
10191     else o->op_flags &= ~OPf_SPECIAL;
10192 #if !defined(PERL_EXTERNAL_GLOB)
10193     if (!PL_globhook) {
10194         ENTER;
10195         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
10196                                newSVpvs("File::Glob"), NULL, NULL, NULL);
10197         LEAVE;
10198     }
10199 #endif /* !PERL_EXTERNAL_GLOB */
10200     gv = (GV *)newSV(0);
10201     gv_init(gv, 0, "", 0, 0);
10202     gv_IOadd(gv);
10203     op_append_elem(OP_GLOB, o, newGVOP(OP_GV, 0, gv));
10204     SvREFCNT_dec_NN(gv); /* newGVOP increased it */
10205     scalarkids(o);
10206     return o;
10207 }
10208
10209 OP *
10210 Perl_ck_grep(pTHX_ OP *o)
10211 {
10212     LOGOP *gwop;
10213     OP *kid;
10214     const OPCODE type = o->op_type == OP_GREPSTART ? OP_GREPWHILE : OP_MAPWHILE;
10215     PADOFFSET offset;
10216
10217     PERL_ARGS_ASSERT_CK_GREP;
10218
10219     /* don't allocate gwop here, as we may leak it if PL_parser->error_count > 0 */
10220
10221     if (o->op_flags & OPf_STACKED) {
10222         kid = cUNOPx(OpSIBLING(cLISTOPo->op_first))->op_first;
10223         if (kid->op_type != OP_SCOPE && kid->op_type != OP_LEAVE)
10224             return no_fh_allowed(o);
10225         o->op_flags &= ~OPf_STACKED;
10226     }
10227     kid = OpSIBLING(cLISTOPo->op_first);
10228     if (type == OP_MAPWHILE)
10229         list(kid);
10230     else
10231         scalar(kid);
10232     o = ck_fun(o);
10233     if (PL_parser && PL_parser->error_count)
10234         return o;
10235     kid = OpSIBLING(cLISTOPo->op_first);
10236     if (kid->op_type != OP_NULL)
10237         Perl_croak(aTHX_ "panic: ck_grep, type=%u", (unsigned) kid->op_type);
10238     kid = kUNOP->op_first;
10239
10240     gwop = S_alloc_LOGOP(aTHX_ type, o, LINKLIST(kid));
10241     kid->op_next = (OP*)gwop;
10242     offset = pad_findmy_pvs("$_", 0);
10243     if (offset == NOT_IN_PAD || PAD_COMPNAME_FLAGS_isOUR(offset)) {
10244         o->op_private = gwop->op_private = 0;
10245         gwop->op_targ = pad_alloc(type, SVs_PADTMP);
10246     }
10247     else {
10248         o->op_private = gwop->op_private = OPpGREP_LEX;
10249         gwop->op_targ = o->op_targ = offset;
10250     }
10251
10252     kid = OpSIBLING(cLISTOPo->op_first);
10253     for (kid = OpSIBLING(kid); kid; kid = OpSIBLING(kid))
10254         op_lvalue(kid, OP_GREPSTART);
10255
10256     return (OP*)gwop;
10257 }
10258
10259 OP *
10260 Perl_ck_index(pTHX_ OP *o)
10261 {
10262     PERL_ARGS_ASSERT_CK_INDEX;
10263
10264     if (o->op_flags & OPf_KIDS) {
10265         OP *kid = OpSIBLING(cLISTOPo->op_first);        /* get past pushmark */
10266         if (kid)
10267             kid = OpSIBLING(kid);                       /* get past "big" */
10268         if (kid && kid->op_type == OP_CONST) {
10269             const bool save_taint = TAINT_get;
10270             SV *sv = kSVOP->op_sv;
10271             if ((!SvPOK(sv) || SvNIOKp(sv)) && SvOK(sv) && !SvROK(sv)) {
10272                 sv = newSV(0);
10273                 sv_copypv(sv, kSVOP->op_sv);
10274                 SvREFCNT_dec_NN(kSVOP->op_sv);
10275                 kSVOP->op_sv = sv;
10276             }
10277             if (SvOK(sv)) fbm_compile(sv, 0);
10278             TAINT_set(save_taint);
10279 #ifdef NO_TAINT_SUPPORT
10280             PERL_UNUSED_VAR(save_taint);
10281 #endif
10282         }
10283     }
10284     return ck_fun(o);
10285 }
10286
10287 OP *
10288 Perl_ck_lfun(pTHX_ OP *o)
10289 {
10290     const OPCODE type = o->op_type;
10291
10292     PERL_ARGS_ASSERT_CK_LFUN;
10293
10294     return modkids(ck_fun(o), type);
10295 }
10296
10297 OP *
10298 Perl_ck_defined(pTHX_ OP *o)            /* 19990527 MJD */
10299 {
10300     PERL_ARGS_ASSERT_CK_DEFINED;
10301
10302     if ((o->op_flags & OPf_KIDS)) {
10303         switch (cUNOPo->op_first->op_type) {
10304         case OP_RV2AV:
10305         case OP_PADAV:
10306             Perl_croak(aTHX_ "Can't use 'defined(@array)'"
10307                              " (Maybe you should just omit the defined()?)");
10308         break;
10309         case OP_RV2HV:
10310         case OP_PADHV:
10311             Perl_croak(aTHX_ "Can't use 'defined(%%hash)'"
10312                              " (Maybe you should just omit the defined()?)");
10313             break;
10314         default:
10315             /* no warning */
10316             break;
10317         }
10318     }
10319     return ck_rfun(o);
10320 }
10321
10322 OP *
10323 Perl_ck_readline(pTHX_ OP *o)
10324 {
10325     PERL_ARGS_ASSERT_CK_READLINE;
10326
10327     if (o->op_flags & OPf_KIDS) {
10328          OP *kid = cLISTOPo->op_first;
10329          if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
10330     }
10331     else {
10332         OP * const newop
10333             = newUNOP(OP_READLINE, o->op_flags | OPf_SPECIAL, newGVOP(OP_GV, 0, PL_argvgv));
10334         op_free(o);
10335         return newop;
10336     }
10337     return o;
10338 }
10339
10340 OP *
10341 Perl_ck_rfun(pTHX_ OP *o)
10342 {
10343     const OPCODE type = o->op_type;
10344
10345     PERL_ARGS_ASSERT_CK_RFUN;
10346
10347     return refkids(ck_fun(o), type);
10348 }
10349
10350 OP *
10351 Perl_ck_listiob(pTHX_ OP *o)
10352 {
10353     OP *kid;
10354
10355     PERL_ARGS_ASSERT_CK_LISTIOB;
10356
10357     kid = cLISTOPo->op_first;
10358     if (!kid) {
10359         o = force_list(o, 1);
10360         kid = cLISTOPo->op_first;
10361     }
10362     if (kid->op_type == OP_PUSHMARK)
10363         kid = OpSIBLING(kid);
10364     if (kid && o->op_flags & OPf_STACKED)
10365         kid = OpSIBLING(kid);
10366     else if (kid && !OpHAS_SIBLING(kid)) {              /* print HANDLE; */
10367         if (kid->op_type == OP_CONST && kid->op_private & OPpCONST_BARE
10368          && !kid->op_folded) {
10369             o->op_flags |= OPf_STACKED; /* make it a filehandle */
10370             scalar(kid);
10371             /* replace old const op with new OP_RV2GV parent */
10372             kid = S_op_sibling_newUNOP(aTHX_ o, cLISTOPo->op_first,
10373                                         OP_RV2GV, OPf_REF);
10374             kid = OpSIBLING(kid);
10375         }
10376     }
10377
10378     if (!kid)
10379         op_append_elem(o->op_type, o, newDEFSVOP());
10380
10381     if (o->op_type == OP_PRTF) return modkids(listkids(o), OP_PRTF);
10382     return listkids(o);
10383 }
10384
10385 OP *
10386 Perl_ck_smartmatch(pTHX_ OP *o)
10387 {
10388     dVAR;
10389     PERL_ARGS_ASSERT_CK_SMARTMATCH;
10390     if (0 == (o->op_flags & OPf_SPECIAL)) {
10391         OP *first  = cBINOPo->op_first;
10392         OP *second = OpSIBLING(first);
10393         
10394         /* Implicitly take a reference to an array or hash */
10395
10396         /* remove the original two siblings, then add back the
10397          * (possibly different) first and second sibs.
10398          */
10399         op_sibling_splice(o, NULL, 1, NULL);
10400         op_sibling_splice(o, NULL, 1, NULL);
10401         first  = ref_array_or_hash(first);
10402         second = ref_array_or_hash(second);
10403         op_sibling_splice(o, NULL, 0, second);
10404         op_sibling_splice(o, NULL, 0, first);
10405         
10406         /* Implicitly take a reference to a regular expression */
10407         if (first->op_type == OP_MATCH) {
10408             CHANGE_TYPE(first, OP_QR);
10409         }
10410         if (second->op_type == OP_MATCH) {
10411             CHANGE_TYPE(second, OP_QR);
10412         }
10413     }
10414     
10415     return o;
10416 }
10417
10418
10419 static OP *
10420 S_maybe_targlex(pTHX_ OP *o)
10421 {
10422     OP * const kid = cLISTOPo->op_first;
10423     /* has a disposable target? */
10424     if ((PL_opargs[kid->op_type] & OA_TARGLEX)
10425         && !(kid->op_flags & OPf_STACKED)
10426         /* Cannot steal the second time! */
10427         && !(kid->op_private & OPpTARGET_MY)
10428         )
10429     {
10430         OP * const kkid = OpSIBLING(kid);
10431
10432         /* Can just relocate the target. */
10433         if (kkid && kkid->op_type == OP_PADSV
10434             && (!(kkid->op_private & OPpLVAL_INTRO)
10435                || kkid->op_private & OPpPAD_STATE))
10436         {
10437             kid->op_targ = kkid->op_targ;
10438             kkid->op_targ = 0;
10439             /* Now we do not need PADSV and SASSIGN.
10440              * Detach kid and free the rest. */
10441             op_sibling_splice(o, NULL, 1, NULL);
10442             op_free(o);
10443             kid->op_private |= OPpTARGET_MY;    /* Used for context settings */
10444             return kid;
10445         }
10446     }
10447     return o;
10448 }
10449
10450 OP *
10451 Perl_ck_sassign(pTHX_ OP *o)
10452 {
10453     dVAR;
10454     OP * const kid = cLISTOPo->op_first;
10455
10456     PERL_ARGS_ASSERT_CK_SASSIGN;
10457
10458     if (OpHAS_SIBLING(kid)) {
10459         OP *kkid = OpSIBLING(kid);
10460         /* For state variable assignment with attributes, kkid is a list op
10461            whose op_last is a padsv. */
10462         if ((kkid->op_type == OP_PADSV ||
10463              (OP_TYPE_IS_OR_WAS(kkid, OP_LIST) &&
10464               (kkid = cLISTOPx(kkid)->op_last)->op_type == OP_PADSV
10465              )
10466             )
10467                 && (kkid->op_private & (OPpLVAL_INTRO|OPpPAD_STATE))
10468                     == (OPpLVAL_INTRO|OPpPAD_STATE)) {
10469             const PADOFFSET target = kkid->op_targ;
10470             OP *const other = newOP(OP_PADSV,
10471                                     kkid->op_flags
10472                                     | ((kkid->op_private & ~OPpLVAL_INTRO) << 8));
10473             OP *const first = newOP(OP_NULL, 0);
10474             OP *const nullop =
10475                 newCONDOP(0, first, S_maybe_targlex(aTHX_ o), other);
10476             OP *const condop = first->op_next;
10477
10478             CHANGE_TYPE(condop, OP_ONCE);
10479             other->op_targ = target;
10480             nullop->op_flags |= OPf_WANT_SCALAR;
10481
10482             /* Store the initializedness of state vars in a separate
10483                pad entry.  */
10484             condop->op_targ =
10485               pad_add_name_pvn("$",1,padadd_NO_DUP_CHECK|padadd_STATE,0,0);
10486             /* hijacking PADSTALE for uninitialized state variables */
10487             SvPADSTALE_on(PAD_SVl(condop->op_targ));
10488
10489             return nullop;
10490         }
10491     }
10492     return S_maybe_targlex(aTHX_ o);
10493 }
10494
10495 OP *
10496 Perl_ck_match(pTHX_ OP *o)
10497 {
10498     PERL_ARGS_ASSERT_CK_MATCH;
10499
10500     if (o->op_type != OP_QR && PL_compcv) {
10501         const PADOFFSET offset = pad_findmy_pvs("$_", 0);
10502         if (offset != NOT_IN_PAD && !(PAD_COMPNAME_FLAGS_isOUR(offset))) {
10503             o->op_targ = offset;
10504             o->op_private |= OPpTARGET_MY;
10505         }
10506     }
10507     if (o->op_type == OP_MATCH || o->op_type == OP_QR)
10508         o->op_private |= OPpRUNTIME;
10509     return o;
10510 }
10511
10512 OP *
10513 Perl_ck_method(pTHX_ OP *o)
10514 {
10515     SV *sv, *methsv, *rclass;
10516     const char* method;
10517     char* compatptr;
10518     int utf8;
10519     STRLEN len, nsplit = 0, i;
10520     OP* new_op;
10521     OP * const kid = cUNOPo->op_first;
10522
10523     PERL_ARGS_ASSERT_CK_METHOD;
10524     if (kid->op_type != OP_CONST) return o;
10525
10526     sv = kSVOP->op_sv;
10527
10528     /* replace ' with :: */
10529     while ((compatptr = strchr(SvPVX(sv), '\''))) {
10530         *compatptr = ':';
10531         sv_insert(sv, compatptr - SvPVX_const(sv), 0, ":", 1);
10532     }
10533
10534     method = SvPVX_const(sv);
10535     len = SvCUR(sv);
10536     utf8 = SvUTF8(sv) ? -1 : 1;
10537
10538     for (i = len - 1; i > 0; --i) if (method[i] == ':') {
10539         nsplit = i+1;
10540         break;
10541     }
10542
10543     methsv = newSVpvn_share(method+nsplit, utf8*(len - nsplit), 0);
10544
10545     if (!nsplit) { /* $proto->method() */
10546         op_free(o);
10547         return newMETHOP_named(OP_METHOD_NAMED, 0, methsv);
10548     }
10549
10550     if (nsplit == 7 && memEQ(method, "SUPER::", nsplit)) { /* $proto->SUPER::method() */
10551         op_free(o);
10552         return newMETHOP_named(OP_METHOD_SUPER, 0, methsv);
10553     }
10554
10555     /* $proto->MyClass::method() and $proto->MyClass::SUPER::method() */
10556     if (nsplit >= 9 && strnEQ(method+nsplit-9, "::SUPER::", 9)) {
10557         rclass = newSVpvn_share(method, utf8*(nsplit-9), 0);
10558         new_op = newMETHOP_named(OP_METHOD_REDIR_SUPER, 0, methsv);
10559     } else {
10560         rclass = newSVpvn_share(method, utf8*(nsplit-2), 0);
10561         new_op = newMETHOP_named(OP_METHOD_REDIR, 0, methsv);
10562     }
10563 #ifdef USE_ITHREADS
10564     op_relocate_sv(&rclass, &cMETHOPx(new_op)->op_rclass_targ);
10565 #else
10566     cMETHOPx(new_op)->op_rclass_sv = rclass;
10567 #endif
10568     op_free(o);
10569     return new_op;
10570 }
10571
10572 OP *
10573 Perl_ck_null(pTHX_ OP *o)
10574 {
10575     PERL_ARGS_ASSERT_CK_NULL;
10576     PERL_UNUSED_CONTEXT;
10577     return o;
10578 }
10579
10580 OP *
10581 Perl_ck_open(pTHX_ OP *o)
10582 {
10583     PERL_ARGS_ASSERT_CK_OPEN;
10584
10585     S_io_hints(aTHX_ o);
10586     {
10587          /* In case of three-arg dup open remove strictness
10588           * from the last arg if it is a bareword. */
10589          OP * const first = cLISTOPx(o)->op_first; /* The pushmark. */
10590          OP * const last  = cLISTOPx(o)->op_last;  /* The bareword. */
10591          OP *oa;
10592          const char *mode;
10593
10594          if ((last->op_type == OP_CONST) &&             /* The bareword. */
10595              (last->op_private & OPpCONST_BARE) &&
10596              (last->op_private & OPpCONST_STRICT) &&
10597              (oa = OpSIBLING(first)) &&         /* The fh. */
10598              (oa = OpSIBLING(oa)) &&                    /* The mode. */
10599              (oa->op_type == OP_CONST) &&
10600              SvPOK(((SVOP*)oa)->op_sv) &&
10601              (mode = SvPVX_const(((SVOP*)oa)->op_sv)) &&
10602              mode[0] == '>' && mode[1] == '&' &&        /* A dup open. */
10603              (last == OpSIBLING(oa)))                   /* The bareword. */
10604               last->op_private &= ~OPpCONST_STRICT;
10605     }
10606     return ck_fun(o);
10607 }
10608
10609 OP *
10610 Perl_ck_prototype(pTHX_ OP *o)
10611 {
10612     PERL_ARGS_ASSERT_CK_PROTOTYPE;
10613     if (!(o->op_flags & OPf_KIDS)) {
10614         op_free(o);
10615         return newUNOP(OP_PROTOTYPE, 0, newDEFSVOP());
10616     }
10617     return o;
10618 }
10619
10620 OP *
10621 Perl_ck_refassign(pTHX_ OP *o)
10622 {
10623     OP * const right = cLISTOPo->op_first;
10624     OP * const left = OpSIBLING(right);
10625     OP *varop = cUNOPx(cUNOPx(left)->op_first)->op_first;
10626     bool stacked = 0;
10627
10628     PERL_ARGS_ASSERT_CK_REFASSIGN;
10629     assert (left);
10630     assert (left->op_type == OP_SREFGEN);
10631
10632     o->op_private = varop->op_private & (OPpLVAL_INTRO|OPpPAD_STATE);
10633
10634     switch (varop->op_type) {
10635     case OP_PADAV:
10636         o->op_private |= OPpLVREF_AV;
10637         goto settarg;
10638     case OP_PADHV:
10639         o->op_private |= OPpLVREF_HV;
10640     case OP_PADSV:
10641       settarg:
10642         o->op_targ = varop->op_targ;
10643         varop->op_targ = 0;
10644         PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
10645         break;
10646     case OP_RV2AV:
10647         o->op_private |= OPpLVREF_AV;
10648         goto checkgv;
10649     case OP_RV2HV:
10650         o->op_private |= OPpLVREF_HV;
10651     case OP_RV2SV:
10652       checkgv:
10653         if (cUNOPx(varop)->op_first->op_type != OP_GV) goto bad;
10654       detach_and_stack:
10655         /* Point varop to its GV kid, detached.  */
10656         varop = op_sibling_splice(varop, NULL, -1, NULL);
10657         stacked = TRUE;
10658         break;
10659     case OP_RV2CV: {
10660         OP * const kidparent =
10661             cUNOPx(cUNOPx(varop)->op_first)->op_first->op_sibling;
10662         OP * const kid = cUNOPx(kidparent)->op_first;
10663         o->op_private |= OPpLVREF_CV;
10664         if (kid->op_type == OP_GV) {
10665             varop = kidparent;
10666             goto detach_and_stack;
10667         }
10668         if (kid->op_type != OP_PADCV)   goto bad;
10669         o->op_targ = kid->op_targ;
10670         kid->op_targ = 0;
10671         break;
10672     }
10673     case OP_AELEM:
10674     case OP_HELEM:
10675         o->op_private |= OPpLVREF_ELEM;
10676         op_null(varop);
10677         stacked = TRUE;
10678         /* Detach varop.  */
10679         op_sibling_splice(cUNOPx(left)->op_first, NULL, -1, NULL);
10680         break;
10681     default:
10682       bad:
10683         /* diag_listed_as: Can't modify reference to %s in %s assignment */
10684         yyerror(Perl_form(aTHX_ "Can't modify reference to %s in scalar "
10685                                 "assignment",
10686                                  OP_DESC(varop)));
10687         return o;
10688     }
10689     if (!FEATURE_REFALIASING_IS_ENABLED)
10690         Perl_croak(aTHX_
10691                   "Experimental aliasing via reference not enabled");
10692     Perl_ck_warner_d(aTHX_
10693                      packWARN(WARN_EXPERIMENTAL__REFALIASING),
10694                     "Aliasing via reference is experimental");
10695     if (stacked) {
10696         o->op_flags |= OPf_STACKED;
10697         op_sibling_splice(o, right, 1, varop);
10698     }
10699     else {
10700         o->op_flags &=~ OPf_STACKED;
10701         op_sibling_splice(o, right, 1, NULL);
10702     }
10703     op_free(left);
10704     return o;
10705 }
10706
10707 OP *
10708 Perl_ck_repeat(pTHX_ OP *o)
10709 {
10710     PERL_ARGS_ASSERT_CK_REPEAT;
10711
10712     if (cBINOPo->op_first->op_flags & OPf_PARENS) {
10713         OP* kids;
10714         o->op_private |= OPpREPEAT_DOLIST;
10715         kids = op_sibling_splice(o, NULL, 1, NULL); /* detach first kid */
10716         kids = force_list(kids, 1); /* promote it to a list */
10717         op_sibling_splice(o, NULL, 0, kids); /* and add back */
10718     }
10719     else
10720         scalar(o);
10721     return o;
10722 }
10723
10724 OP *
10725 Perl_ck_require(pTHX_ OP *o)
10726 {
10727     GV* gv;
10728
10729     PERL_ARGS_ASSERT_CK_REQUIRE;
10730
10731     if (o->op_flags & OPf_KIDS) {       /* Shall we supply missing .pm? */
10732         SVOP * const kid = (SVOP*)cUNOPo->op_first;
10733         HEK *hek;
10734         U32 hash;
10735         char *s;
10736         STRLEN len;
10737         if (kid->op_type == OP_CONST) {
10738           SV * const sv = kid->op_sv;
10739           U32 const was_readonly = SvREADONLY(sv);
10740           if (kid->op_private & OPpCONST_BARE) {
10741             dVAR;
10742             const char *end;
10743
10744             if (was_readonly) {
10745                     SvREADONLY_off(sv);
10746             }   
10747             if (SvIsCOW(sv)) sv_force_normal_flags(sv, 0);
10748
10749             s = SvPVX(sv);
10750             len = SvCUR(sv);
10751             end = s + len;
10752             for (; s < end; s++) {
10753                 if (*s == ':' && s[1] == ':') {
10754                     *s = '/';
10755                     Move(s+2, s+1, end - s - 1, char);
10756                     --end;
10757                 }
10758             }
10759             SvEND_set(sv, end);
10760             sv_catpvs(sv, ".pm");
10761             PERL_HASH(hash, SvPVX(sv), SvCUR(sv));
10762             hek = share_hek(SvPVX(sv),
10763                             (SSize_t)SvCUR(sv) * (SvUTF8(sv) ? -1 : 1),
10764                             hash);
10765             sv_sethek(sv, hek);
10766             unshare_hek(hek);
10767             SvFLAGS(sv) |= was_readonly;
10768           }
10769           else if (SvPOK(sv) && !SvNIOK(sv) && !SvGMAGICAL(sv)) {
10770             s = SvPV(sv, len);
10771             if (SvREFCNT(sv) > 1) {
10772                 kid->op_sv = newSVpvn_share(
10773                     s, SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len, 0);
10774                 SvREFCNT_dec_NN(sv);
10775             }
10776             else {
10777                 dVAR;
10778                 if (was_readonly) SvREADONLY_off(sv);
10779                 PERL_HASH(hash, s, len);
10780                 hek = share_hek(s,
10781                                 SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len,
10782                                 hash);
10783                 sv_sethek(sv, hek);
10784                 unshare_hek(hek);
10785                 SvFLAGS(sv) |= was_readonly;
10786             }
10787           }
10788         }
10789     }
10790
10791     if (!(o->op_flags & OPf_SPECIAL) /* Wasn't written as CORE::require */
10792         /* handle override, if any */
10793      && (gv = gv_override("require", 7))) {
10794         OP *kid, *newop;
10795         if (o->op_flags & OPf_KIDS) {
10796             kid = cUNOPo->op_first;
10797             op_sibling_splice(o, NULL, -1, NULL);
10798         }
10799         else {
10800             kid = newDEFSVOP();
10801         }
10802         op_free(o);
10803         newop = S_new_entersubop(aTHX_ gv, kid);
10804         return newop;
10805     }
10806
10807     return ck_fun(o);
10808 }
10809
10810 OP *
10811 Perl_ck_return(pTHX_ OP *o)
10812 {
10813     OP *kid;
10814
10815     PERL_ARGS_ASSERT_CK_RETURN;
10816
10817     kid = OpSIBLING(cLISTOPo->op_first);
10818     if (CvLVALUE(PL_compcv)) {
10819         for (; kid; kid = OpSIBLING(kid))
10820             op_lvalue(kid, OP_LEAVESUBLV);
10821     }
10822
10823     return o;
10824 }
10825
10826 OP *
10827 Perl_ck_select(pTHX_ OP *o)
10828 {
10829     dVAR;
10830     OP* kid;
10831
10832     PERL_ARGS_ASSERT_CK_SELECT;
10833
10834     if (o->op_flags & OPf_KIDS) {
10835         kid = OpSIBLING(cLISTOPo->op_first);     /* get past pushmark */
10836         if (kid && OpHAS_SIBLING(kid)) {
10837             CHANGE_TYPE(o, OP_SSELECT);
10838             o = ck_fun(o);
10839             return fold_constants(op_integerize(op_std_init(o)));
10840         }
10841     }
10842     o = ck_fun(o);
10843     kid = OpSIBLING(cLISTOPo->op_first);    /* get past pushmark */
10844     if (kid && kid->op_type == OP_RV2GV)
10845         kid->op_private &= ~HINT_STRICT_REFS;
10846     return o;
10847 }
10848
10849 OP *
10850 Perl_ck_shift(pTHX_ OP *o)
10851 {
10852     const I32 type = o->op_type;
10853
10854     PERL_ARGS_ASSERT_CK_SHIFT;
10855
10856     if (!(o->op_flags & OPf_KIDS)) {
10857         OP *argop;
10858
10859         if (!CvUNIQUE(PL_compcv)) {
10860             o->op_flags |= OPf_SPECIAL;
10861             return o;
10862         }
10863
10864         argop = newUNOP(OP_RV2AV, 0, scalar(newGVOP(OP_GV, 0, PL_argvgv)));
10865         op_free(o);
10866         return newUNOP(type, 0, scalar(argop));
10867     }
10868     return scalar(ck_fun(o));
10869 }
10870
10871 OP *
10872 Perl_ck_sort(pTHX_ OP *o)
10873 {
10874     OP *firstkid;
10875     OP *kid;
10876     HV * const hinthv =
10877         PL_hints & HINT_LOCALIZE_HH ? GvHV(PL_hintgv) : NULL;
10878     U8 stacked;
10879
10880     PERL_ARGS_ASSERT_CK_SORT;
10881
10882     if (hinthv) {
10883             SV ** const svp = hv_fetchs(hinthv, "sort", FALSE);
10884             if (svp) {
10885                 const I32 sorthints = (I32)SvIV(*svp);
10886                 if ((sorthints & HINT_SORT_QUICKSORT) != 0)
10887                     o->op_private |= OPpSORT_QSORT;
10888                 if ((sorthints & HINT_SORT_STABLE) != 0)
10889                     o->op_private |= OPpSORT_STABLE;
10890             }
10891     }
10892
10893     if (o->op_flags & OPf_STACKED)
10894         simplify_sort(o);
10895     firstkid = OpSIBLING(cLISTOPo->op_first);           /* get past pushmark */
10896
10897     if ((stacked = o->op_flags & OPf_STACKED)) {        /* may have been cleared */
10898         OP *kid = cUNOPx(firstkid)->op_first;           /* get past null */
10899
10900         /* if the first arg is a code block, process it and mark sort as
10901          * OPf_SPECIAL */
10902         if (kid->op_type == OP_SCOPE || kid->op_type == OP_LEAVE) {
10903             LINKLIST(kid);
10904             if (kid->op_type == OP_LEAVE)
10905                     op_null(kid);                       /* wipe out leave */
10906             /* Prevent execution from escaping out of the sort block. */
10907             kid->op_next = 0;
10908
10909             /* provide scalar context for comparison function/block */
10910             kid = scalar(firstkid);
10911             kid->op_next = kid;
10912             o->op_flags |= OPf_SPECIAL;
10913         }
10914         else if (kid->op_type == OP_CONST
10915               && kid->op_private & OPpCONST_BARE) {
10916             char tmpbuf[256];
10917             STRLEN len;
10918             PADOFFSET off;
10919             const char * const name = SvPV(kSVOP_sv, len);
10920             *tmpbuf = '&';
10921             assert (len < 256);
10922             Copy(name, tmpbuf+1, len, char);
10923             off = pad_findmy_pvn(tmpbuf, len+1, SvUTF8(kSVOP_sv));
10924             if (off != NOT_IN_PAD) {
10925                 if (PAD_COMPNAME_FLAGS_isOUR(off)) {
10926                     SV * const fq =
10927                         newSVhek(HvNAME_HEK(PAD_COMPNAME_OURSTASH(off)));
10928                     sv_catpvs(fq, "::");
10929                     sv_catsv(fq, kSVOP_sv);
10930                     SvREFCNT_dec_NN(kSVOP_sv);
10931                     kSVOP->op_sv = fq;
10932                 }
10933                 else {
10934                     OP * const padop = newOP(OP_PADCV, 0);
10935                     padop->op_targ = off;
10936                     cUNOPx(firstkid)->op_first = padop;
10937 #ifdef PERL_OP_PARENT
10938                     padop->op_sibling = firstkid;
10939 #endif
10940                     op_free(kid);
10941                 }
10942             }
10943         }
10944
10945         firstkid = OpSIBLING(firstkid);
10946     }
10947
10948     for (kid = firstkid; kid; kid = OpSIBLING(kid)) {
10949         /* provide list context for arguments */
10950         list(kid);
10951         if (stacked)
10952             op_lvalue(kid, OP_GREPSTART);
10953     }
10954
10955     return o;
10956 }
10957
10958 /* for sort { X } ..., where X is one of
10959  *   $a <=> $b, $b <= $a, $a cmp $b, $b cmp $a
10960  * elide the second child of the sort (the one containing X),
10961  * and set these flags as appropriate
10962         OPpSORT_NUMERIC;
10963         OPpSORT_INTEGER;
10964         OPpSORT_DESCEND;
10965  * Also, check and warn on lexical $a, $b.
10966  */
10967
10968 STATIC void
10969 S_simplify_sort(pTHX_ OP *o)
10970 {
10971     OP *kid = OpSIBLING(cLISTOPo->op_first);    /* get past pushmark */
10972     OP *k;
10973     int descending;
10974     GV *gv;
10975     const char *gvname;
10976     bool have_scopeop;
10977
10978     PERL_ARGS_ASSERT_SIMPLIFY_SORT;
10979
10980     kid = kUNOP->op_first;                              /* get past null */
10981     if (!(have_scopeop = kid->op_type == OP_SCOPE)
10982      && kid->op_type != OP_LEAVE)
10983         return;
10984     kid = kLISTOP->op_last;                             /* get past scope */
10985     switch(kid->op_type) {
10986         case OP_NCMP:
10987         case OP_I_NCMP:
10988         case OP_SCMP:
10989             if (!have_scopeop) goto padkids;
10990             break;
10991         default:
10992             return;
10993     }
10994     k = kid;                                            /* remember this node*/
10995     if (kBINOP->op_first->op_type != OP_RV2SV
10996      || kBINOP->op_last ->op_type != OP_RV2SV)
10997     {
10998         /*
10999            Warn about my($a) or my($b) in a sort block, *if* $a or $b is
11000            then used in a comparison.  This catches most, but not
11001            all cases.  For instance, it catches
11002                sort { my($a); $a <=> $b }
11003            but not
11004                sort { my($a); $a < $b ? -1 : $a == $b ? 0 : 1; }
11005            (although why you'd do that is anyone's guess).
11006         */
11007
11008        padkids:
11009         if (!ckWARN(WARN_SYNTAX)) return;
11010         kid = kBINOP->op_first;
11011         do {
11012             if (kid->op_type == OP_PADSV) {
11013                 PADNAME * const name = PAD_COMPNAME(kid->op_targ);
11014                 if (PadnameLEN(name) == 2 && *PadnamePV(name) == '$'
11015                  && (  PadnamePV(name)[1] == 'a'
11016                     || PadnamePV(name)[1] == 'b'  ))
11017                     /* diag_listed_as: "my %s" used in sort comparison */
11018                     Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
11019                                      "\"%s %s\" used in sort comparison",
11020                                       PadnameIsSTATE(name)
11021                                         ? "state"
11022                                         : "my",
11023                                       PadnamePV(name));
11024             }
11025         } while ((kid = OpSIBLING(kid)));
11026         return;
11027     }
11028     kid = kBINOP->op_first;                             /* get past cmp */
11029     if (kUNOP->op_first->op_type != OP_GV)
11030         return;
11031     kid = kUNOP->op_first;                              /* get past rv2sv */
11032     gv = kGVOP_gv;
11033     if (GvSTASH(gv) != PL_curstash)
11034         return;
11035     gvname = GvNAME(gv);
11036     if (*gvname == 'a' && gvname[1] == '\0')
11037         descending = 0;
11038     else if (*gvname == 'b' && gvname[1] == '\0')
11039         descending = 1;
11040     else
11041         return;
11042
11043     kid = k;                                            /* back to cmp */
11044     /* already checked above that it is rv2sv */
11045     kid = kBINOP->op_last;                              /* down to 2nd arg */
11046     if (kUNOP->op_first->op_type != OP_GV)
11047         return;
11048     kid = kUNOP->op_first;                              /* get past rv2sv */
11049     gv = kGVOP_gv;
11050     if (GvSTASH(gv) != PL_curstash)
11051         return;
11052     gvname = GvNAME(gv);
11053     if ( descending
11054          ? !(*gvname == 'a' && gvname[1] == '\0')
11055          : !(*gvname == 'b' && gvname[1] == '\0'))
11056         return;
11057     o->op_flags &= ~(OPf_STACKED | OPf_SPECIAL);
11058     if (descending)
11059         o->op_private |= OPpSORT_DESCEND;
11060     if (k->op_type == OP_NCMP)
11061         o->op_private |= OPpSORT_NUMERIC;
11062     if (k->op_type == OP_I_NCMP)
11063         o->op_private |= OPpSORT_NUMERIC | OPpSORT_INTEGER;
11064     kid = OpSIBLING(cLISTOPo->op_first);
11065     /* cut out and delete old block (second sibling) */
11066     op_sibling_splice(o, cLISTOPo->op_first, 1, NULL);
11067     op_free(kid);
11068 }
11069
11070 OP *
11071 Perl_ck_split(pTHX_ OP *o)
11072 {
11073     dVAR;
11074     OP *kid;
11075
11076     PERL_ARGS_ASSERT_CK_SPLIT;
11077
11078     if (o->op_flags & OPf_STACKED)
11079         return no_fh_allowed(o);
11080
11081     kid = cLISTOPo->op_first;
11082     if (kid->op_type != OP_NULL)
11083         Perl_croak(aTHX_ "panic: ck_split, type=%u", (unsigned) kid->op_type);
11084     /* delete leading NULL node, then add a CONST if no other nodes */
11085     op_sibling_splice(o, NULL, 1,
11086         OpHAS_SIBLING(kid) ? NULL : newSVOP(OP_CONST, 0, newSVpvs(" ")));
11087     op_free(kid);
11088     kid = cLISTOPo->op_first;
11089
11090     if (kid->op_type != OP_MATCH || kid->op_flags & OPf_STACKED) {
11091         /* remove kid, and replace with new optree */
11092         op_sibling_splice(o, NULL, 1, NULL);
11093         /* OPf_SPECIAL is used to trigger split " " behavior */
11094         kid = pmruntime( newPMOP(OP_MATCH, OPf_SPECIAL), kid, NULL, 0, 0);
11095         op_sibling_splice(o, NULL, 0, kid);
11096     }
11097     CHANGE_TYPE(kid, OP_PUSHRE);
11098     scalar(kid);
11099     if (((PMOP *)kid)->op_pmflags & PMf_GLOBAL) {
11100       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
11101                      "Use of /g modifier is meaningless in split");
11102     }
11103
11104     if (!OpHAS_SIBLING(kid))
11105         op_append_elem(OP_SPLIT, o, newDEFSVOP());
11106
11107     kid = OpSIBLING(kid);
11108     assert(kid);
11109     scalar(kid);
11110
11111     if (!OpHAS_SIBLING(kid))
11112     {
11113         op_append_elem(OP_SPLIT, o, newSVOP(OP_CONST, 0, newSViv(0)));
11114         o->op_private |= OPpSPLIT_IMPLIM;
11115     }
11116     assert(OpHAS_SIBLING(kid));
11117
11118     kid = OpSIBLING(kid);
11119     scalar(kid);
11120
11121     if (OpHAS_SIBLING(kid))
11122         return too_many_arguments_pv(o,OP_DESC(o), 0);
11123
11124     return o;
11125 }
11126
11127 OP *
11128 Perl_ck_stringify(pTHX_ OP *o)
11129 {
11130     OP * const kid = OpSIBLING(cUNOPo->op_first);
11131     PERL_ARGS_ASSERT_CK_STRINGIFY;
11132     if (kid->op_type == OP_JOIN || kid->op_type == OP_QUOTEMETA
11133      || kid->op_type == OP_LC   || kid->op_type == OP_LCFIRST
11134      || kid->op_type == OP_UC   || kid->op_type == OP_UCFIRST)
11135     {
11136         assert(!OpHAS_SIBLING(kid));
11137         op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
11138         op_free(o);
11139         return kid;
11140     }
11141     return ck_fun(o);
11142 }
11143         
11144 OP *
11145 Perl_ck_join(pTHX_ OP *o)
11146 {
11147     OP * const kid = OpSIBLING(cLISTOPo->op_first);
11148
11149     PERL_ARGS_ASSERT_CK_JOIN;
11150
11151     if (kid && kid->op_type == OP_MATCH) {
11152         if (ckWARN(WARN_SYNTAX)) {
11153             const REGEXP *re = PM_GETRE(kPMOP);
11154             const SV *msg = re
11155                     ? newSVpvn_flags( RX_PRECOMP_const(re), RX_PRELEN(re),
11156                                             SVs_TEMP | ( RX_UTF8(re) ? SVf_UTF8 : 0 ) )
11157                     : newSVpvs_flags( "STRING", SVs_TEMP );
11158             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
11159                         "/%"SVf"/ should probably be written as \"%"SVf"\"",
11160                         SVfARG(msg), SVfARG(msg));
11161         }
11162     }
11163     if (kid
11164      && (kid->op_type == OP_CONST /* an innocent, unsuspicious separator */
11165         || (kid->op_type == OP_PADSV && !(kid->op_private & OPpLVAL_INTRO))
11166         || (  kid->op_type==OP_RV2SV && kUNOP->op_first->op_type == OP_GV
11167            && !(kid->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))))
11168     {
11169         const OP * const bairn = OpSIBLING(kid); /* the list */
11170         if (bairn && !OpHAS_SIBLING(bairn) /* single-item list */
11171          && OP_GIMME(bairn,0) == G_SCALAR)
11172         {
11173             OP * const ret = op_convert_list(OP_STRINGIFY, OPf_FOLDED,
11174                                      op_sibling_splice(o, kid, 1, NULL));
11175             op_free(o);
11176             return ret;
11177         }
11178     }
11179
11180     return ck_fun(o);
11181 }
11182
11183 /*
11184 =for apidoc Am|CV *|rv2cv_op_cv|OP *cvop|U32 flags
11185
11186 Examines an op, which is expected to identify a subroutine at runtime,
11187 and attempts to determine at compile time which subroutine it identifies.
11188 This is normally used during Perl compilation to determine whether
11189 a prototype can be applied to a function call.  I<cvop> is the op
11190 being considered, normally an C<rv2cv> op.  A pointer to the identified
11191 subroutine is returned, if it could be determined statically, and a null
11192 pointer is returned if it was not possible to determine statically.
11193
11194 Currently, the subroutine can be identified statically if the RV that the
11195 C<rv2cv> is to operate on is provided by a suitable C<gv> or C<const> op.
11196 A C<gv> op is suitable if the GV's CV slot is populated.  A C<const> op is
11197 suitable if the constant value must be an RV pointing to a CV.  Details of
11198 this process may change in future versions of Perl.  If the C<rv2cv> op
11199 has the C<OPpENTERSUB_AMPER> flag set then no attempt is made to identify
11200 the subroutine statically: this flag is used to suppress compile-time
11201 magic on a subroutine call, forcing it to use default runtime behaviour.
11202
11203 If I<flags> has the bit C<RV2CVOPCV_MARK_EARLY> set, then the handling
11204 of a GV reference is modified.  If a GV was examined and its CV slot was
11205 found to be empty, then the C<gv> op has the C<OPpEARLY_CV> flag set.
11206 If the op is not optimised away, and the CV slot is later populated with
11207 a subroutine having a prototype, that flag eventually triggers the warning
11208 "called too early to check prototype".
11209
11210 If I<flags> has the bit C<RV2CVOPCV_RETURN_NAME_GV> set, then instead
11211 of returning a pointer to the subroutine it returns a pointer to the
11212 GV giving the most appropriate name for the subroutine in this context.
11213 Normally this is just the C<CvGV> of the subroutine, but for an anonymous
11214 (C<CvANON>) subroutine that is referenced through a GV it will be the
11215 referencing GV.  The resulting C<GV*> is cast to C<CV*> to be returned.
11216 A null pointer is returned as usual if there is no statically-determinable
11217 subroutine.
11218
11219 =cut
11220 */
11221
11222 /* shared by toke.c:yylex */
11223 CV *
11224 Perl_find_lexical_cv(pTHX_ PADOFFSET off)
11225 {
11226     PADNAME *name = PAD_COMPNAME(off);
11227     CV *compcv = PL_compcv;
11228     while (PadnameOUTER(name)) {
11229         assert(PARENT_PAD_INDEX(name));
11230         compcv = CvOUTSIDE(PL_compcv);
11231         name = PadlistNAMESARRAY(CvPADLIST(compcv))
11232                 [off = PARENT_PAD_INDEX(name)];
11233     }
11234     assert(!PadnameIsOUR(name));
11235     if (!PadnameIsSTATE(name) && PadnamePROTOCV(name)) {
11236         return PadnamePROTOCV(name);
11237     }
11238     return (CV *)AvARRAY(PadlistARRAY(CvPADLIST(compcv))[1])[off];
11239 }
11240
11241 CV *
11242 Perl_rv2cv_op_cv(pTHX_ OP *cvop, U32 flags)
11243 {
11244     OP *rvop;
11245     CV *cv;
11246     GV *gv;
11247     PERL_ARGS_ASSERT_RV2CV_OP_CV;
11248     if (flags & ~RV2CVOPCV_FLAG_MASK)
11249         Perl_croak(aTHX_ "panic: rv2cv_op_cv bad flags %x", (unsigned)flags);
11250     if (cvop->op_type != OP_RV2CV)
11251         return NULL;
11252     if (cvop->op_private & OPpENTERSUB_AMPER)
11253         return NULL;
11254     if (!(cvop->op_flags & OPf_KIDS))
11255         return NULL;
11256     rvop = cUNOPx(cvop)->op_first;
11257     switch (rvop->op_type) {
11258         case OP_GV: {
11259             gv = cGVOPx_gv(rvop);
11260             if (!isGV(gv)) {
11261                 if (SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV) {
11262                     cv = MUTABLE_CV(SvRV(gv));
11263                     gv = NULL;
11264                     break;
11265                 }
11266                 if (flags & RV2CVOPCV_RETURN_STUB)
11267                     return (CV *)gv;
11268                 else return NULL;
11269             }
11270             cv = GvCVu(gv);
11271             if (!cv) {
11272                 if (flags & RV2CVOPCV_MARK_EARLY)
11273                     rvop->op_private |= OPpEARLY_CV;
11274                 return NULL;
11275             }
11276         } break;
11277         case OP_CONST: {
11278             SV *rv = cSVOPx_sv(rvop);
11279             if (!SvROK(rv))
11280                 return NULL;
11281             cv = (CV*)SvRV(rv);
11282             gv = NULL;
11283         } break;
11284         case OP_PADCV: {
11285             cv = find_lexical_cv(rvop->op_targ);
11286             gv = NULL;
11287         } break;
11288         default: {
11289             return NULL;
11290         } NOT_REACHED; /* NOTREACHED */
11291     }
11292     if (SvTYPE((SV*)cv) != SVt_PVCV)
11293         return NULL;
11294     if (flags & (RV2CVOPCV_RETURN_NAME_GV|RV2CVOPCV_MAYBE_NAME_GV)) {
11295         if ((!CvANON(cv) || !gv) && !CvLEXICAL(cv)
11296          && ((flags & RV2CVOPCV_RETURN_NAME_GV) || !CvNAMED(cv)))
11297             gv = CvGV(cv);
11298         return (CV*)gv;
11299     } else {
11300         return cv;
11301     }
11302 }
11303
11304 /*
11305 =for apidoc Am|OP *|ck_entersub_args_list|OP *entersubop
11306
11307 Performs the default fixup of the arguments part of an C<entersub>
11308 op tree.  This consists of applying list context to each of the
11309 argument ops.  This is the standard treatment used on a call marked
11310 with C<&>, or a method call, or a call through a subroutine reference,
11311 or any other call where the callee can't be identified at compile time,
11312 or a call where the callee has no prototype.
11313
11314 =cut
11315 */
11316
11317 OP *
11318 Perl_ck_entersub_args_list(pTHX_ OP *entersubop)
11319 {
11320     OP *aop;
11321     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_LIST;
11322     aop = cUNOPx(entersubop)->op_first;
11323     if (!OpHAS_SIBLING(aop))
11324         aop = cUNOPx(aop)->op_first;
11325     for (aop = OpSIBLING(aop); OpHAS_SIBLING(aop); aop = OpSIBLING(aop)) {
11326         list(aop);
11327         op_lvalue(aop, OP_ENTERSUB);
11328     }
11329     return entersubop;
11330 }
11331
11332 /*
11333 =for apidoc Am|OP *|ck_entersub_args_proto|OP *entersubop|GV *namegv|SV *protosv
11334
11335 Performs the fixup of the arguments part of an C<entersub> op tree
11336 based on a subroutine prototype.  This makes various modifications to
11337 the argument ops, from applying context up to inserting C<refgen> ops,
11338 and checking the number and syntactic types of arguments, as directed by
11339 the prototype.  This is the standard treatment used on a subroutine call,
11340 not marked with C<&>, where the callee can be identified at compile time
11341 and has a prototype.
11342
11343 I<protosv> supplies the subroutine prototype to be applied to the call.
11344 It may be a normal defined scalar, of which the string value will be used.
11345 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
11346 that has been cast to C<SV*>) which has a prototype.  The prototype
11347 supplied, in whichever form, does not need to match the actual callee
11348 referenced by the op tree.
11349
11350 If the argument ops disagree with the prototype, for example by having
11351 an unacceptable number of arguments, a valid op tree is returned anyway.
11352 The error is reflected in the parser state, normally resulting in a single
11353 exception at the top level of parsing which covers all the compilation
11354 errors that occurred.  In the error message, the callee is referred to
11355 by the name defined by the I<namegv> parameter.
11356
11357 =cut
11358 */
11359
11360 OP *
11361 Perl_ck_entersub_args_proto(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
11362 {
11363     STRLEN proto_len;
11364     const char *proto, *proto_end;
11365     OP *aop, *prev, *cvop, *parent;
11366     int optional = 0;
11367     I32 arg = 0;
11368     I32 contextclass = 0;
11369     const char *e = NULL;
11370     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO;
11371     if (SvTYPE(protosv) == SVt_PVCV ? !SvPOK(protosv) : !SvOK(protosv))
11372         Perl_croak(aTHX_ "panic: ck_entersub_args_proto CV with no proto, "
11373                    "flags=%lx", (unsigned long) SvFLAGS(protosv));
11374     if (SvTYPE(protosv) == SVt_PVCV)
11375          proto = CvPROTO(protosv), proto_len = CvPROTOLEN(protosv);
11376     else proto = SvPV(protosv, proto_len);
11377     proto = S_strip_spaces(aTHX_ proto, &proto_len);
11378     proto_end = proto + proto_len;
11379     parent = entersubop;
11380     aop = cUNOPx(entersubop)->op_first;
11381     if (!OpHAS_SIBLING(aop)) {
11382         parent = aop;
11383         aop = cUNOPx(aop)->op_first;
11384     }
11385     prev = aop;
11386     aop = OpSIBLING(aop);
11387     for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
11388     while (aop != cvop) {
11389         OP* o3 = aop;
11390
11391         if (proto >= proto_end)
11392         {
11393             SV * const namesv = cv_name((CV *)namegv, NULL, 0);
11394             yyerror_pv(Perl_form(aTHX_ "Too many arguments for %"SVf,
11395                                         SVfARG(namesv)), SvUTF8(namesv));
11396             return entersubop;
11397         }
11398
11399         switch (*proto) {
11400             case ';':
11401                 optional = 1;
11402                 proto++;
11403                 continue;
11404             case '_':
11405                 /* _ must be at the end */
11406                 if (proto[1] && !strchr(";@%", proto[1]))
11407                     goto oops;
11408                 /* FALLTHROUGH */
11409             case '$':
11410                 proto++;
11411                 arg++;
11412                 scalar(aop);
11413                 break;
11414             case '%':
11415             case '@':
11416                 list(aop);
11417                 arg++;
11418                 break;
11419             case '&':
11420                 proto++;
11421                 arg++;
11422                 if (o3->op_type != OP_SREFGEN
11423                  || (  cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
11424                         != OP_ANONCODE
11425                     && cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
11426                         != OP_RV2CV))
11427                     bad_type_gv(arg, namegv, o3,
11428                             arg == 1 ? "block or sub {}" : "sub {}");
11429                 break;
11430             case '*':
11431                 /* '*' allows any scalar type, including bareword */
11432                 proto++;
11433                 arg++;
11434                 if (o3->op_type == OP_RV2GV)
11435                     goto wrapref;       /* autoconvert GLOB -> GLOBref */
11436                 else if (o3->op_type == OP_CONST)
11437                     o3->op_private &= ~OPpCONST_STRICT;
11438                 scalar(aop);
11439                 break;
11440             case '+':
11441                 proto++;
11442                 arg++;
11443                 if (o3->op_type == OP_RV2AV ||
11444                     o3->op_type == OP_PADAV ||
11445                     o3->op_type == OP_RV2HV ||
11446                     o3->op_type == OP_PADHV
11447                 ) {
11448                     goto wrapref;
11449                 }
11450                 scalar(aop);
11451                 break;
11452             case '[': case ']':
11453                 goto oops;
11454
11455             case '\\':
11456                 proto++;
11457                 arg++;
11458             again:
11459                 switch (*proto++) {
11460                     case '[':
11461                         if (contextclass++ == 0) {
11462                             e = strchr(proto, ']');
11463                             if (!e || e == proto)
11464                                 goto oops;
11465                         }
11466                         else
11467                             goto oops;
11468                         goto again;
11469
11470                     case ']':
11471                         if (contextclass) {
11472                             const char *p = proto;
11473                             const char *const end = proto;
11474                             contextclass = 0;
11475                             while (*--p != '[')
11476                                 /* \[$] accepts any scalar lvalue */
11477                                 if (*p == '$'
11478                                  && Perl_op_lvalue_flags(aTHX_
11479                                      scalar(o3),
11480                                      OP_READ, /* not entersub */
11481                                      OP_LVALUE_NO_CROAK
11482                                     )) goto wrapref;
11483                             bad_type_gv(arg, namegv, o3,
11484                                     Perl_form(aTHX_ "one of %.*s",(int)(end - p), p));
11485                         } else
11486                             goto oops;
11487                         break;
11488                     case '*':
11489                         if (o3->op_type == OP_RV2GV)
11490                             goto wrapref;
11491                         if (!contextclass)
11492                             bad_type_gv(arg, namegv, o3, "symbol");
11493                         break;
11494                     case '&':
11495                         if (o3->op_type == OP_ENTERSUB
11496                          && !(o3->op_flags & OPf_STACKED))
11497                             goto wrapref;
11498                         if (!contextclass)
11499                             bad_type_gv(arg, namegv, o3, "subroutine");
11500                         break;
11501                     case '$':
11502                         if (o3->op_type == OP_RV2SV ||
11503                                 o3->op_type == OP_PADSV ||
11504                                 o3->op_type == OP_HELEM ||
11505                                 o3->op_type == OP_AELEM)
11506                             goto wrapref;
11507                         if (!contextclass) {
11508                             /* \$ accepts any scalar lvalue */
11509                             if (Perl_op_lvalue_flags(aTHX_
11510                                     scalar(o3),
11511                                     OP_READ,  /* not entersub */
11512                                     OP_LVALUE_NO_CROAK
11513                                )) goto wrapref;
11514                             bad_type_gv(arg, namegv, o3, "scalar");
11515                         }
11516                         break;
11517                     case '@':
11518                         if (o3->op_type == OP_RV2AV ||
11519                                 o3->op_type == OP_PADAV)
11520                         {
11521                             o3->op_flags &=~ OPf_PARENS;
11522                             goto wrapref;
11523                         }
11524                         if (!contextclass)
11525                             bad_type_gv(arg, namegv, o3, "array");
11526                         break;
11527                     case '%':
11528                         if (o3->op_type == OP_RV2HV ||
11529                                 o3->op_type == OP_PADHV)
11530                         {
11531                             o3->op_flags &=~ OPf_PARENS;
11532                             goto wrapref;
11533                         }
11534                         if (!contextclass)
11535                             bad_type_gv(arg, namegv, o3, "hash");
11536                         break;
11537                     wrapref:
11538                             aop = S_op_sibling_newUNOP(aTHX_ parent, prev,
11539                                                 OP_REFGEN, 0);
11540                         if (contextclass && e) {
11541                             proto = e + 1;
11542                             contextclass = 0;
11543                         }
11544                         break;
11545                     default: goto oops;
11546                 }
11547                 if (contextclass)
11548                     goto again;
11549                 break;
11550             case ' ':
11551                 proto++;
11552                 continue;
11553             default:
11554             oops: {
11555                 Perl_croak(aTHX_ "Malformed prototype for %"SVf": %"SVf,
11556                                   SVfARG(cv_name((CV *)namegv, NULL, 0)),
11557                                   SVfARG(protosv));
11558             }
11559         }
11560
11561         op_lvalue(aop, OP_ENTERSUB);
11562         prev = aop;
11563         aop = OpSIBLING(aop);
11564     }
11565     if (aop == cvop && *proto == '_') {
11566         /* generate an access to $_ */
11567         op_sibling_splice(parent, prev, 0, newDEFSVOP());
11568     }
11569     if (!optional && proto_end > proto &&
11570         (*proto != '@' && *proto != '%' && *proto != ';' && *proto != '_'))
11571     {
11572         SV * const namesv = cv_name((CV *)namegv, NULL, 0);
11573         yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %"SVf,
11574                                     SVfARG(namesv)), SvUTF8(namesv));
11575     }
11576     return entersubop;
11577 }
11578
11579 /*
11580 =for apidoc Am|OP *|ck_entersub_args_proto_or_list|OP *entersubop|GV *namegv|SV *protosv
11581
11582 Performs the fixup of the arguments part of an C<entersub> op tree either
11583 based on a subroutine prototype or using default list-context processing.
11584 This is the standard treatment used on a subroutine call, not marked
11585 with C<&>, where the callee can be identified at compile time.
11586
11587 I<protosv> supplies the subroutine prototype to be applied to the call,
11588 or indicates that there is no prototype.  It may be a normal scalar,
11589 in which case if it is defined then the string value will be used
11590 as a prototype, and if it is undefined then there is no prototype.
11591 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
11592 that has been cast to C<SV*>), of which the prototype will be used if it
11593 has one.  The prototype (or lack thereof) supplied, in whichever form,
11594 does not need to match the actual callee referenced by the op tree.
11595
11596 If the argument ops disagree with the prototype, for example by having
11597 an unacceptable number of arguments, a valid op tree is returned anyway.
11598 The error is reflected in the parser state, normally resulting in a single
11599 exception at the top level of parsing which covers all the compilation
11600 errors that occurred.  In the error message, the callee is referred to
11601 by the name defined by the I<namegv> parameter.
11602
11603 =cut
11604 */
11605
11606 OP *
11607 Perl_ck_entersub_args_proto_or_list(pTHX_ OP *entersubop,
11608         GV *namegv, SV *protosv)
11609 {
11610     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO_OR_LIST;
11611     if (SvTYPE(protosv) == SVt_PVCV ? SvPOK(protosv) : SvOK(protosv))
11612         return ck_entersub_args_proto(entersubop, namegv, protosv);
11613     else
11614         return ck_entersub_args_list(entersubop);
11615 }
11616
11617 OP *
11618 Perl_ck_entersub_args_core(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
11619 {
11620     int opnum = SvTYPE(protosv) == SVt_PVCV ? 0 : (int)SvUV(protosv);
11621     OP *aop = cUNOPx(entersubop)->op_first;
11622
11623     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_CORE;
11624
11625     if (!opnum) {
11626         OP *cvop;
11627         if (!OpHAS_SIBLING(aop))
11628             aop = cUNOPx(aop)->op_first;
11629         aop = OpSIBLING(aop);
11630         for (cvop = aop; OpSIBLING(cvop); cvop = OpSIBLING(cvop)) ;
11631         if (aop != cvop)
11632             (void)too_many_arguments_pv(entersubop, GvNAME(namegv), 0);
11633         
11634         op_free(entersubop);
11635         switch(GvNAME(namegv)[2]) {
11636         case 'F': return newSVOP(OP_CONST, 0,
11637                                         newSVpv(CopFILE(PL_curcop),0));
11638         case 'L': return newSVOP(
11639                            OP_CONST, 0,
11640                            Perl_newSVpvf(aTHX_
11641                              "%"IVdf, (IV)CopLINE(PL_curcop)
11642                            )
11643                          );
11644         case 'P': return newSVOP(OP_CONST, 0,
11645                                    (PL_curstash
11646                                      ? newSVhek(HvNAME_HEK(PL_curstash))
11647                                      : &PL_sv_undef
11648                                    )
11649                                 );
11650         }
11651         NOT_REACHED;
11652     }
11653     else {
11654         OP *prev, *cvop, *first, *parent;
11655         U32 flags = 0;
11656
11657         parent = entersubop;
11658         if (!OpHAS_SIBLING(aop)) {
11659             parent = aop;
11660             aop = cUNOPx(aop)->op_first;
11661         }
11662         
11663         first = prev = aop;
11664         aop = OpSIBLING(aop);
11665         /* find last sibling */
11666         for (cvop = aop;
11667              OpHAS_SIBLING(cvop);
11668              prev = cvop, cvop = OpSIBLING(cvop))
11669             ;
11670         if (!(cvop->op_private & OPpENTERSUB_NOPAREN)
11671             /* Usually, OPf_SPECIAL on an op with no args means that it had
11672              * parens, but these have their own meaning for that flag: */
11673             && opnum != OP_VALUES && opnum != OP_KEYS && opnum != OP_EACH
11674             && opnum != OP_DELETE && opnum != OP_EXISTS)
11675                 flags |= OPf_SPECIAL;
11676         /* excise cvop from end of sibling chain */
11677         op_sibling_splice(parent, prev, 1, NULL);
11678         op_free(cvop);
11679         if (aop == cvop) aop = NULL;
11680
11681         /* detach remaining siblings from the first sibling, then
11682          * dispose of original optree */
11683
11684         if (aop)
11685             op_sibling_splice(parent, first, -1, NULL);
11686         op_free(entersubop);
11687
11688         if (opnum == OP_ENTEREVAL
11689          && GvNAMELEN(namegv)==9 && strnEQ(GvNAME(namegv), "evalbytes", 9))
11690             flags |= OPpEVAL_BYTES <<8;
11691         
11692         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
11693         case OA_UNOP:
11694         case OA_BASEOP_OR_UNOP:
11695         case OA_FILESTATOP:
11696             return aop ? newUNOP(opnum,flags,aop) : newOP(opnum,flags);
11697         case OA_BASEOP:
11698             if (aop) {
11699                     (void)too_many_arguments_pv(aop, GvNAME(namegv), 0);
11700                 op_free(aop);
11701             }
11702             return opnum == OP_RUNCV
11703                 ? newPVOP(OP_RUNCV,0,NULL)
11704                 : newOP(opnum,0);
11705         default:
11706             return op_convert_list(opnum,0,aop);
11707         }
11708     }
11709     NOT_REACHED;
11710     return entersubop;
11711 }
11712
11713 /*
11714 =for apidoc Am|void|cv_get_call_checker|CV *cv|Perl_call_checker *ckfun_p|SV **ckobj_p
11715
11716 Retrieves the function that will be used to fix up a call to I<cv>.
11717 Specifically, the function is applied to an C<entersub> op tree for a
11718 subroutine call, not marked with C<&>, where the callee can be identified
11719 at compile time as I<cv>.
11720
11721 The C-level function pointer is returned in I<*ckfun_p>, and an SV
11722 argument for it is returned in I<*ckobj_p>.  The function is intended
11723 to be called in this manner:
11724
11725     entersubop = (*ckfun_p)(aTHX_ entersubop, namegv, (*ckobj_p));
11726
11727 In this call, I<entersubop> is a pointer to the C<entersub> op,
11728 which may be replaced by the check function, and I<namegv> is a GV
11729 supplying the name that should be used by the check function to refer
11730 to the callee of the C<entersub> op if it needs to emit any diagnostics.
11731 It is permitted to apply the check function in non-standard situations,
11732 such as to a call to a different subroutine or to a method call.
11733
11734 By default, the function is
11735 L<Perl_ck_entersub_args_proto_or_list|/ck_entersub_args_proto_or_list>,
11736 and the SV parameter is I<cv> itself.  This implements standard
11737 prototype processing.  It can be changed, for a particular subroutine,
11738 by L</cv_set_call_checker>.
11739
11740 =cut
11741 */
11742
11743 static void
11744 S_cv_get_call_checker(CV *cv, Perl_call_checker *ckfun_p, SV **ckobj_p,
11745                       U8 *flagsp)
11746 {
11747     MAGIC *callmg;
11748     callmg = SvMAGICAL((SV*)cv) ? mg_find((SV*)cv, PERL_MAGIC_checkcall) : NULL;
11749     if (callmg) {
11750         *ckfun_p = DPTR2FPTR(Perl_call_checker, callmg->mg_ptr);
11751         *ckobj_p = callmg->mg_obj;
11752         if (flagsp) *flagsp = callmg->mg_flags;
11753     } else {
11754         *ckfun_p = Perl_ck_entersub_args_proto_or_list;
11755         *ckobj_p = (SV*)cv;
11756         if (flagsp) *flagsp = 0;
11757     }
11758 }
11759
11760 void
11761 Perl_cv_get_call_checker(pTHX_ CV *cv, Perl_call_checker *ckfun_p, SV **ckobj_p)
11762 {
11763     PERL_ARGS_ASSERT_CV_GET_CALL_CHECKER;
11764     PERL_UNUSED_CONTEXT;
11765     S_cv_get_call_checker(cv, ckfun_p, ckobj_p, NULL);
11766 }
11767
11768 /*
11769 =for apidoc Am|void|cv_set_call_checker_flags|CV *cv|Perl_call_checker ckfun|SV *ckobj|U32 flags
11770
11771 Sets the function that will be used to fix up a call to I<cv>.
11772 Specifically, the function is applied to an C<entersub> op tree for a
11773 subroutine call, not marked with C<&>, where the callee can be identified
11774 at compile time as I<cv>.
11775
11776 The C-level function pointer is supplied in I<ckfun>, and an SV argument
11777 for it is supplied in I<ckobj>.  The function should be defined like this:
11778
11779     STATIC OP * ckfun(pTHX_ OP *op, GV *namegv, SV *ckobj)
11780
11781 It is intended to be called in this manner:
11782
11783     entersubop = ckfun(aTHX_ entersubop, namegv, ckobj);
11784
11785 In this call, I<entersubop> is a pointer to the C<entersub> op,
11786 which may be replaced by the check function, and I<namegv> supplies
11787 the name that should be used by the check function to refer
11788 to the callee of the C<entersub> op if it needs to emit any diagnostics.
11789 It is permitted to apply the check function in non-standard situations,
11790 such as to a call to a different subroutine or to a method call.
11791
11792 I<namegv> may not actually be a GV.  For efficiency, perl may pass a
11793 CV or other SV instead.  Whatever is passed can be used as the first
11794 argument to L</cv_name>.  You can force perl to pass a GV by including
11795 C<CALL_CHECKER_REQUIRE_GV> in the I<flags>.
11796
11797 The current setting for a particular CV can be retrieved by
11798 L</cv_get_call_checker>.
11799
11800 =for apidoc Am|void|cv_set_call_checker|CV *cv|Perl_call_checker ckfun|SV *ckobj
11801
11802 The original form of L</cv_set_call_checker_flags>, which passes it the
11803 C<CALL_CHECKER_REQUIRE_GV> flag for backward-compatibility.
11804
11805 =cut
11806 */
11807
11808 void
11809 Perl_cv_set_call_checker(pTHX_ CV *cv, Perl_call_checker ckfun, SV *ckobj)
11810 {
11811     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER;
11812     cv_set_call_checker_flags(cv, ckfun, ckobj, CALL_CHECKER_REQUIRE_GV);
11813 }
11814
11815 void
11816 Perl_cv_set_call_checker_flags(pTHX_ CV *cv, Perl_call_checker ckfun,
11817                                      SV *ckobj, U32 flags)
11818 {
11819     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER_FLAGS;
11820     if (ckfun == Perl_ck_entersub_args_proto_or_list && ckobj == (SV*)cv) {
11821         if (SvMAGICAL((SV*)cv))
11822             mg_free_type((SV*)cv, PERL_MAGIC_checkcall);
11823     } else {
11824         MAGIC *callmg;
11825         sv_magic((SV*)cv, &PL_sv_undef, PERL_MAGIC_checkcall, NULL, 0);
11826         callmg = mg_find((SV*)cv, PERL_MAGIC_checkcall);
11827         assert(callmg);
11828         if (callmg->mg_flags & MGf_REFCOUNTED) {
11829             SvREFCNT_dec(callmg->mg_obj);
11830             callmg->mg_flags &= ~MGf_REFCOUNTED;
11831         }
11832         callmg->mg_ptr = FPTR2DPTR(char *, ckfun);
11833         callmg->mg_obj = ckobj;
11834         if (ckobj != (SV*)cv) {
11835             SvREFCNT_inc_simple_void_NN(ckobj);
11836             callmg->mg_flags |= MGf_REFCOUNTED;
11837         }
11838         callmg->mg_flags = (callmg->mg_flags &~ MGf_REQUIRE_GV)
11839                          | (U8)(flags & MGf_REQUIRE_GV) | MGf_COPY;
11840     }
11841 }
11842
11843 static void
11844 S_entersub_alloc_targ(pTHX_ OP * const o)
11845 {
11846     o->op_targ = pad_alloc(OP_ENTERSUB, SVs_PADTMP);
11847     o->op_private |= OPpENTERSUB_HASTARG;
11848 }
11849
11850 OP *
11851 Perl_ck_subr(pTHX_ OP *o)
11852 {
11853     OP *aop, *cvop;
11854     CV *cv;
11855     GV *namegv;
11856     SV **const_class = NULL;
11857
11858     PERL_ARGS_ASSERT_CK_SUBR;
11859
11860     aop = cUNOPx(o)->op_first;
11861     if (!OpHAS_SIBLING(aop))
11862         aop = cUNOPx(aop)->op_first;
11863     aop = OpSIBLING(aop);
11864     for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
11865     cv = rv2cv_op_cv(cvop, RV2CVOPCV_MARK_EARLY);
11866     namegv = cv ? (GV*)rv2cv_op_cv(cvop, RV2CVOPCV_MAYBE_NAME_GV) : NULL;
11867
11868     o->op_private &= ~1;
11869     o->op_private |= (PL_hints & HINT_STRICT_REFS);
11870     if (PERLDB_SUB && PL_curstash != PL_debstash)
11871         o->op_private |= OPpENTERSUB_DB;
11872     switch (cvop->op_type) {
11873         case OP_RV2CV:
11874             o->op_private |= (cvop->op_private & OPpENTERSUB_AMPER);
11875             op_null(cvop);
11876             break;
11877         case OP_METHOD:
11878         case OP_METHOD_NAMED:
11879         case OP_METHOD_SUPER:
11880         case OP_METHOD_REDIR:
11881         case OP_METHOD_REDIR_SUPER:
11882             if (aop->op_type == OP_CONST) {
11883                 aop->op_private &= ~OPpCONST_STRICT;
11884                 const_class = &cSVOPx(aop)->op_sv;
11885             }
11886             else if (aop->op_type == OP_LIST) {
11887                 OP * const sib = OpSIBLING(((UNOP*)aop)->op_first);
11888                 if (sib && sib->op_type == OP_CONST) {
11889                     sib->op_private &= ~OPpCONST_STRICT;
11890                     const_class = &cSVOPx(sib)->op_sv;
11891                 }
11892             }
11893             /* make class name a shared cow string to speedup method calls */
11894             /* constant string might be replaced with object, f.e. bigint */
11895             if (const_class && SvPOK(*const_class)) {
11896                 STRLEN len;
11897                 const char* str = SvPV(*const_class, len);
11898                 if (len) {
11899                     SV* const shared = newSVpvn_share(
11900                         str, SvUTF8(*const_class)
11901                                     ? -(SSize_t)len : (SSize_t)len,
11902                         0
11903                     );
11904                     SvREFCNT_dec(*const_class);
11905                     *const_class = shared;
11906                 }
11907             }
11908             break;
11909     }
11910
11911     if (!cv) {
11912         S_entersub_alloc_targ(aTHX_ o);
11913         return ck_entersub_args_list(o);
11914     } else {
11915         Perl_call_checker ckfun;
11916         SV *ckobj;
11917         U8 flags;
11918         S_cv_get_call_checker(cv, &ckfun, &ckobj, &flags);
11919         if (CvISXSUB(cv) || !CvROOT(cv))
11920             S_entersub_alloc_targ(aTHX_ o);
11921         if (!namegv) {
11922             /* The original call checker API guarantees that a GV will be
11923                be provided with the right name.  So, if the old API was
11924                used (or the REQUIRE_GV flag was passed), we have to reify
11925                the CV’s GV, unless this is an anonymous sub.  This is not
11926                ideal for lexical subs, as its stringification will include
11927                the package.  But it is the best we can do.  */
11928             if (flags & MGf_REQUIRE_GV) {
11929                 if (!CvANON(cv) && (!CvNAMED(cv) || CvNAME_HEK(cv)))
11930                     namegv = CvGV(cv);
11931             }
11932             else namegv = MUTABLE_GV(cv);
11933             /* After a syntax error in a lexical sub, the cv that
11934                rv2cv_op_cv returns may be a nameless stub. */
11935             if (!namegv) return ck_entersub_args_list(o);
11936
11937         }
11938         return ckfun(aTHX_ o, namegv, ckobj);
11939     }
11940 }
11941
11942 OP *
11943 Perl_ck_svconst(pTHX_ OP *o)
11944 {
11945     SV * const sv = cSVOPo->op_sv;
11946     PERL_ARGS_ASSERT_CK_SVCONST;
11947     PERL_UNUSED_CONTEXT;
11948 #ifdef PERL_OLD_COPY_ON_WRITE
11949     if (SvIsCOW(sv)) sv_force_normal(sv);
11950 #elif defined(PERL_NEW_COPY_ON_WRITE)
11951     /* Since the read-only flag may be used to protect a string buffer, we
11952        cannot do copy-on-write with existing read-only scalars that are not
11953        already copy-on-write scalars.  To allow $_ = "hello" to do COW with
11954        that constant, mark the constant as COWable here, if it is not
11955        already read-only. */
11956     if (!SvREADONLY(sv) && !SvIsCOW(sv) && SvCANCOW(sv)) {
11957         SvIsCOW_on(sv);
11958         CowREFCNT(sv) = 0;
11959 # ifdef PERL_DEBUG_READONLY_COW
11960         sv_buf_to_ro(sv);
11961 # endif
11962     }
11963 #endif
11964     SvREADONLY_on(sv);
11965     return o;
11966 }
11967
11968 OP *
11969 Perl_ck_trunc(pTHX_ OP *o)
11970 {
11971     PERL_ARGS_ASSERT_CK_TRUNC;
11972
11973     if (o->op_flags & OPf_KIDS) {
11974         SVOP *kid = (SVOP*)cUNOPo->op_first;
11975
11976         if (kid->op_type == OP_NULL)
11977             kid = (SVOP*)OpSIBLING(kid);
11978         if (kid && kid->op_type == OP_CONST &&
11979             (kid->op_private & OPpCONST_BARE) &&
11980             !kid->op_folded)
11981         {
11982             o->op_flags |= OPf_SPECIAL;
11983             kid->op_private &= ~OPpCONST_STRICT;
11984         }
11985     }
11986     return ck_fun(o);
11987 }
11988
11989 OP *
11990 Perl_ck_substr(pTHX_ OP *o)
11991 {
11992     PERL_ARGS_ASSERT_CK_SUBSTR;
11993
11994     o = ck_fun(o);
11995     if ((o->op_flags & OPf_KIDS) && (o->op_private == 4)) {
11996         OP *kid = cLISTOPo->op_first;
11997
11998         if (kid->op_type == OP_NULL)
11999             kid = OpSIBLING(kid);
12000         if (kid)
12001             kid->op_flags |= OPf_MOD;
12002
12003     }
12004     return o;
12005 }
12006
12007 OP *
12008 Perl_ck_tell(pTHX_ OP *o)
12009 {
12010     PERL_ARGS_ASSERT_CK_TELL;
12011     o = ck_fun(o);
12012     if (o->op_flags & OPf_KIDS) {
12013      OP *kid = cLISTOPo->op_first;
12014      if (kid->op_type == OP_NULL && OpHAS_SIBLING(kid)) kid = OpSIBLING(kid);
12015      if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
12016     }
12017     return o;
12018 }
12019
12020 OP *
12021 Perl_ck_each(pTHX_ OP *o)
12022 {
12023     dVAR;
12024     OP *kid = o->op_flags & OPf_KIDS ? cUNOPo->op_first : NULL;
12025     const unsigned orig_type  = o->op_type;
12026     const unsigned array_type = orig_type == OP_EACH ? OP_AEACH
12027                               : orig_type == OP_KEYS ? OP_AKEYS : OP_AVALUES;
12028     const unsigned ref_type   = orig_type == OP_EACH ? OP_REACH
12029                               : orig_type == OP_KEYS ? OP_RKEYS : OP_RVALUES;
12030
12031     PERL_ARGS_ASSERT_CK_EACH;
12032
12033     if (kid) {
12034         switch (kid->op_type) {
12035             case OP_PADHV:
12036             case OP_RV2HV:
12037                 break;
12038             case OP_PADAV:
12039             case OP_RV2AV:
12040                 CHANGE_TYPE(o, array_type);
12041                 break;
12042             case OP_CONST:
12043                 if (kid->op_private == OPpCONST_BARE
12044                  || !SvROK(cSVOPx_sv(kid))
12045                  || (  SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV
12046                     && SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVHV  )
12047                    )
12048                     /* we let ck_fun handle it */
12049                     break;
12050             default:
12051                 CHANGE_TYPE(o, ref_type);
12052                 scalar(kid);
12053         }
12054     }
12055     /* if treating as a reference, defer additional checks to runtime */
12056     if (o->op_type == ref_type) {
12057         /* diag_listed_as: keys on reference is experimental */
12058         Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__AUTODEREF),
12059                               "%s is experimental", PL_op_desc[ref_type]);
12060         return o;
12061     }
12062     return ck_fun(o);
12063 }
12064
12065 OP *
12066 Perl_ck_length(pTHX_ OP *o)
12067 {
12068     PERL_ARGS_ASSERT_CK_LENGTH;
12069
12070     o = ck_fun(o);
12071
12072     if (ckWARN(WARN_SYNTAX)) {
12073         const OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : NULL;
12074
12075         if (kid) {
12076             SV *name = NULL;
12077             const bool hash = kid->op_type == OP_PADHV
12078                            || kid->op_type == OP_RV2HV;
12079             switch (kid->op_type) {
12080                 case OP_PADHV:
12081                 case OP_PADAV:
12082                 case OP_RV2HV:
12083                 case OP_RV2AV:
12084                     name = S_op_varname(aTHX_ kid);
12085                     break;
12086                 default:
12087                     return o;
12088             }
12089             if (name)
12090                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
12091                     "length() used on %"SVf" (did you mean \"scalar(%s%"SVf
12092                     ")\"?)",
12093                     SVfARG(name), hash ? "keys " : "", SVfARG(name)
12094                 );
12095             else if (hash)
12096      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
12097                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
12098                     "length() used on %%hash (did you mean \"scalar(keys %%hash)\"?)");
12099             else
12100      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
12101                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
12102                     "length() used on @array (did you mean \"scalar(@array)\"?)");
12103         }
12104     }
12105
12106     return o;
12107 }
12108
12109 /* Check for in place reverse and sort assignments like "@a = reverse @a"
12110    and modify the optree to make them work inplace */
12111
12112 STATIC void
12113 S_inplace_aassign(pTHX_ OP *o) {
12114
12115     OP *modop, *modop_pushmark;
12116     OP *oright;
12117     OP *oleft, *oleft_pushmark;
12118
12119     PERL_ARGS_ASSERT_INPLACE_AASSIGN;
12120
12121     assert((o->op_flags & OPf_WANT) == OPf_WANT_VOID);
12122
12123     assert(cUNOPo->op_first->op_type == OP_NULL);
12124     modop_pushmark = cUNOPx(cUNOPo->op_first)->op_first;
12125     assert(modop_pushmark->op_type == OP_PUSHMARK);
12126     modop = OpSIBLING(modop_pushmark);
12127
12128     if (modop->op_type != OP_SORT && modop->op_type != OP_REVERSE)
12129         return;
12130
12131     /* no other operation except sort/reverse */
12132     if (OpHAS_SIBLING(modop))
12133         return;
12134
12135     assert(cUNOPx(modop)->op_first->op_type == OP_PUSHMARK);
12136     if (!(oright = OpSIBLING(cUNOPx(modop)->op_first))) return;
12137
12138     if (modop->op_flags & OPf_STACKED) {
12139         /* skip sort subroutine/block */
12140         assert(oright->op_type == OP_NULL);
12141         oright = OpSIBLING(oright);
12142     }
12143
12144     assert(OpSIBLING(cUNOPo->op_first)->op_type == OP_NULL);
12145     oleft_pushmark = cUNOPx(OpSIBLING(cUNOPo->op_first))->op_first;
12146     assert(oleft_pushmark->op_type == OP_PUSHMARK);
12147     oleft = OpSIBLING(oleft_pushmark);
12148
12149     /* Check the lhs is an array */
12150     if (!oleft ||
12151         (oleft->op_type != OP_RV2AV && oleft->op_type != OP_PADAV)
12152         || OpHAS_SIBLING(oleft)
12153         || (oleft->op_private & OPpLVAL_INTRO)
12154     )
12155         return;
12156
12157     /* Only one thing on the rhs */
12158     if (OpHAS_SIBLING(oright))
12159         return;
12160
12161     /* check the array is the same on both sides */
12162     if (oleft->op_type == OP_RV2AV) {
12163         if (oright->op_type != OP_RV2AV
12164             || !cUNOPx(oright)->op_first
12165             || cUNOPx(oright)->op_first->op_type != OP_GV
12166             || cUNOPx(oleft )->op_first->op_type != OP_GV
12167             || cGVOPx_gv(cUNOPx(oleft)->op_first) !=
12168                cGVOPx_gv(cUNOPx(oright)->op_first)
12169         )
12170             return;
12171     }
12172     else if (oright->op_type != OP_PADAV
12173         || oright->op_targ != oleft->op_targ
12174     )
12175         return;
12176
12177     /* This actually is an inplace assignment */
12178
12179     modop->op_private |= OPpSORT_INPLACE;
12180
12181     /* transfer MODishness etc from LHS arg to RHS arg */
12182     oright->op_flags = oleft->op_flags;
12183
12184     /* remove the aassign op and the lhs */
12185     op_null(o);
12186     op_null(oleft_pushmark);
12187     if (oleft->op_type == OP_RV2AV && cUNOPx(oleft)->op_first)
12188         op_null(cUNOPx(oleft)->op_first);
12189     op_null(oleft);
12190 }
12191
12192
12193
12194 /* S_maybe_multideref(): given an op_next chain of ops beginning at 'start'
12195  * that potentially represent a series of one or more aggregate derefs
12196  * (such as $a->[1]{$key}), examine the chain, and if appropriate, convert
12197  * the whole chain to a single OP_MULTIDEREF op (maybe with a few
12198  * additional ops left in too).
12199  *
12200  * The caller will have already verified that the first few ops in the
12201  * chain following 'start' indicate a multideref candidate, and will have
12202  * set 'orig_o' to the point further on in the chain where the first index
12203  * expression (if any) begins.  'orig_action' specifies what type of
12204  * beginning has already been determined by the ops between start..orig_o
12205  * (e.g.  $lex_ary[], $pkg_ary->{}, expr->[], etc).
12206  *
12207  * 'hints' contains any hints flags that need adding (currently just
12208  * OPpHINT_STRICT_REFS) as found in any rv2av/hv skipped by the caller.
12209  */
12210
12211 void
12212 S_maybe_multideref(pTHX_ OP *start, OP *orig_o, UV orig_action, U8 hints)
12213 {
12214     dVAR;
12215     int pass;
12216     UNOP_AUX_item *arg_buf = NULL;
12217     bool reset_start_targ  = FALSE; /* start->op_targ needs zeroing */
12218     int index_skip         = -1;    /* don't output index arg on this action */
12219
12220     /* similar to regex compiling, do two passes; the first pass
12221      * determines whether the op chain is convertible and calculates the
12222      * buffer size; the second pass populates the buffer and makes any
12223      * changes necessary to ops (such as moving consts to the pad on
12224      * threaded builds)
12225      */
12226     for (pass = 0; pass < 2; pass++) {
12227         OP *o                = orig_o;
12228         UV action            = orig_action;
12229         OP *first_elem_op    = NULL;  /* first seen aelem/helem */
12230         OP *top_op           = NULL;  /* highest [ah]elem/exists/del/rv2[ah]v */
12231         int action_count     = 0;     /* number of actions seen so far */
12232         int action_ix        = 0;     /* action_count % (actions per IV) */
12233         bool next_is_hash    = FALSE; /* is the next lookup to be a hash? */
12234         bool is_last         = FALSE; /* no more derefs to follow */
12235         bool maybe_aelemfast = FALSE; /* we can replace with aelemfast? */
12236         UNOP_AUX_item *arg     = arg_buf;
12237         UNOP_AUX_item *action_ptr = arg_buf;
12238
12239         if (pass)
12240             action_ptr->uv = 0;
12241         arg++;
12242
12243         switch (action) {
12244         case MDEREF_HV_gvsv_vivify_rv2hv_helem:
12245         case MDEREF_HV_gvhv_helem:
12246             next_is_hash = TRUE;
12247             /* FALLTHROUGH */
12248         case MDEREF_AV_gvsv_vivify_rv2av_aelem:
12249         case MDEREF_AV_gvav_aelem:
12250             if (pass) {
12251 #ifdef USE_ITHREADS
12252                 arg->pad_offset = cPADOPx(start)->op_padix;
12253                 /* stop it being swiped when nulled */
12254                 cPADOPx(start)->op_padix = 0;
12255 #else
12256                 arg->sv = cSVOPx(start)->op_sv;
12257                 cSVOPx(start)->op_sv = NULL;
12258 #endif
12259             }
12260             arg++;
12261             break;
12262
12263         case MDEREF_HV_padhv_helem:
12264         case MDEREF_HV_padsv_vivify_rv2hv_helem:
12265             next_is_hash = TRUE;
12266             /* FALLTHROUGH */
12267         case MDEREF_AV_padav_aelem:
12268         case MDEREF_AV_padsv_vivify_rv2av_aelem:
12269             if (pass) {
12270                 arg->pad_offset = start->op_targ;
12271                 /* we skip setting op_targ = 0 for now, since the intact
12272                  * OP_PADXV is needed by S_check_hash_fields_and_hekify */
12273                 reset_start_targ = TRUE;
12274             }
12275             arg++;
12276             break;
12277
12278         case MDEREF_HV_pop_rv2hv_helem:
12279             next_is_hash = TRUE;
12280             /* FALLTHROUGH */
12281         case MDEREF_AV_pop_rv2av_aelem:
12282             break;
12283
12284         default:
12285             NOT_REACHED;
12286             return;
12287         }
12288
12289         while (!is_last) {
12290             /* look for another (rv2av/hv; get index;
12291              * aelem/helem/exists/delele) sequence */
12292
12293             OP *kid;
12294             bool is_deref;
12295             bool ok;
12296             UV index_type = MDEREF_INDEX_none;
12297
12298             if (action_count) {
12299                 /* if this is not the first lookup, consume the rv2av/hv  */
12300
12301                 /* for N levels of aggregate lookup, we normally expect
12302                  * that the first N-1 [ah]elem ops will be flagged as
12303                  * /DEREF (so they autovivifiy if necessary), and the last
12304                  * lookup op not to be.
12305                  * For other things (like @{$h{k1}{k2}}) extra scope or
12306                  * leave ops can appear, so abandon the effort in that
12307                  * case */
12308                 if (o->op_type != OP_RV2AV && o->op_type != OP_RV2HV)
12309                     return;
12310
12311                 /* rv2av or rv2hv sKR/1 */
12312
12313                 ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
12314                                             |OPf_REF|OPf_MOD|OPf_SPECIAL)));
12315                 if (o->op_flags != (OPf_WANT_SCALAR|OPf_KIDS|OPf_REF))
12316                     return;
12317
12318                 /* at this point, we wouldn't expect any of these
12319                  * possible private flags:
12320                  * OPpMAYBE_LVSUB, OPpOUR_INTRO, OPpLVAL_INTRO
12321                  * OPpTRUEBOOL, OPpMAYBE_TRUEBOOL (rv2hv only)
12322                  */
12323                 ASSUME(!(o->op_private &
12324                     ~(OPpHINT_STRICT_REFS|OPpARG1_MASK|OPpSLICEWARNING)));
12325
12326                 hints = (o->op_private & OPpHINT_STRICT_REFS);
12327
12328                 /* make sure the type of the previous /DEREF matches the
12329                  * type of the next lookup */
12330                 ASSUME(o->op_type == (next_is_hash ? OP_RV2HV : OP_RV2AV));
12331                 top_op = o;
12332
12333                 action = next_is_hash
12334                             ? MDEREF_HV_vivify_rv2hv_helem
12335                             : MDEREF_AV_vivify_rv2av_aelem;
12336                 o = o->op_next;
12337             }
12338
12339             /* if this is the second pass, and we're at the depth where
12340              * previously we encountered a non-simple index expression,
12341              * stop processing the index at this point */
12342             if (action_count != index_skip) {
12343
12344                 /* look for one or more simple ops that return an array
12345                  * index or hash key */
12346
12347                 switch (o->op_type) {
12348                 case OP_PADSV:
12349                     /* it may be a lexical var index */
12350                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_PARENS
12351                                             |OPf_REF|OPf_MOD|OPf_SPECIAL)));
12352                     ASSUME(!(o->op_private &
12353                             ~(OPpPAD_STATE|OPpDEREF|OPpLVAL_INTRO)));
12354
12355                     if (   OP_GIMME(o,0) == G_SCALAR
12356                         && !(o->op_flags & (OPf_REF|OPf_MOD))
12357                         && o->op_private == 0)
12358                     {
12359                         if (pass)
12360                             arg->pad_offset = o->op_targ;
12361                         arg++;
12362                         index_type = MDEREF_INDEX_padsv;
12363                         o = o->op_next;
12364                     }
12365                     break;
12366
12367                 case OP_CONST:
12368                     if (next_is_hash) {
12369                         /* it's a constant hash index */
12370                         if (!(SvFLAGS(cSVOPo_sv) & (SVf_IOK|SVf_NOK|SVf_POK)))
12371                             /* "use constant foo => FOO; $h{+foo}" for
12372                              * some weird FOO, can leave you with constants
12373                              * that aren't simple strings. It's not worth
12374                              * the extra hassle for those edge cases */
12375                             break;
12376
12377                         if (pass) {
12378                             UNOP *rop = NULL;
12379                             OP * helem_op = o->op_next;
12380
12381                             ASSUME(   helem_op->op_type == OP_HELEM
12382                                    || helem_op->op_type == OP_NULL);
12383                             if (helem_op->op_type == OP_HELEM) {
12384                                 rop = (UNOP*)(((BINOP*)helem_op)->op_first);
12385                                 if (   helem_op->op_private & OPpLVAL_INTRO
12386                                     || rop->op_type != OP_RV2HV
12387                                 )
12388                                     rop = NULL;
12389                             }
12390                             S_check_hash_fields_and_hekify(aTHX_ rop, cSVOPo);
12391
12392 #ifdef USE_ITHREADS
12393                             /* Relocate sv to the pad for thread safety */
12394                             op_relocate_sv(&cSVOPo->op_sv, &o->op_targ);
12395                             arg->pad_offset = o->op_targ;
12396                             o->op_targ = 0;
12397 #else
12398                             arg->sv = cSVOPx_sv(o);
12399 #endif
12400                         }
12401                     }
12402                     else {
12403                         /* it's a constant array index */
12404                         IV iv;
12405                         SV *ix_sv = cSVOPo->op_sv;
12406                         if (!SvIOK(ix_sv))
12407                             break;
12408                         iv = SvIV(ix_sv);
12409
12410                         if (   action_count == 0
12411                             && iv >= -128
12412                             && iv <= 127
12413                             && (   action == MDEREF_AV_padav_aelem
12414                                 || action == MDEREF_AV_gvav_aelem)
12415                         )
12416                             maybe_aelemfast = TRUE;
12417
12418                         if (pass) {
12419                             arg->iv = iv;
12420                             SvREFCNT_dec_NN(cSVOPo->op_sv);
12421                         }
12422                     }
12423                     if (pass)
12424                         /* we've taken ownership of the SV */
12425                         cSVOPo->op_sv = NULL;
12426                     arg++;
12427                     index_type = MDEREF_INDEX_const;
12428                     o = o->op_next;
12429                     break;
12430
12431                 case OP_GV:
12432                     /* it may be a package var index */
12433
12434                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_SPECIAL)));
12435                     ASSUME(!(o->op_private & ~(OPpEARLY_CV)));
12436                     if (  (o->op_flags &~ OPf_SPECIAL) != OPf_WANT_SCALAR
12437                         || o->op_private != 0
12438                     )
12439                         break;
12440
12441                     kid = o->op_next;
12442                     if (kid->op_type != OP_RV2SV)
12443                         break;
12444
12445                     ASSUME(!(kid->op_flags &
12446                             ~(OPf_WANT|OPf_KIDS|OPf_MOD|OPf_REF
12447                              |OPf_SPECIAL|OPf_PARENS)));
12448                     ASSUME(!(kid->op_private &
12449                                     ~(OPpARG1_MASK
12450                                      |OPpHINT_STRICT_REFS|OPpOUR_INTRO
12451                                      |OPpDEREF|OPpLVAL_INTRO)));
12452                     if(   (kid->op_flags &~ OPf_PARENS)
12453                             != (OPf_WANT_SCALAR|OPf_KIDS)
12454                        || (kid->op_private & ~(OPpARG1_MASK|HINT_STRICT_REFS))
12455                     )
12456                         break;
12457
12458                     if (pass) {
12459 #ifdef USE_ITHREADS
12460                         arg->pad_offset = cPADOPx(o)->op_padix;
12461                         /* stop it being swiped when nulled */
12462                         cPADOPx(o)->op_padix = 0;
12463 #else
12464                         arg->sv = cSVOPx(o)->op_sv;
12465                         cSVOPo->op_sv = NULL;
12466 #endif
12467                     }
12468                     arg++;
12469                     index_type = MDEREF_INDEX_gvsv;
12470                     o = kid->op_next;
12471                     break;
12472
12473                 } /* switch */
12474             } /* action_count != index_skip */
12475
12476             action |= index_type;
12477
12478
12479             /* at this point we have either:
12480              *   * detected what looks like a simple index expression,
12481              *     and expect the next op to be an [ah]elem, or
12482              *     an nulled  [ah]elem followed by a delete or exists;
12483              *  * found a more complex expression, so something other
12484              *    than the above follows.
12485              */
12486
12487             /* possibly an optimised away [ah]elem (where op_next is
12488              * exists or delete) */
12489             if (o->op_type == OP_NULL)
12490                 o = o->op_next;
12491
12492             /* at this point we're looking for an OP_AELEM, OP_HELEM,
12493              * OP_EXISTS or OP_DELETE */
12494
12495             /* if something like arybase (a.k.a $[ ) is in scope,
12496              * abandon optimisation attempt */
12497             if (  (o->op_type == OP_AELEM || o->op_type == OP_HELEM)
12498                && PL_check[o->op_type] != Perl_ck_null)
12499                 return;
12500
12501             if (   o->op_type != OP_AELEM
12502                 || (o->op_private &
12503                       (OPpLVAL_INTRO|OPpLVAL_DEFER|OPpDEREF|OPpMAYBE_LVSUB))
12504                 )
12505                 maybe_aelemfast = FALSE;
12506
12507             /* look for aelem/helem/exists/delete. If it's not the last elem
12508              * lookup, it *must* have OPpDEREF_AV/HV, but not many other
12509              * flags; if it's the last, then it mustn't have
12510              * OPpDEREF_AV/HV, but may have lots of other flags, like
12511              * OPpLVAL_INTRO etc
12512              */
12513
12514             if (   index_type == MDEREF_INDEX_none
12515                 || (   o->op_type != OP_AELEM  && o->op_type != OP_HELEM
12516                     && o->op_type != OP_EXISTS && o->op_type != OP_DELETE)
12517             )
12518                 ok = FALSE;
12519             else {
12520                 /* we have aelem/helem/exists/delete with valid simple index */
12521
12522                 is_deref =    (o->op_type == OP_AELEM || o->op_type == OP_HELEM)
12523                            && (   (o->op_private & OPpDEREF) == OPpDEREF_AV
12524                                || (o->op_private & OPpDEREF) == OPpDEREF_HV);
12525
12526                 if (is_deref) {
12527                     ASSUME(!(o->op_flags &
12528                                  ~(OPf_WANT|OPf_KIDS|OPf_MOD|OPf_PARENS)));
12529                     ASSUME(!(o->op_private & ~(OPpARG2_MASK|OPpDEREF)));
12530
12531                     ok =    (o->op_flags &~ OPf_PARENS)
12532                                == (OPf_WANT_SCALAR|OPf_KIDS|OPf_MOD)
12533                          && !(o->op_private & ~(OPpDEREF|OPpARG2_MASK));
12534                 }
12535                 else if (o->op_type == OP_EXISTS) {
12536                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
12537                                 |OPf_REF|OPf_MOD|OPf_SPECIAL)));
12538                     ASSUME(!(o->op_private & ~(OPpARG1_MASK|OPpEXISTS_SUB)));
12539                     ok =  !(o->op_private & ~OPpARG1_MASK);
12540                 }
12541                 else if (o->op_type == OP_DELETE) {
12542                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
12543                                 |OPf_REF|OPf_MOD|OPf_SPECIAL)));
12544                     ASSUME(!(o->op_private &
12545                                     ~(OPpARG1_MASK|OPpSLICE|OPpLVAL_INTRO)));
12546                     /* don't handle slices or 'local delete'; the latter
12547                      * is fairly rare, and has a complex runtime */
12548                     ok =  !(o->op_private & ~OPpARG1_MASK);
12549                     if (OP_TYPE_IS_OR_WAS(cUNOPo->op_first, OP_AELEM))
12550                         /* skip handling run-tome error */
12551                         ok = (ok && cBOOL(o->op_flags & OPf_SPECIAL));
12552                 }
12553                 else {
12554                     ASSUME(o->op_type == OP_AELEM || o->op_type == OP_HELEM);
12555                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_MOD
12556                                             |OPf_PARENS|OPf_REF|OPf_SPECIAL)));
12557                     ASSUME(!(o->op_private & ~(OPpARG2_MASK|OPpMAYBE_LVSUB
12558                                     |OPpLVAL_DEFER|OPpDEREF|OPpLVAL_INTRO)));
12559                     ok = (o->op_private & OPpDEREF) != OPpDEREF_SV;
12560                 }
12561             }
12562
12563             if (ok) {
12564                 if (!first_elem_op)
12565                     first_elem_op = o;
12566                 top_op = o;
12567                 if (is_deref) {
12568                     next_is_hash = cBOOL((o->op_private & OPpDEREF) == OPpDEREF_HV);
12569                     o = o->op_next;
12570                 }
12571                 else {
12572                     is_last = TRUE;
12573                     action |= MDEREF_FLAG_last;
12574                 }
12575             }
12576             else {
12577                 /* at this point we have something that started
12578                  * promisingly enough (with rv2av or whatever), but failed
12579                  * to find a simple index followed by an
12580                  * aelem/helem/exists/delete. If this is the first action,
12581                  * give up; but if we've already seen at least one
12582                  * aelem/helem, then keep them and add a new action with
12583                  * MDEREF_INDEX_none, which causes it to do the vivify
12584                  * from the end of the previous lookup, and do the deref,
12585                  * but stop at that point. So $a[0][expr] will do one
12586                  * av_fetch, vivify and deref, then continue executing at
12587                  * expr */
12588                 if (!action_count)
12589                     return;
12590                 is_last = TRUE;
12591                 index_skip = action_count;
12592                 action |= MDEREF_FLAG_last;
12593             }
12594
12595             if (pass)
12596                 action_ptr->uv |= (action << (action_ix * MDEREF_SHIFT));
12597             action_ix++;
12598             action_count++;
12599             /* if there's no space for the next action, create a new slot
12600              * for it *before* we start adding args for that action */
12601             if ((action_ix + 1) * MDEREF_SHIFT > UVSIZE*8) {
12602                 action_ptr = arg;
12603                 if (pass)
12604                     arg->uv = 0;
12605                 arg++;
12606                 action_ix = 0;
12607             }
12608         } /* while !is_last */
12609
12610         /* success! */
12611
12612         if (pass) {
12613             OP *mderef;
12614             OP *p;
12615
12616             mderef = newUNOP_AUX(OP_MULTIDEREF, 0, NULL, arg_buf);
12617             if (index_skip == -1) {
12618                 mderef->op_flags = o->op_flags
12619                         & (OPf_WANT|OPf_MOD|(next_is_hash ? OPf_SPECIAL : 0));
12620                 if (o->op_type == OP_EXISTS)
12621                     mderef->op_private = OPpMULTIDEREF_EXISTS;
12622                 else if (o->op_type == OP_DELETE)
12623                     mderef->op_private = OPpMULTIDEREF_DELETE;
12624                 else
12625                     mderef->op_private = o->op_private
12626                         & (OPpMAYBE_LVSUB|OPpLVAL_DEFER|OPpLVAL_INTRO);
12627             }
12628             /* accumulate strictness from every level (although I don't think
12629              * they can actually vary) */
12630             mderef->op_private |= hints;
12631
12632             /* integrate the new multideref op into the optree and the
12633              * op_next chain.
12634              *
12635              * In general an op like aelem or helem has two child
12636              * sub-trees: the aggregate expression (a_expr) and the
12637              * index expression (i_expr):
12638              *
12639              *     aelem
12640              *       |
12641              *     a_expr - i_expr
12642              *
12643              * The a_expr returns an AV or HV, while the i-expr returns an
12644              * index. In general a multideref replaces most or all of a
12645              * multi-level tree, e.g.
12646              *
12647              *     exists
12648              *       |
12649              *     ex-aelem
12650              *       |
12651              *     rv2av  - i_expr1
12652              *       |
12653              *     helem
12654              *       |
12655              *     rv2hv  - i_expr2
12656              *       |
12657              *     aelem
12658              *       |
12659              *     a_expr - i_expr3
12660              *
12661              * With multideref, all the i_exprs will be simple vars or
12662              * constants, except that i_expr1 may be arbitrary in the case
12663              * of MDEREF_INDEX_none.
12664              *
12665              * The bottom-most a_expr will be either:
12666              *   1) a simple var (so padXv or gv+rv2Xv);
12667              *   2) a simple scalar var dereferenced (e.g. $r->[0]):
12668              *      so a simple var with an extra rv2Xv;
12669              *   3) or an arbitrary expression.
12670              *
12671              * 'start', the first op in the execution chain, will point to
12672              *   1),2): the padXv or gv op;
12673              *   3):    the rv2Xv which forms the last op in the a_expr
12674              *          execution chain, and the top-most op in the a_expr
12675              *          subtree.
12676              *
12677              * For all cases, the 'start' node is no longer required,
12678              * but we can't free it since one or more external nodes
12679              * may point to it. E.g. consider
12680              *     $h{foo} = $a ? $b : $c
12681              * Here, both the op_next and op_other branches of the
12682              * cond_expr point to the gv[*h] of the hash expression, so
12683              * we can't free the 'start' op.
12684              *
12685              * For expr->[...], we need to save the subtree containing the
12686              * expression; for the other cases, we just need to save the
12687              * start node.
12688              * So in all cases, we null the start op and keep it around by
12689              * making it the child of the multideref op; for the expr->
12690              * case, the expr will be a subtree of the start node.
12691              *
12692              * So in the simple 1,2 case the  optree above changes to
12693              *
12694              *     ex-exists
12695              *       |
12696              *     multideref
12697              *       |
12698              *     ex-gv (or ex-padxv)
12699              *
12700              *  with the op_next chain being
12701              *
12702              *  -> ex-gv -> multideref -> op-following-ex-exists ->
12703              *
12704              *  In the 3 case, we have
12705              *
12706              *     ex-exists
12707              *       |
12708              *     multideref
12709              *       |
12710              *     ex-rv2xv
12711              *       |
12712              *    rest-of-a_expr
12713              *      subtree
12714              *
12715              *  and
12716              *
12717              *  -> rest-of-a_expr subtree ->
12718              *    ex-rv2xv -> multideref -> op-following-ex-exists ->
12719              *
12720              *
12721              * Where the last i_expr is non-simple (i.e. MDEREF_INDEX_none,
12722              * e.g. $a[0]{foo}[$x+1], the next rv2xv is nulled and the
12723              * multideref attached as the child, e.g.
12724              *
12725              *     exists
12726              *       |
12727              *     ex-aelem
12728              *       |
12729              *     ex-rv2av  - i_expr1
12730              *       |
12731              *     multideref
12732              *       |
12733              *     ex-whatever
12734              *
12735              */
12736
12737             /* if we free this op, don't free the pad entry */
12738             if (reset_start_targ)
12739                 start->op_targ = 0;
12740
12741
12742             /* Cut the bit we need to save out of the tree and attach to
12743              * the multideref op, then free the rest of the tree */
12744
12745             /* find parent of node to be detached (for use by splice) */
12746             p = first_elem_op;
12747             if (   orig_action == MDEREF_AV_pop_rv2av_aelem
12748                 || orig_action == MDEREF_HV_pop_rv2hv_helem)
12749             {
12750                 /* there is an arbitrary expression preceding us, e.g.
12751                  * expr->[..]? so we need to save the 'expr' subtree */
12752                 if (p->op_type == OP_EXISTS || p->op_type == OP_DELETE)
12753                     p = cUNOPx(p)->op_first;
12754                 ASSUME(   start->op_type == OP_RV2AV
12755                        || start->op_type == OP_RV2HV);
12756             }
12757             else {
12758                 /* either a padXv or rv2Xv+gv, maybe with an ex-Xelem
12759                  * above for exists/delete. */
12760                 while (   (p->op_flags & OPf_KIDS)
12761                        && cUNOPx(p)->op_first != start
12762                 )
12763                     p = cUNOPx(p)->op_first;
12764             }
12765             ASSUME(cUNOPx(p)->op_first == start);
12766
12767             /* detach from main tree, and re-attach under the multideref */
12768             op_sibling_splice(mderef, NULL, 0,
12769                     op_sibling_splice(p, NULL, 1, NULL));
12770             op_null(start);
12771
12772             start->op_next = mderef;
12773
12774             mderef->op_next = index_skip == -1 ? o->op_next : o;
12775
12776             /* excise and free the original tree, and replace with
12777              * the multideref op */
12778             op_free(op_sibling_splice(top_op, NULL, -1, mderef));
12779             op_null(top_op);
12780         }
12781         else {
12782             Size_t size = arg - arg_buf;
12783
12784             if (maybe_aelemfast && action_count == 1)
12785                 return;
12786
12787             arg_buf = (UNOP_AUX_item*)PerlMemShared_malloc(
12788                                 sizeof(UNOP_AUX_item) * (size + 1));
12789             /* for dumping etc: store the length in a hidden first slot;
12790              * we set the op_aux pointer to the second slot */
12791             arg_buf->uv = size;
12792             arg_buf++;
12793         }
12794     } /* for (pass = ...) */
12795 }
12796
12797
12798
12799 /* mechanism for deferring recursion in rpeep() */
12800
12801 #define MAX_DEFERRED 4
12802
12803 #define DEFER(o) \
12804   STMT_START { \
12805     if (defer_ix == (MAX_DEFERRED-1)) { \
12806         OP **defer = defer_queue[defer_base]; \
12807         CALL_RPEEP(*defer); \
12808         S_prune_chain_head(defer); \
12809         defer_base = (defer_base + 1) % MAX_DEFERRED; \
12810         defer_ix--; \
12811     } \
12812     defer_queue[(defer_base + ++defer_ix) % MAX_DEFERRED] = &(o); \
12813   } STMT_END
12814
12815 #define IS_AND_OP(o)   (o->op_type == OP_AND)
12816 #define IS_OR_OP(o)    (o->op_type == OP_OR)
12817
12818
12819 /* A peephole optimizer.  We visit the ops in the order they're to execute.
12820  * See the comments at the top of this file for more details about when
12821  * peep() is called */
12822
12823 void
12824 Perl_rpeep(pTHX_ OP *o)
12825 {
12826     dVAR;
12827     OP* oldop = NULL;
12828     OP* oldoldop = NULL;
12829     OP** defer_queue[MAX_DEFERRED]; /* small queue of deferred branches */
12830     int defer_base = 0;
12831     int defer_ix = -1;
12832     OP *fop;
12833     OP *sop;
12834
12835     if (!o || o->op_opt)
12836         return;
12837     ENTER;
12838     SAVEOP();
12839     SAVEVPTR(PL_curcop);
12840     for (;; o = o->op_next) {
12841         if (o && o->op_opt)
12842             o = NULL;
12843         if (!o) {
12844             while (defer_ix >= 0) {
12845                 OP **defer =
12846                         defer_queue[(defer_base + defer_ix--) % MAX_DEFERRED];
12847                 CALL_RPEEP(*defer);
12848                 S_prune_chain_head(defer);
12849             }
12850             break;
12851         }
12852
12853       redo:
12854         /* By default, this op has now been optimised. A couple of cases below
12855            clear this again.  */
12856         o->op_opt = 1;
12857         PL_op = o;
12858
12859         /* look for a series of 1 or more aggregate derefs, e.g.
12860          *   $a[1]{foo}[$i]{$k}
12861          * and replace with a single OP_MULTIDEREF op.
12862          * Each index must be either a const, or a simple variable,
12863          *
12864          * First, look for likely combinations of starting ops,
12865          * corresponding to (global and lexical variants of)
12866          *     $a[...]   $h{...}
12867          *     $r->[...] $r->{...}
12868          *     (preceding expression)->[...]
12869          *     (preceding expression)->{...}
12870          * and if so, call maybe_multideref() to do a full inspection
12871          * of the op chain and if appropriate, replace with an
12872          * OP_MULTIDEREF
12873          */
12874         {
12875             UV action;
12876             OP *o2 = o;
12877             U8 hints = 0;
12878
12879             switch (o2->op_type) {
12880             case OP_GV:
12881                 /* $pkg[..]   :   gv[*pkg]
12882                  * $pkg->[...]:   gv[*pkg]; rv2sv sKM/DREFAV */
12883
12884                 /* Fail if there are new op flag combinations that we're
12885                  * not aware of, rather than:
12886                  *  * silently failing to optimise, or
12887                  *  * silently optimising the flag away.
12888                  * If this ASSUME starts failing, examine what new flag
12889                  * has been added to the op, and decide whether the
12890                  * optimisation should still occur with that flag, then
12891                  * update the code accordingly. This applies to all the
12892                  * other ASSUMEs in the block of code too.
12893                  */
12894                 ASSUME(!(o2->op_flags & ~(OPf_WANT|OPf_MOD|OPf_SPECIAL)));
12895                 ASSUME(!(o2->op_private & ~OPpEARLY_CV));
12896
12897                 o2 = o2->op_next;
12898
12899                 if (o2->op_type == OP_RV2AV) {
12900                     action = MDEREF_AV_gvav_aelem;
12901                     goto do_deref;
12902                 }
12903
12904                 if (o2->op_type == OP_RV2HV) {
12905                     action = MDEREF_HV_gvhv_helem;
12906                     goto do_deref;
12907                 }
12908
12909                 if (o2->op_type != OP_RV2SV)
12910                     break;
12911
12912                 /* at this point we've seen gv,rv2sv, so the only valid
12913                  * construct left is $pkg->[] or $pkg->{} */
12914
12915                 ASSUME(!(o2->op_flags & OPf_STACKED));
12916                 if ((o2->op_flags & (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
12917                             != (OPf_WANT_SCALAR|OPf_MOD))
12918                     break;
12919
12920                 ASSUME(!(o2->op_private & ~(OPpARG1_MASK|HINT_STRICT_REFS
12921                                     |OPpOUR_INTRO|OPpDEREF|OPpLVAL_INTRO)));
12922                 if (o2->op_private & (OPpOUR_INTRO|OPpLVAL_INTRO))
12923                     break;
12924                 if (   (o2->op_private & OPpDEREF) != OPpDEREF_AV
12925                     && (o2->op_private & OPpDEREF) != OPpDEREF_HV)
12926                     break;
12927
12928                 o2 = o2->op_next;
12929                 if (o2->op_type == OP_RV2AV) {
12930                     action = MDEREF_AV_gvsv_vivify_rv2av_aelem;
12931                     goto do_deref;
12932                 }
12933                 if (o2->op_type == OP_RV2HV) {
12934                     action = MDEREF_HV_gvsv_vivify_rv2hv_helem;
12935                     goto do_deref;
12936                 }
12937                 break;
12938
12939             case OP_PADSV:
12940                 /* $lex->[...]: padsv[$lex] sM/DREFAV */
12941
12942                 ASSUME(!(o2->op_flags &
12943                     ~(OPf_WANT|OPf_PARENS|OPf_REF|OPf_MOD|OPf_SPECIAL)));
12944                 if ((o2->op_flags &
12945                         (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
12946                      != (OPf_WANT_SCALAR|OPf_MOD))
12947                     break;
12948
12949                 ASSUME(!(o2->op_private &
12950                                 ~(OPpPAD_STATE|OPpDEREF|OPpLVAL_INTRO)));
12951                 /* skip if state or intro, or not a deref */
12952                 if (      o2->op_private != OPpDEREF_AV
12953                        && o2->op_private != OPpDEREF_HV)
12954                     break;
12955
12956                 o2 = o2->op_next;
12957                 if (o2->op_type == OP_RV2AV) {
12958                     action = MDEREF_AV_padsv_vivify_rv2av_aelem;
12959                     goto do_deref;
12960                 }
12961                 if (o2->op_type == OP_RV2HV) {
12962                     action = MDEREF_HV_padsv_vivify_rv2hv_helem;
12963                     goto do_deref;
12964                 }
12965                 break;
12966
12967             case OP_PADAV:
12968             case OP_PADHV:
12969                 /*    $lex[..]:  padav[@lex:1,2] sR *
12970                  * or $lex{..}:  padhv[%lex:1,2] sR */
12971                 ASSUME(!(o2->op_flags & ~(OPf_WANT|OPf_MOD|OPf_PARENS|
12972                                             OPf_REF|OPf_SPECIAL)));
12973                 if ((o2->op_flags &
12974                         (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
12975                      != (OPf_WANT_SCALAR|OPf_REF))
12976                     break;
12977                 if (o2->op_flags != (OPf_WANT_SCALAR|OPf_REF))
12978                     break;
12979                 /* OPf_PARENS isn't currently used in this case;
12980                  * if that changes, let us know! */
12981                 ASSUME(!(o2->op_flags & OPf_PARENS));
12982
12983                 /* at this point, we wouldn't expect any of the remaining
12984                  * possible private flags:
12985                  * OPpPAD_STATE, OPpLVAL_INTRO, OPpTRUEBOOL,
12986                  * OPpMAYBE_TRUEBOOL, OPpMAYBE_LVSUB
12987                  *
12988                  * OPpSLICEWARNING shouldn't affect runtime
12989                  */
12990                 ASSUME(!(o2->op_private & ~(OPpSLICEWARNING)));
12991
12992                 action = o2->op_type == OP_PADAV
12993                             ? MDEREF_AV_padav_aelem
12994                             : MDEREF_HV_padhv_helem;
12995                 o2 = o2->op_next;
12996                 S_maybe_multideref(aTHX_ o, o2, action, 0);
12997                 break;
12998
12999
13000             case OP_RV2AV:
13001             case OP_RV2HV:
13002                 action = o2->op_type == OP_RV2AV
13003                             ? MDEREF_AV_pop_rv2av_aelem
13004                             : MDEREF_HV_pop_rv2hv_helem;
13005                 /* FALLTHROUGH */
13006             do_deref:
13007                 /* (expr)->[...]:  rv2av sKR/1;
13008                  * (expr)->{...}:  rv2hv sKR/1; */
13009
13010                 ASSUME(o2->op_type == OP_RV2AV || o2->op_type == OP_RV2HV);
13011
13012                 ASSUME(!(o2->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
13013                                 |OPf_REF|OPf_MOD|OPf_STACKED|OPf_SPECIAL)));
13014                 if (o2->op_flags != (OPf_WANT_SCALAR|OPf_KIDS|OPf_REF))
13015                     break;
13016
13017                 /* at this point, we wouldn't expect any of these
13018                  * possible private flags:
13019                  * OPpMAYBE_LVSUB, OPpLVAL_INTRO
13020                  * OPpTRUEBOOL, OPpMAYBE_TRUEBOOL, (rv2hv only)
13021                  */
13022                 ASSUME(!(o2->op_private &
13023                     ~(OPpHINT_STRICT_REFS|OPpARG1_MASK|OPpSLICEWARNING
13024                      |OPpOUR_INTRO)));
13025                 hints |= (o2->op_private & OPpHINT_STRICT_REFS);
13026
13027                 o2 = o2->op_next;
13028
13029                 S_maybe_multideref(aTHX_ o, o2, action, hints);
13030                 break;
13031
13032             default:
13033                 break;
13034             }
13035         }
13036
13037
13038         switch (o->op_type) {
13039         case OP_DBSTATE:
13040             PL_curcop = ((COP*)o);              /* for warnings */
13041             break;
13042         case OP_NEXTSTATE:
13043             PL_curcop = ((COP*)o);              /* for warnings */
13044
13045             /* Optimise a "return ..." at the end of a sub to just be "...".
13046              * This saves 2 ops. Before:
13047              * 1  <;> nextstate(main 1 -e:1) v ->2
13048              * 4  <@> return K ->5
13049              * 2    <0> pushmark s ->3
13050              * -    <1> ex-rv2sv sK/1 ->4
13051              * 3      <#> gvsv[*cat] s ->4
13052              *
13053              * After:
13054              * -  <@> return K ->-
13055              * -    <0> pushmark s ->2
13056              * -    <1> ex-rv2sv sK/1 ->-
13057              * 2      <$> gvsv(*cat) s ->3
13058              */
13059             {
13060                 OP *next = o->op_next;
13061                 OP *sibling = OpSIBLING(o);
13062                 if (   OP_TYPE_IS(next, OP_PUSHMARK)
13063                     && OP_TYPE_IS(sibling, OP_RETURN)
13064                     && OP_TYPE_IS(sibling->op_next, OP_LINESEQ)
13065                     && ( OP_TYPE_IS(sibling->op_next->op_next, OP_LEAVESUB)
13066                        ||OP_TYPE_IS(sibling->op_next->op_next,
13067                                     OP_LEAVESUBLV))
13068                     && cUNOPx(sibling)->op_first == next
13069                     && OpHAS_SIBLING(next) && OpSIBLING(next)->op_next
13070                     && next->op_next
13071                 ) {
13072                     /* Look through the PUSHMARK's siblings for one that
13073                      * points to the RETURN */
13074                     OP *top = OpSIBLING(next);
13075                     while (top && top->op_next) {
13076                         if (top->op_next == sibling) {
13077                             top->op_next = sibling->op_next;
13078                             o->op_next = next->op_next;
13079                             break;
13080                         }
13081                         top = OpSIBLING(top);
13082                     }
13083                 }
13084             }
13085
13086             /* Optimise 'my $x; my $y;' into 'my ($x, $y);'
13087              *
13088              * This latter form is then suitable for conversion into padrange
13089              * later on. Convert:
13090              *
13091              *   nextstate1 -> padop1 -> nextstate2 -> padop2 -> nextstate3
13092              *
13093              * into:
13094              *
13095              *   nextstate1 ->     listop     -> nextstate3
13096              *                 /            \
13097              *         pushmark -> padop1 -> padop2
13098              */
13099             if (o->op_next && (
13100                     o->op_next->op_type == OP_PADSV
13101                  || o->op_next->op_type == OP_PADAV
13102                  || o->op_next->op_type == OP_PADHV
13103                 )
13104                 && !(o->op_next->op_private & ~OPpLVAL_INTRO)
13105                 && o->op_next->op_next && o->op_next->op_next->op_type == OP_NEXTSTATE
13106                 && o->op_next->op_next->op_next && (
13107                     o->op_next->op_next->op_next->op_type == OP_PADSV
13108                  || o->op_next->op_next->op_next->op_type == OP_PADAV
13109                  || o->op_next->op_next->op_next->op_type == OP_PADHV
13110                 )
13111                 && !(o->op_next->op_next->op_next->op_private & ~OPpLVAL_INTRO)
13112                 && o->op_next->op_next->op_next->op_next && o->op_next->op_next->op_next->op_next->op_type == OP_NEXTSTATE
13113                 && (!CopLABEL((COP*)o)) /* Don't mess with labels */
13114                 && (!CopLABEL((COP*)o->op_next->op_next)) /* ... */
13115             ) {
13116                 OP *pad1, *ns2, *pad2, *ns3, *newop, *newpm;
13117
13118                 pad1 =    o->op_next;
13119                 ns2  = pad1->op_next;
13120                 pad2 =  ns2->op_next;
13121                 ns3  = pad2->op_next;
13122
13123                 /* we assume here that the op_next chain is the same as
13124                  * the op_sibling chain */
13125                 assert(OpSIBLING(o)    == pad1);
13126                 assert(OpSIBLING(pad1) == ns2);
13127                 assert(OpSIBLING(ns2)  == pad2);
13128                 assert(OpSIBLING(pad2) == ns3);
13129
13130                 /* create new listop, with children consisting of:
13131                  * a new pushmark, pad1, pad2. */
13132                 OpSIBLING_set(pad2, NULL);
13133                 newop = newLISTOP(OP_LIST, 0, pad1, pad2);
13134                 newop->op_flags |= OPf_PARENS;
13135                 newop->op_flags = (newop->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
13136                 newpm = cUNOPx(newop)->op_first; /* pushmark */
13137
13138                 /* Kill nextstate2 between padop1/padop2 */
13139                 op_free(ns2);
13140
13141                 o    ->op_next = newpm;
13142                 newpm->op_next = pad1;
13143                 pad1 ->op_next = pad2;
13144                 pad2 ->op_next = newop; /* listop */
13145                 newop->op_next = ns3;
13146
13147                 OpSIBLING_set(o, newop);
13148                 OpSIBLING_set(newop, ns3);
13149                 newop->op_lastsib = 0;
13150
13151                 newop->op_flags = (newop->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
13152
13153                 /* Ensure pushmark has this flag if padops do */
13154                 if (pad1->op_flags & OPf_MOD && pad2->op_flags & OPf_MOD) {
13155                     o->op_next->op_flags |= OPf_MOD;
13156                 }
13157
13158                 break;
13159             }
13160
13161             /* Two NEXTSTATEs in a row serve no purpose. Except if they happen
13162                to carry two labels. For now, take the easier option, and skip
13163                this optimisation if the first NEXTSTATE has a label.  */
13164             if (!CopLABEL((COP*)o) && !PERLDB_NOOPT) {
13165                 OP *nextop = o->op_next;
13166                 while (nextop && nextop->op_type == OP_NULL)
13167                     nextop = nextop->op_next;
13168
13169                 if (nextop && (nextop->op_type == OP_NEXTSTATE)) {
13170                     op_null(o);
13171                     if (oldop)
13172                         oldop->op_next = nextop;
13173                     /* Skip (old)oldop assignment since the current oldop's
13174                        op_next already points to the next op.  */
13175                     continue;
13176                 }
13177             }
13178             break;
13179
13180         case OP_CONCAT:
13181             if (o->op_next && o->op_next->op_type == OP_STRINGIFY) {
13182                 if (o->op_next->op_private & OPpTARGET_MY) {
13183                     if (o->op_flags & OPf_STACKED) /* chained concats */
13184                         break; /* ignore_optimization */
13185                     else {
13186                         /* assert(PL_opargs[o->op_type] & OA_TARGLEX); */
13187                         o->op_targ = o->op_next->op_targ;
13188                         o->op_next->op_targ = 0;
13189                         o->op_private |= OPpTARGET_MY;
13190                     }
13191                 }
13192                 op_null(o->op_next);
13193             }
13194             break;
13195         case OP_STUB:
13196             if ((o->op_flags & OPf_WANT) != OPf_WANT_LIST) {
13197                 break; /* Scalar stub must produce undef.  List stub is noop */
13198             }
13199             goto nothin;
13200         case OP_NULL:
13201             if (o->op_targ == OP_NEXTSTATE
13202                 || o->op_targ == OP_DBSTATE)
13203             {
13204                 PL_curcop = ((COP*)o);
13205             }
13206             /* XXX: We avoid setting op_seq here to prevent later calls
13207                to rpeep() from mistakenly concluding that optimisation
13208                has already occurred. This doesn't fix the real problem,
13209                though (See 20010220.007). AMS 20010719 */
13210             /* op_seq functionality is now replaced by op_opt */
13211             o->op_opt = 0;
13212             /* FALLTHROUGH */
13213         case OP_SCALAR:
13214         case OP_LINESEQ:
13215         case OP_SCOPE:
13216         nothin:
13217             if (oldop) {
13218                 oldop->op_next = o->op_next;
13219                 o->op_opt = 0;
13220                 continue;
13221             }
13222             break;
13223
13224         case OP_PUSHMARK:
13225
13226             /* Given
13227                  5 repeat/DOLIST
13228                  3   ex-list
13229                  1     pushmark
13230                  2     scalar or const
13231                  4   const[0]
13232                convert repeat into a stub with no kids.
13233              */
13234             if (o->op_next->op_type == OP_CONST
13235              || (  o->op_next->op_type == OP_PADSV
13236                 && !(o->op_next->op_private & OPpLVAL_INTRO))
13237              || (  o->op_next->op_type == OP_GV
13238                 && o->op_next->op_next->op_type == OP_RV2SV
13239                 && !(o->op_next->op_next->op_private
13240                         & (OPpLVAL_INTRO|OPpOUR_INTRO))))
13241             {
13242                 const OP *kid = o->op_next->op_next;
13243                 if (o->op_next->op_type == OP_GV)
13244                    kid = kid->op_next;
13245                 /* kid is now the ex-list.  */
13246                 if (kid->op_type == OP_NULL
13247                  && (kid = kid->op_next)->op_type == OP_CONST
13248                     /* kid is now the repeat count.  */
13249                  && kid->op_next->op_type == OP_REPEAT
13250                  && kid->op_next->op_private & OPpREPEAT_DOLIST
13251                  && (kid->op_next->op_flags & OPf_WANT) == OPf_WANT_LIST
13252                  && SvIOK(kSVOP_sv) && SvIVX(kSVOP_sv) == 0)
13253                 {
13254                     o = kid->op_next; /* repeat */
13255                     assert(oldop);
13256                     oldop->op_next = o;
13257                     op_free(cBINOPo->op_first);
13258                     op_free(cBINOPo->op_last );
13259                     o->op_flags &=~ OPf_KIDS;
13260                     /* stub is a baseop; repeat is a binop */
13261                     STATIC_ASSERT_STMT(sizeof(OP) <= sizeof(BINOP));
13262                     CHANGE_TYPE(o, OP_STUB);
13263                     o->op_private = 0;
13264                     break;
13265                 }
13266             }
13267
13268             /* Convert a series of PAD ops for my vars plus support into a
13269              * single padrange op. Basically
13270              *
13271              *    pushmark -> pad[ahs]v -> pad[ahs]?v -> ... -> (list) -> rest
13272              *
13273              * becomes, depending on circumstances, one of
13274              *
13275              *    padrange  ----------------------------------> (list) -> rest
13276              *    padrange  --------------------------------------------> rest
13277              *
13278              * where all the pad indexes are sequential and of the same type
13279              * (INTRO or not).
13280              * We convert the pushmark into a padrange op, then skip
13281              * any other pad ops, and possibly some trailing ops.
13282              * Note that we don't null() the skipped ops, to make it
13283              * easier for Deparse to undo this optimisation (and none of
13284              * the skipped ops are holding any resourses). It also makes
13285              * it easier for find_uninit_var(), as it can just ignore
13286              * padrange, and examine the original pad ops.
13287              */
13288         {
13289             OP *p;
13290             OP *followop = NULL; /* the op that will follow the padrange op */
13291             U8 count = 0;
13292             U8 intro = 0;
13293             PADOFFSET base = 0; /* init only to stop compiler whining */
13294             bool gvoid = 0;     /* init only to stop compiler whining */
13295             bool defav = 0;  /* seen (...) = @_ */
13296             bool reuse = 0;  /* reuse an existing padrange op */
13297
13298             /* look for a pushmark -> gv[_] -> rv2av */
13299
13300             {
13301                 OP *rv2av, *q;
13302                 p = o->op_next;
13303                 if (   p->op_type == OP_GV
13304                     && cGVOPx_gv(p) == PL_defgv
13305                     && (rv2av = p->op_next)
13306                     && rv2av->op_type == OP_RV2AV
13307                     && !(rv2av->op_flags & OPf_REF)
13308                     && !(rv2av->op_private & (OPpLVAL_INTRO|OPpMAYBE_LVSUB))
13309                     && ((rv2av->op_flags & OPf_WANT) == OPf_WANT_LIST)
13310                 ) {
13311                     q = rv2av->op_next;
13312                     if (q->op_type == OP_NULL)
13313                         q = q->op_next;
13314                     if (q->op_type == OP_PUSHMARK) {
13315                         defav = 1;
13316                         p = q;
13317                     }
13318                 }
13319             }
13320             if (!defav) {
13321                 p = o;
13322             }
13323
13324             /* scan for PAD ops */
13325
13326             for (p = p->op_next; p; p = p->op_next) {
13327                 if (p->op_type == OP_NULL)
13328                     continue;
13329
13330                 if ((     p->op_type != OP_PADSV
13331                        && p->op_type != OP_PADAV
13332                        && p->op_type != OP_PADHV
13333                     )
13334                       /* any private flag other than INTRO? e.g. STATE */
13335                    || (p->op_private & ~OPpLVAL_INTRO)
13336                 )
13337                     break;
13338
13339                 /* let $a[N] potentially be optimised into AELEMFAST_LEX
13340                  * instead */
13341                 if (   p->op_type == OP_PADAV
13342                     && p->op_next
13343                     && p->op_next->op_type == OP_CONST
13344                     && p->op_next->op_next
13345                     && p->op_next->op_next->op_type == OP_AELEM
13346                 )
13347                     break;
13348
13349                 /* for 1st padop, note what type it is and the range
13350                  * start; for the others, check that it's the same type
13351                  * and that the targs are contiguous */
13352                 if (count == 0) {
13353                     intro = (p->op_private & OPpLVAL_INTRO);
13354                     base = p->op_targ;
13355                     gvoid = OP_GIMME(p,0) == G_VOID;
13356                 }
13357                 else {
13358                     if ((p->op_private & OPpLVAL_INTRO) != intro)
13359                         break;
13360                     /* Note that you'd normally  expect targs to be
13361                      * contiguous in my($a,$b,$c), but that's not the case
13362                      * when external modules start doing things, e.g.
13363                      i* Function::Parameters */
13364                     if (p->op_targ != base + count)
13365                         break;
13366                     assert(p->op_targ == base + count);
13367                     /* Either all the padops or none of the padops should
13368                        be in void context.  Since we only do the optimisa-
13369                        tion for av/hv when the aggregate itself is pushed
13370                        on to the stack (one item), there is no need to dis-
13371                        tinguish list from scalar context.  */
13372                     if (gvoid != (OP_GIMME(p,0) == G_VOID))
13373                         break;
13374                 }
13375
13376                 /* for AV, HV, only when we're not flattening */
13377                 if (   p->op_type != OP_PADSV
13378                     && !gvoid
13379                     && !(p->op_flags & OPf_REF)
13380                 )
13381                     break;
13382
13383                 if (count >= OPpPADRANGE_COUNTMASK)
13384                     break;
13385
13386                 /* there's a biggest base we can fit into a
13387                  * SAVEt_CLEARPADRANGE in pp_padrange */
13388                 if (intro && base >
13389                         (UV_MAX >> (OPpPADRANGE_COUNTSHIFT+SAVE_TIGHT_SHIFT)))
13390                     break;
13391
13392                 /* Success! We've got another valid pad op to optimise away */
13393                 count++;
13394                 followop = p->op_next;
13395             }
13396
13397             if (count < 1 || (count == 1 && !defav))
13398                 break;
13399
13400             /* pp_padrange in specifically compile-time void context
13401              * skips pushing a mark and lexicals; in all other contexts
13402              * (including unknown till runtime) it pushes a mark and the
13403              * lexicals. We must be very careful then, that the ops we
13404              * optimise away would have exactly the same effect as the
13405              * padrange.
13406              * In particular in void context, we can only optimise to
13407              * a padrange if see see the complete sequence
13408              *     pushmark, pad*v, ...., list
13409              * which has the net effect of of leaving the markstack as it
13410              * was.  Not pushing on to the stack (whereas padsv does touch
13411              * the stack) makes no difference in void context.
13412              */
13413             assert(followop);
13414             if (gvoid) {
13415                 if (followop->op_type == OP_LIST
13416                         && OP_GIMME(followop,0) == G_VOID
13417                    )
13418                 {
13419                     followop = followop->op_next; /* skip OP_LIST */
13420
13421                     /* consolidate two successive my(...);'s */
13422
13423                     if (   oldoldop
13424                         && oldoldop->op_type == OP_PADRANGE
13425                         && (oldoldop->op_flags & OPf_WANT) == OPf_WANT_VOID
13426                         && (oldoldop->op_private & OPpLVAL_INTRO) == intro
13427                         && !(oldoldop->op_flags & OPf_SPECIAL)
13428                     ) {
13429                         U8 old_count;
13430                         assert(oldoldop->op_next == oldop);
13431                         assert(   oldop->op_type == OP_NEXTSTATE
13432                                || oldop->op_type == OP_DBSTATE);
13433                         assert(oldop->op_next == o);
13434
13435                         old_count
13436                             = (oldoldop->op_private & OPpPADRANGE_COUNTMASK);
13437
13438                        /* Do not assume pad offsets for $c and $d are con-
13439                           tiguous in
13440                             my ($a,$b,$c);
13441                             my ($d,$e,$f);
13442                         */
13443                         if (  oldoldop->op_targ + old_count == base
13444                            && old_count < OPpPADRANGE_COUNTMASK - count) {
13445                             base = oldoldop->op_targ;
13446                             count += old_count;
13447                             reuse = 1;
13448                         }
13449                     }
13450
13451                     /* if there's any immediately following singleton
13452                      * my var's; then swallow them and the associated
13453                      * nextstates; i.e.
13454                      *    my ($a,$b); my $c; my $d;
13455                      * is treated as
13456                      *    my ($a,$b,$c,$d);
13457                      */
13458
13459                     while (    ((p = followop->op_next))
13460                             && (  p->op_type == OP_PADSV
13461                                || p->op_type == OP_PADAV
13462                                || p->op_type == OP_PADHV)
13463                             && (p->op_flags & OPf_WANT) == OPf_WANT_VOID
13464                             && (p->op_private & OPpLVAL_INTRO) == intro
13465                             && !(p->op_private & ~OPpLVAL_INTRO)
13466                             && p->op_next
13467                             && (   p->op_next->op_type == OP_NEXTSTATE
13468                                 || p->op_next->op_type == OP_DBSTATE)
13469                             && count < OPpPADRANGE_COUNTMASK
13470                             && base + count == p->op_targ
13471                     ) {
13472                         count++;
13473                         followop = p->op_next;
13474                     }
13475                 }
13476                 else
13477                     break;
13478             }
13479
13480             if (reuse) {
13481                 assert(oldoldop->op_type == OP_PADRANGE);
13482                 oldoldop->op_next = followop;
13483                 oldoldop->op_private = (intro | count);
13484                 o = oldoldop;
13485                 oldop = NULL;
13486                 oldoldop = NULL;
13487             }
13488             else {
13489                 /* Convert the pushmark into a padrange.
13490                  * To make Deparse easier, we guarantee that a padrange was
13491                  * *always* formerly a pushmark */
13492                 assert(o->op_type == OP_PUSHMARK);
13493                 o->op_next = followop;
13494                 CHANGE_TYPE(o, OP_PADRANGE);
13495                 o->op_targ = base;
13496                 /* bit 7: INTRO; bit 6..0: count */
13497                 o->op_private = (intro | count);
13498                 o->op_flags = ((o->op_flags & ~(OPf_WANT|OPf_SPECIAL))
13499                               | gvoid * OPf_WANT_VOID
13500                               | (defav ? OPf_SPECIAL : 0));
13501             }
13502             break;
13503         }
13504
13505         case OP_PADAV:
13506         case OP_PADSV:
13507         case OP_PADHV:
13508         /* Skip over state($x) in void context.  */
13509         if (oldop && o->op_private == (OPpPAD_STATE|OPpLVAL_INTRO)
13510          && (o->op_flags & OPf_WANT) == OPf_WANT_VOID)
13511         {
13512             oldop->op_next = o->op_next;
13513             goto redo_nextstate;
13514         }
13515         if (o->op_type != OP_PADAV)
13516             break;
13517         /* FALLTHROUGH */
13518         case OP_GV:
13519             if (o->op_type == OP_PADAV || o->op_next->op_type == OP_RV2AV) {
13520                 OP* const pop = (o->op_type == OP_PADAV) ?
13521                             o->op_next : o->op_next->op_next;
13522                 IV i;
13523                 if (pop && pop->op_type == OP_CONST &&
13524                     ((PL_op = pop->op_next)) &&
13525                     pop->op_next->op_type == OP_AELEM &&
13526                     !(pop->op_next->op_private &
13527                       (OPpLVAL_INTRO|OPpLVAL_DEFER|OPpDEREF|OPpMAYBE_LVSUB)) &&
13528                     (i = SvIV(((SVOP*)pop)->op_sv)) >= -128 && i <= 127)
13529                 {
13530                     GV *gv;
13531                     if (cSVOPx(pop)->op_private & OPpCONST_STRICT)
13532                         no_bareword_allowed(pop);
13533                     if (o->op_type == OP_GV)
13534                         op_null(o->op_next);
13535                     op_null(pop->op_next);
13536                     op_null(pop);
13537                     o->op_flags |= pop->op_next->op_flags & OPf_MOD;
13538                     o->op_next = pop->op_next->op_next;
13539                     o->op_ppaddr = PL_ppaddr[OP_AELEMFAST];
13540                     o->op_private = (U8)i;
13541                     if (o->op_type == OP_GV) {
13542                         gv = cGVOPo_gv;
13543                         GvAVn(gv);
13544                         o->op_type = OP_AELEMFAST;
13545                     }
13546                     else
13547                         o->op_type = OP_AELEMFAST_LEX;
13548                 }
13549                 if (o->op_type != OP_GV)
13550                     break;
13551             }
13552
13553             /* Remove $foo from the op_next chain in void context.  */
13554             if (oldop
13555              && (  o->op_next->op_type == OP_RV2SV
13556                 || o->op_next->op_type == OP_RV2AV
13557                 || o->op_next->op_type == OP_RV2HV  )
13558              && (o->op_next->op_flags & OPf_WANT) == OPf_WANT_VOID
13559              && !(o->op_next->op_private & OPpLVAL_INTRO))
13560             {
13561                 oldop->op_next = o->op_next->op_next;
13562                 /* Reprocess the previous op if it is a nextstate, to
13563                    allow double-nextstate optimisation.  */
13564               redo_nextstate:
13565                 if (oldop->op_type == OP_NEXTSTATE) {
13566                     oldop->op_opt = 0;
13567                     o = oldop;
13568                     oldop = oldoldop;
13569                     oldoldop = NULL;
13570                     goto redo;
13571                 }
13572                 o = oldop;
13573             }
13574             else if (o->op_next->op_type == OP_RV2SV) {
13575                 if (!(o->op_next->op_private & OPpDEREF)) {
13576                     op_null(o->op_next);
13577                     o->op_private |= o->op_next->op_private & (OPpLVAL_INTRO
13578                                                                | OPpOUR_INTRO);
13579                     o->op_next = o->op_next->op_next;
13580                     CHANGE_TYPE(o, OP_GVSV);
13581                 }
13582             }
13583             else if (o->op_next->op_type == OP_READLINE
13584                     && o->op_next->op_next->op_type == OP_CONCAT
13585                     && (o->op_next->op_next->op_flags & OPf_STACKED))
13586             {
13587                 /* Turn "$a .= <FH>" into an OP_RCATLINE. AMS 20010917 */
13588                 CHANGE_TYPE(o, OP_RCATLINE);
13589                 o->op_flags |= OPf_STACKED;
13590                 op_null(o->op_next->op_next);
13591                 op_null(o->op_next);
13592             }
13593
13594             break;
13595         
13596 #define HV_OR_SCALARHV(op)                                   \
13597     (  (op)->op_type == OP_PADHV || (op)->op_type == OP_RV2HV \
13598        ? (op)                                                  \
13599        : (op)->op_type == OP_SCALAR && (op)->op_flags & OPf_KIDS \
13600        && (  cUNOPx(op)->op_first->op_type == OP_PADHV          \
13601           || cUNOPx(op)->op_first->op_type == OP_RV2HV)          \
13602          ? cUNOPx(op)->op_first                                   \
13603          : NULL)
13604
13605         case OP_NOT:
13606             if ((fop = HV_OR_SCALARHV(cUNOP->op_first)))
13607                 fop->op_private |= OPpTRUEBOOL;
13608             break;
13609
13610         case OP_AND:
13611         case OP_OR:
13612         case OP_DOR:
13613             fop = cLOGOP->op_first;
13614             sop = OpSIBLING(fop);
13615             while (cLOGOP->op_other->op_type == OP_NULL)
13616                 cLOGOP->op_other = cLOGOP->op_other->op_next;
13617             while (o->op_next && (   o->op_type == o->op_next->op_type
13618                                   || o->op_next->op_type == OP_NULL))
13619                 o->op_next = o->op_next->op_next;
13620
13621             /* if we're an OR and our next is a AND in void context, we'll
13622                follow it's op_other on short circuit, same for reverse.
13623                We can't do this with OP_DOR since if it's true, its return
13624                value is the underlying value which must be evaluated
13625                by the next op */
13626             if (o->op_next &&
13627                 (
13628                     (IS_AND_OP(o) && IS_OR_OP(o->op_next))
13629                  || (IS_OR_OP(o) && IS_AND_OP(o->op_next))
13630                 )
13631                 && (o->op_next->op_flags & OPf_WANT) == OPf_WANT_VOID
13632             ) {
13633                 o->op_next = ((LOGOP*)o->op_next)->op_other;
13634             }
13635             DEFER(cLOGOP->op_other);
13636           
13637             o->op_opt = 1;
13638             fop = HV_OR_SCALARHV(fop);
13639             if (sop) sop = HV_OR_SCALARHV(sop);
13640             if (fop || sop
13641             ){  
13642                 OP * nop = o;
13643                 OP * lop = o;
13644                 if (!((nop->op_flags & OPf_WANT) == OPf_WANT_VOID)) {
13645                     while (nop && nop->op_next) {
13646                         switch (nop->op_next->op_type) {
13647                             case OP_NOT:
13648                             case OP_AND:
13649                             case OP_OR:
13650                             case OP_DOR:
13651                                 lop = nop = nop->op_next;
13652                                 break;
13653                             case OP_NULL:
13654                                 nop = nop->op_next;
13655                                 break;
13656                             default:
13657                                 nop = NULL;
13658                                 break;
13659                         }
13660                     }            
13661                 }
13662                 if (fop) {
13663                     if (  (lop->op_flags & OPf_WANT) == OPf_WANT_VOID
13664                       || o->op_type == OP_AND  )
13665                         fop->op_private |= OPpTRUEBOOL;
13666                     else if (!(lop->op_flags & OPf_WANT))
13667                         fop->op_private |= OPpMAYBE_TRUEBOOL;
13668                 }
13669                 if (  (lop->op_flags & OPf_WANT) == OPf_WANT_VOID
13670                    && sop)
13671                     sop->op_private |= OPpTRUEBOOL;
13672             }                  
13673             
13674             
13675             break;
13676         
13677         case OP_COND_EXPR:
13678             if ((fop = HV_OR_SCALARHV(cLOGOP->op_first)))
13679                 fop->op_private |= OPpTRUEBOOL;
13680 #undef HV_OR_SCALARHV
13681             /* GERONIMO! */ /* FALLTHROUGH */
13682
13683         case OP_MAPWHILE:
13684         case OP_GREPWHILE:
13685         case OP_ANDASSIGN:
13686         case OP_ORASSIGN:
13687         case OP_DORASSIGN:
13688         case OP_RANGE:
13689         case OP_ONCE:
13690             while (cLOGOP->op_other->op_type == OP_NULL)
13691                 cLOGOP->op_other = cLOGOP->op_other->op_next;
13692             DEFER(cLOGOP->op_other);
13693             break;
13694
13695         case OP_ENTERLOOP:
13696         case OP_ENTERITER:
13697             while (cLOOP->op_redoop->op_type == OP_NULL)
13698                 cLOOP->op_redoop = cLOOP->op_redoop->op_next;
13699             while (cLOOP->op_nextop->op_type == OP_NULL)
13700                 cLOOP->op_nextop = cLOOP->op_nextop->op_next;
13701             while (cLOOP->op_lastop->op_type == OP_NULL)
13702                 cLOOP->op_lastop = cLOOP->op_lastop->op_next;
13703             /* a while(1) loop doesn't have an op_next that escapes the
13704              * loop, so we have to explicitly follow the op_lastop to
13705              * process the rest of the code */
13706             DEFER(cLOOP->op_lastop);
13707             break;
13708
13709         case OP_ENTERTRY:
13710             assert(cLOGOPo->op_other->op_type == OP_LEAVETRY);
13711             DEFER(cLOGOPo->op_other);
13712             break;
13713
13714         case OP_SUBST:
13715             assert(!(cPMOP->op_pmflags & PMf_ONCE));
13716             while (cPMOP->op_pmstashstartu.op_pmreplstart &&
13717                    cPMOP->op_pmstashstartu.op_pmreplstart->op_type == OP_NULL)
13718                 cPMOP->op_pmstashstartu.op_pmreplstart
13719                     = cPMOP->op_pmstashstartu.op_pmreplstart->op_next;
13720             DEFER(cPMOP->op_pmstashstartu.op_pmreplstart);
13721             break;
13722
13723         case OP_SORT: {
13724             OP *oright;
13725
13726             if (o->op_flags & OPf_SPECIAL) {
13727                 /* first arg is a code block */
13728                 OP * const nullop = OpSIBLING(cLISTOP->op_first);
13729                 OP * kid          = cUNOPx(nullop)->op_first;
13730
13731                 assert(nullop->op_type == OP_NULL);
13732                 assert(kid->op_type == OP_SCOPE
13733                  || (kid->op_type == OP_NULL && kid->op_targ == OP_LEAVE));
13734                 /* since OP_SORT doesn't have a handy op_other-style
13735                  * field that can point directly to the start of the code
13736                  * block, store it in the otherwise-unused op_next field
13737                  * of the top-level OP_NULL. This will be quicker at
13738                  * run-time, and it will also allow us to remove leading
13739                  * OP_NULLs by just messing with op_nexts without
13740                  * altering the basic op_first/op_sibling layout. */
13741                 kid = kLISTOP->op_first;
13742                 assert(
13743                       (kid->op_type == OP_NULL
13744                       && (  kid->op_targ == OP_NEXTSTATE
13745                          || kid->op_targ == OP_DBSTATE  ))
13746                     || kid->op_type == OP_STUB
13747                     || kid->op_type == OP_ENTER);
13748                 nullop->op_next = kLISTOP->op_next;
13749                 DEFER(nullop->op_next);
13750             }
13751
13752             /* check that RHS of sort is a single plain array */
13753             oright = cUNOPo->op_first;
13754             if (!oright || oright->op_type != OP_PUSHMARK)
13755                 break;
13756
13757             if (o->op_private & OPpSORT_INPLACE)
13758                 break;
13759
13760             /* reverse sort ... can be optimised.  */
13761             if (!OpHAS_SIBLING(cUNOPo)) {
13762                 /* Nothing follows us on the list. */
13763                 OP * const reverse = o->op_next;
13764
13765                 if (reverse->op_type == OP_REVERSE &&
13766                     (reverse->op_flags & OPf_WANT) == OPf_WANT_LIST) {
13767                     OP * const pushmark = cUNOPx(reverse)->op_first;
13768                     if (pushmark && (pushmark->op_type == OP_PUSHMARK)
13769                         && (OpSIBLING(cUNOPx(pushmark)) == o)) {
13770                         /* reverse -> pushmark -> sort */
13771                         o->op_private |= OPpSORT_REVERSE;
13772                         op_null(reverse);
13773                         pushmark->op_next = oright->op_next;
13774                         op_null(oright);
13775                     }
13776                 }
13777             }
13778
13779             break;
13780         }
13781
13782         case OP_REVERSE: {
13783             OP *ourmark, *theirmark, *ourlast, *iter, *expushmark, *rv2av;
13784             OP *gvop = NULL;
13785             LISTOP *enter, *exlist;
13786
13787             if (o->op_private & OPpSORT_INPLACE)
13788                 break;
13789
13790             enter = (LISTOP *) o->op_next;
13791             if (!enter)
13792                 break;
13793             if (enter->op_type == OP_NULL) {
13794                 enter = (LISTOP *) enter->op_next;
13795                 if (!enter)
13796                     break;
13797             }
13798             /* for $a (...) will have OP_GV then OP_RV2GV here.
13799                for (...) just has an OP_GV.  */
13800             if (enter->op_type == OP_GV) {
13801                 gvop = (OP *) enter;
13802                 enter = (LISTOP *) enter->op_next;
13803                 if (!enter)
13804                     break;
13805                 if (enter->op_type == OP_RV2GV) {
13806                   enter = (LISTOP *) enter->op_next;
13807                   if (!enter)
13808                     break;
13809                 }
13810             }
13811
13812             if (enter->op_type != OP_ENTERITER)
13813                 break;
13814
13815             iter = enter->op_next;
13816             if (!iter || iter->op_type != OP_ITER)
13817                 break;
13818             
13819             expushmark = enter->op_first;
13820             if (!expushmark || expushmark->op_type != OP_NULL
13821                 || expushmark->op_targ != OP_PUSHMARK)
13822                 break;
13823
13824             exlist = (LISTOP *) OpSIBLING(expushmark);
13825             if (!exlist || exlist->op_type != OP_NULL
13826                 || exlist->op_targ != OP_LIST)
13827                 break;
13828
13829             if (exlist->op_last != o) {
13830                 /* Mmm. Was expecting to point back to this op.  */
13831                 break;
13832             }
13833             theirmark = exlist->op_first;
13834             if (!theirmark || theirmark->op_type != OP_PUSHMARK)
13835                 break;
13836
13837             if (OpSIBLING(theirmark) != o) {
13838                 /* There's something between the mark and the reverse, eg
13839                    for (1, reverse (...))
13840                    so no go.  */
13841                 break;
13842             }
13843
13844             ourmark = ((LISTOP *)o)->op_first;
13845             if (!ourmark || ourmark->op_type != OP_PUSHMARK)
13846                 break;
13847
13848             ourlast = ((LISTOP *)o)->op_last;
13849             if (!ourlast || ourlast->op_next != o)
13850                 break;
13851
13852             rv2av = OpSIBLING(ourmark);
13853             if (rv2av && rv2av->op_type == OP_RV2AV && !OpHAS_SIBLING(rv2av)
13854                 && rv2av->op_flags == (OPf_WANT_LIST | OPf_KIDS)
13855                 && enter->op_flags == (OPf_WANT_LIST | OPf_KIDS)) {
13856                 /* We're just reversing a single array.  */
13857                 rv2av->op_flags = OPf_WANT_SCALAR | OPf_KIDS | OPf_REF;
13858                 enter->op_flags |= OPf_STACKED;
13859             }
13860
13861             /* We don't have control over who points to theirmark, so sacrifice
13862                ours.  */
13863             theirmark->op_next = ourmark->op_next;
13864             theirmark->op_flags = ourmark->op_flags;
13865             ourlast->op_next = gvop ? gvop : (OP *) enter;
13866             op_null(ourmark);
13867             op_null(o);
13868             enter->op_private |= OPpITER_REVERSED;
13869             iter->op_private |= OPpITER_REVERSED;
13870             
13871             break;
13872         }
13873
13874         case OP_QR:
13875         case OP_MATCH:
13876             if (!(cPMOP->op_pmflags & PMf_ONCE)) {
13877                 assert (!cPMOP->op_pmstashstartu.op_pmreplstart);
13878             }
13879             break;
13880
13881         case OP_RUNCV:
13882             if (!(o->op_private & OPpOFFBYONE) && !CvCLONE(PL_compcv)
13883              && (!CvANON(PL_compcv) || (!PL_cv_has_eval && !PL_perldb)))
13884             {
13885                 SV *sv;
13886                 if (CvEVAL(PL_compcv)) sv = &PL_sv_undef;
13887                 else {
13888                     sv = newRV((SV *)PL_compcv);
13889                     sv_rvweaken(sv);
13890                     SvREADONLY_on(sv);
13891                 }
13892                 CHANGE_TYPE(o, OP_CONST);
13893                 o->op_flags |= OPf_SPECIAL;
13894                 cSVOPo->op_sv = sv;
13895             }
13896             break;
13897
13898         case OP_SASSIGN:
13899             if (OP_GIMME(o,0) == G_VOID
13900              || (  o->op_next->op_type == OP_LINESEQ
13901                 && (  o->op_next->op_next->op_type == OP_LEAVESUB
13902                    || (  o->op_next->op_next->op_type == OP_RETURN
13903                       && !CvLVALUE(PL_compcv)))))
13904             {
13905                 OP *right = cBINOP->op_first;
13906                 if (right) {
13907                     /*   sassign
13908                     *      RIGHT
13909                     *      substr
13910                     *         pushmark
13911                     *         arg1
13912                     *         arg2
13913                     *         ...
13914                     * becomes
13915                     *
13916                     *  ex-sassign
13917                     *     substr
13918                     *        pushmark
13919                     *        RIGHT
13920                     *        arg1
13921                     *        arg2
13922                     *        ...
13923                     */
13924                     OP *left = OpSIBLING(right);
13925                     if (left->op_type == OP_SUBSTR
13926                          && (left->op_private & 7) < 4) {
13927                         op_null(o);
13928                         /* cut out right */
13929                         op_sibling_splice(o, NULL, 1, NULL);
13930                         /* and insert it as second child of OP_SUBSTR */
13931                         op_sibling_splice(left, cBINOPx(left)->op_first, 0,
13932                                     right);
13933                         left->op_private |= OPpSUBSTR_REPL_FIRST;
13934                         left->op_flags =
13935                             (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
13936                     }
13937                 }
13938             }
13939             break;
13940
13941         case OP_AASSIGN:
13942             /* We do the common-vars check here, rather than in newASSIGNOP
13943                (as formerly), so that all lexical vars that get aliased are
13944                marked as such before we do the check.  */
13945             /* There can’t be common vars if the lhs is a stub.  */
13946             if (OpSIBLING(cLISTOPx(cBINOPo->op_last)->op_first)
13947                     == cLISTOPx(cBINOPo->op_last)->op_last
13948              && cLISTOPx(cBINOPo->op_last)->op_last->op_type == OP_STUB)
13949             {
13950                 o->op_private &=~ OPpASSIGN_COMMON;
13951                 break;
13952             }
13953             if (o->op_private & OPpASSIGN_COMMON) {
13954                  /* See the comment before S_aassign_common_vars concerning
13955                     PL_generation sorcery.  */
13956                 PL_generation++;
13957                 if (!aassign_common_vars(o))
13958                     o->op_private &=~ OPpASSIGN_COMMON;
13959             }
13960             else if (S_aassign_common_vars_aliases_only(aTHX_ o))
13961                 o->op_private |= OPpASSIGN_COMMON;
13962             break;
13963
13964         case OP_CUSTOM: {
13965             Perl_cpeep_t cpeep = 
13966                 XopENTRYCUSTOM(o, xop_peep);
13967             if (cpeep)
13968                 cpeep(aTHX_ o, oldop);
13969             break;
13970         }
13971             
13972         }
13973         /* did we just null the current op? If so, re-process it to handle
13974          * eliding "empty" ops from the chain */
13975         if (o->op_type == OP_NULL && oldop && oldop->op_next == o) {
13976             o->op_opt = 0;
13977             o = oldop;
13978         }
13979         else {
13980             oldoldop = oldop;
13981             oldop = o;
13982         }
13983     }
13984     LEAVE;
13985 }
13986
13987 void
13988 Perl_peep(pTHX_ OP *o)
13989 {
13990     CALL_RPEEP(o);
13991 }
13992
13993 /*
13994 =head1 Custom Operators
13995
13996 =for apidoc Ao||custom_op_xop
13997 Return the XOP structure for a given custom op.  This macro should be
13998 considered internal to OP_NAME and the other access macros: use them instead.
13999 This macro does call a function.  Prior
14000 to 5.19.6, this was implemented as a
14001 function.
14002
14003 =cut
14004 */
14005
14006 XOPRETANY
14007 Perl_custom_op_get_field(pTHX_ const OP *o, const xop_flags_enum field)
14008 {
14009     SV *keysv;
14010     HE *he = NULL;
14011     XOP *xop;
14012
14013     static const XOP xop_null = { 0, 0, 0, 0, 0 };
14014
14015     PERL_ARGS_ASSERT_CUSTOM_OP_GET_FIELD;
14016     assert(o->op_type == OP_CUSTOM);
14017
14018     /* This is wrong. It assumes a function pointer can be cast to IV,
14019      * which isn't guaranteed, but this is what the old custom OP code
14020      * did. In principle it should be safer to Copy the bytes of the
14021      * pointer into a PV: since the new interface is hidden behind
14022      * functions, this can be changed later if necessary.  */
14023     /* Change custom_op_xop if this ever happens */
14024     keysv = sv_2mortal(newSViv(PTR2IV(o->op_ppaddr)));
14025
14026     if (PL_custom_ops)
14027         he = hv_fetch_ent(PL_custom_ops, keysv, 0, 0);
14028
14029     /* assume noone will have just registered a desc */
14030     if (!he && PL_custom_op_names &&
14031         (he = hv_fetch_ent(PL_custom_op_names, keysv, 0, 0))
14032     ) {
14033         const char *pv;
14034         STRLEN l;
14035
14036         /* XXX does all this need to be shared mem? */
14037         Newxz(xop, 1, XOP);
14038         pv = SvPV(HeVAL(he), l);
14039         XopENTRY_set(xop, xop_name, savepvn(pv, l));
14040         if (PL_custom_op_descs &&
14041             (he = hv_fetch_ent(PL_custom_op_descs, keysv, 0, 0))
14042         ) {
14043             pv = SvPV(HeVAL(he), l);
14044             XopENTRY_set(xop, xop_desc, savepvn(pv, l));
14045         }
14046         Perl_custom_op_register(aTHX_ o->op_ppaddr, xop);
14047     }
14048     else {
14049         if (!he)
14050             xop = (XOP *)&xop_null;
14051         else
14052             xop = INT2PTR(XOP *, SvIV(HeVAL(he)));
14053     }
14054     {
14055         XOPRETANY any;
14056         if(field == XOPe_xop_ptr) {
14057             any.xop_ptr = xop;
14058         } else {
14059             const U32 flags = XopFLAGS(xop);
14060             if(flags & field) {
14061                 switch(field) {
14062                 case XOPe_xop_name:
14063                     any.xop_name = xop->xop_name;
14064                     break;
14065                 case XOPe_xop_desc:
14066                     any.xop_desc = xop->xop_desc;
14067                     break;
14068                 case XOPe_xop_class:
14069                     any.xop_class = xop->xop_class;
14070                     break;
14071                 case XOPe_xop_peep:
14072                     any.xop_peep = xop->xop_peep;
14073                     break;
14074                 default:
14075                     NOT_REACHED;
14076                     break;
14077                 }
14078             } else {
14079                 switch(field) {
14080                 case XOPe_xop_name:
14081                     any.xop_name = XOPd_xop_name;
14082                     break;
14083                 case XOPe_xop_desc:
14084                     any.xop_desc = XOPd_xop_desc;
14085                     break;
14086                 case XOPe_xop_class:
14087                     any.xop_class = XOPd_xop_class;
14088                     break;
14089                 case XOPe_xop_peep:
14090                     any.xop_peep = XOPd_xop_peep;
14091                     break;
14092                 default:
14093                     NOT_REACHED;
14094                     break;
14095                 }
14096             }
14097         }
14098         /* Some gcc releases emit a warning for this function:
14099          * op.c: In function 'Perl_custom_op_get_field':
14100          * op.c:...: warning: 'any.xop_name' may be used uninitialized in this function [-Wmaybe-uninitialized]
14101          * Whether this is true, is currently unknown. */
14102         return any;
14103     }
14104 }
14105
14106 /*
14107 =for apidoc Ao||custom_op_register
14108 Register a custom op.  See L<perlguts/"Custom Operators">.
14109
14110 =cut
14111 */
14112
14113 void
14114 Perl_custom_op_register(pTHX_ Perl_ppaddr_t ppaddr, const XOP *xop)
14115 {
14116     SV *keysv;
14117
14118     PERL_ARGS_ASSERT_CUSTOM_OP_REGISTER;
14119
14120     /* see the comment in custom_op_xop */
14121     keysv = sv_2mortal(newSViv(PTR2IV(ppaddr)));
14122
14123     if (!PL_custom_ops)
14124         PL_custom_ops = newHV();
14125
14126     if (!hv_store_ent(PL_custom_ops, keysv, newSViv(PTR2IV(xop)), 0))
14127         Perl_croak(aTHX_ "panic: can't register custom OP %s", xop->xop_name);
14128 }
14129
14130 /*
14131
14132 =for apidoc core_prototype
14133
14134 This function assigns the prototype of the named core function to C<sv>, or
14135 to a new mortal SV if C<sv> is NULL.  It returns the modified C<sv>, or
14136 NULL if the core function has no prototype.  C<code> is a code as returned
14137 by C<keyword()>.  It must not be equal to 0.
14138
14139 =cut
14140 */
14141
14142 SV *
14143 Perl_core_prototype(pTHX_ SV *sv, const char *name, const int code,
14144                           int * const opnum)
14145 {
14146     int i = 0, n = 0, seen_question = 0, defgv = 0;
14147     I32 oa;
14148 #define MAX_ARGS_OP ((sizeof(I32) - 1) * 2)
14149     char str[ MAX_ARGS_OP * 2 + 2 ]; /* One ';', one '\0' */
14150     bool nullret = FALSE;
14151
14152     PERL_ARGS_ASSERT_CORE_PROTOTYPE;
14153
14154     assert (code);
14155
14156     if (!sv) sv = sv_newmortal();
14157
14158 #define retsetpvs(x,y) sv_setpvs(sv, x); if(opnum) *opnum=(y); return sv
14159
14160     switch (code < 0 ? -code : code) {
14161     case KEY_and   : case KEY_chop: case KEY_chomp:
14162     case KEY_cmp   : case KEY_defined: case KEY_delete: case KEY_exec  :
14163     case KEY_exists: case KEY_eq     : case KEY_ge    : case KEY_goto  :
14164     case KEY_grep  : case KEY_gt     : case KEY_last  : case KEY_le    :
14165     case KEY_lt    : case KEY_map    : case KEY_ne    : case KEY_next  :
14166     case KEY_or    : case KEY_print  : case KEY_printf: case KEY_qr    :
14167     case KEY_redo  : case KEY_require: case KEY_return: case KEY_say   :
14168     case KEY_select: case KEY_sort   : case KEY_split : case KEY_system:
14169     case KEY_x     : case KEY_xor    :
14170         if (!opnum) return NULL; nullret = TRUE; goto findopnum;
14171     case KEY_glob:    retsetpvs("_;", OP_GLOB);
14172     case KEY_keys:    retsetpvs("+", OP_KEYS);
14173     case KEY_values:  retsetpvs("+", OP_VALUES);
14174     case KEY_each:    retsetpvs("+", OP_EACH);
14175     case KEY_push:    retsetpvs("+@", OP_PUSH);
14176     case KEY_unshift: retsetpvs("+@", OP_UNSHIFT);
14177     case KEY_pop:     retsetpvs(";+", OP_POP);
14178     case KEY_shift:   retsetpvs(";+", OP_SHIFT);
14179     case KEY_pos:     retsetpvs(";\\[$*]", OP_POS);
14180     case KEY_splice:
14181         retsetpvs("+;$$@", OP_SPLICE);
14182     case KEY___FILE__: case KEY___LINE__: case KEY___PACKAGE__:
14183         retsetpvs("", 0);
14184     case KEY_evalbytes:
14185         name = "entereval"; break;
14186     case KEY_readpipe:
14187         name = "backtick";
14188     }
14189
14190 #undef retsetpvs
14191
14192   findopnum:
14193     while (i < MAXO) {  /* The slow way. */
14194         if (strEQ(name, PL_op_name[i])
14195             || strEQ(name, PL_op_desc[i]))
14196         {
14197             if (nullret) { assert(opnum); *opnum = i; return NULL; }
14198             goto found;
14199         }
14200         i++;
14201     }
14202     return NULL;
14203   found:
14204     defgv = PL_opargs[i] & OA_DEFGV;
14205     oa = PL_opargs[i] >> OASHIFT;
14206     while (oa) {
14207         if (oa & OA_OPTIONAL && !seen_question && (
14208               !defgv || (oa & (OA_OPTIONAL - 1)) == OA_FILEREF
14209         )) {
14210             seen_question = 1;
14211             str[n++] = ';';
14212         }
14213         if ((oa & (OA_OPTIONAL - 1)) >= OA_AVREF
14214             && (oa & (OA_OPTIONAL - 1)) <= OA_SCALARREF
14215             /* But globs are already references (kinda) */
14216             && (oa & (OA_OPTIONAL - 1)) != OA_FILEREF
14217         ) {
14218             str[n++] = '\\';
14219         }
14220         if ((oa & (OA_OPTIONAL - 1)) == OA_SCALARREF
14221          && !scalar_mod_type(NULL, i)) {
14222             str[n++] = '[';
14223             str[n++] = '$';
14224             str[n++] = '@';
14225             str[n++] = '%';
14226             if (i == OP_LOCK || i == OP_UNDEF) str[n++] = '&';
14227             str[n++] = '*';
14228             str[n++] = ']';
14229         }
14230         else str[n++] = ("?$@@%&*$")[oa & (OA_OPTIONAL - 1)];
14231         if (oa & OA_OPTIONAL && defgv && str[n-1] == '$') {
14232             str[n-1] = '_'; defgv = 0;
14233         }
14234         oa = oa >> 4;
14235     }
14236     if (code == -KEY_not || code == -KEY_getprotobynumber) str[n++] = ';';
14237     str[n++] = '\0';
14238     sv_setpvn(sv, str, n - 1);
14239     if (opnum) *opnum = i;
14240     return sv;
14241 }
14242
14243 OP *
14244 Perl_coresub_op(pTHX_ SV * const coreargssv, const int code,
14245                       const int opnum)
14246 {
14247     OP * const argop = newSVOP(OP_COREARGS,0,coreargssv);
14248     OP *o;
14249
14250     PERL_ARGS_ASSERT_CORESUB_OP;
14251
14252     switch(opnum) {
14253     case 0:
14254         return op_append_elem(OP_LINESEQ,
14255                        argop,
14256                        newSLICEOP(0,
14257                                   newSVOP(OP_CONST, 0, newSViv(-code % 3)),
14258                                   newOP(OP_CALLER,0)
14259                        )
14260                );
14261     case OP_SELECT: /* which represents OP_SSELECT as well */
14262         if (code)
14263             return newCONDOP(
14264                          0,
14265                          newBINOP(OP_GT, 0,
14266                                   newAVREF(newGVOP(OP_GV, 0, PL_defgv)),
14267                                   newSVOP(OP_CONST, 0, newSVuv(1))
14268                                  ),
14269                          coresub_op(newSVuv((UV)OP_SSELECT), 0,
14270                                     OP_SSELECT),
14271                          coresub_op(coreargssv, 0, OP_SELECT)
14272                    );
14273         /* FALLTHROUGH */
14274     default:
14275         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
14276         case OA_BASEOP:
14277             return op_append_elem(
14278                         OP_LINESEQ, argop,
14279                         newOP(opnum,
14280                               opnum == OP_WANTARRAY || opnum == OP_RUNCV
14281                                 ? OPpOFFBYONE << 8 : 0)
14282                    );
14283         case OA_BASEOP_OR_UNOP:
14284             if (opnum == OP_ENTEREVAL) {
14285                 o = newUNOP(OP_ENTEREVAL,OPpEVAL_COPHH<<8,argop);
14286                 if (code == -KEY_evalbytes) o->op_private |= OPpEVAL_BYTES;
14287             }
14288             else o = newUNOP(opnum,0,argop);
14289             if (opnum == OP_CALLER) o->op_private |= OPpOFFBYONE;
14290             else {
14291           onearg:
14292               if (is_handle_constructor(o, 1))
14293                 argop->op_private |= OPpCOREARGS_DEREF1;
14294               if (scalar_mod_type(NULL, opnum))
14295                 argop->op_private |= OPpCOREARGS_SCALARMOD;
14296             }
14297             return o;
14298         default:
14299             o = op_convert_list(opnum,OPf_SPECIAL*(opnum == OP_GLOB),argop);
14300             if (is_handle_constructor(o, 2))
14301                 argop->op_private |= OPpCOREARGS_DEREF2;
14302             if (opnum == OP_SUBSTR) {
14303                 o->op_private |= OPpMAYBE_LVSUB;
14304                 return o;
14305             }
14306             else goto onearg;
14307         }
14308     }
14309 }
14310
14311 void
14312 Perl_report_redefined_cv(pTHX_ const SV *name, const CV *old_cv,
14313                                SV * const *new_const_svp)
14314 {
14315     const char *hvname;
14316     bool is_const = !!CvCONST(old_cv);
14317     SV *old_const_sv = is_const ? cv_const_sv(old_cv) : NULL;
14318
14319     PERL_ARGS_ASSERT_REPORT_REDEFINED_CV;
14320
14321     if (is_const && new_const_svp && old_const_sv == *new_const_svp)
14322         return;
14323         /* They are 2 constant subroutines generated from
14324            the same constant. This probably means that
14325            they are really the "same" proxy subroutine
14326            instantiated in 2 places. Most likely this is
14327            when a constant is exported twice.  Don't warn.
14328         */
14329     if (
14330         (ckWARN(WARN_REDEFINE)
14331          && !(
14332                 CvGV(old_cv) && GvSTASH(CvGV(old_cv))
14333              && HvNAMELEN(GvSTASH(CvGV(old_cv))) == 7
14334              && (hvname = HvNAME(GvSTASH(CvGV(old_cv))),
14335                  strEQ(hvname, "autouse"))
14336              )
14337         )
14338      || (is_const
14339          && ckWARN_d(WARN_REDEFINE)
14340          && (!new_const_svp || sv_cmp(old_const_sv, *new_const_svp))
14341         )
14342     )
14343         Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
14344                           is_const
14345                             ? "Constant subroutine %"SVf" redefined"
14346                             : "Subroutine %"SVf" redefined",
14347                           SVfARG(name));
14348 }
14349
14350 /*
14351 =head1 Hook manipulation
14352
14353 These functions provide convenient and thread-safe means of manipulating
14354 hook variables.
14355
14356 =cut
14357 */
14358
14359 /*
14360 =for apidoc Am|void|wrap_op_checker|Optype opcode|Perl_check_t new_checker|Perl_check_t *old_checker_p
14361
14362 Puts a C function into the chain of check functions for a specified op
14363 type.  This is the preferred way to manipulate the L</PL_check> array.
14364 I<opcode> specifies which type of op is to be affected.  I<new_checker>
14365 is a pointer to the C function that is to be added to that opcode's
14366 check chain, and I<old_checker_p> points to the storage location where a
14367 pointer to the next function in the chain will be stored.  The value of
14368 I<new_pointer> is written into the L</PL_check> array, while the value
14369 previously stored there is written to I<*old_checker_p>.
14370
14371 The function should be defined like this:
14372
14373     static OP *new_checker(pTHX_ OP *op) { ... }
14374
14375 It is intended to be called in this manner:
14376
14377     new_checker(aTHX_ op)
14378
14379 I<old_checker_p> should be defined like this:
14380
14381     static Perl_check_t old_checker_p;
14382
14383 L</PL_check> is global to an entire process, and a module wishing to
14384 hook op checking may find itself invoked more than once per process,
14385 typically in different threads.  To handle that situation, this function
14386 is idempotent.  The location I<*old_checker_p> must initially (once
14387 per process) contain a null pointer.  A C variable of static duration
14388 (declared at file scope, typically also marked C<static> to give
14389 it internal linkage) will be implicitly initialised appropriately,
14390 if it does not have an explicit initialiser.  This function will only
14391 actually modify the check chain if it finds I<*old_checker_p> to be null.
14392 This function is also thread safe on the small scale.  It uses appropriate
14393 locking to avoid race conditions in accessing L</PL_check>.
14394
14395 When this function is called, the function referenced by I<new_checker>
14396 must be ready to be called, except for I<*old_checker_p> being unfilled.
14397 In a threading situation, I<new_checker> may be called immediately,
14398 even before this function has returned.  I<*old_checker_p> will always
14399 be appropriately set before I<new_checker> is called.  If I<new_checker>
14400 decides not to do anything special with an op that it is given (which
14401 is the usual case for most uses of op check hooking), it must chain the
14402 check function referenced by I<*old_checker_p>.
14403
14404 If you want to influence compilation of calls to a specific subroutine,
14405 then use L</cv_set_call_checker> rather than hooking checking of all
14406 C<entersub> ops.
14407
14408 =cut
14409 */
14410
14411 void
14412 Perl_wrap_op_checker(pTHX_ Optype opcode,
14413     Perl_check_t new_checker, Perl_check_t *old_checker_p)
14414 {
14415     dVAR;
14416
14417     PERL_UNUSED_CONTEXT;
14418     PERL_ARGS_ASSERT_WRAP_OP_CHECKER;
14419     if (*old_checker_p) return;
14420     OP_CHECK_MUTEX_LOCK;
14421     if (!*old_checker_p) {
14422         *old_checker_p = PL_check[opcode];
14423         PL_check[opcode] = new_checker;
14424     }
14425     OP_CHECK_MUTEX_UNLOCK;
14426 }
14427
14428 #include "XSUB.h"
14429
14430 /* Efficient sub that returns a constant scalar value. */
14431 static void
14432 const_sv_xsub(pTHX_ CV* cv)
14433 {
14434     dXSARGS;
14435     SV *const sv = MUTABLE_SV(XSANY.any_ptr);
14436     PERL_UNUSED_ARG(items);
14437     if (!sv) {
14438         XSRETURN(0);
14439     }
14440     EXTEND(sp, 1);
14441     ST(0) = sv;
14442     XSRETURN(1);
14443 }
14444
14445 static void
14446 const_av_xsub(pTHX_ CV* cv)
14447 {
14448     dXSARGS;
14449     AV * const av = MUTABLE_AV(XSANY.any_ptr);
14450     SP -= items;
14451     assert(av);
14452 #ifndef DEBUGGING
14453     if (!av) {
14454         XSRETURN(0);
14455     }
14456 #endif
14457     if (SvRMAGICAL(av))
14458         Perl_croak(aTHX_ "Magical list constants are not supported");
14459     if (GIMME_V != G_ARRAY) {
14460         EXTEND(SP, 1);
14461         ST(0) = sv_2mortal(newSViv((IV)AvFILLp(av)+1));
14462         XSRETURN(1);
14463     }
14464     EXTEND(SP, AvFILLp(av)+1);
14465     Copy(AvARRAY(av), &ST(0), AvFILLp(av)+1, SV *);
14466     XSRETURN(AvFILLp(av)+1);
14467 }
14468
14469 /*
14470  * Local variables:
14471  * c-indentation-style: bsd
14472  * c-basic-offset: 4
14473  * indent-tabs-mode: nil
14474  * End:
14475  *
14476  * ex: set ts=8 sts=4 sw=4 et:
14477  */