File: autovivification.xs

package info (click to toggle)
libautovivification-perl 0.06-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 284 kB
  • ctags: 83
  • sloc: perl: 1,599; ansic: 181; makefile: 2
file content (1167 lines) | stat: -rw-r--r-- 27,599 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
/* This file is part of the autovivification Perl module.
 * See http://search.cpan.org/dist/autovivification/ */

#define PERL_NO_GET_CONTEXT
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"

#define __PACKAGE__     "autovivification"
#define __PACKAGE_LEN__ (sizeof(__PACKAGE__)-1)

/* --- Compatibility wrappers ---------------------------------------------- */

#ifndef HvNAME_get
# define HvNAME_get(H) HvNAME(H)
#endif

#ifndef HvNAMELEN_get
# define HvNAMELEN_get(H) strlen(HvNAME_get(H))
#endif

#define A_HAS_PERL(R, V, S) (PERL_REVISION > (R) || (PERL_REVISION == (R) && (PERL_VERSION > (V) || (PERL_VERSION == (V) && (PERL_SUBVERSION >= (S))))))

#undef ENTERn
#if defined(ENTER_with_name) && !A_HAS_PERL(5, 11, 4)
# define ENTERn(N) ENTER_with_name(N)
#else
# define ENTERn(N) ENTER
#endif

#undef LEAVEn
#if defined(LEAVE_with_name) && !A_HAS_PERL(5, 11, 4)
# define LEAVEn(N) LEAVE_with_name(N)
#else
# define LEAVEn(N) LEAVE
#endif

#ifndef A_WORKAROUND_REQUIRE_PROPAGATION
# define A_WORKAROUND_REQUIRE_PROPAGATION !A_HAS_PERL(5, 10, 1)
#endif

/* ... Thread safety and multiplicity ...................................... */

/* Always safe when the workaround isn't needed */
#if !A_WORKAROUND_REQUIRE_PROPAGATION
# undef A_FORKSAFE
# define A_FORKSAFE 1
/* Otherwise, safe unless Makefile.PL says it's Win32 */
#elif !defined(A_FORKSAFE)
# define A_FORKSAFE 1
#endif

#ifndef A_MULTIPLICITY
# if defined(MULTIPLICITY) || defined(PERL_IMPLICIT_CONTEXT)
#  define A_MULTIPLICITY 1
# else
#  define A_MULTIPLICITY 0
# endif
#endif
#if A_MULTIPLICITY && !defined(tTHX)
# define tTHX PerlInterpreter*
#endif

#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))
# define A_THREADSAFE 1
# ifndef MY_CXT_CLONE
#  define MY_CXT_CLONE \
    dMY_CXT_SV;                                                      \
    my_cxt_t *my_cxtp = (my_cxt_t*)SvPVX(newSV(sizeof(my_cxt_t)-1)); \
    Copy(INT2PTR(my_cxt_t*, SvUV(my_cxt_sv)), my_cxtp, 1, my_cxt_t); \
    sv_setuv(my_cxt_sv, PTR2UV(my_cxtp))
# endif
#else
# define A_THREADSAFE 0
# undef  dMY_CXT
# define dMY_CXT      dNOOP
# undef  MY_CXT
# define MY_CXT       a_globaldata
# undef  START_MY_CXT
# define START_MY_CXT STATIC my_cxt_t MY_CXT;
# undef  MY_CXT_INIT
# define MY_CXT_INIT  NOOP
# undef  MY_CXT_CLONE
# define MY_CXT_CLONE NOOP
#endif

/* --- Helpers ------------------------------------------------------------- */

/* ... Thread-safe hints ................................................... */

#if A_WORKAROUND_REQUIRE_PROPAGATION

typedef struct {
 U32 bits;
 IV  require_tag;
} a_hint_t;

#define A_HINT_FREE(H) PerlMemShared_free(H)

#if A_THREADSAFE

#define PTABLE_NAME        ptable_hints
#define PTABLE_VAL_FREE(V) A_HINT_FREE(V)

#define pPTBL  pTHX
#define pPTBL_ pTHX_
#define aPTBL  aTHX
#define aPTBL_ aTHX_

#include "ptable.h"

#define ptable_hints_store(T, K, V) ptable_hints_store(aTHX_ (T), (K), (V))
#define ptable_hints_free(T)        ptable_hints_free(aTHX_ (T))

#define MY_CXT_KEY __PACKAGE__ "::_guts" XS_VERSION

typedef struct {
 ptable *tbl;   /* It really is a ptable_hints */
 tTHX    owner;
} my_cxt_t;

START_MY_CXT

STATIC SV *a_clone(pTHX_ SV *sv, tTHX owner) {
#define a_clone(S, O) a_clone(aTHX_ (S), (O))
 CLONE_PARAMS  param;
 AV           *stashes = NULL;
 SV           *dupsv;

 if (SvTYPE(sv) == SVt_PVHV && HvNAME_get(sv))
  stashes = newAV();

 param.stashes    = stashes;
 param.flags      = 0;
 param.proto_perl = owner;

 dupsv = sv_dup(sv, &param);

 if (stashes) {
  av_undef(stashes);
  SvREFCNT_dec(stashes);
 }

 return SvREFCNT_inc(dupsv);
}

