]> git.vpit.fr Git - perl/modules/autovivification.git/blob - autovivification.xs
Improve the thread destructor trick
[perl/modules/autovivification.git] / autovivification.xs
1 /* This file is part of the autovivification Perl module.
2  * See http://search.cpan.org/dist/autovivification/ */
3
4 #define PERL_NO_GET_CONTEXT
5 #include "EXTERN.h"
6 #include "perl.h"
7 #include "XSUB.h"
8
9 #define __PACKAGE__     "autovivification"
10 #define __PACKAGE_LEN__ (sizeof(__PACKAGE__)-1)
11
12 /* --- Compatibility wrappers ---------------------------------------------- */
13
14 #ifndef HvNAME_get
15 # define HvNAME_get(H) HvNAME(H)
16 #endif
17
18 #ifndef HvNAMELEN_get
19 # define HvNAMELEN_get(H) strlen(HvNAME_get(H))
20 #endif
21
22 #define A_HAS_PERL(R, V, S) (PERL_REVISION > (R) || (PERL_REVISION == (R) && (PERL_VERSION > (V) || (PERL_VERSION == (V) && (PERL_SUBVERSION >= (S))))))
23
24 #undef ENTERn
25 #if defined(ENTER_with_name) && !A_HAS_PERL(5, 11, 4)
26 # define ENTERn(N) ENTER_with_name(N)
27 #else
28 # define ENTERn(N) ENTER
29 #endif
30
31 #undef LEAVEn
32 #if defined(LEAVE_with_name) && !A_HAS_PERL(5, 11, 4)
33 # define LEAVEn(N) LEAVE_with_name(N)
34 #else
35 # define LEAVEn(N) LEAVE
36 #endif
37
38 #ifndef A_WORKAROUND_REQUIRE_PROPAGATION
39 # define A_WORKAROUND_REQUIRE_PROPAGATION !A_HAS_PERL(5, 10, 1)
40 #endif
41
42 /* ... Thread safety and multiplicity ...................................... */
43
44 /* Always safe when the workaround isn't needed */
45 #if !A_WORKAROUND_REQUIRE_PROPAGATION
46 # undef A_FORKSAFE
47 # define A_FORKSAFE 1
48 /* Otherwise, safe unless Makefile.PL says it's Win32 */
49 #elif !defined(A_FORKSAFE)
50 # define A_FORKSAFE 1
51 #endif
52
53 #ifndef A_MULTIPLICITY
54 # if defined(MULTIPLICITY) || defined(PERL_IMPLICIT_CONTEXT)
55 #  define A_MULTIPLICITY 1
56 # else
57 #  define A_MULTIPLICITY 0
58 # endif
59 #endif
60 #if A_MULTIPLICITY && !defined(tTHX)
61 # define tTHX PerlInterpreter*
62 #endif
63
64 #if A_MULTIPLICITY && defined(USE_ITHREADS) && defined(dMY_CXT) && defined(MY_CXT) && defined(START_MY_CXT) && defined(MY_CXT_INIT) && (defined(MY_CXT_CLONE) || defined(dMY_CXT_SV))
65 # define A_THREADSAFE 1
66 # ifndef MY_CXT_CLONE
67 #  define MY_CXT_CLONE \
68     dMY_CXT_SV;                                                      \
69     my_cxt_t *my_cxtp = (my_cxt_t*)SvPVX(newSV(sizeof(my_cxt_t)-1)); \
70     Copy(INT2PTR(my_cxt_t*, SvUV(my_cxt_sv)), my_cxtp, 1, my_cxt_t); \
71     sv_setuv(my_cxt_sv, PTR2UV(my_cxtp))
72 # endif
73 #else
74 # define A_THREADSAFE 0
75 # undef  dMY_CXT
76 # define dMY_CXT      dNOOP
77 # undef  MY_CXT
78 # define MY_CXT       a_globaldata
79 # undef  START_MY_CXT
80 # define START_MY_CXT STATIC my_cxt_t MY_CXT;
81 # undef  MY_CXT_INIT
82 # define MY_CXT_INIT  NOOP
83 # undef  MY_CXT_CLONE
84 # define MY_CXT_CLONE NOOP
85 #endif
86
87 /* --- Helpers ------------------------------------------------------------- */
88
89 /* ... Thread-safe hints ................................................... */
90
91 #if A_WORKAROUND_REQUIRE_PROPAGATION
92
93 typedef struct {
94  U32 bits;
95  IV  require_tag;
96 } a_hint_t;
97
98 #define A_HINT_FREE(H) PerlMemShared_free(H)
99
100 #if A_THREADSAFE
101
102 #define PTABLE_NAME        ptable_hints
103 #define PTABLE_VAL_FREE(V) A_HINT_FREE(V)
104
105 #define pPTBL  pTHX
106 #define pPTBL_ pTHX_
107 #define aPTBL  aTHX
108 #define aPTBL_ aTHX_
109
110 #include "ptable.h"
111
112 #define ptable_hints_store(T, K, V) ptable_hints_store(aTHX_ (T), (K), (V))
113 #define ptable_hints_free(T)        ptable_hints_free(aTHX_ (T))
114
115 #define MY_CXT_KEY __PACKAGE__ "::_guts" XS_VERSION
116
117 typedef struct {
118  ptable *tbl;   /* It really is a ptable_hints */
119  tTHX    owner;
120 } my_cxt_t;
121
122 START_MY_CXT
123
124 STATIC SV *a_clone(pTHX_ SV *sv, tTHX owner) {
125 #define a_clone(S, O) a_clone(aTHX_ (S), (O))
126  CLONE_PARAMS  param;
127  AV           *stashes = NULL;
128  SV           *dupsv;
129
130  if (SvTYPE(sv) == SVt_PVHV && HvNAME_get(sv))
131   stashes = newAV();
132
133  param.stashes    = stashes;
134  param.flags      = 0;
135  param.proto_perl = owner;
136
137  dupsv = sv_dup(sv, &param);
138
139  if (stashes) {
140   av_undef(stashes);
141   SvREFCNT_dec(stashes);
142  }
143
144  return SvREFCNT_inc(dupsv);
145 }
146
147 STATIC void a_ptable_clone(pTHX_ ptable_ent *ent, void *ud_) {
148  my_cxt_t *ud = ud_;
149  a_hint_t *h1 = ent->val;
150  a_hint_t *h2;
151
152  if (ud->owner == aTHX)
153   return;
154
155  h2              = PerlMemShared_malloc(sizeof *h2);
156  h2->bits        = h1->bits;
157  h2->require_tag = PTR2IV(a_clone(INT2PTR(SV *, h1->require_tag), ud->owner));
158
159  ptable_hints_store(ud->tbl, ent->key, h2);
160 }
161
162 #include "reap.h"
163
164 STATIC void a_thread_cleanup(pTHX_ void *ud) {
165  dMY_CXT;
166
167  ptable_hints_free(MY_CXT.tbl);
168 }
169
170 #endif /* A_THREADSAFE */
171
172 STATIC IV a_require_tag(pTHX) {
173 #define a_require_tag() a_require_tag(aTHX)
174  const CV *cv, *outside;
175
176  cv = PL_compcv;
177
178  if (!cv) {
179   /* If for some reason the pragma is operational at run-time, try to discover
180    * the current cv in use. */
181   const PERL_SI *si;
182
183   for (si = PL_curstackinfo; si; si = si->si_prev) {
184    I32 cxix;
185
186    for (cxix = si->si_cxix; cxix >= 0; --cxix) {
187     const PERL_CONTEXT *cx = si->si_cxstack + cxix;
188
189     switch (CxTYPE(cx)) {
190      case CXt_SUB:
191      case CXt_FORMAT:
192       /* The propagation workaround is only needed up to 5.10.0 and at that
193        * time format and sub contexts were still identical. And even later the
194        * cv members offsets should have been kept the same. */
195       cv = cx->blk_sub.cv;
196       goto get_enclosing_cv;
197      case CXt_EVAL:
198       cv = cx->blk_eval.cv;
199       goto get_enclosing_cv;
200      default:
201       break;
202     }
203    }
204   }
205
206   cv = PL_main_cv;
207  }
208
209 get_enclosing_cv:
210  for (outside = CvOUTSIDE(cv); outside; outside = CvOUTSIDE(cv))
211   cv = outside;
212
213  return PTR2IV(cv);
214 }
215
216 STATIC SV *a_tag(pTHX_ UV bits) {
217 #define a_tag(B) a_tag(aTHX_ (B))
218  a_hint_t *h;
219  dMY_CXT;
220
221  h              = PerlMemShared_malloc(sizeof *h);
222  h->bits        = bits;
223  h->require_tag = a_require_tag();
224
225 #if A_THREADSAFE
226  /* We only need for the key to be an unique tag for looking up the value later.
227   * Allocated memory provides convenient unique identifiers, so that's why we
228   * use the hint as the key itself. */
229  ptable_hints_store(MY_CXT.tbl, h, h);
230 #endif /* A_THREADSAFE */
231
232  return newSViv(PTR2IV(h));
233 }
234
235 STATIC UV a_detag(pTHX_ const SV *hint) {
236 #define a_detag(H) a_detag(aTHX_ (H))
237  a_hint_t *h;
238  dMY_CXT;
239
240  if (!(hint && SvIOK(hint)))
241   return 0;
242
243  h = INT2PTR(a_hint_t *, SvIVX(hint));
244 #if A_THREADSAFE
245  h = ptable_fetch(MY_CXT.tbl, h);
246 #endif /* A_THREADSAFE */
247
248  if (a_require_tag() != h->require_tag)
249   return 0;
250
251  return h->bits;
252 }
253
254 #else /* A_WORKAROUND_REQUIRE_PROPAGATION */
255
256 #define a_tag(B)   newSVuv(B)
257 /* PVs fetched from the hints chain have their SvLEN set to zero, so get the UV
258  * from a copy. */
259 #define a_detag(H) \
260  ((H)              \
261   ? (SvIOK(H)      \
262      ? SvUVX(H)    \
263      : (SvPOK(H)   \
264         ? sv_2uv(SvLEN(H) ? (H) : sv_mortalcopy(H)) \
265         : 0        \
266        )           \
267      )             \
268   : 0)
269
270 #endif /* !A_WORKAROUND_REQUIRE_PROPAGATION */
271
272 /* Used both for hints and op flags */
273 #define A_HINT_STRICT 1
274 #define A_HINT_WARN   2
275 #define A_HINT_FETCH  4
276 #define A_HINT_STORE  8
277 #define A_HINT_EXISTS 16
278 #define A_HINT_DELETE 32
279 #define A_HINT_NOTIFY (A_HINT_STRICT|A_HINT_WARN)
280 #define A_HINT_DO     (A_HINT_FETCH|A_HINT_STORE|A_HINT_EXISTS|A_HINT_DELETE)
281 #define A_HINT_MASK   (A_HINT_NOTIFY|A_HINT_DO)
282
283 /* Only used in op flags */
284 #define A_HINT_ROOT   64
285 #define A_HINT_DEREF  128
286
287 STATIC U32 a_hash = 0;
288
289 STATIC UV a_hint(pTHX) {
290 #define a_hint() a_hint(aTHX)
291  SV *hint;
292 #if A_HAS_PERL(5, 9, 5)
293  hint = Perl_refcounted_he_fetch(aTHX_ PL_curcop->cop_hints_hash,
294                                        NULL,
295                                        __PACKAGE__, __PACKAGE_LEN__,
296                                        0,
297                                        a_hash);
298 #else
299  SV **val = hv_fetch(GvHV(PL_hintgv), __PACKAGE__, __PACKAGE_LEN__, a_hash);
300  if (!val)
301   return 0;
302  hint = *val;
303 #endif
304  return a_detag(hint);
305 }
306
307 /* ... op => info map ...................................................... */
308
309 typedef struct {
310  OP *(*old_pp)(pTHX);
311  UV flags;
312  void *next;
313 } a_op_info;
314
315 #define PTABLE_NAME        ptable_map
316 #define PTABLE_VAL_FREE(V) PerlMemShared_free(V)
317
318 #include "ptable.h"
319
320 /* PerlMemShared_free() needs the [ap]PTBLMS_? default values */
321 #define ptable_map_store(T, K, V) ptable_map_store(aPTBLMS_ (T), (K), (V))
322
323 STATIC ptable *a_op_map = NULL;
324
325 #ifdef USE_ITHREADS
326 STATIC perl_mutex a_op_map_mutex;
327 #endif
328
329 STATIC const a_op_info *a_map_fetch(const OP *o, a_op_info *oi) {
330  const a_op_info *val;
331
332 #ifdef USE_ITHREADS
333  MUTEX_LOCK(&a_op_map_mutex);
334 #endif
335
336  val = ptable_fetch(a_op_map, o);
337  if (val) {
338   *oi = *val;
339   val = oi;
340  }
341
342 #ifdef USE_ITHREADS
343  MUTEX_UNLOCK(&a_op_map_mutex);
344 #endif
345
346  return val;
347 }
348
349 STATIC const a_op_info *a_map_store_locked(pPTBLMS_ const OP *o, OP *(*old_pp)(pTHX), void *next, UV flags) {
350 #define a_map_store_locked(O, PP, N, F) a_map_store_locked(aPTBLMS_ (O), (PP), (N), (F))
351  a_op_info *oi;
352
353  if (!(oi = ptable_fetch(a_op_map, o))) {
354   oi = PerlMemShared_malloc(sizeof *oi);
355   ptable_map_store(a_op_map, o, oi);
356  }
357
358  oi->old_pp = old_pp;
359  oi->next   = next;
360  oi->flags  = flags;
361
362  return oi;
363 }
364
365 STATIC void a_map_store(pPTBLMS_ const OP *o, OP *(*old_pp)(pTHX), void *next, UV flags) {
366 #define a_map_store(O, PP, N, F) a_map_store(aPTBLMS_ (O), (PP), (N), (F))
367
368 #ifdef USE_ITHREADS
369  MUTEX_LOCK(&a_op_map_mutex);
370 #endif
371
372  a_map_store_locked(o, old_pp, next, flags);
373
374 #ifdef USE_ITHREADS
375  MUTEX_UNLOCK(&a_op_map_mutex);
376 #endif
377 }
378
379 STATIC void a_map_delete(pTHX_ const OP *o) {
380 #define a_map_delete(O) a_map_delete(aTHX_ (O))
381 #ifdef USE_ITHREADS
382  MUTEX_LOCK(&a_op_map_mutex);
383 #endif
384
385  ptable_map_store(a_op_map, o, NULL);
386
387 #ifdef USE_ITHREADS
388  MUTEX_UNLOCK(&a_op_map_mutex);
389 #endif
390 }
391
392 STATIC const OP *a_map_descend(const OP *o) {
393  switch (PL_opargs[o->op_type] & OA_CLASS_MASK) {
394   case OA_BASEOP:
395   case OA_UNOP:
396   case OA_BINOP:
397   case OA_BASEOP_OR_UNOP:
398    return cUNOPo->op_first;
399   case OA_LIST:
400   case OA_LISTOP:
401    return cLISTOPo->op_last;
402  }
403
404  return NULL;
405 }
406
407 STATIC void a_map_store_root(pPTBLMS_ const OP *root, OP *(*old_pp)(pTHX), UV flags) {
408 #define a_map_store_root(R, PP, F) a_map_store_root(aPTBLMS_ (R), (PP), (F))
409  const a_op_info *roi;
410  a_op_info *oi;
411  const OP *o = root;
412
413 #ifdef USE_ITHREADS
414  MUTEX_LOCK(&a_op_map_mutex);
415 #endif
416
417  roi = a_map_store_locked(o, old_pp, (OP *) root, flags | A_HINT_ROOT);
418
419  while (o->op_flags & OPf_KIDS) {
420   o = a_map_descend(o);
421   if (!o)
422    break;
423   if ((oi = ptable_fetch(a_op_map, o))) {
424    oi->flags &= ~A_HINT_ROOT;
425    oi->next   = (a_op_info *) roi;
426    break;
427   }
428  }
429
430 #ifdef USE_ITHREADS
431  MUTEX_UNLOCK(&a_op_map_mutex);
432 #endif
433
434  return;
435 }
436
437 STATIC void a_map_update_flags_topdown(const OP *root, UV flags) {
438  a_op_info *oi;
439  const OP *o = root;
440
441 #ifdef USE_ITHREADS
442  MUTEX_LOCK(&a_op_map_mutex);
443 #endif
444
445  flags &= ~A_HINT_ROOT;
446
447  do {
448   if ((oi = ptable_fetch(a_op_map, o)))
449    oi->flags = (oi->flags & A_HINT_ROOT) | flags;
450   if (!(o->op_flags & OPf_KIDS))
451    break;
452   o = a_map_descend(o);
453  } while (o);
454
455 #ifdef USE_ITHREADS
456  MUTEX_UNLOCK(&a_op_map_mutex);
457 #endif
458
459  return;
460 }
461
462 #define a_map_cancel(R) a_map_update_flags_topdown((R), 0)
463
464 STATIC void a_map_update_flags_bottomup(const OP *o, UV flags, UV rflags) {
465  a_op_info *oi;
466
467 #ifdef USE_ITHREADS
468  MUTEX_LOCK(&a_op_map_mutex);
469 #endif
470
471  flags  &= ~A_HINT_ROOT;
472  rflags |=  A_HINT_ROOT;
473
474  oi = ptable_fetch(a_op_map, o);
475  while (!(oi->flags & A_HINT_ROOT)) {
476   oi->flags = flags;
477   oi        = oi->next;
478  }
479  oi->flags = rflags;
480
481 #ifdef USE_ITHREADS
482  MUTEX_UNLOCK(&a_op_map_mutex);
483 #endif
484
485  return;
486 }
487
488 /* ... Decide whether this expression should be autovivified or not ........ */
489
490 STATIC UV a_map_resolve(const OP *o, a_op_info *oi) {
491  UV flags = 0, rflags;
492  const OP *root;
493  a_op_info *roi = oi;
494
495  while (!(roi->flags & A_HINT_ROOT))
496   roi = roi->next;
497  if (!roi)
498   goto cancel;
499
500  rflags = roi->flags & ~A_HINT_ROOT;
501  if (!rflags)
502   goto cancel;
503
504  root = roi->next;
505  if (root->op_flags & OPf_MOD) {
506   if (rflags & A_HINT_STORE)
507    flags = (A_HINT_STORE|A_HINT_DEREF);
508  } else if (rflags & A_HINT_FETCH)
509    flags = (A_HINT_FETCH|A_HINT_DEREF);
510
511  if (!flags) {
512 cancel:
513   a_map_update_flags_bottomup(o, 0, 0);
514   return 0;
515  }
516
517  flags |= (rflags & A_HINT_NOTIFY);
518  a_map_update_flags_bottomup(o, flags, 0);
519
520  return oi->flags & A_HINT_ROOT ? 0 : flags;
521 }
522
523 /* ... Lightweight pp_defined() ............................................ */
524
525 STATIC bool a_defined(pTHX_ SV *sv) {
526 #define a_defined(S) a_defined(aTHX_ (S))
527  bool defined = FALSE;
528
529  switch (SvTYPE(sv)) {
530   case SVt_PVAV:
531    if (AvMAX(sv) >= 0 || SvGMAGICAL(sv)
532                       || (SvRMAGICAL(sv) && mg_find(sv, PERL_MAGIC_tied)))
533     defined = TRUE;
534    break;
535   case SVt_PVHV:
536    if (HvARRAY(sv) || SvGMAGICAL(sv)
537                    || (SvRMAGICAL(sv) && mg_find(sv, PERL_MAGIC_tied)))
538     defined = TRUE;
539    break;
540   default:
541    SvGETMAGIC(sv);
542    if (SvOK(sv))
543     defined = TRUE;
544  }
545
546  return defined;
547 }
548
549 /* --- PP functions -------------------------------------------------------- */
550
551 /* Be aware that we restore PL_op->op_ppaddr from the pointer table old_pp
552  * value, another extension might have saved our pp replacement as the ppaddr
553  * for this op, so this doesn't ensure that our function will never be called
554  * again. That's why we don't remove the op info from our map, so that it can
555  * still run correctly if required. */
556
557 /* ... pp_rv2av ............................................................ */
558
559 STATIC OP *a_pp_rv2av(pTHX) {
560  a_op_info oi;
561  UV flags;
562  dSP;
563
564  a_map_fetch(PL_op, &oi);
565  flags = oi.flags;
566
567  if (flags & A_HINT_DEREF) {
568   if (!a_defined(TOPs)) {
569    /* We always need to push an empty array to fool the pp_aelem() that comes
570     * later. */
571    SV *av;
572    POPs;
573    av = sv_2mortal((SV *) newAV());
574    PUSHs(av);
575    RETURN;
576   }
577  } else {
578   PL_op->op_ppaddr = oi.old_pp;
579  }
580
581  return CALL_FPTR(oi.old_pp)(aTHX);
582 }
583
584 /* ... pp_rv2hv ............................................................ */
585
586 STATIC OP *a_pp_rv2hv_simple(pTHX) {
587  a_op_info oi;
588  UV flags;
589  dSP;
590
591  a_map_fetch(PL_op, &oi);
592  flags = oi.flags;
593
594  if (flags & A_HINT_DEREF) {
595   if (!a_defined(TOPs))
596    RETURN;
597  } else {
598   PL_op->op_ppaddr = oi.old_pp;
599  }
600
601  return CALL_FPTR(oi.old_pp)(aTHX);
602 }
603
604 STATIC OP *a_pp_rv2hv(pTHX) {
605  a_op_info oi;
606  UV flags;
607  dSP;
608
609  a_map_fetch(PL_op, &oi);
610  flags = oi.flags;
611
612  if (flags & A_HINT_DEREF) {
613   if (!a_defined(TOPs)) {
614    SV *hv;
615    POPs;
616    hv = sv_2mortal((SV *) newHV());
617    PUSHs(hv);
618    RETURN;
619   }
620  } else {
621   PL_op->op_ppaddr = oi.old_pp;
622  }
623
624  return CALL_FPTR(oi.old_pp)(aTHX);
625 }
626
627 /* ... pp_deref (aelem,helem,rv2sv,padsv) .................................. */
628
629 STATIC OP *a_pp_deref(pTHX) {
630  a_op_info oi;
631  UV flags;
632  dSP;
633
634  a_map_fetch(PL_op, &oi);
635  flags = oi.flags;
636
637  if (flags & A_HINT_DEREF) {
638   OP *o;
639   U8 old_private;
640
641 deref:
642   old_private       = PL_op->op_private;
643   PL_op->op_private = ((old_private & ~OPpDEREF) | OPpLVAL_DEFER);
644   o = CALL_FPTR(oi.old_pp)(aTHX);
645   PL_op->op_private = old_private;
646
647   if (flags & (A_HINT_NOTIFY|A_HINT_STORE)) {
648    SPAGAIN;
649    if (!a_defined(TOPs)) {
650     if (flags & A_HINT_STRICT)
651      croak("Reference vivification forbidden");
652     else if (flags & A_HINT_WARN)
653       warn("Reference was vivified");
654     else /* A_HINT_STORE */
655      croak("Can't vivify reference");
656    }
657   }
658
659   return o;
660  } else if ((flags & ~A_HINT_ROOT)
661                     && (PL_op->op_private & OPpDEREF || flags & A_HINT_ROOT)) {
662   /* Decide if the expression must autovivify or not.
663    * This branch should be called only once by expression. */
664   flags = a_map_resolve(PL_op, &oi);
665
666   /* We need the updated flags value in the deref branch. */
667   if (flags & A_HINT_DEREF)
668    goto deref;
669  }
670
671  /* This op doesn't need to skip autovivification, so restore the original
672   * state. */
673  PL_op->op_ppaddr = oi.old_pp;
674
675  return CALL_FPTR(oi.old_pp)(aTHX);
676 }
677
678 /* ... pp_root (exists,delete,keys,values) ................................. */
679
680 STATIC OP *a_pp_root_unop(pTHX) {
681  a_op_info oi;
682  dSP;
683
684  if (!a_defined(TOPs)) {
685   POPs;
686   /* Can only be reached by keys or values */
687   if (GIMME_V == G_SCALAR) {
688    dTARGET;
689    PUSHi(0);
690   }
691   RETURN;
692  }
693
694  a_map_fetch(PL_op, &oi);
695
696  return CALL_FPTR(oi.old_pp)(aTHX);
697 }
698
699 STATIC OP *a_pp_root_binop(pTHX) {
700  a_op_info oi;
701  dSP;
702
703  if (!a_defined(TOPm1s)) {
704   POPs;
705   POPs;
706   if (PL_op->op_type == OP_EXISTS)
707    RETPUSHNO;
708   else
709    RETPUSHUNDEF;
710  }
711
712  a_map_fetch(PL_op, &oi);
713
714  return CALL_FPTR(oi.old_pp)(aTHX);
715 }
716
717 /* --- Check functions ----------------------------------------------------- */
718
719 STATIC void a_recheck_rv2xv(pTHX_ OP *o, OPCODE type, OP *(*new_pp)(pTHX)) {
720 #define a_recheck_rv2xv(O, T, PP) a_recheck_rv2xv(aTHX_ (O), (T), (PP))
721  a_op_info oi;
722
723  if (o->op_type == type && o->op_ppaddr != new_pp
724                         && cUNOPo->op_first->op_type != OP_GV
725                         && a_map_fetch(o, &oi)) {
726   a_map_store(o, o->op_ppaddr, oi.next, oi.flags);
727   o->op_ppaddr = new_pp;
728  }
729
730  return;
731 }
732
733 /* ... ck_pad{any,sv} ...................................................... */
734
735 /* Sadly, the PADSV OPs we are interested in don't trigger the padsv check
736  * function, but are instead manually mutated from a PADANY. This is why we set
737  * PL_ppaddr[OP_PADSV] in the padany check function so that PADSV OPs will have
738  * their op_ppaddr set to our pp_padsv. PL_ppaddr[OP_PADSV] is then reset at the
739  * beginning of every ck_pad{any,sv}. Some unwanted OPs can still call our
740  * pp_padsv, but much less than if we would have set PL_ppaddr[OP_PADSV]
741  * globally. */
742
743 STATIC OP *(*a_pp_padsv_saved)(pTHX) = 0;
744
745 STATIC void a_pp_padsv_save(void) {
746  if (a_pp_padsv_saved)
747   return;
748
749  a_pp_padsv_saved    = PL_ppaddr[OP_PADSV];
750  PL_ppaddr[OP_PADSV] = a_pp_deref;
751 }
752
753 STATIC void a_pp_padsv_restore(OP *o) {
754  if (!a_pp_padsv_saved)
755   return;
756
757  if (o->op_ppaddr == a_pp_deref)
758   o->op_ppaddr = a_pp_padsv_saved;
759
760  PL_ppaddr[OP_PADSV] = a_pp_padsv_saved;
761  a_pp_padsv_saved    = 0;
762 }
763
764 STATIC OP *(*a_old_ck_padany)(pTHX_ OP *) = 0;
765
766 STATIC OP *a_ck_padany(pTHX_ OP *o) {
767  UV hint;
768
769  a_pp_padsv_restore(o);
770
771  o = CALL_FPTR(a_old_ck_padany)(aTHX_ o);
772
773  hint = a_hint();
774  if (hint & A_HINT_DO) {
775   a_pp_padsv_save();
776   a_map_store_root(o, a_pp_padsv_saved, hint);
777  } else
778   a_map_delete(o);
779
780  return o;
781 }
782
783 STATIC OP *(*a_old_ck_padsv)(pTHX_ OP *) = 0;
784
785 STATIC OP *a_ck_padsv(pTHX_ OP *o) {
786  UV hint;
787
788  a_pp_padsv_restore(o);
789
790  o = CALL_FPTR(a_old_ck_padsv)(aTHX_ o);
791
792  hint = a_hint();
793  if (hint & A_HINT_DO) {
794   a_map_store_root(o, o->op_ppaddr, hint);
795   o->op_ppaddr = a_pp_deref;
796  } else
797   a_map_delete(o);
798
799  return o;
800 }
801
802 /* ... ck_deref (aelem,helem,rv2sv) ........................................ */
803
804 /* Those ops appear both at the root and inside an expression but there's no
805  * way to distinguish both situations. Worse, we can't even know if we are in a
806  * modifying context, so the expression can't be resolved yet. It will be at the
807  * first invocation of a_pp_deref() for this expression. */
808
809 STATIC OP *(*a_old_ck_aelem)(pTHX_ OP *) = 0;
810 STATIC OP *(*a_old_ck_helem)(pTHX_ OP *) = 0;
811 STATIC OP *(*a_old_ck_rv2sv)(pTHX_ OP *) = 0;
812
813 STATIC OP *a_ck_deref(pTHX_ OP *o) {
814  OP * (*old_ck)(pTHX_ OP *o) = 0;
815  UV hint = a_hint();
816
817  switch (o->op_type) {
818   case OP_AELEM:
819    old_ck = a_old_ck_aelem;
820    if ((hint & A_HINT_DO) && !(hint & A_HINT_STRICT))
821     a_recheck_rv2xv(cUNOPo->op_first, OP_RV2AV, a_pp_rv2av);
822    break;
823   case OP_HELEM:
824    old_ck = a_old_ck_helem;
825    if ((hint & A_HINT_DO) && !(hint & A_HINT_STRICT))
826     a_recheck_rv2xv(cUNOPo->op_first, OP_RV2HV, a_pp_rv2hv_simple);
827    break;
828   case OP_RV2SV:
829    old_ck = a_old_ck_rv2sv;
830    break;
831  }
832  o = CALL_FPTR(old_ck)(aTHX_ o);
833
834  if (hint & A_HINT_DO) {
835   a_map_store_root(o, o->op_ppaddr, hint);
836   o->op_ppaddr = a_pp_deref;
837  } else
838   a_map_delete(o);
839
840  return o;
841 }
842
843 /* ... ck_rv2xv (rv2av,rv2hv) .............................................. */
844
845 /* Those ops also appear both inisde and at the root, hence the caveats for
846  * a_ck_deref() still apply here. Since a padsv/rv2sv must appear before a
847  * rv2[ah]v, resolution is handled by the first call to a_pp_deref() in the
848  * expression. */
849
850 STATIC OP *(*a_old_ck_rv2av)(pTHX_ OP *) = 0;
851 STATIC OP *(*a_old_ck_rv2hv)(pTHX_ OP *) = 0;
852
853 STATIC OP *a_ck_rv2xv(pTHX_ OP *o) {
854  OP * (*old_ck)(pTHX_ OP *o) = 0;
855  OP * (*new_pp)(pTHX)        = 0;
856  UV hint;
857
858  switch (o->op_type) {
859   case OP_RV2AV: old_ck = a_old_ck_rv2av; new_pp = a_pp_rv2av; break;
860   case OP_RV2HV: old_ck = a_old_ck_rv2hv; new_pp = a_pp_rv2hv_simple; break;
861  }
862  o = CALL_FPTR(old_ck)(aTHX_ o);
863
864  if (cUNOPo->op_first->op_type == OP_GV)
865   return o;
866
867  hint = a_hint();
868  if (hint & A_HINT_DO && !(hint & A_HINT_STRICT)) {
869   a_map_store_root(o, o->op_ppaddr, hint);
870   o->op_ppaddr = new_pp;
871  } else
872   a_map_delete(o);
873
874  return o;
875 }
876
877 /* ... ck_xslice (aslice,hslice) ........................................... */
878
879 /* I think those are only found at the root, but there's nothing that really
880  * prevent them to be inside the expression too. We only need to update the
881  * root so that the rest of the expression will see the right context when
882  * resolving. That's why we don't replace the ppaddr. */
883
884 STATIC OP *(*a_old_ck_aslice)(pTHX_ OP *) = 0;
885 STATIC OP *(*a_old_ck_hslice)(pTHX_ OP *) = 0;
886
887 STATIC OP *a_ck_xslice(pTHX_ OP *o) {
888  OP * (*old_ck)(pTHX_ OP *o) = 0;
889  UV hint = a_hint();
890
891  switch (o->op_type) {
892   case OP_ASLICE:
893    old_ck = a_old_ck_aslice;
894    break;
895   case OP_HSLICE:
896    old_ck = a_old_ck_hslice;
897    if (hint & A_HINT_DO)
898     a_recheck_rv2xv(cUNOPo->op_first->op_sibling, OP_RV2HV, a_pp_rv2hv);
899    break;
900  }
901  o = CALL_FPTR(old_ck)(aTHX_ o);
902
903  if (hint & A_HINT_DO) {
904   a_map_store_root(o, 0, hint);
905  } else
906   a_map_delete(o);
907
908  return o;
909 }
910
911 /* ... ck_root (exists,delete,keys,values) ................................. */
912
913 /* Those ops are only found at the root of a dereferencing expression. We can
914  * then resolve at compile time if vivification must take place or not. */
915
916 STATIC OP *(*a_old_ck_exists)(pTHX_ OP *) = 0;
917 STATIC OP *(*a_old_ck_delete)(pTHX_ OP *) = 0;
918 STATIC OP *(*a_old_ck_keys)  (pTHX_ OP *) = 0;
919 STATIC OP *(*a_old_ck_values)(pTHX_ OP *) = 0;
920
921 STATIC OP *a_ck_root(pTHX_ OP *o) {
922  OP * (*old_ck)(pTHX_ OP *o) = 0;
923  OP * (*new_pp)(pTHX)        = 0;
924  bool enabled = FALSE;
925  UV hint = a_hint();
926
927  switch (o->op_type) {
928   case OP_EXISTS:
929    old_ck  = a_old_ck_exists;
930    new_pp  = a_pp_root_binop;
931    enabled = hint & A_HINT_EXISTS;
932    break;
933   case OP_DELETE:
934    old_ck  = a_old_ck_delete;
935    new_pp  = a_pp_root_binop;
936    enabled = hint & A_HINT_DELETE;
937    break;
938   case OP_KEYS:
939    old_ck  = a_old_ck_keys;
940    new_pp  = a_pp_root_unop;
941    enabled = hint & A_HINT_FETCH;
942    break;
943   case OP_VALUES:
944    old_ck  = a_old_ck_values;
945    new_pp  = a_pp_root_unop;
946    enabled = hint & A_HINT_FETCH;
947    break;
948  }
949  o = CALL_FPTR(old_ck)(aTHX_ o);
950
951  if (hint & A_HINT_DO) {
952   if (enabled) {
953    a_map_update_flags_topdown(o, hint | A_HINT_DEREF);
954    a_map_store_root(o, o->op_ppaddr, hint);
955    o->op_ppaddr = new_pp;
956   } else {
957    a_map_cancel(o);
958   }
959  } else
960   a_map_delete(o);
961
962  return o;
963 }
964
965 STATIC U32 a_initialized = 0;
966
967 STATIC void a_teardown(pTHX_ void *root) {
968
969  if (!a_initialized)
970   return;
971
972 #if A_MULTIPLICITY
973  if (aTHX != root)
974   return;
975 #endif
976
977 #if A_THREADSAFE && A_WORKAROUND_REQUIRE_PROPAGATION
978  {
979   dMY_CXT;
980   ptable_hints_free(MY_CXT.tbl);
981  }
982 #endif
983
984  PL_check[OP_PADANY] = MEMBER_TO_FPTR(a_old_ck_padany);
985  a_old_ck_padany     = 0;
986  PL_check[OP_PADSV]  = MEMBER_TO_FPTR(a_old_ck_padsv);
987  a_old_ck_padsv      = 0;
988
989  PL_check[OP_AELEM]  = MEMBER_TO_FPTR(a_old_ck_aelem);
990  a_old_ck_aelem      = 0;
991  PL_check[OP_HELEM]  = MEMBER_TO_FPTR(a_old_ck_helem);
992  a_old_ck_helem      = 0;
993  PL_check[OP_RV2SV]  = MEMBER_TO_FPTR(a_old_ck_rv2sv);
994  a_old_ck_rv2sv      = 0;
995
996  PL_check[OP_RV2AV]  = MEMBER_TO_FPTR(a_old_ck_rv2av);
997  a_old_ck_rv2av      = 0;
998  PL_check[OP_RV2HV]  = MEMBER_TO_FPTR(a_old_ck_rv2hv);
999  a_old_ck_rv2hv      = 0;
1000
1001  PL_check[OP_ASLICE] = MEMBER_TO_FPTR(a_old_ck_aslice);
1002  a_old_ck_aslice     = 0;
1003  PL_check[OP_HSLICE] = MEMBER_TO_FPTR(a_old_ck_hslice);
1004  a_old_ck_hslice     = 0;
1005
1006  PL_check[OP_EXISTS] = MEMBER_TO_FPTR(a_old_ck_exists);
1007  a_old_ck_exists     = 0;
1008  PL_check[OP_DELETE] = MEMBER_TO_FPTR(a_old_ck_delete);
1009  a_old_ck_delete     = 0;
1010  PL_check[OP_KEYS]   = MEMBER_TO_FPTR(a_old_ck_keys);
1011  a_old_ck_keys       = 0;
1012  PL_check[OP_VALUES] = MEMBER_TO_FPTR(a_old_ck_values);
1013  a_old_ck_values     = 0;
1014
1015  if (a_pp_padsv_saved) {
1016   PL_ppaddr[OP_PADSV] = a_pp_padsv_saved;
1017   a_pp_padsv_saved    = 0;
1018  }
1019
1020  a_initialized = 0;
1021 }
1022
1023 STATIC void a_setup(pTHX) {
1024 #define a_setup() a_setup(aTHX)
1025  if (a_initialized)
1026   return;
1027
1028 #if A_THREADSAFE && A_WORKAROUND_REQUIRE_PROPAGATION
1029  {
1030   MY_CXT_INIT;
1031   MY_CXT.tbl   = ptable_new();
1032   MY_CXT.owner = aTHX;
1033  }
1034 #endif
1035
1036  a_old_ck_padany     = PL_check[OP_PADANY];
1037  PL_check[OP_PADANY] = MEMBER_TO_FPTR(a_ck_padany);
1038  a_old_ck_padsv      = PL_check[OP_PADSV];
1039  PL_check[OP_PADSV]  = MEMBER_TO_FPTR(a_ck_padsv);
1040
1041  a_old_ck_aelem      = PL_check[OP_AELEM];
1042  PL_check[OP_AELEM]  = MEMBER_TO_FPTR(a_ck_deref);
1043  a_old_ck_helem      = PL_check[OP_HELEM];
1044  PL_check[OP_HELEM]  = MEMBER_TO_FPTR(a_ck_deref);
1045  a_old_ck_rv2sv      = PL_check[OP_RV2SV];
1046  PL_check[OP_RV2SV]  = MEMBER_TO_FPTR(a_ck_deref);
1047
1048  a_old_ck_rv2av      = PL_check[OP_RV2AV];
1049  PL_check[OP_RV2AV]  = MEMBER_TO_FPTR(a_ck_rv2xv);
1050  a_old_ck_rv2hv      = PL_check[OP_RV2HV];
1051  PL_check[OP_RV2HV]  = MEMBER_TO_FPTR(a_ck_rv2xv);
1052
1053  a_old_ck_aslice     = PL_check[OP_ASLICE];
1054  PL_check[OP_ASLICE] = MEMBER_TO_FPTR(a_ck_xslice);
1055  a_old_ck_hslice     = PL_check[OP_HSLICE];
1056  PL_check[OP_HSLICE] = MEMBER_TO_FPTR(a_ck_xslice);
1057
1058  a_old_ck_exists     = PL_check[OP_EXISTS];
1059  PL_check[OP_EXISTS] = MEMBER_TO_FPTR(a_ck_root);
1060  a_old_ck_delete     = PL_check[OP_DELETE];
1061  PL_check[OP_DELETE] = MEMBER_TO_FPTR(a_ck_root);
1062  a_old_ck_keys       = PL_check[OP_KEYS];
1063  PL_check[OP_KEYS]   = MEMBER_TO_FPTR(a_ck_root);
1064  a_old_ck_values     = PL_check[OP_VALUES];
1065  PL_check[OP_VALUES] = MEMBER_TO_FPTR(a_ck_root);
1066
1067 #if A_MULTIPLICITY
1068  call_atexit(a_teardown, aTHX);
1069 #else
1070  call_atexit(a_teardown, NULL);
1071 #endif
1072
1073  a_initialized = 1;
1074 }
1075
1076 STATIC U32 a_booted = 0;
1077
1078 /* --- XS ------------------------------------------------------------------ */
1079
1080 MODULE = autovivification      PACKAGE = autovivification
1081
1082 PROTOTYPES: ENABLE
1083
1084 BOOT: 
1085 {                                    
1086  if (!a_booted++) {
1087   HV *stash;
1088
1089   a_op_map = ptable_new();
1090 #ifdef USE_ITHREADS
1091   MUTEX_INIT(&a_op_map_mutex);
1092 #endif
1093
1094   PERL_HASH(a_hash, __PACKAGE__, __PACKAGE_LEN__);
1095
1096   stash = gv_stashpvn(__PACKAGE__, __PACKAGE_LEN__, 1);
1097   newCONSTSUB(stash, "A_HINT_STRICT", newSVuv(A_HINT_STRICT));
1098   newCONSTSUB(stash, "A_HINT_WARN",   newSVuv(A_HINT_WARN));
1099   newCONSTSUB(stash, "A_HINT_FETCH",  newSVuv(A_HINT_FETCH));
1100   newCONSTSUB(stash, "A_HINT_STORE",  newSVuv(A_HINT_STORE));
1101   newCONSTSUB(stash, "A_HINT_EXISTS", newSVuv(A_HINT_EXISTS));
1102   newCONSTSUB(stash, "A_HINT_DELETE", newSVuv(A_HINT_DELETE));
1103   newCONSTSUB(stash, "A_HINT_MASK",   newSVuv(A_HINT_MASK));
1104   newCONSTSUB(stash, "A_THREADSAFE",  newSVuv(A_THREADSAFE));
1105   newCONSTSUB(stash, "A_FORKSAFE",    newSVuv(A_FORKSAFE));
1106  }
1107
1108  a_setup();
1109 }
1110
1111 #if A_THREADSAFE && A_WORKAROUND_REQUIRE_PROPAGATION
1112
1113 void
1114 CLONE(...)
1115 PROTOTYPE: DISABLE
1116 PREINIT:
1117  ptable *t;
1118 PPCODE:
1119  {
1120   my_cxt_t ud;
1121   dMY_CXT;
1122   ud.tbl   = t = ptable_new();
1123   ud.owner = MY_CXT.owner;
1124   ptable_walk(MY_CXT.tbl, a_ptable_clone, &ud);
1125  }
1126  {
1127   MY_CXT_CLONE;
1128   MY_CXT.tbl   = t;
1129   MY_CXT.owner = aTHX;
1130  }
1131  reap(3, a_thread_cleanup, NULL);
1132  XSRETURN(0);
1133
1134 #endif
1135
1136 SV *
1137 _tag(SV *hint)
1138 PROTOTYPE: $
1139 CODE:
1140  RETVAL = a_tag(SvOK(hint) ? SvUV(hint) : 0);
1141 OUTPUT:
1142  RETVAL
1143
1144 SV *
1145 _detag(SV *tag)
1146 PROTOTYPE: $
1147 CODE:
1148  if (!SvOK(tag))
1149   XSRETURN_UNDEF;
1150  RETVAL = newSVuv(a_detag(tag));
1151 OUTPUT:
1152  RETVAL