This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Make sort bareword respect lexical subs
[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 /* remove any leading "empty" ops from the op_next chain whose first
113  * node's address is stored in op_p. Store the updated address of the
114  * first node in op_p.
115  */
116
117 STATIC void
118 S_prune_chain_head(OP** op_p)
119 {
120     while (*op_p
121         && (   (*op_p)->op_type == OP_NULL
122             || (*op_p)->op_type == OP_SCOPE
123             || (*op_p)->op_type == OP_SCALAR
124             || (*op_p)->op_type == OP_LINESEQ)
125     )
126         *op_p = (*op_p)->op_next;
127 }
128
129
130 /* See the explanatory comments above struct opslab in op.h. */
131
132 #ifdef PERL_DEBUG_READONLY_OPS
133 #  define PERL_SLAB_SIZE 128
134 #  define PERL_MAX_SLAB_SIZE 4096
135 #  include <sys/mman.h>
136 #endif
137
138 #ifndef PERL_SLAB_SIZE
139 #  define PERL_SLAB_SIZE 64
140 #endif
141 #ifndef PERL_MAX_SLAB_SIZE
142 #  define PERL_MAX_SLAB_SIZE 2048
143 #endif
144
145 /* rounds up to nearest pointer */
146 #define SIZE_TO_PSIZE(x)        (((x) + sizeof(I32 *) - 1)/sizeof(I32 *))
147 #define DIFF(o,p)               ((size_t)((I32 **)(p) - (I32**)(o)))
148
149 static OPSLAB *
150 S_new_slab(pTHX_ size_t sz)
151 {
152 #ifdef PERL_DEBUG_READONLY_OPS
153     OPSLAB *slab = (OPSLAB *) mmap(0, sz * sizeof(I32 *),
154                                    PROT_READ|PROT_WRITE,
155                                    MAP_ANON|MAP_PRIVATE, -1, 0);
156     DEBUG_m(PerlIO_printf(Perl_debug_log, "mapped %lu at %p\n",
157                           (unsigned long) sz, slab));
158     if (slab == MAP_FAILED) {
159         perror("mmap failed");
160         abort();
161     }
162     slab->opslab_size = (U16)sz;
163 #else
164     OPSLAB *slab = (OPSLAB *)PerlMemShared_calloc(sz, sizeof(I32 *));
165 #endif
166 #ifndef WIN32
167     /* The context is unused in non-Windows */
168     PERL_UNUSED_CONTEXT;
169 #endif
170     slab->opslab_first = (OPSLOT *)((I32 **)slab + sz - 1);
171     return slab;
172 }
173
174 /* requires double parens and aTHX_ */
175 #define DEBUG_S_warn(args)                                             \
176     DEBUG_S(                                                            \
177         PerlIO_printf(Perl_debug_log, "%s", SvPVx_nolen(Perl_mess args)) \
178     )
179
180 void *
181 Perl_Slab_Alloc(pTHX_ size_t sz)
182 {
183     OPSLAB *slab;
184     OPSLAB *slab2;
185     OPSLOT *slot;
186     OP *o;
187     size_t opsz, space;
188
189     /* We only allocate ops from the slab during subroutine compilation.
190        We find the slab via PL_compcv, hence that must be non-NULL. It could
191        also be pointing to a subroutine which is now fully set up (CvROOT()
192        pointing to the top of the optree for that sub), or a subroutine
193        which isn't using the slab allocator. If our sanity checks aren't met,
194        don't use a slab, but allocate the OP directly from the heap.  */
195     if (!PL_compcv || CvROOT(PL_compcv)
196      || (CvSTART(PL_compcv) && !CvSLABBED(PL_compcv)))
197     {
198         o = (OP*)PerlMemShared_calloc(1, sz);
199         goto gotit;
200     }
201
202     /* While the subroutine is under construction, the slabs are accessed via
203        CvSTART(), to avoid needing to expand PVCV by one pointer for something
204        unneeded at runtime. Once a subroutine is constructed, the slabs are
205        accessed via CvROOT(). So if CvSTART() is NULL, no slab has been
206        allocated yet.  See the commit message for 8be227ab5eaa23f2 for more
207        details.  */
208     if (!CvSTART(PL_compcv)) {
209         CvSTART(PL_compcv) =
210             (OP *)(slab = S_new_slab(aTHX_ PERL_SLAB_SIZE));
211         CvSLABBED_on(PL_compcv);
212         slab->opslab_refcnt = 2; /* one for the CV; one for the new OP */
213     }
214     else ++(slab = (OPSLAB *)CvSTART(PL_compcv))->opslab_refcnt;
215
216     opsz = SIZE_TO_PSIZE(sz);
217     sz = opsz + OPSLOT_HEADER_P;
218
219     /* The slabs maintain a free list of OPs. In particular, constant folding
220        will free up OPs, so it makes sense to re-use them where possible. A
221        freed up slot is used in preference to a new allocation.  */
222     if (slab->opslab_freed) {
223         OP **too = &slab->opslab_freed;
224         o = *too;
225         DEBUG_S_warn((aTHX_ "found free op at %p, slab %p", (void*)o, (void*)slab));
226         while (o && DIFF(OpSLOT(o), OpSLOT(o)->opslot_next) < sz) {
227             DEBUG_S_warn((aTHX_ "Alas! too small"));
228             o = *(too = &o->op_next);
229             if (o) { DEBUG_S_warn((aTHX_ "found another free op at %p", (void*)o)); }
230         }
231         if (o) {
232             *too = o->op_next;
233             Zero(o, opsz, I32 *);
234             o->op_slabbed = 1;
235             goto gotit;
236         }
237     }
238
239 #define INIT_OPSLOT \
240             slot->opslot_slab = slab;                   \
241             slot->opslot_next = slab2->opslab_first;    \
242             slab2->opslab_first = slot;                 \
243             o = &slot->opslot_op;                       \
244             o->op_slabbed = 1
245
246     /* The partially-filled slab is next in the chain. */
247     slab2 = slab->opslab_next ? slab->opslab_next : slab;
248     if ((space = DIFF(&slab2->opslab_slots, slab2->opslab_first)) < sz) {
249         /* Remaining space is too small. */
250
251         /* If we can fit a BASEOP, add it to the free chain, so as not
252            to waste it. */
253         if (space >= SIZE_TO_PSIZE(sizeof(OP)) + OPSLOT_HEADER_P) {
254             slot = &slab2->opslab_slots;
255             INIT_OPSLOT;
256             o->op_type = OP_FREED;
257             o->op_next = slab->opslab_freed;
258             slab->opslab_freed = o;
259         }
260
261         /* Create a new slab.  Make this one twice as big. */
262         slot = slab2->opslab_first;
263         while (slot->opslot_next) slot = slot->opslot_next;
264         slab2 = S_new_slab(aTHX_
265                             (DIFF(slab2, slot)+1)*2 > PERL_MAX_SLAB_SIZE
266                                         ? PERL_MAX_SLAB_SIZE
267                                         : (DIFF(slab2, slot)+1)*2);
268         slab2->opslab_next = slab->opslab_next;
269         slab->opslab_next = slab2;
270     }
271     assert(DIFF(&slab2->opslab_slots, slab2->opslab_first) >= sz);
272
273     /* Create a new op slot */
274     slot = (OPSLOT *)((I32 **)slab2->opslab_first - sz);
275     assert(slot >= &slab2->opslab_slots);
276     if (DIFF(&slab2->opslab_slots, slot)
277          < SIZE_TO_PSIZE(sizeof(OP)) + OPSLOT_HEADER_P)
278         slot = &slab2->opslab_slots;
279     INIT_OPSLOT;
280     DEBUG_S_warn((aTHX_ "allocating op at %p, slab %p", (void*)o, (void*)slab));
281
282   gotit:
283     /* lastsib == 1, op_sibling == 0 implies a solitary unattached op */
284     o->op_lastsib = 1;
285     assert(!o->op_sibling);
286
287     return (void *)o;
288 }
289
290 #undef INIT_OPSLOT
291
292 #ifdef PERL_DEBUG_READONLY_OPS
293 void
294 Perl_Slab_to_ro(pTHX_ OPSLAB *slab)
295 {
296     PERL_ARGS_ASSERT_SLAB_TO_RO;
297
298     if (slab->opslab_readonly) return;
299     slab->opslab_readonly = 1;
300     for (; slab; slab = slab->opslab_next) {
301         /*DEBUG_U(PerlIO_printf(Perl_debug_log,"mprotect ->ro %lu at %p\n",
302                               (unsigned long) slab->opslab_size, slab));*/
303         if (mprotect(slab, slab->opslab_size * sizeof(I32 *), PROT_READ))
304             Perl_warn(aTHX_ "mprotect for %p %lu failed with %d", slab,
305                              (unsigned long)slab->opslab_size, errno);
306     }
307 }
308
309 void
310 Perl_Slab_to_rw(pTHX_ OPSLAB *const slab)
311 {
312     OPSLAB *slab2;
313
314     PERL_ARGS_ASSERT_SLAB_TO_RW;
315
316     if (!slab->opslab_readonly) return;
317     slab2 = slab;
318     for (; slab2; slab2 = slab2->opslab_next) {
319         /*DEBUG_U(PerlIO_printf(Perl_debug_log,"mprotect ->rw %lu at %p\n",
320                               (unsigned long) size, slab2));*/
321         if (mprotect((void *)slab2, slab2->opslab_size * sizeof(I32 *),
322                      PROT_READ|PROT_WRITE)) {
323             Perl_warn(aTHX_ "mprotect RW for %p %lu failed with %d", slab,
324                              (unsigned long)slab2->opslab_size, errno);
325         }
326     }
327     slab->opslab_readonly = 0;
328 }
329
330 #else
331 #  define Slab_to_rw(op)    NOOP
332 #endif
333
334 /* This cannot possibly be right, but it was copied from the old slab
335    allocator, to which it was originally added, without explanation, in
336    commit 083fcd5. */
337 #ifdef NETWARE
338 #    define PerlMemShared PerlMem
339 #endif
340
341 void
342 Perl_Slab_Free(pTHX_ void *op)
343 {
344     OP * const o = (OP *)op;
345     OPSLAB *slab;
346
347     PERL_ARGS_ASSERT_SLAB_FREE;
348
349     if (!o->op_slabbed) {
350         if (!o->op_static)
351             PerlMemShared_free(op);
352         return;
353     }
354
355     slab = OpSLAB(o);
356     /* If this op is already freed, our refcount will get screwy. */
357     assert(o->op_type != OP_FREED);
358     o->op_type = OP_FREED;
359     o->op_next = slab->opslab_freed;
360     slab->opslab_freed = o;
361     DEBUG_S_warn((aTHX_ "free op at %p, recorded in slab %p", (void*)o, (void*)slab));
362     OpslabREFCNT_dec_padok(slab);
363 }
364
365 void
366 Perl_opslab_free_nopad(pTHX_ OPSLAB *slab)
367 {
368     const bool havepad = !!PL_comppad;
369     PERL_ARGS_ASSERT_OPSLAB_FREE_NOPAD;
370     if (havepad) {
371         ENTER;
372         PAD_SAVE_SETNULLPAD();
373     }
374     opslab_free(slab);
375     if (havepad) LEAVE;
376 }
377
378 void
379 Perl_opslab_free(pTHX_ OPSLAB *slab)
380 {
381     OPSLAB *slab2;
382     PERL_ARGS_ASSERT_OPSLAB_FREE;
383     PERL_UNUSED_CONTEXT;
384     DEBUG_S_warn((aTHX_ "freeing slab %p", (void*)slab));
385     assert(slab->opslab_refcnt == 1);
386     for (; slab; slab = slab2) {
387         slab2 = slab->opslab_next;
388 #ifdef DEBUGGING
389         slab->opslab_refcnt = ~(size_t)0;
390 #endif
391 #ifdef PERL_DEBUG_READONLY_OPS
392         DEBUG_m(PerlIO_printf(Perl_debug_log, "Deallocate slab at %p\n",
393                                                (void*)slab));
394         if (munmap(slab, slab->opslab_size * sizeof(I32 *))) {
395             perror("munmap failed");
396             abort();
397         }
398 #else
399         PerlMemShared_free(slab);
400 #endif
401     }
402 }
403
404 void
405 Perl_opslab_force_free(pTHX_ OPSLAB *slab)
406 {
407     OPSLAB *slab2;
408     OPSLOT *slot;
409 #ifdef DEBUGGING
410     size_t savestack_count = 0;
411 #endif
412     PERL_ARGS_ASSERT_OPSLAB_FORCE_FREE;
413     slab2 = slab;
414     do {
415         for (slot = slab2->opslab_first;
416              slot->opslot_next;
417              slot = slot->opslot_next) {
418             if (slot->opslot_op.op_type != OP_FREED
419              && !(slot->opslot_op.op_savefree
420 #ifdef DEBUGGING
421                   && ++savestack_count
422 #endif
423                  )
424             ) {
425                 assert(slot->opslot_op.op_slabbed);
426                 op_free(&slot->opslot_op);
427                 if (slab->opslab_refcnt == 1) goto free;
428             }
429         }
430     } while ((slab2 = slab2->opslab_next));
431     /* > 1 because the CV still holds a reference count. */
432     if (slab->opslab_refcnt > 1) { /* still referenced by the savestack */
433 #ifdef DEBUGGING
434         assert(savestack_count == slab->opslab_refcnt-1);
435 #endif
436         /* Remove the CV’s reference count. */
437         slab->opslab_refcnt--;
438         return;
439     }
440    free:
441     opslab_free(slab);
442 }
443
444 #ifdef PERL_DEBUG_READONLY_OPS
445 OP *
446 Perl_op_refcnt_inc(pTHX_ OP *o)
447 {
448     if(o) {
449         OPSLAB *const slab = o->op_slabbed ? OpSLAB(o) : NULL;
450         if (slab && slab->opslab_readonly) {
451             Slab_to_rw(slab);
452             ++o->op_targ;
453             Slab_to_ro(slab);
454         } else {
455             ++o->op_targ;
456         }
457     }
458     return o;
459
460 }
461
462 PADOFFSET
463 Perl_op_refcnt_dec(pTHX_ OP *o)
464 {
465     PADOFFSET result;
466     OPSLAB *const slab = o->op_slabbed ? OpSLAB(o) : NULL;
467
468     PERL_ARGS_ASSERT_OP_REFCNT_DEC;
469
470     if (slab && slab->opslab_readonly) {
471         Slab_to_rw(slab);
472         result = --o->op_targ;
473         Slab_to_ro(slab);
474     } else {
475         result = --o->op_targ;
476     }
477     return result;
478 }
479 #endif
480 /*
481  * In the following definition, the ", (OP*)0" is just to make the compiler
482  * think the expression is of the right type: croak actually does a Siglongjmp.
483  */
484 #define CHECKOP(type,o) \
485     ((PL_op_mask && PL_op_mask[type])                           \
486      ? ( op_free((OP*)o),                                       \
487          Perl_croak(aTHX_ "'%s' trapped by operation mask", PL_op_desc[type]),  \
488          (OP*)0 )                                               \
489      : PL_check[type](aTHX_ (OP*)o))
490
491 #define RETURN_UNLIMITED_NUMBER (PERL_INT_MAX / 2)
492
493 #define CHANGE_TYPE(o,type) \
494     STMT_START {                                \
495         o->op_type = (OPCODE)type;              \
496         o->op_ppaddr = PL_ppaddr[type];         \
497     } STMT_END
498
499 STATIC OP *
500 S_no_fh_allowed(pTHX_ OP *o)
501 {
502     PERL_ARGS_ASSERT_NO_FH_ALLOWED;
503
504     yyerror(Perl_form(aTHX_ "Missing comma after first argument to %s function",
505                  OP_DESC(o)));
506     return o;
507 }
508
509 STATIC OP *
510 S_too_few_arguments_pv(pTHX_ OP *o, const char* name, U32 flags)
511 {
512     PERL_ARGS_ASSERT_TOO_FEW_ARGUMENTS_PV;
513     yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %s", name), flags);
514     return o;
515 }
516  
517 STATIC OP *
518 S_too_many_arguments_pv(pTHX_ OP *o, const char *name, U32 flags)
519 {
520     PERL_ARGS_ASSERT_TOO_MANY_ARGUMENTS_PV;
521
522     yyerror_pv(Perl_form(aTHX_ "Too many arguments for %s", name), flags);
523     return o;
524 }
525
526 STATIC void
527 S_bad_type_pv(pTHX_ I32 n, const char *t, const char *name, U32 flags, const OP *kid)
528 {
529     PERL_ARGS_ASSERT_BAD_TYPE_PV;
530
531     yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %s must be %s (not %s)",
532                  (int)n, name, t, OP_DESC(kid)), flags);
533 }
534
535 STATIC void
536 S_bad_type_gv(pTHX_ I32 n, const char *t, GV *gv, U32 flags, const OP *kid)
537 {
538     SV * const namesv = cv_name((CV *)gv, NULL);
539     PERL_ARGS_ASSERT_BAD_TYPE_GV;
540  
541     yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %"SVf" must be %s (not %s)",
542                  (int)n, SVfARG(namesv), t, OP_DESC(kid)), SvUTF8(namesv) | flags);
543 }
544
545 STATIC void
546 S_no_bareword_allowed(pTHX_ OP *o)
547 {
548     PERL_ARGS_ASSERT_NO_BAREWORD_ALLOWED;
549
550     qerror(Perl_mess(aTHX_
551                      "Bareword \"%"SVf"\" not allowed while \"strict subs\" in use",
552                      SVfARG(cSVOPo_sv)));
553     o->op_private &= ~OPpCONST_STRICT; /* prevent warning twice about the same OP */
554 }
555
556 /* "register" allocation */
557
558 PADOFFSET
559 Perl_allocmy(pTHX_ const char *const name, const STRLEN len, const U32 flags)
560 {
561     PADOFFSET off;
562     const bool is_our = (PL_parser->in_my == KEY_our);
563
564     PERL_ARGS_ASSERT_ALLOCMY;
565
566     if (flags & ~SVf_UTF8)
567         Perl_croak(aTHX_ "panic: allocmy illegal flag bits 0x%" UVxf,
568                    (UV)flags);
569
570     /* Until we're using the length for real, cross check that we're being
571        told the truth.  */
572     assert(strlen(name) == len);
573
574     /* complain about "my $<special_var>" etc etc */
575     if (len &&
576         !(is_our ||
577           isALPHA(name[1]) ||
578           ((flags & SVf_UTF8) && isIDFIRST_utf8((U8 *)name+1)) ||
579           (name[1] == '_' && (*name == '$' || len > 2))))
580     {
581         /* name[2] is true if strlen(name) > 2  */
582         if (!(flags & SVf_UTF8 && UTF8_IS_START(name[1]))
583          && (!isPRINT(name[1]) || strchr("\t\n\r\f", name[1]))) {
584             yyerror(Perl_form(aTHX_ "Can't use global %c^%c%.*s in \"%s\"",
585                               name[0], toCTRL(name[1]), (int)(len - 2), name + 2,
586                               PL_parser->in_my == KEY_state ? "state" : "my"));
587         } else {
588             yyerror_pv(Perl_form(aTHX_ "Can't use global %.*s in \"%s\"", (int) len, name,
589                               PL_parser->in_my == KEY_state ? "state" : "my"), flags & SVf_UTF8);
590         }
591     }
592     else if (len == 2 && name[1] == '_' && !is_our)
593         /* diag_listed_as: Use of my $_ is experimental */
594         Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__LEXICAL_TOPIC),
595                               "Use of %s $_ is experimental",
596                                PL_parser->in_my == KEY_state
597                                  ? "state"
598                                  : "my");
599
600     /* allocate a spare slot and store the name in that slot */
601
602     off = pad_add_name_pvn(name, len,
603                        (is_our ? padadd_OUR :
604                         PL_parser->in_my == KEY_state ? padadd_STATE : 0)
605                             | ( flags & SVf_UTF8 ? SVf_UTF8 : 0 ),
606                     PL_parser->in_my_stash,
607                     (is_our
608                         /* $_ is always in main::, even with our */
609                         ? (PL_curstash && !strEQ(name,"$_") ? PL_curstash : PL_defstash)
610                         : NULL
611                     )
612     );
613     /* anon sub prototypes contains state vars should always be cloned,
614      * otherwise the state var would be shared between anon subs */
615
616     if (PL_parser->in_my == KEY_state && CvANON(PL_compcv))
617         CvCLONE_on(PL_compcv);
618
619     return off;
620 }
621
622 /*
623 =head1 Optree Manipulation Functions
624
625 =for apidoc alloccopstash
626
627 Available only under threaded builds, this function allocates an entry in
628 C<PL_stashpad> for the stash passed to it.
629
630 =cut
631 */
632
633 #ifdef USE_ITHREADS
634 PADOFFSET
635 Perl_alloccopstash(pTHX_ HV *hv)
636 {
637     PADOFFSET off = 0, o = 1;
638     bool found_slot = FALSE;
639
640     PERL_ARGS_ASSERT_ALLOCCOPSTASH;
641
642     if (PL_stashpad[PL_stashpadix] == hv) return PL_stashpadix;
643
644     for (; o < PL_stashpadmax; ++o) {
645         if (PL_stashpad[o] == hv) return PL_stashpadix = o;
646         if (!PL_stashpad[o] || SvTYPE(PL_stashpad[o]) != SVt_PVHV)
647             found_slot = TRUE, off = o;
648     }
649     if (!found_slot) {
650         Renew(PL_stashpad, PL_stashpadmax + 10, HV *);
651         Zero(PL_stashpad + PL_stashpadmax, 10, HV *);
652         off = PL_stashpadmax;
653         PL_stashpadmax += 10;
654     }
655
656     PL_stashpad[PL_stashpadix = off] = hv;
657     return off;
658 }
659 #endif
660
661 /* free the body of an op without examining its contents.
662  * Always use this rather than FreeOp directly */
663
664 static void
665 S_op_destroy(pTHX_ OP *o)
666 {
667     FreeOp(o);
668 }
669
670 /* Destructor */
671
672 /*
673 =for apidoc Am|void|op_free|OP *o
674
675 Free an op.  Only use this when an op is no longer linked to from any
676 optree.
677
678 =cut
679 */
680
681 void
682 Perl_op_free(pTHX_ OP *o)
683 {
684 #ifdef USE_ITHREADS
685     dVAR;
686 #endif
687     OPCODE type;
688
689     /* Though ops may be freed twice, freeing the op after its slab is a
690        big no-no. */
691     assert(!o || !o->op_slabbed || OpSLAB(o)->opslab_refcnt != ~(size_t)0); 
692     /* During the forced freeing of ops after compilation failure, kidops
693        may be freed before their parents. */
694     if (!o || o->op_type == OP_FREED)
695         return;
696
697     type = o->op_type;
698
699     /* an op should only ever acquire op_private flags that we know about.
700      * If this fails, you may need to fix something in regen/op_private */
701     assert(!(o->op_private & ~PL_op_private_valid[type]));
702
703     if (o->op_private & OPpREFCOUNTED) {
704         switch (type) {
705         case OP_LEAVESUB:
706         case OP_LEAVESUBLV:
707         case OP_LEAVEEVAL:
708         case OP_LEAVE:
709         case OP_SCOPE:
710         case OP_LEAVEWRITE:
711             {
712             PADOFFSET refcnt;
713             OP_REFCNT_LOCK;
714             refcnt = OpREFCNT_dec(o);
715             OP_REFCNT_UNLOCK;
716             if (refcnt) {
717                 /* Need to find and remove any pattern match ops from the list
718                    we maintain for reset().  */
719                 find_and_forget_pmops(o);
720                 return;
721             }
722             }
723             break;
724         default:
725             break;
726         }
727     }
728
729     /* Call the op_free hook if it has been set. Do it now so that it's called
730      * at the right time for refcounted ops, but still before all of the kids
731      * are freed. */
732     CALL_OPFREEHOOK(o);
733
734     if (o->op_flags & OPf_KIDS) {
735         OP *kid, *nextkid;
736         for (kid = cUNOPo->op_first; kid; kid = nextkid) {
737             nextkid = OP_SIBLING(kid); /* Get before next freeing kid */
738             op_free(kid);
739         }
740     }
741     if (type == OP_NULL)
742         type = (OPCODE)o->op_targ;
743
744     if (o->op_slabbed)
745         Slab_to_rw(OpSLAB(o));
746
747     /* COP* is not cleared by op_clear() so that we may track line
748      * numbers etc even after null() */
749     if (type == OP_NEXTSTATE || type == OP_DBSTATE) {
750         cop_free((COP*)o);
751     }
752
753     op_clear(o);
754     FreeOp(o);
755 #ifdef DEBUG_LEAKING_SCALARS
756     if (PL_op == o)
757         PL_op = NULL;
758 #endif
759 }
760
761 void
762 Perl_op_clear(pTHX_ OP *o)
763 {
764
765     dVAR;
766
767     PERL_ARGS_ASSERT_OP_CLEAR;
768
769     switch (o->op_type) {
770     case OP_NULL:       /* Was holding old type, if any. */
771         /* FALLTHROUGH */
772     case OP_ENTERTRY:
773     case OP_ENTEREVAL:  /* Was holding hints. */
774         o->op_targ = 0;
775         break;
776     default:
777         if (!(o->op_flags & OPf_REF)
778             || (PL_check[o->op_type] != Perl_ck_ftst))
779             break;
780         /* FALLTHROUGH */
781     case OP_GVSV:
782     case OP_GV:
783     case OP_AELEMFAST:
784         {
785             GV *gv = (o->op_type == OP_GV || o->op_type == OP_GVSV)
786 #ifdef USE_ITHREADS
787                         && PL_curpad
788 #endif
789                         ? cGVOPo_gv : NULL;
790             /* It's possible during global destruction that the GV is freed
791                before the optree. Whilst the SvREFCNT_inc is happy to bump from
792                0 to 1 on a freed SV, the corresponding SvREFCNT_dec from 1 to 0
793                will trigger an assertion failure, because the entry to sv_clear
794                checks that the scalar is not already freed.  A check of for
795                !SvIS_FREED(gv) turns out to be invalid, because during global
796                destruction the reference count can be forced down to zero
797                (with SVf_BREAK set).  In which case raising to 1 and then
798                dropping to 0 triggers cleanup before it should happen.  I
799                *think* that this might actually be a general, systematic,
800                weakness of the whole idea of SVf_BREAK, in that code *is*
801                allowed to raise and lower references during global destruction,
802                so any *valid* code that happens to do this during global
803                destruction might well trigger premature cleanup.  */
804             bool still_valid = gv && SvREFCNT(gv);
805
806             if (still_valid)
807                 SvREFCNT_inc_simple_void(gv);
808 #ifdef USE_ITHREADS
809             if (cPADOPo->op_padix > 0) {
810                 /* No GvIN_PAD_off(cGVOPo_gv) here, because other references
811                  * may still exist on the pad */
812                 pad_swipe(cPADOPo->op_padix, TRUE);
813                 cPADOPo->op_padix = 0;
814             }
815 #else
816             SvREFCNT_dec(cSVOPo->op_sv);
817             cSVOPo->op_sv = NULL;
818 #endif
819             if (still_valid) {
820                 int try_downgrade = SvREFCNT(gv) == 2;
821                 SvREFCNT_dec_NN(gv);
822                 if (try_downgrade)
823                     gv_try_downgrade(gv);
824             }
825         }
826         break;
827     case OP_METHOD_NAMED:
828     case OP_CONST:
829     case OP_HINTSEVAL:
830         SvREFCNT_dec(cSVOPo->op_sv);
831         cSVOPo->op_sv = NULL;
832 #ifdef USE_ITHREADS
833         /** Bug #15654
834           Even if op_clear does a pad_free for the target of the op,
835           pad_free doesn't actually remove the sv that exists in the pad;
836           instead it lives on. This results in that it could be reused as 
837           a target later on when the pad was reallocated.
838         **/
839         if(o->op_targ) {
840           pad_swipe(o->op_targ,1);
841           o->op_targ = 0;
842         }
843 #endif
844         break;
845     case OP_DUMP:
846     case OP_GOTO:
847     case OP_NEXT:
848     case OP_LAST:
849     case OP_REDO:
850         if (o->op_flags & (OPf_SPECIAL|OPf_STACKED|OPf_KIDS))
851             break;
852         /* FALLTHROUGH */
853     case OP_TRANS:
854     case OP_TRANSR:
855         if (o->op_private & (OPpTRANS_FROM_UTF|OPpTRANS_TO_UTF)) {
856             assert(o->op_type == OP_TRANS || o->op_type == OP_TRANSR);
857 #ifdef USE_ITHREADS
858             if (cPADOPo->op_padix > 0) {
859                 pad_swipe(cPADOPo->op_padix, TRUE);
860                 cPADOPo->op_padix = 0;
861             }
862 #else
863             SvREFCNT_dec(cSVOPo->op_sv);
864             cSVOPo->op_sv = NULL;
865 #endif
866         }
867         else {
868             PerlMemShared_free(cPVOPo->op_pv);
869             cPVOPo->op_pv = NULL;
870         }
871         break;
872     case OP_SUBST:
873         op_free(cPMOPo->op_pmreplrootu.op_pmreplroot);
874         goto clear_pmop;
875     case OP_PUSHRE:
876 #ifdef USE_ITHREADS
877         if (cPMOPo->op_pmreplrootu.op_pmtargetoff) {
878             /* No GvIN_PAD_off here, because other references may still
879              * exist on the pad */
880             pad_swipe(cPMOPo->op_pmreplrootu.op_pmtargetoff, TRUE);
881         }
882 #else
883         SvREFCNT_dec(MUTABLE_SV(cPMOPo->op_pmreplrootu.op_pmtargetgv));
884 #endif
885         /* FALLTHROUGH */
886     case OP_MATCH:
887     case OP_QR:
888 clear_pmop:
889         if (!(cPMOPo->op_pmflags & PMf_CODELIST_PRIVATE))
890             op_free(cPMOPo->op_code_list);
891         cPMOPo->op_code_list = NULL;
892         forget_pmop(cPMOPo);
893         cPMOPo->op_pmreplrootu.op_pmreplroot = NULL;
894         /* we use the same protection as the "SAFE" version of the PM_ macros
895          * here since sv_clean_all might release some PMOPs
896          * after PL_regex_padav has been cleared
897          * and the clearing of PL_regex_padav needs to
898          * happen before sv_clean_all
899          */
900 #ifdef USE_ITHREADS
901         if(PL_regex_pad) {        /* We could be in destruction */
902             const IV offset = (cPMOPo)->op_pmoffset;
903             ReREFCNT_dec(PM_GETRE(cPMOPo));
904             PL_regex_pad[offset] = &PL_sv_undef;
905             sv_catpvn_nomg(PL_regex_pad[0], (const char *)&offset,
906                            sizeof(offset));
907         }
908 #else
909         ReREFCNT_dec(PM_GETRE(cPMOPo));
910         PM_SETRE(cPMOPo, NULL);
911 #endif
912
913         break;
914     }
915
916     if (o->op_targ > 0) {
917         pad_free(o->op_targ);
918         o->op_targ = 0;
919     }
920 }
921
922 STATIC void
923 S_cop_free(pTHX_ COP* cop)
924 {
925     PERL_ARGS_ASSERT_COP_FREE;
926
927     CopFILE_free(cop);
928     if (! specialWARN(cop->cop_warnings))
929         PerlMemShared_free(cop->cop_warnings);
930     cophh_free(CopHINTHASH_get(cop));
931     if (PL_curcop == cop)
932        PL_curcop = NULL;
933 }
934
935 STATIC void
936 S_forget_pmop(pTHX_ PMOP *const o
937               )
938 {
939     HV * const pmstash = PmopSTASH(o);
940
941     PERL_ARGS_ASSERT_FORGET_PMOP;
942
943     if (pmstash && !SvIS_FREED(pmstash) && SvMAGICAL(pmstash)) {
944         MAGIC * const mg = mg_find((const SV *)pmstash, PERL_MAGIC_symtab);
945         if (mg) {
946             PMOP **const array = (PMOP**) mg->mg_ptr;
947             U32 count = mg->mg_len / sizeof(PMOP**);
948             U32 i = count;
949
950             while (i--) {
951                 if (array[i] == o) {
952                     /* Found it. Move the entry at the end to overwrite it.  */
953                     array[i] = array[--count];
954                     mg->mg_len = count * sizeof(PMOP**);
955                     /* Could realloc smaller at this point always, but probably
956                        not worth it. Probably worth free()ing if we're the
957                        last.  */
958                     if(!count) {
959                         Safefree(mg->mg_ptr);
960                         mg->mg_ptr = NULL;
961                     }
962                     break;
963                 }
964             }
965         }
966     }
967     if (PL_curpm == o) 
968         PL_curpm = NULL;
969 }
970
971 STATIC void
972 S_find_and_forget_pmops(pTHX_ OP *o)
973 {
974     PERL_ARGS_ASSERT_FIND_AND_FORGET_PMOPS;
975
976     if (o->op_flags & OPf_KIDS) {
977         OP *kid = cUNOPo->op_first;
978         while (kid) {
979             switch (kid->op_type) {
980             case OP_SUBST:
981             case OP_PUSHRE:
982             case OP_MATCH:
983             case OP_QR:
984                 forget_pmop((PMOP*)kid);
985             }
986             find_and_forget_pmops(kid);
987             kid = OP_SIBLING(kid);
988         }
989     }
990 }
991
992 /*
993 =for apidoc Am|void|op_null|OP *o
994
995 Neutralizes an op when it is no longer needed, but is still linked to from
996 other ops.
997
998 =cut
999 */
1000
1001 void
1002 Perl_op_null(pTHX_ OP *o)
1003 {
1004     dVAR;
1005
1006     PERL_ARGS_ASSERT_OP_NULL;
1007
1008     if (o->op_type == OP_NULL)
1009         return;
1010     op_clear(o);
1011     o->op_targ = o->op_type;
1012     o->op_type = OP_NULL;
1013     o->op_ppaddr = PL_ppaddr[OP_NULL];
1014 }
1015
1016 void
1017 Perl_op_refcnt_lock(pTHX)
1018 {
1019 #ifdef USE_ITHREADS
1020     dVAR;
1021 #endif
1022     PERL_UNUSED_CONTEXT;
1023     OP_REFCNT_LOCK;
1024 }
1025
1026 void
1027 Perl_op_refcnt_unlock(pTHX)
1028 {
1029 #ifdef USE_ITHREADS
1030     dVAR;
1031 #endif
1032     PERL_UNUSED_CONTEXT;
1033     OP_REFCNT_UNLOCK;
1034 }
1035
1036
1037 /*
1038 =for apidoc op_sibling_splice
1039
1040 A general function for editing the structure of an existing chain of
1041 op_sibling nodes. By analogy with the perl-level splice() function, allows
1042 you to delete zero or more sequential nodes, replacing them with zero or
1043 more different nodes.  Performs the necessary op_first/op_last
1044 housekeeping on the parent node and op_sibling manipulation on the
1045 children. The last deleted node will be marked as as the last node by
1046 updating the op_sibling or op_lastsib field as appropriate.
1047
1048 Note that op_next is not manipulated, and nodes are not freed; that is the
1049 responsibility of the caller. It also won't create a new list op for an
1050 empty list etc; use higher-level functions like op_append_elem() for that.
1051
1052 parent is the parent node of the sibling chain.
1053
1054 start is the node preceding the first node to be spliced. Node(s)
1055 following it will be deleted, and ops will be inserted after it. If it is
1056 NULL, the first node onwards is deleted, and nodes are inserted at the
1057 beginning.
1058
1059 del_count is the number of nodes to delete. If zero, no nodes are deleted.
1060 If -1 or greater than or equal to the number of remaining kids, all
1061 remaining kids are deleted.
1062
1063 insert is the first of a chain of nodes to be inserted in place of the nodes.
1064 If NULL, no nodes are inserted.
1065
1066 The head of the chain of deleted ops is returned, or NULL if no ops were
1067 deleted.
1068
1069 For example:
1070
1071     action                    before      after         returns
1072     ------                    -----       -----         -------
1073
1074                               P           P
1075     splice(P, A, 2, X-Y-Z)    |           |             B-C
1076                               A-B-C-D     A-X-Y-Z-D
1077
1078                               P           P
1079     splice(P, NULL, 1, X-Y)   |           |             A
1080                               A-B-C-D     X-Y-B-C-D
1081
1082                               P           P
1083     splice(P, NULL, 3, NULL)  |           |             A-B-C
1084                               A-B-C-D     D
1085
1086                               P           P
1087     splice(P, B, 0, X-Y)      |           |             NULL
1088                               A-B-C-D     A-B-X-Y-C-D
1089
1090 =cut
1091 */
1092
1093 OP *
1094 Perl_op_sibling_splice(OP *parent, OP *start, int del_count, OP* insert)
1095 {
1096     OP *first = start ? OP_SIBLING(start) : cLISTOPx(parent)->op_first;
1097     OP *rest;
1098     OP *last_del = NULL;
1099     OP *last_ins = NULL;
1100
1101     PERL_ARGS_ASSERT_OP_SIBLING_SPLICE;
1102
1103     assert(del_count >= -1);
1104
1105     if (del_count && first) {
1106         last_del = first;
1107         while (--del_count && OP_HAS_SIBLING(last_del))
1108             last_del = OP_SIBLING(last_del);
1109         rest = OP_SIBLING(last_del);
1110         OP_SIBLING_set(last_del, NULL);
1111         last_del->op_lastsib = 1;
1112     }
1113     else
1114         rest = first;
1115
1116     if (insert) {
1117         last_ins = insert;
1118         while (OP_HAS_SIBLING(last_ins))
1119             last_ins = OP_SIBLING(last_ins);
1120         OP_SIBLING_set(last_ins, rest);
1121         last_ins->op_lastsib = rest ? 0 : 1;
1122     }
1123     else
1124         insert = rest;
1125
1126     if (start) {
1127         OP_SIBLING_set(start, insert);
1128         start->op_lastsib = insert ? 0 : 1;
1129     }
1130     else
1131         cLISTOPx(parent)->op_first = insert;
1132
1133     if (!rest) {
1134         /* update op_last etc */
1135         U32 type = parent->op_type;
1136         OP *lastop;
1137
1138         if (type == OP_NULL)
1139             type = parent->op_targ;
1140         type = PL_opargs[type] & OA_CLASS_MASK;
1141
1142         lastop = last_ins ? last_ins : start ? start : NULL;
1143         if (   type == OA_BINOP
1144             || type == OA_LISTOP
1145             || type == OA_PMOP
1146             || type == OA_LOOP
1147         )
1148             cLISTOPx(parent)->op_last = lastop;
1149
1150         if (lastop) {
1151             lastop->op_lastsib = 1;
1152 #ifdef PERL_OP_PARENT
1153             lastop->op_sibling = parent;
1154 #endif
1155         }
1156     }
1157     return last_del ? first : NULL;
1158 }
1159
1160 /*
1161 =for apidoc op_parent
1162
1163 returns the parent OP of o, if it has a parent. Returns NULL otherwise.
1164 (Currently perl must be built with C<-DPERL_OP_PARENT> for this feature to
1165 work.
1166
1167 =cut
1168 */
1169
1170 OP *
1171 Perl_op_parent(OP *o)
1172 {
1173     PERL_ARGS_ASSERT_OP_PARENT;
1174 #ifdef PERL_OP_PARENT
1175     while (OP_HAS_SIBLING(o))
1176         o = OP_SIBLING(o);
1177     return o->op_sibling;
1178 #else
1179     PERL_UNUSED_ARG(o);
1180     return NULL;
1181 #endif
1182 }
1183
1184
1185 /* replace the sibling following start with a new UNOP, which becomes
1186  * the parent of the original sibling; e.g.
1187  *
1188  *  op_sibling_newUNOP(P, A, unop-args...)
1189  *
1190  *  P              P
1191  *  |      becomes |
1192  *  A-B-C          A-U-C
1193  *                   |
1194  *                   B
1195  *
1196  * where U is the new UNOP.
1197  *
1198  * parent and start args are the same as for op_sibling_splice();
1199  * type and flags args are as newUNOP().
1200  *
1201  * Returns the new UNOP.
1202  */
1203
1204 OP *
1205 S_op_sibling_newUNOP(pTHX_ OP *parent, OP *start, I32 type, I32 flags)
1206 {
1207     OP *kid, *newop;
1208
1209     kid = op_sibling_splice(parent, start, 1, NULL);
1210     newop = newUNOP(type, flags, kid);
1211     op_sibling_splice(parent, start, 0, newop);
1212     return newop;
1213 }
1214
1215
1216 /* lowest-level newLOGOP-style function - just allocates and populates
1217  * the struct. Higher-level stuff should be done by S_new_logop() /
1218  * newLOGOP(). This function exists mainly to avoid op_first assignment
1219  * being spread throughout this file.
1220  */
1221
1222 LOGOP *
1223 S_alloc_LOGOP(pTHX_ I32 type, OP *first, OP* other)
1224 {
1225     LOGOP *logop;
1226     OP *kid = first;
1227     NewOp(1101, logop, 1, LOGOP);
1228     logop->op_type = (OPCODE)type;
1229     logop->op_first = first;
1230     logop->op_other = other;
1231     logop->op_flags = OPf_KIDS;
1232     while (kid && OP_HAS_SIBLING(kid))
1233         kid = OP_SIBLING(kid);
1234     if (kid) {
1235         kid->op_lastsib = 1;
1236 #ifdef PERL_OP_PARENT
1237         kid->op_sibling = (OP*)logop;
1238 #endif
1239     }
1240     return logop;
1241 }
1242
1243
1244 /* Contextualizers */
1245
1246 /*
1247 =for apidoc Am|OP *|op_contextualize|OP *o|I32 context
1248
1249 Applies a syntactic context to an op tree representing an expression.
1250 I<o> is the op tree, and I<context> must be C<G_SCALAR>, C<G_ARRAY>,
1251 or C<G_VOID> to specify the context to apply.  The modified op tree
1252 is returned.
1253
1254 =cut
1255 */
1256
1257 OP *
1258 Perl_op_contextualize(pTHX_ OP *o, I32 context)
1259 {
1260     PERL_ARGS_ASSERT_OP_CONTEXTUALIZE;
1261     switch (context) {
1262         case G_SCALAR: return scalar(o);
1263         case G_ARRAY:  return list(o);
1264         case G_VOID:   return scalarvoid(o);
1265         default:
1266             Perl_croak(aTHX_ "panic: op_contextualize bad context %ld",
1267                        (long) context);
1268     }
1269 }
1270
1271 /*
1272
1273 =for apidoc Am|OP*|op_linklist|OP *o
1274 This function is the implementation of the L</LINKLIST> macro.  It should
1275 not be called directly.
1276
1277 =cut
1278 */
1279
1280 OP *
1281 Perl_op_linklist(pTHX_ OP *o)
1282 {
1283     OP *first;
1284
1285     PERL_ARGS_ASSERT_OP_LINKLIST;
1286
1287     if (o->op_next)
1288         return o->op_next;
1289
1290     /* establish postfix order */
1291     first = cUNOPo->op_first;
1292     if (first) {
1293         OP *kid;
1294         o->op_next = LINKLIST(first);
1295         kid = first;
1296         for (;;) {
1297             OP *sibl = OP_SIBLING(kid);
1298             if (sibl) {
1299                 kid->op_next = LINKLIST(sibl);
1300                 kid = sibl;
1301             } else {
1302                 kid->op_next = o;
1303                 break;
1304             }
1305         }
1306     }
1307     else
1308         o->op_next = o;
1309
1310     return o->op_next;
1311 }
1312
1313 static OP *
1314 S_scalarkids(pTHX_ OP *o)
1315 {
1316     if (o && o->op_flags & OPf_KIDS) {
1317         OP *kid;
1318         for (kid = cLISTOPo->op_first; kid; kid = OP_SIBLING(kid))
1319             scalar(kid);
1320     }
1321     return o;
1322 }
1323
1324 STATIC OP *
1325 S_scalarboolean(pTHX_ OP *o)
1326 {
1327     PERL_ARGS_ASSERT_SCALARBOOLEAN;
1328
1329     if (o->op_type == OP_SASSIGN && cBINOPo->op_first->op_type == OP_CONST
1330      && !(cBINOPo->op_first->op_flags & OPf_SPECIAL)) {
1331         if (ckWARN(WARN_SYNTAX)) {
1332             const line_t oldline = CopLINE(PL_curcop);
1333
1334             if (PL_parser && PL_parser->copline != NOLINE) {
1335                 /* This ensures that warnings are reported at the first line
1336                    of the conditional, not the last.  */
1337                 CopLINE_set(PL_curcop, PL_parser->copline);
1338             }
1339             Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "Found = in conditional, should be ==");
1340             CopLINE_set(PL_curcop, oldline);
1341         }
1342     }
1343     return scalar(o);
1344 }
1345
1346 static SV *
1347 S_op_varname(pTHX_ const OP *o)
1348 {
1349     assert(o);
1350     assert(o->op_type == OP_PADAV || o->op_type == OP_RV2AV ||
1351            o->op_type == OP_PADHV || o->op_type == OP_RV2HV);
1352     {
1353         const char funny  = o->op_type == OP_PADAV
1354                          || o->op_type == OP_RV2AV ? '@' : '%';
1355         if (o->op_type == OP_RV2AV || o->op_type == OP_RV2HV) {
1356             GV *gv;
1357             if (cUNOPo->op_first->op_type != OP_GV
1358              || !(gv = cGVOPx_gv(cUNOPo->op_first)))
1359                 return NULL;
1360             return varname(gv, funny, 0, NULL, 0, 1);
1361         }
1362         return
1363             varname(MUTABLE_GV(PL_compcv), funny, o->op_targ, NULL, 0, 1);
1364     }
1365 }
1366
1367 static void
1368 S_op_pretty(pTHX_ const OP *o, SV **retsv, const char **retpv)
1369 { /* or not so pretty :-) */
1370     if (o->op_type == OP_CONST) {
1371         *retsv = cSVOPo_sv;
1372         if (SvPOK(*retsv)) {
1373             SV *sv = *retsv;
1374             *retsv = sv_newmortal();
1375             pv_pretty(*retsv, SvPVX_const(sv), SvCUR(sv), 32, NULL, NULL,
1376                       PERL_PV_PRETTY_DUMP |PERL_PV_ESCAPE_UNI_DETECT);
1377         }
1378         else if (!SvOK(*retsv))
1379             *retpv = "undef";
1380     }
1381     else *retpv = "...";
1382 }
1383
1384 static void
1385 S_scalar_slice_warning(pTHX_ const OP *o)
1386 {
1387     OP *kid;
1388     const char lbrack =
1389         o->op_type == OP_HSLICE ? '{' : '[';
1390     const char rbrack =
1391         o->op_type == OP_HSLICE ? '}' : ']';
1392     SV *name;
1393     SV *keysv = NULL; /* just to silence compiler warnings */
1394     const char *key = NULL;
1395
1396     if (!(o->op_private & OPpSLICEWARNING))
1397         return;
1398     if (PL_parser && PL_parser->error_count)
1399         /* This warning can be nonsensical when there is a syntax error. */
1400         return;
1401
1402     kid = cLISTOPo->op_first;
1403     kid = OP_SIBLING(kid); /* get past pushmark */
1404     /* weed out false positives: any ops that can return lists */
1405     switch (kid->op_type) {
1406     case OP_BACKTICK:
1407     case OP_GLOB:
1408     case OP_READLINE:
1409     case OP_MATCH:
1410     case OP_RV2AV:
1411     case OP_EACH:
1412     case OP_VALUES:
1413     case OP_KEYS:
1414     case OP_SPLIT:
1415     case OP_LIST:
1416     case OP_SORT:
1417     case OP_REVERSE:
1418     case OP_ENTERSUB:
1419     case OP_CALLER:
1420     case OP_LSTAT:
1421     case OP_STAT:
1422     case OP_READDIR:
1423     case OP_SYSTEM:
1424     case OP_TMS:
1425     case OP_LOCALTIME:
1426     case OP_GMTIME:
1427     case OP_ENTEREVAL:
1428     case OP_REACH:
1429     case OP_RKEYS:
1430     case OP_RVALUES:
1431         return;
1432     }
1433
1434     /* Don't warn if we have a nulled list either. */
1435     if (kid->op_type == OP_NULL && kid->op_targ == OP_LIST)
1436         return;
1437
1438     assert(OP_SIBLING(kid));
1439     name = S_op_varname(aTHX_ OP_SIBLING(kid));
1440     if (!name) /* XS module fiddling with the op tree */
1441         return;
1442     S_op_pretty(aTHX_ kid, &keysv, &key);
1443     assert(SvPOK(name));
1444     sv_chop(name,SvPVX(name)+1);
1445     if (key)
1446        /* diag_listed_as: Scalar value @%s[%s] better written as $%s[%s] */
1447         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1448                    "Scalar value @%"SVf"%c%s%c better written as $%"SVf
1449                    "%c%s%c",
1450                     SVfARG(name), lbrack, key, rbrack, SVfARG(name),
1451                     lbrack, key, rbrack);
1452     else
1453        /* diag_listed_as: Scalar value @%s[%s] better written as $%s[%s] */
1454         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1455                    "Scalar value @%"SVf"%c%"SVf"%c better written as $%"
1456                     SVf"%c%"SVf"%c",
1457                     SVfARG(name), lbrack, SVfARG(keysv), rbrack,
1458                     SVfARG(name), lbrack, SVfARG(keysv), rbrack);
1459 }
1460
1461 OP *
1462 Perl_scalar(pTHX_ OP *o)
1463 {
1464     OP *kid;
1465
1466     /* assumes no premature commitment */
1467     if (!o || (PL_parser && PL_parser->error_count)
1468          || (o->op_flags & OPf_WANT)
1469          || o->op_type == OP_RETURN)
1470     {
1471         return o;
1472     }
1473
1474     o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_SCALAR;
1475
1476     switch (o->op_type) {
1477     case OP_REPEAT:
1478         scalar(cBINOPo->op_first);
1479         break;
1480     case OP_OR:
1481     case OP_AND:
1482     case OP_COND_EXPR:
1483         for (kid = OP_SIBLING(cUNOPo->op_first); kid; kid = OP_SIBLING(kid))
1484             scalar(kid);
1485         break;
1486         /* FALLTHROUGH */
1487     case OP_SPLIT:
1488     case OP_MATCH:
1489     case OP_QR:
1490     case OP_SUBST:
1491     case OP_NULL:
1492     default:
1493         if (o->op_flags & OPf_KIDS) {
1494             for (kid = cUNOPo->op_first; kid; kid = OP_SIBLING(kid))
1495                 scalar(kid);
1496         }
1497         break;
1498     case OP_LEAVE:
1499     case OP_LEAVETRY:
1500         kid = cLISTOPo->op_first;
1501         scalar(kid);
1502         kid = OP_SIBLING(kid);
1503     do_kids:
1504         while (kid) {
1505             OP *sib = OP_SIBLING(kid);
1506             if (sib && kid->op_type != OP_LEAVEWHEN)
1507                 scalarvoid(kid);
1508             else
1509                 scalar(kid);
1510             kid = sib;
1511         }
1512         PL_curcop = &PL_compiling;
1513         break;
1514     case OP_SCOPE:
1515     case OP_LINESEQ:
1516     case OP_LIST:
1517         kid = cLISTOPo->op_first;
1518         goto do_kids;
1519     case OP_SORT:
1520         Perl_ck_warner(aTHX_ packWARN(WARN_VOID), "Useless use of sort in scalar context");
1521         break;
1522     case OP_KVHSLICE:
1523     case OP_KVASLICE:
1524     {
1525         /* Warn about scalar context */
1526         const char lbrack = o->op_type == OP_KVHSLICE ? '{' : '[';
1527         const char rbrack = o->op_type == OP_KVHSLICE ? '}' : ']';
1528         SV *name;
1529         SV *keysv;
1530         const char *key = NULL;
1531
1532         /* This warning can be nonsensical when there is a syntax error. */
1533         if (PL_parser && PL_parser->error_count)
1534             break;
1535
1536         if (!ckWARN(WARN_SYNTAX)) break;
1537
1538         kid = cLISTOPo->op_first;
1539         kid = OP_SIBLING(kid); /* get past pushmark */
1540         assert(OP_SIBLING(kid));
1541         name = S_op_varname(aTHX_ OP_SIBLING(kid));
1542         if (!name) /* XS module fiddling with the op tree */
1543             break;
1544         S_op_pretty(aTHX_ kid, &keysv, &key);
1545         assert(SvPOK(name));
1546         sv_chop(name,SvPVX(name)+1);
1547         if (key)
1548   /* diag_listed_as: %%s[%s] in scalar context better written as $%s[%s] */
1549             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1550                        "%%%"SVf"%c%s%c in scalar context better written "
1551                        "as $%"SVf"%c%s%c",
1552                         SVfARG(name), lbrack, key, rbrack, SVfARG(name),
1553                         lbrack, key, rbrack);
1554         else
1555   /* diag_listed_as: %%s[%s] in scalar context better written as $%s[%s] */
1556             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1557                        "%%%"SVf"%c%"SVf"%c in scalar context better "
1558                        "written as $%"SVf"%c%"SVf"%c",
1559                         SVfARG(name), lbrack, SVfARG(keysv), rbrack,
1560                         SVfARG(name), lbrack, SVfARG(keysv), rbrack);
1561     }
1562     }
1563     return o;
1564 }
1565
1566 OP *
1567 Perl_scalarvoid(pTHX_ OP *o)
1568 {
1569     dVAR;
1570     OP *kid;
1571     SV *useless_sv = NULL;
1572     const char* useless = NULL;
1573     SV* sv;
1574     U8 want;
1575
1576     PERL_ARGS_ASSERT_SCALARVOID;
1577
1578     if (o->op_type == OP_NEXTSTATE
1579         || o->op_type == OP_DBSTATE
1580         || (o->op_type == OP_NULL && (o->op_targ == OP_NEXTSTATE
1581                                       || o->op_targ == OP_DBSTATE)))
1582         PL_curcop = (COP*)o;            /* for warning below */
1583
1584     /* assumes no premature commitment */
1585     want = o->op_flags & OPf_WANT;
1586     if ((want && want != OPf_WANT_SCALAR)
1587          || (PL_parser && PL_parser->error_count)
1588          || o->op_type == OP_RETURN || o->op_type == OP_REQUIRE || o->op_type == OP_LEAVEWHEN)
1589     {
1590         return o;
1591     }
1592
1593     if ((o->op_private & OPpTARGET_MY)
1594         && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
1595     {
1596         return scalar(o);                       /* As if inside SASSIGN */
1597     }
1598
1599     o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
1600
1601     switch (o->op_type) {
1602     default:
1603         if (!(PL_opargs[o->op_type] & OA_FOLDCONST))
1604             break;
1605         /* FALLTHROUGH */
1606     case OP_REPEAT:
1607         if (o->op_flags & OPf_STACKED)
1608             break;
1609         goto func_ops;
1610     case OP_SUBSTR:
1611         if (o->op_private == 4)
1612             break;
1613         /* FALLTHROUGH */
1614     case OP_GVSV:
1615     case OP_WANTARRAY:
1616     case OP_GV:
1617     case OP_SMARTMATCH:
1618     case OP_PADSV:
1619     case OP_PADAV:
1620     case OP_PADHV:
1621     case OP_PADANY:
1622     case OP_AV2ARYLEN:
1623     case OP_REF:
1624     case OP_REFGEN:
1625     case OP_SREFGEN:
1626     case OP_DEFINED:
1627     case OP_HEX:
1628     case OP_OCT:
1629     case OP_LENGTH:
1630     case OP_VEC:
1631     case OP_INDEX:
1632     case OP_RINDEX:
1633     case OP_SPRINTF:
1634     case OP_AELEM:
1635     case OP_AELEMFAST:
1636     case OP_AELEMFAST_LEX:
1637     case OP_ASLICE:
1638     case OP_KVASLICE:
1639     case OP_HELEM:
1640     case OP_HSLICE:
1641     case OP_KVHSLICE:
1642     case OP_UNPACK:
1643     case OP_PACK:
1644     case OP_JOIN:
1645     case OP_LSLICE:
1646     case OP_ANONLIST:
1647     case OP_ANONHASH:
1648     case OP_SORT:
1649     case OP_REVERSE:
1650     case OP_RANGE:
1651     case OP_FLIP:
1652     case OP_FLOP:
1653     case OP_CALLER:
1654     case OP_FILENO:
1655     case OP_EOF:
1656     case OP_TELL:
1657     case OP_GETSOCKNAME:
1658     case OP_GETPEERNAME:
1659     case OP_READLINK:
1660     case OP_TELLDIR:
1661     case OP_GETPPID:
1662     case OP_GETPGRP:
1663     case OP_GETPRIORITY:
1664     case OP_TIME:
1665     case OP_TMS:
1666     case OP_LOCALTIME:
1667     case OP_GMTIME:
1668     case OP_GHBYNAME:
1669     case OP_GHBYADDR:
1670     case OP_GHOSTENT:
1671     case OP_GNBYNAME:
1672     case OP_GNBYADDR:
1673     case OP_GNETENT:
1674     case OP_GPBYNAME:
1675     case OP_GPBYNUMBER:
1676     case OP_GPROTOENT:
1677     case OP_GSBYNAME:
1678     case OP_GSBYPORT:
1679     case OP_GSERVENT:
1680     case OP_GPWNAM:
1681     case OP_GPWUID:
1682     case OP_GGRNAM:
1683     case OP_GGRGID:
1684     case OP_GETLOGIN:
1685     case OP_PROTOTYPE:
1686     case OP_RUNCV:
1687       func_ops:
1688         if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))
1689             /* Otherwise it's "Useless use of grep iterator" */
1690             useless = OP_DESC(o);
1691         break;
1692
1693     case OP_SPLIT:
1694         kid = cLISTOPo->op_first;
1695         if (kid && kid->op_type == OP_PUSHRE
1696 #ifdef USE_ITHREADS
1697                 && !((PMOP*)kid)->op_pmreplrootu.op_pmtargetoff)
1698 #else
1699                 && !((PMOP*)kid)->op_pmreplrootu.op_pmtargetgv)
1700 #endif
1701             useless = OP_DESC(o);
1702         break;
1703
1704     case OP_NOT:
1705        kid = cUNOPo->op_first;
1706        if (kid->op_type != OP_MATCH && kid->op_type != OP_SUBST &&
1707            kid->op_type != OP_TRANS && kid->op_type != OP_TRANSR) {
1708                 goto func_ops;
1709        }
1710        useless = "negative pattern binding (!~)";
1711        break;
1712
1713     case OP_SUBST:
1714         if (cPMOPo->op_pmflags & PMf_NONDESTRUCT)
1715             useless = "non-destructive substitution (s///r)";
1716         break;
1717
1718     case OP_TRANSR:
1719         useless = "non-destructive transliteration (tr///r)";
1720         break;
1721
1722     case OP_RV2GV:
1723     case OP_RV2SV:
1724     case OP_RV2AV:
1725     case OP_RV2HV:
1726         if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)) &&
1727                 (!OP_HAS_SIBLING(o) || OP_SIBLING(o)->op_type != OP_READLINE))
1728             useless = "a variable";
1729         break;
1730
1731     case OP_CONST:
1732         sv = cSVOPo_sv;
1733         if (cSVOPo->op_private & OPpCONST_STRICT)
1734             no_bareword_allowed(o);
1735         else {
1736             if (ckWARN(WARN_VOID)) {
1737                 /* don't warn on optimised away booleans, eg 
1738                  * use constant Foo, 5; Foo || print; */
1739                 if (cSVOPo->op_private & OPpCONST_SHORTCIRCUIT)
1740                     useless = NULL;
1741                 /* the constants 0 and 1 are permitted as they are
1742                    conventionally used as dummies in constructs like
1743                         1 while some_condition_with_side_effects;  */
1744                 else if (SvNIOK(sv) && (SvNV(sv) == 0.0 || SvNV(sv) == 1.0))
1745                     useless = NULL;
1746                 else if (SvPOK(sv)) {
1747                     SV * const dsv = newSVpvs("");
1748                     useless_sv
1749                         = Perl_newSVpvf(aTHX_
1750                                         "a constant (%s)",
1751                                         pv_pretty(dsv, SvPVX_const(sv),
1752                                                   SvCUR(sv), 32, NULL, NULL,
1753                                                   PERL_PV_PRETTY_DUMP
1754                                                   | PERL_PV_ESCAPE_NOCLEAR
1755                                                   | PERL_PV_ESCAPE_UNI_DETECT));
1756                     SvREFCNT_dec_NN(dsv);
1757                 }
1758                 else if (SvOK(sv)) {
1759                     useless_sv = Perl_newSVpvf(aTHX_ "a constant (%"SVf")", SVfARG(sv));
1760                 }
1761                 else
1762                     useless = "a constant (undef)";
1763             }
1764         }
1765         op_null(o);             /* don't execute or even remember it */
1766         break;
1767
1768     case OP_POSTINC:
1769         o->op_type = OP_PREINC;         /* pre-increment is faster */
1770         o->op_ppaddr = PL_ppaddr[OP_PREINC];
1771         break;
1772
1773     case OP_POSTDEC:
1774         o->op_type = OP_PREDEC;         /* pre-decrement is faster */
1775         o->op_ppaddr = PL_ppaddr[OP_PREDEC];
1776         break;
1777
1778     case OP_I_POSTINC:
1779         o->op_type = OP_I_PREINC;       /* pre-increment is faster */
1780         o->op_ppaddr = PL_ppaddr[OP_I_PREINC];
1781         break;
1782
1783     case OP_I_POSTDEC:
1784         o->op_type = OP_I_PREDEC;       /* pre-decrement is faster */
1785         o->op_ppaddr = PL_ppaddr[OP_I_PREDEC];
1786         break;
1787
1788     case OP_SASSIGN: {
1789         OP *rv2gv;
1790         UNOP *refgen, *rv2cv;
1791         LISTOP *exlist;
1792
1793         if ((o->op_private & ~OPpASSIGN_BACKWARDS) != 2)
1794             break;
1795
1796         rv2gv = ((BINOP *)o)->op_last;
1797         if (!rv2gv || rv2gv->op_type != OP_RV2GV)
1798             break;
1799
1800         refgen = (UNOP *)((BINOP *)o)->op_first;
1801
1802         if (!refgen || refgen->op_type != OP_REFGEN)
1803             break;
1804
1805         exlist = (LISTOP *)refgen->op_first;
1806         if (!exlist || exlist->op_type != OP_NULL
1807             || exlist->op_targ != OP_LIST)
1808             break;
1809
1810         if (exlist->op_first->op_type != OP_PUSHMARK)
1811             break;
1812
1813         rv2cv = (UNOP*)exlist->op_last;
1814
1815         if (rv2cv->op_type != OP_RV2CV)
1816             break;
1817
1818         assert ((rv2gv->op_private & OPpDONT_INIT_GV) == 0);
1819         assert ((o->op_private & OPpASSIGN_CV_TO_GV) == 0);
1820         assert ((rv2cv->op_private & OPpMAY_RETURN_CONSTANT) == 0);
1821
1822         o->op_private |= OPpASSIGN_CV_TO_GV;
1823         rv2gv->op_private |= OPpDONT_INIT_GV;
1824         rv2cv->op_private |= OPpMAY_RETURN_CONSTANT;
1825
1826         break;
1827     }
1828
1829     case OP_AASSIGN: {
1830         inplace_aassign(o);
1831         break;
1832     }
1833
1834     case OP_OR:
1835     case OP_AND:
1836         kid = cLOGOPo->op_first;
1837         if (kid->op_type == OP_NOT
1838             && (kid->op_flags & OPf_KIDS)) {
1839             if (o->op_type == OP_AND) {
1840                 o->op_type = OP_OR;
1841                 o->op_ppaddr = PL_ppaddr[OP_OR];
1842             } else {
1843                 o->op_type = OP_AND;
1844                 o->op_ppaddr = PL_ppaddr[OP_AND];
1845             }
1846             op_null(kid);
1847         }
1848         /* FALLTHROUGH */
1849
1850     case OP_DOR:
1851     case OP_COND_EXPR:
1852     case OP_ENTERGIVEN:
1853     case OP_ENTERWHEN:
1854         for (kid = OP_SIBLING(cUNOPo->op_first); kid; kid = OP_SIBLING(kid))
1855             scalarvoid(kid);
1856         break;
1857
1858     case OP_NULL:
1859         if (o->op_flags & OPf_STACKED)
1860             break;
1861         /* FALLTHROUGH */
1862     case OP_NEXTSTATE:
1863     case OP_DBSTATE:
1864     case OP_ENTERTRY:
1865     case OP_ENTER:
1866         if (!(o->op_flags & OPf_KIDS))
1867             break;
1868         /* FALLTHROUGH */
1869     case OP_SCOPE:
1870     case OP_LEAVE:
1871     case OP_LEAVETRY:
1872     case OP_LEAVELOOP:
1873     case OP_LINESEQ:
1874     case OP_LIST:
1875     case OP_LEAVEGIVEN:
1876     case OP_LEAVEWHEN:
1877         for (kid = cLISTOPo->op_first; kid; kid = OP_SIBLING(kid))
1878             scalarvoid(kid);
1879         break;
1880     case OP_ENTEREVAL:
1881         scalarkids(o);
1882         break;
1883     case OP_SCALAR:
1884         return scalar(o);
1885     }
1886
1887     if (useless_sv) {
1888         /* mortalise it, in case warnings are fatal.  */
1889         Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
1890                        "Useless use of %"SVf" in void context",
1891                        SVfARG(sv_2mortal(useless_sv)));
1892     }
1893     else if (useless) {
1894        Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
1895                       "Useless use of %s in void context",
1896                       useless);
1897     }
1898     return o;
1899 }
1900
1901 static OP *
1902 S_listkids(pTHX_ OP *o)
1903 {
1904     if (o && o->op_flags & OPf_KIDS) {
1905         OP *kid;
1906         for (kid = cLISTOPo->op_first; kid; kid = OP_SIBLING(kid))
1907             list(kid);
1908     }
1909     return o;
1910 }
1911
1912 OP *
1913 Perl_list(pTHX_ OP *o)
1914 {
1915     OP *kid;
1916
1917     /* assumes no premature commitment */
1918     if (!o || (o->op_flags & OPf_WANT)
1919          || (PL_parser && PL_parser->error_count)
1920          || o->op_type == OP_RETURN)
1921     {
1922         return o;
1923     }
1924
1925     if ((o->op_private & OPpTARGET_MY)
1926         && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
1927     {
1928         return o;                               /* As if inside SASSIGN */
1929     }
1930
1931     o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_LIST;
1932
1933     switch (o->op_type) {
1934     case OP_FLOP:
1935     case OP_REPEAT:
1936         list(cBINOPo->op_first);
1937         break;
1938     case OP_OR:
1939     case OP_AND:
1940     case OP_COND_EXPR:
1941         for (kid = OP_SIBLING(cUNOPo->op_first); kid; kid = OP_SIBLING(kid))
1942             list(kid);
1943         break;
1944     default:
1945     case OP_MATCH:
1946     case OP_QR:
1947     case OP_SUBST:
1948     case OP_NULL:
1949         if (!(o->op_flags & OPf_KIDS))
1950             break;
1951         if (!o->op_next && cUNOPo->op_first->op_type == OP_FLOP) {
1952             list(cBINOPo->op_first);
1953             return gen_constant_list(o);
1954         }
1955     case OP_LIST:
1956         listkids(o);
1957         break;
1958     case OP_LEAVE:
1959     case OP_LEAVETRY:
1960         kid = cLISTOPo->op_first;
1961         list(kid);
1962         kid = OP_SIBLING(kid);
1963     do_kids:
1964         while (kid) {
1965             OP *sib = OP_SIBLING(kid);
1966             if (sib && kid->op_type != OP_LEAVEWHEN)
1967                 scalarvoid(kid);
1968             else
1969                 list(kid);
1970             kid = sib;
1971         }
1972         PL_curcop = &PL_compiling;
1973         break;
1974     case OP_SCOPE:
1975     case OP_LINESEQ:
1976         kid = cLISTOPo->op_first;
1977         goto do_kids;
1978     }
1979     return o;
1980 }
1981
1982 static OP *
1983 S_scalarseq(pTHX_ OP *o)
1984 {
1985     if (o) {
1986         const OPCODE type = o->op_type;
1987
1988         if (type == OP_LINESEQ || type == OP_SCOPE ||
1989             type == OP_LEAVE || type == OP_LEAVETRY)
1990         {
1991             OP *kid;
1992             for (kid = cLISTOPo->op_first; kid; kid = OP_SIBLING(kid)) {
1993                 if (OP_HAS_SIBLING(kid)) {
1994                     scalarvoid(kid);
1995                 }
1996             }
1997             PL_curcop = &PL_compiling;
1998         }
1999         o->op_flags &= ~OPf_PARENS;
2000         if (PL_hints & HINT_BLOCK_SCOPE)
2001             o->op_flags |= OPf_PARENS;
2002     }
2003     else
2004         o = newOP(OP_STUB, 0);
2005     return o;
2006 }
2007
2008 STATIC OP *
2009 S_modkids(pTHX_ OP *o, I32 type)
2010 {
2011     if (o && o->op_flags & OPf_KIDS) {
2012         OP *kid;
2013         for (kid = cLISTOPo->op_first; kid; kid = OP_SIBLING(kid))
2014             op_lvalue(kid, type);
2015     }
2016     return o;
2017 }
2018
2019 /*
2020 =for apidoc finalize_optree
2021
2022 This function finalizes the optree.  Should be called directly after
2023 the complete optree is built.  It does some additional
2024 checking which can't be done in the normal ck_xxx functions and makes
2025 the tree thread-safe.
2026
2027 =cut
2028 */
2029 void
2030 Perl_finalize_optree(pTHX_ OP* o)
2031 {
2032     PERL_ARGS_ASSERT_FINALIZE_OPTREE;
2033
2034     ENTER;
2035     SAVEVPTR(PL_curcop);
2036
2037     finalize_op(o);
2038
2039     LEAVE;
2040 }
2041
2042 STATIC void
2043 S_finalize_op(pTHX_ OP* o)
2044 {
2045     PERL_ARGS_ASSERT_FINALIZE_OP;
2046
2047
2048     switch (o->op_type) {
2049     case OP_NEXTSTATE:
2050     case OP_DBSTATE:
2051         PL_curcop = ((COP*)o);          /* for warnings */
2052         break;
2053     case OP_EXEC:
2054         if (OP_HAS_SIBLING(o)) {
2055             OP *sib = OP_SIBLING(o);
2056             if ((  sib->op_type == OP_NEXTSTATE || sib->op_type == OP_DBSTATE)
2057                 && ckWARN(WARN_EXEC)
2058                 && OP_HAS_SIBLING(sib))
2059             {
2060                     const OPCODE type = OP_SIBLING(sib)->op_type;
2061                     if (type != OP_EXIT && type != OP_WARN && type != OP_DIE) {
2062                         const line_t oldline = CopLINE(PL_curcop);
2063                         CopLINE_set(PL_curcop, CopLINE((COP*)sib));
2064                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
2065                             "Statement unlikely to be reached");
2066                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
2067                             "\t(Maybe you meant system() when you said exec()?)\n");
2068                         CopLINE_set(PL_curcop, oldline);
2069                     }
2070             }
2071         }
2072         break;
2073
2074     case OP_GV:
2075         if ((o->op_private & OPpEARLY_CV) && ckWARN(WARN_PROTOTYPE)) {
2076             GV * const gv = cGVOPo_gv;
2077             if (SvTYPE(gv) == SVt_PVGV && GvCV(gv) && SvPVX_const(GvCV(gv))) {
2078                 /* XXX could check prototype here instead of just carping */
2079                 SV * const sv = sv_newmortal();
2080                 gv_efullname3(sv, gv, NULL);
2081                 Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
2082                     "%"SVf"() called too early to check prototype",
2083                     SVfARG(sv));
2084             }
2085         }
2086         break;
2087
2088     case OP_CONST:
2089         if (cSVOPo->op_private & OPpCONST_STRICT)
2090             no_bareword_allowed(o);
2091         /* FALLTHROUGH */
2092 #ifdef USE_ITHREADS
2093     case OP_HINTSEVAL:
2094     case OP_METHOD_NAMED:
2095         /* Relocate sv to the pad for thread safety.
2096          * Despite being a "constant", the SV is written to,
2097          * for reference counts, sv_upgrade() etc. */
2098         if (cSVOPo->op_sv) {
2099             const PADOFFSET ix = pad_alloc(OP_CONST, SVf_READONLY);
2100             SvREFCNT_dec(PAD_SVl(ix));
2101             PAD_SETSV(ix, cSVOPo->op_sv);
2102             /* XXX I don't know how this isn't readonly already. */
2103             if (!SvIsCOW(PAD_SVl(ix))) SvREADONLY_on(PAD_SVl(ix));
2104             cSVOPo->op_sv = NULL;
2105             o->op_targ = ix;
2106         }
2107 #endif
2108         break;
2109
2110     case OP_HELEM: {
2111         UNOP *rop;
2112         SV *lexname;
2113         GV **fields;
2114         SVOP *key_op;
2115         OP *kid;
2116         bool check_fields;
2117
2118         if ((key_op = cSVOPx(((BINOP*)o)->op_last))->op_type != OP_CONST)
2119             break;
2120
2121         rop = (UNOP*)((BINOP*)o)->op_first;
2122
2123         goto check_keys;
2124
2125     case OP_HSLICE:
2126         S_scalar_slice_warning(aTHX_ o);
2127         /* FALLTHROUGH */
2128
2129     case OP_KVHSLICE:
2130         kid = OP_SIBLING(cLISTOPo->op_first);
2131         if (/* I bet there's always a pushmark... */
2132             OP_TYPE_ISNT_AND_WASNT_NN(kid, OP_LIST)
2133             && OP_TYPE_ISNT_NN(kid, OP_CONST))
2134         {
2135             break;
2136         }
2137
2138         key_op = (SVOP*)(kid->op_type == OP_CONST
2139                                 ? kid
2140                                 : OP_SIBLING(kLISTOP->op_first));
2141
2142         rop = (UNOP*)((LISTOP*)o)->op_last;
2143
2144       check_keys:       
2145         if (o->op_private & OPpLVAL_INTRO || rop->op_type != OP_RV2HV)
2146             rop = NULL;
2147         else if (rop->op_first->op_type == OP_PADSV)
2148             /* @$hash{qw(keys here)} */
2149             rop = (UNOP*)rop->op_first;
2150         else {
2151             /* @{$hash}{qw(keys here)} */
2152             if (rop->op_first->op_type == OP_SCOPE
2153                 && cLISTOPx(rop->op_first)->op_last->op_type == OP_PADSV)
2154                 {
2155                     rop = (UNOP*)cLISTOPx(rop->op_first)->op_last;
2156                 }
2157             else
2158                 rop = NULL;
2159         }
2160
2161         lexname = NULL; /* just to silence compiler warnings */
2162         fields  = NULL; /* just to silence compiler warnings */
2163
2164         check_fields =
2165             rop
2166          && (lexname = *av_fetch(PL_comppad_name, rop->op_targ, TRUE),
2167              SvPAD_TYPED(lexname))
2168          && (fields = (GV**)hv_fetchs(SvSTASH(lexname), "FIELDS", FALSE))
2169          && isGV(*fields) && GvHV(*fields);
2170         for (; key_op;
2171              key_op = (SVOP*)OP_SIBLING(key_op)) {
2172             SV **svp, *sv;
2173             if (key_op->op_type != OP_CONST)
2174                 continue;
2175             svp = cSVOPx_svp(key_op);
2176
2177             /* Make the CONST have a shared SV */
2178             if ((!SvIsCOW_shared_hash(sv = *svp))
2179              && SvTYPE(sv) < SVt_PVMG && SvOK(sv) && !SvROK(sv)) {
2180                 SSize_t keylen;
2181                 const char * const key = SvPV_const(sv, *(STRLEN*)&keylen);
2182                 SV *nsv = newSVpvn_share(key,
2183                                          SvUTF8(sv) ? -keylen : keylen, 0);
2184                 SvREFCNT_dec_NN(sv);
2185                 *svp = nsv;
2186             }
2187
2188             if (check_fields
2189              && !hv_fetch_ent(GvHV(*fields), *svp, FALSE, 0)) {
2190                 Perl_croak(aTHX_ "No such class field \"%"SVf"\" " 
2191                            "in variable %"SVf" of type %"HEKf, 
2192                       SVfARG(*svp), SVfARG(lexname),
2193                       HEKfARG(HvNAME_HEK(SvSTASH(lexname))));
2194             }
2195         }
2196         break;
2197     }
2198     case OP_ASLICE:
2199         S_scalar_slice_warning(aTHX_ o);
2200         break;
2201
2202     case OP_SUBST: {
2203         if (cPMOPo->op_pmreplrootu.op_pmreplroot)
2204             finalize_op(cPMOPo->op_pmreplrootu.op_pmreplroot);
2205         break;
2206     }
2207     default:
2208         break;
2209     }
2210
2211     if (o->op_flags & OPf_KIDS) {
2212         OP *kid;
2213
2214 #ifdef DEBUGGING
2215         /* check that op_last points to the last sibling, and that
2216          * the last op_sibling field points back to the parent, and
2217          * that the only ops with KIDS are those which are entitled to
2218          * them */
2219         U32 type = o->op_type;
2220         U32 family;
2221         bool has_last;
2222
2223         if (type == OP_NULL) {
2224             type = o->op_targ;
2225             /* ck_glob creates a null UNOP with ex-type GLOB
2226              * (which is a list op. So pretend it wasn't a listop */
2227             if (type == OP_GLOB)
2228                 type = OP_NULL;
2229         }
2230         family = PL_opargs[type] & OA_CLASS_MASK;
2231
2232         has_last = (   family == OA_BINOP
2233                     || family == OA_LISTOP
2234                     || family == OA_PMOP
2235                     || family == OA_LOOP
2236                    );
2237         assert(  has_last /* has op_first and op_last, or ...
2238               ... has (or may have) op_first: */
2239               || family == OA_UNOP
2240               || family == OA_LOGOP
2241               || family == OA_BASEOP_OR_UNOP
2242               || family == OA_FILESTATOP
2243               || family == OA_LOOPEXOP
2244               /* I don't know why SASSIGN is tagged as OA_BASEOP - DAPM */
2245               || type == OP_SASSIGN
2246               || type == OP_CUSTOM
2247               || type == OP_NULL /* new_logop does this */
2248               );
2249         /* XXX list form of 'x' is has a null op_last. This is wrong,
2250          * but requires too much hacking (e.g. in Deparse) to fix for
2251          * now */
2252         if (type == OP_REPEAT && (o->op_private & OPpREPEAT_DOLIST)) {
2253             assert(has_last);
2254             has_last = 0;
2255         }
2256
2257         for (kid = cUNOPo->op_first; kid; kid = OP_SIBLING(kid)) {
2258 #  ifdef PERL_OP_PARENT
2259             if (!OP_HAS_SIBLING(kid)) {
2260                 if (has_last)
2261                     assert(kid == cLISTOPo->op_last);
2262                 assert(kid->op_sibling == o);
2263             }
2264 #  else
2265             if (OP_HAS_SIBLING(kid)) {
2266                 assert(!kid->op_lastsib);
2267             }
2268             else {
2269                 assert(kid->op_lastsib);
2270                 if (has_last)
2271                     assert(kid == cLISTOPo->op_last);
2272             }
2273 #  endif
2274         }
2275 #endif
2276
2277         for (kid = cUNOPo->op_first; kid; kid = OP_SIBLING(kid))
2278             finalize_op(kid);
2279     }
2280 }
2281
2282 /*
2283 =for apidoc Amx|OP *|op_lvalue|OP *o|I32 type
2284
2285 Propagate lvalue ("modifiable") context to an op and its children.
2286 I<type> represents the context type, roughly based on the type of op that
2287 would do the modifying, although C<local()> is represented by OP_NULL,
2288 because it has no op type of its own (it is signalled by a flag on
2289 the lvalue op).
2290
2291 This function detects things that can't be modified, such as C<$x+1>, and
2292 generates errors for them.  For example, C<$x+1 = 2> would cause it to be
2293 called with an op of type OP_ADD and a C<type> argument of OP_SASSIGN.
2294
2295 It also flags things that need to behave specially in an lvalue context,
2296 such as C<$$x = 5> which might have to vivify a reference in C<$x>.
2297
2298 =cut
2299 */
2300
2301 static bool
2302 S_vivifies(const OPCODE type)
2303 {
2304     switch(type) {
2305     case OP_RV2AV:     case   OP_ASLICE:
2306     case OP_RV2HV:     case OP_KVASLICE:
2307     case OP_RV2SV:     case   OP_HSLICE:
2308     case OP_AELEMFAST: case OP_KVHSLICE:
2309     case OP_HELEM:
2310     case OP_AELEM:
2311         return 1;
2312     }
2313     return 0;
2314 }
2315
2316 OP *
2317 Perl_op_lvalue_flags(pTHX_ OP *o, I32 type, U32 flags)
2318 {
2319     dVAR;
2320     OP *kid;
2321     /* -1 = error on localize, 0 = ignore localize, 1 = ok to localize */
2322     int localize = -1;
2323
2324     if (!o || (PL_parser && PL_parser->error_count))
2325         return o;
2326
2327     if ((o->op_private & OPpTARGET_MY)
2328         && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
2329     {
2330         return o;
2331     }
2332
2333     assert( (o->op_flags & OPf_WANT) != OPf_WANT_VOID );
2334
2335     if (type == OP_PRTF || type == OP_SPRINTF) type = OP_ENTERSUB;
2336
2337     switch (o->op_type) {
2338     case OP_UNDEF:
2339         PL_modcount++;
2340         return o;
2341     case OP_STUB:
2342         if ((o->op_flags & OPf_PARENS))
2343             break;
2344         goto nomod;
2345     case OP_ENTERSUB:
2346         if ((type == OP_UNDEF || type == OP_REFGEN || type == OP_LOCK) &&
2347             !(o->op_flags & OPf_STACKED)) {
2348             o->op_type = OP_RV2CV;              /* entersub => rv2cv */
2349             o->op_ppaddr = PL_ppaddr[OP_RV2CV];
2350             assert(cUNOPo->op_first->op_type == OP_NULL);
2351             op_null(((LISTOP*)cUNOPo->op_first)->op_first);/* disable pushmark */
2352             break;
2353         }
2354         else {                          /* lvalue subroutine call */
2355             o->op_private |= OPpLVAL_INTRO
2356                            |(OPpENTERSUB_INARGS * (type == OP_LEAVESUBLV));
2357             PL_modcount = RETURN_UNLIMITED_NUMBER;
2358             if (type == OP_GREPSTART || type == OP_ENTERSUB || type == OP_REFGEN) {
2359                 /* Potential lvalue context: */
2360                 o->op_private |= OPpENTERSUB_INARGS;
2361                 break;
2362             }
2363             else {                      /* Compile-time error message: */
2364                 OP *kid = cUNOPo->op_first;
2365                 CV *cv;
2366                 GV *gv;
2367
2368                 if (kid->op_type != OP_PUSHMARK) {
2369                     if (kid->op_type != OP_NULL || kid->op_targ != OP_LIST)
2370                         Perl_croak(aTHX_
2371                                 "panic: unexpected lvalue entersub "
2372                                 "args: type/targ %ld:%"UVuf,
2373                                 (long)kid->op_type, (UV)kid->op_targ);
2374                     kid = kLISTOP->op_first;
2375                 }
2376                 while (OP_HAS_SIBLING(kid))
2377                     kid = OP_SIBLING(kid);
2378                 if (!(kid->op_type == OP_NULL && kid->op_targ == OP_RV2CV)) {
2379                     break;      /* Postpone until runtime */
2380                 }
2381
2382                 kid = kUNOP->op_first;
2383                 if (kid->op_type == OP_NULL && kid->op_targ == OP_RV2SV)
2384                     kid = kUNOP->op_first;
2385                 if (kid->op_type == OP_NULL)
2386                     Perl_croak(aTHX_
2387                                "Unexpected constant lvalue entersub "
2388                                "entry via type/targ %ld:%"UVuf,
2389                                (long)kid->op_type, (UV)kid->op_targ);
2390                 if (kid->op_type != OP_GV) {
2391                     break;
2392                 }
2393
2394                 gv = kGVOP_gv;
2395                 cv = isGV(gv)
2396                     ? GvCV(gv)
2397                     : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
2398                         ? MUTABLE_CV(SvRV(gv))
2399                         : NULL;
2400                 if (!cv)
2401                     break;
2402                 if (CvLVALUE(cv))
2403                     break;
2404             }
2405         }
2406         /* FALLTHROUGH */
2407     default:
2408       nomod:
2409         if (flags & OP_LVALUE_NO_CROAK) return NULL;
2410         /* grep, foreach, subcalls, refgen */
2411         if (type == OP_GREPSTART || type == OP_ENTERSUB
2412          || type == OP_REFGEN    || type == OP_LEAVESUBLV)
2413             break;
2414         yyerror(Perl_form(aTHX_ "Can't modify %s in %s",
2415                      (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)
2416                       ? "do block"
2417                       : (o->op_type == OP_ENTERSUB
2418                         ? "non-lvalue subroutine call"
2419                         : OP_DESC(o))),
2420                      type ? PL_op_desc[type] : "local"));
2421         return o;
2422
2423     case OP_PREINC:
2424     case OP_PREDEC:
2425     case OP_POW:
2426     case OP_MULTIPLY:
2427     case OP_DIVIDE:
2428     case OP_MODULO:
2429     case OP_REPEAT:
2430     case OP_ADD:
2431     case OP_SUBTRACT:
2432     case OP_CONCAT:
2433     case OP_LEFT_SHIFT:
2434     case OP_RIGHT_SHIFT:
2435     case OP_BIT_AND:
2436     case OP_BIT_XOR:
2437     case OP_BIT_OR:
2438     case OP_I_MULTIPLY:
2439     case OP_I_DIVIDE:
2440     case OP_I_MODULO:
2441     case OP_I_ADD:
2442     case OP_I_SUBTRACT:
2443         if (!(o->op_flags & OPf_STACKED))
2444             goto nomod;
2445         PL_modcount++;
2446         break;
2447
2448     case OP_COND_EXPR:
2449         localize = 1;
2450         for (kid = OP_SIBLING(cUNOPo->op_first); kid; kid = OP_SIBLING(kid))
2451             op_lvalue(kid, type);
2452         break;
2453
2454     case OP_RV2AV:
2455     case OP_RV2HV:
2456         if (type == OP_REFGEN && o->op_flags & OPf_PARENS) {
2457            PL_modcount = RETURN_UNLIMITED_NUMBER;
2458             return o;           /* Treat \(@foo) like ordinary list. */
2459         }
2460         /* FALLTHROUGH */
2461     case OP_RV2GV:
2462         if (scalar_mod_type(o, type))
2463             goto nomod;
2464         ref(cUNOPo->op_first, o->op_type);
2465         /* FALLTHROUGH */
2466     case OP_ASLICE:
2467     case OP_HSLICE:
2468         localize = 1;
2469         /* FALLTHROUGH */
2470     case OP_AASSIGN:
2471         /* Do not apply the lvsub flag for rv2[ah]v in scalar context.  */
2472         if (type == OP_LEAVESUBLV && (
2473                 (o->op_type != OP_RV2AV && o->op_type != OP_RV2HV)
2474              || (o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
2475            ))
2476             o->op_private |= OPpMAYBE_LVSUB;
2477         /* FALLTHROUGH */
2478     case OP_NEXTSTATE:
2479     case OP_DBSTATE:
2480        PL_modcount = RETURN_UNLIMITED_NUMBER;
2481         break;
2482     case OP_KVHSLICE:
2483     case OP_KVASLICE:
2484         if (type == OP_LEAVESUBLV)
2485             o->op_private |= OPpMAYBE_LVSUB;
2486         goto nomod;
2487     case OP_AV2ARYLEN:
2488         PL_hints |= HINT_BLOCK_SCOPE;
2489         if (type == OP_LEAVESUBLV)
2490             o->op_private |= OPpMAYBE_LVSUB;
2491         PL_modcount++;
2492         break;
2493     case OP_RV2SV:
2494         ref(cUNOPo->op_first, o->op_type);
2495         localize = 1;
2496         /* FALLTHROUGH */
2497     case OP_GV:
2498         PL_hints |= HINT_BLOCK_SCOPE;
2499         /* FALLTHROUGH */
2500     case OP_SASSIGN:
2501     case OP_ANDASSIGN:
2502     case OP_ORASSIGN:
2503     case OP_DORASSIGN:
2504         PL_modcount++;
2505         break;
2506
2507     case OP_AELEMFAST:
2508     case OP_AELEMFAST_LEX:
2509         localize = -1;
2510         PL_modcount++;
2511         break;
2512
2513     case OP_PADAV:
2514     case OP_PADHV:
2515        PL_modcount = RETURN_UNLIMITED_NUMBER;
2516         if (type == OP_REFGEN && o->op_flags & OPf_PARENS)
2517             return o;           /* Treat \(@foo) like ordinary list. */
2518         if (scalar_mod_type(o, type))
2519             goto nomod;
2520         if ((o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
2521           && type == OP_LEAVESUBLV)
2522             o->op_private |= OPpMAYBE_LVSUB;
2523         /* FALLTHROUGH */
2524     case OP_PADSV:
2525         PL_modcount++;
2526         if (!type) /* local() */
2527             Perl_croak(aTHX_ "Can't localize lexical variable %"SVf,
2528                  PAD_COMPNAME_SV(o->op_targ));
2529         break;
2530
2531     case OP_PUSHMARK:
2532         localize = 0;
2533         break;
2534
2535     case OP_KEYS:
2536     case OP_RKEYS:
2537         if (type != OP_SASSIGN && type != OP_LEAVESUBLV)
2538             goto nomod;
2539         goto lvalue_func;
2540     case OP_SUBSTR:
2541         if (o->op_private == 4) /* don't allow 4 arg substr as lvalue */
2542             goto nomod;
2543         /* FALLTHROUGH */
2544     case OP_POS:
2545     case OP_VEC:
2546       lvalue_func:
2547         if (type == OP_LEAVESUBLV)
2548             o->op_private |= OPpMAYBE_LVSUB;
2549         if (o->op_flags & OPf_KIDS)
2550             op_lvalue(OP_SIBLING(cBINOPo->op_first), type);
2551         break;
2552
2553     case OP_AELEM:
2554     case OP_HELEM:
2555         ref(cBINOPo->op_first, o->op_type);
2556         if (type == OP_ENTERSUB &&
2557              !(o->op_private & (OPpLVAL_INTRO | OPpDEREF)))
2558             o->op_private |= OPpLVAL_DEFER;
2559         if (type == OP_LEAVESUBLV)
2560             o->op_private |= OPpMAYBE_LVSUB;
2561         localize = 1;
2562         PL_modcount++;
2563         break;
2564
2565     case OP_LEAVE:
2566     case OP_LEAVELOOP:
2567         o->op_private |= OPpLVALUE;
2568         /* FALLTHROUGH */
2569     case OP_SCOPE:
2570     case OP_ENTER:
2571     case OP_LINESEQ:
2572         localize = 0;
2573         if (o->op_flags & OPf_KIDS)
2574             op_lvalue(cLISTOPo->op_last, type);
2575         break;
2576
2577     case OP_NULL:
2578         localize = 0;
2579         if (o->op_flags & OPf_SPECIAL)          /* do BLOCK */
2580             goto nomod;
2581         else if (!(o->op_flags & OPf_KIDS))
2582             break;
2583         if (o->op_targ != OP_LIST) {
2584             op_lvalue(cBINOPo->op_first, type);
2585             break;
2586         }
2587         /* FALLTHROUGH */
2588     case OP_LIST:
2589         localize = 0;
2590         for (kid = cLISTOPo->op_first; kid; kid = OP_SIBLING(kid))
2591             /* elements might be in void context because the list is
2592                in scalar context or because they are attribute sub calls */
2593             if ( (kid->op_flags & OPf_WANT) != OPf_WANT_VOID )
2594                 op_lvalue(kid, type);
2595         break;
2596
2597     case OP_RETURN:
2598         if (type != OP_LEAVESUBLV)
2599             goto nomod;
2600         break; /* op_lvalue()ing was handled by ck_return() */
2601
2602     case OP_COREARGS:
2603         return o;
2604
2605     case OP_AND:
2606     case OP_OR:
2607         if (type == OP_LEAVESUBLV
2608          || !S_vivifies(cLOGOPo->op_first->op_type))
2609             op_lvalue(cLOGOPo->op_first, type);
2610         if (type == OP_LEAVESUBLV
2611          || !S_vivifies(OP_SIBLING(cLOGOPo->op_first)->op_type))
2612             op_lvalue(OP_SIBLING(cLOGOPo->op_first), type);
2613         goto nomod;
2614     }
2615
2616     /* [20011101.069] File test operators interpret OPf_REF to mean that
2617        their argument is a filehandle; thus \stat(".") should not set
2618        it. AMS 20011102 */
2619     if (type == OP_REFGEN &&
2620         PL_check[o->op_type] == Perl_ck_ftst)
2621         return o;
2622
2623     if (type != OP_LEAVESUBLV)
2624         o->op_flags |= OPf_MOD;
2625
2626     if (type == OP_AASSIGN || type == OP_SASSIGN)
2627         o->op_flags |= OPf_SPECIAL|OPf_REF;
2628     else if (!type) { /* local() */
2629         switch (localize) {
2630         case 1:
2631             o->op_private |= OPpLVAL_INTRO;
2632             o->op_flags &= ~OPf_SPECIAL;
2633             PL_hints |= HINT_BLOCK_SCOPE;
2634             break;
2635         case 0:
2636             break;
2637         case -1:
2638             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
2639                            "Useless localization of %s", OP_DESC(o));
2640         }
2641     }
2642     else if (type != OP_GREPSTART && type != OP_ENTERSUB
2643              && type != OP_LEAVESUBLV)
2644         o->op_flags |= OPf_REF;
2645     return o;
2646 }
2647
2648 STATIC bool
2649 S_scalar_mod_type(const OP *o, I32 type)
2650 {
2651     switch (type) {
2652     case OP_POS:
2653     case OP_SASSIGN:
2654         if (o && o->op_type == OP_RV2GV)
2655             return FALSE;
2656         /* FALLTHROUGH */
2657     case OP_PREINC:
2658     case OP_PREDEC:
2659     case OP_POSTINC:
2660     case OP_POSTDEC:
2661     case OP_I_PREINC:
2662     case OP_I_PREDEC:
2663     case OP_I_POSTINC:
2664     case OP_I_POSTDEC:
2665     case OP_POW:
2666     case OP_MULTIPLY:
2667     case OP_DIVIDE:
2668     case OP_MODULO:
2669     case OP_REPEAT:
2670     case OP_ADD:
2671     case OP_SUBTRACT:
2672     case OP_I_MULTIPLY:
2673     case OP_I_DIVIDE:
2674     case OP_I_MODULO:
2675     case OP_I_ADD:
2676     case OP_I_SUBTRACT:
2677     case OP_LEFT_SHIFT:
2678     case OP_RIGHT_SHIFT:
2679     case OP_BIT_AND:
2680     case OP_BIT_XOR:
2681     case OP_BIT_OR:
2682     case OP_CONCAT:
2683     case OP_SUBST:
2684     case OP_TRANS:
2685     case OP_TRANSR:
2686     case OP_READ:
2687     case OP_SYSREAD:
2688     case OP_RECV:
2689     case OP_ANDASSIGN:
2690     case OP_ORASSIGN:
2691     case OP_DORASSIGN:
2692         return TRUE;
2693     default:
2694         return FALSE;
2695     }
2696 }
2697
2698 STATIC bool
2699 S_is_handle_constructor(const OP *o, I32 numargs)
2700 {
2701     PERL_ARGS_ASSERT_IS_HANDLE_CONSTRUCTOR;
2702
2703     switch (o->op_type) {
2704     case OP_PIPE_OP:
2705     case OP_SOCKPAIR:
2706         if (numargs == 2)
2707             return TRUE;
2708         /* FALLTHROUGH */
2709     case OP_SYSOPEN:
2710     case OP_OPEN:
2711     case OP_SELECT:             /* XXX c.f. SelectSaver.pm */
2712     case OP_SOCKET:
2713     case OP_OPEN_DIR:
2714     case OP_ACCEPT:
2715         if (numargs == 1)
2716             return TRUE;
2717         /* FALLTHROUGH */
2718     default:
2719         return FALSE;
2720     }
2721 }
2722
2723 static OP *
2724 S_refkids(pTHX_ OP *o, I32 type)
2725 {
2726     if (o && o->op_flags & OPf_KIDS) {
2727         OP *kid;
2728         for (kid = cLISTOPo->op_first; kid; kid = OP_SIBLING(kid))
2729             ref(kid, type);
2730     }
2731     return o;
2732 }
2733
2734 OP *
2735 Perl_doref(pTHX_ OP *o, I32 type, bool set_op_ref)
2736 {
2737     dVAR;
2738     OP *kid;
2739
2740     PERL_ARGS_ASSERT_DOREF;
2741
2742     if (!o || (PL_parser && PL_parser->error_count))
2743         return o;
2744
2745     switch (o->op_type) {
2746     case OP_ENTERSUB:
2747         if ((type == OP_EXISTS || type == OP_DEFINED) &&
2748             !(o->op_flags & OPf_STACKED)) {
2749             o->op_type = OP_RV2CV;             /* entersub => rv2cv */
2750             o->op_ppaddr = PL_ppaddr[OP_RV2CV];
2751             assert(cUNOPo->op_first->op_type == OP_NULL);
2752             op_null(((LISTOP*)cUNOPo->op_first)->op_first);     /* disable pushmark */
2753             o->op_flags |= OPf_SPECIAL;
2754         }
2755         else if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV){
2756             o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
2757                               : type == OP_RV2HV ? OPpDEREF_HV
2758                               : OPpDEREF_SV);
2759             o->op_flags |= OPf_MOD;
2760         }
2761
2762         break;
2763
2764     case OP_COND_EXPR:
2765         for (kid = OP_SIBLING(cUNOPo->op_first); kid; kid = OP_SIBLING(kid))
2766             doref(kid, type, set_op_ref);
2767         break;
2768     case OP_RV2SV:
2769         if (type == OP_DEFINED)
2770             o->op_flags |= OPf_SPECIAL;         /* don't create GV */
2771         doref(cUNOPo->op_first, o->op_type, set_op_ref);
2772         /* FALLTHROUGH */
2773     case OP_PADSV:
2774         if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
2775             o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
2776                               : type == OP_RV2HV ? OPpDEREF_HV
2777                               : OPpDEREF_SV);
2778             o->op_flags |= OPf_MOD;
2779         }
2780         break;
2781
2782     case OP_RV2AV:
2783     case OP_RV2HV:
2784         if (set_op_ref)
2785             o->op_flags |= OPf_REF;
2786         /* FALLTHROUGH */
2787     case OP_RV2GV:
2788         if (type == OP_DEFINED)
2789             o->op_flags |= OPf_SPECIAL;         /* don't create GV */
2790         doref(cUNOPo->op_first, o->op_type, set_op_ref);
2791         break;
2792
2793     case OP_PADAV:
2794     case OP_PADHV:
2795         if (set_op_ref)
2796             o->op_flags |= OPf_REF;
2797         break;
2798
2799     case OP_SCALAR:
2800     case OP_NULL:
2801         if (!(o->op_flags & OPf_KIDS) || type == OP_DEFINED)
2802             break;
2803         doref(cBINOPo->op_first, type, set_op_ref);
2804         break;
2805     case OP_AELEM:
2806     case OP_HELEM:
2807         doref(cBINOPo->op_first, o->op_type, set_op_ref);
2808         if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
2809             o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
2810                               : type == OP_RV2HV ? OPpDEREF_HV
2811                               : OPpDEREF_SV);
2812             o->op_flags |= OPf_MOD;
2813         }
2814         break;
2815
2816     case OP_SCOPE:
2817     case OP_LEAVE:
2818         set_op_ref = FALSE;
2819         /* FALLTHROUGH */
2820     case OP_ENTER:
2821     case OP_LIST:
2822         if (!(o->op_flags & OPf_KIDS))
2823             break;
2824         doref(cLISTOPo->op_last, type, set_op_ref);
2825         break;
2826     default:
2827         break;
2828     }
2829     return scalar(o);
2830
2831 }
2832
2833 STATIC OP *
2834 S_dup_attrlist(pTHX_ OP *o)
2835 {
2836     OP *rop;
2837
2838     PERL_ARGS_ASSERT_DUP_ATTRLIST;
2839
2840     /* An attrlist is either a simple OP_CONST or an OP_LIST with kids,
2841      * where the first kid is OP_PUSHMARK and the remaining ones
2842      * are OP_CONST.  We need to push the OP_CONST values.
2843      */
2844     if (o->op_type == OP_CONST)
2845         rop = newSVOP(OP_CONST, o->op_flags, SvREFCNT_inc_NN(cSVOPo->op_sv));
2846     else {
2847         assert((o->op_type == OP_LIST) && (o->op_flags & OPf_KIDS));
2848         rop = NULL;
2849         for (o = cLISTOPo->op_first; o; o = OP_SIBLING(o)) {
2850             if (o->op_type == OP_CONST)
2851                 rop = op_append_elem(OP_LIST, rop,
2852                                   newSVOP(OP_CONST, o->op_flags,
2853                                           SvREFCNT_inc_NN(cSVOPo->op_sv)));
2854         }
2855     }
2856     return rop;
2857 }
2858
2859 STATIC void
2860 S_apply_attrs(pTHX_ HV *stash, SV *target, OP *attrs)
2861 {
2862     SV * const stashsv = stash ? newSVhek(HvNAME_HEK(stash)) : &PL_sv_no;
2863
2864     PERL_ARGS_ASSERT_APPLY_ATTRS;
2865
2866     /* fake up C<use attributes $pkg,$rv,@attrs> */
2867
2868 #define ATTRSMODULE "attributes"
2869 #define ATTRSMODULE_PM "attributes.pm"
2870
2871     Perl_load_module(aTHX_ PERL_LOADMOD_IMPORT_OPS,
2872                          newSVpvs(ATTRSMODULE),
2873                          NULL,
2874                          op_prepend_elem(OP_LIST,
2875                                       newSVOP(OP_CONST, 0, stashsv),
2876                                       op_prepend_elem(OP_LIST,
2877                                                    newSVOP(OP_CONST, 0,
2878                                                            newRV(target)),
2879                                                    dup_attrlist(attrs))));
2880 }
2881
2882 STATIC void
2883 S_apply_attrs_my(pTHX_ HV *stash, OP *target, OP *attrs, OP **imopsp)
2884 {
2885     OP *pack, *imop, *arg;
2886     SV *meth, *stashsv, **svp;
2887
2888     PERL_ARGS_ASSERT_APPLY_ATTRS_MY;
2889
2890     if (!attrs)
2891         return;
2892
2893     assert(target->op_type == OP_PADSV ||
2894            target->op_type == OP_PADHV ||
2895            target->op_type == OP_PADAV);
2896
2897     /* Ensure that attributes.pm is loaded. */
2898     /* Don't force the C<use> if we don't need it. */
2899     svp = hv_fetchs(GvHVn(PL_incgv), ATTRSMODULE_PM, FALSE);
2900     if (svp && *svp != &PL_sv_undef)
2901         NOOP;   /* already in %INC */
2902     else
2903         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
2904                                newSVpvs(ATTRSMODULE), NULL);
2905
2906     /* Need package name for method call. */
2907     pack = newSVOP(OP_CONST, 0, newSVpvs(ATTRSMODULE));
2908
2909     /* Build up the real arg-list. */
2910     stashsv = stash ? newSVhek(HvNAME_HEK(stash)) : &PL_sv_no;
2911
2912     arg = newOP(OP_PADSV, 0);
2913     arg->op_targ = target->op_targ;
2914     arg = op_prepend_elem(OP_LIST,
2915                        newSVOP(OP_CONST, 0, stashsv),
2916                        op_prepend_elem(OP_LIST,
2917                                     newUNOP(OP_REFGEN, 0,
2918                                             op_lvalue(arg, OP_REFGEN)),
2919                                     dup_attrlist(attrs)));
2920
2921     /* Fake up a method call to import */
2922     meth = newSVpvs_share("import");
2923     imop = convert(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL|OPf_WANT_VOID,
2924                    op_append_elem(OP_LIST,
2925                                op_prepend_elem(OP_LIST, pack, list(arg)),
2926                                newSVOP(OP_METHOD_NAMED, 0, meth)));
2927
2928     /* Combine the ops. */
2929     *imopsp = op_append_elem(OP_LIST, *imopsp, imop);
2930 }
2931
2932 /*
2933 =notfor apidoc apply_attrs_string
2934
2935 Attempts to apply a list of attributes specified by the C<attrstr> and
2936 C<len> arguments to the subroutine identified by the C<cv> argument which
2937 is expected to be associated with the package identified by the C<stashpv>
2938 argument (see L<attributes>).  It gets this wrong, though, in that it
2939 does not correctly identify the boundaries of the individual attribute
2940 specifications within C<attrstr>.  This is not really intended for the
2941 public API, but has to be listed here for systems such as AIX which
2942 need an explicit export list for symbols.  (It's called from XS code
2943 in support of the C<ATTRS:> keyword from F<xsubpp>.)  Patches to fix it
2944 to respect attribute syntax properly would be welcome.
2945
2946 =cut
2947 */
2948
2949 void
2950 Perl_apply_attrs_string(pTHX_ const char *stashpv, CV *cv,
2951                         const char *attrstr, STRLEN len)
2952 {
2953     OP *attrs = NULL;
2954
2955     PERL_ARGS_ASSERT_APPLY_ATTRS_STRING;
2956
2957     if (!len) {
2958         len = strlen(attrstr);
2959     }
2960
2961     while (len) {
2962         for (; isSPACE(*attrstr) && len; --len, ++attrstr) ;
2963         if (len) {
2964             const char * const sstr = attrstr;
2965             for (; !isSPACE(*attrstr) && len; --len, ++attrstr) ;
2966             attrs = op_append_elem(OP_LIST, attrs,
2967                                 newSVOP(OP_CONST, 0,
2968                                         newSVpvn(sstr, attrstr-sstr)));
2969         }
2970     }
2971
2972     Perl_load_module(aTHX_ PERL_LOADMOD_IMPORT_OPS,
2973                      newSVpvs(ATTRSMODULE),
2974                      NULL, op_prepend_elem(OP_LIST,
2975                                   newSVOP(OP_CONST, 0, newSVpv(stashpv,0)),
2976                                   op_prepend_elem(OP_LIST,
2977                                                newSVOP(OP_CONST, 0,
2978                                                        newRV(MUTABLE_SV(cv))),
2979                                                attrs)));
2980 }
2981
2982 STATIC void
2983 S_move_proto_attr(pTHX_ OP **proto, OP **attrs, const GV * name)
2984 {
2985     OP *new_proto = NULL;
2986     STRLEN pvlen;
2987     char *pv;
2988     OP *o;
2989
2990     PERL_ARGS_ASSERT_MOVE_PROTO_ATTR;
2991
2992     if (!*attrs)
2993         return;
2994
2995     o = *attrs;
2996     if (o->op_type == OP_CONST) {
2997         pv = SvPV(cSVOPo_sv, pvlen);
2998         if (pvlen >= 10 && memEQ(pv, "prototype(", 10)) {
2999             SV * const tmpsv = newSVpvn_flags(pv + 10, pvlen - 11, SvUTF8(cSVOPo_sv));
3000             SV ** const tmpo = cSVOPx_svp(o);
3001             SvREFCNT_dec(cSVOPo_sv);
3002             *tmpo = tmpsv;
3003             new_proto = o;
3004             *attrs = NULL;
3005         }
3006     } else if (o->op_type == OP_LIST) {
3007         OP * lasto;
3008         assert(o->op_flags & OPf_KIDS);
3009         lasto = cLISTOPo->op_first;
3010         assert(lasto->op_type == OP_PUSHMARK);
3011         for (o = OP_SIBLING(lasto); o; o = OP_SIBLING(o)) {
3012             if (o->op_type == OP_CONST) {
3013                 pv = SvPV(cSVOPo_sv, pvlen);
3014                 if (pvlen >= 10 && memEQ(pv, "prototype(", 10)) {
3015                     SV * const tmpsv = newSVpvn_flags(pv + 10, pvlen - 11, SvUTF8(cSVOPo_sv));
3016                     SV ** const tmpo = cSVOPx_svp(o);
3017                     SvREFCNT_dec(cSVOPo_sv);
3018                     *tmpo = tmpsv;
3019                     if (new_proto && ckWARN(WARN_MISC)) {
3020                         STRLEN new_len;
3021                         const char * newp = SvPV(cSVOPo_sv, new_len);
3022                         Perl_warner(aTHX_ packWARN(WARN_MISC),
3023                             "Attribute prototype(%"UTF8f") discards earlier prototype attribute in same sub",
3024                             UTF8fARG(SvUTF8(cSVOPo_sv), new_len, newp));
3025                         op_free(new_proto);
3026                     }
3027                     else if (new_proto)
3028                         op_free(new_proto);
3029                     new_proto = o;
3030                     /* excise new_proto from the list */
3031                     op_sibling_splice(*attrs, lasto, 1, NULL);
3032                     o = lasto;
3033                     continue;
3034                 }
3035             }
3036             lasto = o;
3037         }
3038         /* If the list is now just the PUSHMARK, scrap the whole thing; otherwise attributes.xs
3039            would get pulled in with no real need */
3040         if (!OP_HAS_SIBLING(cLISTOPx(*attrs)->op_first)) {
3041             op_free(*attrs);
3042             *attrs = NULL;
3043         }
3044     }
3045
3046     if (new_proto) {
3047         SV *svname;
3048         if (isGV(name)) {
3049             svname = sv_newmortal();
3050             gv_efullname3(svname, name, NULL);
3051         }
3052         else if (SvPOK(name) && *SvPVX((SV *)name) == '&')
3053             svname = newSVpvn_flags(SvPVX((SV *)name)+1, SvCUR(name)-1, SvUTF8(name)|SVs_TEMP);
3054         else
3055             svname = (SV *)name;
3056         if (ckWARN(WARN_ILLEGALPROTO))
3057             (void)validate_proto(svname, cSVOPx_sv(new_proto), TRUE);
3058         if (*proto && ckWARN(WARN_PROTOTYPE)) {
3059             STRLEN old_len, new_len;
3060             const char * oldp = SvPV(cSVOPx_sv(*proto), old_len);
3061             const char * newp = SvPV(cSVOPx_sv(new_proto), new_len);
3062
3063             Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
3064                 "Prototype '%"UTF8f"' overridden by attribute 'prototype(%"UTF8f")'"
3065                 " in %"SVf,
3066                 UTF8fARG(SvUTF8(cSVOPx_sv(*proto)), old_len, oldp),
3067                 UTF8fARG(SvUTF8(cSVOPx_sv(new_proto)), new_len, newp),
3068                 SVfARG(svname));
3069         }
3070         if (*proto)
3071             op_free(*proto);
3072         *proto = new_proto;
3073     }
3074 }
3075
3076 static void
3077 S_cant_declare(pTHX_ OP *o)
3078 {
3079     if (o->op_type == OP_NULL
3080      && (o->op_flags & (OPf_SPECIAL|OPf_KIDS)) == OPf_KIDS)
3081         o = cUNOPo->op_first;
3082     yyerror(Perl_form(aTHX_ "Can't declare %s in \"%s\"",
3083                              o->op_type == OP_NULL
3084                                && o->op_flags & OPf_SPECIAL
3085                                  ? "do block"
3086                                  : OP_DESC(o),
3087                              PL_parser->in_my == KEY_our   ? "our"   :
3088                              PL_parser->in_my == KEY_state ? "state" :
3089                                                              "my"));
3090 }
3091
3092 STATIC OP *
3093 S_my_kid(pTHX_ OP *o, OP *attrs, OP **imopsp)
3094 {
3095     I32 type;
3096     const bool stately = PL_parser && PL_parser->in_my == KEY_state;
3097
3098     PERL_ARGS_ASSERT_MY_KID;
3099
3100     if (!o || (PL_parser && PL_parser->error_count))
3101         return o;
3102
3103     type = o->op_type;
3104
3105     if (type == OP_LIST) {
3106         OP *kid;
3107         for (kid = cLISTOPo->op_first; kid; kid = OP_SIBLING(kid))
3108             my_kid(kid, attrs, imopsp);
3109         return o;
3110     } else if (type == OP_UNDEF || type == OP_STUB) {
3111         return o;
3112     } else if (type == OP_RV2SV ||      /* "our" declaration */
3113                type == OP_RV2AV ||
3114                type == OP_RV2HV) { /* XXX does this let anything illegal in? */
3115         if (cUNOPo->op_first->op_type != OP_GV) { /* MJD 20011224 */
3116             S_cant_declare(aTHX_ o);
3117         } else if (attrs) {
3118             GV * const gv = cGVOPx_gv(cUNOPo->op_first);
3119             assert(PL_parser);
3120             PL_parser->in_my = FALSE;
3121             PL_parser->in_my_stash = NULL;
3122             apply_attrs(GvSTASH(gv),
3123                         (type == OP_RV2SV ? GvSV(gv) :
3124                          type == OP_RV2AV ? MUTABLE_SV(GvAV(gv)) :
3125                          type == OP_RV2HV ? MUTABLE_SV(GvHV(gv)) : MUTABLE_SV(gv)),
3126                         attrs);
3127         }
3128         o->op_private |= OPpOUR_INTRO;
3129         return o;
3130     }
3131     else if (type != OP_PADSV &&
3132              type != OP_PADAV &&
3133              type != OP_PADHV &&
3134              type != OP_PUSHMARK)
3135     {
3136         S_cant_declare(aTHX_ o);
3137         return o;
3138     }
3139     else if (attrs && type != OP_PUSHMARK) {
3140         HV *stash;
3141
3142         assert(PL_parser);
3143         PL_parser->in_my = FALSE;
3144         PL_parser->in_my_stash = NULL;
3145
3146         /* check for C<my Dog $spot> when deciding package */
3147         stash = PAD_COMPNAME_TYPE(o->op_targ);
3148         if (!stash)
3149             stash = PL_curstash;
3150         apply_attrs_my(stash, o, attrs, imopsp);
3151     }
3152     o->op_flags |= OPf_MOD;
3153     o->op_private |= OPpLVAL_INTRO;
3154     if (stately)
3155         o->op_private |= OPpPAD_STATE;
3156     return o;
3157 }
3158
3159 OP *
3160 Perl_my_attrs(pTHX_ OP *o, OP *attrs)
3161 {
3162     OP *rops;
3163     int maybe_scalar = 0;
3164
3165     PERL_ARGS_ASSERT_MY_ATTRS;
3166
3167 /* [perl #17376]: this appears to be premature, and results in code such as
3168    C< our(%x); > executing in list mode rather than void mode */
3169 #if 0
3170     if (o->op_flags & OPf_PARENS)
3171         list(o);
3172     else
3173         maybe_scalar = 1;
3174 #else
3175     maybe_scalar = 1;
3176 #endif
3177     if (attrs)
3178         SAVEFREEOP(attrs);
3179     rops = NULL;
3180     o = my_kid(o, attrs, &rops);
3181     if (rops) {
3182         if (maybe_scalar && o->op_type == OP_PADSV) {
3183             o = scalar(op_append_list(OP_LIST, rops, o));
3184             o->op_private |= OPpLVAL_INTRO;
3185         }
3186         else {
3187             /* The listop in rops might have a pushmark at the beginning,
3188                which will mess up list assignment. */
3189             LISTOP * const lrops = (LISTOP *)rops; /* for brevity */
3190             if (rops->op_type == OP_LIST && 
3191                 lrops->op_first && lrops->op_first->op_type == OP_PUSHMARK)
3192             {
3193                 OP * const pushmark = lrops->op_first;
3194                 /* excise pushmark */
3195                 op_sibling_splice(rops, NULL, 1, NULL);
3196                 op_free(pushmark);
3197             }
3198             o = op_append_list(OP_LIST, o, rops);
3199         }
3200     }
3201     PL_parser->in_my = FALSE;
3202     PL_parser->in_my_stash = NULL;
3203     return o;
3204 }
3205
3206 OP *
3207 Perl_sawparens(pTHX_ OP *o)
3208 {
3209     PERL_UNUSED_CONTEXT;
3210     if (o)
3211         o->op_flags |= OPf_PARENS;
3212     return o;
3213 }
3214
3215 OP *
3216 Perl_bind_match(pTHX_ I32 type, OP *left, OP *right)
3217 {
3218     OP *o;
3219     bool ismatchop = 0;
3220     const OPCODE ltype = left->op_type;
3221     const OPCODE rtype = right->op_type;
3222
3223     PERL_ARGS_ASSERT_BIND_MATCH;
3224
3225     if ( (ltype == OP_RV2AV || ltype == OP_RV2HV || ltype == OP_PADAV
3226           || ltype == OP_PADHV) && ckWARN(WARN_MISC))
3227     {
3228       const char * const desc
3229           = PL_op_desc[(
3230                           rtype == OP_SUBST || rtype == OP_TRANS
3231                        || rtype == OP_TRANSR
3232                        )
3233                        ? (int)rtype : OP_MATCH];
3234       const bool isary = ltype == OP_RV2AV || ltype == OP_PADAV;
3235       SV * const name =
3236         S_op_varname(aTHX_ left);
3237       if (name)
3238         Perl_warner(aTHX_ packWARN(WARN_MISC),
3239              "Applying %s to %"SVf" will act on scalar(%"SVf")",
3240              desc, SVfARG(name), SVfARG(name));
3241       else {
3242         const char * const sample = (isary
3243              ? "@array" : "%hash");
3244         Perl_warner(aTHX_ packWARN(WARN_MISC),
3245              "Applying %s to %s will act on scalar(%s)",
3246              desc, sample, sample);
3247       }
3248     }
3249
3250     if (rtype == OP_CONST &&
3251         cSVOPx(right)->op_private & OPpCONST_BARE &&
3252         cSVOPx(right)->op_private & OPpCONST_STRICT)
3253     {
3254         no_bareword_allowed(right);
3255     }
3256
3257     /* !~ doesn't make sense with /r, so error on it for now */
3258     if (rtype == OP_SUBST && (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT) &&
3259         type == OP_NOT)
3260         /* diag_listed_as: Using !~ with %s doesn't make sense */
3261         yyerror("Using !~ with s///r doesn't make sense");
3262     if (rtype == OP_TRANSR && type == OP_NOT)
3263         /* diag_listed_as: Using !~ with %s doesn't make sense */
3264         yyerror("Using !~ with tr///r doesn't make sense");
3265
3266     ismatchop = (rtype == OP_MATCH ||
3267                  rtype == OP_SUBST ||
3268                  rtype == OP_TRANS || rtype == OP_TRANSR)
3269              && !(right->op_flags & OPf_SPECIAL);
3270     if (ismatchop && right->op_private & OPpTARGET_MY) {
3271         right->op_targ = 0;
3272         right->op_private &= ~OPpTARGET_MY;
3273     }
3274     if (!(right->op_flags & OPf_STACKED) && ismatchop) {
3275         OP *newleft;
3276
3277         right->op_flags |= OPf_STACKED;
3278         if (rtype != OP_MATCH && rtype != OP_TRANSR &&
3279             ! (rtype == OP_TRANS &&
3280                right->op_private & OPpTRANS_IDENTICAL) &&
3281             ! (rtype == OP_SUBST &&
3282                (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT)))
3283             newleft = op_lvalue(left, rtype);
3284         else
3285             newleft = left;
3286         if (right->op_type == OP_TRANS || right->op_type == OP_TRANSR)
3287             o = newBINOP(OP_NULL, OPf_STACKED, scalar(newleft), right);
3288         else
3289             o = op_prepend_elem(rtype, scalar(newleft), right);
3290         if (type == OP_NOT)
3291             return newUNOP(OP_NOT, 0, scalar(o));
3292         return o;
3293     }
3294     else
3295         return bind_match(type, left,
3296                 pmruntime(newPMOP(OP_MATCH, 0), right, 0, 0));
3297 }
3298
3299 OP *
3300 Perl_invert(pTHX_ OP *o)
3301 {
3302     if (!o)
3303         return NULL;
3304     return newUNOP(OP_NOT, OPf_SPECIAL, scalar(o));
3305 }
3306
3307 /*
3308 =for apidoc Amx|OP *|op_scope|OP *o
3309
3310 Wraps up an op tree with some additional ops so that at runtime a dynamic
3311 scope will be created.  The original ops run in the new dynamic scope,
3312 and then, provided that they exit normally, the scope will be unwound.
3313 The additional ops used to create and unwind the dynamic scope will
3314 normally be an C<enter>/C<leave> pair, but a C<scope> op may be used
3315 instead if the ops are simple enough to not need the full dynamic scope
3316 structure.
3317
3318 =cut
3319 */
3320
3321 OP *
3322 Perl_op_scope(pTHX_ OP *o)
3323 {
3324     dVAR;
3325     if (o) {
3326         if (o->op_flags & OPf_PARENS || PERLDB_NOOPT || TAINTING_get) {
3327             o = op_prepend_elem(OP_LINESEQ, newOP(OP_ENTER, 0), o);
3328             o->op_type = OP_LEAVE;
3329             o->op_ppaddr = PL_ppaddr[OP_LEAVE];
3330         }
3331         else if (o->op_type == OP_LINESEQ) {
3332             OP *kid;
3333             o->op_type = OP_SCOPE;
3334             o->op_ppaddr = PL_ppaddr[OP_SCOPE];
3335             kid = ((LISTOP*)o)->op_first;
3336             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) {
3337                 op_null(kid);
3338
3339                 /* The following deals with things like 'do {1 for 1}' */
3340                 kid = OP_SIBLING(kid);
3341                 if (kid &&
3342                     (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE))
3343                     op_null(kid);
3344             }
3345         }
3346         else
3347             o = newLISTOP(OP_SCOPE, 0, o, NULL);
3348     }
3349     return o;
3350 }
3351
3352 OP *
3353 Perl_op_unscope(pTHX_ OP *o)
3354 {
3355     if (o && o->op_type == OP_LINESEQ) {
3356         OP *kid = cLISTOPo->op_first;
3357         for(; kid; kid = OP_SIBLING(kid))
3358             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE)
3359                 op_null(kid);
3360     }
3361     return o;
3362 }
3363
3364 int
3365 Perl_block_start(pTHX_ int full)
3366 {
3367     const int retval = PL_savestack_ix;
3368
3369     pad_block_start(full);
3370     SAVEHINTS();
3371     PL_hints &= ~HINT_BLOCK_SCOPE;
3372     SAVECOMPILEWARNINGS();
3373     PL_compiling.cop_warnings = DUP_WARNINGS(PL_compiling.cop_warnings);
3374
3375     CALL_BLOCK_HOOKS(bhk_start, full);
3376
3377     return retval;
3378 }
3379
3380 OP*
3381 Perl_block_end(pTHX_ I32 floor, OP *seq)
3382 {
3383     const int needblockscope = PL_hints & HINT_BLOCK_SCOPE;
3384     OP* retval = scalarseq(seq);
3385     OP *o;
3386
3387     CALL_BLOCK_HOOKS(bhk_pre_end, &retval);
3388
3389     LEAVE_SCOPE(floor);
3390     if (needblockscope)
3391         PL_hints |= HINT_BLOCK_SCOPE; /* propagate out */
3392     o = pad_leavemy();
3393
3394     if (o) {
3395         /* pad_leavemy has created a sequence of introcv ops for all my
3396            subs declared in the block.  We have to replicate that list with
3397            clonecv ops, to deal with this situation:
3398
3399                sub {
3400                    my sub s1;
3401                    my sub s2;
3402                    sub s1 { state sub foo { \&s2 } }
3403                }->()
3404
3405            Originally, I was going to have introcv clone the CV and turn
3406            off the stale flag.  Since &s1 is declared before &s2, the
3407            introcv op for &s1 is executed (on sub entry) before the one for
3408            &s2.  But the &foo sub inside &s1 (which is cloned when &s1 is
3409            cloned, since it is a state sub) closes over &s2 and expects
3410            to see it in its outer CV’s pad.  If the introcv op clones &s1,
3411            then &s2 is still marked stale.  Since &s1 is not active, and
3412            &foo closes over &s1’s implicit entry for &s2, we get a â€˜Varia-
3413            ble will not stay shared’ warning.  Because it is the same stub
3414            that will be used when the introcv op for &s2 is executed, clos-
3415            ing over it is safe.  Hence, we have to turn off the stale flag
3416            on all lexical subs in the block before we clone any of them.
3417            Hence, having introcv clone the sub cannot work.  So we create a
3418            list of ops like this:
3419
3420                lineseq
3421                   |
3422                   +-- introcv
3423                   |
3424                   +-- introcv
3425                   |
3426                   +-- introcv
3427                   |
3428                   .
3429                   .
3430                   .
3431                   |
3432                   +-- clonecv
3433                   |
3434                   +-- clonecv
3435                   |
3436                   +-- clonecv
3437                   |
3438                   .
3439                   .
3440                   .
3441          */
3442         OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : o;
3443         OP * const last = o->op_flags & OPf_KIDS ? cLISTOPo->op_last : o;
3444         for (;; kid = OP_SIBLING(kid)) {
3445             OP *newkid = newOP(OP_CLONECV, 0);
3446             newkid->op_targ = kid->op_targ;
3447             o = op_append_elem(OP_LINESEQ, o, newkid);
3448             if (kid == last) break;
3449         }
3450         retval = op_prepend_elem(OP_LINESEQ, o, retval);
3451     }
3452
3453     CALL_BLOCK_HOOKS(bhk_post_end, &retval);
3454
3455     return retval;
3456 }
3457
3458 /*
3459 =head1 Compile-time scope hooks
3460
3461 =for apidoc Aox||blockhook_register
3462
3463 Register a set of hooks to be called when the Perl lexical scope changes
3464 at compile time.  See L<perlguts/"Compile-time scope hooks">.
3465
3466 =cut
3467 */
3468
3469 void
3470 Perl_blockhook_register(pTHX_ BHK *hk)
3471 {
3472     PERL_ARGS_ASSERT_BLOCKHOOK_REGISTER;
3473
3474     Perl_av_create_and_push(aTHX_ &PL_blockhooks, newSViv(PTR2IV(hk)));
3475 }
3476
3477 STATIC OP *
3478 S_newDEFSVOP(pTHX)
3479 {
3480     const PADOFFSET offset = pad_findmy_pvs("$_", 0);
3481     if (offset == NOT_IN_PAD || PAD_COMPNAME_FLAGS_isOUR(offset)) {
3482         return newSVREF(newGVOP(OP_GV, 0, PL_defgv));
3483     }
3484     else {
3485         OP * const o = newOP(OP_PADSV, 0);
3486         o->op_targ = offset;
3487         return o;
3488     }
3489 }
3490
3491 void
3492 Perl_newPROG(pTHX_ OP *o)
3493 {
3494     PERL_ARGS_ASSERT_NEWPROG;
3495
3496     if (PL_in_eval) {
3497         PERL_CONTEXT *cx;
3498         I32 i;
3499         if (PL_eval_root)
3500                 return;
3501         PL_eval_root = newUNOP(OP_LEAVEEVAL,
3502                                ((PL_in_eval & EVAL_KEEPERR)
3503                                 ? OPf_SPECIAL : 0), o);
3504
3505         cx = &cxstack[cxstack_ix];
3506         assert(CxTYPE(cx) == CXt_EVAL);
3507
3508         if ((cx->blk_gimme & G_WANT) == G_VOID)
3509             scalarvoid(PL_eval_root);
3510         else if ((cx->blk_gimme & G_WANT) == G_ARRAY)
3511             list(PL_eval_root);
3512         else
3513             scalar(PL_eval_root);
3514
3515         PL_eval_start = op_linklist(PL_eval_root);
3516         PL_eval_root->op_private |= OPpREFCOUNTED;
3517         OpREFCNT_set(PL_eval_root, 1);
3518         PL_eval_root->op_next = 0;
3519         i = PL_savestack_ix;
3520         SAVEFREEOP(o);
3521         ENTER;
3522         CALL_PEEP(PL_eval_start);
3523         finalize_optree(PL_eval_root);
3524         S_prune_chain_head(&PL_eval_start);
3525         LEAVE;
3526         PL_savestack_ix = i;
3527     }
3528     else {
3529         if (o->op_type == OP_STUB) {
3530             /* This block is entered if nothing is compiled for the main
3531                program. This will be the case for an genuinely empty main
3532                program, or one which only has BEGIN blocks etc, so already
3533                run and freed.
3534
3535                Historically (5.000) the guard above was !o. However, commit
3536                f8a08f7b8bd67b28 (Jun 2001), integrated to blead as
3537                c71fccf11fde0068, changed perly.y so that newPROG() is now
3538                called with the output of block_end(), which returns a new
3539                OP_STUB for the case of an empty optree. ByteLoader (and
3540                maybe other things) also take this path, because they set up
3541                PL_main_start and PL_main_root directly, without generating an
3542                optree.
3543
3544                If the parsing the main program aborts (due to parse errors,
3545                or due to BEGIN or similar calling exit), then newPROG()
3546                isn't even called, and hence this code path and its cleanups
3547                are skipped. This shouldn't make a make a difference:
3548                * a non-zero return from perl_parse is a failure, and
3549                  perl_destruct() should be called immediately.
3550                * however, if exit(0) is called during the parse, then
3551                  perl_parse() returns 0, and perl_run() is called. As
3552                  PL_main_start will be NULL, perl_run() will return
3553                  promptly, and the exit code will remain 0.
3554             */
3555
3556             PL_comppad_name = 0;
3557             PL_compcv = 0;
3558             S_op_destroy(aTHX_ o);
3559             return;
3560         }
3561         PL_main_root = op_scope(sawparens(scalarvoid(o)));
3562         PL_curcop = &PL_compiling;
3563         PL_main_start = LINKLIST(PL_main_root);
3564         PL_main_root->op_private |= OPpREFCOUNTED;
3565         OpREFCNT_set(PL_main_root, 1);
3566         PL_main_root->op_next = 0;
3567         CALL_PEEP(PL_main_start);
3568         finalize_optree(PL_main_root);
3569         S_prune_chain_head(&PL_main_start);
3570         cv_forget_slab(PL_compcv);
3571         PL_compcv = 0;
3572
3573         /* Register with debugger */
3574         if (PERLDB_INTER) {
3575             CV * const cv = get_cvs("DB::postponed", 0);
3576             if (cv) {
3577                 dSP;
3578                 PUSHMARK(SP);
3579                 XPUSHs(MUTABLE_SV(CopFILEGV(&PL_compiling)));
3580                 PUTBACK;
3581                 call_sv(MUTABLE_SV(cv), G_DISCARD);
3582             }
3583         }
3584     }
3585 }
3586
3587 OP *
3588 Perl_localize(pTHX_ OP *o, I32 lex)
3589 {
3590     PERL_ARGS_ASSERT_LOCALIZE;
3591
3592     if (o->op_flags & OPf_PARENS)
3593 /* [perl #17376]: this appears to be premature, and results in code such as
3594    C< our(%x); > executing in list mode rather than void mode */
3595 #if 0
3596         list(o);
3597 #else
3598         NOOP;
3599 #endif
3600     else {
3601         if ( PL_parser->bufptr > PL_parser->oldbufptr
3602             && PL_parser->bufptr[-1] == ','
3603             && ckWARN(WARN_PARENTHESIS))
3604         {
3605             char *s = PL_parser->bufptr;
3606             bool sigil = FALSE;
3607
3608             /* some heuristics to detect a potential error */
3609             while (*s && (strchr(", \t\n", *s)))
3610                 s++;
3611
3612             while (1) {
3613                 if (*s && strchr("@$%*", *s) && *++s
3614                        && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s))) {
3615                     s++;
3616                     sigil = TRUE;
3617                     while (*s && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s)))
3618                         s++;
3619                     while (*s && (strchr(", \t\n", *s)))
3620                         s++;
3621                 }
3622                 else
3623                     break;
3624             }
3625             if (sigil && (*s == ';' || *s == '=')) {
3626                 Perl_warner(aTHX_ packWARN(WARN_PARENTHESIS),
3627                                 "Parentheses missing around \"%s\" list",
3628                                 lex
3629                                     ? (PL_parser->in_my == KEY_our
3630                                         ? "our"
3631                                         : PL_parser->in_my == KEY_state
3632                                             ? "state"
3633                                             : "my")
3634                                     : "local");
3635             }
3636         }
3637     }
3638     if (lex)
3639         o = my(o);
3640     else
3641         o = op_lvalue(o, OP_NULL);              /* a bit kludgey */
3642     PL_parser->in_my = FALSE;
3643     PL_parser->in_my_stash = NULL;
3644     return o;
3645 }
3646
3647 OP *
3648 Perl_jmaybe(pTHX_ OP *o)
3649 {
3650     PERL_ARGS_ASSERT_JMAYBE;
3651
3652     if (o->op_type == OP_LIST) {
3653         OP * const o2
3654             = newSVREF(newGVOP(OP_GV, 0, gv_fetchpvs(";", GV_ADD|GV_NOTQUAL, SVt_PV)));
3655         o = convert(OP_JOIN, 0, op_prepend_elem(OP_LIST, o2, o));
3656     }
3657     return o;
3658 }
3659
3660 PERL_STATIC_INLINE OP *
3661 S_op_std_init(pTHX_ OP *o)
3662 {
3663     I32 type = o->op_type;
3664
3665     PERL_ARGS_ASSERT_OP_STD_INIT;
3666
3667     if (PL_opargs[type] & OA_RETSCALAR)
3668         scalar(o);
3669     if (PL_opargs[type] & OA_TARGET && !o->op_targ)
3670         o->op_targ = pad_alloc(type, SVs_PADTMP);
3671
3672     return o;
3673 }
3674
3675 PERL_STATIC_INLINE OP *
3676 S_op_integerize(pTHX_ OP *o)
3677 {
3678     I32 type = o->op_type;
3679
3680     PERL_ARGS_ASSERT_OP_INTEGERIZE;
3681
3682     /* integerize op. */
3683     if ((PL_opargs[type] & OA_OTHERINT) && (PL_hints & HINT_INTEGER))
3684     {
3685         dVAR;
3686         o->op_ppaddr = PL_ppaddr[++(o->op_type)];
3687     }
3688
3689     if (type == OP_NEGATE)
3690         /* XXX might want a ck_negate() for this */
3691         cUNOPo->op_first->op_private &= ~OPpCONST_STRICT;
3692
3693     return o;
3694 }
3695
3696 static OP *
3697 S_fold_constants(pTHX_ OP *o)
3698 {
3699     dVAR;
3700     OP * VOL curop;
3701     OP *newop;
3702     VOL I32 type = o->op_type;
3703     SV * VOL sv = NULL;
3704     int ret = 0;
3705     I32 oldscope;
3706     OP *old_next;
3707     SV * const oldwarnhook = PL_warnhook;
3708     SV * const olddiehook  = PL_diehook;
3709     COP not_compiling;
3710     U8 oldwarn = PL_dowarn;
3711     dJMPENV;
3712
3713     PERL_ARGS_ASSERT_FOLD_CONSTANTS;
3714
3715     if (!(PL_opargs[type] & OA_FOLDCONST))
3716         goto nope;
3717
3718     switch (type) {
3719     case OP_UCFIRST:
3720     case OP_LCFIRST:
3721     case OP_UC:
3722     case OP_LC:
3723     case OP_FC:
3724 #ifdef USE_LOCALE_CTYPE
3725         if (IN_LC_COMPILETIME(LC_CTYPE))
3726             goto nope;
3727 #endif
3728         break;
3729     case OP_SLT:
3730     case OP_SGT:
3731     case OP_SLE:
3732     case OP_SGE:
3733     case OP_SCMP:
3734 #ifdef USE_LOCALE_COLLATE
3735         if (IN_LC_COMPILETIME(LC_COLLATE))
3736             goto nope;
3737 #endif
3738         break;
3739     case OP_SPRINTF:
3740         /* XXX what about the numeric ops? */
3741 #ifdef USE_LOCALE_NUMERIC
3742         if (IN_LC_COMPILETIME(LC_NUMERIC))
3743             goto nope;
3744 #endif
3745         break;
3746     case OP_PACK:
3747         if (!OP_HAS_SIBLING(cLISTOPo->op_first)
3748           || OP_SIBLING(cLISTOPo->op_first)->op_type != OP_CONST)
3749             goto nope;
3750         {
3751             SV * const sv = cSVOPx_sv(OP_SIBLING(cLISTOPo->op_first));
3752             if (!SvPOK(sv) || SvGMAGICAL(sv)) goto nope;
3753             {
3754                 const char *s = SvPVX_const(sv);
3755                 while (s < SvEND(sv)) {
3756                     if (isALPHA_FOLD_EQ(*s, 'p')) goto nope;
3757                     s++;
3758                 }
3759             }
3760         }
3761         break;
3762     case OP_REPEAT:
3763         if (o->op_private & OPpREPEAT_DOLIST) goto nope;
3764         break;
3765     case OP_SREFGEN:
3766         if (cUNOPx(cUNOPo->op_first)->op_first->op_type != OP_CONST
3767          || SvPADTMP(cSVOPx_sv(cUNOPx(cUNOPo->op_first)->op_first)))
3768             goto nope;
3769     }
3770
3771     if (PL_parser && PL_parser->error_count)
3772         goto nope;              /* Don't try to run w/ errors */
3773
3774     for (curop = LINKLIST(o); curop != o; curop = LINKLIST(curop)) {
3775         const OPCODE type = curop->op_type;
3776         if ((type != OP_CONST || (curop->op_private & OPpCONST_BARE)) &&
3777             type != OP_LIST &&
3778             type != OP_SCALAR &&
3779             type != OP_NULL &&
3780             type != OP_PUSHMARK)
3781         {
3782             goto nope;
3783         }
3784     }
3785
3786     curop = LINKLIST(o);
3787     old_next = o->op_next;
3788     o->op_next = 0;
3789     PL_op = curop;
3790
3791     oldscope = PL_scopestack_ix;
3792     create_eval_scope(G_FAKINGEVAL);
3793
3794     /* Verify that we don't need to save it:  */
3795     assert(PL_curcop == &PL_compiling);
3796     StructCopy(&PL_compiling, &not_compiling, COP);
3797     PL_curcop = &not_compiling;
3798     /* The above ensures that we run with all the correct hints of the
3799        currently compiling COP, but that IN_PERL_RUNTIME is not true. */
3800     assert(IN_PERL_RUNTIME);
3801     PL_warnhook = PERL_WARNHOOK_FATAL;
3802     PL_diehook  = NULL;
3803     JMPENV_PUSH(ret);
3804
3805     /* Effective $^W=1.  */
3806     if ( ! (PL_dowarn & G_WARN_ALL_MASK))
3807         PL_dowarn |= G_WARN_ON;
3808
3809     switch (ret) {
3810     case 0:
3811         CALLRUNOPS(aTHX);
3812         sv = *(PL_stack_sp--);
3813         if (o->op_targ && sv == PAD_SV(o->op_targ)) {   /* grab pad temp? */
3814             pad_swipe(o->op_targ,  FALSE);
3815         }
3816         else if (SvTEMP(sv)) {                  /* grab mortal temp? */
3817             SvREFCNT_inc_simple_void(sv);
3818             SvTEMP_off(sv);
3819         }
3820         else { assert(SvIMMORTAL(sv)); }
3821         break;
3822     case 3:
3823         /* Something tried to die.  Abandon constant folding.  */
3824         /* Pretend the error never happened.  */
3825         CLEAR_ERRSV();
3826         o->op_next = old_next;
3827         break;
3828     default:
3829         JMPENV_POP;
3830         /* Don't expect 1 (setjmp failed) or 2 (something called my_exit)  */
3831         PL_warnhook = oldwarnhook;
3832         PL_diehook  = olddiehook;
3833         /* XXX note that this croak may fail as we've already blown away
3834          * the stack - eg any nested evals */
3835         Perl_croak(aTHX_ "panic: fold_constants JMPENV_PUSH returned %d", ret);
3836     }
3837     JMPENV_POP;
3838     PL_dowarn   = oldwarn;
3839     PL_warnhook = oldwarnhook;
3840     PL_diehook  = olddiehook;
3841     PL_curcop = &PL_compiling;
3842
3843     if (PL_scopestack_ix > oldscope)
3844         delete_eval_scope();
3845
3846     if (ret)
3847         goto nope;
3848
3849     op_free(o);
3850     assert(sv);
3851     if (type == OP_STRINGIFY) SvPADTMP_off(sv);
3852     else if (!SvIMMORTAL(sv)) {
3853         SvPADTMP_on(sv);
3854         SvREADONLY_on(sv);
3855     }
3856     if (type == OP_RV2GV)
3857         newop = newGVOP(OP_GV, 0, MUTABLE_GV(sv));
3858     else
3859     {
3860         newop = newSVOP(OP_CONST, 0, MUTABLE_SV(sv));
3861         if (type != OP_STRINGIFY) newop->op_folded = 1;
3862     }
3863     return newop;
3864
3865  nope:
3866     return o;
3867 }
3868
3869 static OP *
3870 S_gen_constant_list(pTHX_ OP *o)
3871 {
3872     dVAR;
3873     OP *curop;
3874     const SSize_t oldtmps_floor = PL_tmps_floor;
3875     SV **svp;
3876     AV *av;
3877
3878     list(o);
3879     if (PL_parser && PL_parser->error_count)
3880         return o;               /* Don't attempt to run with errors */
3881
3882     curop = LINKLIST(o);
3883     o->op_next = 0;
3884     CALL_PEEP(curop);
3885     S_prune_chain_head(&curop);
3886     PL_op = curop;
3887     Perl_pp_pushmark(aTHX);
3888     CALLRUNOPS(aTHX);
3889     PL_op = curop;
3890     assert (!(curop->op_flags & OPf_SPECIAL));
3891     assert(curop->op_type == OP_RANGE);
3892     Perl_pp_anonlist(aTHX);
3893     PL_tmps_floor = oldtmps_floor;
3894
3895     o->op_type = OP_RV2AV;
3896     o->op_ppaddr = PL_ppaddr[OP_RV2AV];
3897     o->op_flags &= ~OPf_REF;    /* treat \(1..2) like an ordinary list */
3898     o->op_flags |= OPf_PARENS;  /* and flatten \(1..2,3) */
3899     o->op_opt = 0;              /* needs to be revisited in rpeep() */
3900     av = (AV *)SvREFCNT_inc_NN(*PL_stack_sp--);
3901
3902     /* replace subtree with an OP_CONST */
3903     curop = ((UNOP*)o)->op_first;
3904     op_sibling_splice(o, NULL, -1, newSVOP(OP_CONST, 0, (SV *)av));
3905     op_free(curop);
3906
3907     if (AvFILLp(av) != -1)
3908         for (svp = AvARRAY(av) + AvFILLp(av); svp >= AvARRAY(av); --svp)
3909         {
3910             SvPADTMP_on(*svp);
3911             SvREADONLY_on(*svp);
3912         }
3913     LINKLIST(o);
3914     return list(o);
3915 }
3916
3917 /* convert o (and any siblings) into a list if not already, then
3918  * convert the parent OP_LIST to type 'type', and CHECKOP() and fold it
3919  */
3920
3921 OP *
3922 Perl_convert(pTHX_ I32 type, I32 flags, OP *o)
3923 {
3924     dVAR;
3925     if (type < 0) type = -type, flags |= OPf_SPECIAL;
3926     if (!o || o->op_type != OP_LIST)
3927         o = force_list(o, 0);
3928     else
3929         o->op_flags &= ~OPf_WANT;
3930
3931     if (!(PL_opargs[type] & OA_MARK))
3932         op_null(cLISTOPo->op_first);
3933     else {
3934         OP * const kid2 = OP_SIBLING(cLISTOPo->op_first);
3935         if (kid2 && kid2->op_type == OP_COREARGS) {
3936             op_null(cLISTOPo->op_first);
3937             kid2->op_private |= OPpCOREARGS_PUSHMARK;
3938         }
3939     }   
3940
3941     o->op_type = (OPCODE)type;
3942     o->op_ppaddr = PL_ppaddr[type];
3943     o->op_flags |= flags;
3944
3945     o = CHECKOP(type, o);
3946     if (o->op_type != (unsigned)type)
3947         return o;
3948
3949     return fold_constants(op_integerize(op_std_init(o)));
3950 }
3951
3952 /*
3953 =head1 Optree Manipulation Functions
3954 */
3955
3956 /* List constructors */
3957
3958 /*
3959 =for apidoc Am|OP *|op_append_elem|I32 optype|OP *first|OP *last
3960
3961 Append an item to the list of ops contained directly within a list-type
3962 op, returning the lengthened list.  I<first> is the list-type op,
3963 and I<last> is the op to append to the list.  I<optype> specifies the
3964 intended opcode for the list.  If I<first> is not already a list of the
3965 right type, it will be upgraded into one.  If either I<first> or I<last>
3966 is null, the other is returned unchanged.
3967
3968 =cut
3969 */
3970
3971 OP *
3972 Perl_op_append_elem(pTHX_ I32 type, OP *first, OP *last)
3973 {
3974     if (!first)
3975         return last;
3976
3977     if (!last)
3978         return first;
3979
3980     if (first->op_type != (unsigned)type
3981         || (type == OP_LIST && (first->op_flags & OPf_PARENS)))
3982     {
3983         return newLISTOP(type, 0, first, last);
3984     }
3985
3986     op_sibling_splice(first, ((LISTOP*)first)->op_last, 0, last);
3987     first->op_flags |= OPf_KIDS;
3988     return first;
3989 }
3990
3991 /*
3992 =for apidoc Am|OP *|op_append_list|I32 optype|OP *first|OP *last
3993
3994 Concatenate the lists of ops contained directly within two list-type ops,
3995 returning the combined list.  I<first> and I<last> are the list-type ops
3996 to concatenate.  I<optype> specifies the intended opcode for the list.
3997 If either I<first> or I<last> is not already a list of the right type,
3998 it will be upgraded into one.  If either I<first> or I<last> is null,
3999 the other is returned unchanged.
4000
4001 =cut
4002 */
4003
4004 OP *
4005 Perl_op_append_list(pTHX_ I32 type, OP *first, OP *last)
4006 {
4007     if (!first)
4008         return last;
4009
4010     if (!last)
4011         return first;
4012
4013     if (first->op_type != (unsigned)type)
4014         return op_prepend_elem(type, first, last);
4015
4016     if (last->op_type != (unsigned)type)
4017         return op_append_elem(type, first, last);
4018
4019     ((LISTOP*)first)->op_last->op_lastsib = 0;
4020     OP_SIBLING_set(((LISTOP*)first)->op_last, ((LISTOP*)last)->op_first);
4021     ((LISTOP*)first)->op_last = ((LISTOP*)last)->op_last;
4022     ((LISTOP*)first)->op_last->op_lastsib = 1;
4023 #ifdef PERL_OP_PARENT
4024     ((LISTOP*)first)->op_last->op_sibling = first;
4025 #endif
4026     first->op_flags |= (last->op_flags & OPf_KIDS);
4027
4028
4029     S_op_destroy(aTHX_ last);
4030
4031     return first;
4032 }
4033
4034 /*
4035 =for apidoc Am|OP *|op_prepend_elem|I32 optype|OP *first|OP *last
4036
4037 Prepend an item to the list of ops contained directly within a list-type
4038 op, returning the lengthened list.  I<first> is the op to prepend to the
4039 list, and I<last> is the list-type op.  I<optype> specifies the intended
4040 opcode for the list.  If I<last> is not already a list of the right type,
4041 it will be upgraded into one.  If either I<first> or I<last> is null,
4042 the other is returned unchanged.
4043
4044 =cut
4045 */
4046
4047 OP *
4048 Perl_op_prepend_elem(pTHX_ I32 type, OP *first, OP *last)
4049 {
4050     if (!first)
4051         return last;
4052
4053     if (!last)
4054         return first;
4055
4056     if (last->op_type == (unsigned)type) {
4057         if (type == OP_LIST) {  /* already a PUSHMARK there */
4058             /* insert 'first' after pushmark */
4059             op_sibling_splice(last, cLISTOPx(last)->op_first, 0, first);
4060             if (!(first->op_flags & OPf_PARENS))
4061                 last->op_flags &= ~OPf_PARENS;
4062         }
4063         else
4064             op_sibling_splice(last, NULL, 0, first);
4065         last->op_flags |= OPf_KIDS;
4066         return last;
4067     }
4068
4069     return newLISTOP(type, 0, first, last);
4070 }
4071
4072 /* Constructors */
4073
4074
4075 /*
4076 =head1 Optree construction
4077
4078 =for apidoc Am|OP *|newNULLLIST
4079
4080 Constructs, checks, and returns a new C<stub> op, which represents an
4081 empty list expression.
4082
4083 =cut
4084 */
4085
4086 OP *
4087 Perl_newNULLLIST(pTHX)
4088 {
4089     return newOP(OP_STUB, 0);
4090 }
4091
4092 /* promote o and any siblings to be a list if its not already; i.e.
4093  *
4094  *  o - A - B
4095  *
4096  * becomes
4097  *
4098  *  list
4099  *    |
4100  *  pushmark - o - A - B
4101  *
4102  * If nullit it true, the list op is nulled.
4103  */
4104
4105 static OP *
4106 S_force_list(pTHX_ OP *o, bool nullit)
4107 {
4108     if (!o || o->op_type != OP_LIST) {
4109         OP *rest = NULL;
4110         if (o) {
4111             /* manually detach any siblings then add them back later */
4112             rest = OP_SIBLING(o);
4113             OP_SIBLING_set(o, NULL);
4114             o->op_lastsib = 1;
4115         }
4116         o = newLISTOP(OP_LIST, 0, o, NULL);
4117         if (rest)
4118             op_sibling_splice(o, cLISTOPo->op_last, 0, rest);
4119     }
4120     if (nullit)
4121         op_null(o);
4122     return o;
4123 }
4124
4125 /*
4126 =for apidoc Am|OP *|newLISTOP|I32 type|I32 flags|OP *first|OP *last
4127
4128 Constructs, checks, and returns an op of any list type.  I<type> is
4129 the opcode.  I<flags> gives the eight bits of C<op_flags>, except that
4130 C<OPf_KIDS> will be set automatically if required.  I<first> and I<last>
4131 supply up to two ops to be direct children of the list op; they are
4132 consumed by this function and become part of the constructed op tree.
4133
4134 =cut
4135 */
4136
4137 OP *
4138 Perl_newLISTOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
4139 {
4140     dVAR;
4141     LISTOP *listop;
4142
4143     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LISTOP);
4144
4145     NewOp(1101, listop, 1, LISTOP);
4146
4147     listop->op_type = (OPCODE)type;
4148     listop->op_ppaddr = PL_ppaddr[type];
4149     if (first || last)
4150         flags |= OPf_KIDS;
4151     listop->op_flags = (U8)flags;
4152
4153     if (!last && first)
4154         last = first;
4155     else if (!first && last)
4156         first = last;
4157     else if (first)
4158         OP_SIBLING_set(first, last);
4159     listop->op_first = first;
4160     listop->op_last = last;
4161     if (type == OP_LIST) {
4162         OP* const pushop = newOP(OP_PUSHMARK, 0);
4163         pushop->op_lastsib = 0;
4164         OP_SIBLING_set(pushop, first);
4165         listop->op_first = pushop;
4166         listop->op_flags |= OPf_KIDS;
4167         if (!last)
4168             listop->op_last = pushop;
4169     }
4170     if (first)
4171         first->op_lastsib = 0;
4172     if (listop->op_last) {
4173         listop->op_last->op_lastsib = 1;
4174 #ifdef PERL_OP_PARENT
4175         listop->op_last->op_sibling = (OP*)listop;
4176 #endif
4177     }
4178
4179     return CHECKOP(type, listop);
4180 }
4181
4182 /*
4183 =for apidoc Am|OP *|newOP|I32 type|I32 flags
4184
4185 Constructs, checks, and returns an op of any base type (any type that
4186 has no extra fields).  I<type> is the opcode.  I<flags> gives the
4187 eight bits of C<op_flags>, and, shifted up eight bits, the eight bits
4188 of C<op_private>.
4189
4190 =cut
4191 */
4192
4193 OP *
4194 Perl_newOP(pTHX_ I32 type, I32 flags)
4195 {
4196     dVAR;
4197     OP *o;
4198
4199     if (type == -OP_ENTEREVAL) {
4200         type = OP_ENTEREVAL;
4201         flags |= OPpEVAL_BYTES<<8;
4202     }
4203
4204     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP
4205         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
4206         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
4207         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
4208
4209     NewOp(1101, o, 1, OP);
4210     o->op_type = (OPCODE)type;
4211     o->op_ppaddr = PL_ppaddr[type];
4212     o->op_flags = (U8)flags;
4213
4214     o->op_next = o;
4215     o->op_private = (U8)(0 | (flags >> 8));
4216     if (PL_opargs[type] & OA_RETSCALAR)
4217         scalar(o);
4218     if (PL_opargs[type] & OA_TARGET)
4219         o->op_targ = pad_alloc(type, SVs_PADTMP);
4220     return CHECKOP(type, o);
4221 }
4222
4223 /*
4224 =for apidoc Am|OP *|newUNOP|I32 type|I32 flags|OP *first
4225
4226 Constructs, checks, and returns an op of any unary type.  I<type> is
4227 the opcode.  I<flags> gives the eight bits of C<op_flags>, except that
4228 C<OPf_KIDS> will be set automatically if required, and, shifted up eight
4229 bits, the eight bits of C<op_private>, except that the bit with value 1
4230 is automatically set.  I<first> supplies an optional op to be the direct
4231 child of the unary op; it is consumed by this function and become part
4232 of the constructed op tree.
4233
4234 =cut
4235 */
4236
4237 OP *
4238 Perl_newUNOP(pTHX_ I32 type, I32 flags, OP *first)
4239 {
4240     dVAR;
4241     UNOP *unop;
4242
4243     if (type == -OP_ENTEREVAL) {
4244         type = OP_ENTEREVAL;
4245         flags |= OPpEVAL_BYTES<<8;
4246     }
4247
4248     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP
4249         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
4250         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
4251         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
4252         || type == OP_SASSIGN
4253         || type == OP_ENTERTRY
4254         || type == OP_NULL );
4255
4256     if (!first)
4257         first = newOP(OP_STUB, 0);
4258     if (PL_opargs[type] & OA_MARK)
4259         first = force_list(first, 1);
4260
4261     NewOp(1101, unop, 1, UNOP);
4262     unop->op_type = (OPCODE)type;
4263     unop->op_ppaddr = PL_ppaddr[type];
4264     unop->op_first = first;
4265     unop->op_flags = (U8)(flags | OPf_KIDS);
4266     unop->op_private = (U8)(1 | (flags >> 8));
4267
4268 #ifdef PERL_OP_PARENT
4269     if (!OP_HAS_SIBLING(first)) /* true unless weird syntax error */
4270         first->op_sibling = (OP*)unop;
4271 #endif
4272
4273     unop = (UNOP*) CHECKOP(type, unop);
4274     if (unop->op_next)
4275         return (OP*)unop;
4276
4277     return fold_constants(op_integerize(op_std_init((OP *) unop)));
4278 }
4279
4280 /*
4281 =for apidoc Am|OP *|newBINOP|I32 type|I32 flags|OP *first|OP *last
4282
4283 Constructs, checks, and returns an op of any binary type.  I<type>
4284 is the opcode.  I<flags> gives the eight bits of C<op_flags>, except
4285 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
4286 the eight bits of C<op_private>, except that the bit with value 1 or
4287 2 is automatically set as required.  I<first> and I<last> supply up to
4288 two ops to be the direct children of the binary op; they are consumed
4289 by this function and become part of the constructed op tree.
4290
4291 =cut
4292 */
4293
4294 OP *
4295 Perl_newBINOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
4296 {
4297     dVAR;
4298     BINOP *binop;
4299
4300     ASSUME((PL_opargs[type] & OA_CLASS_MASK) == OA_BINOP
4301         || type == OP_SASSIGN || type == OP_NULL );
4302
4303     NewOp(1101, binop, 1, BINOP);
4304
4305     if (!first)
4306         first = newOP(OP_NULL, 0);
4307
4308     binop->op_type = (OPCODE)type;
4309     binop->op_ppaddr = PL_ppaddr[type];
4310     binop->op_first = first;
4311     binop->op_flags = (U8)(flags | OPf_KIDS);
4312     if (!last) {
4313         last = first;
4314         binop->op_private = (U8)(1 | (flags >> 8));
4315     }
4316     else {
4317         binop->op_private = (U8)(2 | (flags >> 8));
4318         OP_SIBLING_set(first, last);
4319         first->op_lastsib = 0;
4320     }
4321
4322 #ifdef PERL_OP_PARENT
4323     if (!OP_HAS_SIBLING(last)) /* true unless weird syntax error */
4324         last->op_sibling = (OP*)binop;
4325 #endif
4326
4327     binop = (BINOP*)CHECKOP(type, binop);
4328     if (binop->op_next || binop->op_type != (OPCODE)type)
4329         return (OP*)binop;
4330
4331     binop->op_last = OP_SIBLING(binop->op_first);
4332 #ifdef PERL_OP_PARENT
4333     if (binop->op_last)
4334         binop->op_last->op_sibling = (OP*)binop;
4335 #endif
4336
4337     return fold_constants(op_integerize(op_std_init((OP *)binop)));
4338 }
4339
4340 static int uvcompare(const void *a, const void *b)
4341     __attribute__nonnull__(1)
4342     __attribute__nonnull__(2)
4343     __attribute__pure__;
4344 static int uvcompare(const void *a, const void *b)
4345 {
4346     if (*((const UV *)a) < (*(const UV *)b))
4347         return -1;
4348     if (*((const UV *)a) > (*(const UV *)b))
4349         return 1;
4350     if (*((const UV *)a+1) < (*(const UV *)b+1))
4351         return -1;
4352     if (*((const UV *)a+1) > (*(const UV *)b+1))
4353         return 1;
4354     return 0;
4355 }
4356
4357 static OP *
4358 S_pmtrans(pTHX_ OP *o, OP *expr, OP *repl)
4359 {
4360     SV * const tstr = ((SVOP*)expr)->op_sv;
4361     SV * const rstr =
4362                               ((SVOP*)repl)->op_sv;
4363     STRLEN tlen;
4364     STRLEN rlen;
4365     const U8 *t = (U8*)SvPV_const(tstr, tlen);
4366     const U8 *r = (U8*)SvPV_const(rstr, rlen);
4367     I32 i;
4368     I32 j;
4369     I32 grows = 0;
4370     short *tbl;
4371
4372     const I32 complement = o->op_private & OPpTRANS_COMPLEMENT;
4373     const I32 squash     = o->op_private & OPpTRANS_SQUASH;
4374     I32 del              = o->op_private & OPpTRANS_DELETE;
4375     SV* swash;
4376
4377     PERL_ARGS_ASSERT_PMTRANS;
4378
4379     PL_hints |= HINT_BLOCK_SCOPE;
4380
4381     if (SvUTF8(tstr))
4382         o->op_private |= OPpTRANS_FROM_UTF;
4383
4384     if (SvUTF8(rstr))
4385         o->op_private |= OPpTRANS_TO_UTF;
4386
4387     if (o->op_private & (OPpTRANS_FROM_UTF|OPpTRANS_TO_UTF)) {
4388         SV* const listsv = newSVpvs("# comment\n");
4389         SV* transv = NULL;
4390         const U8* tend = t + tlen;
4391         const U8* rend = r + rlen;
4392         STRLEN ulen;
4393         UV tfirst = 1;
4394         UV tlast = 0;
4395         IV tdiff;
4396         UV rfirst = 1;
4397         UV rlast = 0;
4398         IV rdiff;
4399         IV diff;
4400         I32 none = 0;
4401         U32 max = 0;
4402         I32 bits;
4403         I32 havefinal = 0;
4404         U32 final = 0;
4405         const I32 from_utf  = o->op_private & OPpTRANS_FROM_UTF;
4406         const I32 to_utf    = o->op_private & OPpTRANS_TO_UTF;
4407         U8* tsave = NULL;
4408         U8* rsave = NULL;
4409         const U32 flags = UTF8_ALLOW_DEFAULT;
4410
4411         if (!from_utf) {
4412             STRLEN len = tlen;
4413             t = tsave = bytes_to_utf8(t, &len);
4414             tend = t + len;
4415         }
4416         if (!to_utf && rlen) {
4417             STRLEN len = rlen;
4418             r = rsave = bytes_to_utf8(r, &len);
4419             rend = r + len;
4420         }
4421
4422 /* There is a snag with this code on EBCDIC: scan_const() in toke.c has
4423  * encoded chars in native encoding which makes ranges in the EBCDIC 0..255
4424  * odd.  */
4425
4426         if (complement) {
4427             U8 tmpbuf[UTF8_MAXBYTES+1];
4428             UV *cp;
4429             UV nextmin = 0;
4430             Newx(cp, 2*tlen, UV);
4431             i = 0;
4432             transv = newSVpvs("");
4433             while (t < tend) {
4434                 cp[2*i] = utf8n_to_uvchr(t, tend-t, &ulen, flags);
4435                 t += ulen;
4436                 if (t < tend && *t == ILLEGAL_UTF8_BYTE) {
4437                     t++;
4438                     cp[2*i+1] = utf8n_to_uvchr(t, tend-t, &ulen, flags);
4439                     t += ulen;
4440                 }
4441                 else {
4442                  cp[2*i+1] = cp[2*i];
4443                 }
4444                 i++;
4445             }
4446             qsort(cp, i, 2*sizeof(UV), uvcompare);
4447             for (j = 0; j < i; j++) {
4448                 UV  val = cp[2*j];
4449                 diff = val - nextmin;
4450                 if (diff > 0) {
4451                     t = uvchr_to_utf8(tmpbuf,nextmin);
4452                     sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
4453                     if (diff > 1) {
4454                         U8  range_mark = ILLEGAL_UTF8_BYTE;
4455                         t = uvchr_to_utf8(tmpbuf, val - 1);
4456                         sv_catpvn(transv, (char *)&range_mark, 1);
4457                         sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
4458                     }
4459                 }
4460                 val = cp[2*j+1];
4461                 if (val >= nextmin)
4462                     nextmin = val + 1;
4463             }
4464             t = uvchr_to_utf8(tmpbuf,nextmin);
4465             sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
4466             {
4467                 U8 range_mark = ILLEGAL_UTF8_BYTE;
4468                 sv_catpvn(transv, (char *)&range_mark, 1);
4469             }
4470             t = uvchr_to_utf8(tmpbuf, 0x7fffffff);
4471             sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
4472             t = (const U8*)SvPVX_const(transv);
4473             tlen = SvCUR(transv);
4474             tend = t + tlen;
4475             Safefree(cp);
4476         }
4477         else if (!rlen && !del) {
4478             r = t; rlen = tlen; rend = tend;
4479         }
4480         if (!squash) {
4481                 if ((!rlen && !del) || t == r ||
4482                     (tlen == rlen && memEQ((char *)t, (char *)r, tlen)))
4483                 {
4484                     o->op_private |= OPpTRANS_IDENTICAL;
4485                 }
4486         }
4487
4488         while (t < tend || tfirst <= tlast) {
4489             /* see if we need more "t" chars */
4490             if (tfirst > tlast) {
4491                 tfirst = (I32)utf8n_to_uvchr(t, tend - t, &ulen, flags);
4492                 t += ulen;
4493                 if (t < tend && *t == ILLEGAL_UTF8_BYTE) {      /* illegal utf8 val indicates range */
4494                     t++;
4495                     tlast = (I32)utf8n_to_uvchr(t, tend - t, &ulen, flags);
4496                     t += ulen;
4497                 }
4498                 else
4499                     tlast = tfirst;
4500             }
4501
4502             /* now see if we need more "r" chars */
4503             if (rfirst > rlast) {
4504                 if (r < rend) {
4505                     rfirst = (I32)utf8n_to_uvchr(r, rend - r, &ulen, flags);
4506                     r += ulen;
4507                     if (r < rend && *r == ILLEGAL_UTF8_BYTE) {  /* illegal utf8 val indicates range */
4508                         r++;
4509                         rlast = (I32)utf8n_to_uvchr(r, rend - r, &ulen, flags);
4510                         r += ulen;
4511                     }
4512                     else
4513                         rlast = rfirst;
4514                 }
4515                 else {
4516                     if (!havefinal++)
4517                         final = rlast;
4518                     rfirst = rlast = 0xffffffff;
4519                 }
4520             }
4521
4522             /* now see which range will peter our first, if either. */
4523             tdiff = tlast - tfirst;
4524             rdiff = rlast - rfirst;
4525
4526             if (tdiff <= rdiff)
4527                 diff = tdiff;
4528             else
4529                 diff = rdiff;
4530
4531             if (rfirst == 0xffffffff) {
4532                 diff = tdiff;   /* oops, pretend rdiff is infinite */
4533                 if (diff > 0)
4534                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t%04lx\tXXXX\n",
4535                                    (long)tfirst, (long)tlast);
4536                 else
4537                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t\tXXXX\n", (long)tfirst);
4538             }
4539             else {
4540                 if (diff > 0)
4541                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t%04lx\t%04lx\n",
4542                                    (long)tfirst, (long)(tfirst + diff),
4543                                    (long)rfirst);
4544                 else
4545                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t\t%04lx\n",
4546                                    (long)tfirst, (long)rfirst);
4547
4548                 if (rfirst + diff > max)
4549                     max = rfirst + diff;
4550                 if (!grows)
4551                     grows = (tfirst < rfirst &&
4552                              UNISKIP(tfirst) < UNISKIP(rfirst + diff));
4553                 rfirst += diff + 1;
4554             }
4555             tfirst += diff + 1;
4556         }
4557
4558         none = ++max;
4559         if (del)
4560             del = ++max;
4561
4562         if (max > 0xffff)
4563             bits = 32;
4564         else if (max > 0xff)
4565             bits = 16;
4566         else
4567             bits = 8;
4568
4569         swash = MUTABLE_SV(swash_init("utf8", "", listsv, bits, none));
4570 #ifdef USE_ITHREADS
4571         cPADOPo->op_padix = pad_alloc(OP_TRANS, SVf_READONLY);
4572         SvREFCNT_dec(PAD_SVl(cPADOPo->op_padix));
4573         PAD_SETSV(cPADOPo->op_padix, swash);
4574         SvPADTMP_on(swash);
4575         SvREADONLY_on(swash);
4576 #else
4577         cSVOPo->op_sv = swash;
4578 #endif
4579         SvREFCNT_dec(listsv);
4580         SvREFCNT_dec(transv);
4581
4582         if (!del && havefinal && rlen)
4583             (void)hv_store(MUTABLE_HV(SvRV(swash)), "FINAL", 5,
4584                            newSVuv((UV)final), 0);
4585
4586         if (grows)
4587             o->op_private |= OPpTRANS_GROWS;
4588
4589         Safefree(tsave);
4590         Safefree(rsave);
4591
4592         op_free(expr);
4593         op_free(repl);
4594         return o;
4595     }
4596
4597     tbl = (short*)PerlMemShared_calloc(
4598         (o->op_private & OPpTRANS_COMPLEMENT) &&
4599             !(o->op_private & OPpTRANS_DELETE) ? 258 : 256,
4600         sizeof(short));
4601     cPVOPo->op_pv = (char*)tbl;
4602     if (complement) {
4603         for (i = 0; i < (I32)tlen; i++)
4604             tbl[t[i]] = -1;
4605         for (i = 0, j = 0; i < 256; i++) {
4606             if (!tbl[i]) {
4607                 if (j >= (I32)rlen) {
4608                     if (del)
4609                         tbl[i] = -2;
4610                     else if (rlen)
4611                         tbl[i] = r[j-1];
4612                     else
4613                         tbl[i] = (short)i;
4614                 }
4615                 else {
4616                     if (i < 128 && r[j] >= 128)
4617                         grows = 1;
4618                     tbl[i] = r[j++];
4619                 }
4620             }
4621         }
4622         if (!del) {
4623             if (!rlen) {
4624                 j = rlen;
4625                 if (!squash)
4626                     o->op_private |= OPpTRANS_IDENTICAL;
4627             }
4628             else if (j >= (I32)rlen)
4629                 j = rlen - 1;
4630             else {
4631                 tbl = 
4632                     (short *)
4633                     PerlMemShared_realloc(tbl,
4634                                           (0x101+rlen-j) * sizeof(short));
4635                 cPVOPo->op_pv = (char*)tbl;
4636             }
4637             tbl[0x100] = (short)(rlen - j);
4638             for (i=0; i < (I32)rlen - j; i++)
4639                 tbl[0x101+i] = r[j+i];
4640         }
4641     }
4642     else {
4643         if (!rlen && !del) {
4644             r = t; rlen = tlen;
4645             if (!squash)
4646                 o->op_private |= OPpTRANS_IDENTICAL;
4647         }
4648         else if (!squash && rlen == tlen && memEQ((char*)t, (char*)r, tlen)) {
4649             o->op_private |= OPpTRANS_IDENTICAL;
4650         }
4651         for (i = 0; i < 256; i++)
4652             tbl[i] = -1;
4653         for (i = 0, j = 0; i < (I32)tlen; i++,j++) {
4654             if (j >= (I32)rlen) {
4655                 if (del) {
4656                     if (tbl[t[i]] == -1)
4657                         tbl[t[i]] = -2;
4658                     continue;
4659                 }
4660                 --j;
4661             }
4662             if (tbl[t[i]] == -1) {
4663                 if (t[i] < 128 && r[j] >= 128)
4664                     grows = 1;
4665                 tbl[t[i]] = r[j];
4666             }
4667         }
4668     }
4669
4670     if(del && rlen == tlen) {
4671         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Useless use of /d modifier in transliteration operator"); 
4672     } else if(rlen > tlen && !complement) {
4673         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Replacement list is longer than search list");
4674     }
4675
4676     if (grows)
4677         o->op_private |= OPpTRANS_GROWS;
4678     op_free(expr);
4679     op_free(repl);
4680
4681     return o;
4682 }
4683
4684 /*
4685 =for apidoc Am|OP *|newPMOP|I32 type|I32 flags
4686
4687 Constructs, checks, and returns an op of any pattern matching type.
4688 I<type> is the opcode.  I<flags> gives the eight bits of C<op_flags>
4689 and, shifted up eight bits, the eight bits of C<op_private>.
4690
4691 =cut
4692 */
4693
4694 OP *
4695 Perl_newPMOP(pTHX_ I32 type, I32 flags)
4696 {
4697     dVAR;
4698     PMOP *pmop;
4699
4700     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PMOP);
4701
4702     NewOp(1101, pmop, 1, PMOP);
4703     pmop->op_type = (OPCODE)type;
4704     pmop->op_ppaddr = PL_ppaddr[type];
4705     pmop->op_flags = (U8)flags;
4706     pmop->op_private = (U8)(0 | (flags >> 8));
4707
4708     if (PL_hints & HINT_RE_TAINT)
4709         pmop->op_pmflags |= PMf_RETAINT;
4710 #ifdef USE_LOCALE_CTYPE
4711     if (IN_LC_COMPILETIME(LC_CTYPE)) {
4712         set_regex_charset(&(pmop->op_pmflags), REGEX_LOCALE_CHARSET);
4713     }
4714     else
4715 #endif
4716          if (IN_UNI_8_BIT) {
4717         set_regex_charset(&(pmop->op_pmflags), REGEX_UNICODE_CHARSET);
4718     }
4719     if (PL_hints & HINT_RE_FLAGS) {
4720         SV *reflags = Perl_refcounted_he_fetch_pvn(aTHX_
4721          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags"), 0, 0
4722         );
4723         if (reflags && SvOK(reflags)) pmop->op_pmflags |= SvIV(reflags);
4724         reflags = Perl_refcounted_he_fetch_pvn(aTHX_
4725          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags_charset"), 0, 0
4726         );
4727         if (reflags && SvOK(reflags)) {
4728             set_regex_charset(&(pmop->op_pmflags), (regex_charset)SvIV(reflags));
4729         }
4730     }
4731
4732
4733 #ifdef USE_ITHREADS
4734     assert(SvPOK(PL_regex_pad[0]));
4735     if (SvCUR(PL_regex_pad[0])) {
4736         /* Pop off the "packed" IV from the end.  */
4737         SV *const repointer_list = PL_regex_pad[0];
4738         const char *p = SvEND(repointer_list) - sizeof(IV);
4739         const IV offset = *((IV*)p);
4740
4741         assert(SvCUR(repointer_list) % sizeof(IV) == 0);
4742
4743         SvEND_set(repointer_list, p);
4744
4745         pmop->op_pmoffset = offset;
4746         /* This slot should be free, so assert this:  */
4747         assert(PL_regex_pad[offset] == &PL_sv_undef);
4748     } else {
4749         SV * const repointer = &PL_sv_undef;
4750         av_push(PL_regex_padav, repointer);
4751         pmop->op_pmoffset = av_tindex(PL_regex_padav);
4752         PL_regex_pad = AvARRAY(PL_regex_padav);
4753     }
4754 #endif
4755
4756     return CHECKOP(type, pmop);
4757 }
4758
4759 /* Given some sort of match op o, and an expression expr containing a
4760  * pattern, either compile expr into a regex and attach it to o (if it's
4761  * constant), or convert expr into a runtime regcomp op sequence (if it's
4762  * not)
4763  *
4764  * isreg indicates that the pattern is part of a regex construct, eg
4765  * $x =~ /pattern/ or split /pattern/, as opposed to $x =~ $pattern or
4766  * split "pattern", which aren't. In the former case, expr will be a list
4767  * if the pattern contains more than one term (eg /a$b/) or if it contains
4768  * a replacement, ie s/// or tr///.
4769  *
4770  * When the pattern has been compiled within a new anon CV (for
4771  * qr/(?{...})/ ), then floor indicates the savestack level just before
4772  * the new sub was created
4773  */
4774
4775 OP *
4776 Perl_pmruntime(pTHX_ OP *o, OP *expr, bool isreg, I32 floor)
4777 {
4778     dVAR;
4779     PMOP *pm;
4780     LOGOP *rcop;
4781     I32 repl_has_vars = 0;
4782     OP* repl = NULL;
4783     bool is_trans = (o->op_type == OP_TRANS || o->op_type == OP_TRANSR);
4784     bool is_compiletime;
4785     bool has_code;
4786
4787     PERL_ARGS_ASSERT_PMRUNTIME;
4788
4789     /* for s/// and tr///, last element in list is the replacement; pop it */
4790
4791     if (is_trans || o->op_type == OP_SUBST) {
4792         OP* kid;
4793         repl = cLISTOPx(expr)->op_last;
4794         kid = cLISTOPx(expr)->op_first;
4795         while (OP_SIBLING(kid) != repl)
4796             kid = OP_SIBLING(kid);
4797         op_sibling_splice(expr, kid, 1, NULL);
4798     }
4799
4800     /* for TRANS, convert LIST/PUSH/CONST into CONST, and pass to pmtrans() */
4801
4802     if (is_trans) {
4803         OP *first, *last;
4804
4805         assert(expr->op_type == OP_LIST);
4806         first = cLISTOPx(expr)->op_first;
4807         last  = cLISTOPx(expr)->op_last;
4808         assert(first->op_type == OP_PUSHMARK);
4809         assert(OP_SIBLING(first) == last);
4810
4811         /* cut 'last' from sibling chain, then free everything else */
4812         op_sibling_splice(expr, first, 1, NULL);
4813         op_free(expr);
4814
4815         return pmtrans(o, last, repl);
4816     }
4817
4818     /* find whether we have any runtime or code elements;
4819      * at the same time, temporarily set the op_next of each DO block;
4820      * then when we LINKLIST, this will cause the DO blocks to be excluded
4821      * from the op_next chain (and from having LINKLIST recursively
4822      * applied to them). We fix up the DOs specially later */
4823
4824     is_compiletime = 1;
4825     has_code = 0;
4826     if (expr->op_type == OP_LIST) {
4827         OP *o;
4828         for (o = cLISTOPx(expr)->op_first; o; o = OP_SIBLING(o)) {
4829             if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)) {
4830                 has_code = 1;
4831                 assert(!o->op_next && OP_HAS_SIBLING(o));
4832                 o->op_next = OP_SIBLING(o);
4833             }
4834             else if (o->op_type != OP_CONST && o->op_type != OP_PUSHMARK)
4835                 is_compiletime = 0;
4836         }
4837     }
4838     else if (expr->op_type != OP_CONST)
4839         is_compiletime = 0;
4840
4841     LINKLIST(expr);
4842
4843     /* fix up DO blocks; treat each one as a separate little sub;
4844      * also, mark any arrays as LIST/REF */
4845
4846     if (expr->op_type == OP_LIST) {
4847         OP *o;
4848         for (o = cLISTOPx(expr)->op_first; o; o = OP_SIBLING(o)) {
4849
4850             if (o->op_type == OP_PADAV || o->op_type == OP_RV2AV) {
4851                 assert( !(o->op_flags  & OPf_WANT));
4852                 /* push the array rather than its contents. The regex
4853                  * engine will retrieve and join the elements later */
4854                 o->op_flags |= (OPf_WANT_LIST | OPf_REF);
4855                 continue;
4856             }
4857
4858             if (!(o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)))
4859                 continue;
4860             o->op_next = NULL; /* undo temporary hack from above */
4861             scalar(o);
4862             LINKLIST(o);
4863             if (cLISTOPo->op_first->op_type == OP_LEAVE) {
4864                 LISTOP *leaveop = cLISTOPx(cLISTOPo->op_first);
4865                 /* skip ENTER */
4866                 assert(leaveop->op_first->op_type == OP_ENTER);
4867                 assert(OP_HAS_SIBLING(leaveop->op_first));
4868                 o->op_next = OP_SIBLING(leaveop->op_first);
4869                 /* skip leave */
4870                 assert(leaveop->op_flags & OPf_KIDS);
4871                 assert(leaveop->op_last->op_next == (OP*)leaveop);
4872                 leaveop->op_next = NULL; /* stop on last op */
4873                 op_null((OP*)leaveop);
4874             }
4875             else {
4876                 /* skip SCOPE */
4877                 OP *scope = cLISTOPo->op_first;
4878                 assert(scope->op_type == OP_SCOPE);
4879                 assert(scope->op_flags & OPf_KIDS);
4880                 scope->op_next = NULL; /* stop on last op */
4881                 op_null(scope);
4882             }
4883             /* have to peep the DOs individually as we've removed it from
4884              * the op_next chain */
4885             CALL_PEEP(o);
4886             S_prune_chain_head(&(o->op_next));
4887             if (is_compiletime)
4888                 /* runtime finalizes as part of finalizing whole tree */
4889                 finalize_optree(o);
4890         }
4891     }
4892     else if (expr->op_type == OP_PADAV || expr->op_type == OP_RV2AV) {
4893         assert( !(expr->op_flags  & OPf_WANT));
4894         /* push the array rather than its contents. The regex
4895          * engine will retrieve and join the elements later */
4896         expr->op_flags |= (OPf_WANT_LIST | OPf_REF);
4897     }
4898
4899     PL_hints |= HINT_BLOCK_SCOPE;
4900     pm = (PMOP*)o;
4901     assert(floor==0 || (pm->op_pmflags & PMf_HAS_CV));
4902
4903     if (is_compiletime) {
4904         U32 rx_flags = pm->op_pmflags & RXf_PMf_COMPILETIME;
4905         regexp_engine const *eng = current_re_engine();
4906
4907         if (o->op_flags & OPf_SPECIAL)
4908             rx_flags |= RXf_SPLIT;
4909
4910         if (!has_code || !eng->op_comp) {
4911             /* compile-time simple constant pattern */
4912
4913             if ((pm->op_pmflags & PMf_HAS_CV) && !has_code) {
4914                 /* whoops! we guessed that a qr// had a code block, but we
4915                  * were wrong (e.g. /[(?{}]/ ). Throw away the PL_compcv
4916                  * that isn't required now. Note that we have to be pretty
4917                  * confident that nothing used that CV's pad while the
4918                  * regex was parsed */
4919                 assert(AvFILLp(PL_comppad) == 0); /* just @_ */
4920                 /* But we know that one op is using this CV's slab. */
4921                 cv_forget_slab(PL_compcv);
4922                 LEAVE_SCOPE(floor);
4923                 pm->op_pmflags &= ~PMf_HAS_CV;
4924             }
4925
4926             PM_SETRE(pm,
4927                 eng->op_comp
4928                     ? eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
4929                                         rx_flags, pm->op_pmflags)
4930                     : Perl_re_op_compile(aTHX_ NULL, 0, expr, eng, NULL, NULL,
4931                                         rx_flags, pm->op_pmflags)
4932             );
4933             op_free(expr);
4934         }
4935         else {
4936             /* compile-time pattern that includes literal code blocks */
4937             REGEXP* re = eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
4938                         rx_flags,
4939                         (pm->op_pmflags |
4940                             ((PL_hints & HINT_RE_EVAL) ? PMf_USE_RE_EVAL : 0))
4941                     );
4942             PM_SETRE(pm, re);
4943             if (pm->op_pmflags & PMf_HAS_CV) {
4944                 CV *cv;
4945                 /* this QR op (and the anon sub we embed it in) is never
4946                  * actually executed. It's just a placeholder where we can
4947                  * squirrel away expr in op_code_list without the peephole
4948                  * optimiser etc processing it for a second time */
4949                 OP *qr = newPMOP(OP_QR, 0);
4950                 ((PMOP*)qr)->op_code_list = expr;
4951
4952                 /* handle the implicit sub{} wrapped round the qr/(?{..})/ */
4953                 SvREFCNT_inc_simple_void(PL_compcv);
4954                 cv = newATTRSUB(floor, 0, NULL, NULL, qr);
4955                 ReANY(re)->qr_anoncv = cv;
4956
4957                 /* attach the anon CV to the pad so that
4958                  * pad_fixup_inner_anons() can find it */
4959                 (void)pad_add_anon(cv, o->op_type);
4960                 SvREFCNT_inc_simple_void(cv);
4961             }
4962             else {
4963                 pm->op_code_list = expr;
4964             }
4965         }
4966     }
4967     else {
4968         /* runtime pattern: build chain of regcomp etc ops */
4969         bool reglist;
4970         PADOFFSET cv_targ = 0;
4971
4972         reglist = isreg && expr->op_type == OP_LIST;
4973         if (reglist)
4974             op_null(expr);
4975
4976         if (has_code) {
4977             pm->op_code_list = expr;
4978             /* don't free op_code_list; its ops are embedded elsewhere too */
4979             pm->op_pmflags |= PMf_CODELIST_PRIVATE;
4980         }
4981
4982         if (o->op_flags & OPf_SPECIAL)
4983             pm->op_pmflags |= PMf_SPLIT;
4984
4985         /* the OP_REGCMAYBE is a placeholder in the non-threaded case
4986          * to allow its op_next to be pointed past the regcomp and
4987          * preceding stacking ops;
4988          * OP_REGCRESET is there to reset taint before executing the
4989          * stacking ops */
4990         if (pm->op_pmflags & PMf_KEEP || TAINTING_get)
4991             expr = newUNOP((TAINTING_get ? OP_REGCRESET : OP_REGCMAYBE),0,expr);
4992
4993         if (pm->op_pmflags & PMf_HAS_CV) {
4994             /* we have a runtime qr with literal code. This means
4995              * that the qr// has been wrapped in a new CV, which
4996              * means that runtime consts, vars etc will have been compiled
4997              * against a new pad. So... we need to execute those ops
4998              * within the environment of the new CV. So wrap them in a call
4999              * to a new anon sub. i.e. for
5000              *
5001              *     qr/a$b(?{...})/,
5002              *
5003              * we build an anon sub that looks like
5004              *
5005              *     sub { "a", $b, '(?{...})' }
5006              *
5007              * and call it, passing the returned list to regcomp.
5008              * Or to put it another way, the list of ops that get executed
5009              * are:
5010              *
5011              *     normal              PMf_HAS_CV
5012              *     ------              -------------------
5013              *                         pushmark (for regcomp)
5014              *                         pushmark (for entersub)
5015              *                         pushmark (for refgen)
5016              *                         anoncode
5017              *                         refgen
5018              *                         entersub
5019              *     regcreset                  regcreset
5020              *     pushmark                   pushmark
5021              *     const("a")                 const("a")
5022              *     gvsv(b)                    gvsv(b)
5023              *     const("(?{...})")          const("(?{...})")
5024              *                                leavesub
5025              *     regcomp             regcomp
5026              */
5027
5028             SvREFCNT_inc_simple_void(PL_compcv);
5029             /* these lines are just an unrolled newANONATTRSUB */
5030             expr = newSVOP(OP_ANONCODE, 0,
5031                     MUTABLE_SV(newATTRSUB(floor, 0, NULL, NULL, expr)));
5032             cv_targ = expr->op_targ;
5033             expr = newUNOP(OP_REFGEN, 0, expr);
5034
5035             expr = list(force_list(newUNOP(OP_ENTERSUB, 0, scalar(expr)), 1));
5036         }
5037
5038         rcop = S_alloc_LOGOP(aTHX_ OP_REGCOMP, scalar(expr), o);
5039         rcop->op_ppaddr = PL_ppaddr[OP_REGCOMP];
5040         rcop->op_flags |=  ((PL_hints & HINT_RE_EVAL) ? OPf_SPECIAL : 0)
5041                            | (reglist ? OPf_STACKED : 0);
5042         rcop->op_targ = cv_targ;
5043
5044         /* /$x/ may cause an eval, since $x might be qr/(?{..})/  */
5045         if (PL_hints & HINT_RE_EVAL) PL_cv_has_eval = 1;
5046
5047         /* establish postfix order */
5048         if (expr->op_type == OP_REGCRESET || expr->op_type == OP_REGCMAYBE) {
5049             LINKLIST(expr);
5050             rcop->op_next = expr;
5051             ((UNOP*)expr)->op_first->op_next = (OP*)rcop;
5052         }
5053         else {
5054             rcop->op_next = LINKLIST(expr);
5055             expr->op_next = (OP*)rcop;
5056         }
5057
5058         op_prepend_elem(o->op_type, scalar((OP*)rcop), o);
5059     }
5060
5061     if (repl) {
5062         OP *curop = repl;
5063         bool konst;
5064         /* If we are looking at s//.../e with a single statement, get past
5065            the implicit do{}. */
5066         if (curop->op_type == OP_NULL && curop->op_flags & OPf_KIDS
5067              && cUNOPx(curop)->op_first->op_type == OP_SCOPE
5068              && cUNOPx(curop)->op_first->op_flags & OPf_KIDS)
5069          {
5070             OP *sib;
5071             OP *kid = cUNOPx(cUNOPx(curop)->op_first)->op_first;
5072             if (kid->op_type == OP_NULL && (sib = OP_SIBLING(kid))
5073                      && !OP_HAS_SIBLING(sib))
5074                 curop = sib;
5075         }
5076         if (curop->op_type == OP_CONST)
5077             konst = TRUE;
5078         else if (( (curop->op_type == OP_RV2SV ||
5079                     curop->op_type == OP_RV2AV ||
5080                     curop->op_type == OP_RV2HV ||
5081                     curop->op_type == OP_RV2GV)
5082                    && cUNOPx(curop)->op_first
5083                    && cUNOPx(curop)->op_first->op_type == OP_GV )
5084                 || curop->op_type == OP_PADSV
5085                 || curop->op_type == OP_PADAV
5086                 || curop->op_type == OP_PADHV
5087                 || curop->op_type == OP_PADANY) {
5088             repl_has_vars = 1;
5089             konst = TRUE;
5090         }
5091         else konst = FALSE;
5092         if (konst
5093             && !(repl_has_vars
5094                  && (!PM_GETRE(pm)
5095                      || !RX_PRELEN(PM_GETRE(pm))
5096                      || RX_EXTFLAGS(PM_GETRE(pm)) & RXf_EVAL_SEEN)))
5097         {
5098             pm->op_pmflags |= PMf_CONST;        /* const for long enough */
5099             op_prepend_elem(o->op_type, scalar(repl), o);
5100         }
5101         else {
5102             rcop = S_alloc_LOGOP(aTHX_ OP_SUBSTCONT, scalar(repl), o);
5103             rcop->op_ppaddr = PL_ppaddr[OP_SUBSTCONT];
5104             rcop->op_private = 1;
5105
5106             /* establish postfix order */
5107             rcop->op_next = LINKLIST(repl);
5108             repl->op_next = (OP*)rcop;
5109
5110             pm->op_pmreplrootu.op_pmreplroot = scalar((OP*)rcop);
5111             assert(!(pm->op_pmflags & PMf_ONCE));
5112             pm->op_pmstashstartu.op_pmreplstart = LINKLIST(rcop);
5113             rcop->op_next = 0;
5114         }
5115     }
5116
5117     return (OP*)pm;
5118 }
5119
5120 /*
5121 =for apidoc Am|OP *|newSVOP|I32 type|I32 flags|SV *sv
5122
5123 Constructs, checks, and returns an op of any type that involves an
5124 embedded SV.  I<type> is the opcode.  I<flags> gives the eight bits
5125 of C<op_flags>.  I<sv> gives the SV to embed in the op; this function
5126 takes ownership of one reference to it.
5127
5128 =cut
5129 */
5130
5131 OP *
5132 Perl_newSVOP(pTHX_ I32 type, I32 flags, SV *sv)
5133 {
5134     dVAR;
5135     SVOP *svop;
5136
5137     PERL_ARGS_ASSERT_NEWSVOP;
5138
5139     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
5140         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
5141         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP);
5142
5143     NewOp(1101, svop, 1, SVOP);
5144     svop->op_type = (OPCODE)type;
5145     svop->op_ppaddr = PL_ppaddr[type];
5146     svop->op_sv = sv;
5147     svop->op_next = (OP*)svop;
5148     svop->op_flags = (U8)flags;
5149     svop->op_private = (U8)(0 | (flags >> 8));
5150     if (PL_opargs[type] & OA_RETSCALAR)
5151         scalar((OP*)svop);
5152     if (PL_opargs[type] & OA_TARGET)
5153         svop->op_targ = pad_alloc(type, SVs_PADTMP);
5154     return CHECKOP(type, svop);
5155 }
5156
5157 #ifdef USE_ITHREADS
5158
5159 /*
5160 =for apidoc Am|OP *|newPADOP|I32 type|I32 flags|SV *sv
5161
5162 Constructs, checks, and returns an op of any type that involves a
5163 reference to a pad element.  I<type> is the opcode.  I<flags> gives the
5164 eight bits of C<op_flags>.  A pad slot is automatically allocated, and
5165 is populated with I<sv>; this function takes ownership of one reference
5166 to it.
5167
5168 This function only exists if Perl has been compiled to use ithreads.
5169
5170 =cut
5171 */
5172
5173 OP *
5174 Perl_newPADOP(pTHX_ I32 type, I32 flags, SV *sv)
5175 {
5176     dVAR;
5177     PADOP *padop;
5178
5179     PERL_ARGS_ASSERT_NEWPADOP;
5180
5181     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
5182         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
5183         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP);
5184
5185     NewOp(1101, padop, 1, PADOP);
5186     padop->op_type = (OPCODE)type;
5187     padop->op_ppaddr = PL_ppaddr[type];
5188     padop->op_padix =
5189         pad_alloc(type, IS_PADGV(sv) ? SVf_READONLY : SVs_PADTMP);
5190     SvREFCNT_dec(PAD_SVl(padop->op_padix));
5191     PAD_SETSV(padop->op_padix, sv);
5192     assert(sv);
5193     padop->op_next = (OP*)padop;
5194     padop->op_flags = (U8)flags;
5195     if (PL_opargs[type] & OA_RETSCALAR)
5196         scalar((OP*)padop);
5197     if (PL_opargs[type] & OA_TARGET)
5198         padop->op_targ = pad_alloc(type, SVs_PADTMP);
5199     return CHECKOP(type, padop);
5200 }
5201
5202 #endif /* USE_ITHREADS */
5203
5204 /*
5205 =for apidoc Am|OP *|newGVOP|I32 type|I32 flags|GV *gv
5206
5207 Constructs, checks, and returns an op of any type that involves an
5208 embedded reference to a GV.  I<type> is the opcode.  I<flags> gives the
5209 eight bits of C<op_flags>.  I<gv> identifies the GV that the op should
5210 reference; calling this function does not transfer ownership of any
5211 reference to it.
5212
5213 =cut
5214 */
5215
5216 OP *
5217 Perl_newGVOP(pTHX_ I32 type, I32 flags, GV *gv)
5218 {
5219     PERL_ARGS_ASSERT_NEWGVOP;
5220
5221 #ifdef USE_ITHREADS
5222     GvIN_PAD_on(gv);
5223     return newPADOP(type, flags, SvREFCNT_inc_simple_NN(gv));
5224 #else
5225     return newSVOP(type, flags, SvREFCNT_inc_simple_NN(gv));
5226 #endif
5227 }
5228
5229 /*
5230 =for apidoc Am|OP *|newPVOP|I32 type|I32 flags|char *pv
5231
5232 Constructs, checks, and returns an op of any type that involves an
5233 embedded C-level pointer (PV).  I<type> is the opcode.  I<flags> gives
5234 the eight bits of C<op_flags>.  I<pv> supplies the C-level pointer, which
5235 must have been allocated using C<PerlMemShared_malloc>; the memory will
5236 be freed when the op is destroyed.
5237
5238 =cut
5239 */
5240
5241 OP *
5242 Perl_newPVOP(pTHX_ I32 type, I32 flags, char *pv)
5243 {
5244     dVAR;
5245     const bool utf8 = cBOOL(flags & SVf_UTF8);
5246     PVOP *pvop;
5247
5248     flags &= ~SVf_UTF8;
5249
5250     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
5251         || type == OP_RUNCV
5252         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
5253
5254     NewOp(1101, pvop, 1, PVOP);
5255     pvop->op_type = (OPCODE)type;
5256     pvop->op_ppaddr = PL_ppaddr[type];
5257     pvop->op_pv = pv;
5258     pvop->op_next = (OP*)pvop;
5259     pvop->op_flags = (U8)flags;
5260     pvop->op_private = utf8 ? OPpPV_IS_UTF8 : 0;
5261     if (PL_opargs[type] & OA_RETSCALAR)
5262         scalar((OP*)pvop);
5263     if (PL_opargs[type] & OA_TARGET)
5264         pvop->op_targ = pad_alloc(type, SVs_PADTMP);
5265     return CHECKOP(type, pvop);
5266 }
5267
5268 void
5269 Perl_package(pTHX_ OP *o)
5270 {
5271     SV *const sv = cSVOPo->op_sv;
5272
5273     PERL_ARGS_ASSERT_PACKAGE;
5274
5275     SAVEGENERICSV(PL_curstash);
5276     save_item(PL_curstname);
5277
5278     PL_curstash = (HV *)SvREFCNT_inc(gv_stashsv(sv, GV_ADD));
5279
5280     sv_setsv(PL_curstname, sv);
5281
5282     PL_hints |= HINT_BLOCK_SCOPE;
5283     PL_parser->copline = NOLINE;
5284
5285     op_free(o);
5286 }
5287
5288 void
5289 Perl_package_version( pTHX_ OP *v )
5290 {
5291     U32 savehints = PL_hints;
5292     PERL_ARGS_ASSERT_PACKAGE_VERSION;
5293     PL_hints &= ~HINT_STRICT_VARS;
5294     sv_setsv( GvSV(gv_fetchpvs("VERSION", GV_ADDMULTI, SVt_PV)), cSVOPx(v)->op_sv );
5295     PL_hints = savehints;
5296     op_free(v);
5297 }
5298
5299 void
5300 Perl_utilize(pTHX_ int aver, I32 floor, OP *version, OP *idop, OP *arg)
5301 {
5302     OP *pack;
5303     OP *imop;
5304     OP *veop;
5305     SV *use_version = NULL;
5306
5307     PERL_ARGS_ASSERT_UTILIZE;
5308
5309     if (idop->op_type != OP_CONST)
5310         Perl_croak(aTHX_ "Module name must be constant");
5311
5312     veop = NULL;
5313
5314     if (version) {
5315         SV * const vesv = ((SVOP*)version)->op_sv;
5316
5317         if (!arg && !SvNIOKp(vesv)) {
5318             arg = version;
5319         }
5320         else {
5321             OP *pack;
5322             SV *meth;
5323
5324             if (version->op_type != OP_CONST || !SvNIOKp(vesv))
5325                 Perl_croak(aTHX_ "Version number must be a constant number");
5326
5327             /* Make copy of idop so we don't free it twice */
5328             pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
5329
5330             /* Fake up a method call to VERSION */
5331             meth = newSVpvs_share("VERSION");
5332             veop = convert(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
5333                             op_append_elem(OP_LIST,
5334                                         op_prepend_elem(OP_LIST, pack, list(version)),
5335                                         newSVOP(OP_METHOD_NAMED, 0, meth)));
5336         }
5337     }
5338
5339     /* Fake up an import/unimport */
5340     if (arg && arg->op_type == OP_STUB) {
5341         imop = arg;             /* no import on explicit () */
5342     }
5343     else if (SvNIOKp(((SVOP*)idop)->op_sv)) {
5344         imop = NULL;            /* use 5.0; */
5345         if (aver)
5346             use_version = ((SVOP*)idop)->op_sv;
5347         else
5348             idop->op_private |= OPpCONST_NOVER;
5349     }
5350     else {
5351         SV *meth;
5352
5353         /* Make copy of idop so we don't free it twice */
5354         pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
5355
5356         /* Fake up a method call to import/unimport */
5357         meth = aver
5358             ? newSVpvs_share("import") : newSVpvs_share("unimport");
5359         imop = convert(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
5360                        op_append_elem(OP_LIST,
5361                                    op_prepend_elem(OP_LIST, pack, list(arg)),
5362                                    newSVOP(OP_METHOD_NAMED, 0, meth)));
5363     }
5364
5365     /* Fake up the BEGIN {}, which does its thing immediately. */
5366     newATTRSUB(floor,
5367         newSVOP(OP_CONST, 0, newSVpvs_share("BEGIN")),
5368         NULL,
5369         NULL,
5370         op_append_elem(OP_LINESEQ,
5371             op_append_elem(OP_LINESEQ,
5372                 newSTATEOP(0, NULL, newUNOP(OP_REQUIRE, 0, idop)),
5373                 newSTATEOP(0, NULL, veop)),
5374             newSTATEOP(0, NULL, imop) ));
5375
5376     if (use_version) {
5377         /* Enable the
5378          * feature bundle that corresponds to the required version. */
5379         use_version = sv_2mortal(new_version(use_version));
5380         S_enable_feature_bundle(aTHX_ use_version);
5381
5382         /* If a version >= 5.11.0 is requested, strictures are on by default! */
5383         if (vcmp(use_version,
5384                  sv_2mortal(upg_version(newSVnv(5.011000), FALSE))) >= 0) {
5385             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
5386                 PL_hints |= HINT_STRICT_REFS;
5387             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
5388                 PL_hints |= HINT_STRICT_SUBS;
5389             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
5390                 PL_hints |= HINT_STRICT_VARS;
5391         }
5392         /* otherwise they are off */
5393         else {
5394             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
5395                 PL_hints &= ~HINT_STRICT_REFS;
5396             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
5397                 PL_hints &= ~HINT_STRICT_SUBS;
5398             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
5399                 PL_hints &= ~HINT_STRICT_VARS;
5400         }
5401     }
5402
5403     /* The "did you use incorrect case?" warning used to be here.
5404      * The problem is that on case-insensitive filesystems one
5405      * might get false positives for "use" (and "require"):
5406      * "use Strict" or "require CARP" will work.  This causes
5407      * portability problems for the script: in case-strict
5408      * filesystems the script will stop working.
5409      *
5410      * The "incorrect case" warning checked whether "use Foo"
5411      * imported "Foo" to your namespace, but that is wrong, too:
5412      * there is no requirement nor promise in the language that
5413      * a Foo.pm should or would contain anything in package "Foo".
5414      *
5415      * There is very little Configure-wise that can be done, either:
5416      * the case-sensitivity of the build filesystem of Perl does not
5417      * help in guessing the case-sensitivity of the runtime environment.
5418      */
5419
5420     PL_hints |= HINT_BLOCK_SCOPE;
5421     PL_parser->copline = NOLINE;
5422     PL_cop_seqmax++; /* Purely for B::*'s benefit */
5423     if (PL_cop_seqmax == PERL_PADSEQ_INTRO) /* not a legal value */
5424         PL_cop_seqmax++;
5425
5426 }
5427
5428 /*
5429 =head1 Embedding Functions
5430
5431 =for apidoc load_module
5432
5433 Loads the module whose name is pointed to by the string part of name.
5434 Note that the actual module name, not its filename, should be given.
5435 Eg, "Foo::Bar" instead of "Foo/Bar.pm".  flags can be any of
5436 PERL_LOADMOD_DENY, PERL_LOADMOD_NOIMPORT, or PERL_LOADMOD_IMPORT_OPS
5437 (or 0 for no flags).  ver, if specified
5438 and not NULL, provides version semantics
5439 similar to C<use Foo::Bar VERSION>.  The optional trailing SV*
5440 arguments can be used to specify arguments to the module's import()
5441 method, similar to C<use Foo::Bar VERSION LIST>.  They must be
5442 terminated with a final NULL pointer.  Note that this list can only
5443 be omitted when the PERL_LOADMOD_NOIMPORT flag has been used.
5444 Otherwise at least a single NULL pointer to designate the default
5445 import list is required.
5446
5447 The reference count for each specified C<SV*> parameter is decremented.
5448
5449 =cut */
5450
5451 void
5452 Perl_load_module(pTHX_ U32 flags, SV *name, SV *ver, ...)
5453 {
5454     va_list args;
5455
5456     PERL_ARGS_ASSERT_LOAD_MODULE;
5457
5458     va_start(args, ver);
5459     vload_module(flags, name, ver, &args);
5460     va_end(args);
5461 }
5462
5463 #ifdef PERL_IMPLICIT_CONTEXT
5464 void
5465 Perl_load_module_nocontext(U32 flags, SV *name, SV *ver, ...)
5466 {
5467     dTHX;
5468     va_list args;
5469     PERL_ARGS_ASSERT_LOAD_MODULE_NOCONTEXT;
5470     va_start(args, ver);
5471     vload_module(flags, name, ver, &args);
5472     va_end(args);
5473 }
5474 #endif
5475
5476 void
5477 Perl_vload_module(pTHX_ U32 flags, SV *name, SV *ver, va_list *args)
5478 {
5479     OP *veop, *imop;
5480     OP * const modname = newSVOP(OP_CONST, 0, name);
5481
5482     PERL_ARGS_ASSERT_VLOAD_MODULE;
5483
5484     modname->op_private |= OPpCONST_BARE;
5485     if (ver) {
5486         veop = newSVOP(OP_CONST, 0, ver);
5487     }
5488     else
5489         veop = NULL;
5490     if (flags & PERL_LOADMOD_NOIMPORT) {
5491         imop = sawparens(newNULLLIST());
5492     }
5493     else if (flags & PERL_LOADMOD_IMPORT_OPS) {
5494         imop = va_arg(*args, OP*);
5495     }
5496     else {
5497         SV *sv;
5498         imop = NULL;
5499         sv = va_arg(*args, SV*);
5500         while (sv) {
5501             imop = op_append_elem(OP_LIST, imop, newSVOP(OP_CONST, 0, sv));
5502             sv = va_arg(*args, SV*);
5503         }
5504     }
5505
5506     /* utilize() fakes up a BEGIN { require ..; import ... }, so make sure
5507      * that it has a PL_parser to play with while doing that, and also
5508      * that it doesn't mess with any existing parser, by creating a tmp
5509      * new parser with lex_start(). This won't actually be used for much,
5510      * since pp_require() will create another parser for the real work.
5511      * The ENTER/LEAVE pair protect callers from any side effects of use.  */
5512
5513     ENTER;
5514     SAVEVPTR(PL_curcop);
5515     lex_start(NULL, NULL, LEX_START_SAME_FILTER);
5516     utilize(!(flags & PERL_LOADMOD_DENY), start_subparse(FALSE, 0),
5517             veop, modname, imop);
5518     LEAVE;
5519 }
5520
5521 PERL_STATIC_INLINE OP *
5522 S_new_entersubop(pTHX_ GV *gv, OP *arg)
5523 {
5524     return newUNOP(OP_ENTERSUB, OPf_STACKED,
5525                    newLISTOP(OP_LIST, 0, arg,
5526                              newUNOP(OP_RV2CV, 0,
5527                                      newGVOP(OP_GV, 0, gv))));
5528 }
5529
5530 OP *
5531 Perl_dofile(pTHX_ OP *term, I32 force_builtin)
5532 {
5533     OP *doop;
5534     GV *gv;
5535
5536     PERL_ARGS_ASSERT_DOFILE;
5537
5538     if (!force_builtin && (gv = gv_override("do", 2))) {
5539         doop = S_new_entersubop(aTHX_ gv, term);
5540     }
5541     else {
5542         doop = newUNOP(OP_DOFILE, 0, scalar(term));
5543     }
5544     return doop;
5545 }
5546
5547 /*
5548 =head1 Optree construction
5549
5550 =for apidoc Am|OP *|newSLICEOP|I32 flags|OP *subscript|OP *listval
5551
5552 Constructs, checks, and returns an C<lslice> (list slice) op.  I<flags>
5553 gives the eight bits of C<op_flags>, except that C<OPf_KIDS> will
5554 be set automatically, and, shifted up eight bits, the eight bits of
5555 C<op_private>, except that the bit with value 1 or 2 is automatically
5556 set as required.  I<listval> and I<subscript> supply the parameters of
5557 the slice; they are consumed by this function and become part of the
5558 constructed op tree.
5559
5560 =cut
5561 */
5562
5563 OP *
5564 Perl_newSLICEOP(pTHX_ I32 flags, OP *subscript, OP *listval)
5565 {
5566     return newBINOP(OP_LSLICE, flags,
5567             list(force_list(subscript, 1)),
5568             list(force_list(listval,   1)) );
5569 }
5570
5571 STATIC I32
5572 S_is_list_assignment(pTHX_ const OP *o)
5573 {
5574     unsigned type;
5575     U8 flags;
5576
5577     if (!o)
5578         return TRUE;
5579
5580     if ((o->op_type == OP_NULL) && (o->op_flags & OPf_KIDS))
5581         o = cUNOPo->op_first;
5582
5583     flags = o->op_flags;
5584     type = o->op_type;
5585     if (type == OP_COND_EXPR) {
5586         OP * const sib = OP_SIBLING(cLOGOPo->op_first);
5587         const I32 t = is_list_assignment(sib);
5588         const I32 f = is_list_assignment(OP_SIBLING(sib));
5589
5590         if (t && f)
5591             return TRUE;
5592         if (t || f)
5593             yyerror("Assignment to both a list and a scalar");
5594         return FALSE;
5595     }
5596
5597     if (type == OP_LIST &&
5598         (flags & OPf_WANT) == OPf_WANT_SCALAR &&
5599         o->op_private & OPpLVAL_INTRO)
5600         return FALSE;
5601
5602     if (type == OP_LIST || flags & OPf_PARENS ||
5603         type == OP_RV2AV || type == OP_RV2HV ||
5604         type == OP_ASLICE || type == OP_HSLICE ||
5605         type == OP_KVASLICE || type == OP_KVHSLICE)
5606         return TRUE;
5607
5608     if (type == OP_PADAV || type == OP_PADHV)
5609         return TRUE;
5610
5611     if (type == OP_RV2SV)
5612         return FALSE;
5613
5614     return FALSE;
5615 }
5616
5617 /*
5618   Helper function for newASSIGNOP to detection commonality between the
5619   lhs and the rhs.  Marks all variables with PL_generation.  If it
5620   returns TRUE the assignment must be able to handle common variables.
5621 */
5622 PERL_STATIC_INLINE bool
5623 S_aassign_common_vars(pTHX_ OP* o)
5624 {
5625     OP *curop;
5626     for (curop = cUNOPo->op_first; curop; curop = OP_SIBLING(curop)) {
5627         if (PL_opargs[curop->op_type] & OA_DANGEROUS) {
5628             if (curop->op_type == OP_GV) {
5629                 GV *gv = cGVOPx_gv(curop);
5630                 if (gv == PL_defgv
5631                     || (int)GvASSIGN_GENERATION(gv) == PL_generation)
5632                     return TRUE;
5633                 GvASSIGN_GENERATION_set(gv, PL_generation);
5634             }
5635             else if (curop->op_type == OP_PADSV ||
5636                 curop->op_type == OP_PADAV ||
5637                 curop->op_type == OP_PADHV ||
5638                 curop->op_type == OP_PADANY)
5639                 {
5640                     if (PAD_COMPNAME_GEN(curop->op_targ)
5641                         == (STRLEN)PL_generation)
5642                         return TRUE;
5643                     PAD_COMPNAME_GEN_set(curop->op_targ, PL_generation);
5644
5645                 }
5646             else if (curop->op_type == OP_RV2CV)
5647                 return TRUE;
5648             else if (curop->op_type == OP_RV2SV ||
5649                 curop->op_type == OP_RV2AV ||
5650                 curop->op_type == OP_RV2HV ||
5651                 curop->op_type == OP_RV2GV) {
5652                 if (cUNOPx(curop)->op_first->op_type != OP_GV)  /* funny deref? */
5653                     return TRUE;
5654             }
5655             else if (curop->op_type == OP_PUSHRE) {
5656                 GV *const gv =
5657 #ifdef USE_ITHREADS
5658                     ((PMOP*)curop)->op_pmreplrootu.op_pmtargetoff
5659                         ? MUTABLE_GV(PAD_SVl(((PMOP*)curop)->op_pmreplrootu.op_pmtargetoff))
5660                         : NULL;
5661 #else
5662                     ((PMOP*)curop)->op_pmreplrootu.op_pmtargetgv;
5663 #endif
5664                 if (gv) {
5665                     if (gv == PL_defgv
5666                         || (int)GvASSIGN_GENERATION(gv) == PL_generation)
5667                         return TRUE;
5668                     GvASSIGN_GENERATION_set(gv, PL_generation);
5669                 }
5670             }
5671             else
5672                 return TRUE;
5673         }
5674
5675         if (curop->op_flags & OPf_KIDS) {
5676             if (aassign_common_vars(curop))
5677                 return TRUE;
5678         }
5679     }
5680     return FALSE;
5681 }
5682
5683 /*
5684 =for apidoc Am|OP *|newASSIGNOP|I32 flags|OP *left|I32 optype|OP *right
5685
5686 Constructs, checks, and returns an assignment op.  I<left> and I<right>
5687 supply the parameters of the assignment; they are consumed by this
5688 function and become part of the constructed op tree.
5689
5690 If I<optype> is C<OP_ANDASSIGN>, C<OP_ORASSIGN>, or C<OP_DORASSIGN>, then
5691 a suitable conditional optree is constructed.  If I<optype> is the opcode
5692 of a binary operator, such as C<OP_BIT_OR>, then an op is constructed that
5693 performs the binary operation and assigns the result to the left argument.
5694 Either way, if I<optype> is non-zero then I<flags> has no effect.
5695
5696 If I<optype> is zero, then a plain scalar or list assignment is
5697 constructed.  Which type of assignment it is is automatically determined.
5698 I<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
5699 will be set automatically, and, shifted up eight bits, the eight bits
5700 of C<op_private>, except that the bit with value 1 or 2 is automatically
5701 set as required.
5702
5703 =cut
5704 */
5705
5706 OP *
5707 Perl_newASSIGNOP(pTHX_ I32 flags, OP *left, I32 optype, OP *right)
5708 {
5709     OP *o;
5710
5711     if (optype) {
5712         if (optype == OP_ANDASSIGN || optype == OP_ORASSIGN || optype == OP_DORASSIGN) {
5713             return newLOGOP(optype, 0,
5714                 op_lvalue(scalar(left), optype),
5715                 newUNOP(OP_SASSIGN, 0, scalar(right)));
5716         }
5717         else {
5718             return newBINOP(optype, OPf_STACKED,
5719                 op_lvalue(scalar(left), optype), scalar(right));
5720         }
5721     }
5722
5723     if (is_list_assignment(left)) {
5724         static const char no_list_state[] = "Initialization of state variables"
5725             " in list context currently forbidden";
5726         OP *curop;
5727         bool maybe_common_vars = TRUE;
5728
5729         if (left->op_type == OP_ASLICE || left->op_type == OP_HSLICE)
5730             left->op_private &= ~ OPpSLICEWARNING;
5731
5732         PL_modcount = 0;
5733         left = op_lvalue(left, OP_AASSIGN);
5734         curop = list(force_list(left, 1));
5735         o = newBINOP(OP_AASSIGN, flags, list(force_list(right, 1)), curop);
5736         o->op_private = (U8)(0 | (flags >> 8));
5737
5738         if (OP_TYPE_IS_OR_WAS(left, OP_LIST))
5739         {
5740             OP* lop = ((LISTOP*)left)->op_first;
5741             maybe_common_vars = FALSE;
5742             while (lop) {
5743                 if (lop->op_type == OP_PADSV ||
5744                     lop->op_type == OP_PADAV ||
5745                     lop->op_type == OP_PADHV ||
5746                     lop->op_type == OP_PADANY) {
5747                     if (!(lop->op_private & OPpLVAL_INTRO))
5748                         maybe_common_vars = TRUE;
5749
5750                     if (lop->op_private & OPpPAD_STATE) {
5751                         if (left->op_private & OPpLVAL_INTRO) {
5752                             /* Each variable in state($a, $b, $c) = ... */
5753                         }
5754                         else {
5755                             /* Each state variable in
5756                                (state $a, my $b, our $c, $d, undef) = ... */
5757                         }
5758                         yyerror(no_list_state);
5759                     } else {
5760                         /* Each my variable in
5761                            (state $a, my $b, our $c, $d, undef) = ... */
5762                     }
5763                 } else if (lop->op_type == OP_UNDEF ||
5764                            OP_TYPE_IS_OR_WAS(lop, OP_PUSHMARK)) {
5765                     /* undef may be interesting in
5766                        (state $a, undef, state $c) */
5767                 } else {
5768                     /* Other ops in the list. */
5769                     maybe_common_vars = TRUE;
5770                 }
5771                 lop = OP_SIBLING(lop);
5772             }
5773         }
5774         else if ((left->op_private & OPpLVAL_INTRO)
5775                 && (   left->op_type == OP_PADSV
5776                     || left->op_type == OP_PADAV
5777                     || left->op_type == OP_PADHV
5778                     || left->op_type == OP_PADANY))
5779         {
5780             if (left->op_type == OP_PADSV) maybe_common_vars = FALSE;
5781             if (left->op_private & OPpPAD_STATE) {
5782                 /* All single variable list context state assignments, hence
5783                    state ($a) = ...
5784                    (state $a) = ...
5785                    state @a = ...
5786                    state (@a) = ...
5787                    (state @a) = ...
5788                    state %a = ...
5789                    state (%a) = ...
5790                    (state %a) = ...
5791                 */
5792                 yyerror(no_list_state);
5793             }
5794         }
5795
5796         /* PL_generation sorcery:
5797          * an assignment like ($a,$b) = ($c,$d) is easier than
5798          * ($a,$b) = ($c,$a), since there is no need for temporary vars.
5799          * To detect whether there are common vars, the global var
5800          * PL_generation is incremented for each assign op we compile.
5801          * Then, while compiling the assign op, we run through all the
5802          * variables on both sides of the assignment, setting a spare slot
5803          * in each of them to PL_generation. If any of them already have
5804          * that value, we know we've got commonality.  We could use a
5805          * single bit marker, but then we'd have to make 2 passes, first
5806          * to clear the flag, then to test and set it.  To find somewhere
5807          * to store these values, evil chicanery is done with SvUVX().
5808          */
5809
5810         if (maybe_common_vars) {
5811             PL_generation++;
5812             if (aassign_common_vars(o))
5813                 o->op_private |= OPpASSIGN_COMMON;
5814             LINKLIST(o);
5815         }
5816
5817         if (right && right->op_type == OP_SPLIT) {
5818             OP* tmpop = ((LISTOP*)right)->op_first;
5819             if (tmpop && (tmpop->op_type == OP_PUSHRE)) {
5820                 PMOP * const pm = (PMOP*)tmpop;
5821                 if (left->op_type == OP_RV2AV &&
5822                     !(left->op_private & OPpLVAL_INTRO) &&
5823                     !(o->op_private & OPpASSIGN_COMMON) )
5824                 {
5825                     tmpop = ((UNOP*)left)->op_first;
5826                     if (tmpop->op_type == OP_GV
5827 #ifdef USE_ITHREADS
5828                         && !pm->op_pmreplrootu.op_pmtargetoff
5829 #else
5830                         && !pm->op_pmreplrootu.op_pmtargetgv
5831 #endif
5832                         ) {
5833 #ifdef USE_ITHREADS
5834                         pm->op_pmreplrootu.op_pmtargetoff
5835                             = cPADOPx(tmpop)->op_padix;
5836                         cPADOPx(tmpop)->op_padix = 0;   /* steal it */
5837 #else
5838                         pm->op_pmreplrootu.op_pmtargetgv
5839                             = MUTABLE_GV(cSVOPx(tmpop)->op_sv);
5840                         cSVOPx(tmpop)->op_sv = NULL;    /* steal it */
5841 #endif
5842                         tmpop = cUNOPo->op_first;       /* to list (nulled) */
5843                         tmpop = ((UNOP*)tmpop)->op_first; /* to pushmark */
5844                         /* detach rest of siblings from o subtree,
5845                          * and free subtree */
5846                         op_sibling_splice(cUNOPo->op_first, tmpop, -1, NULL);
5847                         right->op_next = tmpop->op_next;  /* fix starting loc */
5848                         op_free(o);                     /* blow off assign */
5849                         right->op_flags &= ~OPf_WANT;
5850                                 /* "I don't know and I don't care." */
5851                         return right;
5852                     }
5853                 }
5854                 else {
5855                    if (PL_modcount < RETURN_UNLIMITED_NUMBER &&
5856                       ((LISTOP*)right)->op_last->op_type == OP_CONST)
5857                     {
5858                         SV ** const svp =
5859                             &((SVOP*)((LISTOP*)right)->op_last)->op_sv;
5860                         SV * const sv = *svp;
5861                         if (SvIOK(sv) && SvIVX(sv) == 0)
5862                         {
5863                           if (right->op_private & OPpSPLIT_IMPLIM) {
5864                             /* our own SV, created in ck_split */
5865                             SvREADONLY_off(sv);
5866                             sv_setiv(sv, PL_modcount+1);
5867                           }
5868                           else {
5869                             /* SV may belong to someone else */
5870                             SvREFCNT_dec(sv);
5871                             *svp = newSViv(PL_modcount+1);
5872                           }
5873                         }
5874                     }
5875                 }
5876             }
5877         }
5878         return o;
5879     }
5880     if (!right)
5881         right = newOP(OP_UNDEF, 0);
5882     if (right->op_type == OP_READLINE) {
5883         right->op_flags |= OPf_STACKED;
5884         return newBINOP(OP_NULL, flags, op_lvalue(scalar(left), OP_SASSIGN),
5885                 scalar(right));
5886     }
5887     else {
5888         o = newBINOP(OP_SASSIGN, flags,
5889             scalar(right), op_lvalue(scalar(left), OP_SASSIGN) );
5890     }
5891     return o;
5892 }
5893
5894 /*
5895 =for apidoc Am|OP *|newSTATEOP|I32 flags|char *label|OP *o
5896
5897 Constructs a state op (COP).  The state op is normally a C<nextstate> op,
5898 but will be a C<dbstate> op if debugging is enabled for currently-compiled
5899 code.  The state op is populated from C<PL_curcop> (or C<PL_compiling>).
5900 If I<label> is non-null, it supplies the name of a label to attach to
5901 the state op; this function takes ownership of the memory pointed at by
5902 I<label>, and will free it.  I<flags> gives the eight bits of C<op_flags>
5903 for the state op.
5904
5905 If I<o> is null, the state op is returned.  Otherwise the state op is
5906 combined with I<o> into a C<lineseq> list op, which is returned.  I<o>
5907 is consumed by this function and becomes part of the returned op tree.
5908
5909 =cut
5910 */
5911
5912 OP *
5913 Perl_newSTATEOP(pTHX_ I32 flags, char *label, OP *o)
5914 {
5915     dVAR;
5916     const U32 seq = intro_my();
5917     const U32 utf8 = flags & SVf_UTF8;
5918     COP *cop;
5919
5920     flags &= ~SVf_UTF8;
5921
5922     NewOp(1101, cop, 1, COP);
5923     if (PERLDB_LINE && CopLINE(PL_curcop) && PL_curstash != PL_debstash) {
5924         cop->op_type = OP_DBSTATE;
5925         cop->op_ppaddr = PL_ppaddr[ OP_DBSTATE ];
5926     }
5927     else {
5928         cop->op_type = OP_NEXTSTATE;
5929         cop->op_ppaddr = PL_ppaddr[ OP_NEXTSTATE ];
5930     }
5931     cop->op_flags = (U8)flags;
5932     CopHINTS_set(cop, PL_hints);
5933 #ifdef NATIVE_HINTS
5934     cop->op_private |= NATIVE_HINTS;
5935 #endif
5936 #ifdef VMS
5937     if (VMSISH_HUSHED) cop->op_private |= OPpHUSH_VMSISH;
5938 #endif
5939     cop->op_next = (OP*)cop;
5940
5941     cop->cop_seq = seq;
5942     cop->cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
5943     CopHINTHASH_set(cop, cophh_copy(CopHINTHASH_get(PL_curcop)));
5944     if (label) {
5945         Perl_cop_store_label(aTHX_ cop, label, strlen(label), utf8);
5946
5947         PL_hints |= HINT_BLOCK_SCOPE;
5948         /* It seems that we need to defer freeing this pointer, as other parts
5949            of the grammar end up wanting to copy it after this op has been
5950            created. */
5951         SAVEFREEPV(label);
5952     }
5953
5954     if (PL_parser->preambling != NOLINE) {
5955         CopLINE_set(cop, PL_parser->preambling);
5956         PL_parser->copline = NOLINE;
5957     }
5958     else if (PL_parser->copline == NOLINE)
5959         CopLINE_set(cop, CopLINE(PL_curcop));
5960     else {
5961         CopLINE_set(cop, PL_parser->copline);
5962         PL_parser->copline = NOLINE;
5963     }
5964 #ifdef USE_ITHREADS
5965     CopFILE_set(cop, CopFILE(PL_curcop));       /* XXX share in a pvtable? */
5966 #else
5967     CopFILEGV_set(cop, CopFILEGV(PL_curcop));
5968 #endif
5969     CopSTASH_set(cop, PL_curstash);
5970
5971     if (cop->op_type == OP_DBSTATE) {
5972         /* this line can have a breakpoint - store the cop in IV */
5973         AV *av = CopFILEAVx(PL_curcop);
5974         if (av) {
5975             SV * const * const svp = av_fetch(av, CopLINE(cop), FALSE);
5976             if (svp && *svp != &PL_sv_undef ) {
5977                 (void)SvIOK_on(*svp);
5978                 SvIV_set(*svp, PTR2IV(cop));
5979             }
5980         }
5981     }
5982
5983     if (flags & OPf_SPECIAL)
5984         op_null((OP*)cop);
5985     return op_prepend_elem(OP_LINESEQ, (OP*)cop, o);
5986 }
5987
5988 /*
5989 =for apidoc Am|OP *|newLOGOP|I32 type|I32 flags|OP *first|OP *other
5990
5991 Constructs, checks, and returns a logical (flow control) op.  I<type>
5992 is the opcode.  I<flags> gives the eight bits of C<op_flags>, except
5993 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
5994 the eight bits of C<op_private>, except that the bit with value 1 is
5995 automatically set.  I<first> supplies the expression controlling the
5996 flow, and I<other> supplies the side (alternate) chain of ops; they are
5997 consumed by this function and become part of the constructed op tree.
5998
5999 =cut
6000 */
6001
6002 OP *
6003 Perl_newLOGOP(pTHX_ I32 type, I32 flags, OP *first, OP *other)
6004 {
6005     PERL_ARGS_ASSERT_NEWLOGOP;
6006
6007     return new_logop(type, flags, &first, &other);
6008 }
6009
6010 STATIC OP *
6011 S_search_const(pTHX_ OP *o)
6012 {
6013     PERL_ARGS_ASSERT_SEARCH_CONST;
6014
6015     switch (o->op_type) {
6016         case OP_CONST:
6017             return o;
6018         case OP_NULL:
6019             if (o->op_flags & OPf_KIDS)
6020                 return search_const(cUNOPo->op_first);
6021             break;
6022         case OP_LEAVE:
6023         case OP_SCOPE:
6024         case OP_LINESEQ:
6025         {
6026             OP *kid;
6027             if (!(o->op_flags & OPf_KIDS))
6028                 return NULL;
6029             kid = cLISTOPo->op_first;
6030             do {
6031                 switch (kid->op_type) {
6032                     case OP_ENTER:
6033                     case OP_NULL:
6034                     case OP_NEXTSTATE:
6035                         kid = OP_SIBLING(kid);
6036                         break;
6037                     default:
6038                         if (kid != cLISTOPo->op_last)
6039                             return NULL;
6040                         goto last;
6041                 }
6042             } while (kid);
6043             if (!kid)
6044                 kid = cLISTOPo->op_last;
6045 last:
6046             return search_const(kid);
6047         }
6048     }
6049
6050     return NULL;
6051 }
6052
6053 STATIC OP *
6054 S_new_logop(pTHX_ I32 type, I32 flags, OP** firstp, OP** otherp)
6055 {
6056     dVAR;
6057     LOGOP *logop;
6058     OP *o;
6059     OP *first;
6060     OP *other;
6061     OP *cstop = NULL;
6062     int prepend_not = 0;
6063
6064     PERL_ARGS_ASSERT_NEW_LOGOP;
6065
6066     first = *firstp;
6067     other = *otherp;
6068
6069     /* [perl #59802]: Warn about things like "return $a or $b", which
6070        is parsed as "(return $a) or $b" rather than "return ($a or
6071        $b)".  NB: This also applies to xor, which is why we do it
6072        here.
6073      */
6074     switch (first->op_type) {
6075     case OP_NEXT:
6076     case OP_LAST:
6077     case OP_REDO:
6078         /* XXX: Perhaps we should emit a stronger warning for these.
6079            Even with the high-precedence operator they don't seem to do
6080            anything sensible.
6081
6082            But until we do, fall through here.
6083          */
6084     case OP_RETURN:
6085     case OP_EXIT:
6086     case OP_DIE:
6087     case OP_GOTO:
6088         /* XXX: Currently we allow people to "shoot themselves in the
6089            foot" by explicitly writing "(return $a) or $b".
6090
6091            Warn unless we are looking at the result from folding or if
6092            the programmer explicitly grouped the operators like this.
6093            The former can occur with e.g.
6094
6095                 use constant FEATURE => ( $] >= ... );
6096                 sub { not FEATURE and return or do_stuff(); }
6097          */
6098         if (!first->op_folded && !(first->op_flags & OPf_PARENS))
6099             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
6100                            "Possible precedence issue with control flow operator");
6101         /* XXX: Should we optimze this to "return $a;" (i.e. remove
6102            the "or $b" part)?
6103         */
6104         break;
6105     }
6106
6107     if (type == OP_XOR)         /* Not short circuit, but here by precedence. */
6108         return newBINOP(type, flags, scalar(first), scalar(other));
6109
6110     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOGOP);
6111
6112     scalarboolean(first);
6113     /* optimize AND and OR ops that have NOTs as children */
6114     if (first->op_type == OP_NOT
6115         && (first->op_flags & OPf_KIDS)
6116         && ((first->op_flags & OPf_SPECIAL) /* unless ($x) { } */
6117             || (other->op_type == OP_NOT))  /* if (!$x && !$y) { } */
6118         ) {
6119         if (type == OP_AND || type == OP_OR) {
6120             if (type == OP_AND)
6121                 type = OP_OR;
6122             else
6123                 type = OP_AND;
6124             op_null(first);
6125             if (other->op_type == OP_NOT) { /* !a AND|OR !b => !(a OR|AND b) */
6126                 op_null(other);
6127                 prepend_not = 1; /* prepend a NOT op later */
6128             }
6129         }
6130     }
6131     /* search for a constant op that could let us fold the test */
6132     if ((cstop = search_const(first))) {
6133         if (cstop->op_private & OPpCONST_STRICT)
6134             no_bareword_allowed(cstop);
6135         else if ((cstop->op_private & OPpCONST_BARE))
6136                 Perl_ck_warner(aTHX_ packWARN(WARN_BAREWORD), "Bareword found in conditional");
6137         if ((type == OP_AND &&  SvTRUE(((SVOP*)cstop)->op_sv)) ||
6138             (type == OP_OR  && !SvTRUE(((SVOP*)cstop)->op_sv)) ||
6139             (type == OP_DOR && !SvOK(((SVOP*)cstop)->op_sv))) {
6140             *firstp = NULL;
6141             if (other->op_type == OP_CONST)
6142                 other->op_private |= OPpCONST_SHORTCIRCUIT;
6143             op_free(first);
6144             if (other->op_type == OP_LEAVE)
6145                 other = newUNOP(OP_NULL, OPf_SPECIAL, other);
6146             else if (other->op_type == OP_MATCH
6147                   || other->op_type == OP_SUBST
6148                   || other->op_type == OP_TRANSR
6149                   || other->op_type == OP_TRANS)
6150                 /* Mark the op as being unbindable with =~ */
6151                 other->op_flags |= OPf_SPECIAL;
6152
6153             other->op_folded = 1;
6154             return other;
6155         }
6156         else {
6157             /* check for C<my $x if 0>, or C<my($x,$y) if 0> */
6158             const OP *o2 = other;
6159             if ( ! (o2->op_type == OP_LIST
6160                     && (( o2 = cUNOPx(o2)->op_first))
6161                     && o2->op_type == OP_PUSHMARK
6162                     && (( o2 = OP_SIBLING(o2))) )
6163             )
6164                 o2 = other;
6165             if ((o2->op_type == OP_PADSV || o2->op_type == OP_PADAV
6166                         || o2->op_type == OP_PADHV)
6167                 && o2->op_private & OPpLVAL_INTRO
6168                 && !(o2->op_private & OPpPAD_STATE))
6169             {
6170                 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED),
6171                                  "Deprecated use of my() in false conditional");
6172             }
6173
6174             *otherp = NULL;
6175             if (cstop->op_type == OP_CONST)
6176                 cstop->op_private |= OPpCONST_SHORTCIRCUIT;
6177                 op_free(other);
6178             return first;
6179         }
6180     }
6181     else if ((first->op_flags & OPf_KIDS) && type != OP_DOR
6182         && ckWARN(WARN_MISC)) /* [#24076] Don't warn for <FH> err FOO. */
6183     {
6184         const OP * const k1 = ((UNOP*)first)->op_first;
6185         const OP * const k2 = OP_SIBLING(k1);
6186         OPCODE warnop = 0;
6187         switch (first->op_type)
6188         {
6189         case OP_NULL:
6190             if (k2 && k2->op_type == OP_READLINE
6191                   && (k2->op_flags & OPf_STACKED)
6192                   && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
6193             {
6194                 warnop = k2->op_type;
6195             }
6196             break;
6197
6198         case OP_SASSIGN:
6199             if (k1->op_type == OP_READDIR
6200                   || k1->op_type == OP_GLOB
6201                   || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
6202                  || k1->op_type == OP_EACH
6203                  || k1->op_type == OP_AEACH)
6204             {
6205                 warnop = ((k1->op_type == OP_NULL)
6206                           ? (OPCODE)k1->op_targ : k1->op_type);
6207             }
6208             break;
6209         }
6210         if (warnop) {
6211             const line_t oldline = CopLINE(PL_curcop);
6212             /* This ensures that warnings are reported at the first line
6213                of the construction, not the last.  */
6214             CopLINE_set(PL_curcop, PL_parser->copline);
6215             Perl_warner(aTHX_ packWARN(WARN_MISC),
6216                  "Value of %s%s can be \"0\"; test with defined()",
6217                  PL_op_desc[warnop],
6218                  ((warnop == OP_READLINE || warnop == OP_GLOB)
6219                   ? " construct" : "() operator"));
6220             CopLINE_set(PL_curcop, oldline);
6221         }
6222     }
6223
6224     if (!other)
6225         return first;
6226
6227     if (type == OP_ANDASSIGN || type == OP_ORASSIGN || type == OP_DORASSIGN)
6228         other->op_private |= OPpASSIGN_BACKWARDS;  /* other is an OP_SASSIGN */
6229
6230     logop = S_alloc_LOGOP(aTHX_ type, first, LINKLIST(other));
6231     logop->op_ppaddr = PL_ppaddr[type];
6232     logop->op_flags |= (U8)flags;
6233     logop->op_private = (U8)(1 | (flags >> 8));
6234
6235     /* establish postfix order */
6236     logop->op_next = LINKLIST(first);
6237     first->op_next = (OP*)logop;
6238     assert(!OP_HAS_SIBLING(first));
6239     op_sibling_splice((OP*)logop, first, 0, other);
6240
6241     CHECKOP(type,logop);
6242
6243     o = newUNOP(prepend_not ? OP_NOT : OP_NULL, 0, (OP*)logop);
6244     other->op_next = o;
6245
6246     return o;
6247 }
6248
6249 /*
6250 =for apidoc Am|OP *|newCONDOP|I32 flags|OP *first|OP *trueop|OP *falseop
6251
6252 Constructs, checks, and returns a conditional-expression (C<cond_expr>)
6253 op.  I<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
6254 will be set automatically, and, shifted up eight bits, the eight bits of
6255 C<op_private>, except that the bit with value 1 is automatically set.
6256 I<first> supplies the expression selecting between the two branches,
6257 and I<trueop> and I<falseop> supply the branches; they are consumed by
6258 this function and become part of the constructed op tree.
6259
6260 =cut
6261 */
6262
6263 OP *
6264 Perl_newCONDOP(pTHX_ I32 flags, OP *first, OP *trueop, OP *falseop)
6265 {
6266     dVAR;
6267     LOGOP *logop;
6268     OP *start;
6269     OP *o;
6270     OP *cstop;
6271
6272     PERL_ARGS_ASSERT_NEWCONDOP;
6273
6274     if (!falseop)
6275         return newLOGOP(OP_AND, 0, first, trueop);
6276     if (!trueop)
6277         return newLOGOP(OP_OR, 0, first, falseop);
6278
6279     scalarboolean(first);
6280     if ((cstop = search_const(first))) {
6281         /* Left or right arm of the conditional?  */
6282         const bool left = SvTRUE(((SVOP*)cstop)->op_sv);
6283         OP *live = left ? trueop : falseop;
6284         OP *const dead = left ? falseop : trueop;
6285         if (cstop->op_private & OPpCONST_BARE &&
6286             cstop->op_private & OPpCONST_STRICT) {
6287             no_bareword_allowed(cstop);
6288         }
6289         op_free(first);
6290         op_free(dead);
6291         if (live->op_type == OP_LEAVE)
6292             live = newUNOP(OP_NULL, OPf_SPECIAL, live);
6293         else if (live->op_type == OP_MATCH || live->op_type == OP_SUBST
6294               || live->op_type == OP_TRANS || live->op_type == OP_TRANSR)
6295             /* Mark the op as being unbindable with =~ */
6296             live->op_flags |= OPf_SPECIAL;
6297         live->op_folded = 1;
6298         return live;
6299     }
6300     logop = S_alloc_LOGOP(aTHX_ OP_COND_EXPR, first, LINKLIST(trueop));
6301     logop->op_ppaddr = PL_ppaddr[OP_COND_EXPR];
6302     logop->op_flags |= (U8)flags;
6303     logop->op_private = (U8)(1 | (flags >> 8));
6304     logop->op_next = LINKLIST(falseop);
6305
6306     CHECKOP(OP_COND_EXPR, /* that's logop->op_type */
6307             logop);
6308
6309     /* establish postfix order */
6310     start = LINKLIST(first);
6311     first->op_next = (OP*)logop;
6312
6313     /* make first, trueop, falseop siblings */
6314     op_sibling_splice((OP*)logop, first,  0, trueop);
6315     op_sibling_splice((OP*)logop, trueop, 0, falseop);
6316
6317     o = newUNOP(OP_NULL, 0, (OP*)logop);
6318
6319     trueop->op_next = falseop->op_next = o;
6320
6321     o->op_next = start;
6322     return o;
6323 }
6324
6325 /*
6326 =for apidoc Am|OP *|newRANGE|I32 flags|OP *left|OP *right
6327
6328 Constructs and returns a C<range> op, with subordinate C<flip> and
6329 C<flop> ops.  I<flags> gives the eight bits of C<op_flags> for the
6330 C<flip> op and, shifted up eight bits, the eight bits of C<op_private>
6331 for both the C<flip> and C<range> ops, except that the bit with value
6332 1 is automatically set.  I<left> and I<right> supply the expressions
6333 controlling the endpoints of the range; they are consumed by this function
6334 and become part of the constructed op tree.
6335
6336 =cut
6337 */
6338
6339 OP *
6340 Perl_newRANGE(pTHX_ I32 flags, OP *left, OP *right)
6341 {
6342     dVAR;
6343     LOGOP *range;
6344     OP *flip;
6345     OP *flop;
6346     OP *leftstart;
6347     OP *o;
6348
6349     PERL_ARGS_ASSERT_NEWRANGE;
6350
6351     range = S_alloc_LOGOP(aTHX_ OP_RANGE, left, LINKLIST(right));
6352     range->op_ppaddr = PL_ppaddr[OP_RANGE];
6353     range->op_flags = OPf_KIDS;
6354     leftstart = LINKLIST(left);
6355     range->op_private = (U8)(1 | (flags >> 8));
6356
6357     /* make left and right siblings */
6358     op_sibling_splice((OP*)range, left, 0, right);
6359
6360     range->op_next = (OP*)range;
6361     flip = newUNOP(OP_FLIP, flags, (OP*)range);
6362     flop = newUNOP(OP_FLOP, 0, flip);
6363     o = newUNOP(OP_NULL, 0, flop);
6364     LINKLIST(flop);
6365     range->op_next = leftstart;
6366
6367     left->op_next = flip;
6368     right->op_next = flop;
6369
6370     range->op_targ = pad_alloc(OP_RANGE, SVs_PADMY);
6371     sv_upgrade(PAD_SV(range->op_targ), SVt_PVNV);
6372     flip->op_targ = pad_alloc(OP_RANGE, SVs_PADMY);
6373     sv_upgrade(PAD_SV(flip->op_targ), SVt_PVNV);
6374
6375     flip->op_private =  left->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
6376     flop->op_private = right->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
6377
6378     /* check barewords before they might be optimized aways */
6379     if (flip->op_private && cSVOPx(left)->op_private & OPpCONST_STRICT)
6380         no_bareword_allowed(left);
6381     if (flop->op_private && cSVOPx(right)->op_private & OPpCONST_STRICT)
6382         no_bareword_allowed(right);
6383
6384     flip->op_next = o;
6385     if (!flip->op_private || !flop->op_private)
6386         LINKLIST(o);            /* blow off optimizer unless constant */
6387
6388     return o;
6389 }
6390
6391 /*
6392 =for apidoc Am|OP *|newLOOPOP|I32 flags|I32 debuggable|OP *expr|OP *block
6393
6394 Constructs, checks, and returns an op tree expressing a loop.  This is
6395 only a loop in the control flow through the op tree; it does not have
6396 the heavyweight loop structure that allows exiting the loop by C<last>
6397 and suchlike.  I<flags> gives the eight bits of C<op_flags> for the
6398 top-level op, except that some bits will be set automatically as required.
6399 I<expr> supplies the expression controlling loop iteration, and I<block>
6400 supplies the body of the loop; they are consumed by this function and
6401 become part of the constructed op tree.  I<debuggable> is currently
6402 unused and should always be 1.
6403
6404 =cut
6405 */
6406
6407 OP *
6408 Perl_newLOOPOP(pTHX_ I32 flags, I32 debuggable, OP *expr, OP *block)
6409 {
6410     OP* listop;
6411     OP* o;
6412     const bool once = block && block->op_flags & OPf_SPECIAL &&
6413                       block->op_type == OP_NULL;
6414
6415     PERL_UNUSED_ARG(debuggable);
6416
6417     if (expr) {
6418         if (once && (
6419               (expr->op_type == OP_CONST && !SvTRUE(((SVOP*)expr)->op_sv))
6420            || (  expr->op_type == OP_NOT
6421               && cUNOPx(expr)->op_first->op_type == OP_CONST
6422               && SvTRUE(cSVOPx_sv(cUNOPx(expr)->op_first))
6423               )
6424            ))
6425             /* Return the block now, so that S_new_logop does not try to
6426                fold it away. */
6427             return block;       /* do {} while 0 does once */
6428         if (expr->op_type == OP_READLINE
6429             || expr->op_type == OP_READDIR
6430             || expr->op_type == OP_GLOB
6431             || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
6432             || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
6433             expr = newUNOP(OP_DEFINED, 0,
6434                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
6435         } else if (expr->op_flags & OPf_KIDS) {
6436             const OP * const k1 = ((UNOP*)expr)->op_first;
6437             const OP * const k2 = k1 ? OP_SIBLING(k1) : NULL;
6438             switch (expr->op_type) {
6439               case OP_NULL:
6440                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
6441                       && (k2->op_flags & OPf_STACKED)
6442                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
6443                     expr = newUNOP(OP_DEFINED, 0, expr);
6444                 break;
6445
6446               case OP_SASSIGN:
6447                 if (k1 && (k1->op_type == OP_READDIR
6448                       || k1->op_type == OP_GLOB
6449                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
6450                      || k1->op_type == OP_EACH
6451                      || k1->op_type == OP_AEACH))
6452                     expr = newUNOP(OP_DEFINED, 0, expr);
6453                 break;
6454             }
6455         }
6456     }
6457
6458     /* if block is null, the next op_append_elem() would put UNSTACK, a scalar
6459      * op, in listop. This is wrong. [perl #27024] */
6460     if (!block)
6461         block = newOP(OP_NULL, 0);
6462     listop = op_append_elem(OP_LINESEQ, block, newOP(OP_UNSTACK, 0));
6463     o = new_logop(OP_AND, 0, &expr, &listop);
6464
6465     if (once) {
6466         ASSUME(listop);
6467     }
6468
6469     if (listop)
6470         ((LISTOP*)listop)->op_last->op_next = LINKLIST(o);
6471
6472     if (once && o != listop)
6473     {
6474         assert(cUNOPo->op_first->op_type == OP_AND
6475             || cUNOPo->op_first->op_type == OP_OR);
6476         o->op_next = ((LOGOP*)cUNOPo->op_first)->op_other;
6477     }
6478
6479     if (o == listop)
6480         o = newUNOP(OP_NULL, 0, o);     /* or do {} while 1 loses outer block */
6481
6482     o->op_flags |= flags;
6483     o = op_scope(o);
6484     o->op_flags |= OPf_SPECIAL; /* suppress POPBLOCK curpm restoration*/
6485     return o;
6486 }
6487
6488 /*
6489 =for apidoc Am|OP *|newWHILEOP|I32 flags|I32 debuggable|LOOP *loop|OP *expr|OP *block|OP *cont|I32 has_my
6490
6491 Constructs, checks, and returns an op tree expressing a C<while> loop.
6492 This is a heavyweight loop, with structure that allows exiting the loop
6493 by C<last> and suchlike.
6494
6495 I<loop> is an optional preconstructed C<enterloop> op to use in the
6496 loop; if it is null then a suitable op will be constructed automatically.
6497 I<expr> supplies the loop's controlling expression.  I<block> supplies the
6498 main body of the loop, and I<cont> optionally supplies a C<continue> block
6499 that operates as a second half of the body.  All of these optree inputs
6500 are consumed by this function and become part of the constructed op tree.
6501
6502 I<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
6503 op and, shifted up eight bits, the eight bits of C<op_private> for
6504 the C<leaveloop> op, except that (in both cases) some bits will be set
6505 automatically.  I<debuggable> is currently unused and should always be 1.
6506 I<has_my> can be supplied as true to force the
6507 loop body to be enclosed in its own scope.
6508
6509 =cut
6510 */
6511
6512 OP *
6513 Perl_newWHILEOP(pTHX_ I32 flags, I32 debuggable, LOOP *loop,
6514         OP *expr, OP *block, OP *cont, I32 has_my)
6515 {
6516     dVAR;
6517     OP *redo;
6518     OP *next = NULL;
6519     OP *listop;
6520     OP *o;
6521     U8 loopflags = 0;
6522
6523     PERL_UNUSED_ARG(debuggable);
6524
6525     if (expr) {
6526         if (expr->op_type == OP_READLINE
6527          || expr->op_type == OP_READDIR
6528          || expr->op_type == OP_GLOB
6529          || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
6530                      || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
6531             expr = newUNOP(OP_DEFINED, 0,
6532                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
6533         } else if (expr->op_flags & OPf_KIDS) {
6534             const OP * const k1 = ((UNOP*)expr)->op_first;
6535             const OP * const k2 = (k1) ? OP_SIBLING(k1) : NULL;
6536             switch (expr->op_type) {
6537               case OP_NULL:
6538                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
6539                       && (k2->op_flags & OPf_STACKED)
6540                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
6541                     expr = newUNOP(OP_DEFINED, 0, expr);
6542                 break;
6543
6544               case OP_SASSIGN:
6545                 if (k1 && (k1->op_type == OP_READDIR
6546                       || k1->op_type == OP_GLOB
6547                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
6548                      || k1->op_type == OP_EACH
6549                      || k1->op_type == OP_AEACH))
6550                     expr = newUNOP(OP_DEFINED, 0, expr);
6551                 break;
6552             }
6553         }
6554     }
6555
6556     if (!block)
6557         block = newOP(OP_NULL, 0);
6558     else if (cont || has_my) {
6559         block = op_scope(block);
6560     }
6561
6562     if (cont) {
6563         next = LINKLIST(cont);
6564     }
6565     if (expr) {
6566         OP * const unstack = newOP(OP_UNSTACK, 0);
6567         if (!next)
6568             next = unstack;
6569         cont = op_append_elem(OP_LINESEQ, cont, unstack);
6570     }
6571
6572     assert(block);
6573     listop = op_append_list(OP_LINESEQ, block, cont);
6574     assert(listop);
6575     redo = LINKLIST(listop);
6576
6577     if (expr) {
6578         scalar(listop);
6579         o = new_logop(OP_AND, 0, &expr, &listop);
6580         if (o == expr && o->op_type == OP_CONST && !SvTRUE(cSVOPo->op_sv)) {
6581             op_free((OP*)loop);
6582             return expr;                /* listop already freed by new_logop */
6583         }
6584         if (listop)
6585             ((LISTOP*)listop)->op_last->op_next =
6586                 (o == listop ? redo : LINKLIST(o));
6587     }
6588     else
6589         o = listop;
6590
6591     if (!loop) {
6592         NewOp(1101,loop,1,LOOP);
6593         loop->op_type = OP_ENTERLOOP;
6594         loop->op_ppaddr = PL_ppaddr[OP_ENTERLOOP];
6595         loop->op_private = 0;
6596         loop->op_next = (OP*)loop;
6597     }
6598
6599     o = newBINOP(OP_LEAVELOOP, 0, (OP*)loop, o);
6600
6601     loop->op_redoop = redo;
6602     loop->op_lastop = o;
6603     o->op_private |= loopflags;
6604
6605     if (next)
6606         loop->op_nextop = next;
6607     else
6608         loop->op_nextop = o;
6609
6610     o->op_flags |= flags;
6611     o->op_private |= (flags >> 8);
6612     return o;
6613 }
6614
6615 /*
6616 =for apidoc Am|OP *|newFOROP|I32 flags|OP *sv|OP *expr|OP *block|OP *cont
6617
6618 Constructs, checks, and returns an op tree expressing a C<foreach>
6619 loop (iteration through a list of values).  This is a heavyweight loop,
6620 with structure that allows exiting the loop by C<last> and suchlike.
6621
6622 I<sv> optionally supplies the variable that will be aliased to each
6623 item in turn; if null, it defaults to C<$_> (either lexical or global).
6624 I<expr> supplies the list of values to iterate over.  I<block> supplies
6625 the main body of the loop, and I<cont> optionally supplies a C<continue>
6626 block that operates as a second half of the body.  All of these optree
6627 inputs are consumed by this function and become part of the constructed
6628 op tree.
6629
6630 I<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
6631 op and, shifted up eight bits, the eight bits of C<op_private> for
6632 the C<leaveloop> op, except that (in both cases) some bits will be set
6633 automatically.
6634
6635 =cut
6636 */
6637
6638 OP *
6639 Perl_newFOROP(pTHX_ I32 flags, OP *sv, OP *expr, OP *block, OP *cont)
6640 {
6641     dVAR;
6642     LOOP *loop;
6643     OP *wop;
6644     PADOFFSET padoff = 0;
6645     I32 iterflags = 0;
6646     I32 iterpflags = 0;
6647
6648     PERL_ARGS_ASSERT_NEWFOROP;
6649
6650     if (sv) {
6651         if (sv->op_type == OP_RV2SV) {  /* symbol table variable */
6652             iterpflags = sv->op_private & OPpOUR_INTRO; /* for our $x () */
6653             sv->op_type = OP_RV2GV;
6654             sv->op_ppaddr = PL_ppaddr[OP_RV2GV];
6655
6656             /* The op_type check is needed to prevent a possible segfault
6657              * if the loop variable is undeclared and 'strict vars' is in
6658              * effect. This is illegal but is nonetheless parsed, so we
6659              * may reach this point with an OP_CONST where we're expecting
6660              * an OP_GV.
6661              */
6662             if (cUNOPx(sv)->op_first->op_type == OP_GV
6663              && cGVOPx_gv(cUNOPx(sv)->op_first) == PL_defgv)
6664                 iterpflags |= OPpITER_DEF;
6665         }
6666         else if (sv->op_type == OP_PADSV) { /* private variable */
6667             iterpflags = sv->op_private & OPpLVAL_INTRO; /* for my $x () */
6668             padoff = sv->op_targ;
6669             sv->op_targ = 0;
6670             op_free(sv);
6671             sv = NULL;
6672         }
6673         else
6674             Perl_croak(aTHX_ "Can't use %s for loop variable", PL_op_desc[sv->op_type]);
6675         if (padoff) {
6676             SV *const namesv = PAD_COMPNAME_SV(padoff);
6677             STRLEN len;
6678             const char *const name = SvPV_const(namesv, len);
6679
6680             if (len == 2 && name[0] == '$' && name[1] == '_')
6681                 iterpflags |= OPpITER_DEF;
6682         }
6683     }
6684     else {
6685         const PADOFFSET offset = pad_findmy_pvs("$_", 0);
6686         if (offset == NOT_IN_PAD || PAD_COMPNAME_FLAGS_isOUR(offset)) {
6687             sv = newGVOP(OP_GV, 0, PL_defgv);
6688         }
6689         else {
6690             padoff = offset;
6691         }
6692         iterpflags |= OPpITER_DEF;
6693     }
6694
6695     if (expr->op_type == OP_RV2AV || expr->op_type == OP_PADAV) {
6696         expr = op_lvalue(force_list(scalar(ref(expr, OP_ITER)), 1), OP_GREPSTART);
6697         iterflags |= OPf_STACKED;
6698     }
6699     else if (expr->op_type == OP_NULL &&
6700              (expr->op_flags & OPf_KIDS) &&
6701              ((BINOP*)expr)->op_first->op_type == OP_FLOP)
6702     {
6703         /* Basically turn for($x..$y) into the same as for($x,$y), but we
6704          * set the STACKED flag to indicate that these values are to be
6705          * treated as min/max values by 'pp_enteriter'.
6706          */
6707         const UNOP* const flip = (UNOP*)((UNOP*)((BINOP*)expr)->op_first)->op_first;
6708         LOGOP* const range = (LOGOP*) flip->op_first;
6709         OP* const left  = range->op_first;
6710         OP* const right = OP_SIBLING(left);
6711         LISTOP* listop;
6712
6713         range->op_flags &= ~OPf_KIDS;
6714         /* detach range's children */
6715         op_sibling_splice((OP*)range, NULL, -1, NULL);
6716
6717         listop = (LISTOP*)newLISTOP(OP_LIST, 0, left, right);
6718         listop->op_first->op_next = range->op_next;
6719         left->op_next = range->op_other;
6720         right->op_next = (OP*)listop;
6721         listop->op_next = listop->op_first;
6722
6723         op_free(expr);
6724         expr = (OP*)(listop);
6725         op_null(expr);
6726         iterflags |= OPf_STACKED;
6727     }
6728     else {
6729         expr = op_lvalue(force_list(expr, 1), OP_GREPSTART);
6730     }
6731
6732     loop = (LOOP*)list(convert(OP_ENTERITER, iterflags,
6733                                op_append_elem(OP_LIST, expr, scalar(sv))));
6734     assert(!loop->op_next);
6735     /* for my  $x () sets OPpLVAL_INTRO;
6736      * for our $x () sets OPpOUR_INTRO */
6737     loop->op_private = (U8)iterpflags;
6738     if (loop->op_slabbed
6739      && DIFF(loop, OpSLOT(loop)->opslot_next)
6740          < SIZE_TO_PSIZE(sizeof(LOOP)))
6741     {
6742         LOOP *tmp;
6743         NewOp(1234,tmp,1,LOOP);
6744         Copy(loop,tmp,1,LISTOP);
6745 #ifdef PERL_OP_PARENT
6746         assert(loop->op_last->op_sibling == (OP*)loop);
6747         loop->op_last->op_sibling = (OP*)tmp; /*point back to new parent */
6748 #endif
6749         S_op_destroy(aTHX_ (OP*)loop);
6750         loop = tmp;
6751     }
6752     else if (!loop->op_slabbed)
6753         loop = (LOOP*)PerlMemShared_realloc(loop, sizeof(LOOP));
6754     loop->op_targ = padoff;
6755     wop = newWHILEOP(flags, 1, loop, newOP(OP_ITER, 0), block, cont, 0);
6756     return wop;
6757 }
6758
6759 /*
6760 =for apidoc Am|OP *|newLOOPEX|I32 type|OP *label
6761
6762 Constructs, checks, and returns a loop-exiting op (such as C<goto>
6763 or C<last>).  I<type> is the opcode.  I<label> supplies the parameter
6764 determining the target of the op; it is consumed by this function and
6765 becomes part of the constructed op tree.
6766
6767 =cut
6768 */
6769
6770 OP*
6771 Perl_newLOOPEX(pTHX_ I32 type, OP *label)
6772 {
6773     OP *o = NULL;
6774
6775     PERL_ARGS_ASSERT_NEWLOOPEX;
6776
6777     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
6778
6779     if (type != OP_GOTO) {
6780         /* "last()" means "last" */
6781         if (label->op_type == OP_STUB && (label->op_flags & OPf_PARENS)) {
6782             o = newOP(type, OPf_SPECIAL);
6783         }
6784     }
6785     else {
6786         /* Check whether it's going to be a goto &function */
6787         if (label->op_type == OP_ENTERSUB
6788                 && !(label->op_flags & OPf_STACKED))
6789             label = newUNOP(OP_REFGEN, 0, op_lvalue(label, OP_REFGEN));
6790     }
6791
6792     /* Check for a constant argument */
6793     if (label->op_type == OP_CONST) {
6794             SV * const sv = ((SVOP *)label)->op_sv;
6795             STRLEN l;
6796             const char *s = SvPV_const(sv,l);
6797             if (l == strlen(s)) {
6798                 o = newPVOP(type,
6799                             SvUTF8(((SVOP*)label)->op_sv),
6800                             savesharedpv(
6801                                 SvPV_nolen_const(((SVOP*)label)->op_sv)));
6802             }
6803     }
6804     
6805     /* If we have already created an op, we do not need the label. */
6806     if (o)
6807                 op_free(label);
6808     else o = newUNOP(type, OPf_STACKED, label);
6809
6810     PL_hints |= HINT_BLOCK_SCOPE;
6811     return o;
6812 }
6813
6814 /* if the condition is a literal array or hash
6815    (or @{ ... } etc), make a reference to it.
6816  */
6817 STATIC OP *
6818 S_ref_array_or_hash(pTHX_ OP *cond)
6819 {
6820     if (cond
6821     && (cond->op_type == OP_RV2AV
6822     ||  cond->op_type == OP_PADAV
6823     ||  cond->op_type == OP_RV2HV
6824     ||  cond->op_type == OP_PADHV))
6825
6826         return newUNOP(OP_REFGEN, 0, op_lvalue(cond, OP_REFGEN));
6827
6828     else if(cond
6829     && (cond->op_type == OP_ASLICE
6830     ||  cond->op_type == OP_KVASLICE
6831     ||  cond->op_type == OP_HSLICE
6832     ||  cond->op_type == OP_KVHSLICE)) {
6833
6834         /* anonlist now needs a list from this op, was previously used in
6835          * scalar context */
6836         cond->op_flags |= ~(OPf_WANT_SCALAR | OPf_REF);
6837         cond->op_flags |= OPf_WANT_LIST;
6838
6839         return newANONLIST(op_lvalue(cond, OP_ANONLIST));
6840     }
6841
6842     else
6843         return cond;
6844 }
6845
6846 /* These construct the optree fragments representing given()
6847    and when() blocks.
6848
6849    entergiven and enterwhen are LOGOPs; the op_other pointer
6850    points up to the associated leave op. We need this so we
6851    can put it in the context and make break/continue work.
6852    (Also, of course, pp_enterwhen will jump straight to
6853    op_other if the match fails.)
6854  */
6855
6856 STATIC OP *
6857 S_newGIVWHENOP(pTHX_ OP *cond, OP *block,
6858                    I32 enter_opcode, I32 leave_opcode,
6859                    PADOFFSET entertarg)
6860 {
6861     dVAR;
6862     LOGOP *enterop;
6863     OP *o;
6864
6865     PERL_ARGS_ASSERT_NEWGIVWHENOP;
6866
6867     enterop = S_alloc_LOGOP(aTHX_ enter_opcode, block, NULL);
6868     enterop->op_ppaddr = PL_ppaddr[enter_opcode];
6869     enterop->op_targ = ((entertarg == NOT_IN_PAD) ? 0 : entertarg);
6870     enterop->op_private = 0;
6871
6872     o = newUNOP(leave_opcode, 0, (OP *) enterop);
6873
6874     if (cond) {
6875         /* prepend cond if we have one */
6876         op_sibling_splice((OP*)enterop, NULL, 0, scalar(cond));
6877
6878         o->op_next = LINKLIST(cond);
6879         cond->op_next = (OP *) enterop;
6880     }
6881     else {
6882         /* This is a default {} block */
6883         enterop->op_flags |= OPf_SPECIAL;
6884         o      ->op_flags |= OPf_SPECIAL;
6885
6886         o->op_next = (OP *) enterop;
6887     }
6888
6889     CHECKOP(enter_opcode, enterop); /* Currently does nothing, since
6890                                        entergiven and enterwhen both
6891                                        use ck_null() */
6892
6893     enterop->op_next = LINKLIST(block);
6894     block->op_next = enterop->op_other = o;
6895
6896     return o;
6897 }
6898
6899 /* Does this look like a boolean operation? For these purposes
6900    a boolean operation is:
6901      - a subroutine call [*]
6902      - a logical connective
6903      - a comparison operator
6904      - a filetest operator, with the exception of -s -M -A -C
6905      - defined(), exists() or eof()
6906      - /$re/ or $foo =~ /$re/
6907    
6908    [*] possibly surprising
6909  */
6910 STATIC bool
6911 S_looks_like_bool(pTHX_ const OP *o)
6912 {
6913     PERL_ARGS_ASSERT_LOOKS_LIKE_BOOL;
6914
6915     switch(o->op_type) {
6916         case OP_OR:
6917         case OP_DOR:
6918             return looks_like_bool(cLOGOPo->op_first);
6919
6920         case OP_AND:
6921         {
6922             OP* sibl = OP_SIBLING(cLOGOPo->op_first);
6923             ASSUME(sibl);
6924             return (
6925                 looks_like_bool(cLOGOPo->op_first)
6926              && looks_like_bool(sibl));
6927         }
6928
6929         case OP_NULL:
6930         case OP_SCALAR:
6931             return (
6932                 o->op_flags & OPf_KIDS
6933             && looks_like_bool(cUNOPo->op_first));
6934
6935         case OP_ENTERSUB:
6936
6937         case OP_NOT:    case OP_XOR:
6938
6939         case OP_EQ:     case OP_NE:     case OP_LT:
6940         case OP_GT:     case OP_LE:     case OP_GE:
6941
6942         case OP_I_EQ:   case OP_I_NE:   case OP_I_LT:
6943         case OP_I_GT:   case OP_I_LE:   case OP_I_GE:
6944
6945         case OP_SEQ:    case OP_SNE:    case OP_SLT:
6946         case OP_SGT:    case OP_SLE:    case OP_SGE:
6947         
6948         case OP_SMARTMATCH:
6949         
6950         case OP_FTRREAD:  case OP_FTRWRITE: case OP_FTREXEC:
6951         case OP_FTEREAD:  case OP_FTEWRITE: case OP_FTEEXEC:
6952         case OP_FTIS:     case OP_FTEOWNED: case OP_FTROWNED:
6953         case OP_FTZERO:   case OP_FTSOCK:   case OP_FTCHR:
6954         case OP_FTBLK:    case OP_FTFILE:   case OP_FTDIR:
6955         case OP_FTPIPE:   case OP_FTLINK:   case OP_FTSUID:
6956         case OP_FTSGID:   case OP_FTSVTX:   case OP_FTTTY:
6957         case OP_FTTEXT:   case OP_FTBINARY:
6958         
6959         case OP_DEFINED: case OP_EXISTS:
6960         case OP_MATCH:   case OP_EOF:
6961
6962         case OP_FLOP:
6963
6964             return TRUE;
6965         
6966         case OP_CONST:
6967             /* Detect comparisons that have been optimized away */
6968             if (cSVOPo->op_sv == &PL_sv_yes
6969             ||  cSVOPo->op_sv == &PL_sv_no)
6970             
6971                 return TRUE;
6972             else
6973                 return FALSE;
6974
6975         /* FALLTHROUGH */
6976         default:
6977             return FALSE;
6978     }
6979 }
6980
6981 /*
6982 =for apidoc Am|OP *|newGIVENOP|OP *cond|OP *block|PADOFFSET defsv_off
6983
6984 Constructs, checks, and returns an op tree expressing a C<given> block.
6985 I<cond> supplies the expression that will be locally assigned to a lexical
6986 variable, and I<block> supplies the body of the C<given> construct; they
6987 are consumed by this function and become part of the constructed op tree.
6988 I<defsv_off> is the pad offset of the scalar lexical variable that will
6989 be affected.  If it is 0, the global $_ will be used.
6990
6991 =cut
6992 */
6993
6994 OP *
6995 Perl_newGIVENOP(pTHX_ OP *cond, OP *block, PADOFFSET defsv_off)
6996 {
6997     PERL_ARGS_ASSERT_NEWGIVENOP;
6998     return newGIVWHENOP(
6999         ref_array_or_hash(cond),
7000         block,
7001         OP_ENTERGIVEN, OP_LEAVEGIVEN,
7002         defsv_off);
7003 }
7004
7005 /*
7006 =for apidoc Am|OP *|newWHENOP|OP *cond|OP *block
7007
7008 Constructs, checks, and returns an op tree expressing a C<when> block.
7009 I<cond> supplies the test expression, and I<block> supplies the block
7010 that will be executed if the test evaluates to true; they are consumed
7011 by this function and become part of the constructed op tree.  I<cond>
7012 will be interpreted DWIMically, often as a comparison against C<$_>,
7013 and may be null to generate a C<default> block.
7014
7015 =cut
7016 */
7017
7018 OP *
7019 Perl_newWHENOP(pTHX_ OP *cond, OP *block)
7020 {
7021     const bool cond_llb = (!cond || looks_like_bool(cond));
7022     OP *cond_op;
7023
7024     PERL_ARGS_ASSERT_NEWWHENOP;
7025
7026     if (cond_llb)
7027         cond_op = cond;
7028     else {
7029         cond_op = newBINOP(OP_SMARTMATCH, OPf_SPECIAL,
7030                 newDEFSVOP(),
7031                 scalar(ref_array_or_hash(cond)));
7032     }
7033     
7034     return newGIVWHENOP(cond_op, block, OP_ENTERWHEN, OP_LEAVEWHEN, 0);
7035 }
7036
7037 /* must not conflict with SVf_UTF8 */
7038 #define CV_CKPROTO_CURSTASH     0x1
7039
7040 void
7041 Perl_cv_ckproto_len_flags(pTHX_ const CV *cv, const GV *gv, const char *p,
7042                     const STRLEN len, const U32 flags)
7043 {
7044     SV *name = NULL, *msg;
7045     const char * cvp = SvROK(cv)
7046                         ? SvTYPE(SvRV_const(cv)) == SVt_PVCV
7047                            ? (cv = (const CV *)SvRV_const(cv), CvPROTO(cv))
7048                            : ""
7049                         : CvPROTO(cv);
7050     STRLEN clen = CvPROTOLEN(cv), plen = len;
7051
7052     PERL_ARGS_ASSERT_CV_CKPROTO_LEN_FLAGS;
7053
7054     if (p == NULL && cvp == NULL)
7055         return;
7056
7057     if (!ckWARN_d(WARN_PROTOTYPE))
7058         return;
7059
7060     if (p && cvp) {
7061         p = S_strip_spaces(aTHX_ p, &plen);
7062         cvp = S_strip_spaces(aTHX_ cvp, &clen);
7063         if ((flags & SVf_UTF8) == SvUTF8(cv)) {
7064             if (plen == clen && memEQ(cvp, p, plen))
7065                 return;
7066         } else {
7067             if (flags & SVf_UTF8) {
7068                 if (bytes_cmp_utf8((const U8 *)cvp, clen, (const U8 *)p, plen) == 0)
7069                     return;
7070             }
7071             else {
7072                 if (bytes_cmp_utf8((const U8 *)p, plen, (const U8 *)cvp, clen) == 0)
7073                     return;
7074             }
7075         }
7076     }
7077
7078     msg = sv_newmortal();
7079
7080     if (gv)
7081     {
7082         if (isGV(gv))
7083             gv_efullname3(name = sv_newmortal(), gv, NULL);
7084         else if (SvPOK(gv) && *SvPVX((SV *)gv) == '&')
7085             name = newSVpvn_flags(SvPVX((SV *)gv)+1, SvCUR(gv)-1, SvUTF8(gv)|SVs_TEMP);
7086         else if (flags & CV_CKPROTO_CURSTASH || SvROK(gv)) {
7087             name = sv_2mortal(newSVhek(HvNAME_HEK(PL_curstash)));
7088             sv_catpvs(name, "::");
7089             if (SvROK(gv)) {
7090                 assert (SvTYPE(SvRV_const(gv)) == SVt_PVCV);
7091                 assert (CvNAMED(SvRV_const(gv)));
7092                 sv_cathek(name, CvNAME_HEK(MUTABLE_CV(SvRV_const(gv))));
7093             }
7094             else sv_catsv(name, (SV *)gv);
7095         }
7096         else name = (SV *)gv;
7097     }
7098     sv_setpvs(msg, "Prototype mismatch:");
7099     if (name)
7100         Perl_sv_catpvf(aTHX_ msg, " sub %"SVf, SVfARG(name));
7101     if (cvp)
7102         Perl_sv_catpvf(aTHX_ msg, " (%"UTF8f")", 
7103             UTF8fARG(SvUTF8(cv),clen,cvp)
7104         );
7105     else
7106         sv_catpvs(msg, ": none");
7107     sv_catpvs(msg, " vs ");
7108     if (p)
7109         Perl_sv_catpvf(aTHX_ msg, "(%"UTF8f")", UTF8fARG(flags & SVf_UTF8,len,p));
7110     else
7111         sv_catpvs(msg, "none");
7112     Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE), "%"SVf, SVfARG(msg));
7113 }
7114
7115 static void const_sv_xsub(pTHX_ CV* cv);
7116 static void const_av_xsub(pTHX_ CV* cv);
7117
7118 /*
7119
7120 =head1 Optree Manipulation Functions
7121
7122 =for apidoc cv_const_sv
7123
7124 If C<cv> is a constant sub eligible for inlining, returns the constant
7125 value returned by the sub.  Otherwise, returns NULL.
7126
7127 Constant subs can be created with C<newCONSTSUB> or as described in
7128 L<perlsub/"Constant Functions">.
7129
7130 =cut
7131 */
7132 SV *
7133 Perl_cv_const_sv(const CV *const cv)
7134 {
7135     SV *sv;
7136     if (!cv)
7137         return NULL;
7138     if (!(SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM))
7139         return NULL;
7140     sv = CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
7141     if (sv && SvTYPE(sv) == SVt_PVAV) return NULL;
7142     return sv;
7143 }
7144
7145 SV *
7146 Perl_cv_const_sv_or_av(const CV * const cv)
7147 {
7148     if (!cv)
7149         return NULL;
7150     if (SvROK(cv)) return SvRV((SV *)cv);
7151     assert (SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM);
7152     return CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
7153 }
7154
7155 /* op_const_sv:  examine an optree to determine whether it's in-lineable.
7156  * Can be called in 3 ways:
7157  *
7158  * !cv
7159  *      look for a single OP_CONST with attached value: return the value
7160  *
7161  * cv && CvCLONE(cv) && !CvCONST(cv)
7162  *
7163  *      examine the clone prototype, and if contains only a single
7164  *      OP_CONST referencing a pad const, or a single PADSV referencing
7165  *      an outer lexical, return a non-zero value to indicate the CV is
7166  *      a candidate for "constizing" at clone time
7167  *
7168  * cv && CvCONST(cv)
7169  *
7170  *      We have just cloned an anon prototype that was marked as a const
7171  *      candidate. Try to grab the current value, and in the case of
7172  *      PADSV, ignore it if it has multiple references. In this case we
7173  *      return a newly created *copy* of the value.
7174  */
7175
7176 SV *
7177 Perl_op_const_sv(pTHX_ const OP *o, CV *cv)
7178 {
7179     SV *sv = NULL;
7180
7181     if (!o)
7182         return NULL;
7183
7184     if (o->op_type == OP_LINESEQ && cLISTOPo->op_first)
7185         o = OP_SIBLING(cLISTOPo->op_first);
7186
7187     for (; o; o = o->op_next) {
7188         const OPCODE type = o->op_type;
7189
7190         if (sv && o->op_next == o)
7191             return sv;
7192         if (o->op_next != o) {
7193             if (type == OP_NEXTSTATE
7194              || (type == OP_NULL && !(o->op_flags & OPf_KIDS))
7195              || type == OP_PUSHMARK)
7196                 continue;
7197             if (type == OP_DBSTATE)
7198                 continue;
7199         }
7200         if (type == OP_LEAVESUB || type == OP_RETURN)
7201             break;
7202         if (sv)
7203             return NULL;
7204         if (type == OP_CONST && cSVOPo->op_sv)
7205             sv = cSVOPo->op_sv;
7206         else if (type == OP_UNDEF && !o->op_private) {
7207             sv = newSV(0);
7208             SAVEFREESV(sv);
7209         }
7210         else if (cv && type == OP_CONST) {
7211             sv = PAD_BASE_SV(CvPADLIST(cv), o->op_targ);
7212             if (!sv)
7213                 return NULL;
7214         }
7215         else if (cv && type == OP_PADSV) {
7216             if (CvCONST(cv)) { /* newly cloned anon */
7217                 sv = PAD_BASE_SV(CvPADLIST(cv), o->op_targ);
7218                 /* the candidate should have 1 ref from this pad and 1 ref
7219                  * from the parent */
7220                 if (!sv || SvREFCNT(sv) != 2)
7221                     return NULL;
7222                 sv = newSVsv(sv);
7223                 SvREADONLY_on(sv);
7224                 return sv;
7225             }
7226             else {
7227                 if (PAD_COMPNAME_FLAGS(o->op_targ) & SVf_FAKE)
7228                     sv = &PL_sv_undef; /* an arbitrary non-null value */
7229             }
7230         }
7231         else {
7232             return NULL;
7233         }
7234     }
7235     return sv;
7236 }
7237
7238 static bool
7239 S_already_defined(pTHX_ CV *const cv, OP * const block, OP * const o,
7240                         PADNAME * const name, SV ** const const_svp)
7241 {
7242     assert (cv);
7243     assert (o || name);
7244     assert (const_svp);
7245     if ((!block
7246          )) {
7247         if (CvFLAGS(PL_compcv)) {
7248             /* might have had built-in attrs applied */
7249             const bool pureperl = !CvISXSUB(cv) && CvROOT(cv);
7250             if (CvLVALUE(PL_compcv) && ! CvLVALUE(cv) && pureperl
7251              && ckWARN(WARN_MISC))
7252             {
7253                 /* protect against fatal warnings leaking compcv */
7254                 SAVEFREESV(PL_compcv);
7255                 Perl_warner(aTHX_ packWARN(WARN_MISC), "lvalue attribute ignored after the subroutine has been defined");
7256                 SvREFCNT_inc_simple_void_NN(PL_compcv);
7257             }
7258             CvFLAGS(cv) |=
7259                 (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS
7260                   & ~(CVf_LVALUE * pureperl));
7261         }
7262         return FALSE;
7263     }
7264
7265     /* redundant check for speed: */
7266     if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
7267         const line_t oldline = CopLINE(PL_curcop);
7268         SV *namesv = o
7269             ? cSVOPo->op_sv
7270             : sv_2mortal(newSVpvn_utf8(
7271                 PadnamePV(name)+1,PadnameLEN(name)-1, PadnameUTF8(name)
7272               ));
7273         if (PL_parser && PL_parser->copline != NOLINE)
7274             /* This ensures that warnings are reported at the first
7275                line of a redefinition, not the last.  */
7276             CopLINE_set(PL_curcop, PL_parser->copline);
7277         /* protect against fatal warnings leaking compcv */
7278         SAVEFREESV(PL_compcv);
7279         report_redefined_cv(namesv, cv, const_svp);
7280         SvREFCNT_inc_simple_void_NN(PL_compcv);
7281         CopLINE_set(PL_curcop, oldline);
7282     }
7283     SAVEFREESV(cv);
7284     return TRUE;
7285 }
7286
7287 CV *
7288 Perl_newMYSUB(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs, OP *block)
7289 {
7290     CV **spot;
7291     SV **svspot;
7292     const char *ps;
7293     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
7294     U32 ps_utf8 = 0;
7295     CV *cv = NULL;
7296     CV *compcv = PL_compcv;
7297     SV *const_sv;
7298     PADNAME *name;
7299     PADOFFSET pax = o->op_targ;
7300     CV *outcv = CvOUTSIDE(PL_compcv);
7301     CV *clonee = NULL;
7302     HEK *hek = NULL;
7303     bool reusable = FALSE;
7304
7305     PERL_ARGS_ASSERT_NEWMYSUB;
7306
7307     /* Find the pad slot for storing the new sub.
7308        We cannot use PL_comppad, as it is the pad owned by the new sub.  We
7309        need to look in CvOUTSIDE and find the pad belonging to the enclos-
7310        ing sub.  And then we need to dig deeper if this is a lexical from
7311        outside, as in:
7312            my sub foo; sub { sub foo { } }
7313      */
7314    redo:
7315     name = PadlistNAMESARRAY(CvPADLIST(outcv))[pax];
7316     if (PadnameOUTER(name) && PARENT_PAD_INDEX(name)) {
7317         pax = PARENT_PAD_INDEX(name);
7318         outcv = CvOUTSIDE(outcv);
7319         assert(outcv);
7320         goto redo;
7321     }
7322     svspot =
7323         &PadARRAY(PadlistARRAY(CvPADLIST(outcv))
7324                         [CvDEPTH(outcv) ? CvDEPTH(outcv) : 1])[pax];
7325     spot = (CV **)svspot;
7326
7327     if (!(PL_parser && PL_parser->error_count))
7328         move_proto_attr(&proto, &attrs, (GV *)name);
7329
7330     if (proto) {
7331         assert(proto->op_type == OP_CONST);
7332         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
7333         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
7334     }
7335     else
7336         ps = NULL;
7337
7338     if (proto)
7339         SAVEFREEOP(proto);
7340     if (attrs)
7341         SAVEFREEOP(attrs);
7342
7343     if (PL_parser && PL_parser->error_count) {
7344         op_free(block);
7345         SvREFCNT_dec(PL_compcv);
7346         PL_compcv = 0;
7347         goto done;
7348     }
7349
7350     if (CvDEPTH(outcv) && CvCLONE(compcv)) {
7351         cv = *spot;
7352         svspot = (SV **)(spot = &clonee);
7353     }
7354     else if (PadnameIsSTATE(name) || CvDEPTH(outcv))
7355         cv = *spot;
7356     else {
7357         MAGIC *mg;
7358         SvUPGRADE(name, SVt_PVMG);
7359         mg = mg_find(name, PERL_MAGIC_proto);
7360         assert (SvTYPE(*spot) == SVt_PVCV);
7361         if (CvNAMED(*spot))
7362             hek = CvNAME_HEK(*spot);
7363         else {
7364             dVAR;
7365             U32 hash;
7366             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
7367             CvNAME_HEK_set(*spot, hek =
7368                 share_hek(
7369                     PadnamePV(name)+1,
7370                     PadnameLEN(name)-1 * (PadnameUTF8(name) ? -1 : 1), hash
7371                 )
7372             );
7373             CvLEXICAL_on(*spot);
7374         }
7375         if (mg) {
7376             assert(mg->mg_obj);
7377             cv = (CV *)mg->mg_obj;
7378         }
7379         else {
7380             sv_magic(name, &PL_sv_undef, PERL_MAGIC_proto, NULL, 0);
7381             mg = mg_find(name, PERL_MAGIC_proto);
7382         }
7383         spot = (CV **)(svspot = &mg->mg_obj);
7384     }
7385
7386     if (!block || !ps || *ps || attrs
7387         || (CvFLAGS(compcv) & CVf_BUILTIN_ATTRS)
7388         )
7389         const_sv = NULL;
7390     else
7391         const_sv = op_const_sv(block, NULL);
7392
7393     if (cv) {
7394         const bool exists = CvROOT(cv) || CvXSUB(cv);
7395
7396         /* if the subroutine doesn't exist and wasn't pre-declared
7397          * with a prototype, assume it will be AUTOLOADed,
7398          * skipping the prototype check
7399          */
7400         if (exists || SvPOK(cv))
7401             cv_ckproto_len_flags(cv, (GV *)name, ps, ps_len, ps_utf8);
7402         /* already defined? */
7403         if (exists) {
7404             if (S_already_defined(aTHX_ cv,block,NULL,name,&const_sv))
7405                 cv = NULL;
7406             else {
7407                 if (attrs) goto attrs;
7408                 /* just a "sub foo;" when &foo is already defined */
7409                 SAVEFREESV(compcv);
7410                 goto done;
7411             }
7412         }
7413         else if (CvDEPTH(outcv) && CvCLONE(compcv)) {
7414             cv = NULL;
7415             reusable = TRUE;
7416         }
7417     }
7418     if (const_sv) {
7419         SvREFCNT_inc_simple_void_NN(const_sv);
7420         SvFLAGS(const_sv) = (SvFLAGS(const_sv) & ~SVs_PADMY) | SVs_PADTMP;
7421         if (cv) {
7422             assert(!CvROOT(cv) && !CvCONST(cv));
7423             cv_forget_slab(cv);
7424         }
7425         else {
7426             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
7427             CvFILE_set_from_cop(cv, PL_curcop);
7428             CvSTASH_set(cv, PL_curstash);
7429             *spot = cv;
7430         }
7431         sv_setpvs(MUTABLE_SV(cv), "");  /* prototype is "" */
7432         CvXSUBANY(cv).any_ptr = const_sv;
7433         CvXSUB(cv) = const_sv_xsub;
7434         CvCONST_on(cv);
7435         CvISXSUB_on(cv);
7436         op_free(block);
7437         SvREFCNT_dec(compcv);
7438         PL_compcv = NULL;
7439         goto setname;
7440     }
7441     /* Checking whether outcv is CvOUTSIDE(compcv) is not sufficient to
7442        determine whether this sub definition is in the same scope as its
7443        declaration.  If this sub definition is inside an inner named pack-
7444        age sub (my sub foo; sub bar { sub foo { ... } }), outcv points to
7445        the package sub.  So check PadnameOUTER(name) too.
7446      */
7447     if (outcv == CvOUTSIDE(compcv) && !PadnameOUTER(name)) { 
7448         assert(!CvWEAKOUTSIDE(compcv));
7449         SvREFCNT_dec(CvOUTSIDE(compcv));
7450         CvWEAKOUTSIDE_on(compcv);
7451     }
7452     /* XXX else do we have a circular reference? */
7453     if (cv) {   /* must reuse cv in case stub is referenced elsewhere */
7454         /* transfer PL_compcv to cv */
7455         if (block
7456         ) {
7457             cv_flags_t preserved_flags =
7458                 CvFLAGS(cv) & (CVf_BUILTIN_ATTRS|CVf_NAMED);
7459             PADLIST *const temp_padl = CvPADLIST(cv);
7460             CV *const temp_cv = CvOUTSIDE(cv);
7461             const cv_flags_t other_flags =
7462                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
7463             OP * const cvstart = CvSTART(cv);
7464
7465             SvPOK_off(cv);
7466             CvFLAGS(cv) =
7467                 CvFLAGS(compcv) | preserved_flags;
7468             CvOUTSIDE(cv) = CvOUTSIDE(compcv);
7469             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(compcv);
7470             CvPADLIST(cv) = CvPADLIST(compcv);
7471             CvOUTSIDE(compcv) = temp_cv;
7472             CvPADLIST(compcv) = temp_padl;
7473             CvSTART(cv) = CvSTART(compcv);
7474             CvSTART(compcv) = cvstart;
7475             CvFLAGS(compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
7476             CvFLAGS(compcv) |= other_flags;
7477
7478             if (CvFILE(cv) && CvDYNFILE(cv)) {
7479                 Safefree(CvFILE(cv));
7480             }
7481
7482             /* inner references to compcv must be fixed up ... */
7483             pad_fixup_inner_anons(CvPADLIST(cv), compcv, cv);
7484             if (PERLDB_INTER)/* Advice debugger on the new sub. */
7485               ++PL_sub_generation;
7486         }
7487         else {
7488             /* Might have had built-in attributes applied -- propagate them. */
7489             CvFLAGS(cv) |= (CvFLAGS(compcv) & CVf_BUILTIN_ATTRS);
7490         }
7491         /* ... before we throw it away */
7492         SvREFCNT_dec(compcv);
7493         PL_compcv = compcv = cv;
7494     }
7495     else {
7496         cv = compcv;
7497         *spot = cv;
7498     }
7499    setname:
7500     CvLEXICAL_on(cv);
7501     if (!CvNAME_HEK(cv)) {
7502         if (hek) (void)share_hek_hek(hek);
7503         else {
7504             dVAR;
7505             U32 hash;
7506             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
7507             hek = share_hek(PadnamePV(name)+1,
7508                       PadnameLEN(name)-1 * (PadnameUTF8(name) ? -1 : 1),
7509                       hash);
7510         }
7511         CvNAME_HEK_set(cv, hek);
7512     }
7513     if (const_sv) goto clone;
7514
7515     CvFILE_set_from_cop(cv, PL_curcop);
7516     CvSTASH_set(cv, PL_curstash);
7517
7518     if (ps) {
7519         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
7520         if ( ps_utf8 ) SvUTF8_on(MUTABLE_SV(cv));
7521     }
7522
7523     if (!block)
7524         goto attrs;
7525
7526     /* If we assign an optree to a PVCV, then we've defined a subroutine that
7527        the debugger could be able to set a breakpoint in, so signal to
7528        pp_entereval that it should not throw away any saved lines at scope
7529        exit.  */
7530        
7531     PL_breakable_sub_gen++;
7532     /* This makes sub {}; work as expected.  */
7533     if (block->op_type == OP_STUB) {
7534             OP* const newblock = newSTATEOP(0, NULL, 0);
7535             op_free(block);
7536             block = newblock;
7537     }
7538     CvROOT(cv) = CvLVALUE(cv)
7539                    ? newUNOP(OP_LEAVESUBLV, 0,
7540                              op_lvalue(scalarseq(block), OP_LEAVESUBLV))
7541                    : newUNOP(OP_LEAVESUB, 0, scalarseq(block));
7542     CvROOT(cv)->op_private |= OPpREFCOUNTED;
7543     OpREFCNT_set(CvROOT(cv), 1);
7544     /* The cv no longer needs to hold a refcount on the slab, as CvROOT
7545        itself has a refcount. */
7546     CvSLABBED_off(cv);
7547     OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
7548     CvSTART(cv) = LINKLIST(CvROOT(cv));
7549     CvROOT(cv)->op_next = 0;
7550     CALL_PEEP(CvSTART(cv));
7551     finalize_optree(CvROOT(cv));
7552     S_prune_chain_head(&CvSTART(cv));
7553
7554     /* now that optimizer has done its work, adjust pad values */
7555
7556     pad_tidy(CvCLONE(cv) ? padtidy_SUBCLONE : padtidy_SUB);
7557
7558     if (CvCLONE(cv)) {
7559         assert(!CvCONST(cv));
7560         if (ps && !*ps && op_const_sv(block, cv))
7561             CvCONST_on(cv);
7562     }
7563
7564   attrs:
7565     if (attrs) {
7566         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
7567         apply_attrs(PL_curstash, MUTABLE_SV(cv), attrs);
7568     }
7569
7570     if (block) {
7571         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
7572             SV * const tmpstr = sv_newmortal();
7573             GV * const db_postponed = gv_fetchpvs("DB::postponed",
7574                                                   GV_ADDMULTI, SVt_PVHV);
7575             HV *hv;
7576             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
7577                                           CopFILE(PL_curcop),
7578                                           (long)PL_subline,
7579                                           (long)CopLINE(PL_curcop));
7580             if (HvNAME_HEK(PL_curstash)) {
7581                 sv_sethek(tmpstr, HvNAME_HEK(PL_curstash));
7582                 sv_catpvs(tmpstr, "::");
7583             }
7584             else sv_setpvs(tmpstr, "__ANON__::");
7585             sv_catpvn_flags(tmpstr, PadnamePV(name)+1, PadnameLEN(name)-1,
7586                             PadnameUTF8(name) ? SV_CATUTF8 : SV_CATBYTES);
7587             (void)hv_store(GvHV(PL_DBsub), SvPVX_const(tmpstr),
7588                     SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr), sv, 0);
7589             hv = GvHVn(db_postponed);
7590             if (HvTOTALKEYS(hv) > 0 && hv_exists(hv, SvPVX_const(tmpstr), SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr))) {
7591                 CV * const pcv = GvCV(db_postponed);
7592                 if (pcv) {
7593                     dSP;
7594                     PUSHMARK(SP);
7595                     XPUSHs(tmpstr);
7596                     PUTBACK;
7597                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
7598                 }
7599             }
7600         }
7601     }
7602
7603   clone:
7604     if (clonee) {
7605         assert(CvDEPTH(outcv));
7606         spot = (CV **)
7607             &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[CvDEPTH(outcv)])[pax];
7608         if (reusable) cv_clone_into(clonee, *spot);
7609         else *spot = cv_clone(clonee);
7610         SvREFCNT_dec_NN(clonee);
7611         cv = *spot;
7612         SvPADMY_on(cv);
7613     }
7614     if (CvDEPTH(outcv) && !reusable && PadnameIsSTATE(name)) {
7615         PADOFFSET depth = CvDEPTH(outcv);
7616         while (--depth) {
7617             SV *oldcv;
7618             svspot = &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[depth])[pax];
7619             oldcv = *svspot;
7620             *svspot = SvREFCNT_inc_simple_NN(cv);
7621             SvREFCNT_dec(oldcv);
7622         }
7623     }
7624
7625   done:
7626     if (PL_parser)
7627         PL_parser->copline = NOLINE;
7628     LEAVE_SCOPE(floor);
7629     if (o) op_free(o);
7630     return cv;
7631 }
7632
7633 /* _x = extended */
7634 CV *
7635 Perl_newATTRSUB_x(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs,
7636                             OP *block, bool o_is_gv)
7637 {
7638     GV *gv;
7639     const char *ps;
7640     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
7641     U32 ps_utf8 = 0;
7642     CV *cv = NULL;
7643     SV *const_sv;
7644     const bool ec = PL_parser && PL_parser->error_count;
7645     /* If the subroutine has no body, no attributes, and no builtin attributes
7646        then it's just a sub declaration, and we may be able to get away with
7647        storing with a placeholder scalar in the symbol table, rather than a
7648        full CV.  If anything is present then it will take a full CV to
7649        store it.  */
7650     const I32 gv_fetch_flags
7651         = ec ? GV_NOADD_NOINIT :
7652         (block || attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS))
7653         ? GV_ADDMULTI : GV_ADDMULTI | GV_NOINIT;
7654     STRLEN namlen = 0;
7655     const char * const name =
7656          o ? SvPV_const(o_is_gv ? (SV *)o : cSVOPo->op_sv, namlen) : NULL;
7657     bool has_name;
7658     bool name_is_utf8 = o && !o_is_gv && SvUTF8(cSVOPo->op_sv);
7659 #ifdef PERL_DEBUG_READONLY_OPS
7660     OPSLAB *slab = NULL;
7661 #endif
7662     bool special = FALSE;
7663
7664     if (o_is_gv) {
7665         gv = (GV*)o;
7666         o = NULL;
7667         has_name = TRUE;
7668     } else if (name) {
7669         /* Try to optimise and avoid creating a GV.  Instead, the CV’s name
7670            hek and CvSTASH pointer together can imply the GV.  If the name
7671            contains a package name, then GvSTASH(CvGV(cv)) may differ from
7672            CvSTASH, so forego the optimisation if we find any.
7673            Also, we may be called from load_module at run time, so
7674            PL_curstash (which sets CvSTASH) may not point to the stash the
7675            sub is stored in.  */
7676         const I32 flags =
7677            ec ? GV_NOADD_NOINIT
7678               :   PL_curstash != CopSTASH(PL_curcop)
7679                || memchr(name, ':', namlen) || memchr(name, '\'', namlen)
7680                     ? gv_fetch_flags
7681                     : GV_ADDMULTI | GV_NOINIT;
7682         gv = gv_fetchsv(cSVOPo->op_sv, flags, SVt_PVCV);
7683         has_name = TRUE;
7684     } else if (PERLDB_NAMEANON && CopLINE(PL_curcop)) {
7685         SV * const sv = sv_newmortal();
7686         Perl_sv_setpvf(aTHX_ sv, "%s[%s:%"IVdf"]",
7687                        PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
7688                        CopFILE(PL_curcop), (IV)CopLINE(PL_curcop));
7689         gv = gv_fetchsv(sv, gv_fetch_flags, SVt_PVCV);
7690         has_name = TRUE;
7691     } else if (PL_curstash) {
7692         gv = gv_fetchpvs("__ANON__", gv_fetch_flags, SVt_PVCV);
7693         has_name = FALSE;
7694     } else {
7695         gv = gv_fetchpvs("__ANON__::__ANON__", gv_fetch_flags, SVt_PVCV);
7696         has_name = FALSE;
7697     }
7698     if (!ec)
7699         move_proto_attr(&proto, &attrs,
7700                         isGV(gv) ? gv : (GV *)cSVOPo->op_sv);
7701
7702     if (proto) {
7703         assert(proto->op_type == OP_CONST);
7704         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
7705         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
7706     }
7707     else
7708         ps = NULL;
7709
7710     if (o)
7711         SAVEFREEOP(o);
7712     if (proto)
7713         SAVEFREEOP(proto);
7714     if (attrs)
7715         SAVEFREEOP(attrs);
7716
7717     if (ec) {
7718         op_free(block);
7719         if (name) SvREFCNT_dec(PL_compcv);
7720         else cv = PL_compcv;
7721         PL_compcv = 0;
7722         if (name && block) {
7723             const char *s = strrchr(name, ':');
7724             s = s ? s+1 : name;
7725             if (strEQ(s, "BEGIN")) {
7726                 if (PL_in_eval & EVAL_KEEPERR)
7727                     Perl_croak_nocontext("BEGIN not safe after errors--compilation aborted");
7728                 else {
7729                     SV * const errsv = ERRSV;
7730                     /* force display of errors found but not reported */
7731                     sv_catpvs(errsv, "BEGIN not safe after errors--compilation aborted");
7732                     Perl_croak_nocontext("%"SVf, SVfARG(errsv));
7733                 }
7734             }
7735         }
7736         goto done;
7737     }
7738
7739     if (!block && SvTYPE(gv) != SVt_PVGV) {
7740       /* If we are not defining a new sub and the existing one is not a
7741          full GV + CV... */
7742       if (attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS)) {
7743         /* We are applying attributes to an existing sub, so we need it
7744            upgraded if it is a constant.  */
7745         if (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)
7746             gv_init_pvn(gv, PL_curstash, name, namlen,
7747                         SVf_UTF8 * name_is_utf8);
7748       }
7749       else {                    /* Maybe prototype now, and had at maximum
7750                                    a prototype or const/sub ref before.  */
7751         if (SvTYPE(gv) > SVt_NULL) {
7752             cv_ckproto_len_flags((const CV *)gv,
7753                                  o ? (const GV *)cSVOPo->op_sv : NULL, ps,
7754                                  ps_len, ps_utf8);
7755         }
7756         if (!SvROK(gv)) {
7757           if (ps) {
7758             sv_setpvn(MUTABLE_SV(gv), ps, ps_len);
7759             if ( ps_utf8 ) SvUTF8_on(MUTABLE_SV(gv));
7760           }
7761           else
7762             sv_setiv(MUTABLE_SV(gv), -1);
7763         }
7764
7765         SvREFCNT_dec(PL_compcv);
7766         cv = PL_compcv = NULL;
7767         goto done;
7768       }
7769     }
7770
7771     cv = (!name || (isGV(gv) && GvCVGEN(gv)))
7772         ? NULL
7773         : isGV(gv)
7774             ? GvCV(gv)
7775             : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
7776                 ? (CV *)SvRV(gv)
7777                 : NULL;
7778
7779
7780     if (!block || !ps || *ps || attrs
7781         || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS)
7782         )
7783         const_sv = NULL;
7784     else
7785         const_sv = op_const_sv(block, NULL);
7786
7787     if (SvPOK(gv) || (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)) {
7788         assert (block);
7789         cv_ckproto_len_flags((const CV *)gv,
7790                              o ? (const GV *)cSVOPo->op_sv : NULL, ps,
7791                              ps_len, ps_utf8|CV_CKPROTO_CURSTASH);
7792         if (SvROK(gv)) {
7793             /* All the other code for sub redefinition warnings expects the
7794                clobbered sub to be a CV.  Instead of making all those code
7795                paths more complex, just inline the RV version here.  */
7796             const line_t oldline = CopLINE(PL_curcop);
7797             assert(IN_PERL_COMPILETIME);
7798             if (PL_parser && PL_parser->copline != NOLINE)
7799                 /* This ensures that warnings are reported at the first
7800                    line of a redefinition, not the last.  */
7801                 CopLINE_set(PL_curcop, PL_parser->copline);
7802             /* protect against fatal warnings leaking compcv */
7803             SAVEFREESV(PL_compcv);
7804
7805             if (ckWARN(WARN_REDEFINE)
7806              || (  ckWARN_d(WARN_REDEFINE)
7807                 && (  !const_sv || SvRV(gv) == const_sv
7808                    || sv_cmp(SvRV(gv), const_sv)  )))
7809                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
7810                           "Constant subroutine %"SVf" redefined",
7811                           SVfARG(cSVOPo->op_sv));
7812
7813             SvREFCNT_inc_simple_void_NN(PL_compcv);
7814             CopLINE_set(PL_curcop, oldline);
7815             SvREFCNT_dec(SvRV(gv));
7816         }
7817     }
7818
7819     if (cv) {
7820         const bool exists = CvROOT(cv) || CvXSUB(cv);
7821
7822         /* if the subroutine doesn't exist and wasn't pre-declared
7823          * with a prototype, assume it will be AUTOLOADed,
7824          * skipping the prototype check
7825          */
7826         if (exists || SvPOK(cv))
7827             cv_ckproto_len_flags(cv, gv, ps, ps_len, ps_utf8);
7828         /* already defined (or promised)? */
7829         if (exists || (isGV(gv) && GvASSUMECV(gv))) {
7830             if (S_already_defined(aTHX_ cv, block, o, NULL, &const_sv))
7831                 cv = NULL;
7832             else {
7833                 if (attrs) goto attrs;
7834                 /* just a "sub foo;" when &foo is already defined */
7835                 SAVEFREESV(PL_compcv);
7836                 goto done;
7837             }
7838         }
7839     }
7840     if (const_sv) {
7841         SvREFCNT_inc_simple_void_NN(const_sv);
7842         SvFLAGS(const_sv) = (SvFLAGS(const_sv) & ~SVs_PADMY) | SVs_PADTMP;
7843         if (cv) {
7844             assert(!CvROOT(cv) && !CvCONST(cv));
7845             cv_forget_slab(cv);
7846             sv_setpvs(MUTABLE_SV(cv), "");  /* prototype is "" */
7847             CvXSUBANY(cv).any_ptr = const_sv;
7848             CvXSUB(cv) = const_sv_xsub;
7849             CvCONST_on(cv);
7850             CvISXSUB_on(cv);
7851         }
7852         else {
7853             if (isGV(gv)) {
7854                 if (name) GvCV_set(gv, NULL);
7855                 cv = newCONSTSUB_flags(
7856                     NULL, name, namlen, name_is_utf8 ? SVf_UTF8 : 0,
7857                     const_sv
7858                 );
7859             }
7860             else {
7861                 if (!SvROK(gv)) {
7862                     SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
7863                     prepare_SV_for_RV((SV *)gv);
7864                     SvOK_off((SV *)gv);
7865                     SvROK_on(gv);
7866                 }
7867                 SvRV_set(gv, const_sv);
7868             }
7869         }
7870         op_free(block);
7871         SvREFCNT_dec(PL_compcv);
7872         PL_compcv = NULL;
7873         goto done;
7874     }
7875     if (cv) {                           /* must reuse cv if autoloaded */
7876         /* transfer PL_compcv to cv */
7877         if (block
7878         ) {
7879             cv_flags_t existing_builtin_attrs = CvFLAGS(cv) & CVf_BUILTIN_ATTRS;
7880             PADLIST *const temp_av = CvPADLIST(cv);
7881             CV *const temp_cv = CvOUTSIDE(cv);
7882             const cv_flags_t other_flags =
7883                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
7884             OP * const cvstart = CvSTART(cv);
7885
7886             if (isGV(gv)) {
7887                 CvGV_set(cv,gv);
7888                 assert(!CvCVGV_RC(cv));
7889                 assert(CvGV(cv) == gv);
7890             }
7891             else {
7892                 U32 hash;
7893                 PERL_HASH(hash, name, namlen);
7894                 CvNAME_HEK_set(cv,
7895                                share_hek(name,
7896                                          name_is_utf8
7897                                             ? -(SSize_t)namlen
7898                                             :  (SSize_t)namlen,
7899                                          hash));
7900             }
7901
7902             SvPOK_off(cv);
7903             CvFLAGS(cv) = CvFLAGS(PL_compcv) | existing_builtin_attrs
7904                                              | CvNAMED(cv);
7905             CvOUTSIDE(cv) = CvOUTSIDE(PL_compcv);
7906             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(PL_compcv);
7907             CvPADLIST(cv) = CvPADLIST(PL_compcv);
7908             CvOUTSIDE(PL_compcv) = temp_cv;
7909             CvPADLIST(PL_compcv) = temp_av;
7910             CvSTART(cv) = CvSTART(PL_compcv);
7911             CvSTART(PL_compcv) = cvstart;
7912             CvFLAGS(PL_compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
7913             CvFLAGS(PL_compcv) |= other_flags;
7914
7915             if (CvFILE(cv) && CvDYNFILE(cv)) {
7916                 Safefree(CvFILE(cv));
7917     }
7918             CvFILE_set_from_cop(cv, PL_curcop);
7919             CvSTASH_set(cv, PL_curstash);
7920
7921             /* inner references to PL_compcv must be fixed up ... */
7922             pad_fixup_inner_anons(CvPADLIST(cv), PL_compcv, cv);
7923             if (PERLDB_INTER)/* Advice debugger on the new sub. */
7924               ++PL_sub_generation;
7925         }
7926         else {
7927             /* Might have had built-in attributes applied -- propagate them. */
7928             CvFLAGS(cv) |= (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS);
7929         }
7930         /* ... before we throw it away */
7931         SvREFCNT_dec(PL_compcv);
7932         PL_compcv = cv;
7933     }
7934     else {
7935         cv = PL_compcv;
7936         if (name && isGV(gv)) {
7937             GvCV_set(gv, cv);
7938             GvCVGEN(gv) = 0;
7939             if (HvENAME_HEK(GvSTASH(gv)))
7940                 /* sub Foo::bar { (shift)+1 } */
7941                 gv_method_changed(gv);
7942         }
7943         else if (name) {
7944             if (!SvROK(gv)) {
7945                 SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
7946                 prepare_SV_for_RV((SV *)gv);
7947                 SvOK_off((SV *)gv);
7948                 SvROK_on(gv);
7949             }
7950             SvRV_set(gv, (SV *)cv);
7951         }
7952     }
7953     if (!CvHASGV(cv)) {
7954         if (isGV(gv)) CvGV_set(cv, gv);
7955         else {
7956             U32 hash;
7957             PERL_HASH(hash, name, namlen);
7958             CvNAME_HEK_set(cv, share_hek(name,
7959                                          name_is_utf8
7960                                             ? -(SSize_t)namlen
7961                                             :  (SSize_t)namlen,
7962                                          hash));
7963         }
7964         CvFILE_set_from_cop(cv, PL_curcop);
7965         CvSTASH_set(cv, PL_curstash);
7966     }
7967
7968     if (ps) {
7969         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
7970         if ( ps_utf8 ) SvUTF8_on(MUTABLE_SV(cv));
7971     }
7972
7973     if (!block)
7974         goto attrs;
7975
7976     /* If we assign an optree to a PVCV, then we've defined a subroutine that
7977        the debugger could be able to set a breakpoint in, so signal to
7978        pp_entereval that it should not throw away any saved lines at scope
7979        exit.  */
7980        
7981     PL_breakable_sub_gen++;
7982     /* This makes sub {}; work as expected.  */
7983     if (block->op_type == OP_STUB) {
7984             OP* const newblock = newSTATEOP(0, NULL, 0);
7985             op_free(block);
7986             block = newblock;
7987     }
7988     CvROOT(cv) = CvLVALUE(cv)
7989                    ? newUNOP(OP_LEAVESUBLV, 0,
7990                              op_lvalue(scalarseq(block), OP_LEAVESUBLV))
7991                    : newUNOP(OP_LEAVESUB, 0, scalarseq(block));
7992     CvROOT(cv)->op_private |= OPpREFCOUNTED;
7993     OpREFCNT_set(CvROOT(cv), 1);
7994     /* The cv no longer needs to hold a refcount on the slab, as CvROOT
7995        itself has a refcount. */
7996     CvSLABBED_off(cv);
7997     OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
7998 #ifdef PERL_DEBUG_READONLY_OPS
7999     slab = (OPSLAB *)CvSTART(cv);
8000 #endif
8001     CvSTART(cv) = LINKLIST(CvROOT(cv));
8002     CvROOT(cv)->op_next = 0;
8003     CALL_PEEP(CvSTART(cv));
8004     finalize_optree(CvROOT(cv));
8005     S_prune_chain_head(&CvSTART(cv));
8006
8007     /* now that optimizer has done its work, adjust pad values */
8008
8009     pad_tidy(CvCLONE(cv) ? padtidy_SUBCLONE : padtidy_SUB);
8010
8011     if (CvCLONE(cv)) {
8012         assert(!CvCONST(cv));
8013         if (ps && !*ps && op_const_sv(block, cv))
8014             CvCONST_on(cv);
8015     }
8016
8017   attrs:
8018     if (attrs) {
8019         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
8020         HV *stash = name && !CvNAMED(cv) && GvSTASH(CvGV(cv))
8021                         ? GvSTASH(CvGV(cv))
8022                         : PL_curstash;
8023         if (!name) SAVEFREESV(cv);
8024         apply_attrs(stash, MUTABLE_SV(cv), attrs);
8025         if (!name) SvREFCNT_inc_simple_void_NN(cv);
8026     }
8027
8028     if (block && has_name) {
8029         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
8030             SV * const tmpstr = cv_name(cv,NULL);
8031             GV * const db_postponed = gv_fetchpvs("DB::postponed",
8032                                                   GV_ADDMULTI, SVt_PVHV);
8033             HV *hv;
8034             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
8035                                           CopFILE(PL_curcop),
8036                                           (long)PL_subline,
8037                                           (long)CopLINE(PL_curcop));
8038             (void)hv_store(GvHV(PL_DBsub), SvPVX_const(tmpstr),
8039                     SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr), sv, 0);
8040             hv = GvHVn(db_postponed);
8041             if (HvTOTALKEYS(hv) > 0 && hv_exists(hv, SvPVX_const(tmpstr), SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr))) {
8042                 CV * const pcv = GvCV(db_postponed);
8043                 if (pcv) {
8044                     dSP;
8045                     PUSHMARK(SP);
8046                     XPUSHs(tmpstr);
8047                     PUTBACK;
8048                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
8049                 }
8050             }
8051         }
8052
8053         if (name) {
8054             if (PL_parser && PL_parser->error_count)
8055                 clear_special_blocks(name, gv, cv);
8056             else
8057                 special = process_special_blocks(floor, name, gv, cv);
8058         }
8059     }
8060
8061   done:
8062     if (PL_parser)
8063         PL_parser->copline = NOLINE;
8064     LEAVE_SCOPE(floor);
8065 #ifdef PERL_DEBUG_READONLY_OPS
8066     /* Watch out for BEGIN blocks */
8067     if (!special) Slab_to_ro(slab);
8068 #endif
8069     return cv;
8070 }
8071
8072 STATIC void
8073 S_clear_special_blocks(pTHX_ const char *const fullname,
8074                        GV *const gv, CV *const cv) {
8075     const char *colon;
8076     const char *name;
8077
8078     PERL_ARGS_ASSERT_CLEAR_SPECIAL_BLOCKS;
8079
8080     colon = strrchr(fullname,':');
8081     name = colon ? colon + 1 : fullname;
8082
8083     if ((*name == 'B' && strEQ(name, "BEGIN"))
8084         || (*name == 'E' && strEQ(name, "END"))
8085         || (*name == 'U' && strEQ(name, "UNITCHECK"))
8086         || (*name == 'C' && strEQ(name, "CHECK"))
8087         || (*name == 'I' && strEQ(name, "INIT"))) {
8088         if (!isGV(gv)) {
8089             (void)CvGV(cv);
8090             assert(isGV(gv));
8091         }
8092         GvCV_set(gv, NULL);
8093         SvREFCNT_dec_NN(MUTABLE_SV(cv));
8094     }
8095 }
8096
8097 STATIC bool
8098 S_process_special_blocks(pTHX_ I32 floor, const char *const fullname,
8099                          GV *const gv,
8100                          CV *const cv)
8101 {
8102     const char *const colon = strrchr(fullname,':');
8103     const char *const name = colon ? colon + 1 : fullname;
8104
8105     PERL_ARGS_ASSERT_PROCESS_SPECIAL_BLOCKS;
8106
8107     if (*name == 'B') {
8108         if (strEQ(name, "BEGIN")) {
8109             const I32 oldscope = PL_scopestack_ix;
8110             dSP;
8111             (void)CvGV(cv);
8112             if (floor) LEAVE_SCOPE(floor);
8113             ENTER;
8114             PUSHSTACKi(PERLSI_REQUIRE);
8115             SAVECOPFILE(&PL_compiling);
8116             SAVECOPLINE(&PL_compiling);
8117             SAVEVPTR(PL_curcop);
8118
8119             DEBUG_x( dump_sub(gv) );
8120             Perl_av_create_and_push(aTHX_ &PL_beginav, MUTABLE_SV(cv));
8121             GvCV_set(gv,0);             /* cv has been hijacked */
8122             call_list(oldscope, PL_beginav);
8123
8124             POPSTACK;
8125             LEAVE;
8126             return TRUE;
8127         }
8128         else
8129             return FALSE;
8130     } else {
8131         if (*name == 'E') {
8132             if strEQ(name, "END") {
8133                 DEBUG_x( dump_sub(gv) );
8134                 Perl_av_create_and_unshift_one(aTHX_ &PL_endav, MUTABLE_SV(cv));
8135             } else
8136                 return FALSE;
8137         } else if (*name == 'U') {
8138             if (strEQ(name, "UNITCHECK")) {
8139                 /* It's never too late to run a unitcheck block */
8140                 Perl_av_create_and_unshift_one(aTHX_ &PL_unitcheckav, MUTABLE_SV(cv));
8141             }
8142             else
8143                 return FALSE;
8144         } else if (*name == 'C') {
8145             if (strEQ(name, "CHECK")) {
8146                 if (PL_main_start)
8147                     /* diag_listed_as: Too late to run %s block */
8148                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
8149                                    "Too late to run CHECK block");
8150                 Perl_av_create_and_unshift_one(aTHX_ &PL_checkav, MUTABLE_SV(cv));
8151             }
8152             else
8153                 return FALSE;
8154         } else if (*name == 'I') {
8155             if (strEQ(name, "INIT")) {
8156                 if (PL_main_start)
8157                     /* diag_listed_as: Too late to run %s block */
8158                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
8159                                    "Too late to run INIT block");
8160                 Perl_av_create_and_push(aTHX_ &PL_initav, MUTABLE_SV(cv));
8161             }
8162             else
8163                 return FALSE;
8164         } else
8165             return FALSE;
8166         DEBUG_x( dump_sub(gv) );
8167         (void)CvGV(cv);
8168         GvCV_set(gv,0);         /* cv has been hijacked */
8169         return TRUE;
8170     }
8171 }
8172
8173 /*
8174 =for apidoc newCONSTSUB
8175
8176 See L</newCONSTSUB_flags>.
8177
8178 =cut
8179 */
8180
8181 CV *
8182 Perl_newCONSTSUB(pTHX_ HV *stash, const char *name, SV *sv)
8183 {
8184     return newCONSTSUB_flags(stash, name, name ? strlen(name) : 0, 0, sv);
8185 }
8186
8187 /*
8188 =for apidoc newCONSTSUB_flags
8189
8190 Creates a constant sub equivalent to Perl C<sub FOO () { 123 }> which is
8191 eligible for inlining at compile-time.
8192
8193 Currently, the only useful value for C<flags> is SVf_UTF8.
8194
8195 The newly created subroutine takes ownership of a reference to the passed in
8196 SV.
8197
8198 Passing NULL for SV creates a constant sub equivalent to C<sub BAR () {}>,
8199 which won't be called if used as a destructor, but will suppress the overhead
8200 of a call to C<AUTOLOAD>.  (This form, however, isn't eligible for inlining at
8201 compile time.)
8202
8203 =cut
8204 */
8205
8206 CV *
8207 Perl_newCONSTSUB_flags(pTHX_ HV *stash, const char *name, STRLEN len,
8208                              U32 flags, SV *sv)
8209 {
8210     CV* cv;
8211     const char *const file = CopFILE(PL_curcop);
8212
8213     ENTER;
8214
8215     if (IN_PERL_RUNTIME) {
8216         /* at runtime, it's not safe to manipulate PL_curcop: it may be
8217          * an op shared between threads. Use a non-shared COP for our
8218          * dirty work */
8219          SAVEVPTR(PL_curcop);
8220          SAVECOMPILEWARNINGS();
8221          PL_compiling.cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
8222          PL_curcop = &PL_compiling;
8223     }
8224     SAVECOPLINE(PL_curcop);
8225     CopLINE_set(PL_curcop, PL_parser ? PL_parser->copline : NOLINE);
8226
8227     SAVEHINTS();
8228     PL_hints &= ~HINT_BLOCK_SCOPE;
8229
8230     if (stash) {
8231         SAVEGENERICSV(PL_curstash);
8232         PL_curstash = (HV *)SvREFCNT_inc_simple_NN(stash);
8233     }
8234
8235     /* Protect sv against leakage caused by fatal warnings. */
8236     if (sv) SAVEFREESV(sv);
8237
8238     /* file becomes the CvFILE. For an XS, it's usually static storage,
8239        and so doesn't get free()d.  (It's expected to be from the C pre-
8240        processor __FILE__ directive). But we need a dynamically allocated one,
8241        and we need it to get freed.  */
8242     cv = newXS_len_flags(name, len,
8243                          sv && SvTYPE(sv) == SVt_PVAV
8244                              ? const_av_xsub
8245                              : const_sv_xsub,
8246                          file ? file : "", "",
8247                          &sv, XS_DYNAMIC_FILENAME | flags);
8248     CvXSUBANY(cv).any_ptr = SvREFCNT_inc_simple(sv);
8249     CvCONST_on(cv);
8250
8251     LEAVE;
8252
8253     return cv;
8254 }
8255
8256 CV *
8257 Perl_newXS_flags(pTHX_ const char *name, XSUBADDR_t subaddr,
8258                  const char *const filename, const char *const proto,
8259                  U32 flags)
8260 {
8261     PERL_ARGS_ASSERT_NEWXS_FLAGS;
8262     return newXS_len_flags(
8263        name, name ? strlen(name) : 0, subaddr, filename, proto, NULL, flags
8264     );
8265 }
8266
8267 CV *
8268 Perl_newXS_len_flags(pTHX_ const char *name, STRLEN len,
8269                            XSUBADDR_t subaddr, const char *const filename,
8270                            const char *const proto, SV **const_svp,
8271                            U32 flags)
8272 {
8273     CV *cv;
8274     bool interleave = FALSE;
8275
8276     PERL_ARGS_ASSERT_NEWXS_LEN_FLAGS;
8277
8278     {
8279         GV * const gv = gv_fetchpvn(
8280                             name ? name : PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
8281                             name ? len : PL_curstash ? sizeof("__ANON__") - 1:
8282                                 sizeof("__ANON__::__ANON__") - 1,
8283                             GV_ADDMULTI | flags, SVt_PVCV);
8284     
8285         if (!subaddr)
8286             Perl_croak(aTHX_ "panic: no address for '%s' in '%s'", name, filename);
8287     
8288         if ((cv = (name ? GvCV(gv) : NULL))) {
8289             if (GvCVGEN(gv)) {
8290                 /* just a cached method */
8291                 SvREFCNT_dec(cv);
8292                 cv = NULL;
8293             }
8294             else if (CvROOT(cv) || CvXSUB(cv) || GvASSUMECV(gv)) {
8295                 /* already defined (or promised) */
8296                 /* Redundant check that allows us to avoid creating an SV
8297                    most of the time: */
8298                 if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
8299                     report_redefined_cv(newSVpvn_flags(
8300                                          name,len,(flags&SVf_UTF8)|SVs_TEMP
8301                                         ),
8302                                         cv, const_svp);
8303                 }
8304                 interleave = TRUE;
8305                 ENTER;
8306                 SAVEFREESV(cv);
8307                 cv = NULL;
8308             }
8309         }
8310     
8311         if (cv)                         /* must reuse cv if autoloaded */
8312             cv_undef(cv);
8313         else {
8314             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
8315             if (name) {
8316                 GvCV_set(gv,cv);
8317                 GvCVGEN(gv) = 0;
8318                 if (HvENAME_HEK(GvSTASH(gv)))
8319                     gv_method_changed(gv); /* newXS */
8320             }
8321         }
8322         if (!name)
8323             CvANON_on(cv);
8324         CvGV_set(cv, gv);
8325         (void)gv_fetchfile(filename);
8326         CvFILE(cv) = (char *)filename; /* NOTE: not copied, as it is expected to be
8327                                     an external constant string */
8328         assert(!CvDYNFILE(cv)); /* cv_undef should have turned it off */
8329         CvISXSUB_on(cv);
8330         CvXSUB(cv) = subaddr;
8331     
8332         if (name)
8333             process_special_blocks(0, name, gv, cv);
8334     }
8335
8336     if (flags & XS_DYNAMIC_FILENAME) {
8337         CvFILE(cv) = savepv(filename);
8338         CvDYNFILE_on(cv);
8339     }
8340     sv_setpv(MUTABLE_SV(cv), proto);
8341     if (interleave) LEAVE;
8342     return cv;
8343 }
8344
8345 CV *
8346 Perl_newSTUB(pTHX_ GV *gv, bool fake)
8347 {
8348     CV *cv = MUTABLE_CV(newSV_type(SVt_PVCV));
8349     GV *cvgv;
8350     PERL_ARGS_ASSERT_NEWSTUB;
8351     assert(!GvCVu(gv));
8352     GvCV_set(gv, cv);
8353     GvCVGEN(gv) = 0;
8354     if (!fake && HvENAME_HEK(GvSTASH(gv)))
8355         gv_method_changed(gv);
8356     if (SvFAKE(gv)) {
8357         cvgv = gv_fetchsv((SV *)gv, GV_ADDMULTI, SVt_PVCV);
8358         SvFAKE_off(cvgv);
8359     }
8360     else cvgv = gv;
8361     CvGV_set(cv, cvgv);
8362     CvFILE_set_from_cop(cv, PL_curcop);
8363     CvSTASH_set(cv, PL_curstash);
8364     GvMULTI_on(gv);
8365     return cv;
8366 }
8367
8368 /*
8369 =for apidoc U||newXS
8370
8371 Used by C<xsubpp> to hook up XSUBs as Perl subs.  I<filename> needs to be
8372 static storage, as it is used directly as CvFILE(), without a copy being made.
8373
8374 =cut
8375 */
8376
8377 CV *
8378 Perl_newXS(pTHX_ const char *name, XSUBADDR_t subaddr, const char *filename)
8379 {
8380     PERL_ARGS_ASSERT_NEWXS;
8381     return newXS_len_flags(
8382         name, name ? strlen(name) : 0, subaddr, filename, NULL, NULL, 0
8383     );
8384 }
8385
8386 void
8387 Perl_newFORM(pTHX_ I32 floor, OP *o, OP *block)
8388 {
8389     CV *cv;
8390
8391     GV *gv;
8392
8393     if (PL_parser && PL_parser->error_count) {
8394         op_free(block);
8395         goto finish;
8396     }
8397
8398     gv = o
8399         ? gv_fetchsv(cSVOPo->op_sv, GV_ADD, SVt_PVFM)
8400         : gv_fetchpvs("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVFM);
8401
8402     GvMULTI_on(gv);
8403     if ((cv = GvFORM(gv))) {
8404         if (ckWARN(WARN_REDEFINE)) {
8405             const line_t oldline = CopLINE(PL_curcop);
8406             if (PL_parser && PL_parser->copline != NOLINE)
8407                 CopLINE_set(PL_curcop, PL_parser->copline);
8408             if (o) {
8409                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
8410                             "Format %"SVf" redefined", SVfARG(cSVOPo->op_sv));
8411             } else {
8412                 /* diag_listed_as: Format %s redefined */
8413                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
8414                             "Format STDOUT redefined");
8415             }
8416             CopLINE_set(PL_curcop, oldline);
8417         }
8418         SvREFCNT_dec(cv);
8419     }
8420     cv = PL_compcv;
8421     GvFORM(gv) = (CV *)SvREFCNT_inc_simple_NN(cv);
8422     CvGV_set(cv, gv);
8423     CvFILE_set_from_cop(cv, PL_curcop);
8424
8425
8426     pad_tidy(padtidy_FORMAT);
8427     CvROOT(cv) = newUNOP(OP_LEAVEWRITE, 0, scalarseq(block));
8428     CvROOT(cv)->op_private |= OPpREFCOUNTED;
8429     OpREFCNT_set(CvROOT(cv), 1);
8430     CvSTART(cv) = LINKLIST(CvROOT(cv));
8431     CvROOT(cv)->op_next = 0;
8432     CALL_PEEP(CvSTART(cv));
8433     finalize_optree(CvROOT(cv));
8434     S_prune_chain_head(&CvSTART(cv));
8435     cv_forget_slab(cv);
8436
8437   finish:
8438     op_free(o);
8439     if (PL_parser)
8440         PL_parser->copline = NOLINE;
8441     LEAVE_SCOPE(floor);
8442 }
8443
8444 OP *
8445 Perl_newANONLIST(pTHX_ OP *o)
8446 {
8447     return convert(OP_ANONLIST, OPf_SPECIAL, o);
8448 }
8449
8450 OP *
8451 Perl_newANONHASH(pTHX_ OP *o)
8452 {
8453     return convert(OP_ANONHASH, OPf_SPECIAL, o);
8454 }
8455
8456 OP *
8457 Perl_newANONSUB(pTHX_ I32 floor, OP *proto, OP *block)
8458 {
8459     return newANONATTRSUB(floor, proto, NULL, block);
8460 }
8461
8462 OP *
8463 Perl_newANONATTRSUB(pTHX_ I32 floor, OP *proto, OP *attrs, OP *block)
8464 {
8465     return newUNOP(OP_REFGEN, 0,
8466         newSVOP(OP_ANONCODE, 0,
8467                 MUTABLE_SV(newATTRSUB(floor, 0, proto, attrs, block))));
8468 }
8469
8470 OP *
8471 Perl_oopsAV(pTHX_ OP *o)
8472 {
8473     dVAR;
8474
8475     PERL_ARGS_ASSERT_OOPSAV;
8476
8477     switch (o->op_type) {
8478     case OP_PADSV:
8479     case OP_PADHV:
8480         o->op_type = OP_PADAV;
8481         o->op_ppaddr = PL_ppaddr[OP_PADAV];
8482         return ref(o, OP_RV2AV);
8483
8484     case OP_RV2SV:
8485     case OP_RV2HV:
8486         o->op_type = OP_RV2AV;
8487         o->op_ppaddr = PL_ppaddr[OP_RV2AV];
8488         ref(o, OP_RV2AV);
8489         break;
8490
8491     default:
8492         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsAV");
8493         break;
8494     }
8495     return o;
8496 }
8497
8498 OP *
8499 Perl_oopsHV(pTHX_ OP *o)
8500 {
8501     dVAR;
8502
8503     PERL_ARGS_ASSERT_OOPSHV;
8504
8505     switch (o->op_type) {
8506     case OP_PADSV:
8507     case OP_PADAV:
8508         o->op_type = OP_PADHV;
8509         o->op_ppaddr = PL_ppaddr[OP_PADHV];
8510         return ref(o, OP_RV2HV);
8511
8512     case OP_RV2SV:
8513     case OP_RV2AV:
8514         o->op_type = OP_RV2HV;
8515         o->op_ppaddr = PL_ppaddr[OP_RV2HV];
8516         ref(o, OP_RV2HV);
8517         break;
8518
8519     default:
8520         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsHV");
8521         break;
8522     }
8523     return o;
8524 }
8525
8526 OP *
8527 Perl_newAVREF(pTHX_ OP *o)
8528 {
8529     dVAR;
8530
8531     PERL_ARGS_ASSERT_NEWAVREF;
8532
8533     if (o->op_type == OP_PADANY) {
8534         o->op_type = OP_PADAV;
8535         o->op_ppaddr = PL_ppaddr[OP_PADAV];
8536         return o;
8537     }
8538     else if ((o->op_type == OP_RV2AV || o->op_type == OP_PADAV)) {
8539         Perl_croak(aTHX_ "Can't use an array as a reference");
8540     }
8541     return newUNOP(OP_RV2AV, 0, scalar(o));
8542 }
8543
8544 OP *
8545 Perl_newGVREF(pTHX_ I32 type, OP *o)
8546 {
8547     if (type == OP_MAPSTART || type == OP_GREPSTART || type == OP_SORT)
8548         return newUNOP(OP_NULL, 0, o);
8549     return ref(newUNOP(OP_RV2GV, OPf_REF, o), type);
8550 }
8551
8552 OP *
8553 Perl_newHVREF(pTHX_ OP *o)
8554 {
8555     dVAR;
8556
8557     PERL_ARGS_ASSERT_NEWHVREF;
8558
8559     if (o->op_type == OP_PADANY) {
8560         o->op_type = OP_PADHV;
8561         o->op_ppaddr = PL_ppaddr[OP_PADHV];
8562         return o;
8563     }
8564     else if ((o->op_type == OP_RV2HV || o->op_type == OP_PADHV)) {
8565         Perl_croak(aTHX_ "Can't use a hash as a reference");
8566     }
8567     return newUNOP(OP_RV2HV, 0, scalar(o));
8568 }
8569
8570 OP *
8571 Perl_newCVREF(pTHX_ I32 flags, OP *o)
8572 {
8573     if (o->op_type == OP_PADANY) {
8574         dVAR;
8575         o->op_type = OP_PADCV;
8576         o->op_ppaddr = PL_ppaddr[OP_PADCV];
8577     }
8578     return newUNOP(OP_RV2CV, flags, scalar(o));
8579 }
8580
8581 OP *
8582 Perl_newSVREF(pTHX_ OP *o)
8583 {
8584     dVAR;
8585
8586     PERL_ARGS_ASSERT_NEWSVREF;
8587
8588     if (o->op_type == OP_PADANY) {
8589         o->op_type = OP_PADSV;
8590         o->op_ppaddr = PL_ppaddr[OP_PADSV];
8591         return o;
8592     }
8593     return newUNOP(OP_RV2SV, 0, scalar(o));
8594 }
8595
8596 /* Check routines. See the comments at the top of this file for details
8597  * on when these are called */
8598
8599 OP *
8600 Perl_ck_anoncode(pTHX_ OP *o)
8601 {
8602     PERL_ARGS_ASSERT_CK_ANONCODE;
8603
8604     cSVOPo->op_targ = pad_add_anon((CV*)cSVOPo->op_sv, o->op_type);
8605     cSVOPo->op_sv = NULL;
8606     return o;
8607 }
8608
8609 static void
8610 S_io_hints(pTHX_ OP *o)
8611 {
8612 #if O_BINARY != 0 || O_TEXT != 0
8613     HV * const table =
8614         PL_hints & HINT_LOCALIZE_HH ? GvHV(PL_hintgv) : NULL;;
8615     if (table) {
8616         SV **svp = hv_fetchs(table, "open_IN", FALSE);
8617         if (svp && *svp) {
8618             STRLEN len = 0;
8619             const char *d = SvPV_const(*svp, len);
8620             const I32 mode = mode_from_discipline(d, len);
8621             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
8622 #  if O_BINARY != 0
8623             if (mode & O_BINARY)
8624                 o->op_private |= OPpOPEN_IN_RAW;
8625 #  endif
8626 #  if O_TEXT != 0
8627             if (mode & O_TEXT)
8628                 o->op_private |= OPpOPEN_IN_CRLF;
8629 #  endif
8630         }
8631
8632         svp = hv_fetchs(table, "open_OUT", FALSE);
8633         if (svp && *svp) {
8634             STRLEN len = 0;
8635             const char *d = SvPV_const(*svp, len);
8636             const I32 mode = mode_from_discipline(d, len);
8637             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
8638 #  if O_BINARY != 0
8639             if (mode & O_BINARY)
8640                 o->op_private |= OPpOPEN_OUT_RAW;
8641 #  endif
8642 #  if O_TEXT != 0
8643             if (mode & O_TEXT)
8644                 o->op_private |= OPpOPEN_OUT_CRLF;
8645 #  endif
8646         }
8647     }
8648 #else
8649     PERL_UNUSED_CONTEXT;
8650     PERL_UNUSED_ARG(o);
8651 #endif
8652 }
8653
8654 OP *
8655 Perl_ck_backtick(pTHX_ OP *o)
8656 {
8657     GV *gv;
8658     OP *newop = NULL;
8659     OP *sibl;
8660     PERL_ARGS_ASSERT_CK_BACKTICK;
8661     /* qx and `` have a null pushmark; CORE::readpipe has only one kid. */
8662     if (o->op_flags & OPf_KIDS && (sibl = OP_SIBLING(cUNOPo->op_first))
8663      && (gv = gv_override("readpipe",8)))
8664     {
8665         /* detach rest of siblings from o and its first child */
8666         op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
8667         newop = S_new_entersubop(aTHX_ gv, sibl);
8668     }
8669     else if (!(o->op_flags & OPf_KIDS))
8670         newop = newUNOP(OP_BACKTICK, 0, newDEFSVOP());
8671     if (newop) {
8672         op_free(o);
8673         return newop;
8674     }
8675     S_io_hints(aTHX_ o);
8676     return o;
8677 }
8678
8679 OP *
8680 Perl_ck_bitop(pTHX_ OP *o)
8681 {
8682     PERL_ARGS_ASSERT_CK_BITOP;
8683
8684     o->op_private = (U8)(PL_hints & HINT_INTEGER);
8685     if (!(o->op_flags & OPf_STACKED) /* Not an assignment */
8686             && (o->op_type == OP_BIT_OR
8687              || o->op_type == OP_BIT_AND
8688              || o->op_type == OP_BIT_XOR))
8689     {
8690         const OP * const left = cBINOPo->op_first;
8691         const OP * const right = OP_SIBLING(left);
8692         if ((OP_IS_NUMCOMPARE(left->op_type) &&
8693                 (left->op_flags & OPf_PARENS) == 0) ||
8694             (OP_IS_NUMCOMPARE(right->op_type) &&
8695                 (right->op_flags & OPf_PARENS) == 0))
8696             Perl_ck_warner(aTHX_ packWARN(WARN_PRECEDENCE),
8697                            "Possible precedence problem on bitwise %c operator",
8698                            o->op_type == OP_BIT_OR ? '|'
8699                            : o->op_type == OP_BIT_AND ? '&' : '^'
8700                            );
8701     }
8702     return o;
8703 }
8704
8705 PERL_STATIC_INLINE bool
8706 is_dollar_bracket(pTHX_ const OP * const o)
8707 {
8708     const OP *kid;
8709     PERL_UNUSED_CONTEXT;
8710     return o->op_type == OP_RV2SV && o->op_flags & OPf_KIDS
8711         && (kid = cUNOPx(o)->op_first)
8712         && kid->op_type == OP_GV
8713         && strEQ(GvNAME(cGVOPx_gv(kid)), "[");
8714 }
8715
8716 OP *
8717 Perl_ck_cmp(pTHX_ OP *o)
8718 {
8719     PERL_ARGS_ASSERT_CK_CMP;
8720     if (ckWARN(WARN_SYNTAX)) {
8721         const OP *kid = cUNOPo->op_first;
8722         if (kid &&
8723             (
8724                 (   is_dollar_bracket(aTHX_ kid)
8725                  && OP_SIBLING(kid) && OP_SIBLING(kid)->op_type == OP_CONST
8726                 )
8727              || (   kid->op_type == OP_CONST
8728                  && (kid = OP_SIBLING(kid)) && is_dollar_bracket(aTHX_ kid)
8729                 )
8730            )
8731         )
8732             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
8733                         "$[ used in %s (did you mean $] ?)", OP_DESC(o));
8734     }
8735     return o;
8736 }
8737
8738 OP *
8739 Perl_ck_concat(pTHX_ OP *o)
8740 {
8741     const OP * const kid = cUNOPo->op_first;
8742
8743     PERL_ARGS_ASSERT_CK_CONCAT;
8744     PERL_UNUSED_CONTEXT;
8745
8746     if (kid->op_type == OP_CONCAT && !(kid->op_private & OPpTARGET_MY) &&
8747             !(kUNOP->op_first->op_flags & OPf_MOD))
8748         o->op_flags |= OPf_STACKED;
8749     return o;
8750 }
8751
8752 OP *
8753 Perl_ck_spair(pTHX_ OP *o)
8754 {
8755     dVAR;
8756
8757     PERL_ARGS_ASSERT_CK_SPAIR;
8758
8759     if (o->op_flags & OPf_KIDS) {
8760         OP* newop;
8761         OP* kid;
8762         OP* kidkid;
8763         const OPCODE type = o->op_type;
8764         o = modkids(ck_fun(o), type);
8765         kid    = cUNOPo->op_first;
8766         kidkid = kUNOP->op_first;
8767         newop = OP_SIBLING(kidkid);
8768         if (newop) {
8769             const OPCODE type = newop->op_type;
8770             if (OP_HAS_SIBLING(newop) || !(PL_opargs[type] & OA_RETSCALAR) ||
8771                     type == OP_PADAV || type == OP_PADHV ||
8772                     type == OP_RV2AV || type == OP_RV2HV)
8773                 return o;
8774         }
8775         /* excise first sibling */
8776         op_sibling_splice(kid, NULL, 1, NULL);
8777         op_free(kidkid);
8778     }
8779     /* transforms OP_REFGEN into OP_SREFGEN, OP_CHOP into OP_SCHOP,
8780      * and OP_CHOMP into OP_SCHOMP */
8781     o->op_ppaddr = PL_ppaddr[++o->op_type];
8782     return ck_fun(o);
8783 }
8784
8785 OP *
8786 Perl_ck_delete(pTHX_ OP *o)
8787 {
8788     PERL_ARGS_ASSERT_CK_DELETE;
8789
8790     o = ck_fun(o);
8791     o->op_private = 0;
8792     if (o->op_flags & OPf_KIDS) {
8793         OP * const kid = cUNOPo->op_first;
8794         switch (kid->op_type) {
8795         case OP_ASLICE:
8796             o->op_flags |= OPf_SPECIAL;
8797             /* FALLTHROUGH */
8798         case OP_HSLICE:
8799             o->op_private |= OPpSLICE;
8800             break;
8801         case OP_AELEM:
8802             o->op_flags |= OPf_SPECIAL;
8803             /* FALLTHROUGH */
8804         case OP_HELEM:
8805             break;
8806         case OP_KVASLICE:
8807             Perl_croak(aTHX_ "delete argument is index/value array slice,"
8808                              " use array slice");
8809         case OP_KVHSLICE:
8810             Perl_croak(aTHX_ "delete argument is key/value hash slice, use"
8811                              " hash slice");
8812         default:
8813             Perl_croak(aTHX_ "delete argument is not a HASH or ARRAY "
8814                              "element or slice");
8815         }
8816         if (kid->op_private & OPpLVAL_INTRO)
8817             o->op_private |= OPpLVAL_INTRO;
8818         op_null(kid);
8819     }
8820     return o;
8821 }
8822
8823 OP *
8824 Perl_ck_eof(pTHX_ OP *o)
8825 {
8826     PERL_ARGS_ASSERT_CK_EOF;
8827
8828     if (o->op_flags & OPf_KIDS) {
8829         OP *kid;
8830         if (cLISTOPo->op_first->op_type == OP_STUB) {
8831             OP * const newop
8832                 = newUNOP(o->op_type, OPf_SPECIAL, newGVOP(OP_GV, 0, PL_argvgv));
8833             op_free(o);
8834             o = newop;
8835         }
8836         o = ck_fun(o);
8837         kid = cLISTOPo->op_first;
8838         if (kid->op_type == OP_RV2GV)
8839             kid->op_private |= OPpALLOW_FAKE;
8840     }
8841     return o;
8842 }
8843
8844 OP *
8845 Perl_ck_eval(pTHX_ OP *o)
8846 {
8847     dVAR;
8848
8849     PERL_ARGS_ASSERT_CK_EVAL;
8850
8851     PL_hints |= HINT_BLOCK_SCOPE;
8852     if (o->op_flags & OPf_KIDS) {
8853         SVOP * const kid = (SVOP*)cUNOPo->op_first;
8854         assert(kid);
8855
8856         if (kid->op_type == OP_LINESEQ || kid->op_type == OP_STUB) {
8857             LOGOP *enter;
8858
8859             /* cut whole sibling chain free from o */
8860             op_sibling_splice(o, NULL, -1, NULL);
8861             op_free(o);
8862
8863             enter = S_alloc_LOGOP(aTHX_ OP_ENTERTRY, NULL, NULL);
8864             enter->op_ppaddr = PL_ppaddr[OP_ENTERTRY];
8865
8866             /* establish postfix order */
8867             enter->op_next = (OP*)enter;
8868
8869             o = op_prepend_elem(OP_LINESEQ, (OP*)enter, (OP*)kid);
8870             o->op_type = OP_LEAVETRY;
8871             o->op_ppaddr = PL_ppaddr[OP_LEAVETRY];
8872             enter->op_other = o;
8873             return o;
8874         }
8875         else {
8876             scalar((OP*)kid);
8877             PL_cv_has_eval = 1;
8878         }
8879     }
8880     else {
8881         const U8 priv = o->op_private;
8882         op_free(o);
8883         /* the newUNOP will recursively call ck_eval(), which will handle
8884          * all the stuff at the end of this function, like adding
8885          * OP_HINTSEVAL
8886          */
8887         return newUNOP(OP_ENTEREVAL, priv <<8, newDEFSVOP());
8888     }
8889     o->op_targ = (PADOFFSET)PL_hints;
8890     if (o->op_private & OPpEVAL_BYTES) o->op_targ &= ~HINT_UTF8;
8891     if ((PL_hints & HINT_LOCALIZE_HH) != 0
8892      && !(o->op_private & OPpEVAL_COPHH) && GvHV(PL_hintgv)) {
8893         /* Store a copy of %^H that pp_entereval can pick up. */
8894         OP *hhop = newSVOP(OP_HINTSEVAL, 0,
8895                            MUTABLE_SV(hv_copy_hints_hv(GvHV(PL_hintgv))));
8896         /* append hhop to only child  */
8897         op_sibling_splice(o, cUNOPo->op_first, 0, hhop);
8898
8899         o->op_private |= OPpEVAL_HAS_HH;
8900     }
8901     if (!(o->op_private & OPpEVAL_BYTES)
8902          && FEATURE_UNIEVAL_IS_ENABLED)
8903             o->op_private |= OPpEVAL_UNICODE;
8904     return o;
8905 }
8906
8907 OP *
8908 Perl_ck_exec(pTHX_ OP *o)
8909 {
8910     PERL_ARGS_ASSERT_CK_EXEC;
8911
8912     if (o->op_flags & OPf_STACKED) {
8913         OP *kid;
8914         o = ck_fun(o);
8915         kid = OP_SIBLING(cUNOPo->op_first);
8916         if (kid->op_type == OP_RV2GV)
8917             op_null(kid);
8918     }
8919     else
8920         o = listkids(o);
8921     return o;
8922 }
8923
8924 OP *
8925 Perl_ck_exists(pTHX_ OP *o)
8926 {
8927     PERL_ARGS_ASSERT_CK_EXISTS;
8928
8929     o = ck_fun(o);
8930     if (o->op_flags & OPf_KIDS) {
8931         OP * const kid = cUNOPo->op_first;
8932         if (kid->op_type == OP_ENTERSUB) {
8933             (void) ref(kid, o->op_type);
8934             if (kid->op_type != OP_RV2CV
8935                         && !(PL_parser && PL_parser->error_count))
8936                 Perl_croak(aTHX_
8937                           "exists argument is not a subroutine name");
8938             o->op_private |= OPpEXISTS_SUB;
8939         }
8940         else if (kid->op_type == OP_AELEM)
8941             o->op_flags |= OPf_SPECIAL;
8942         else if (kid->op_type != OP_HELEM)
8943             Perl_croak(aTHX_ "exists argument is not a HASH or ARRAY "
8944                              "element or a subroutine");
8945         op_null(kid);
8946     }
8947     return o;
8948 }
8949
8950 OP *
8951 Perl_ck_rvconst(pTHX_ OP *o)
8952 {
8953     dVAR;
8954     SVOP * const kid = (SVOP*)cUNOPo->op_first;
8955
8956     PERL_ARGS_ASSERT_CK_RVCONST;
8957
8958     o->op_private |= (PL_hints & HINT_STRICT_REFS);
8959
8960     if (kid->op_type == OP_CONST) {
8961         int iscv;
8962         GV *gv;
8963         SV * const kidsv = kid->op_sv;
8964
8965         /* Is it a constant from cv_const_sv()? */
8966         if ((SvROK(kidsv) || isGV_with_GP(kidsv)) && SvREADONLY(kidsv)) {
8967             return o;
8968         }
8969         if (SvTYPE(kidsv) == SVt_PVAV) return o;
8970         if ((o->op_private & HINT_STRICT_REFS) && (kid->op_private & OPpCONST_BARE)) {
8971             const char *badthing;
8972             switch (o->op_type) {
8973             case OP_RV2SV:
8974                 badthing = "a SCALAR";
8975                 break;
8976             case OP_RV2AV:
8977                 badthing = "an ARRAY";
8978                 break;
8979             case OP_RV2HV:
8980                 badthing = "a HASH";
8981                 break;
8982             default:
8983                 badthing = NULL;
8984                 break;
8985             }
8986             if (badthing)
8987                 Perl_croak(aTHX_
8988                            "Can't use bareword (\"%"SVf"\") as %s ref while \"strict refs\" in use",
8989                            SVfARG(kidsv), badthing);
8990         }
8991         /*
8992          * This is a little tricky.  We only want to add the symbol if we
8993          * didn't add it in the lexer.  Otherwise we get duplicate strict
8994          * warnings.  But if we didn't add it in the lexer, we must at
8995          * least pretend like we wanted to add it even if it existed before,
8996          * or we get possible typo warnings.  OPpCONST_ENTERED says
8997          * whether the lexer already added THIS instance of this symbol.
8998          */
8999         iscv = o->op_type == OP_RV2CV ? GV_NOEXPAND|GV_ADDMULTI : 0;
9000         gv = gv_fetchsv(kidsv,
9001                 o->op_type == OP_RV2CV
9002                         && o->op_private & OPpMAY_RETURN_CONSTANT
9003                     ? GV_NOEXPAND
9004                     : iscv | !(kid->op_private & OPpCONST_ENTERED),
9005                 iscv
9006                     ? SVt_PVCV
9007                     : o->op_type == OP_RV2SV
9008                         ? SVt_PV
9009                         : o->op_type == OP_RV2AV
9010                             ? SVt_PVAV
9011                             : o->op_type == OP_RV2HV
9012                                 ? SVt_PVHV
9013                                 : SVt_PVGV);
9014         if (gv) {
9015             if (!isGV(gv)) {
9016                 assert(iscv);
9017                 assert(SvROK(gv));
9018                 if (!(o->op_private & OPpMAY_RETURN_CONSTANT)
9019                   && SvTYPE(SvRV(gv)) != SVt_PVCV)
9020                     gv_fetchsv(kidsv, GV_ADDMULTI, SVt_PVCV);
9021             }
9022             kid->op_type = OP_GV;
9023             SvREFCNT_dec(kid->op_sv);
9024 #ifdef USE_ITHREADS
9025             /* XXX hack: dependence on sizeof(PADOP) <= sizeof(SVOP) */
9026             assert (sizeof(PADOP) <= sizeof(SVOP));
9027             kPADOP->op_padix = pad_alloc(OP_GV, SVf_READONLY);
9028             SvREFCNT_dec(PAD_SVl(kPADOP->op_padix));
9029             if (isGV(gv)) GvIN_PAD_on(gv);
9030             PAD_SETSV(kPADOP->op_padix, MUTABLE_SV(SvREFCNT_inc_simple_NN(gv)));
9031 #else
9032             kid->op_sv = SvREFCNT_inc_simple_NN(gv);
9033 #endif
9034             kid->op_private = 0;
9035             kid->op_ppaddr = PL_ppaddr[OP_GV];
9036             /* FAKE globs in the symbol table cause weird bugs (#77810) */
9037             SvFAKE_off(gv);
9038         }
9039     }
9040     return o;
9041 }
9042
9043 OP *
9044 Perl_ck_ftst(pTHX_ OP *o)
9045 {
9046     dVAR;
9047     const I32 type = o->op_type;
9048
9049     PERL_ARGS_ASSERT_CK_FTST;
9050
9051     if (o->op_flags & OPf_REF) {
9052         NOOP;
9053     }
9054     else if (o->op_flags & OPf_KIDS && cUNOPo->op_first->op_type != OP_STUB) {
9055         SVOP * const kid = (SVOP*)cUNOPo->op_first;
9056         const OPCODE kidtype = kid->op_type;
9057
9058         if (kidtype == OP_CONST && (kid->op_private & OPpCONST_BARE)
9059          && !kid->op_folded) {
9060             OP * const newop = newGVOP(type, OPf_REF,
9061                 gv_fetchsv(kid->op_sv, GV_ADD, SVt_PVIO));
9062             op_free(o);
9063             return newop;
9064         }
9065         if ((PL_hints & HINT_FILETEST_ACCESS) && OP_IS_FILETEST_ACCESS(o->op_type))
9066             o->op_private |= OPpFT_ACCESS;
9067         if (PL_check[kidtype] == Perl_ck_ftst
9068                 && kidtype != OP_STAT && kidtype != OP_LSTAT) {
9069             o->op_private |= OPpFT_STACKED;
9070             kid->op_private |= OPpFT_STACKING;
9071             if (kidtype == OP_FTTTY && (
9072                    !(kid->op_private & OPpFT_STACKED)
9073                 || kid->op_private & OPpFT_AFTER_t
9074                ))
9075                 o->op_private |= OPpFT_AFTER_t;
9076         }
9077     }
9078     else {
9079         op_free(o);
9080         if (type == OP_FTTTY)
9081             o = newGVOP(type, OPf_REF, PL_stdingv);
9082         else
9083             o = newUNOP(type, 0, newDEFSVOP());
9084     }
9085     return o;
9086 }
9087
9088 OP *
9089 Perl_ck_fun(pTHX_ OP *o)
9090 {
9091     const int type = o->op_type;
9092     I32 oa = PL_opargs[type] >> OASHIFT;
9093
9094     PERL_ARGS_ASSERT_CK_FUN;
9095
9096     if (o->op_flags & OPf_STACKED) {
9097         if ((oa & OA_OPTIONAL) && (oa >> 4) && !((oa >> 4) & OA_OPTIONAL))
9098             oa &= ~OA_OPTIONAL;
9099         else
9100             return no_fh_allowed(o);
9101     }
9102
9103     if (o->op_flags & OPf_KIDS) {
9104         OP *prev_kid = NULL;
9105         OP *kid = cLISTOPo->op_first;
9106         I32 numargs = 0;
9107         bool seen_optional = FALSE;
9108
9109         if (kid->op_type == OP_PUSHMARK ||
9110             (kid->op_type == OP_NULL && kid->op_targ == OP_PUSHMARK))
9111         {
9112             prev_kid = kid;
9113             kid = OP_SIBLING(kid);
9114         }
9115         if (kid && kid->op_type == OP_COREARGS) {
9116             bool optional = FALSE;
9117             while (oa) {
9118                 numargs++;
9119                 if (oa & OA_OPTIONAL) optional = TRUE;
9120                 oa = oa >> 4;
9121             }
9122             if (optional) o->op_private |= numargs;
9123             return o;
9124         }
9125
9126         while (oa) {
9127             if (oa & OA_OPTIONAL || (oa & 7) == OA_LIST) {
9128                 if (!kid && !seen_optional && PL_opargs[type] & OA_DEFGV) {
9129                     kid = newDEFSVOP();
9130                     /* append kid to chain */
9131                     op_sibling_splice(o, prev_kid, 0, kid);
9132                 }
9133                 seen_optional = TRUE;
9134             }
9135             if (!kid) break;
9136
9137             numargs++;
9138             switch (oa & 7) {
9139             case OA_SCALAR:
9140                 /* list seen where single (scalar) arg expected? */
9141                 if (numargs == 1 && !(oa >> 4)
9142                     && kid->op_type == OP_LIST && type != OP_SCALAR)
9143                 {
9144                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
9145                 }
9146                 if (type != OP_DELETE) scalar(kid);
9147                 break;
9148             case OA_LIST:
9149                 if (oa < 16) {
9150                     kid = 0;
9151                     continue;
9152                 }
9153                 else
9154                     list(kid);
9155                 break;
9156             case OA_AVREF:
9157                 if ((type == OP_PUSH || type == OP_UNSHIFT)
9158                     && !OP_HAS_SIBLING(kid))
9159                     Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
9160                                    "Useless use of %s with no values",
9161                                    PL_op_desc[type]);
9162
9163                 if (kid->op_type == OP_CONST
9164                       && (  !SvROK(cSVOPx_sv(kid)) 
9165                          || SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV  )
9166                         )
9167                     bad_type_pv(numargs, "array", PL_op_desc[type], 0, kid);
9168                 /* Defer checks to run-time if we have a scalar arg */
9169                 if (kid->op_type == OP_RV2AV || kid->op_type == OP_PADAV)
9170                     op_lvalue(kid, type);
9171                 else {
9172                     scalar(kid);
9173                     /* diag_listed_as: push on reference is experimental */
9174                     Perl_ck_warner_d(aTHX_
9175                                      packWARN(WARN_EXPERIMENTAL__AUTODEREF),
9176                                     "%s on reference is experimental",
9177                                      PL_op_desc[type]);
9178                 }
9179                 break;
9180             case OA_HVREF:
9181                 if (kid->op_type != OP_RV2HV && kid->op_type != OP_PADHV)
9182                     bad_type_pv(numargs, "hash", PL_op_desc[type], 0, kid);
9183                 op_lvalue(kid, type);
9184                 break;
9185             case OA_CVREF:
9186                 {
9187                     /* replace kid with newop in chain */
9188                     OP * const newop =
9189                         S_op_sibling_newUNOP(aTHX_ o, prev_kid, OP_NULL, 0);
9190                     newop->op_next = newop;
9191                     kid = newop;
9192                 }
9193                 break;
9194             case OA_FILEREF:
9195                 if (kid->op_type != OP_GV && kid->op_type != OP_RV2GV) {
9196                     if (kid->op_type == OP_CONST &&
9197                         (kid->op_private & OPpCONST_BARE))
9198                     {
9199                         OP * const newop = newGVOP(OP_GV, 0,
9200                             gv_fetchsv(((SVOP*)kid)->op_sv, GV_ADD, SVt_PVIO));
9201                         /* replace kid with newop in chain */
9202                         op_sibling_splice(o, prev_kid, 1, newop);
9203                         op_free(kid);
9204                         kid = newop;
9205                     }
9206                     else if (kid->op_type == OP_READLINE) {
9207                         /* neophyte patrol: open(<FH>), close(<FH>) etc. */
9208                         bad_type_pv(numargs, "HANDLE", OP_DESC(o), 0, kid);
9209                     }
9210                     else {
9211                         I32 flags = OPf_SPECIAL;
9212                         I32 priv = 0;
9213                         PADOFFSET targ = 0;
9214
9215                         /* is this op a FH constructor? */
9216                         if (is_handle_constructor(o,numargs)) {
9217                             const char *name = NULL;
9218                             STRLEN len = 0;
9219                             U32 name_utf8 = 0;
9220                             bool want_dollar = TRUE;
9221
9222                             flags = 0;
9223                             /* Set a flag to tell rv2gv to vivify
9224                              * need to "prove" flag does not mean something
9225                              * else already - NI-S 1999/05/07
9226                              */
9227                             priv = OPpDEREF;
9228                             if (kid->op_type == OP_PADSV) {
9229                                 SV *const namesv
9230                                     = PAD_COMPNAME_SV(kid->op_targ);
9231                                 name = SvPV_const(namesv, len);
9232                                 name_utf8 = SvUTF8(namesv);
9233                             }
9234                             else if (kid->op_type == OP_RV2SV
9235                                      && kUNOP->op_first->op_type == OP_GV)
9236                             {
9237                                 GV * const gv = cGVOPx_gv(kUNOP->op_first);
9238                                 name = GvNAME(gv);
9239                                 len = GvNAMELEN(gv);
9240                                 name_utf8 = GvNAMEUTF8(gv) ? SVf_UTF8 : 0;
9241                             }
9242                             else if (kid->op_type == OP_AELEM
9243                                      || kid->op_type == OP_HELEM)
9244                             {
9245                                  OP *firstop;
9246                                  OP *op = ((BINOP*)kid)->op_first;
9247                                  name = NULL;
9248                                  if (op) {
9249                                       SV *tmpstr = NULL;
9250                                       const char * const a =
9251                                            kid->op_type == OP_AELEM ?
9252                                            "[]" : "{}";
9253                                       if (((op->op_type == OP_RV2AV) ||
9254                                            (op->op_type == OP_RV2HV)) &&
9255                                           (firstop = ((UNOP*)op)->op_first) &&
9256                                           (firstop->op_type == OP_GV)) {
9257                                            /* packagevar $a[] or $h{} */
9258                                            GV * const gv = cGVOPx_gv(firstop);
9259                                            if (gv)
9260                                                 tmpstr =
9261                                                      Perl_newSVpvf(aTHX_
9262                                                                    "%s%c...%c",
9263                                                                    GvNAME(gv),
9264                                                                    a[0], a[1]);
9265                                       }
9266                                       else if (op->op_type == OP_PADAV
9267                                                || op->op_type == OP_PADHV) {
9268                                            /* lexicalvar $a[] or $h{} */
9269                                            const char * const padname =
9270                                                 PAD_COMPNAME_PV(op->op_targ);
9271                                            if (padname)
9272                                                 tmpstr =
9273                                                      Perl_newSVpvf(aTHX_
9274                                                                    "%s%c...%c",
9275                                                                    padname + 1,
9276                                                                    a[0], a[1]);
9277                                       }
9278                                       if (tmpstr) {
9279                                            name = SvPV_const(tmpstr, len);
9280                                            name_utf8 = SvUTF8(tmpstr);
9281                                            sv_2mortal(tmpstr);
9282                                       }
9283                                  }
9284                                  if (!name) {
9285                                       name = "__ANONIO__";
9286                                       len = 10;
9287                                       want_dollar = FALSE;
9288                                  }
9289                                  op_lvalue(kid, type);
9290                             }
9291                             if (name) {
9292                                 SV *namesv;
9293                                 targ = pad_alloc(OP_RV2GV, SVf_READONLY);
9294                                 namesv = PAD_SVl(targ);
9295                                 if (want_dollar && *name != '$')
9296                                     sv_setpvs(namesv, "$");
9297                                 else
9298                                     sv_setpvs(namesv, "");
9299                                 sv_catpvn(namesv, name, len);
9300                                 if ( name_utf8 ) SvUTF8_on(namesv);
9301                             }
9302                         }
9303                         scalar(kid);
9304                         kid = S_op_sibling_newUNOP(aTHX_ o, prev_kid,
9305                                     OP_RV2GV, flags);
9306                         kid->op_targ = targ;
9307                         kid->op_private |= priv;
9308                     }
9309                 }
9310                 scalar(kid);
9311                 break;
9312             case OA_SCALARREF:
9313                 if ((type == OP_UNDEF || type == OP_POS)
9314                     && numargs == 1 && !(oa >> 4)
9315                     && kid->op_type == OP_LIST)
9316                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
9317                 op_lvalue(scalar(kid), type);
9318                 break;
9319             }
9320             oa >>= 4;
9321             prev_kid = kid;
9322             kid = OP_SIBLING(kid);
9323         }
9324         /* FIXME - should the numargs or-ing move after the too many
9325          * arguments check? */
9326         o->op_private |= numargs;
9327         if (kid)
9328             return too_many_arguments_pv(o,OP_DESC(o), 0);
9329         listkids(o);
9330     }
9331     else if (PL_opargs[type] & OA_DEFGV) {
9332         /* Ordering of these two is important to keep f_map.t passing.  */
9333         op_free(o);
9334         return newUNOP(type, 0, newDEFSVOP());
9335     }
9336
9337     if (oa) {
9338         while (oa & OA_OPTIONAL)
9339             oa >>= 4;
9340         if (oa && oa != OA_LIST)
9341             return too_few_arguments_pv(o,OP_DESC(o), 0);
9342     }
9343     return o;
9344 }
9345
9346 OP *
9347 Perl_ck_glob(pTHX_ OP *o)
9348 {
9349     GV *gv;
9350
9351     PERL_ARGS_ASSERT_CK_GLOB;
9352
9353     o = ck_fun(o);
9354     if ((o->op_flags & OPf_KIDS) && !OP_HAS_SIBLING(cLISTOPo->op_first))
9355         op_append_elem(OP_GLOB, o, newDEFSVOP()); /* glob() => glob($_) */
9356
9357     if (!(o->op_flags & OPf_SPECIAL) && (gv = gv_override("glob", 4)))
9358     {
9359         /* convert
9360          *     glob
9361          *       \ null - const(wildcard)
9362          * into
9363          *     null
9364          *       \ enter
9365          *            \ list
9366          *                 \ mark - glob - rv2cv
9367          *                             |        \ gv(CORE::GLOBAL::glob)
9368          *                             |
9369          *                              \ null - const(wildcard)
9370          */
9371         o->op_flags |= OPf_SPECIAL;
9372         o->op_targ = pad_alloc(OP_GLOB, SVs_PADTMP);
9373         o = S_new_entersubop(aTHX_ gv, o);
9374         o = newUNOP(OP_NULL, 0, o);
9375         o->op_targ = OP_GLOB; /* hint at what it used to be: eg in newWHILEOP */
9376         return o;
9377     }
9378     else o->op_flags &= ~OPf_SPECIAL;
9379 #if !defined(PERL_EXTERNAL_GLOB)
9380     if (!PL_globhook) {
9381         ENTER;
9382         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
9383                                newSVpvs("File::Glob"), NULL, NULL, NULL);
9384         LEAVE;
9385     }
9386 #endif /* !PERL_EXTERNAL_GLOB */
9387     gv = (GV *)newSV(0);
9388     gv_init(gv, 0, "", 0, 0);
9389     gv_IOadd(gv);
9390     op_append_elem(OP_GLOB, o, newGVOP(OP_GV, 0, gv));
9391     SvREFCNT_dec_NN(gv); /* newGVOP increased it */
9392     scalarkids(o);
9393     return o;
9394 }
9395
9396 OP *
9397 Perl_ck_grep(pTHX_ OP *o)
9398 {
9399     dVAR;
9400     LOGOP *gwop;
9401     OP *kid;
9402     const OPCODE type = o->op_type == OP_GREPSTART ? OP_GREPWHILE : OP_MAPWHILE;
9403     PADOFFSET offset;
9404
9405     PERL_ARGS_ASSERT_CK_GREP;
9406
9407     o->op_ppaddr = PL_ppaddr[OP_GREPSTART];
9408     /* don't allocate gwop here, as we may leak it if PL_parser->error_count > 0 */
9409
9410     if (o->op_flags & OPf_STACKED) {
9411         kid = cUNOPx(OP_SIBLING(cLISTOPo->op_first))->op_first;
9412         if (kid->op_type != OP_SCOPE && kid->op_type != OP_LEAVE)
9413             return no_fh_allowed(o);
9414         o->op_flags &= ~OPf_STACKED;
9415     }
9416     kid = OP_SIBLING(cLISTOPo->op_first);
9417     if (type == OP_MAPWHILE)
9418         list(kid);
9419     else
9420         scalar(kid);
9421     o = ck_fun(o);
9422     if (PL_parser && PL_parser->error_count)
9423         return o;
9424     kid = OP_SIBLING(cLISTOPo->op_first);
9425     if (kid->op_type != OP_NULL)
9426         Perl_croak(aTHX_ "panic: ck_grep, type=%u", (unsigned) kid->op_type);
9427     kid = kUNOP->op_first;
9428
9429     gwop = S_alloc_LOGOP(aTHX_ type, o, LINKLIST(kid));
9430     gwop->op_ppaddr = PL_ppaddr[type];
9431     kid->op_next = (OP*)gwop;
9432     offset = pad_findmy_pvs("$_", 0);
9433     if (offset == NOT_IN_PAD || PAD_COMPNAME_FLAGS_isOUR(offset)) {
9434         o->op_private = gwop->op_private = 0;
9435         gwop->op_targ = pad_alloc(type, SVs_PADTMP);
9436     }
9437     else {
9438         o->op_private = gwop->op_private = OPpGREP_LEX;
9439         gwop->op_targ = o->op_targ = offset;
9440     }
9441
9442     kid = OP_SIBLING(cLISTOPo->op_first);
9443     for (kid = OP_SIBLING(kid); kid; kid = OP_SIBLING(kid))
9444         op_lvalue(kid, OP_GREPSTART);
9445
9446     return (OP*)gwop;
9447 }
9448
9449 OP *
9450 Perl_ck_index(pTHX_ OP *o)
9451 {
9452     PERL_ARGS_ASSERT_CK_INDEX;
9453
9454     if (o->op_flags & OPf_KIDS) {
9455         OP *kid = OP_SIBLING(cLISTOPo->op_first);       /* get past pushmark */
9456         if (kid)
9457             kid = OP_SIBLING(kid);                      /* get past "big" */
9458         if (kid && kid->op_type == OP_CONST) {
9459             const bool save_taint = TAINT_get;
9460             SV *sv = kSVOP->op_sv;
9461             if ((!SvPOK(sv) || SvNIOKp(sv)) && SvOK(sv) && !SvROK(sv)) {
9462                 sv = newSV(0);
9463                 sv_copypv(sv, kSVOP->op_sv);
9464                 SvREFCNT_dec_NN(kSVOP->op_sv);
9465                 kSVOP->op_sv = sv;
9466             }
9467             if (SvOK(sv)) fbm_compile(sv, 0);
9468             TAINT_set(save_taint);
9469 #ifdef NO_TAINT_SUPPORT
9470             PERL_UNUSED_VAR(save_taint);
9471 #endif
9472         }
9473     }
9474     return ck_fun(o);
9475 }
9476
9477 OP *
9478 Perl_ck_lfun(pTHX_ OP *o)
9479 {
9480     const OPCODE type = o->op_type;
9481
9482     PERL_ARGS_ASSERT_CK_LFUN;
9483
9484     return modkids(ck_fun(o), type);
9485 }
9486
9487 OP *
9488 Perl_ck_defined(pTHX_ OP *o)            /* 19990527 MJD */
9489 {
9490     PERL_ARGS_ASSERT_CK_DEFINED;
9491
9492     if ((o->op_flags & OPf_KIDS)) {
9493         switch (cUNOPo->op_first->op_type) {
9494         case OP_RV2AV:
9495         case OP_PADAV:
9496             Perl_croak(aTHX_ "Can't use 'defined(@array)'"
9497                              " (Maybe you should just omit the defined()?)");
9498         break;
9499         case OP_RV2HV:
9500         case OP_PADHV:
9501             Perl_croak(aTHX_ "Can't use 'defined(%%hash)'"
9502                              " (Maybe you should just omit the defined()?)");
9503             break;
9504         default:
9505             /* no warning */
9506             break;
9507         }
9508     }
9509     return ck_rfun(o);
9510 }
9511
9512 OP *
9513 Perl_ck_readline(pTHX_ OP *o)
9514 {
9515     PERL_ARGS_ASSERT_CK_READLINE;
9516
9517     if (o->op_flags & OPf_KIDS) {
9518          OP *kid = cLISTOPo->op_first;
9519          if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
9520     }
9521     else {
9522         OP * const newop
9523             = newUNOP(OP_READLINE, 0, newGVOP(OP_GV, 0, PL_argvgv));
9524         op_free(o);
9525         return newop;
9526     }
9527     return o;
9528 }
9529
9530 OP *
9531 Perl_ck_rfun(pTHX_ OP *o)
9532 {
9533     const OPCODE type = o->op_type;
9534
9535     PERL_ARGS_ASSERT_CK_RFUN;
9536
9537     return refkids(ck_fun(o), type);
9538 }
9539
9540 OP *
9541 Perl_ck_listiob(pTHX_ OP *o)
9542 {
9543     OP *kid;
9544
9545     PERL_ARGS_ASSERT_CK_LISTIOB;
9546
9547     kid = cLISTOPo->op_first;
9548     if (!kid) {
9549         o = force_list(o, 1);
9550         kid = cLISTOPo->op_first;
9551     }
9552     if (kid->op_type == OP_PUSHMARK)
9553         kid = OP_SIBLING(kid);
9554     if (kid && o->op_flags & OPf_STACKED)
9555         kid = OP_SIBLING(kid);
9556     else if (kid && !OP_HAS_SIBLING(kid)) {             /* print HANDLE; */
9557         if (kid->op_type == OP_CONST && kid->op_private & OPpCONST_BARE
9558          && !kid->op_folded) {
9559             o->op_flags |= OPf_STACKED; /* make it a filehandle */
9560             scalar(kid);
9561             /* replace old const op with new OP_RV2GV parent */
9562             kid = S_op_sibling_newUNOP(aTHX_ o, cLISTOPo->op_first,
9563                                         OP_RV2GV, OPf_REF);
9564             kid = OP_SIBLING(kid);
9565         }
9566     }
9567
9568     if (!kid)
9569         op_append_elem(o->op_type, o, newDEFSVOP());
9570
9571     if (o->op_type == OP_PRTF) return modkids(listkids(o), OP_PRTF);
9572     return listkids(o);
9573 }
9574
9575 OP *
9576 Perl_ck_smartmatch(pTHX_ OP *o)
9577 {
9578     dVAR;
9579     PERL_ARGS_ASSERT_CK_SMARTMATCH;
9580     if (0 == (o->op_flags & OPf_SPECIAL)) {
9581         OP *first  = cBINOPo->op_first;
9582         OP *second = OP_SIBLING(first);
9583         
9584         /* Implicitly take a reference to an array or hash */
9585
9586         /* remove the original two siblings, then add back the
9587          * (possibly different) first and second sibs.
9588          */
9589         op_sibling_splice(o, NULL, 1, NULL);
9590         op_sibling_splice(o, NULL, 1, NULL);
9591         first  = ref_array_or_hash(first);
9592         second = ref_array_or_hash(second);
9593         op_sibling_splice(o, NULL, 0, second);
9594         op_sibling_splice(o, NULL, 0, first);
9595         
9596         /* Implicitly take a reference to a regular expression */
9597         if (first->op_type == OP_MATCH) {
9598             first->op_type = OP_QR;
9599             first->op_ppaddr = PL_ppaddr[OP_QR];
9600         }
9601         if (second->op_type == OP_MATCH) {
9602             second->op_type = OP_QR;
9603             second->op_ppaddr = PL_ppaddr[OP_QR];
9604         }
9605     }
9606     
9607     return o;
9608 }
9609
9610
9611 OP *
9612 Perl_ck_sassign(pTHX_ OP *o)
9613 {
9614     dVAR;
9615     OP * const kid = cLISTOPo->op_first;
9616
9617     PERL_ARGS_ASSERT_CK_SASSIGN;
9618
9619     /* has a disposable target? */
9620     if ((PL_opargs[kid->op_type] & OA_TARGLEX)
9621         && !(kid->op_flags & OPf_STACKED)
9622         /* Cannot steal the second time! */
9623         && !(kid->op_private & OPpTARGET_MY)
9624         )
9625     {
9626         OP * const kkid = OP_SIBLING(kid);
9627
9628         /* Can just relocate the target. */
9629         if (kkid && kkid->op_type == OP_PADSV
9630             && !(kkid->op_private & OPpLVAL_INTRO))
9631         {
9632             kid->op_targ = kkid->op_targ;
9633             kkid->op_targ = 0;
9634             /* Now we do not need PADSV and SASSIGN.
9635              * first replace the PADSV with OP_SIBLING(o), then
9636              * detach kid and OP_SIBLING(o) from o */
9637             op_sibling_splice(o, kid, 1, OP_SIBLING(o));
9638             op_sibling_splice(o, NULL, -1, NULL);
9639             op_free(o);
9640             op_free(kkid);
9641             kid->op_private |= OPpTARGET_MY;    /* Used for context settings */
9642             return kid;
9643         }
9644     }
9645     if (OP_HAS_SIBLING(kid)) {
9646         OP *kkid = OP_SIBLING(kid);
9647         /* For state variable assignment, kkid is a list op whose op_last
9648            is a padsv. */
9649         if ((kkid->op_type == OP_PADSV ||
9650              (OP_TYPE_IS_OR_WAS(kkid, OP_LIST) &&
9651               (kkid = cLISTOPx(kkid)->op_last)->op_type == OP_PADSV
9652              )
9653             )
9654                 && (kkid->op_private & OPpLVAL_INTRO)
9655                 && SvPAD_STATE(PAD_COMPNAME_SV(kkid->op_targ))) {
9656             const PADOFFSET target = kkid->op_targ;
9657             OP *const other = newOP(OP_PADSV,
9658                                     kkid->op_flags
9659                                     | ((kkid->op_private & ~OPpLVAL_INTRO) << 8));
9660             OP *const first = newOP(OP_NULL, 0);
9661             OP *const nullop = newCONDOP(0, first, o, other);
9662             OP *const condop = first->op_next;
9663             /* hijacking PADSTALE for uninitialized state variables */
9664             SvPADSTALE_on(PAD_SVl(target));
9665
9666             condop->op_type = OP_ONCE;
9667             condop->op_ppaddr = PL_ppaddr[OP_ONCE];
9668             condop->op_targ = target;
9669             other->op_targ = target;
9670
9671             /* Because we change the type of the op here, we will skip the
9672                assignment binop->op_last = OP_SIBLING(binop->op_first); at the
9673                end of Perl_newBINOP(). So need to do it here. */
9674             cBINOPo->op_last = OP_SIBLING(cBINOPo->op_first);
9675             cBINOPo->op_first->op_lastsib = 0;
9676             cBINOPo->op_last ->op_lastsib = 1;
9677 #ifdef PERL_OP_PARENT
9678             cBINOPo->op_last->op_sibling = o;
9679 #endif
9680             return nullop;
9681         }
9682     }
9683     return o;
9684 }
9685
9686 OP *
9687 Perl_ck_match(pTHX_ OP *o)
9688 {
9689     PERL_ARGS_ASSERT_CK_MATCH;
9690
9691     if (o->op_type != OP_QR && PL_compcv) {
9692         const PADOFFSET offset = pad_findmy_pvs("$_", 0);
9693         if (offset != NOT_IN_PAD && !(PAD_COMPNAME_FLAGS_isOUR(offset))) {
9694             o->op_targ = offset;
9695             o->op_private |= OPpTARGET_MY;
9696         }
9697     }
9698     if (o->op_type == OP_MATCH || o->op_type == OP_QR)
9699         o->op_private |= OPpRUNTIME;
9700     return o;
9701 }
9702
9703 OP *
9704 Perl_ck_method(pTHX_ OP *o)
9705 {
9706     OP * const kid = cUNOPo->op_first;
9707
9708     PERL_ARGS_ASSERT_CK_METHOD;
9709
9710     if (kid->op_type == OP_CONST) {
9711         SV* sv = kSVOP->op_sv;
9712         const char * const method = SvPVX_const(sv);
9713         if (!(strchr(method, ':') || strchr(method, '\''))) {
9714             OP *cmop;
9715             if (!SvIsCOW_shared_hash(sv)) {
9716                 sv = newSVpvn_share(method, SvUTF8(sv) ? -(I32)SvCUR(sv) : (I32)SvCUR(sv), 0);
9717             }
9718             else {
9719                 kSVOP->op_sv = NULL;
9720             }
9721             cmop = newSVOP(OP_METHOD_NAMED, 0, sv);
9722             op_free(o);
9723             return cmop;
9724         }
9725     }
9726     return o;
9727 }
9728
9729 OP *
9730 Perl_ck_null(pTHX_ OP *o)
9731 {
9732     PERL_ARGS_ASSERT_CK_NULL;
9733     PERL_UNUSED_CONTEXT;
9734     return o;
9735 }
9736
9737 OP *
9738 Perl_ck_open(pTHX_ OP *o)
9739 {
9740     PERL_ARGS_ASSERT_CK_OPEN;
9741
9742     S_io_hints(aTHX_ o);
9743     {
9744          /* In case of three-arg dup open remove strictness
9745           * from the last arg if it is a bareword. */
9746          OP * const first = cLISTOPx(o)->op_first; /* The pushmark. */
9747          OP * const last  = cLISTOPx(o)->op_last;  /* The bareword. */
9748          OP *oa;
9749          const char *mode;
9750
9751          if ((last->op_type == OP_CONST) &&             /* The bareword. */
9752              (last->op_private & OPpCONST_BARE) &&
9753              (last->op_private & OPpCONST_STRICT) &&
9754              (oa = OP_SIBLING(first)) &&                /* The fh. */
9755              (oa = OP_SIBLING(oa)) &&                   /* The mode. */
9756              (oa->op_type == OP_CONST) &&
9757              SvPOK(((SVOP*)oa)->op_sv) &&
9758              (mode = SvPVX_const(((SVOP*)oa)->op_sv)) &&
9759              mode[0] == '>' && mode[1] == '&' &&        /* A dup open. */
9760              (last == OP_SIBLING(oa)))                  /* The bareword. */
9761               last->op_private &= ~OPpCONST_STRICT;
9762     }
9763     return ck_fun(o);
9764 }
9765
9766 OP *
9767 Perl_ck_repeat(pTHX_ OP *o)
9768 {
9769     PERL_ARGS_ASSERT_CK_REPEAT;
9770
9771     if (cBINOPo->op_first->op_flags & OPf_PARENS) {
9772         OP* kids;
9773         o->op_private |= OPpREPEAT_DOLIST;
9774         kids = op_sibling_splice(o, NULL, -1, NULL); /* detach all kids */
9775         kids = force_list(kids, 1); /* promote them to a list */
9776         op_sibling_splice(o, NULL, 0, kids); /* and add back */
9777     }
9778     else
9779         scalar(o);
9780     return o;
9781 }
9782
9783 OP *
9784 Perl_ck_require(pTHX_ OP *o)
9785 {
9786     GV* gv;
9787
9788     PERL_ARGS_ASSERT_CK_REQUIRE;
9789
9790     if (o->op_flags & OPf_KIDS) {       /* Shall we supply missing .pm? */
9791         SVOP * const kid = (SVOP*)cUNOPo->op_first;
9792         HEK *hek;
9793         U32 hash;
9794         char *s;
9795         STRLEN len;
9796         if (kid->op_type == OP_CONST) {
9797           SV * const sv = kid->op_sv;
9798           U32 const was_readonly = SvREADONLY(sv);
9799           if (kid->op_private & OPpCONST_BARE) {
9800             dVAR;
9801             const char *end;
9802
9803             if (was_readonly) {
9804                     SvREADONLY_off(sv);
9805             }   
9806             if (SvIsCOW(sv)) sv_force_normal_flags(sv, 0);
9807
9808             s = SvPVX(sv);
9809             len = SvCUR(sv);
9810             end = s + len;
9811             for (; s < end; s++) {
9812                 if (*s == ':' && s[1] == ':') {
9813                     *s = '/';
9814                     Move(s+2, s+1, end - s - 1, char);
9815                     --end;
9816                 }
9817             }
9818             SvEND_set(sv, end);
9819             sv_catpvs(sv, ".pm");
9820             PERL_HASH(hash, SvPVX(sv), SvCUR(sv));
9821             hek = share_hek(SvPVX(sv),
9822                             (SSize_t)SvCUR(sv) * (SvUTF8(sv) ? -1 : 1),
9823                             hash);
9824             sv_sethek(sv, hek);
9825             unshare_hek(hek);
9826             SvFLAGS(sv) |= was_readonly;
9827           }
9828           else if (SvPOK(sv) && !SvNIOK(sv) && !SvGMAGICAL(sv)) {
9829             s = SvPV(sv, len);
9830             if (SvREFCNT(sv) > 1) {
9831                 kid->op_sv = newSVpvn_share(
9832                     s, SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len, 0);
9833                 SvREFCNT_dec_NN(sv);
9834             }
9835             else {
9836                 dVAR;
9837                 if (was_readonly) SvREADONLY_off(sv);
9838                 PERL_HASH(hash, s, len);
9839                 hek = share_hek(s,
9840                                 SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len,
9841                                 hash);
9842                 sv_sethek(sv, hek);
9843                 unshare_hek(hek);
9844                 SvFLAGS(sv) |= was_readonly;
9845             }
9846           }
9847         }
9848     }
9849
9850     if (!(o->op_flags & OPf_SPECIAL) /* Wasn't written as CORE::require */
9851         /* handle override, if any */
9852      && (gv = gv_override("require", 7))) {
9853         OP *kid, *newop;
9854         if (o->op_flags & OPf_KIDS) {
9855             kid = cUNOPo->op_first;
9856             op_sibling_splice(o, NULL, -1, NULL);
9857         }
9858         else {
9859             kid = newDEFSVOP();
9860         }
9861         op_free(o);
9862         newop = S_new_entersubop(aTHX_ gv, kid);
9863         return newop;
9864     }
9865
9866     return scalar(ck_fun(o));
9867 }
9868
9869 OP *
9870 Perl_ck_return(pTHX_ OP *o)
9871 {
9872     OP *kid;
9873
9874     PERL_ARGS_ASSERT_CK_RETURN;
9875
9876     kid = OP_SIBLING(cLISTOPo->op_first);
9877     if (CvLVALUE(PL_compcv)) {
9878         for (; kid; kid = OP_SIBLING(kid))
9879             op_lvalue(kid, OP_LEAVESUBLV);
9880     }
9881
9882     return o;
9883 }
9884
9885 OP *
9886 Perl_ck_select(pTHX_ OP *o)
9887 {
9888     dVAR;
9889     OP* kid;
9890
9891     PERL_ARGS_ASSERT_CK_SELECT;
9892
9893     if (o->op_flags & OPf_KIDS) {
9894         kid = OP_SIBLING(cLISTOPo->op_first);   /* get past pushmark */
9895         if (kid && OP_HAS_SIBLING(kid)) {
9896             o->op_type = OP_SSELECT;
9897             o->op_ppaddr = PL_ppaddr[OP_SSELECT];
9898             o = ck_fun(o);
9899             return fold_constants(op_integerize(op_std_init(o)));
9900         }
9901     }
9902     o = ck_fun(o);
9903     kid = OP_SIBLING(cLISTOPo->op_first);    /* get past pushmark */
9904     if (kid && kid->op_type == OP_RV2GV)
9905         kid->op_private &= ~HINT_STRICT_REFS;
9906     return o;
9907 }
9908
9909 OP *
9910 Perl_ck_shift(pTHX_ OP *o)
9911 {
9912     const I32 type = o->op_type;
9913
9914     PERL_ARGS_ASSERT_CK_SHIFT;
9915
9916     if (!(o->op_flags & OPf_KIDS)) {
9917         OP *argop;
9918
9919         if (!CvUNIQUE(PL_compcv)) {
9920             o->op_flags |= OPf_SPECIAL;
9921             return o;
9922         }
9923
9924         argop = newUNOP(OP_RV2AV, 0, scalar(newGVOP(OP_GV, 0, PL_argvgv)));
9925         op_free(o);
9926         return newUNOP(type, 0, scalar(argop));
9927     }
9928     return scalar(ck_fun(o));
9929 }
9930
9931 OP *
9932 Perl_ck_sort(pTHX_ OP *o)
9933 {
9934     OP *firstkid;
9935     OP *kid;
9936     HV * const hinthv =
9937         PL_hints & HINT_LOCALIZE_HH ? GvHV(PL_hintgv) : NULL;
9938     U8 stacked;
9939
9940     PERL_ARGS_ASSERT_CK_SORT;
9941
9942     if (hinthv) {
9943             SV ** const svp = hv_fetchs(hinthv, "sort", FALSE);
9944             if (svp) {
9945                 const I32 sorthints = (I32)SvIV(*svp);
9946                 if ((sorthints & HINT_SORT_QUICKSORT) != 0)
9947                     o->op_private |= OPpSORT_QSORT;
9948                 if ((sorthints & HINT_SORT_STABLE) != 0)
9949                     o->op_private |= OPpSORT_STABLE;
9950             }
9951     }
9952
9953     if (o->op_flags & OPf_STACKED)
9954         simplify_sort(o);
9955     firstkid = OP_SIBLING(cLISTOPo->op_first);          /* get past pushmark */
9956
9957     if ((stacked = o->op_flags & OPf_STACKED)) {        /* may have been cleared */
9958         OP *kid = cUNOPx(firstkid)->op_first;           /* get past null */
9959
9960         /* if the first arg is a code block, process it and mark sort as
9961          * OPf_SPECIAL */
9962         if (kid->op_type == OP_SCOPE || kid->op_type == OP_LEAVE) {
9963             LINKLIST(kid);
9964             if (kid->op_type == OP_LEAVE)
9965                     op_null(kid);                       /* wipe out leave */
9966             /* Prevent execution from escaping out of the sort block. */
9967             kid->op_next = 0;
9968
9969             /* provide scalar context for comparison function/block */
9970             kid = scalar(firstkid);
9971             kid->op_next = kid;
9972             o->op_flags |= OPf_SPECIAL;
9973         }
9974         else if (kid->op_type == OP_CONST
9975               && kid->op_private & OPpCONST_BARE) {
9976             char tmpbuf[256];
9977             STRLEN len;
9978             PADOFFSET off;
9979             const char * const name = SvPV(kSVOP_sv, len);
9980             *tmpbuf = '&';
9981             assert (len < 256);
9982             Copy(name, tmpbuf+1, len, char);
9983             off = pad_findmy_pvn(tmpbuf, len+1, SvUTF8(kSVOP_sv));
9984             if (off != NOT_IN_PAD) {
9985                 if (PAD_COMPNAME_FLAGS_isOUR(off)) {
9986                     SV * const new =
9987                         newSVhek(HvNAME_HEK(PAD_COMPNAME_OURSTASH(off)));
9988                     sv_catpvs(new, "::");
9989                     sv_catsv(new, kSVOP_sv);
9990                     SvREFCNT_dec_NN(kSVOP_sv);
9991                     kSVOP->op_sv = new;
9992                 }
9993                 else {
9994                     OP * const new = newOP(OP_PADCV, 0);
9995                     new->op_targ = off;
9996                     cUNOPx(firstkid)->op_first = new;
9997                     op_free(kid);
9998                 }
9999             }
10000         }
10001
10002         firstkid = OP_SIBLING(firstkid);
10003     }
10004
10005     for (kid = firstkid; kid; kid = OP_SIBLING(kid)) {
10006         /* provide list context for arguments */
10007         list(kid);
10008         if (stacked)
10009             op_lvalue(kid, OP_GREPSTART);
10010     }
10011
10012     return o;
10013 }
10014
10015 /* for sort { X } ..., where X is one of
10016  *   $a <=> $b, $b <= $a, $a cmp $b, $b cmp $a
10017  * elide the second child of the sort (the one containing X),
10018  * and set these flags as appropriate
10019         OPpSORT_NUMERIC;
10020         OPpSORT_INTEGER;
10021         OPpSORT_DESCEND;
10022  * Also, check and warn on lexical $a, $b.
10023  */
10024
10025 STATIC void
10026 S_simplify_sort(pTHX_ OP *o)
10027 {
10028     OP *kid = OP_SIBLING(cLISTOPo->op_first);   /* get past pushmark */
10029     OP *k;
10030     int descending;
10031     GV *gv;
10032     const char *gvname;
10033     bool have_scopeop;
10034
10035     PERL_ARGS_ASSERT_SIMPLIFY_SORT;
10036
10037     kid = kUNOP->op_first;                              /* get past null */
10038     if (!(have_scopeop = kid->op_type == OP_SCOPE)
10039      && kid->op_type != OP_LEAVE)
10040         return;
10041     kid = kLISTOP->op_last;                             /* get past scope */
10042     switch(kid->op_type) {
10043         case OP_NCMP:
10044         case OP_I_NCMP:
10045         case OP_SCMP:
10046             if (!have_scopeop) goto padkids;
10047             break;
10048         default:
10049             return;
10050     }
10051     k = kid;                                            /* remember this node*/
10052     if (kBINOP->op_first->op_type != OP_RV2SV
10053      || kBINOP->op_last ->op_type != OP_RV2SV)
10054     {
10055         /*
10056            Warn about my($a) or my($b) in a sort block, *if* $a or $b is
10057            then used in a comparison.  This catches most, but not
10058            all cases.  For instance, it catches
10059                sort { my($a); $a <=> $b }
10060            but not
10061                sort { my($a); $a < $b ? -1 : $a == $b ? 0 : 1; }
10062            (although why you'd do that is anyone's guess).
10063         */
10064
10065        padkids:
10066         if (!ckWARN(WARN_SYNTAX)) return;
10067         kid = kBINOP->op_first;
10068         do {
10069             if (kid->op_type == OP_PADSV) {
10070                 SV * const name = PAD_COMPNAME_SV(kid->op_targ);
10071                 if (SvCUR(name) == 2 && *SvPVX(name) == '$'
10072                  && (SvPVX(name)[1] == 'a' || SvPVX(name)[1] == 'b'))
10073                     /* diag_listed_as: "my %s" used in sort comparison */
10074                     Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
10075                                      "\"%s %s\" used in sort comparison",
10076                                       SvPAD_STATE(name) ? "state" : "my",
10077                                       SvPVX(name));
10078             }
10079         } while ((kid = OP_SIBLING(kid)));
10080         return;
10081     }
10082     kid = kBINOP->op_first;                             /* get past cmp */
10083     if (kUNOP->op_first->op_type != OP_GV)
10084         return;
10085     kid = kUNOP->op_first;                              /* get past rv2sv */
10086     gv = kGVOP_gv;
10087     if (GvSTASH(gv) != PL_curstash)
10088         return;
10089     gvname = GvNAME(gv);
10090     if (*gvname == 'a' && gvname[1] == '\0')
10091         descending = 0;
10092     else if (*gvname == 'b' && gvname[1] == '\0')
10093         descending = 1;
10094     else
10095         return;
10096
10097     kid = k;                                            /* back to cmp */
10098     /* already checked above that it is rv2sv */
10099     kid = kBINOP->op_last;                              /* down to 2nd arg */
10100     if (kUNOP->op_first->op_type != OP_GV)
10101         return;
10102     kid = kUNOP->op_first;                              /* get past rv2sv */
10103     gv = kGVOP_gv;
10104     if (GvSTASH(gv) != PL_curstash)
10105         return;
10106     gvname = GvNAME(gv);
10107     if ( descending
10108          ? !(*gvname == 'a' && gvname[1] == '\0')
10109          : !(*gvname == 'b' && gvname[1] == '\0'))
10110         return;
10111     o->op_flags &= ~(OPf_STACKED | OPf_SPECIAL);
10112     if (descending)
10113         o->op_private |= OPpSORT_DESCEND;
10114     if (k->op_type == OP_NCMP)
10115         o->op_private |= OPpSORT_NUMERIC;
10116     if (k->op_type == OP_I_NCMP)
10117         o->op_private |= OPpSORT_NUMERIC | OPpSORT_INTEGER;
10118     kid = OP_SIBLING(cLISTOPo->op_first);
10119     /* cut out and delete old block (second sibling) */
10120     op_sibling_splice(o, cLISTOPo->op_first, 1, NULL);
10121     op_free(kid);
10122 }
10123
10124 OP *
10125 Perl_ck_split(pTHX_ OP *o)
10126 {
10127     dVAR;
10128     OP *kid;
10129
10130     PERL_ARGS_ASSERT_CK_SPLIT;
10131
10132     if (o->op_flags & OPf_STACKED)
10133         return no_fh_allowed(o);
10134
10135     kid = cLISTOPo->op_first;
10136     if (kid->op_type != OP_NULL)
10137         Perl_croak(aTHX_ "panic: ck_split, type=%u", (unsigned) kid->op_type);
10138     /* delete leading NULL node, then add a CONST if no other nodes */
10139     op_sibling_splice(o, NULL, 1,
10140             OP_HAS_SIBLING(kid) ? NULL : newSVOP(OP_CONST, 0, newSVpvs(" ")));
10141     op_free(kid);
10142     kid = cLISTOPo->op_first;
10143
10144     if (kid->op_type != OP_MATCH || kid->op_flags & OPf_STACKED) {
10145         /* remove kid, and replace with new optree */
10146         op_sibling_splice(o, NULL, 1, NULL);
10147         /* OPf_SPECIAL is used to trigger split " " behavior */
10148         kid = pmruntime( newPMOP(OP_MATCH, OPf_SPECIAL), kid, 0, 0);
10149         op_sibling_splice(o, NULL, 0, kid);
10150     }
10151
10152     kid->op_type = OP_PUSHRE;
10153     kid->op_ppaddr = PL_ppaddr[OP_PUSHRE];
10154     scalar(kid);
10155     if (((PMOP *)kid)->op_pmflags & PMf_GLOBAL) {
10156       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
10157                      "Use of /g modifier is meaningless in split");
10158     }
10159
10160     if (!OP_HAS_SIBLING(kid))
10161         op_append_elem(OP_SPLIT, o, newDEFSVOP());
10162
10163     kid = OP_SIBLING(kid);
10164     assert(kid);
10165     scalar(kid);
10166
10167     if (!OP_HAS_SIBLING(kid))
10168     {
10169         op_append_elem(OP_SPLIT, o, newSVOP(OP_CONST, 0, newSViv(0)));
10170         o->op_private |= OPpSPLIT_IMPLIM;
10171     }
10172     assert(OP_HAS_SIBLING(kid));
10173
10174     kid = OP_SIBLING(kid);
10175     scalar(kid);
10176
10177     if (OP_HAS_SIBLING(kid))
10178         return too_many_arguments_pv(o,OP_DESC(o), 0);
10179
10180     return o;
10181 }
10182
10183 OP *
10184 Perl_ck_join(pTHX_ OP *o)
10185 {
10186     const OP * const kid = OP_SIBLING(cLISTOPo->op_first);
10187
10188     PERL_ARGS_ASSERT_CK_JOIN;
10189
10190     if (kid && kid->op_type == OP_MATCH) {
10191         if (ckWARN(WARN_SYNTAX)) {
10192             const REGEXP *re = PM_GETRE(kPMOP);
10193             const SV *msg = re
10194                     ? newSVpvn_flags( RX_PRECOMP_const(re), RX_PRELEN(re),
10195                                             SVs_TEMP | ( RX_UTF8(re) ? SVf_UTF8 : 0 ) )
10196                     : newSVpvs_flags( "STRING", SVs_TEMP );
10197             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
10198                         "/%"SVf"/ should probably be written as \"%"SVf"\"",
10199                         SVfARG(msg), SVfARG(msg));
10200         }
10201     }
10202     return ck_fun(o);
10203 }
10204
10205 /*
10206 =for apidoc Am|CV *|rv2cv_op_cv|OP *cvop|U32 flags
10207
10208 Examines an op, which is expected to identify a subroutine at runtime,
10209 and attempts to determine at compile time which subroutine it identifies.
10210 This is normally used during Perl compilation to determine whether
10211 a prototype can be applied to a function call.  I<cvop> is the op
10212 being considered, normally an C<rv2cv> op.  A pointer to the identified
10213 subroutine is returned, if it could be determined statically, and a null
10214 pointer is returned if it was not possible to determine statically.
10215
10216 Currently, the subroutine can be identified statically if the RV that the
10217 C<rv2cv> is to operate on is provided by a suitable C<gv> or C<const> op.
10218 A C<gv> op is suitable if the GV's CV slot is populated.  A C<const> op is
10219 suitable if the constant value must be an RV pointing to a CV.  Details of
10220 this process may change in future versions of Perl.  If the C<rv2cv> op
10221 has the C<OPpENTERSUB_AMPER> flag set then no attempt is made to identify
10222 the subroutine statically: this flag is used to suppress compile-time
10223 magic on a subroutine call, forcing it to use default runtime behaviour.
10224
10225 If I<flags> has the bit C<RV2CVOPCV_MARK_EARLY> set, then the handling
10226 of a GV reference is modified.  If a GV was examined and its CV slot was
10227 found to be empty, then the C<gv> op has the C<OPpEARLY_CV> flag set.
10228 If the op is not optimised away, and the CV slot is later populated with
10229 a subroutine having a prototype, that flag eventually triggers the warning
10230 "called too early to check prototype".
10231
10232 If I<flags> has the bit C<RV2CVOPCV_RETURN_NAME_GV> set, then instead
10233 of returning a pointer to the subroutine it returns a pointer to the
10234 GV giving the most appropriate name for the subroutine in this context.
10235 Normally this is just the C<CvGV> of the subroutine, but for an anonymous
10236 (C<CvANON>) subroutine that is referenced through a GV it will be the
10237 referencing GV.  The resulting C<GV*> is cast to C<CV*> to be returned.
10238 A null pointer is returned as usual if there is no statically-determinable
10239 subroutine.
10240
10241 =cut
10242 */
10243
10244 /* shared by toke.c:yylex */
10245 CV *
10246 Perl_find_lexical_cv(pTHX_ PADOFFSET off)
10247 {
10248     PADNAME *name = PAD_COMPNAME(off);
10249     CV *compcv = PL_compcv;
10250     while (PadnameOUTER(name)) {
10251         assert(PARENT_PAD_INDEX(name));
10252         compcv = CvOUTSIDE(PL_compcv);
10253         name = PadlistNAMESARRAY(CvPADLIST(compcv))
10254                 [off = PARENT_PAD_INDEX(name)];
10255     }
10256     assert(!PadnameIsOUR(name));
10257     if (!PadnameIsSTATE(name) && SvMAGICAL(name)) {
10258         MAGIC * mg = mg_find(name, PERL_MAGIC_proto);
10259         assert(mg);
10260         assert(mg->mg_obj);
10261         return (CV *)mg->mg_obj;
10262     }
10263     return (CV *)AvARRAY(PadlistARRAY(CvPADLIST(compcv))[1])[off];
10264 }
10265
10266 CV *
10267 Perl_rv2cv_op_cv(pTHX_ OP *cvop, U32 flags)
10268 {
10269     OP *rvop;
10270     CV *cv;
10271     GV *gv;
10272     PERL_ARGS_ASSERT_RV2CV_OP_CV;
10273     if (flags & ~RV2CVOPCV_FLAG_MASK)
10274         Perl_croak(aTHX_ "panic: rv2cv_op_cv bad flags %x", (unsigned)flags);
10275     if (cvop->op_type != OP_RV2CV)
10276         return NULL;
10277     if (cvop->op_private & OPpENTERSUB_AMPER)
10278         return NULL;
10279     if (!(cvop->op_flags & OPf_KIDS))
10280         return NULL;
10281     rvop = cUNOPx(cvop)->op_first;
10282     switch (rvop->op_type) {
10283         case OP_GV: {
10284             gv = cGVOPx_gv(rvop);
10285             if (!isGV(gv)) {
10286                 if (SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV) {
10287                     cv = MUTABLE_CV(SvRV(gv));
10288                     gv = NULL;
10289                     break;
10290                 }
10291                 if (flags & RV2CVOPCV_RETURN_STUB)
10292                     return (CV *)gv;
10293                 else return NULL;
10294             }
10295             cv = GvCVu(gv);
10296             if (!cv) {
10297                 if (flags & RV2CVOPCV_MARK_EARLY)
10298                     rvop->op_private |= OPpEARLY_CV;
10299                 return NULL;
10300             }
10301         } break;
10302         case OP_CONST: {
10303             SV *rv = cSVOPx_sv(rvop);
10304             if (!SvROK(rv))
10305                 return NULL;
10306             cv = (CV*)SvRV(rv);
10307             gv = NULL;
10308         } break;
10309         case OP_PADCV: {
10310             cv = find_lexical_cv(rvop->op_targ);
10311             gv = NULL;
10312         } break;
10313         default: {
10314             return NULL;
10315         } NOT_REACHED; /* NOTREACHED */
10316     }
10317     if (SvTYPE((SV*)cv) != SVt_PVCV)
10318         return NULL;
10319     if (flags & (RV2CVOPCV_RETURN_NAME_GV|RV2CVOPCV_MAYBE_NAME_GV)) {
10320         if ((!CvANON(cv) || !gv) && !CvLEXICAL(cv)
10321          && ((flags & RV2CVOPCV_RETURN_NAME_GV) || !CvNAMED(cv)))
10322             gv = CvGV(cv);
10323         return (CV*)gv;
10324     } else {
10325         return cv;
10326     }
10327 }
10328
10329 /*
10330 =for apidoc Am|OP *|ck_entersub_args_list|OP *entersubop
10331
10332 Performs the default fixup of the arguments part of an C<entersub>
10333 op tree.  This consists of applying list context to each of the
10334 argument ops.  This is the standard treatment used on a call marked
10335 with C<&>, or a method call, or a call through a subroutine reference,
10336 or any other call where the callee can't be identified at compile time,
10337 or a call where the callee has no prototype.
10338
10339 =cut
10340 */
10341
10342 OP *
10343 Perl_ck_entersub_args_list(pTHX_ OP *entersubop)
10344 {
10345     OP *aop;
10346     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_LIST;
10347     aop = cUNOPx(entersubop)->op_first;
10348     if (!OP_HAS_SIBLING(aop))
10349         aop = cUNOPx(aop)->op_first;
10350     for (aop = OP_SIBLING(aop); OP_HAS_SIBLING(aop); aop = OP_SIBLING(aop)) {
10351         list(aop);
10352         op_lvalue(aop, OP_ENTERSUB);
10353     }
10354     return entersubop;
10355 }
10356
10357 /*
10358 =for apidoc Am|OP *|ck_entersub_args_proto|OP *entersubop|GV *namegv|SV *protosv
10359
10360 Performs the fixup of the arguments part of an C<entersub> op tree
10361 based on a subroutine prototype.  This makes various modifications to
10362 the argument ops, from applying context up to inserting C<refgen> ops,
10363 and checking the number and syntactic types of arguments, as directed by
10364 the prototype.  This is the standard treatment used on a subroutine call,
10365 not marked with C<&>, where the callee can be identified at compile time
10366 and has a prototype.
10367
10368 I<protosv> supplies the subroutine prototype to be applied to the call.
10369 It may be a normal defined scalar, of which the string value will be used.
10370 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
10371 that has been cast to C<SV*>) which has a prototype.  The prototype
10372 supplied, in whichever form, does not need to match the actual callee
10373 referenced by the op tree.
10374
10375 If the argument ops disagree with the prototype, for example by having
10376 an unacceptable number of arguments, a valid op tree is returned anyway.
10377 The error is reflected in the parser state, normally resulting in a single
10378 exception at the top level of parsing which covers all the compilation
10379 errors that occurred.  In the error message, the callee is referred to
10380 by the name defined by the I<namegv> parameter.
10381
10382 =cut
10383 */
10384
10385 OP *
10386 Perl_ck_entersub_args_proto(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
10387 {
10388     STRLEN proto_len;
10389     const char *proto, *proto_end;
10390     OP *aop, *prev, *cvop, *parent;
10391     int optional = 0;
10392     I32 arg = 0;
10393     I32 contextclass = 0;
10394     const char *e = NULL;
10395     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO;
10396     if (SvTYPE(protosv) == SVt_PVCV ? !SvPOK(protosv) : !SvOK(protosv))
10397         Perl_croak(aTHX_ "panic: ck_entersub_args_proto CV with no proto, "
10398                    "flags=%lx", (unsigned long) SvFLAGS(protosv));
10399     if (SvTYPE(protosv) == SVt_PVCV)
10400          proto = CvPROTO(protosv), proto_len = CvPROTOLEN(protosv);
10401     else proto = SvPV(protosv, proto_len);
10402     proto = S_strip_spaces(aTHX_ proto, &proto_len);
10403     proto_end = proto + proto_len;
10404     parent = entersubop;
10405     aop = cUNOPx(entersubop)->op_first;
10406     if (!OP_HAS_SIBLING(aop)) {
10407         parent = aop;
10408         aop = cUNOPx(aop)->op_first;
10409     }
10410     prev = aop;
10411     aop = OP_SIBLING(aop);
10412     for (cvop = aop; OP_HAS_SIBLING(cvop); cvop = OP_SIBLING(cvop)) ;
10413     while (aop != cvop) {
10414         OP* o3 = aop;
10415
10416         if (proto >= proto_end)
10417         {
10418             SV * const namesv = cv_name((CV *)namegv, NULL);
10419             yyerror_pv(Perl_form(aTHX_ "Too many arguments for %"SVf,
10420                                         SVfARG(namesv)), SvUTF8(namesv));
10421             return entersubop;
10422         }
10423
10424         switch (*proto) {
10425             case ';':
10426                 optional = 1;
10427                 proto++;
10428                 continue;
10429             case '_':
10430                 /* _ must be at the end */
10431                 if (proto[1] && !strchr(";@%", proto[1]))
10432                     goto oops;
10433                 /* FALLTHROUGH */
10434             case '$':
10435                 proto++;
10436                 arg++;
10437                 scalar(aop);
10438                 break;
10439             case '%':
10440             case '@':
10441                 list(aop);
10442                 arg++;
10443                 break;
10444             case '&':
10445                 proto++;
10446                 arg++;
10447                 if (o3->op_type != OP_REFGEN && o3->op_type != OP_UNDEF)
10448                     bad_type_gv(arg,
10449                             arg == 1 ? "block or sub {}" : "sub {}",
10450                             namegv, 0, o3);
10451                 break;
10452             case '*':
10453                 /* '*' allows any scalar type, including bareword */
10454                 proto++;
10455                 arg++;
10456                 if (o3->op_type == OP_RV2GV)
10457                     goto wrapref;       /* autoconvert GLOB -> GLOBref */
10458                 else if (o3->op_type == OP_CONST)
10459                     o3->op_private &= ~OPpCONST_STRICT;
10460                 scalar(aop);
10461                 break;
10462             case '+':
10463                 proto++;
10464                 arg++;
10465                 if (o3->op_type == OP_RV2AV ||
10466                     o3->op_type == OP_PADAV ||
10467                     o3->op_type == OP_RV2HV ||
10468                     o3->op_type == OP_PADHV
10469                 ) {
10470                     goto wrapref;
10471                 }
10472                 scalar(aop);
10473                 break;
10474             case '[': case ']':
10475                 goto oops;
10476
10477             case '\\':
10478                 proto++;
10479                 arg++;
10480             again:
10481                 switch (*proto++) {
10482                     case '[':
10483                         if (contextclass++ == 0) {
10484                             e = strchr(proto, ']');
10485                             if (!e || e == proto)
10486                                 goto oops;
10487                         }
10488                         else
10489                             goto oops;
10490                         goto again;
10491
10492                     case ']':
10493                         if (contextclass) {
10494                             const char *p = proto;
10495                             const char *const end = proto;
10496                             contextclass = 0;
10497                             while (*--p != '[')
10498                                 /* \[$] accepts any scalar lvalue */
10499                                 if (*p == '$'
10500                                  && Perl_op_lvalue_flags(aTHX_
10501                                      scalar(o3),
10502                                      OP_READ, /* not entersub */
10503                                      OP_LVALUE_NO_CROAK
10504                                     )) goto wrapref;
10505                             bad_type_gv(arg, Perl_form(aTHX_ "one of %.*s",
10506                                         (int)(end - p), p),
10507                                     namegv, 0, o3);
10508                         } else
10509                             goto oops;
10510                         break;
10511                     case '*':
10512                         if (o3->op_type == OP_RV2GV)
10513                             goto wrapref;
10514                         if (!contextclass)
10515                             bad_type_gv(arg, "symbol", namegv, 0, o3);
10516                         break;
10517                     case '&':
10518                         if (o3->op_type == OP_ENTERSUB)
10519                             goto wrapref;
10520                         if (!contextclass)
10521                             bad_type_gv(arg, "subroutine entry", namegv, 0,
10522                                     o3);
10523                         break;
10524                     case '$':
10525                         if (o3->op_type == OP_RV2SV ||
10526                                 o3->op_type == OP_PADSV ||
10527                                 o3->op_type == OP_HELEM ||
10528                                 o3->op_type == OP_AELEM)
10529                             goto wrapref;
10530                         if (!contextclass) {
10531                             /* \$ accepts any scalar lvalue */
10532                             if (Perl_op_lvalue_flags(aTHX_
10533                                     scalar(o3),
10534                                     OP_READ,  /* not entersub */
10535                                     OP_LVALUE_NO_CROAK
10536                                )) goto wrapref;
10537                             bad_type_gv(arg, "scalar", namegv, 0, o3);
10538                         }
10539                         break;
10540                     case '@':
10541                         if (o3->op_type == OP_RV2AV ||
10542                                 o3->op_type == OP_PADAV)
10543                             goto wrapref;
10544                         if (!contextclass)
10545                             bad_type_gv(arg, "array", namegv, 0, o3);
10546                         break;
10547                     case '%':
10548                         if (o3->op_type == OP_RV2HV ||
10549                                 o3->op_type == OP_PADHV)
10550                             goto wrapref;
10551                         if (!contextclass)
10552                             bad_type_gv(arg, "hash", namegv, 0, o3);
10553                         break;
10554                     wrapref:
10555                             aop = S_op_sibling_newUNOP(aTHX_ parent, prev,
10556                                                 OP_REFGEN, 0);
10557                         if (contextclass && e) {
10558                             proto = e + 1;
10559                             contextclass = 0;
10560                         }
10561                         break;
10562                     default: goto oops;
10563                 }
10564                 if (contextclass)
10565                     goto again;
10566                 break;
10567             case ' ':
10568                 proto++;
10569                 continue;
10570             default:
10571             oops: {
10572                 Perl_croak(aTHX_ "Malformed prototype for %"SVf": %"SVf,
10573                                   SVfARG(cv_name((CV *)namegv, NULL)),
10574                                   SVfARG(protosv));
10575             }
10576         }
10577
10578         op_lvalue(aop, OP_ENTERSUB);
10579         prev = aop;
10580         aop = OP_SIBLING(aop);
10581     }
10582     if (aop == cvop && *proto == '_') {
10583         /* generate an access to $_ */
10584         op_sibling_splice(parent, prev, 0, newDEFSVOP());
10585     }
10586     if (!optional && proto_end > proto &&
10587         (*proto != '@' && *proto != '%' && *proto != ';' && *proto != '_'))
10588     {
10589         SV * const namesv = cv_name((CV *)namegv, NULL);
10590         yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %"SVf,
10591                                     SVfARG(namesv)), SvUTF8(namesv));
10592     }
10593     return entersubop;
10594 }
10595
10596 /*
10597 =for apidoc Am|OP *|ck_entersub_args_proto_or_list|OP *entersubop|GV *namegv|SV *protosv
10598
10599 Performs the fixup of the arguments part of an C<entersub> op tree either
10600 based on a subroutine prototype or using default list-context processing.
10601 This is the standard treatment used on a subroutine call, not marked
10602 with C<&>, where the callee can be identified at compile time.
10603
10604 I<protosv> supplies the subroutine prototype to be applied to the call,
10605 or indicates that there is no prototype.  It may be a normal scalar,
10606 in which case if it is defined then the string value will be used
10607 as a prototype, and if it is undefined then there is no prototype.
10608 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
10609 that has been cast to C<SV*>), of which the prototype will be used if it
10610 has one.  The prototype (or lack thereof) supplied, in whichever form,
10611 does not need to match the actual callee referenced by the op tree.
10612
10613 If the argument ops disagree with the prototype, for example by having
10614 an unacceptable number of arguments, a valid op tree is returned anyway.
10615 The error is reflected in the parser state, normally resulting in a single
10616 exception at the top level of parsing which covers all the compilation
10617 errors that occurred.  In the error message, the callee is referred to
10618 by the name defined by the I<namegv> parameter.
10619
10620 =cut
10621 */
10622
10623 OP *
10624 Perl_ck_entersub_args_proto_or_list(pTHX_ OP *entersubop,
10625         GV *namegv, SV *protosv)
10626 {
10627     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO_OR_LIST;
10628     if (SvTYPE(protosv) == SVt_PVCV ? SvPOK(protosv) : SvOK(protosv))
10629         return ck_entersub_args_proto(entersubop, namegv, protosv);
10630     else
10631         return ck_entersub_args_list(entersubop);
10632 }
10633
10634 OP *
10635 Perl_ck_entersub_args_core(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
10636 {
10637     int opnum = SvTYPE(protosv) == SVt_PVCV ? 0 : (int)SvUV(protosv);
10638     OP *aop = cUNOPx(entersubop)->op_first;
10639
10640     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_CORE;
10641
10642     if (!opnum) {
10643         OP *cvop;
10644         if (!OP_HAS_SIBLING(aop))
10645             aop = cUNOPx(aop)->op_first;
10646         aop = OP_SIBLING(aop);
10647         for (cvop = aop; OP_SIBLING(cvop); cvop = OP_SIBLING(cvop)) ;
10648         if (aop != cvop)
10649             (void)too_many_arguments_pv(entersubop, GvNAME(namegv), 0);
10650         
10651         op_free(entersubop);
10652         switch(GvNAME(namegv)[2]) {
10653         case 'F': return newSVOP(OP_CONST, 0,
10654                                         newSVpv(CopFILE(PL_curcop),0));
10655         case 'L': return newSVOP(
10656                            OP_CONST, 0,
10657                            Perl_newSVpvf(aTHX_
10658                              "%"IVdf, (IV)CopLINE(PL_curcop)
10659                            )
10660                          );
10661         case 'P': return newSVOP(OP_CONST, 0,
10662                                    (PL_curstash
10663                                      ? newSVhek(HvNAME_HEK(PL_curstash))
10664                                      : &PL_sv_undef
10665                                    )
10666                                 );
10667         }
10668         NOT_REACHED;
10669     }
10670     else {
10671         OP *prev, *cvop, *first, *parent;
10672         U32 flags = 0;
10673
10674         parent = entersubop;
10675         if (!OP_HAS_SIBLING(aop)) {
10676             parent = aop;
10677             aop = cUNOPx(aop)->op_first;
10678         }
10679         
10680         first = prev = aop;
10681         aop = OP_SIBLING(aop);
10682         /* find last sibling */
10683         for (cvop = aop;
10684              OP_HAS_SIBLING(cvop);
10685              prev = cvop, cvop = OP_SIBLING(cvop))
10686             ;
10687         if (!(cvop->op_private & OPpENTERSUB_NOPAREN)
10688             /* Usually, OPf_SPECIAL on a UNOP means that its arg had no
10689              * parens, but these have their own meaning for that flag: */
10690             && opnum != OP_VALUES && opnum != OP_KEYS && opnum != OP_EACH
10691             && opnum != OP_DELETE && opnum != OP_EXISTS)
10692                 flags |= OPf_SPECIAL;
10693         /* excise cvop from end of sibling chain */
10694         op_sibling_splice(parent, prev, 1, NULL);
10695         op_free(cvop);
10696         if (aop == cvop) aop = NULL;
10697
10698         /* detach remaining siblings from the first sibling, then
10699          * dispose of original optree */
10700
10701         if (aop)
10702             op_sibling_splice(parent, first, -1, NULL);
10703         op_free(entersubop);
10704
10705         if (opnum == OP_ENTEREVAL
10706          && GvNAMELEN(namegv)==9 && strnEQ(GvNAME(namegv), "evalbytes", 9))
10707             flags |= OPpEVAL_BYTES <<8;
10708         
10709         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
10710         case OA_UNOP:
10711         case OA_BASEOP_OR_UNOP:
10712         case OA_FILESTATOP:
10713             return aop ? newUNOP(opnum,flags,aop) : newOP(opnum,flags);
10714         case OA_BASEOP:
10715             if (aop) {
10716                     (void)too_many_arguments_pv(aop, GvNAME(namegv), 0);
10717                 op_free(aop);
10718             }
10719             return opnum == OP_RUNCV
10720                 ? newPVOP(OP_RUNCV,0,NULL)
10721                 : newOP(opnum,0);
10722         default:
10723             return convert(opnum,0,aop);
10724         }
10725     }
10726     assert(0);
10727     return entersubop;
10728 }
10729
10730 /*
10731 =for apidoc Am|void|cv_get_call_checker|CV *cv|Perl_call_checker *ckfun_p|SV **ckobj_p
10732
10733 Retrieves the function that will be used to fix up a call to I<cv>.
10734 Specifically, the function is applied to an C<entersub> op tree for a
10735 subroutine call, not marked with C<&>, where the callee can be identified
10736 at compile time as I<cv>.
10737
10738 The C-level function pointer is returned in I<*ckfun_p>, and an SV
10739 argument for it is returned in I<*ckobj_p>.  The function is intended
10740 to be called in this manner:
10741
10742     entersubop = (*ckfun_p)(aTHX_ entersubop, namegv, (*ckobj_p));
10743
10744 In this call, I<entersubop> is a pointer to the C<entersub> op,
10745 which may be replaced by the check function, and I<namegv> is a GV
10746 supplying the name that should be used by the check function to refer
10747 to the callee of the C<entersub> op if it needs to emit any diagnostics.
10748 It is permitted to apply the check function in non-standard situations,
10749 such as to a call to a different subroutine or to a method call.
10750
10751 By default, the function is
10752 L<Perl_ck_entersub_args_proto_or_list|/ck_entersub_args_proto_or_list>,
10753 and the SV parameter is I<cv> itself.  This implements standard
10754 prototype processing.  It can be changed, for a particular subroutine,
10755 by L</cv_set_call_checker>.
10756
10757 =cut
10758 */
10759
10760 static void
10761 S_cv_get_call_checker(CV *cv, Perl_call_checker *ckfun_p, SV **ckobj_p,
10762                       U8 *flagsp)
10763 {
10764     MAGIC *callmg;
10765     callmg = SvMAGICAL((SV*)cv) ? mg_find((SV*)cv, PERL_MAGIC_checkcall) : NULL;
10766     if (callmg) {
10767         *ckfun_p = DPTR2FPTR(Perl_call_checker, callmg->mg_ptr);
10768         *ckobj_p = callmg->mg_obj;
10769         if (flagsp) *flagsp = callmg->mg_flags;
10770     } else {
10771         *ckfun_p = Perl_ck_entersub_args_proto_or_list;
10772         *ckobj_p = (SV*)cv;
10773         if (flagsp) *flagsp = 0;
10774     }
10775 }
10776
10777 void
10778 Perl_cv_get_call_checker(pTHX_ CV *cv, Perl_call_checker *ckfun_p, SV **ckobj_p)
10779 {
10780     PERL_ARGS_ASSERT_CV_GET_CALL_CHECKER;
10781     PERL_UNUSED_CONTEXT;
10782     S_cv_get_call_checker(cv, ckfun_p, ckobj_p, NULL);
10783 }
10784
10785 /*
10786 =for apidoc Am|void|cv_set_call_checker_flags|CV *cv|Perl_call_checker ckfun|SV *ckobj|U32 flags
10787
10788 Sets the function that will be used to fix up a call to I<cv>.
10789 Specifically, the function is applied to an C<entersub> op tree for a
10790 subroutine call, not marked with C<&>, where the callee can be identified
10791 at compile time as I<cv>.
10792
10793 The C-level function pointer is supplied in I<ckfun>, and an SV argument
10794 for it is supplied in I<ckobj>.  The function should be defined like this:
10795
10796     STATIC OP * ckfun(pTHX_ OP *op, GV *namegv, SV *ckobj)
10797
10798 It is intended to be called in this manner:
10799
10800     entersubop = ckfun(aTHX_ entersubop, namegv, ckobj);
10801
10802 In this call, I<entersubop> is a pointer to the C<entersub> op,
10803 which may be replaced by the check function, and I<namegv> supplies
10804 the name that should be used by the check function to refer
10805 to the callee of the C<entersub> op if it needs to emit any diagnostics.
10806 It is permitted to apply the check function in non-standard situations,
10807 such as to a call to a different subroutine or to a method call.
10808
10809 I<namegv> may not actually be a GV.  For efficiency, perl may pass a
10810 CV or other SV instead.  Whatever is passed can be used as the first
10811 argument to L</cv_name>.  You can force perl to pass a GV by including
10812 C<CALL_CHECKER_REQUIRE_GV> in the I<flags>.
10813
10814 The current setting for a particular CV can be retrieved by
10815 L</cv_get_call_checker>.
10816
10817 =for apidoc Am|void|cv_set_call_checker|CV *cv|Perl_call_checker ckfun|SV *ckobj
10818
10819 The original form of L</cv_set_call_checker_flags>, which passes it the
10820 C<CALL_CHECKER_REQUIRE_GV> flag for backward-compatibility.
10821
10822 =cut
10823 */
10824
10825 void
10826 Perl_cv_set_call_checker(pTHX_ CV *cv, Perl_call_checker ckfun, SV *ckobj)
10827 {
10828     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER;
10829     cv_set_call_checker_flags(cv, ckfun, ckobj, CALL_CHECKER_REQUIRE_GV);
10830 }
10831
10832 void
10833 Perl_cv_set_call_checker_flags(pTHX_ CV *cv, Perl_call_checker ckfun,
10834                                      SV *ckobj, U32 flags)
10835 {
10836     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER_FLAGS;
10837     if (ckfun == Perl_ck_entersub_args_proto_or_list && ckobj == (SV*)cv) {
10838         if (SvMAGICAL((SV*)cv))
10839             mg_free_type((SV*)cv, PERL_MAGIC_checkcall);
10840     } else {
10841         MAGIC *callmg;
10842         sv_magic((SV*)cv, &PL_sv_undef, PERL_MAGIC_checkcall, NULL, 0);
10843         callmg = mg_find((SV*)cv, PERL_MAGIC_checkcall);
10844         assert(callmg);
10845         if (callmg->mg_flags & MGf_REFCOUNTED) {
10846             SvREFCNT_dec(callmg->mg_obj);
10847             callmg->mg_flags &= ~MGf_REFCOUNTED;
10848         }
10849         callmg->mg_ptr = FPTR2DPTR(char *, ckfun);
10850         callmg->mg_obj = ckobj;
10851         if (ckobj != (SV*)cv) {
10852             SvREFCNT_inc_simple_void_NN(ckobj);
10853             callmg->mg_flags |= MGf_REFCOUNTED;
10854         }
10855         callmg->mg_flags = (callmg->mg_flags &~ MGf_REQUIRE_GV)
10856                          | (U8)(flags & MGf_REQUIRE_GV) | MGf_COPY;
10857     }
10858 }
10859
10860 OP *
10861 Perl_ck_subr(pTHX_ OP *o)
10862 {
10863     OP *aop, *cvop;
10864     CV *cv;
10865     GV *namegv;
10866
10867     PERL_ARGS_ASSERT_CK_SUBR;
10868
10869     aop = cUNOPx(o)->op_first;
10870     if (!OP_HAS_SIBLING(aop))
10871         aop = cUNOPx(aop)->op_first;
10872     aop = OP_SIBLING(aop);
10873     for (cvop = aop; OP_HAS_SIBLING(cvop); cvop = OP_SIBLING(cvop)) ;
10874     cv = rv2cv_op_cv(cvop, RV2CVOPCV_MARK_EARLY);
10875     namegv = cv ? (GV*)rv2cv_op_cv(cvop, RV2CVOPCV_MAYBE_NAME_GV) : NULL;
10876
10877     o->op_private &= ~1;
10878     o->op_private |= OPpENTERSUB_HASTARG;
10879     o->op_private |= (PL_hints & HINT_STRICT_REFS);
10880     if (PERLDB_SUB && PL_curstash != PL_debstash)
10881         o->op_private |= OPpENTERSUB_DB;
10882     if (cvop->op_type == OP_RV2CV) {
10883         o->op_private |= (cvop->op_private & OPpENTERSUB_AMPER);
10884         op_null(cvop);
10885     } else if (cvop->op_type == OP_METHOD || cvop->op_type == OP_METHOD_NAMED) {
10886         if (aop->op_type == OP_CONST)
10887             aop->op_private &= ~OPpCONST_STRICT;
10888         else if (aop->op_type == OP_LIST) {
10889             OP * const sib = OP_SIBLING(((UNOP*)aop)->op_first);
10890             if (sib && sib->op_type == OP_CONST)
10891                 sib->op_private &= ~OPpCONST_STRICT;
10892         }
10893     }
10894
10895     if (!cv) {
10896         return ck_entersub_args_list(o);
10897     } else {
10898         Perl_call_checker ckfun;
10899         SV *ckobj;
10900         U8 flags;
10901         S_cv_get_call_checker(cv, &ckfun, &ckobj, &flags);
10902         if (!namegv) {
10903             /* The original call checker API guarantees that a GV will be
10904                be provided with the right name.  So, if the old API was
10905                used (or the REQUIRE_GV flag was passed), we have to reify
10906                the CV’s GV, unless this is an anonymous sub.  This is not
10907                ideal for lexical subs, as its stringification will include
10908                the package.  But it is the best we can do.  */
10909             if (flags & MGf_REQUIRE_GV) {
10910                 if (!CvANON(cv) && (!CvNAMED(cv) || CvNAME_HEK(cv)))
10911                     namegv = CvGV(cv);
10912             }
10913             else namegv = MUTABLE_GV(cv);
10914             /* After a syntax error in a lexical sub, the cv that
10915                rv2cv_op_cv returns may be a nameless stub. */
10916             if (!namegv) return ck_entersub_args_list(o);
10917
10918         }
10919         return ckfun(aTHX_ o, namegv, ckobj);
10920     }
10921 }
10922
10923 OP *
10924 Perl_ck_svconst(pTHX_ OP *o)
10925 {
10926     SV * const sv = cSVOPo->op_sv;
10927     PERL_ARGS_ASSERT_CK_SVCONST;
10928     PERL_UNUSED_CONTEXT;
10929 #ifdef PERL_OLD_COPY_ON_WRITE
10930     if (SvIsCOW(sv)) sv_force_normal(sv);
10931 #elif defined(PERL_NEW_COPY_ON_WRITE)
10932     /* Since the read-only flag may be used to protect a string buffer, we
10933        cannot do copy-on-write with existing read-only scalars that are not
10934        already copy-on-write scalars.  To allow $_ = "hello" to do COW with
10935        that constant, mark the constant as COWable here, if it is not
10936        already read-only. */
10937     if (!SvREADONLY(sv) && !SvIsCOW(sv) && SvCANCOW(sv)) {
10938         SvIsCOW_on(sv);
10939         CowREFCNT(sv) = 0;
10940 # ifdef PERL_DEBUG_READONLY_COW
10941         sv_buf_to_ro(sv);
10942 # endif
10943     }
10944 #endif
10945     SvREADONLY_on(sv);
10946     return o;
10947 }
10948
10949 OP *
10950 Perl_ck_trunc(pTHX_ OP *o)
10951 {
10952     PERL_ARGS_ASSERT_CK_TRUNC;
10953
10954     if (o->op_flags & OPf_KIDS) {
10955         SVOP *kid = (SVOP*)cUNOPo->op_first;
10956
10957         if (kid->op_type == OP_NULL)
10958             kid = (SVOP*)OP_SIBLING(kid);
10959         if (kid && kid->op_type == OP_CONST &&
10960             (kid->op_private & OPpCONST_BARE) &&
10961             !kid->op_folded)
10962         {
10963             o->op_flags |= OPf_SPECIAL;
10964             kid->op_private &= ~OPpCONST_STRICT;
10965         }
10966     }
10967     return ck_fun(o);
10968 }
10969
10970 OP *
10971 Perl_ck_substr(pTHX_ OP *o)
10972 {
10973     PERL_ARGS_ASSERT_CK_SUBSTR;
10974
10975     o = ck_fun(o);
10976     if ((o->op_flags & OPf_KIDS) && (o->op_private == 4)) {
10977         OP *kid = cLISTOPo->op_first;
10978
10979         if (kid->op_type == OP_NULL)
10980             kid = OP_SIBLING(kid);
10981         if (kid)
10982             kid->op_flags |= OPf_MOD;
10983
10984     }
10985     return o;
10986 }
10987
10988 OP *
10989 Perl_ck_tell(pTHX_ OP *o)
10990 {
10991     PERL_ARGS_ASSERT_CK_TELL;
10992     o = ck_fun(o);
10993     if (o->op_flags & OPf_KIDS) {
10994      OP *kid = cLISTOPo->op_first;
10995      if (kid->op_type == OP_NULL && OP_HAS_SIBLING(kid)) kid = OP_SIBLING(kid);
10996      if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
10997     }
10998     return o;
10999 }
11000
11001 OP *
11002 Perl_ck_each(pTHX_ OP *o)
11003 {
11004     dVAR;
11005     OP *kid = o->op_flags & OPf_KIDS ? cUNOPo->op_first : NULL;
11006     const unsigned orig_type  = o->op_type;
11007     const unsigned array_type = orig_type == OP_EACH ? OP_AEACH
11008                               : orig_type == OP_KEYS ? OP_AKEYS : OP_AVALUES;
11009     const unsigned ref_type   = orig_type == OP_EACH ? OP_REACH
11010                               : orig_type == OP_KEYS ? OP_RKEYS : OP_RVALUES;
11011
11012     PERL_ARGS_ASSERT_CK_EACH;
11013
11014     if (kid) {
11015         switch (kid->op_type) {
11016             case OP_PADHV:
11017             case OP_RV2HV:
11018                 break;
11019             case OP_PADAV:
11020             case OP_RV2AV:
11021                 CHANGE_TYPE(o, array_type);
11022                 break;
11023             case OP_CONST:
11024                 if (kid->op_private == OPpCONST_BARE
11025                  || !SvROK(cSVOPx_sv(kid))
11026                  || (  SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV
11027                     && SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVHV  )
11028                    )
11029                     /* we let ck_fun handle it */
11030                     break;
11031             default:
11032                 CHANGE_TYPE(o, ref_type);
11033                 scalar(kid);
11034         }
11035     }
11036     /* if treating as a reference, defer additional checks to runtime */
11037     if (o->op_type == ref_type) {
11038         /* diag_listed_as: keys on reference is experimental */
11039         Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__AUTODEREF),
11040                               "%s is experimental", PL_op_desc[ref_type]);
11041         return o;
11042     }
11043     return ck_fun(o);
11044 }
11045
11046 OP *
11047 Perl_ck_length(pTHX_ OP *o)
11048 {
11049     PERL_ARGS_ASSERT_CK_LENGTH;
11050
11051     o = ck_fun(o);
11052
11053     if (ckWARN(WARN_SYNTAX)) {
11054         const OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : NULL;
11055
11056         if (kid) {
11057             SV *name = NULL;
11058             const bool hash = kid->op_type == OP_PADHV
11059                            || kid->op_type == OP_RV2HV;
11060             switch (kid->op_type) {
11061                 case OP_PADHV:
11062                 case OP_PADAV:
11063                 case OP_RV2HV:
11064                 case OP_RV2AV:
11065                     name = S_op_varname(aTHX_ kid);
11066                     break;
11067                 default:
11068                     return o;
11069             }
11070             if (name)
11071                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
11072                     "length() used on %"SVf" (did you mean \"scalar(%s%"SVf
11073                     ")\"?)",
11074                     SVfARG(name), hash ? "keys " : "", SVfARG(name)
11075                 );
11076             else if (hash)
11077      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
11078                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
11079                     "length() used on %%hash (did you mean \"scalar(keys %%hash)\"?)");
11080             else
11081      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
11082                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
11083                     "length() used on @array (did you mean \"scalar(@array)\"?)");
11084         }
11085     }
11086
11087     return o;
11088 }
11089
11090 /* Check for in place reverse and sort assignments like "@a = reverse @a"
11091    and modify the optree to make them work inplace */
11092
11093 STATIC void
11094 S_inplace_aassign(pTHX_ OP *o) {
11095
11096     OP *modop, *modop_pushmark;
11097     OP *oright;
11098     OP *oleft, *oleft_pushmark;
11099
11100     PERL_ARGS_ASSERT_INPLACE_AASSIGN;
11101
11102     assert((o->op_flags & OPf_WANT) == OPf_WANT_VOID);
11103
11104     assert(cUNOPo->op_first->op_type == OP_NULL);
11105     modop_pushmark = cUNOPx(cUNOPo->op_first)->op_first;
11106     assert(modop_pushmark->op_type == OP_PUSHMARK);
11107     modop = OP_SIBLING(modop_pushmark);
11108
11109     if (modop->op_type != OP_SORT && modop->op_type != OP_REVERSE)
11110         return;
11111
11112     /* no other operation except sort/reverse */
11113     if (OP_HAS_SIBLING(modop))
11114         return;
11115
11116     assert(cUNOPx(modop)->op_first->op_type == OP_PUSHMARK);
11117     if (!(oright = OP_SIBLING(cUNOPx(modop)->op_first))) return;
11118
11119     if (modop->op_flags & OPf_STACKED) {
11120         /* skip sort subroutine/block */
11121         assert(oright->op_type == OP_NULL);
11122         oright = OP_SIBLING(oright);
11123     }
11124
11125     assert(OP_SIBLING(cUNOPo->op_first)->op_type == OP_NULL);
11126     oleft_pushmark = cUNOPx(OP_SIBLING(cUNOPo->op_first))->op_first;
11127     assert(oleft_pushmark->op_type == OP_PUSHMARK);
11128     oleft = OP_SIBLING(oleft_pushmark);
11129
11130     /* Check the lhs is an array */
11131     if (!oleft ||
11132         (oleft->op_type != OP_RV2AV && oleft->op_type != OP_PADAV)
11133         || OP_HAS_SIBLING(oleft)
11134         || (oleft->op_private & OPpLVAL_INTRO)
11135     )
11136         return;
11137
11138     /* Only one thing on the rhs */
11139     if (OP_HAS_SIBLING(oright))
11140         return;
11141
11142     /* check the array is the same on both sides */
11143     if (oleft->op_type == OP_RV2AV) {
11144         if (oright->op_type != OP_RV2AV
11145             || !cUNOPx(oright)->op_first
11146             || cUNOPx(oright)->op_first->op_type != OP_GV
11147             || cUNOPx(oleft )->op_first->op_type != OP_GV
11148             || cGVOPx_gv(cUNOPx(oleft)->op_first) !=
11149                cGVOPx_gv(cUNOPx(oright)->op_first)
11150         )
11151             return;
11152     }
11153     else if (oright->op_type != OP_PADAV
11154         || oright->op_targ != oleft->op_targ
11155     )
11156         return;
11157
11158     /* This actually is an inplace assignment */
11159
11160     modop->op_private |= OPpSORT_INPLACE;
11161
11162     /* transfer MODishness etc from LHS arg to RHS arg */
11163     oright->op_flags = oleft->op_flags;
11164
11165     /* remove the aassign op and the lhs */
11166     op_null(o);
11167     op_null(oleft_pushmark);
11168     if (oleft->op_type == OP_RV2AV && cUNOPx(oleft)->op_first)
11169         op_null(cUNOPx(oleft)->op_first);
11170     op_null(oleft);
11171 }
11172
11173
11174
11175 /* mechanism for deferring recursion in rpeep() */
11176
11177 #define MAX_DEFERRED 4
11178
11179 #define DEFER(o) \
11180   STMT_START { \
11181     if (defer_ix == (MAX_DEFERRED-1)) { \
11182         OP **defer = defer_queue[defer_base]; \
11183         CALL_RPEEP(*defer); \
11184         S_prune_chain_head(defer); \
11185         defer_base = (defer_base + 1) % MAX_DEFERRED; \
11186         defer_ix--; \
11187     } \
11188     defer_queue[(defer_base + ++defer_ix) % MAX_DEFERRED] = &(o); \
11189   } STMT_END
11190
11191 #define IS_AND_OP(o)   (o->op_type == OP_AND)
11192 #define IS_OR_OP(o)    (o->op_type == OP_OR)
11193
11194
11195 STATIC void
11196 S_null_listop_in_list_context(pTHX_ OP *o)
11197 {
11198     OP *kid;
11199
11200     PERL_ARGS_ASSERT_NULL_LISTOP_IN_LIST_CONTEXT;
11201
11202     /* This is an OP_LIST in list context. That means we
11203      * can ditch the OP_LIST and the OP_PUSHMARK within. */
11204
11205     kid = cLISTOPo->op_first;
11206     /* Find the end of the chain of OPs executed within the OP_LIST. */
11207     while (kid->op_next != o)
11208         kid = kid->op_next;
11209
11210     kid->op_next = o->op_next; /* patch list out of exec chain */
11211     op_null(cUNOPo->op_first); /* NULL the pushmark */
11212     op_null(o); /* NULL the list */
11213 }
11214
11215 /* A peephole optimizer.  We visit the ops in the order they're to execute.
11216  * See the comments at the top of this file for more details about when
11217  * peep() is called */
11218
11219 void
11220 Perl_rpeep(pTHX_ OP *o)
11221 {
11222     dVAR;
11223     OP* oldop = NULL;
11224     OP* oldoldop = NULL;
11225     OP** defer_queue[MAX_DEFERRED]; /* small queue of deferred branches */
11226     int defer_base = 0;
11227     int defer_ix = -1;
11228     OP *fop;
11229     OP *sop;
11230
11231     if (!o || o->op_opt)
11232         return;
11233     ENTER;
11234     SAVEOP();
11235     SAVEVPTR(PL_curcop);
11236     for (;; o = o->op_next) {
11237         if (o && o->op_opt)
11238             o = NULL;
11239         if (!o) {
11240             while (defer_ix >= 0) {
11241                 OP **defer =
11242                         defer_queue[(defer_base + defer_ix--) % MAX_DEFERRED];
11243                 CALL_RPEEP(*defer);
11244                 S_prune_chain_head(defer);
11245             }
11246             break;
11247         }
11248
11249         /* By default, this op has now been optimised. A couple of cases below
11250            clear this again.  */
11251         o->op_opt = 1;
11252         PL_op = o;
11253
11254
11255         /* The following will have the OP_LIST and OP_PUSHMARK
11256          * patched out later IF the OP_LIST is in list context.
11257          * So in that case, we can set the this OP's op_next
11258          * to skip to after the OP_PUSHMARK:
11259          *   a THIS -> b
11260          *   d list -> e
11261          *   b   pushmark -> c
11262          *   c   whatever -> d
11263          *   e whatever
11264          * will eventually become:
11265          *   a THIS -> c
11266          *   - ex-list -> -
11267          *   -   ex-pushmark -> -
11268          *   c   whatever -> e
11269          *   e whatever
11270          */
11271         {
11272             OP *sibling;
11273             OP *other_pushmark;
11274             if (OP_TYPE_IS(o->op_next, OP_PUSHMARK)
11275                 && (sibling = OP_SIBLING(o))
11276                 && sibling->op_type == OP_LIST
11277                 /* This KIDS check is likely superfluous since OP_LIST
11278                  * would otherwise be an OP_STUB. */
11279                 && sibling->op_flags & OPf_KIDS
11280                 && (sibling->op_flags & OPf_WANT) == OPf_WANT_LIST
11281                 && (other_pushmark = cLISTOPx(sibling)->op_first)
11282                 /* Pointer equality also effectively checks that it's a
11283                  * pushmark. */
11284                 && other_pushmark == o->op_next)
11285             {
11286                 o->op_next = other_pushmark->op_next;
11287                 null_listop_in_list_context(sibling);
11288             }
11289         }
11290
11291         switch (o->op_type) {
11292         case OP_DBSTATE:
11293             PL_curcop = ((COP*)o);              /* for warnings */
11294             break;
11295         case OP_NEXTSTATE:
11296             PL_curcop = ((COP*)o);              /* for warnings */
11297
11298             /* Optimise a "return ..." at the end of a sub to just be "...".
11299              * This saves 2 ops. Before:
11300              * 1  <;> nextstate(main 1 -e:1) v ->2
11301              * 4  <@> return K ->5
11302              * 2    <0> pushmark s ->3
11303              * -    <1> ex-rv2sv sK/1 ->4
11304              * 3      <#> gvsv[*cat] s ->4
11305              *
11306              * After:
11307              * -  <@> return K ->-
11308              * -    <0> pushmark s ->2
11309              * -    <1> ex-rv2sv sK/1 ->-
11310              * 2      <$> gvsv(*cat) s ->3
11311              */
11312             {
11313                 OP *next = o->op_next;
11314                 OP *sibling = OP_SIBLING(o);
11315                 if (   OP_TYPE_IS(next, OP_PUSHMARK)
11316                     && OP_TYPE_IS(sibling, OP_RETURN)
11317                     && OP_TYPE_IS(sibling->op_next, OP_LINESEQ)
11318                     && OP_TYPE_IS(sibling->op_next->op_next, OP_LEAVESUB)
11319                     && cUNOPx(sibling)->op_first == next
11320                     && OP_HAS_SIBLING(next) && OP_SIBLING(next)->op_next
11321                     && next->op_next
11322                 ) {
11323                     /* Look through the PUSHMARK's siblings for one that
11324                      * points to the RETURN */
11325                     OP *top = OP_SIBLING(next);
11326                     while (top && top->op_next) {
11327                         if (top->op_next == sibling) {
11328                             top->op_next = sibling->op_next;
11329                             o->op_next = next->op_next;
11330                             break;
11331                         }
11332                         top = OP_SIBLING(top);
11333                     }
11334                 }
11335             }
11336
11337             /* Optimise 'my $x; my $y;' into 'my ($x, $y);'
11338              *
11339              * This latter form is then suitable for conversion into padrange
11340              * later on. Convert:
11341              *
11342              *   nextstate1 -> padop1 -> nextstate2 -> padop2 -> nextstate3
11343              *
11344              * into:
11345              *
11346              *   nextstate1 ->     listop     -> nextstate3
11347              *                 /            \
11348              *         pushmark -> padop1 -> padop2
11349              */
11350             if (o->op_next && (
11351                     o->op_next->op_type == OP_PADSV
11352                  || o->op_next->op_type == OP_PADAV
11353                  || o->op_next->op_type == OP_PADHV
11354                 )
11355                 && !(o->op_next->op_private & ~OPpLVAL_INTRO)
11356                 && o->op_next->op_next && o->op_next->op_next->op_type == OP_NEXTSTATE
11357                 && o->op_next->op_next->op_next && (
11358                     o->op_next->op_next->op_next->op_type == OP_PADSV
11359                  || o->op_next->op_next->op_next->op_type == OP_PADAV
11360                  || o->op_next->op_next->op_next->op_type == OP_PADHV
11361                 )
11362                 && !(o->op_next->op_next->op_next->op_private & ~OPpLVAL_INTRO)
11363                 && o->op_next->op_next->op_next->op_next && o->op_next->op_next->op_next->op_next->op_type == OP_NEXTSTATE
11364                 && (!CopLABEL((COP*)o)) /* Don't mess with labels */
11365                 && (!CopLABEL((COP*)o->op_next->op_next)) /* ... */
11366             ) {
11367                 OP *pad1, *ns2, *pad2, *ns3, *newop, *newpm;
11368
11369                 pad1 =    o->op_next;
11370                 ns2  = pad1->op_next;
11371                 pad2 =  ns2->op_next;
11372                 ns3  = pad2->op_next;
11373
11374                 /* we assume here that the op_next chain is the same as
11375                  * the op_sibling chain */
11376                 assert(OP_SIBLING(o)    == pad1);
11377                 assert(OP_SIBLING(pad1) == ns2);
11378                 assert(OP_SIBLING(ns2)  == pad2);
11379                 assert(OP_SIBLING(pad2) == ns3);
11380
11381                 /* create new listop, with children consisting of:
11382                  * a new pushmark, pad1, pad2. */
11383                 OP_SIBLING_set(pad2, NULL);
11384                 newop = newLISTOP(OP_LIST, 0, pad1, pad2);
11385                 newop->op_flags |= OPf_PARENS;
11386                 newop->op_flags = (newop->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
11387                 newpm = cUNOPx(newop)->op_first; /* pushmark */
11388
11389                 /* Kill nextstate2 between padop1/padop2 */
11390                 op_free(ns2);
11391
11392                 o    ->op_next = newpm;
11393                 newpm->op_next = pad1;
11394                 pad1 ->op_next = pad2;
11395                 pad2 ->op_next = newop; /* listop */
11396                 newop->op_next = ns3;
11397
11398                 OP_SIBLING_set(o, newop);
11399                 OP_SIBLING_set(newop, ns3);
11400                 newop->op_lastsib = 0;
11401
11402                 newop->op_flags = (newop->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
11403
11404                 /* Ensure pushmark has this flag if padops do */
11405                 if (pad1->op_flags & OPf_MOD && pad2->op_flags & OPf_MOD) {
11406                     o->op_next->op_flags |= OPf_MOD;
11407                 }
11408
11409                 break;
11410             }
11411
11412             /* Two NEXTSTATEs in a row serve no purpose. Except if they happen
11413                to carry two labels. For now, take the easier option, and skip
11414                this optimisation if the first NEXTSTATE has a label.  */
11415             if (!CopLABEL((COP*)o) && !PERLDB_NOOPT) {
11416                 OP *nextop = o->op_next;
11417                 while (nextop && nextop->op_type == OP_NULL)
11418                     nextop = nextop->op_next;
11419
11420                 if (nextop && (nextop->op_type == OP_NEXTSTATE)) {
11421                     COP *firstcop = (COP *)o;
11422                     COP *secondcop = (COP *)nextop;
11423                     /* We want the COP pointed to by o (and anything else) to
11424                        become the next COP down the line.  */
11425                     cop_free(firstcop);
11426
11427                     firstcop->op_next = secondcop->op_next;
11428
11429                     /* Now steal all its pointers, and duplicate the other
11430                        data.  */
11431                     firstcop->cop_line = secondcop->cop_line;
11432 #ifdef USE_ITHREADS
11433                     firstcop->cop_stashoff = secondcop->cop_stashoff;
11434                     firstcop->cop_file = secondcop->cop_file;
11435 #else
11436                     firstcop->cop_stash = secondcop->cop_stash;
11437                     firstcop->cop_filegv = secondcop->cop_filegv;
11438 #endif
11439                     firstcop->cop_hints = secondcop->cop_hints;
11440                     firstcop->cop_seq = secondcop->cop_seq;
11441                     firstcop->cop_warnings = secondcop->cop_warnings;
11442                     firstcop->cop_hints_hash = secondcop->cop_hints_hash;
11443
11444 #ifdef USE_ITHREADS
11445                     secondcop->cop_stashoff = 0;
11446                     secondcop->cop_file = NULL;
11447 #else
11448                     secondcop->cop_stash = NULL;
11449                     secondcop->cop_filegv = NULL;
11450 #endif
11451                     secondcop->cop_warnings = NULL;
11452                     secondcop->cop_hints_hash = NULL;
11453
11454                     /* If we use op_null(), and hence leave an ex-COP, some
11455                        warnings are misreported. For example, the compile-time
11456                        error in 'use strict; no strict refs;'  */
11457                     secondcop->op_type = OP_NULL;
11458                     secondcop->op_ppaddr = PL_ppaddr[OP_NULL];
11459                 }
11460             }
11461             break;
11462
11463         case OP_CONCAT:
11464             if (o->op_next && o->op_next->op_type == OP_STRINGIFY) {
11465                 if (o->op_next->op_private & OPpTARGET_MY) {
11466                     if (o->op_flags & OPf_STACKED) /* chained concats */
11467                         break; /* ignore_optimization */
11468                     else {
11469                         /* assert(PL_opargs[o->op_type] & OA_TARGLEX); */
11470                         o->op_targ = o->op_next->op_targ;
11471                         o->op_next->op_targ = 0;
11472                         o->op_private |= OPpTARGET_MY;
11473                     }
11474                 }
11475                 op_null(o->op_next);
11476             }
11477             break;
11478         case OP_STUB:
11479             if ((o->op_flags & OPf_WANT) != OPf_WANT_LIST) {
11480                 break; /* Scalar stub must produce undef.  List stub is noop */
11481             }
11482             goto nothin;
11483         case OP_NULL:
11484             if (o->op_targ == OP_NEXTSTATE
11485                 || o->op_targ == OP_DBSTATE)
11486             {
11487                 PL_curcop = ((COP*)o);
11488             }
11489             /* XXX: We avoid setting op_seq here to prevent later calls
11490                to rpeep() from mistakenly concluding that optimisation
11491                has already occurred. This doesn't fix the real problem,
11492                though (See 20010220.007). AMS 20010719 */
11493             /* op_seq functionality is now replaced by op_opt */
11494             o->op_opt = 0;
11495             /* FALLTHROUGH */
11496         case OP_SCALAR:
11497         case OP_LINESEQ:
11498         case OP_SCOPE:
11499         nothin:
11500             if (oldop) {
11501                 oldop->op_next = o->op_next;
11502                 o->op_opt = 0;
11503                 continue;
11504             }
11505             break;
11506
11507         case OP_PUSHMARK:
11508
11509             /* Convert a series of PAD ops for my vars plus support into a
11510              * single padrange op. Basically
11511              *
11512              *    pushmark -> pad[ahs]v -> pad[ahs]?v -> ... -> (list) -> rest
11513              *
11514              * becomes, depending on circumstances, one of
11515              *
11516              *    padrange  ----------------------------------> (list) -> rest
11517              *    padrange  --------------------------------------------> rest
11518              *
11519              * where all the pad indexes are sequential and of the same type
11520              * (INTRO or not).
11521              * We convert the pushmark into a padrange op, then skip
11522              * any other pad ops, and possibly some trailing ops.
11523              * Note that we don't null() the skipped ops, to make it
11524              * easier for Deparse to undo this optimisation (and none of
11525              * the skipped ops are holding any resourses). It also makes
11526              * it easier for find_uninit_var(), as it can just ignore
11527              * padrange, and examine the original pad ops.
11528              */
11529         {
11530             OP *p;
11531             OP *followop = NULL; /* the op that will follow the padrange op */
11532             U8 count = 0;
11533             U8 intro = 0;
11534             PADOFFSET base = 0; /* init only to stop compiler whining */
11535             U8 gimme       = 0; /* init only to stop compiler whining */
11536             bool defav = 0;  /* seen (...) = @_ */
11537             bool reuse = 0;  /* reuse an existing padrange op */
11538
11539             /* look for a pushmark -> gv[_] -> rv2av */
11540
11541             {
11542                 GV *gv;
11543                 OP *rv2av, *q;
11544                 p = o->op_next;
11545                 if (   p->op_type == OP_GV
11546                     && (gv = cGVOPx_gv(p)) && isGV(gv)
11547                     && GvNAMELEN_get(gv) == 1
11548                     && *GvNAME_get(gv) == '_'
11549                     && GvSTASH(gv) == PL_defstash
11550                     && (rv2av = p->op_next)
11551                     && rv2av->op_type == OP_RV2AV
11552                     && !(rv2av->op_flags & OPf_REF)
11553                     && !(rv2av->op_private & (OPpLVAL_INTRO|OPpMAYBE_LVSUB))
11554                     && ((rv2av->op_flags & OPf_WANT) == OPf_WANT_LIST)
11555                     && OP_SIBLING(o) == rv2av /* these two for Deparse */
11556                     && cUNOPx(rv2av)->op_first == p
11557                 ) {
11558                     q = rv2av->op_next;
11559                     if (q->op_type == OP_NULL)
11560                         q = q->op_next;
11561                     if (q->op_type == OP_PUSHMARK) {
11562                         defav = 1;
11563                         p = q;
11564                     }
11565                 }
11566             }
11567             if (!defav) {
11568                 /* To allow Deparse to pessimise this, it needs to be able
11569                  * to restore the pushmark's original op_next, which it
11570                  * will assume to be the same as OP_SIBLING. */
11571                 if (o->op_next != OP_SIBLING(o))
11572                     break;
11573                 p = o;
11574             }
11575
11576             /* scan for PAD ops */
11577
11578             for (p = p->op_next; p; p = p->op_next) {
11579                 if (p->op_type == OP_NULL)
11580                     continue;
11581
11582                 if ((     p->op_type != OP_PADSV
11583                        && p->op_type != OP_PADAV
11584                        && p->op_type != OP_PADHV
11585                     )
11586                       /* any private flag other than INTRO? e.g. STATE */
11587                    || (p->op_private & ~OPpLVAL_INTRO)
11588                 )
11589                     break;
11590
11591                 /* let $a[N] potentially be optimised into AELEMFAST_LEX
11592                  * instead */
11593                 if (   p->op_type == OP_PADAV
11594                     && p->op_next
11595                     && p->op_next->op_type == OP_CONST
11596                     && p->op_next->op_next
11597                     && p->op_next->op_next->op_type == OP_AELEM
11598                 )
11599                     break;
11600
11601                 /* for 1st padop, note what type it is and the range
11602                  * start; for the others, check that it's the same type
11603                  * and that the targs are contiguous */
11604                 if (count == 0) {
11605                     intro = (p->op_private & OPpLVAL_INTRO);
11606                     base = p->op_targ;
11607                     gimme = (p->op_flags & OPf_WANT);
11608                 }
11609                 else {
11610                     if ((p->op_private & OPpLVAL_INTRO) != intro)
11611                         break;
11612                     /* Note that you'd normally  expect targs to be
11613                      * contiguous in my($a,$b,$c), but that's not the case
11614                      * when external modules start doing things, e.g.
11615                      i* Function::Parameters */
11616                     if (p->op_targ != base + count)
11617                         break;
11618                     assert(p->op_targ == base + count);
11619                     /* all the padops should be in the same context */
11620                     if (gimme != (p->op_flags & OPf_WANT))
11621                         break;
11622                 }
11623
11624                 /* for AV, HV, only when we're not flattening */
11625                 if (   p->op_type != OP_PADSV
11626                     && gimme != OPf_WANT_VOID
11627                     && !(p->op_flags & OPf_REF)
11628                 )
11629                     break;
11630
11631                 if (count >= OPpPADRANGE_COUNTMASK)
11632                     break;
11633
11634                 /* there's a biggest base we can fit into a
11635                  * SAVEt_CLEARPADRANGE in pp_padrange */
11636                 if (intro && base >
11637                         (UV_MAX >> (OPpPADRANGE_COUNTSHIFT+SAVE_TIGHT_SHIFT)))
11638                     break;
11639
11640                 /* Success! We've got another valid pad op to optimise away */
11641                 count++;
11642                 followop = p->op_next;
11643             }
11644
11645             if (count < 1)
11646                 break;
11647
11648             /* pp_padrange in specifically compile-time void context
11649              * skips pushing a mark and lexicals; in all other contexts
11650              * (including unknown till runtime) it pushes a mark and the
11651              * lexicals. We must be very careful then, that the ops we
11652              * optimise away would have exactly the same effect as the
11653              * padrange.
11654              * In particular in void context, we can only optimise to
11655              * a padrange if see see the complete sequence
11656              *     pushmark, pad*v, ...., list, nextstate
11657              * which has the net effect of of leaving the stack empty
11658              * (for now we leave the nextstate in the execution chain, for
11659              * its other side-effects).
11660              */
11661             assert(followop);
11662             if (gimme == OPf_WANT_VOID) {
11663                 if (OP_TYPE_IS_OR_WAS(followop, OP_LIST)
11664                         && gimme == (followop->op_flags & OPf_WANT)
11665                         && (   followop->op_next->op_type == OP_NEXTSTATE
11666                             || followop->op_next->op_type == OP_DBSTATE))
11667                 {
11668                     followop = followop->op_next; /* skip OP_LIST */
11669
11670                     /* consolidate two successive my(...);'s */
11671
11672                     if (   oldoldop
11673                         && oldoldop->op_type == OP_PADRANGE
11674                         && (oldoldop->op_flags & OPf_WANT) == OPf_WANT_VOID
11675                         && (oldoldop->op_private & OPpLVAL_INTRO) == intro
11676                         && !(oldoldop->op_flags & OPf_SPECIAL)
11677                     ) {
11678                         U8 old_count;
11679                         assert(oldoldop->op_next == oldop);
11680                         assert(   oldop->op_type == OP_NEXTSTATE
11681                                || oldop->op_type == OP_DBSTATE);
11682                         assert(oldop->op_next == o);
11683
11684                         old_count
11685                             = (oldoldop->op_private & OPpPADRANGE_COUNTMASK);
11686
11687                        /* Do not assume pad offsets for $c and $d are con-
11688                           tiguous in
11689                             my ($a,$b,$c);
11690                             my ($d,$e,$f);
11691                         */
11692                         if (  oldoldop->op_targ + old_count == base
11693                            && old_count < OPpPADRANGE_COUNTMASK - count) {
11694                             base = oldoldop->op_targ;
11695                             count += old_count;
11696                             reuse = 1;
11697                         }
11698                     }
11699
11700                     /* if there's any immediately following singleton
11701                      * my var's; then swallow them and the associated
11702                      * nextstates; i.e.
11703                      *    my ($a,$b); my $c; my $d;
11704                      * is treated as
11705                      *    my ($a,$b,$c,$d);
11706                      */
11707
11708                     while (    ((p = followop->op_next))
11709                             && (  p->op_type == OP_PADSV
11710                                || p->op_type == OP_PADAV
11711                                || p->op_type == OP_PADHV)
11712                             && (p->op_flags & OPf_WANT) == OPf_WANT_VOID
11713                             && (p->op_private & OPpLVAL_INTRO) == intro
11714                             && !(p->op_private & ~OPpLVAL_INTRO)
11715                             && p->op_next
11716                             && (   p->op_next->op_type == OP_NEXTSTATE
11717                                 || p->op_next->op_type == OP_DBSTATE)
11718                             && count < OPpPADRANGE_COUNTMASK
11719                             && base + count == p->op_targ
11720                     ) {
11721                         count++;
11722                         followop = p->op_next;
11723                     }
11724                 }
11725                 else
11726                     break;
11727             }
11728
11729             if (reuse) {
11730                 assert(oldoldop->op_type == OP_PADRANGE);
11731                 oldoldop->op_next = followop;
11732                 oldoldop->op_private = (intro | count);
11733                 o = oldoldop;
11734                 oldop = NULL;
11735                 oldoldop = NULL;
11736             }
11737             else {
11738                 /* Convert the pushmark into a padrange.
11739                  * To make Deparse easier, we guarantee that a padrange was
11740                  * *always* formerly a pushmark */
11741                 assert(o->op_type == OP_PUSHMARK);
11742                 o->op_next = followop;
11743                 o->op_type = OP_PADRANGE;
11744                 o->op_ppaddr = PL_ppaddr[OP_PADRANGE];
11745                 o->op_targ = base;
11746                 /* bit 7: INTRO; bit 6..0: count */
11747                 o->op_private = (intro | count);
11748                 o->op_flags = ((o->op_flags & ~(OPf_WANT|OPf_SPECIAL))
11749                                     | gimme | (defav ? OPf_SPECIAL : 0));
11750             }
11751             break;
11752         }
11753
11754         case OP_PADAV:
11755         case OP_GV:
11756             if (o->op_type == OP_PADAV || o->op_next->op_type == OP_RV2AV) {
11757                 OP* const pop = (o->op_type == OP_PADAV) ?
11758                             o->op_next : o->op_next->op_next;
11759                 IV i;
11760                 if (pop && pop->op_type == OP_CONST &&
11761                     ((PL_op = pop->op_next)) &&
11762                     pop->op_next->op_type == OP_AELEM &&
11763                     !(pop->op_next->op_private &
11764                       (OPpLVAL_INTRO|OPpLVAL_DEFER|OPpDEREF|OPpMAYBE_LVSUB)) &&
11765                     (i = SvIV(((SVOP*)pop)->op_sv)) >= -128 && i <= 127)
11766                 {
11767                     GV *gv;
11768                     if (cSVOPx(pop)->op_private & OPpCONST_STRICT)
11769                         no_bareword_allowed(pop);
11770                     if (o->op_type == OP_GV)
11771                         op_null(o->op_next);
11772                     op_null(pop->op_next);
11773                     op_null(pop);
11774                     o->op_flags |= pop->op_next->op_flags & OPf_MOD;
11775                     o->op_next = pop->op_next->op_next;
11776                     o->op_ppaddr = PL_ppaddr[OP_AELEMFAST];
11777                     o->op_private = (U8)i;
11778                     if (o->op_type == OP_GV) {
11779                         gv = cGVOPo_gv;
11780                         GvAVn(gv);
11781                         o->op_type = OP_AELEMFAST;
11782                     }
11783                     else
11784                         o->op_type = OP_AELEMFAST_LEX;
11785                 }
11786                 break;
11787             }
11788
11789             if (o->op_next->op_type == OP_RV2SV) {
11790                 if (!(o->op_next->op_private & OPpDEREF)) {
11791                     op_null(o->op_next);
11792                     o->op_private |= o->op_next->op_private & (OPpLVAL_INTRO
11793                                                                | OPpOUR_INTRO);
11794                     o->op_next = o->op_next->op_next;
11795                     o->op_type = OP_GVSV;
11796                     o->op_ppaddr = PL_ppaddr[OP_GVSV];
11797                 }
11798             }
11799             else if (o->op_next->op_type == OP_READLINE
11800                     && o->op_next->op_next->op_type == OP_CONCAT
11801                     && (o->op_next->op_next->op_flags & OPf_STACKED))
11802             {
11803                 /* Turn "$a .= <FH>" into an OP_RCATLINE. AMS 20010917 */
11804                 o->op_type   = OP_RCATLINE;
11805                 o->op_flags |= OPf_STACKED;
11806                 o->op_ppaddr = PL_ppaddr[OP_RCATLINE];
11807                 op_null(o->op_next->op_next);
11808                 op_null(o->op_next);
11809             }
11810
11811             break;
11812         
11813 #define HV_OR_SCALARHV(op)                                   \
11814     (  (op)->op_type == OP_PADHV || (op)->op_type == OP_RV2HV \
11815        ? (op)                                                  \
11816        : (op)->op_type == OP_SCALAR && (op)->op_flags & OPf_KIDS \
11817        && (  cUNOPx(op)->op_first->op_type == OP_PADHV          \
11818           || cUNOPx(op)->op_first->op_type == OP_RV2HV)          \
11819          ? cUNOPx(op)->op_first                                   \
11820          : NULL)
11821
11822         case OP_NOT:
11823             if ((fop = HV_OR_SCALARHV(cUNOP->op_first)))
11824                 fop->op_private |= OPpTRUEBOOL;
11825             break;
11826
11827         case OP_AND:
11828         case OP_OR:
11829         case OP_DOR:
11830             fop = cLOGOP->op_first;
11831             sop = OP_SIBLING(fop);
11832             while (cLOGOP->op_other->op_type == OP_NULL)
11833                 cLOGOP->op_other = cLOGOP->op_other->op_next;
11834             while (o->op_next && (   o->op_type == o->op_next->op_type
11835                                   || o->op_next->op_type == OP_NULL))
11836                 o->op_next = o->op_next->op_next;
11837
11838             /* if we're an OR and our next is a AND in void context, we'll
11839                follow it's op_other on short circuit, same for reverse.
11840                We can't do this with OP_DOR since if it's true, its return
11841                value is the underlying value which must be evaluated
11842                by the next op */
11843             if (o->op_next &&
11844                 (
11845                     (IS_AND_OP(o) && IS_OR_OP(o->op_next))
11846                  || (IS_OR_OP(o) && IS_AND_OP(o->op_next))
11847                 )
11848                 && (o->op_next->op_flags & OPf_WANT) == OPf_WANT_VOID
11849             ) {
11850                 o->op_next = ((LOGOP*)o->op_next)->op_other;
11851             }
11852             DEFER(cLOGOP->op_other);
11853           
11854             o->op_opt = 1;
11855             fop = HV_OR_SCALARHV(fop);
11856             if (sop) sop = HV_OR_SCALARHV(sop);
11857             if (fop || sop
11858             ){  
11859                 OP * nop = o;
11860                 OP * lop = o;
11861                 if (!((nop->op_flags & OPf_WANT) == OPf_WANT_VOID)) {
11862                     while (nop && nop->op_next) {
11863                         switch (nop->op_next->op_type) {
11864                             case OP_NOT:
11865                             case OP_AND:
11866                             case OP_OR:
11867                             case OP_DOR:
11868                                 lop = nop = nop->op_next;
11869                                 break;
11870                             case OP_NULL:
11871                                 nop = nop->op_next;
11872                                 break;
11873                             default:
11874                                 nop = NULL;
11875                                 break;
11876                         }
11877                     }            
11878                 }
11879                 if (fop) {
11880                     if (  (lop->op_flags & OPf_WANT) == OPf_WANT_VOID
11881                       || o->op_type == OP_AND  )
11882                         fop->op_private |= OPpTRUEBOOL;
11883                     else if (!(lop->op_flags & OPf_WANT))
11884                         fop->op_private |= OPpMAYBE_TRUEBOOL;
11885                 }
11886                 if (  (lop->op_flags & OPf_WANT) == OPf_WANT_VOID
11887                    && sop)
11888                     sop->op_private |= OPpTRUEBOOL;
11889             }                  
11890             
11891             
11892             break;
11893         
11894         case OP_COND_EXPR:
11895             if ((fop = HV_OR_SCALARHV(cLOGOP->op_first)))
11896                 fop->op_private |= OPpTRUEBOOL;
11897 #undef HV_OR_SCALARHV
11898             /* GERONIMO! */ /* FALLTHROUGH */
11899
11900         case OP_MAPWHILE:
11901         case OP_GREPWHILE:
11902         case OP_ANDASSIGN:
11903         case OP_ORASSIGN:
11904         case OP_DORASSIGN:
11905         case OP_RANGE:
11906         case OP_ONCE:
11907             while (cLOGOP->op_other->op_type == OP_NULL)
11908                 cLOGOP->op_other = cLOGOP->op_other->op_next;
11909             DEFER(cLOGOP->op_other);
11910             break;
11911
11912         case OP_ENTERLOOP:
11913         case OP_ENTERITER:
11914             while (cLOOP->op_redoop->op_type == OP_NULL)
11915                 cLOOP->op_redoop = cLOOP->op_redoop->op_next;
11916             while (cLOOP->op_nextop->op_type == OP_NULL)
11917                 cLOOP->op_nextop = cLOOP->op_nextop->op_next;
11918             while (cLOOP->op_lastop->op_type == OP_NULL)
11919                 cLOOP->op_lastop = cLOOP->op_lastop->op_next;
11920             /* a while(1) loop doesn't have an op_next that escapes the
11921              * loop, so we have to explicitly follow the op_lastop to
11922              * process the rest of the code */
11923             DEFER(cLOOP->op_lastop);
11924             break;
11925
11926         case OP_ENTERTRY:
11927             assert(cLOGOPo->op_other->op_type == OP_LEAVETRY);
11928             DEFER(cLOGOPo->op_other);
11929             break;
11930
11931         case OP_SUBST:
11932             assert(!(cPMOP->op_pmflags & PMf_ONCE));
11933             while (cPMOP->op_pmstashstartu.op_pmreplstart &&
11934                    cPMOP->op_pmstashstartu.op_pmreplstart->op_type == OP_NULL)
11935                 cPMOP->op_pmstashstartu.op_pmreplstart
11936                     = cPMOP->op_pmstashstartu.op_pmreplstart->op_next;
11937             DEFER(cPMOP->op_pmstashstartu.op_pmreplstart);
11938             break;
11939
11940         case OP_SORT: {
11941             OP *oright;
11942
11943             if (o->op_flags & OPf_SPECIAL) {
11944                 /* first arg is a code block */
11945                 OP * const nullop = OP_SIBLING(cLISTOP->op_first);
11946                 OP * kid          = cUNOPx(nullop)->op_first;
11947
11948                 assert(nullop->op_type == OP_NULL);
11949                 assert(kid->op_type == OP_SCOPE
11950                  || (kid->op_type == OP_NULL && kid->op_targ == OP_LEAVE));
11951                 /* since OP_SORT doesn't have a handy op_other-style
11952                  * field that can point directly to the start of the code
11953                  * block, store it in the otherwise-unused op_next field
11954                  * of the top-level OP_NULL. This will be quicker at
11955                  * run-time, and it will also allow us to remove leading
11956                  * OP_NULLs by just messing with op_nexts without
11957                  * altering the basic op_first/op_sibling layout. */
11958                 kid = kLISTOP->op_first;
11959                 assert(
11960                       (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
11961                     || kid->op_type == OP_STUB
11962                     || kid->op_type == OP_ENTER);
11963                 nullop->op_next = kLISTOP->op_next;
11964                 DEFER(nullop->op_next);
11965             }
11966
11967             /* check that RHS of sort is a single plain array */
11968             oright = cUNOPo->op_first;
11969             if (!oright || oright->op_type != OP_PUSHMARK)
11970                 break;
11971
11972             if (o->op_private & OPpSORT_INPLACE)
11973                 break;
11974
11975             /* reverse sort ... can be optimised.  */
11976             if (!OP_HAS_SIBLING(cUNOPo)) {
11977                 /* Nothing follows us on the list. */
11978                 OP * const reverse = o->op_next;
11979
11980                 if (reverse->op_type == OP_REVERSE &&
11981                     (reverse->op_flags & OPf_WANT) == OPf_WANT_LIST) {
11982                     OP * const pushmark = cUNOPx(reverse)->op_first;
11983                     if (pushmark && (pushmark->op_type == OP_PUSHMARK)
11984                         && (OP_SIBLING(cUNOPx(pushmark)) == o)) {
11985                         /* reverse -> pushmark -> sort */
11986                         o->op_private |= OPpSORT_REVERSE;
11987                         op_null(reverse);
11988                         pushmark->op_next = oright->op_next;
11989                         op_null(oright);
11990                     }
11991                 }
11992             }
11993
11994             break;
11995         }
11996
11997         case OP_REVERSE: {
11998             OP *ourmark, *theirmark, *ourlast, *iter, *expushmark, *rv2av;
11999             OP *gvop = NULL;
12000             LISTOP *enter, *exlist;
12001
12002             if (o->op_private & OPpSORT_INPLACE)
12003                 break;
12004
12005             enter = (LISTOP *) o->op_next;
12006             if (!enter)
12007                 break;
12008             if (enter->op_type == OP_NULL) {
12009                 enter = (LISTOP *) enter->op_next;
12010                 if (!enter)
12011                     break;
12012             }
12013             /* for $a (...) will have OP_GV then OP_RV2GV here.
12014                for (...) just has an OP_GV.  */
12015             if (enter->op_type == OP_GV) {
12016                 gvop = (OP *) enter;
12017                 enter = (LISTOP *) enter->op_next;
12018                 if (!enter)
12019                     break;
12020                 if (enter->op_type == OP_RV2GV) {
12021                   enter = (LISTOP *) enter->op_next;
12022                   if (!enter)
12023                     break;
12024                 }
12025             }
12026
12027             if (enter->op_type != OP_ENTERITER)
12028                 break;
12029
12030             iter = enter->op_next;
12031             if (!iter || iter->op_type != OP_ITER)
12032                 break;
12033             
12034             expushmark = enter->op_first;
12035             if (!expushmark || expushmark->op_type != OP_NULL
12036                 || expushmark->op_targ != OP_PUSHMARK)
12037                 break;
12038
12039             exlist = (LISTOP *) OP_SIBLING(expushmark);
12040             if (!exlist || exlist->op_type != OP_NULL
12041                 || exlist->op_targ != OP_LIST)
12042                 break;
12043
12044             if (exlist->op_last != o) {
12045                 /* Mmm. Was expecting to point back to this op.  */
12046                 break;
12047             }
12048             theirmark = exlist->op_first;
12049             if (!theirmark || theirmark->op_type != OP_PUSHMARK)
12050                 break;
12051
12052             if (OP_SIBLING(theirmark) != o) {
12053                 /* There's something between the mark and the reverse, eg
12054                    for (1, reverse (...))
12055                    so no go.  */
12056                 break;
12057             }
12058
12059             ourmark = ((LISTOP *)o)->op_first;
12060             if (!ourmark || ourmark->op_type != OP_PUSHMARK)
12061                 break;
12062
12063             ourlast = ((LISTOP *)o)->op_last;
12064             if (!ourlast || ourlast->op_next != o)
12065                 break;
12066
12067             rv2av = OP_SIBLING(ourmark);
12068             if (rv2av && rv2av->op_type == OP_RV2AV && !OP_HAS_SIBLING(rv2av)
12069                 && rv2av->op_flags == (OPf_WANT_LIST | OPf_KIDS)
12070                 && enter->op_flags == (OPf_WANT_LIST | OPf_KIDS)) {
12071                 /* We're just reversing a single array.  */
12072                 rv2av->op_flags = OPf_WANT_SCALAR | OPf_KIDS | OPf_REF;
12073                 enter->op_flags |= OPf_STACKED;
12074             }
12075
12076             /* We don't have control over who points to theirmark, so sacrifice
12077                ours.  */
12078             theirmark->op_next = ourmark->op_next;
12079             theirmark->op_flags = ourmark->op_flags;
12080             ourlast->op_next = gvop ? gvop : (OP *) enter;
12081             op_null(ourmark);
12082             op_null(o);
12083             enter->op_private |= OPpITER_REVERSED;
12084             iter->op_private |= OPpITER_REVERSED;
12085             
12086             break;
12087         }
12088
12089         case OP_QR:
12090         case OP_MATCH:
12091             if (!(cPMOP->op_pmflags & PMf_ONCE)) {
12092                 assert (!cPMOP->op_pmstashstartu.op_pmreplstart);
12093             }
12094             break;
12095
12096         case OP_RUNCV:
12097             if (!(o->op_private & OPpOFFBYONE) && !CvCLONE(PL_compcv)) {
12098                 SV *sv;
12099                 if (CvEVAL(PL_compcv)) sv = &PL_sv_undef;
12100                 else {
12101                     sv = newRV((SV *)PL_compcv);
12102                     sv_rvweaken(sv);
12103                     SvREADONLY_on(sv);
12104                 }
12105                 o->op_type = OP_CONST;
12106                 o->op_ppaddr = PL_ppaddr[OP_CONST];
12107                 o->op_flags |= OPf_SPECIAL;
12108                 cSVOPo->op_sv = sv;
12109             }
12110             break;
12111
12112         case OP_SASSIGN:
12113             if (OP_GIMME(o,0) == G_VOID) {
12114                 OP *right = cBINOP->op_first;
12115                 if (right) {
12116                     /*   sassign
12117                     *      RIGHT
12118                     *      substr
12119                     *         pushmark
12120                     *         arg1
12121                     *         arg2
12122                     *         ...
12123                     * becomes
12124                     *
12125                     *  ex-sassign
12126                     *     substr
12127                     *        pushmark
12128                     *        RIGHT
12129                     *        arg1
12130                     *        arg2
12131                     *        ...
12132                     */
12133                     OP *left = OP_SIBLING(right);
12134                     if (left->op_type == OP_SUBSTR
12135                          && (left->op_private & 7) < 4) {
12136                         op_null(o);
12137                         /* cut out right */
12138                         op_sibling_splice(o, NULL, 1, NULL);
12139                         /* and insert it as second child of OP_SUBSTR */
12140                         op_sibling_splice(left, cBINOPx(left)->op_first, 0,
12141                                     right);
12142                         left->op_private |= OPpSUBSTR_REPL_FIRST;
12143                         left->op_flags =
12144                             (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
12145                     }
12146                 }
12147             }
12148             break;
12149
12150         case OP_CUSTOM: {
12151             Perl_cpeep_t cpeep = 
12152                 XopENTRYCUSTOM(o, xop_peep);
12153             if (cpeep)
12154                 cpeep(aTHX_ o, oldop);
12155             break;
12156         }
12157             
12158         }
12159         /* did we just null the current op? If so, re-process it to handle
12160          * eliding "empty" ops from the chain */
12161         if (o->op_type == OP_NULL && oldop && oldop->op_next == o) {
12162             o->op_opt = 0;
12163             o = oldop;
12164         }
12165         else {
12166             oldoldop = oldop;
12167             oldop = o;
12168         }
12169     }
12170     LEAVE;
12171 }
12172
12173 void
12174 Perl_peep(pTHX_ OP *o)
12175 {
12176     CALL_RPEEP(o);
12177 }
12178
12179 /*
12180 =head1 Custom Operators
12181
12182 =for apidoc Ao||custom_op_xop
12183 Return the XOP structure for a given custom op.  This macro should be
12184 considered internal to OP_NAME and the other access macros: use them instead.
12185 This macro does call a function.  Prior
12186 to 5.19.6, this was implemented as a
12187 function.
12188
12189 =cut
12190 */
12191
12192 XOPRETANY
12193 Perl_custom_op_get_field(pTHX_ const OP *o, const xop_flags_enum field)
12194 {
12195     SV *keysv;
12196     HE *he = NULL;
12197     XOP *xop;
12198
12199     static const XOP xop_null = { 0, 0, 0, 0, 0 };
12200
12201     PERL_ARGS_ASSERT_CUSTOM_OP_GET_FIELD;
12202     assert(o->op_type == OP_CUSTOM);
12203
12204     /* This is wrong. It assumes a function pointer can be cast to IV,
12205      * which isn't guaranteed, but this is what the old custom OP code
12206      * did. In principle it should be safer to Copy the bytes of the
12207      * pointer into a PV: since the new interface is hidden behind
12208      * functions, this can be changed later if necessary.  */
12209     /* Change custom_op_xop if this ever happens */
12210     keysv = sv_2mortal(newSViv(PTR2IV(o->op_ppaddr)));
12211
12212     if (PL_custom_ops)
12213         he = hv_fetch_ent(PL_custom_ops, keysv, 0, 0);
12214
12215     /* assume noone will have just registered a desc */
12216     if (!he && PL_custom_op_names &&
12217         (he = hv_fetch_ent(PL_custom_op_names, keysv, 0, 0))
12218     ) {
12219         const char *pv;
12220         STRLEN l;
12221
12222         /* XXX does all this need to be shared mem? */
12223         Newxz(xop, 1, XOP);
12224         pv = SvPV(HeVAL(he), l);
12225         XopENTRY_set(xop, xop_name, savepvn(pv, l));
12226         if (PL_custom_op_descs &&
12227             (he = hv_fetch_ent(PL_custom_op_descs, keysv, 0, 0))
12228         ) {
12229             pv = SvPV(HeVAL(he), l);
12230             XopENTRY_set(xop, xop_desc, savepvn(pv, l));
12231         }
12232         Perl_custom_op_register(aTHX_ o->op_ppaddr, xop);
12233     }
12234     else {
12235         if (!he)
12236             xop = (XOP *)&xop_null;
12237         else
12238             xop = INT2PTR(XOP *, SvIV(HeVAL(he)));
12239     }
12240     {
12241         XOPRETANY any;
12242         if(field == XOPe_xop_ptr) {
12243             any.xop_ptr = xop;
12244         } else {
12245             const U32 flags = XopFLAGS(xop);
12246             if(flags & field) {
12247                 switch(field) {
12248                 case XOPe_xop_name:
12249                     any.xop_name = xop->xop_name;
12250                     break;
12251                 case XOPe_xop_desc:
12252                     any.xop_desc = xop->xop_desc;
12253                     break;
12254                 case XOPe_xop_class:
12255                     any.xop_class = xop->xop_class;
12256                     break;
12257                 case XOPe_xop_peep:
12258                     any.xop_peep = xop->xop_peep;
12259                     break;
12260                 default:
12261                     NOT_REACHED;
12262                     break;
12263                 }
12264             } else {
12265                 switch(field) {
12266                 case XOPe_xop_name:
12267                     any.xop_name = XOPd_xop_name;
12268                     break;
12269                 case XOPe_xop_desc:
12270                     any.xop_desc = XOPd_xop_desc;
12271                     break;
12272                 case XOPe_xop_class:
12273                     any.xop_class = XOPd_xop_class;
12274                     break;
12275                 case XOPe_xop_peep:
12276                     any.xop_peep = XOPd_xop_peep;
12277                     break;
12278                 default:
12279                     NOT_REACHED;
12280                     break;
12281                 }
12282             }
12283         }
12284         /* Some gcc releases emit a warning for this function:
12285          * op.c: In function 'Perl_custom_op_get_field':
12286          * op.c:...: warning: 'any.xop_name' may be used uninitialized in this function [-Wmaybe-uninitialized]
12287          * Whether this is true, is currently unknown. */
12288         return any;
12289     }
12290 }
12291
12292 /*
12293 =for apidoc Ao||custom_op_register
12294 Register a custom op.  See L<perlguts/"Custom Operators">.
12295
12296 =cut
12297 */
12298
12299 void
12300 Perl_custom_op_register(pTHX_ Perl_ppaddr_t ppaddr, const XOP *xop)
12301 {
12302     SV *keysv;
12303
12304     PERL_ARGS_ASSERT_CUSTOM_OP_REGISTER;
12305
12306     /* see the comment in custom_op_xop */
12307     keysv = sv_2mortal(newSViv(PTR2IV(ppaddr)));
12308
12309     if (!PL_custom_ops)
12310         PL_custom_ops = newHV();
12311
12312     if (!hv_store_ent(PL_custom_ops, keysv, newSViv(PTR2IV(xop)), 0))
12313         Perl_croak(aTHX_ "panic: can't register custom OP %s", xop->xop_name);
12314 }
12315
12316 /*
12317
12318 =for apidoc core_prototype
12319
12320 This function assigns the prototype of the named core function to C<sv>, or
12321 to a new mortal SV if C<sv> is NULL.  It returns the modified C<sv>, or
12322 NULL if the core function has no prototype.  C<code> is a code as returned
12323 by C<keyword()>.  It must not be equal to 0.
12324
12325 =cut
12326 */
12327
12328 SV *
12329 Perl_core_prototype(pTHX_ SV *sv, const char *name, const int code,
12330                           int * const opnum)
12331 {
12332     int i = 0, n = 0, seen_question = 0, defgv = 0;
12333     I32 oa;
12334 #define MAX_ARGS_OP ((sizeof(I32) - 1) * 2)
12335     char str[ MAX_ARGS_OP * 2 + 2 ]; /* One ';', one '\0' */
12336     bool nullret = FALSE;
12337
12338     PERL_ARGS_ASSERT_CORE_PROTOTYPE;
12339
12340     assert (code);
12341
12342     if (!sv) sv = sv_newmortal();
12343
12344 #define retsetpvs(x,y) sv_setpvs(sv, x); if(opnum) *opnum=(y); return sv
12345
12346     switch (code < 0 ? -code : code) {
12347     case KEY_and   : case KEY_chop: case KEY_chomp:
12348     case KEY_cmp   : case KEY_defined: case KEY_delete: case KEY_exec  :
12349     case KEY_exists: case KEY_eq     : case KEY_ge    : case KEY_goto  :
12350     case KEY_grep  : case KEY_gt     : case KEY_last  : case KEY_le    :
12351     case KEY_lt    : case KEY_map    : case KEY_ne    : case KEY_next  :
12352     case KEY_or    : case KEY_print  : case KEY_printf: case KEY_qr    :
12353     case KEY_redo  : case KEY_require: case KEY_return: case KEY_say   :
12354     case KEY_select: case KEY_sort   : case KEY_split : case KEY_system:
12355     case KEY_x     : case KEY_xor    :
12356         if (!opnum) return NULL; nullret = TRUE; goto findopnum;
12357     case KEY_glob:    retsetpvs("_;", OP_GLOB);
12358     case KEY_keys:    retsetpvs("+", OP_KEYS);
12359     case KEY_values:  retsetpvs("+", OP_VALUES);
12360     case KEY_each:    retsetpvs("+", OP_EACH);
12361     case KEY_push:    retsetpvs("+@", OP_PUSH);
12362     case KEY_unshift: retsetpvs("+@", OP_UNSHIFT);
12363     case KEY_pop:     retsetpvs(";+", OP_POP);
12364     case KEY_shift:   retsetpvs(";+", OP_SHIFT);
12365     case KEY_pos:     retsetpvs(";\\[$*]", OP_POS);
12366     case KEY_splice:
12367         retsetpvs("+;$$@", OP_SPLICE);
12368     case KEY___FILE__: case KEY___LINE__: case KEY___PACKAGE__:
12369         retsetpvs("", 0);
12370     case KEY_evalbytes:
12371         name = "entereval"; break;
12372     case KEY_readpipe:
12373         name = "backtick";
12374     }
12375
12376 #undef retsetpvs
12377
12378   findopnum:
12379     while (i < MAXO) {  /* The slow way. */
12380         if (strEQ(name, PL_op_name[i])
12381             || strEQ(name, PL_op_desc[i]))
12382         {
12383             if (nullret) { assert(opnum); *opnum = i; return NULL; }
12384             goto found;
12385         }
12386         i++;
12387     }
12388     return NULL;
12389   found:
12390     defgv = PL_opargs[i] & OA_DEFGV;
12391     oa = PL_opargs[i] >> OASHIFT;
12392     while (oa) {
12393         if (oa & OA_OPTIONAL && !seen_question && (
12394               !defgv || (oa & (OA_OPTIONAL - 1)) == OA_FILEREF
12395         )) {
12396             seen_question = 1;
12397             str[n++] = ';';
12398         }
12399         if ((oa & (OA_OPTIONAL - 1)) >= OA_AVREF
12400             && (oa & (OA_OPTIONAL - 1)) <= OA_SCALARREF
12401             /* But globs are already references (kinda) */
12402             && (oa & (OA_OPTIONAL - 1)) != OA_FILEREF
12403         ) {
12404             str[n++] = '\\';
12405         }
12406         if ((oa & (OA_OPTIONAL - 1)) == OA_SCALARREF
12407          && !scalar_mod_type(NULL, i)) {
12408             str[n++] = '[';
12409             str[n++] = '$';
12410             str[n++] = '@';
12411             str[n++] = '%';
12412             if (i == OP_LOCK || i == OP_UNDEF) str[n++] = '&';
12413             str[n++] = '*';
12414             str[n++] = ']';
12415         }
12416         else str[n++] = ("?$@@%&*$")[oa & (OA_OPTIONAL - 1)];
12417         if (oa & OA_OPTIONAL && defgv && str[n-1] == '$') {
12418             str[n-1] = '_'; defgv = 0;
12419         }
12420         oa = oa >> 4;
12421     }
12422     if (code == -KEY_not || code == -KEY_getprotobynumber) str[n++] = ';';
12423     str[n++] = '\0';
12424     sv_setpvn(sv, str, n - 1);
12425     if (opnum) *opnum = i;
12426     return sv;
12427 }
12428
12429 OP *
12430 Perl_coresub_op(pTHX_ SV * const coreargssv, const int code,
12431                       const int opnum)
12432 {
12433     OP * const argop = newSVOP(OP_COREARGS,0,coreargssv);
12434     OP *o;
12435
12436     PERL_ARGS_ASSERT_CORESUB_OP;
12437
12438     switch(opnum) {
12439     case 0:
12440         return op_append_elem(OP_LINESEQ,
12441                        argop,
12442                        newSLICEOP(0,
12443                                   newSVOP(OP_CONST, 0, newSViv(-code % 3)),
12444                                   newOP(OP_CALLER,0)
12445                        )
12446                );
12447     case OP_SELECT: /* which represents OP_SSELECT as well */
12448         if (code)
12449             return newCONDOP(
12450                          0,
12451                          newBINOP(OP_GT, 0,
12452                                   newAVREF(newGVOP(OP_GV, 0, PL_defgv)),
12453                                   newSVOP(OP_CONST, 0, newSVuv(1))
12454                                  ),
12455                          coresub_op(newSVuv((UV)OP_SSELECT), 0,
12456                                     OP_SSELECT),
12457                          coresub_op(coreargssv, 0, OP_SELECT)
12458                    );
12459         /* FALLTHROUGH */
12460     default:
12461         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
12462         case OA_BASEOP:
12463             return op_append_elem(
12464                         OP_LINESEQ, argop,
12465                         newOP(opnum,
12466                               opnum == OP_WANTARRAY || opnum == OP_RUNCV
12467                                 ? OPpOFFBYONE << 8 : 0)
12468                    );
12469         case OA_BASEOP_OR_UNOP:
12470             if (opnum == OP_ENTEREVAL) {
12471                 o = newUNOP(OP_ENTEREVAL,OPpEVAL_COPHH<<8,argop);
12472                 if (code == -KEY_evalbytes) o->op_private |= OPpEVAL_BYTES;
12473             }
12474             else o = newUNOP(opnum,0,argop);
12475             if (opnum == OP_CALLER) o->op_private |= OPpOFFBYONE;
12476             else {
12477           onearg:
12478               if (is_handle_constructor(o, 1))
12479                 argop->op_private |= OPpCOREARGS_DEREF1;
12480               if (scalar_mod_type(NULL, opnum))
12481                 argop->op_private |= OPpCOREARGS_SCALARMOD;
12482             }
12483             return o;
12484         default:
12485             o = convert(opnum,OPf_SPECIAL*(opnum == OP_GLOB),argop);
12486             if (is_handle_constructor(o, 2))
12487                 argop->op_private |= OPpCOREARGS_DEREF2;
12488             if (opnum == OP_SUBSTR) {
12489                 o->op_private |= OPpMAYBE_LVSUB;
12490                 return o;
12491             }
12492             else goto onearg;
12493         }
12494     }
12495 }
12496
12497 void
12498 Perl_report_redefined_cv(pTHX_ const SV *name, const CV *old_cv,
12499                                SV * const *new_const_svp)
12500 {
12501     const char *hvname;
12502     bool is_const = !!CvCONST(old_cv);
12503     SV *old_const_sv = is_const ? cv_const_sv(old_cv) : NULL;
12504
12505     PERL_ARGS_ASSERT_REPORT_REDEFINED_CV;
12506
12507     if (is_const && new_const_svp && old_const_sv == *new_const_svp)
12508         return;
12509         /* They are 2 constant subroutines generated from
12510            the same constant. This probably means that
12511            they are really the "same" proxy subroutine
12512            instantiated in 2 places. Most likely this is
12513            when a constant is exported twice.  Don't warn.
12514         */
12515     if (
12516         (ckWARN(WARN_REDEFINE)
12517          && !(
12518                 CvGV(old_cv) && GvSTASH(CvGV(old_cv))
12519              && HvNAMELEN(GvSTASH(CvGV(old_cv))) == 7
12520              && (hvname = HvNAME(GvSTASH(CvGV(old_cv))),
12521                  strEQ(hvname, "autouse"))
12522              )
12523         )
12524      || (is_const
12525          && ckWARN_d(WARN_REDEFINE)
12526          && (!new_const_svp || sv_cmp(old_const_sv, *new_const_svp))
12527         )
12528     )
12529         Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
12530                           is_const
12531                             ? "Constant subroutine %"SVf" redefined"
12532                             : "Subroutine %"SVf" redefined",
12533                           SVfARG(name));
12534 }
12535
12536 /*
12537 =head1 Hook manipulation
12538
12539 These functions provide convenient and thread-safe means of manipulating
12540 hook variables.
12541
12542 =cut
12543 */
12544
12545 /*
12546 =for apidoc Am|void|wrap_op_checker|Optype opcode|Perl_check_t new_checker|Perl_check_t *old_checker_p
12547
12548 Puts a C function into the chain of check functions for a specified op
12549 type.  This is the preferred way to manipulate the L</PL_check> array.
12550 I<opcode> specifies which type of op is to be affected.  I<new_checker>
12551 is a pointer to the C function that is to be added to that opcode's
12552 check chain, and I<old_checker_p> points to the storage location where a
12553 pointer to the next function in the chain will be stored.  The value of
12554 I<new_pointer> is written into the L</PL_check> array, while the value
12555 previously stored there is written to I<*old_checker_p>.
12556
12557 The function should be defined like this:
12558
12559     static OP *new_checker(pTHX_ OP *op) { ... }
12560
12561 It is intended to be called in this manner:
12562
12563     new_checker(aTHX_ op)
12564
12565 I<old_checker_p> should be defined like this:
12566
12567     static Perl_check_t old_checker_p;
12568
12569 L</PL_check> is global to an entire process, and a module wishing to
12570 hook op checking may find itself invoked more than once per process,
12571 typically in different threads.  To handle that situation, this function
12572 is idempotent.  The location I<*old_checker_p> must initially (once
12573 per process) contain a null pointer.  A C variable of static duration
12574 (declared at file scope, typically also marked C<static> to give
12575 it internal linkage) will be implicitly initialised appropriately,
12576 if it does not have an explicit initialiser.  This function will only
12577 actually modify the check chain if it finds I<*old_checker_p> to be null.
12578 This function is also thread safe on the small scale.  It uses appropriate
12579 locking to avoid race conditions in accessing L</PL_check>.
12580
12581 When this function is called, the function referenced by I<new_checker>
12582 must be ready to be called, except for I<*old_checker_p> being unfilled.
12583 In a threading situation, I<new_checker> may be called immediately,
12584 even before this function has returned.  I<*old_checker_p> will always
12585 be appropriately set before I<new_checker> is called.  If I<new_checker>
12586 decides not to do anything special with an op that it is given (which
12587 is the usual case for most uses of op check hooking), it must chain the
12588 check function referenced by I<*old_checker_p>.
12589
12590 If you want to influence compilation of calls to a specific subroutine,
12591 then use L</cv_set_call_checker> rather than hooking checking of all
12592 C<entersub> ops.
12593
12594 =cut
12595 */
12596
12597 void
12598 Perl_wrap_op_checker(pTHX_ Optype opcode,
12599     Perl_check_t new_checker, Perl_check_t *old_checker_p)
12600 {
12601     dVAR;
12602
12603     PERL_UNUSED_CONTEXT;
12604     PERL_ARGS_ASSERT_WRAP_OP_CHECKER;
12605     if (*old_checker_p) return;
12606     OP_CHECK_MUTEX_LOCK;
12607     if (!*old_checker_p) {
12608         *old_checker_p = PL_check[opcode];
12609         PL_check[opcode] = new_checker;
12610     }
12611     OP_CHECK_MUTEX_UNLOCK;
12612 }
12613
12614 #include "XSUB.h"
12615
12616 /* Efficient sub that returns a constant scalar value. */
12617 static void
12618 const_sv_xsub(pTHX_ CV* cv)
12619 {
12620     dXSARGS;
12621     SV *const sv = MUTABLE_SV(XSANY.any_ptr);
12622     PERL_UNUSED_ARG(items);
12623     if (!sv) {
12624         XSRETURN(0);
12625     }
12626     EXTEND(sp, 1);
12627     ST(0) = sv;
12628     XSRETURN(1);
12629 }
12630
12631 static void
12632 const_av_xsub(pTHX_ CV* cv)
12633 {
12634     dXSARGS;
12635     AV * const av = MUTABLE_AV(XSANY.any_ptr);
12636     SP -= items;
12637     assert(av);
12638 #ifndef DEBUGGING
12639     if (!av) {
12640         XSRETURN(0);
12641     }
12642 #endif
12643     if (SvRMAGICAL(av))
12644         Perl_croak(aTHX_ "Magical list constants are not supported");
12645     if (GIMME_V != G_ARRAY) {
12646         EXTEND(SP, 1);
12647         ST(0) = sv_2mortal(newSViv((IV)AvFILLp(av)+1));
12648         XSRETURN(1);
12649     }
12650     EXTEND(SP, AvFILLp(av)+1);
12651     Copy(AvARRAY(av), &ST(0), AvFILLp(av)+1, SV *);
12652     XSRETURN(AvFILLp(av)+1);
12653 }
12654
12655 /*
12656  * Local variables:
12657  * c-indentation-style: bsd
12658  * c-basic-offset: 4
12659  * indent-tabs-mode: nil
12660  * End:
12661  *
12662  * ex: set ts=8 sts=4 sw=4 et:
12663  */