STATIC void a_ptable_clone(pTHX_ ptable_ent *ent, void *ud_) {
 my_cxt_t *ud = ud_;
 a_hint_t *h1 = ent->val;
 a_hint_t *h2;

 if (ud->owner == aTHX)
  return;

 h2              = PerlMemShared_malloc(sizeof *h2);
 h2->bits        = h1->bits;
 h2->require_tag = PTR2IV(a_clone(INT2PTR(SV *, h1->require_tag), ud->owner));

 ptable_hints_store(ud->tbl, ent->key, h2);
}

STATIC void a_thread_cleanup(pTHX_ void *);

STATIC void a_thread_cleanup(pTHX_ void *ud) {
 int *level = ud;

 if (*level) {
  *level = 0;
  LEAVE;
  SAVEDESTRUCTOR_X(a_thread_cleanup, level);
  ENTER;
 } else {
  dMY_CXT;
  PerlMemShared_free(level);
  ptable_hints_free(MY_CXT.tbl);
 }
}

#endif /* A_THREADSAFE */

STATIC IV a_require_tag(pTHX) {
#define a_require_tag() a_require_tag(aTHX)
 const CV *cv, *outside;

 cv = PL_compcv;

 if (!cv) {
  /* If for some reason the pragma is operational at run-time, try to discover
   * the current cv in use. */
  const PERL_SI *si;

  for (si = PL_curstackinfo; si; si = si->si_prev) {
   I32 cxix;

   for (cxix = si->si_cxix; cxix >= 0; --cxix) {
    const PERL_CONTEXT *cx = si->si_cxstack + cxix;

    switch (CxTYPE(cx)) {
     case CXt_SUB:
     case CXt_FORMAT:
      /* The propagation workaround is only needed up to 5.10.0 and at that
       * time format and sub contexts were still identical. And even later the
       * cv members offsets should have been kept the same. */
      cv = cx->blk_sub.cv;
      goto get_enclosing_cv;
     case CXt_EVAL:
      cv = cx->blk_eval.cv;
      goto get_enclosing_cv;
     default:
      break;
    }
   }
  }

  cv = PL_main_cv;
 }

get_enclosing_cv:
 for (outside = CvOUTSIDE(cv); outside; outside = CvOUTSIDE(cv))
  cv = outside;

 return PTR2IV(cv);
}

STATIC SV *a_tag(pTHX_ UV bits) {
#define a_tag(B) a_tag(aTHX_ (B))
 a_hint_t *h;
 dMY_CXT;

 h              = PerlMemShared_malloc(sizeof *h);
 h->bits        = bits;
 h->require_tag = a_require_tag();

#if A_THREADSAFE
 /* We only need for the key to be an unique tag for looking up the value later.
  * Allocated memory provides convenient unique identifiers, so that's why we
  * use the hint as the key itself. */
 ptable_hints_store(MY_CXT.tbl, h, h);
#endif /* A_THREADSAFE */

 return newSViv(PTR2IV(h));
}

STATIC UV a_detag(pTHX_ const SV *hint) {
#define a_detag(H) a_detag(aTHX_ (H))
 a_hint_t *h;
 dMY_CXT;

 if (!(hint && SvIOK(hint)))
  return 0;

 h = INT2PTR(a_hint_t *, SvIVX(hint));
#if A_THREADSAFE
 h = ptable_fetch(MY_CXT.tbl, h);
#endif /* A_THREADSAFE */

 if (a_require_tag() != h->require_tag)
  return 0;

 return h->bits;
}

#else /* A_WORKAROUND_REQUIRE_PROPAGATION */

#define a_tag(B)   newSVuv(B)
/* PVs fetched from the hints chain have their SvLEN set to zero, so get the UV
 * from a copy. */
#define a_detag(H) \
 ((H)              \
  ? (SvIOK(H)      \
     ? SvUVX(H)    \
     : (SvPOK(H)   \
        ? sv_2uv(SvLEN(H) ? (H) : sv_mortalcopy(H)) \
	: 0        \
       )           \
     )             \
  : 0)

#endif /* !A_WORKAROUND_REQUIRE_PROPAGATION */

/* Used both for hints and op flags */
#define A_HINT_STRICT 1
#define A_HINT_WARN   2
#define A_HINT_FETCH  4
#define A_HINT_STORE  8
#define A_HINT_EXISTS 16
#define A_HINT_DELETE 32
#define A_HINT_NOTIFY (A_HINT_STRICT|A_HINT_WARN)
#define A_HINT_DO     (A_HINT_FETCH|A_HINT_STORE|A_HINT_EXISTS|A_HINT_DELETE)
#define A_HINT_MASK   (A_HINT_NOTIFY|A_HINT_DO)

/* Only used in op flags */
#define A_HINT_ROOT   64
#define A_HINT_DEREF  128

STATIC U32 a_hash = 0;

STATIC UV a_hint(pTHX) {
#define a_hint() a_hint(aTHX)
 SV *hint;
#if A_HAS_PERL(5, 9, 5)
 hint = Perl_refcounted_he_fetch(aTHX_ PL_curcop->cop_hints_hash,
                                       NULL,
                                       __PACKAGE__, __PACKAGE_LEN__,
                                       0,
                                       a_hash);
#else
 SV **val = hv_fetch(GvHV(PL_hintgv), __PACKAGE__, __PACKAGE_LEN__, a_hash);
 if (!val)
  return 0;
 hint = *val;
#endif
 return a_detag(hint);
}

/* ... op => info map ...................................................... */

typedef struct {
 OP *(*old_pp)(pTHX);
 UV flags;
 void *next;
} a_op_info;

#define PTABLE_NAME        ptable_map
#define PTABLE_VAL_FREE(V) PerlMemShared_free(V)

#include "ptable.h"

/* PerlMemShared_free() needs the [ap]PTBLMS_? default values */
#define ptable_map_store(T, K, V) ptable_map_store(aPTBLMS_ (T), (K), (V))

STATIC ptable *a_op_map = NULL;

#ifdef USE_ITHREADS
STATIC perl_mutex a_op_map_mutex;
#endif

STATIC const a_op_info *a_map_fetch(const OP *o, a_op_info *oi) {
 const a_op_info *val;

#ifdef USE_ITHREADS
 MUTEX_LOCK(&a_op_map_mutex);
#endif

 val = ptable_fetch(a_op_map, o);
 if (val) {
  *oi = *val;
  val = oi;
 }

#ifdef USE_ITHREADS
 MUTEX_UNLOCK(&a_op_map_mutex);
#endif

 return val;
}

STATIC const a_op_info *a_map_store_locked(pPTBLMS_ const OP *o, OP *(*old_pp)(pTHX), void *next, UV flags) {
#define a_map_store_locked(O, PP, N, F) a_map_store_locked(aPTBLMS_ (O), (PP), (N), (F))
 a_op_info *oi;

 if (!(oi = ptable_fetch(a_op_map, o))) {
  oi = PerlMemShared_malloc(sizeof *oi);
  ptable_map_store(a_op_map, o, oi);
 }

 oi->old_pp = old_pp;
 oi->next   = next;
 oi->flags  = flags;

 return oi;
}

STATIC void a_map_store(pPTBLMS_ const OP *o, OP *(*old_pp)(pTHX), void *next, UV flags) {
#define a_map_store(O, PP, N, F) a_map_store(aPTBLMS_ (O), (PP), (N), (F))

#ifdef USE_ITHREADS
 MUTEX_LOCK(&a_op_map_mutex);
#endif

 a_map_store_locked(o, old_pp, next, flags);

#ifdef USE_ITHREADS
 MUTEX_UNLOCK(&a_op_map_mutex);
#endif
}

STATIC void a_map_delete(pTHX_ const OP *o) {
#define a_map_delete(O) a_map_delete(aTHX_ (O))
#ifdef USE_ITHREADS
 MUTEX_LOCK(&a_op_map_mutex);
#endif

 ptable_map_store(a_op_map, o, NULL);

#ifdef USE_ITHREADS
 MUTEX_UNLOCK(&a_op_map_mutex);
#endif
}

STATIC const OP *a_map_descend(const OP *o) {
 switch (PL_opargs[o->op_type] & OA_CLASS_MASK) {
  case OA_BASEOP:
  case OA_UNOP:
  case OA_BINOP:
  case OA_BASEOP_OR_UNOP:
   return cUNOPo->op_first;
  case OA_LIST:
  case OA_LISTOP:
   return cLISTOPo->op_last;
 }

 return NULL;
}

STATIC void a_map_store_root(pPTBLMS_ const OP *root, OP *(*old_pp)(pTHX), UV flags) {
#define a_map_store_root(R, PP, F) a_map_store_root(aPTBLMS_ (R), (PP), (F))
 const a_op_info *roi;
 a_op_info *oi;
 const OP *o = root;

#ifdef USE_ITHREADS
 MUTEX_LOCK(&a_op_map_mutex);
#endif

 roi = a_map_store_locked(o, old_pp, (OP *) root, flags | A_HINT_ROOT);

 while (o->op_flags & OPf_KIDS) {
  o = a_map_descend(o);
  if (!o)
   break;
  if ((oi = ptable_fetch(a_op_map, o))) {
   oi->flags &= ~A_HINT_ROOT;
   oi->next   = (a_op_info *) roi;
   break;
  }
 }

#ifdef USE_ITHREADS
 MUTEX_UNLOCK(&a_op_map_mutex);
#endif

 return;
}

STATIC void a_map_update_flags_topdown(const OP *root, UV flags) {
 a_op_info *oi;
 const OP *o = root;

#ifdef USE_ITHREADS
 MUTEX_LOCK(&a_op_map_mutex);
#endif

 flags &= ~A_HINT_ROOT;

 do {
  if ((oi = ptable_fetch(a_op_map, o)))
   oi->flags = (oi->flags & A_HINT_ROOT) | flags;
  if (!(o->op_flags & OPf_KIDS))
   break;
  o = a_map_descend(o);
 } while (o);

#ifdef USE_ITHREADS
 MUTEX_UNLOCK(&a_op_map_mutex);
#endif

 return;
}

#define a_map_cancel(R) a_map_update_flags_topdown((R), 0)

STATIC void a_map_update_flags_bottomup(const OP *o, UV flags, UV rflags) {
 a_op_info *oi;

#ifdef USE_ITHREADS
 MUTEX_LOCK(&a_op_map_mutex);
#endif

 flags  &= ~A_HINT_ROOT;
 rflags |=  A_HINT_ROOT;

 oi = ptable_fetch(a_op_map, o);
 while (!(oi->flags & A_HINT_ROOT)) {
  oi->flags = flags;
  oi        = oi->next;
 }
 oi->flags = rflags;

#ifdef USE_ITHREADS
 MUTEX_UNLOCK(&a_op_map_mutex);
#endif

 return;
}

/* ... Decide whether this expression should be autovivified or not ........ */

STATIC UV a_map_resolve(const OP *o, a_op_info *oi) {
 UV flags = 0, rflags;
 const OP *root;
 a_op_info *roi = oi;

 while (!(roi->flags & A_HINT_ROOT))
  roi = roi->next;
 if (!roi)
  goto cancel;

 rflags = roi->flags & ~A_HINT_ROOT;
 if (!rflags)
  goto cancel;

 root = roi->next;
 if (root->op_flags & OPf_MOD) {
  if (rflags & A_HINT_STORE)
   flags = (A_HINT_STORE|A_HINT_DEREF);
 } else if (rflags & A_HINT_FETCH)
   flags = (A_HINT_FETCH|A_HINT_DEREF);

 if (!flags) {
cancel:
  a_map_update_flags_bottomup(o, 0, 0);
  return 0;
 }

 flags |= (rflags & A_HINT_NOTIFY);
 a_map_update_flags_bottomup(o, flags, 0);

 return oi->flags & A_HINT_ROOT ? 0 : flags;
}

/* ... Lightweight pp_defined() ............................................ */

STATIC bool a_defined(pTHX_ SV *sv) {
#define a_defined(S) a_defined(aTHX_ (S))
 bool defined = FALSE;

 switch (SvTYPE(sv)) {
  case SVt_PVAV:
   if (AvMAX(sv) >= 0 || SvGMAGICAL(sv)
                      || (SvRMAGICAL(sv) && mg_find(sv, PERL_MAGIC_tied)))
    defined = TRUE;
   break;
  case SVt_PVHV:
   if (HvARRAY(sv) || SvGMAGICAL(sv)
                   || (SvRMAGICAL(sv) && mg_find(sv, PERL_MAGIC_tied)))
    defined = TRUE;
   break;
  default:
   SvGETMAGIC(sv);
   if (SvOK(sv))
    defined = TRUE;
 }

 return defined;
}

/* --- PP functions -------------------------------------------------------- */

/* Be aware that we restore PL_op->op_ppaddr from the pointer table old_pp
 * value, another extension might have saved our pp replacement as the ppaddr
 * for this op, so this doesn't ensure that our function will never be called
 * again. That's why we don't remove the op info from our map, so that it can
 * still run correctly if required. */

/* ... pp_rv2av ............................................................ */

STATIC OP *a_pp_rv2av(pTHX) {
 a_op_info oi;
 UV flags;
 dSP;

 a_map_fetch(PL_op, &oi);
 flags = oi.flags;

 if (flags & A_HINT_DEREF) {
  if (!a_defined(TOPs)) {
   /* We always need to push an empty array to fool the pp_aelem() that comes
    * later. */
   SV *av;
   POPs;
   av = sv_2mortal((SV *) newAV());
   PUSHs(av);
   RETURN;
  }
 } else {
  PL_op->op_ppaddr = oi.old_pp;
 }

 return CALL_FPTR(oi.old_pp)(aTHX);
}

/* ... pp_rv2hv ............................................................ */

STATIC OP *a_pp_rv2hv_simple(pTHX) {
 a_op_info oi;
 UV flags;
 dSP;

 a_map_fetch(PL_op, &oi);
 flags = oi.flags;

 if (flags & A_HINT_DEREF) {
  if (!a_defined(TOPs))
   RETURN;
 } else {
  PL_op->op_ppaddr = oi.old_pp;
 }

 return CALL_FPTR(oi.old_pp)(aTHX);
}

STATIC OP *a_pp_rv2hv(pTHX) {
 a_op_info oi;
 UV flags;
 dSP;

 a_map_fetch(PL_op, &oi);
 flags = oi.flags;

 if (flags & A_HINT_DEREF) {
  if (!a_defined(TOPs)) {
   SV *hv;
   POPs;
   hv = sv_2mortal((SV *) newHV());
   PUSHs(hv);
   RETURN;
  }
 } else {
  PL_op->op_ppaddr = oi.old_pp;
 }

 return CALL_FPTR(oi.old_pp)(aTHX);
}

/* ... pp_deref (aelem,helem,rv2sv,padsv) .................................. */

STATIC OP *a_pp_deref(pTHX) {
 a_op_info oi;
 UV flags;
 dSP;

 a_map_fetch(PL_op, &oi);
 flags = oi.flags;

 if (flags & A_HINT_DEREF) {
  OP *o;
  U8 old_private;

deref:
  old_private       = PL_op->op_private;
  PL_op->op_private = ((old_private & ~OPpDEREF) | OPpLVAL_DEFER);
  o = CALL_FPTR(oi.old_pp)(aTHX);
  PL_op->op_private = old_private;

  if (flags & (A_HINT_NOTIFY|A_HINT_STORE)) {
   SPAGAIN;
   if (!a_defined(TOPs)) {
    if (flags & A_HINT_STRICT)
     croak("Reference vivification forbidden");
    else if (flags & A_HINT_WARN)
      warn("Reference was vivified");
    else /* A_HINT_STORE */
     croak("Can't vivify reference");
   }
  }

  return o;
 } else if ((flags & ~A_HINT_ROOT)
                    && (PL_op->op_private & OPpDEREF || flags & A_HINT_ROOT)) {
  /* Decide if the expression must autovivify or not.
   * This branch should be called only once by expression. */
  flags = a_map_resolve(PL_op, &oi);

  /* We need the updated flags value in the deref branch. */
  if (flags & A_HINT_DEREF)
   goto deref;
 }

 /* This op doesn't need to skip autovivification, so restore the original
  * state. */
 PL_op->op_ppaddr = oi.old_pp;

 return CALL_FPTR(oi.old_pp)(aTHX);
}

/* ... pp_root (exists,delete,keys,values) ................................. */

STATIC OP *a_pp_root_unop(pTHX) {
 a_op_info oi;
 dSP;

 if (!a_defined(TOPs)) {
  POPs;
  /* Can only be reached by keys or values */
  if (GIMME_V == G_SCALAR) {
   dTARGET;
   PUSHi(0);
  }
  RETURN;
 }

 a_map_fetch(PL_op, &oi);

 return CALL_FPTR(oi.old_pp)(aTHX);
}

STATIC OP *a_pp_root_binop(pTHX) {
 a_op_info oi;
 dSP;

 if (!a_defined(TOPm1s)) {
  POPs;
  POPs;
  if (PL_op->op_type == OP_EXISTS)
   RETPUSHNO;
  else
   RETPUSHUNDEF;
 }

 a_map_fetch(PL_op, &oi);

 return CALL_FPTR(oi.old_pp)(aTHX);
}

/* --- Check functions ----------------------------------------------------- */

STATIC void a_recheck_rv2xv(pTHX_ OP *o, OPCODE type, OP *(*new_pp)(pTHX)) {
#define a_recheck_rv2xv(O, T, PP) a_recheck_rv2xv(aTHX_ (O), (T), (PP))
 a_op_info oi;

 if (o->op_type == type && o->op_ppaddr != new_pp
                        && cUNOPo->op_first->op_type != OP_GV
                        && a_map_fetch(o, &oi)) {
  a_map_store(o, o->op_ppaddr, oi.next, oi.flags);
  o->op_ppaddr = new_pp;
 }

 return;
}

/* ... ck_pad{any,sv} ...................................................... */

/* Sadly, the PADSV OPs we are interested in don't trigger the padsv check
 * function, but are instead manually mutated from a PADANY. This is why we set
 * PL_ppaddr[OP_PADSV] in the padany check function so that PADSV OPs will have
 * their op_ppaddr set to our pp_padsv. PL_ppaddr[OP_PADSV] is then reset at the
 * beginning of every ck_pad{any,sv}. Some unwanted OPs can still call our
 * pp_padsv, but much less than if we would have set PL_ppaddr[OP_PADSV]
 * globally. */

STATIC OP *(*a_pp_padsv_saved)(pTHX) = 0;

STATIC void a_pp_padsv_save(void) {
 if (a_pp_padsv_saved)
  return;

 a_pp_padsv_saved    = PL_ppaddr[OP_PADSV];
 PL_ppaddr[OP_PADSV] = a_pp_deref;
}

STATIC void a_pp_padsv_restore(OP *o) {
 if (!a_pp_padsv_saved)
  return;

 if (o->op_ppaddr == a_pp_deref)
  o->op_ppaddr = a_pp_padsv_saved;

 PL_ppaddr[OP_PADSV] = a_pp_padsv_saved;
 a_pp_padsv_saved    = 0;
}

STATIC OP *(*a_old_ck_padany)(pTHX_ OP *) = 0;

STATIC OP *a_ck_padany(pTHX_ OP *o) {
 UV hint;

 a_pp_padsv_restore(o);

 o = CALL_FPTR(a_old_ck_padany)(aTHX_ o);

 hint = a_hint();
 if (hint & A_HINT_DO) {
  a_pp_padsv_save();
  a_map_store_root(o, a_pp_padsv_saved, hint);
 } else
  a_map_delete(o);

 return o;
}

STATIC OP *(*a_old_ck_padsv)(pTHX_ OP *) = 0;

STATIC OP *a_ck_padsv(pTHX_ OP *o) {
 UV hint;

 a_pp_padsv_restore(o);

 o = CALL_FPTR(a_old_ck_padsv)(aTHX_ o);

 hint = a_hint();
 if (hint & A_HINT_DO) {
  a_map_store_root(o, o->op_ppaddr, hint);
  o->op_ppaddr = a_pp_deref;
 } else
  a_map_delete(o);

 return o;
}

/* ... ck_deref (aelem,helem,rv2sv) ........................................ */

/* Those ops appear both at the root and inside an expression but there's no
 * way to distinguish both situations. Worse, we can't even know if we are in a
 * modifying context, so the expression can't be resolved yet. It will be at the
 * first invocation of a_pp_deref() for this expression. */

STATIC OP *(*a_old_ck_aelem)(pTHX_ OP *) = 0;
STATIC OP *(*a_old_ck_helem)(pTHX_ OP *) = 0;
STATIC OP *(*a_old_ck_rv2sv)(pTHX_ OP *) = 0;

STATIC OP *a_ck_deref(pTHX_ OP *o) {
 OP * (*old_ck)(pTHX_ OP *o) = 0;
 UV hint = a_hint();

 switch (o->op_type) {
  case OP_AELEM:
   old_ck = a_old_ck_aelem;
   if ((hint & A_HINT_DO) && !(hint & A_HINT_STRICT))
    a_recheck_rv2xv(cUNOPo->op_first, OP_RV2AV, a_pp_rv2av);
   break;
  case OP_HELEM:
   old_ck = a_old_ck_helem;
   if ((hint & A_HINT_DO) && !(hint & A_HINT_STRICT))
    a_recheck_rv2xv(cUNOPo->op_first, OP_RV2HV, a_pp_rv2hv_simple);
   break;
  case OP_RV2SV:
   old_ck = a_old_ck_rv2sv;
   break;
 }
 o = CALL_FPTR(old_ck)(aTHX_ o);

 if (hint & A_HINT_DO) {
  a_map_store_root(o, o->op_ppaddr, hint);
  o->op_ppaddr = a_pp_deref;
 } else
  a_map_delete(o);

 return o;
}

/* ... ck_rv2xv (rv2av,rv2hv) .............................................. */

/* Those ops also appear both inisde and at the root, hence the caveats for
 * a_ck_deref() still apply here. Since a padsv/rv2sv must appear before a
 * rv2[ah]v, resolution is handled by the first call to a_pp_deref() in the
 * expression. */

STATIC OP *(*a_old_ck_rv2av)(pTHX_ OP *) = 0;
STATIC OP *(*a_old_ck_rv2hv)(pTHX_ OP *) = 0;

STATIC OP *a_ck_rv2xv(pTHX_ OP *o) {
 OP * (*old_ck)(pTHX_ OP *o) = 0;
 OP * (*new_pp)(pTHX)        = 0;
 UV hint;

 switch (o->op_type) {
  case OP_RV2AV: old_ck = a_old_ck_rv2av; new_pp = a_pp_rv2av; break;
  case OP_RV2HV: old_ck = a_old_ck_rv2hv; new_pp = a_pp_rv2hv_simple; break;
 }
 o = CALL_FPTR(old_ck)(aTHX_ o);

 if (cUNOPo->op_first->op_type == OP_GV)
  return o;

 hint = a_hint();
 if (hint & A_HINT_DO && !(hint & A_HINT_STRICT)) {
  a_map_store_root(o, o->op_ppaddr, hint);
  o->op_ppaddr = new_pp;
 } else
  a_map_delete(o);

 return o;
}

/* ... ck_xslice (aslice,hslice) ........................................... */

/* I think those are only found at the root, but there's nothing that really
 * prevent them to be inside the expression too. We only need to update the
 * root so that the rest of the expression will see the right context when
 * resolving. That's why we don't replace the ppaddr. */

STATIC OP *(*a_old_ck_aslice)(pTHX_ OP *) = 0;
STATIC OP *(*a_old_ck_hslice)(pTHX_ OP *) = 0;

STATIC OP *a_ck_xslice(pTHX_ OP *o) {
 OP * (*old_ck)(pTHX_ OP *o) = 0;
 UV hint = a_hint();

 switch (o->op_type) {
  case OP_ASLICE:
   old_ck = a_old_ck_aslice;
   break;
  case OP_HSLICE:
   old_ck = a_old_ck_hslice;
   if (hint & A_HINT_DO)
    a_recheck_rv2xv(cUNOPo->op_first->op_sibling, OP_RV2HV, a_pp_rv2hv);
   break;
 }
 o = CALL_FPTR(old_ck)(aTHX_ o);

 if (hint & A_HINT_DO) {
  a_map_store_root(o, 0, hint);
 } else
  a_map_delete(o);

 return o;
}

/* ... ck_root (exists,delete,keys,values) ................................. */

/* Those ops are only found at the root of a dereferencing expression. We can
 * then resolve at compile time if vivification must take place or not. */

STATIC OP *(*a_old_ck_exists)(pTHX_ OP *) = 0;
STATIC OP *(*a_old_ck_delete)(pTHX_ OP *) = 0;
STATIC OP *(*a_old_ck_keys)  (pTHX_ OP *) = 0;
STATIC OP *(*a_old_ck_values)(pTHX_ OP *) = 0;

STATIC OP *a_ck_root(pTHX_ OP *o) {
 OP * (*old_ck)(pTHX_ OP *o) = 0;
 OP * (*new_pp)(pTHX)        = 0;
 bool enabled = FALSE;
 UV hint = a_hint();

 switch (o->op_type) {
  case OP_EXISTS:
   old_ck  = a_old_ck_exists;
   new_pp  = a_pp_root_binop;
   enabled = hint & A_HINT_EXISTS;
   break;
  case OP_DELETE:
   old_ck  = a_old_ck_delete;
   new_pp  = a_pp_root_binop;
   enabled = hint & A_HINT_DELETE;
   break;
  case OP_KEYS:
   old_ck  = a_old_ck_keys;
   new_pp  = a_pp_root_unop;
   enabled = hint & A_HINT_FETCH;
   break;
  case OP_VALUES:
   old_ck  = a_old_ck_values;
   new_pp  = a_pp_root_unop;
   enabled = hint & A_HINT_FETCH;
   break;
 }
 o = CALL_FPTR(old_ck)(aTHX_ o);

 if (hint & A_HINT_DO) {
  if (enabled) {
   a_map_update_flags_topdown(o, hint | A_HINT_DEREF);
   a_map_store_root(o, o->op_ppaddr, hint);
   o->op_ppaddr = new_pp;
  } else {
   a_map_cancel(o);
  }
 } else
  a_map_delete(o);

 return o;
}

STATIC U32 a_initialized = 0;

STATIC void a_teardown(pTHX_ void *root) {

 if (!a_initialized)
  return;

#if A_MULTIPLICITY
 if (aTHX != root)
  return;
#endif

#if A_THREADSAFE && A_WORKAROUND_REQUIRE_PROPAGATION
 {
  dMY_CXT;
  ptable_hints_free(MY_CXT.tbl);
 }
#endif

 PL_check[OP_PADANY] = MEMBER_TO_FPTR(a_old_ck_padany);
 a_old_ck_padany     = 0;
 PL_check[OP_PADSV]  = MEMBER_TO_FPTR(a_old_ck_padsv);
 a_old_ck_padsv      = 0;

 PL_check[OP_AELEM]  = MEMBER_TO_FPTR(a_old_ck_aelem);
 a_old_ck_aelem      = 0;
 PL_check[OP_HELEM]  = MEMBER_TO_FPTR(a_old_ck_helem);
 a_old_ck_helem      = 0;
 PL_check[OP_RV2SV]  = MEMBER_TO_FPTR(a_old_ck_rv2sv);
 a_old_ck_rv2sv      = 0;

 PL_check[OP_RV2AV]  = MEMBER_TO_FPTR(a_old_ck_rv2av);
 a_old_ck_rv2av      = 0;
 PL_check[OP_RV2HV]  = MEMBER_TO_FPTR(a_old_ck_rv2hv);
 a_old_ck_rv2hv      = 0;

 PL_check[OP_ASLICE] = MEMBER_TO_FPTR(a_old_ck_aslice);
 a_old_ck_aslice     = 0;
 PL_check[OP_HSLICE] = MEMBER_TO_FPTR(a_old_ck_hslice);
 a_old_ck_hslice     = 0;

 PL_check[OP_EXISTS] = MEMBER_TO_FPTR(a_old_ck_exists);
 a_old_ck_exists     = 0;
 PL_check[OP_DELETE] = MEMBER_TO_FPTR(a_old_ck_delete);
 a_old_ck_delete     = 0;
 PL_check[OP_KEYS]   = MEMBER_TO_FPTR(a_old_ck_keys);
 a_old_ck_keys       = 0;
 PL_check[OP_VALUES] = MEMBER_TO_FPTR(a_old_ck_values);
 a_old_ck_values     = 0;

 if (a_pp_padsv_saved) {
  PL_ppaddr[OP_PADSV] = a_pp_padsv_saved;
  a_pp_padsv_saved    = 0;
 }

 a_initialized = 0;
}

STATIC void a_setup(pTHX) {
#define a_setup() a_setup(aTHX)
 if (a_initialized)
  return;

#if A_THREADSAFE && A_WORKAROUND_REQUIRE_PROPAGATION
 {
  MY_CXT_INIT;
  MY_CXT.tbl   = ptable_new();
  MY_CXT.owner = aTHX;
 }
#endif

 a_old_ck_padany     = PL_check[OP_PADANY];
 PL_check[OP_PADANY] = MEMBER_TO_FPTR(a_ck_padany);
 a_old_ck_padsv      = PL_check[OP_PADSV];
 PL_check[OP_PADSV]  = MEMBER_TO_FPTR(a_ck_padsv);

 a_old_ck_aelem      = PL_check[OP_AELEM];
 PL_check[OP_AELEM]  = MEMBER_TO_FPTR(a_ck_deref);
 a_old_ck_helem      = PL_check[OP_HELEM];
 PL_check[OP_HELEM]  = MEMBER_TO_FPTR(a_ck_deref);
 a_old_ck_rv2sv      = PL_check[OP_RV2SV];
 PL_check[OP_RV2SV]  = MEMBER_TO_FPTR(a_ck_deref);

 a_old_ck_rv2av      = PL_check[OP_RV2AV];
 PL_check[OP_RV2AV]  = MEMBER_TO_FPTR(a_ck_rv2xv);
 a_old_ck_rv2hv      = PL_check[OP_RV2HV];
 PL_check[OP_RV2HV]  = MEMBER_TO_FPTR(a_ck_rv2xv);

 a_old_ck_aslice     = PL_check[OP_ASLICE];
 PL_check[OP_ASLICE] = MEMBER_TO_FPTR(a_ck_xslice);
 a_old_ck_hslice     = PL_check[OP_HSLICE];
 PL_check[OP_HSLICE] = MEMBER_TO_FPTR(a_ck_xslice);

 a_old_ck_exists     = PL_check[OP_EXISTS];
 PL_check[OP_EXISTS] = MEMBER_TO_FPTR(a_ck_root);
 a_old_ck_delete     = PL_check[OP_DELETE];
 PL_check[OP_DELETE] = MEMBER_TO_FPTR(a_ck_root);
 a_old_ck_keys       = PL_check[OP_KEYS];
 PL_check[OP_KEYS]   = MEMBER_TO_FPTR(a_ck_root);
 a_old_ck_values     = PL_check[OP_VALUES];
 PL_check[OP_VALUES] = MEMBER_TO_FPTR(a_ck_root);

#if A_MULTIPLICITY
 call_atexit(a_teardown, aTHX);
#else
 call_atexit(a_teardown, NULL);
#endif

 a_initialized = 1;
}

STATIC U32 a_booted = 0;

/* --- XS ------------------------------------------------------------------ */

MODULE = autovivification      PACKAGE = autovivification

PROTOTYPES: ENABLE

BOOT: 
{                                    
 if (!a_booted++) {
  HV *stash;

  a_op_map = ptable_new();
#ifdef USE_ITHREADS
  MUTEX_INIT(&a_op_map_mutex);
#endif

  PERL_HASH(a_hash, __PACKAGE__, __PACKAGE_LEN__);

  stash = gv_stashpvn(__PACKAGE__, __PACKAGE_LEN__, 1);
  newCONSTSUB(stash, "A_HINT_STRICT", newSVuv(A_HINT_STRICT));
  newCONSTSUB(stash, "A_HINT_WARN",   newSVuv(A_HINT_WARN));
  newCONSTSUB(stash, "A_HINT_FETCH",  newSVuv(A_HINT_FETCH));
  newCONSTSUB(stash, "A_HINT_STORE",  newSVuv(A_HINT_STORE));
  newCONSTSUB(stash, "A_HINT_EXISTS", newSVuv(A_HINT_EXISTS));
  newCONSTSUB(stash, "A_HINT_DELETE", newSVuv(A_HINT_DELETE));
  newCONSTSUB(stash, "A_HINT_MASK",   newSVuv(A_HINT_MASK));
  newCONSTSUB(stash, "A_THREADSAFE",  newSVuv(A_THREADSAFE));
  newCONSTSUB(stash, "A_FORKSAFE",    newSVuv(A_FORKSAFE));
 }

 a_setup();
}

#if A_THREADSAFE && A_WORKAROUND_REQUIRE_PROPAGATION

void
CLONE(...)
PROTOTYPE: DISABLE
PREINIT:
 ptable *t;
 int    *level;
CODE:
 {
  my_cxt_t ud;
  dMY_CXT;
  ud.tbl   = t = ptable_new();
  ud.owner = MY_CXT.owner;
  ptable_walk(MY_CXT.tbl, a_ptable_clone, &ud);
 }
 {
  MY_CXT_CLONE;
  MY_CXT.tbl   = t;
  MY_CXT.owner = aTHX;
 }
 {
  level = PerlMemShared_malloc(sizeof *level);
  *level = 1;
  LEAVEn("sub");
  SAVEDESTRUCTOR_X(a_thread_cleanup, level);
  ENTERn("sub");
 }

#endif

SV *
_tag(SV *hint)
PROTOTYPE: $
CODE:
 RETVAL = a_tag(SvOK(hint) ? SvUV(hint) : 0);
OUTPUT:
 RETVAL

SV *
_detag(SV *tag)
PROTOTYPE: $
CODE:
 if (!SvOK(tag))
  XSRETURN_UNDEF;
 RETVAL = newSVuv(a_detag(tag));
OUTPUT:
 RETVAL