-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathXS.xs
More file actions
8839 lines (8295 loc) · 263 KB
/
Copy pathXS.xs
File metadata and controls
8839 lines (8295 loc) · 263 KB
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
#define PERL_NO_GET_CONTEXT 1 /* Define at top for more efficiency. */
#if defined(__clang__) && defined(__clang_major__) && __clang_major__ > 11
#pragma clang diagnostic ignored "-Wcompound-token-split-by-macro"
#endif
#include <stdio.h> /* For fileno and stdout */
#include <stdlib.h> /* For free */
#include <string.h> /* For memcmp */
#include <errno.h> /* For errno */
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
#if defined(HAS_FORK) && defined(HAS_PTHREAD_ATFORK)
# include <pthread.h>
#endif
#define NEED_newCONSTSUB
#define NEED_newRV_noinc
#define NEED_sv_2pv_flags
#define NEED_HvNAME_get
#define NEED_grok_number
#define NEED_grok_numeric_radix
#include "ppport.h"
#include "multicall.h" /* only works in 5.6 and newer */
#include "multicall_scoped.h" /* SC_ versions do auto-scoping */
#include "ptypes.h"
/* See xs_internal.h for _validate_and_set mask and status semantics. */
#include "xs_internal.h"
#include "xs_set.h"
#include "cache.h"
#include "sieve.h"
#include "sieve_cluster.h"
#include "util.h"
#include "util_bits.h"
#include "util_math.h"
#include "strint.h"
#include "sort.h"
#include "primality.h"
#include "lucas_seq.h"
#include "factor.h"
#include "factor128.h"
#include "tinysiqs128.h"
#include "inverse_sigma0.h"
#include "znlog.h"
#include "totients.h"
#include "moebius.h"
#include "factmod.h"
#include "lehmer.h"
#include "lmo.h"
#include "legendre_phi.h"
#include "aks.h"
#include "constants.h"
#include "mulmod.h"
#include "entropy.h"
#include "csprng.h"
#include "random_prime.h"
#include "perfect_powers.h"
#include "prime_powers.h"
#include "ramanujan_primes.h"
#include "semi_primes.h"
#include "twin_primes.h"
#include "almost_primes.h"
#include "omega_primes.h"
#include "prime_counts.h"
#include "prime_sums.h"
#include "congruent_numbers.h"
#include "intcomplexity.h"
#include "powerfree.h"
#include "powerful.h"
#include "lucky_numbers.h"
#include "goldbach.h"
#include "rootmod.h"
#include "rational.h"
#include "real.h"
#include "ds_iset.h" /* Used for sumset, setbinop, vecuniq */
/* multicall compatibility stuff */
#if PERL_VERSION_LT(5,7,0) || !defined(dMULTICALL)
# define USE_MULTICALL 0 /* Too much trouble to work around it */
#else
# define USE_MULTICALL 1
#endif
#if PERL_VERSION_LT(5,13,9)
# define FIX_MULTICALL_REFCOUNT \
if (CvDEPTH(multicall_cv) > 1) SvREFCNT_inc(multicall_cv);
#else
# define FIX_MULTICALL_REFCOUNT
#endif
/* Some older Perl headers define Perl_isfinite in terms of helpers that are
* not available in all builds. This only sees a local NV, so avoid those
* compatibility macros entirely. */
#define MPU_NV_ISFINITE(x) ((x) == (x) && ((x) - (x)) == 0.0)
/* Perl globals we use for setting a and b inside the called block */
#define plAgv PL_firstgv
#define plBgv PL_secondgv
#ifndef CvISXSUB
# define CvISXSUB(cv) CvXSUB(cv)
#endif
/* Not right, but close. We don't use it ourselves, but core macros do. */
#if !defined cxinc && PERL_VERSION_GE(5,8,1) && PERL_VERSION_LT(5,11,0)
# define cxinc() Perl_cxinc(aTHX)
#endif
#if PERL_VERSION_LT(5,17,7)
# define SvREFCNT_dec_NN(sv) SvREFCNT_dec(sv)
#endif
#if PERL_VERSION_LT(5,20,0)
# define EXTEND_TYPE int
#else
# define EXTEND_TYPE SSize_t
#endif
#define MAX_EXTEND ((Size_t)((EXTEND_TYPE)-1))
#if PERL_VERSION_GE(5,14,0) && defined(XopENTRY_set)
# define MPU_HAS_CUSTOM_OPS 1
#else
# define MPU_HAS_CUSTOM_OPS 0
#endif
/******************************************************************************/
/******************************************************************************/
/* Information about the GMP back end.
*
* This is not ideal in a couple ways.
*
* - The return type info would be useful for non-GMP functions also. The
* thought was to use this to automatically apply objectify. The PP
* backend should take care of the result itself.
*
* - The versioning is limited. Having more fine grain info, e.g. the GMP
* module provides semantics 20210808 of modint, while we need 20250212.
*
* No matter what we do it's going to be tricky with things like adding
* support for negative inputs, while positive ones remain unchanged.
*/
typedef enum {
R_VOID,
R_BOOL,
R_NATIVE,
R_BIGINT,
R_AREF,
R_OTHER,
} gmp_return_type_t;
typedef struct {
const char *name;
uint32_t version;
uint16_t nretvals;
gmp_return_type_t rettype;
} gmp_info_t;
static const gmp_info_t gmp_info[] = {
{ "sqrtint", 40, 1, R_BIGINT },
{ "addint", 52, 1, R_BIGINT },
{ "subint", 52, 1, R_BIGINT },
{ "mulint", 52, 1, R_BIGINT },
{ "divint", 52, 1, R_BIGINT },
{ "modint", 52, 1, R_BIGINT },
{ "powint", 54, 1, R_BIGINT }, /* 52 with UV exponent */
{ "absint", 52, 1, R_BIGINT },
{ "negint", 52, 1, R_BIGINT },
{ "cdivint", 53, 1, R_BIGINT },
{ "add1int", 53, 1, R_BIGINT },
{ "sub1int", 53, 1, R_BIGINT },
{ "lshiftint", 53, 1, R_BIGINT },
{ "rshiftint", 53, 1, R_BIGINT },
{ "rashiftint", 53, 1, R_BIGINT },
{ "logint", 47, 1, R_BIGINT }, /* no root return */
{ "rootint", 40, 1, R_BIGINT }, /* no root return */
{ "muladdint", 54, 1, R_BIGINT },
{ "mulsubint", 54, 1, R_BIGINT },
{ "addmulint", 54, 1, R_BIGINT },
{ "submulint", 54, 1, R_BIGINT },
{ "invmod", 20, 1, R_BIGINT },
{ "znorder", 22, 1, R_BIGINT },
{ "znlog", 54, 1, R_BIGINT },
{ "znprimroot", 22, 1, R_BIGINT },
{ "negmod", 53, 1, R_BIGINT },
{ "addmod", 53, 1, R_BIGINT }, /* 36 with n > 0 */
{ "submod", 53, 1, R_BIGINT },
{ "mulmod", 53, 1, R_BIGINT }, /* 36 with n > 0 */
{ "powmod", 53, 1, R_BIGINT }, /* 36 with n > 0 */
{ "divmod", 53, 1, R_BIGINT }, /* 36 with n > 0 */
{ "muladdmod", 53, 1, R_BIGINT },
{ "mulsubmod", 53, 1, R_BIGINT },
{ "factorialmod", 54, 1, R_BIGINT }, /* 47 with m > 0 */
{ "binomialmod", 54, 1, R_BIGINT },
{ "divrem", 52, 2, R_BIGINT },
{ "tdivrem", 52, 2, R_BIGINT },
{ "fdivrem", 53, 2, R_BIGINT },
{ "cdivrem", 53, 2, R_BIGINT },
{ "sqrtmod", 53, 1, R_BIGINT }, /* 53 for composites */
{ "rootmod", 54, 1, R_BIGINT },
{ "allsqrtmod", 54, 0xFF, R_BIGINT },
{ "allrootmod", 54, 0xFF, R_BIGINT },
{ "is_primitive_root", 36, 1, R_BOOL },
{ "is_semiprime", 42, 1, R_BOOL },
{ "is_square", 47, 1, R_BOOL },
{ "is_carmichael", 47, 1, R_BOOL },
{ "is_perfect_power", 47, 1, R_BOOL },
{ "is_fundamental", 47, 1, R_BOOL },
{ "is_totient", 47, 1, R_BOOL },
{ "is_practical", 53, 1, R_BOOL },
{ "is_square_free", 53, 1, R_BOOL },
{ "is_powerfree", 53, 1, R_BOOL },
{ "is_smooth", 53, 1, R_BOOL },
{ "is_rough", 53, 1, R_BOOL },
{ "is_almost_prime", 54, 1, R_BOOL }, /* 53 with UV k */
{ "is_divisible", 53, 1, R_BOOL },
{ "is_congruent", 53, 1, R_BOOL },
{ "is_powerful", 53, 1, R_BOOL },
{ "is_qr", 53, 1, R_BOOL },
{ "is_safe_prime", 54, 1, R_BOOL },
{ "is_prime", 1, 1, R_BOOL },
{ "is_prob_prime", 1, 1, R_BOOL },
{ "is_provable_prime", 4, 1, R_BOOL },
{ "is_bpsw_prime", 17, 1, R_BOOL },
{ "is_aks_prime", 16, 1, R_BOOL },
{ "is_mersenne_prime", 28, 1, R_BOOL },
{ "is_gaussian_prime", 52, 1, R_BOOL },
{ "is_pseudoprime", 53, 1, R_BOOL }, /* v0.41 with bases */
{ "is_euler_pseudoprime", 53, 1, R_BOOL }, /* v0.41 with bases */
{ "is_strong_pseudoprime", 53, 1, R_BOOL }, /* v0.41 with bases */
{ "is_euler_plumb_pseudoprime", 39, 1, R_BOOL },
{ "is_perrin_pseudoprime", 40, 1, R_BOOL },
{ "is_lucas_pseudoprime", 1, 1, R_BOOL },
{ "is_strong_lucas_pseudoprime", 1, 1, R_BOOL },
{ "is_extra_strong_lucas_pseudoprime", 1, 1, R_BOOL },
{ "is_almost_extra_strong_lucas_pseudoprime", 13, 1, R_BOOL },
{ "is_frobenius_pseudoprime", 54, 1, R_BOOL }, /* v0.24 IVs */
{ "is_frobenius_underwood_pseudoprime", 13, 1, R_BOOL },
{ "is_frobenius_khashin_pseudoprime", 54, 1, R_BOOL },
{ "miller_rabin_random", 46, 1, R_BOOL },
{ "next_prime", 1, 1, R_BIGINT },
{ "prev_prime", 1, 1, R_BIGINT },
{ "kronecker", 17, 1, R_NATIVE },
{ "valuation", 20, 1, R_NATIVE },
{ "liouville", 22, 1, R_NATIVE },
{ "hammingweight", 47, 1, R_NATIVE },
{ "prime_omega", 53, 1, R_NATIVE },
{ "prime_bigomega", 53, 1, R_NATIVE },
{ "consecutive_integer_lcm", 4, 1, R_BIGINT },
{ "partitions", 16, 1, R_BIGINT },
{ "partitionsq", 54, 1, R_BIGINT },
{ "gcd", 17, 1, R_BIGINT },
{ "lcm", 17, 1, R_BIGINT },
{ "vecsum", 20, 1, R_BIGINT },
{ "vecprod", 26, 1, R_BIGINT },
{ "exp_mangoldt", 19, 1, R_BIGINT },
{ "jordan_totient", 22, 1, R_BIGINT },
{ "carmichael_lambda", 22, 1, R_BIGINT },
{ "binomial", 54, 1, R_BIGINT }, /* v0.22 n > 0, k native */
{ "stirling", 54, 1, R_BIGINT }, /* v0.26 with UV n and m */
{ "lucasu", 53, 1, R_BIGINT }, /* v0.53 with bigint P,Q */
{ "lucasv", 53, 1, R_BIGINT }, /* v0.53 with bigint P,Q */
{ "fibonacci", 54, 1, R_BIGINT },
{ "lucas_number", 54, 1, R_BIGINT },
{ "catalan_number", 54, 1, R_BIGINT },
{ "bell_number", 54, 1, R_BIGINT },
{ "fubini", 54, 1, R_BIGINT },
{ "chinese", 32, 1, R_BIGINT },
{ "chinese2", 53, 2, R_BIGINT },
{ "ramanujan_tau", 53, 1, R_BIGINT }, /* v0.53 much faster */
{ "legendre_phi", 54, 1, R_BIGINT },
{ "dedekind_psi", 54, 1, R_BIGINT },
{ "aliquot_sum", 54, 1, R_BIGINT },
{ "abundance", 54, 1, R_BIGINT },
{ "sopf", 54, 1, R_BIGINT },
{ "sopfr", 54, 1, R_BIGINT },
{ "gcdext", 35, 3, R_BIGINT },
{ "primorial", 37, 1, R_BIGINT },
{ "pn_primorial", 37, 1, R_BIGINT },
{ "permtonum", 47, 1, R_BIGINT },
{ "multifactorial", 54, 1, R_BIGINT }, /* v0.51 with UV args */
{ "subfactorial", 51, 1, R_BIGINT },
{ "falling_factorial", 51, 1, R_BIGINT },
{ "rising_factorial", 51, 1, R_BIGINT },
{ "lucasumod", 53, 1, R_BIGINT },
{ "lucasvmod", 53, 1, R_BIGINT },
{ "lucasuv", 53, 2, R_BIGINT },
{ "lucasuvmod", 53, 2, R_BIGINT },
{ "lucas_sequence", 54, 3, R_BIGINT }, /* v0.13 with IV P,Q */
{ "powersum", 53, 1, R_BIGINT },
{ "fromdigits", 54, 1, R_BIGINT },
{ "remove_factors", 54, 1, R_BIGINT },
{ "remove_factors_exp", 54, 2, R_BIGINT },
{ "urandomb", 43, 1, R_BIGINT },
{ "urandomr", 54, 1, R_BIGINT }, /* v0.43 with non-neg */
{ "urandomm", 44, 1, R_BIGINT },
{ "random_nbit_prime", 42, 1, R_BIGINT },
{ "random_ndigit_prime", 54, 1, R_BIGINT }, /* v0.42 with UV n */
{ "random_strong_prime", 43, 1, R_BIGINT },
{ "random_maurer_prime", 43, 1, R_BIGINT },
{"random_shawe_taylor_prime", 43, 1, R_BIGINT },
{ "random_prime", 54, 1, R_BIGINT }, /* uniform fallback in v0.54 */
{ "random_safe_prime", 52, 1, R_BIGINT },
{ "sieve_range", 36, 0xFF, R_BIGINT },
{ "sieve_prime_cluster", 34, 0xFF, R_BIGINT },
{ "divisors", 53, 0xFF, R_BIGINT },
{ "factor", 41, 0xFF, R_BIGINT },
{ "euler_phi", 54, 0xFF, R_BIGINT },
{ "moebius", 49, 0xFF, R_NATIVE }, /* v0.22 with non-neg */
{ "prime_signature", 54, 0xFF, R_BIGINT },
{ "vecprefixsum", 54, 0xFF, R_BIGINT },
{ "numtoperm", 47, 0xFF, R_NATIVE },
{ "todigits", 41, 0xFF, R_NATIVE },
{ "powerful_count", 53, 1, R_BIGINT },
{ "powerfree_count", 53, 1, R_BIGINT },
{ "prime_power_count", 53, 1, R_BIGINT },
{ "perfect_power_count", 53, 1, R_BIGINT },
{ "nth_powerfree", 53, 1, R_BIGINT },
{ "nth_perfect_power", 53, 1, R_BIGINT },
{ "nth_perfect_power_approx", 53, 1, R_BIGINT },
{ "next_perfect_power", 53, 1, R_BIGINT },
{ "prev_perfect_power", 53, 1, R_BIGINT },
{ "is_power", 54, 1, R_NATIVE }, /* no root return, v0.42 UV k */
{ "is_prime_power", 40, 1, R_NATIVE }, /* no root return */
{ "is_polygonal", 47, 1, R_BOOL }, /* no root return */
{ "bernfrac", 24, 2, R_BIGINT },
{ "harmfrac", 30, 2, R_BIGINT },
{ "primes", 54, 1, R_AREF },
{ "twin_primes", 54, 1, R_AREF },
/* if the input is already a bigint type, we want to use that */
/* { "factorial", 24, 1, R_BIGINT }, */
#if 0 /* the APIs are not identical */
{ "trial_factor", 47, 0xFF, R_BIGINT },
{ "holf_factor", 47, 0xFF, R_BIGINT },
{ "squfof_factor", 47, 0xFF, R_BIGINT },
{ "phro_factor", 47, 0xFF, R_BIGINT },
{ "pplus1_factor", 47, 0xFF, R_BIGINT },
{ "pbrent_factor", 47, 0xFF, R_BIGINT },
{ "pminus1_factor", 47, 0xFF, R_BIGINT },
{ "ecm_factor", 47, 0xFF, R_BIGINT },
{ "cheb_factor", 53, 0xFF, R_BIGINT },
#endif
};
/******************************************************************************/
#define MY_CXT_KEY "Math::Prime::Util::API_guts"
#define CINTS 100
typedef struct {
HV* MPUroot;
HV* MPUGMP;
HV* MPUPP;
SV* const_int[CINTS+1]; /* -1, 0, 1, ..., 99 */
void* randcxt; /* per-thread csprng context */
uint16_t forcount; /* Track nesting level of for loops */
char forexit; /* Boolean whether we should exit early */
const char* bigintname; /* name of desired bigint class */
HV* bigintstash;
} my_cxt_t;
START_MY_CXT
#if defined(HAS_FORK) && defined(HAS_PTHREAD_ATFORK)
static void *_csprng_fork_context = NULL;
static char _csprng_atfork_initialized = 0;
static pthread_mutex_t _csprng_fork_mutex = PTHREAD_MUTEX_INITIALIZER;
static void _csprng_before_fork(void)
{
dTHX;
dMY_CXT;
(void) pthread_mutex_lock(&_csprng_fork_mutex);
_csprng_fork_context = MY_CXT.randcxt;
}
static void _csprng_after_fork_parent(void)
{
_csprng_fork_context = NULL;
(void) pthread_mutex_unlock(&_csprng_fork_mutex);
}
static void _csprng_after_fork_child(void)
{
void *ctx = _csprng_fork_context;
_csprng_fork_context = NULL;
if (ctx != NULL)
csprng_require_reseed(ctx);
(void) pthread_mutex_unlock(&_csprng_fork_mutex);
}
static void _csprng_init_fork_tracking(void)
{
int status = 0;
(void) pthread_mutex_lock(&_csprng_fork_mutex);
if (!_csprng_atfork_initialized) {
status = pthread_atfork(_csprng_before_fork,
_csprng_after_fork_parent,
_csprng_after_fork_child);
if (status == 0)
_csprng_atfork_initialized = 1;
}
(void) pthread_mutex_unlock(&_csprng_fork_mutex);
if (status != 0)
croak("Unable to register CSPRNG fork handler");
}
#endif
static void xs_set_bigint_class(pTHX_ SV* sv) {
dMY_CXT;
if (sv == NULL || !SvOK(sv) || SvCUR(sv) == 0) {
MY_CXT.bigintstash = NULL;
MY_CXT.bigintname = NULL;
} else {
HV* stash = gv_stashsv(sv, GV_ADD);
MY_CXT.bigintstash = stash;
MY_CXT.bigintname = HvNAME(stash);
}
}
static SV* _sv_const_int(pTHX_ IV v) {
if (v >= -1 && v < CINTS) {
dMY_CXT;
return MY_CXT.const_int[v+1];
}
return sv_2mortal(newSViv(v));
}
typedef struct {
uint16_t previous_forcount;
uint16_t expected_forcount;
char previous_forexit;
char active;
} forcount_guard_t;
typedef struct {
SSize_t narrays;
SSize_t *arlen;
SSize_t *arcnt;
SV ***arsvs;
char active;
} forsetproduct_guard_t;
static void forcount_guard_cleanup(pTHX_ void *arg) {
forcount_guard_t *guard = (forcount_guard_t *)arg;
if (guard->active) {
dMY_CXT;
MY_CXT.forcount = guard->previous_forcount;
MY_CXT.forexit = guard->previous_forexit;
guard->active = 0;
}
Safefree(guard);
}
static void forsetproduct_guard_release(pTHX_ forsetproduct_guard_t *guard) {
SSize_t i, j;
if (!guard || !guard->active)
return;
if (guard->arsvs) {
for (i = 0; i < guard->narrays; i++) {
if (guard->arsvs[i]) {
SSize_t len = guard->arlen ? guard->arlen[i] : 0;
for (j = 0; j < len; j++)
if (guard->arsvs[i][j])
SvREFCNT_dec(guard->arsvs[i][j]);
Safefree(guard->arsvs[i]);
}
}
Safefree(guard->arsvs);
guard->arsvs = 0;
}
Safefree(guard->arlen);
guard->arlen = 0;
Safefree(guard->arcnt);
guard->arcnt = 0;
guard->active = 0;
}
static void forsetproduct_guard_cleanup(pTHX_ void *arg) {
forsetproduct_guard_t *guard = (forsetproduct_guard_t *)arg;
forsetproduct_guard_release(aTHX_ guard);
Safefree(guard);
}
#define SV_USE_BIGINT_AMAGIC(svn) \
( (_sv_is_bigint_fast(aTHX_ svn) || (!_XS_get_callgmp() && _sv_is_bigint(aTHX_ svn))) \
&& (SvGETMAGIC(svn),SvAMAGIC(svn)) )
#define SV_USE_FAST_BIGINT_AMAGIC(svn) \
( _sv_is_bigint_fast(aTHX_ svn) && (SvGETMAGIC(svn),SvAMAGIC(svn)) )
/******************************************************************************/
#if BITS_PER_WORD == 32
static const unsigned int uvmax_maxlen = 10;
static const NV nvuvmaxval = 4294967295.0;
static const NV nvivminval = -2147483648.0;
#else
static const unsigned int uvmax_maxlen = 20;
/* TODO, why not 562949953421312 or nvmantbits? */
static const NV nvuvmaxval = 70368744177664.0; /* 2^46 */
static const NV nvivminval = -35184372088832.0; /* -2^45 */
#endif
/******************************************************************************/
static bool xs_validate_integer_inplace(pTHX_ SV* svn, uint32_t mask);
static SV* xs_to_bigint(pTHX_ SV* r);
static SV* xs_to_canonical(pTHX_ SV* sv);
static void xs_aref_to_canonical(pTHX_ SV* aref, const char* name);
static bool xs_sv_is_perfect_square(pTHX_ SV *sv, int *ret);
static bool xs_kronecker_result(pTHX_ SV *sva, SV *svb, int *ret);
#define VCALL_ROOT 0x0
#define VCALL_PP 0x1
#define VCALL_GMP 0x2
typedef enum {
VCALL_USED_NONE = 0,
VCALL_USED_ROOT,
VCALL_USED_PP,
VCALL_USED_GMP
} vcall_used_t;
static int _vcallsubn(pTHX_ I32 flags, I32 stashflags, const char* name,
int nargs, int minversion, vcall_used_t *used);
static int addint_try_native_result(pTHX_ int opix, SV* sva, SV* svb, const char* opname,
int *astatus_out, int *bstatus_out,
int *is_uv_out, UV *uv_out, IV *iv_out) {
int astatus, bstatus, overflow, postneg, nix, smask;
UV a, b, t, ret;
astatus = _validate_and_set(&a, aTHX_ sva, IFLAG_ANY);
bstatus = _validate_and_set(&b, aTHX_ svb, (opix == 7) ? IFLAG_NONNEG : IFLAG_ANY);
if (astatus_out) *astatus_out = astatus;
if (bstatus_out) *bstatus_out = bstatus;
if (bstatus != 0 && b == 0 && (opix == 3 || opix == 4 || opix == 5))
croak("%s: divide by zero", opname);
if (opix == 7 && astatus != 0 && bstatus == 0) {
if (astatus > 0 && (a == 0 || a == 1)) {
*is_uv_out = 1;
*uv_out = a;
return 1;
}
if (astatus < 0 && neg_iv(a) == 1) {
STRLEN lenb;
const char *sb = SvPV_nomg(svb, lenb);
int odd = (lenb > 0 && isDIGIT(sb[lenb-1]) && ((sb[lenb-1] - '0') & 1));
if (odd) {
*is_uv_out = 0;
*iv_out = -1;
} else {
*is_uv_out = 1;
*uv_out = 1;
}
return 1;
}
}
if (astatus == 0 || bstatus == 0)
return 0;
/* We do native arithmetic using non-negative values plus sign bookkeeping. */
nix = opix; /* mutable op index */
ret = overflow = postneg = 0;
smask = ((astatus == -1) << 1) + (bstatus == -1);
/* smask=0: +a +b smask=1: +a -b smask=2: -a +b smask=3: -a -b */
if (smask != 0) {
if (smask & 2) a = neg_iv(a);
if (smask & 1) b = neg_iv(b);
if (opix == 0) {
switch (smask) {
case 1: nix=1; break;
case 2: nix=1; t=a; a=b; b=t; break;
case 3: postneg=1; break;
default: break;
}
} else if (opix == 1) {
switch (smask) {
case 1: nix=0; break;
case 2: nix=0; postneg=1; break;
case 3: t=a; a=b; b=t; break;
default: break;
}
} else if (opix == 2) {
switch (smask) {
case 1:
case 2: postneg = 1; break;
default: break;
}
} else if (opix == 3) {
switch (smask) {
case 1:
case 2: postneg = 1; nix = 5; break;
default: break;
}
} else if (opix == 4) {
switch (smask) {
case 1: nix = 6; postneg = 1; break;
case 2: nix = 6; break;
case 3: postneg = 1; break;
default: break;
}
} else if (opix == 5) {
switch (smask) {
case 1:
case 2: postneg = 1; nix = 3; break;
default: break;
}
} else if (opix == 7) {
postneg = (b & 1);
}
}
switch (nix) {
case 0: ret = a + b; overflow = UV_MAX-a < b; break;
case 1: ret = a - b;
if (b > a && (IV)ret < 0) {
*is_uv_out = 0;
*iv_out = (IV)ret;
return 1;
}
overflow = (b > a);
break;
case 2: ret = a * b; overflow = a > 0 && UV_MAX/a < b; break;
case 3: ret = a / b; break;
case 4: ret = a % b; break;
case 5: ret = a / b + (a % b != 0); break;
case 6: ret = (a%b) ? b-(a%b) : 0; break;
case 7:
default: ret = ipowsafe(a, b);
overflow = (a > 1 && ret == UV_MAX);
break;
}
if (!overflow) {
if (!postneg) {
*is_uv_out = 1;
*uv_out = ret;
return 1;
}
if (ret <= (UV)IV_MAX) {
*is_uv_out = 0;
*iv_out = neg_iv(ret);
return 1;
}
}
return 0;
}
static SV* addint_try_slow_result(pTHX_ int opix, SV* sva, SV* svb, int astatus, int bstatus, const char* opname) {
if (opix <= 4) {
static const int fast_amg[] = {add_amg, subtr_amg, mult_amg, div_amg, modulo_amg};
if (opix != 3 || (astatus == 1 && bstatus == 1)) {
if (SV_USE_FAST_BIGINT_AMAGIC(sva) || SV_USE_FAST_BIGINT_AMAGIC(svb)) {
SV *tsv = amagic_call(sva, svb, fast_amg[opix], 0);
if (tsv)
return sv_isobject(tsv) ? xs_to_canonical(aTHX_ tsv) : tsv;
}
}
}
if (opix <= 5) {
STRLEN lena, lenb, rlen;
const char *sa = SvPV_nomg(sva, lena), *sb = SvPV_nomg(svb, lenb);
SV* tmp = sv_2mortal(newSV(lena + lenb + 2)); /* safe for all six ops */
if ((opix == 3 || opix == 4 || opix == 5) && sb[0] == '0' && strspn(sb, "0") == lenb)
croak("%s: divide by zero", opname);
switch (opix) {
case 0: rlen = strint_add(SvPVX(tmp), sa, lena, sb, lenb); break;
case 1: rlen = strint_sub(SvPVX(tmp), sa, lena, sb, lenb); break;
case 2: rlen = strint_mul(SvPVX(tmp), sa, lena, sb, lenb); break;
case 3: rlen = strint_divint(SvPVX(tmp), sa, lena, sb, lenb); break;
case 4: rlen = strint_modint(SvPVX(tmp), sa, lena, sb, lenb); break;
default: rlen = strint_cdivint(SvPVX(tmp), sa, lena, sb, lenb); break;
}
if (rlen > 0) {
SvCUR_set(tmp, rlen);
SvPOK_on(tmp);
*SvEND(tmp) = '\0';
return xs_to_canonical(aTHX_ tmp);
}
}
if (opix == 7 && bstatus == 1) {
UV powb;
if (_validate_and_set(&powb, aTHX_ svb, IFLAG_NONNEG) == 1) {
STRLEN lena;
const char *sa = SvPV_nomg(sva, lena);
if (lena > 0 && powb <= (UV)(UVCONST(10000000) / lena)) {
STRLEN limit = (STRLEN)(powb * lena) + 2;
SV* tmp = sv_2mortal(newSV(limit + 1));
STRLEN rlen = strint_pow(SvPVX(tmp), sa, lena, powb, limit);
if (rlen > 0) {
SvCUR_set(tmp, rlen);
SvPOK_on(tmp);
*SvEND(tmp) = '\0';
return xs_to_canonical(aTHX_ tmp);
}
}
}
}
if (opix == 7 && bstatus == 0)
croak("%s: exponent too large", opname);
return NULL;
}
static int add1_try_native_result(pTHX_ int opix, SV* svn, int *status_out,
int *is_uv_out, UV *uv_out, IV *iv_out) {
int status;
UV n;
status = _validate_and_set(&n, aTHX_ svn, IFLAG_ANY);
if (status_out) *status_out = status;
if (status == 1) {
if (opix == 1 && n == 0) {
*is_uv_out = 0;
*iv_out = -1;
return 1;
}
if (opix == 1 || (opix == 0 && n < UV_MAX)) {
*is_uv_out = 1;
*uv_out = (opix == 0) ? n+1 : n-1;
return 1;
}
} else if (status == -1) {
if (opix == 0 || (opix == 1 && (IV)n > IV_MIN)) {
*is_uv_out = 0;
*iv_out = (opix == 0) ? (IV)n+1 : (IV)n-1;
return 1;
}
}
return 0;
}
static SV* add1_try_slow_result(pTHX_ int opix, SV* svn) {
if (SV_USE_FAST_BIGINT_AMAGIC(svn)) {
SV *svone = _sv_const_int(aTHX_ 1);
SV *tsv = amagic_call(svn, svone, opix == 0 ? add_amg : subtr_amg, 0);
if (tsv)
return sv_isobject(tsv) ? xs_to_canonical(aTHX_ tsv) : tsv;
}
{
STRLEN len;
const char *s = SvPV_nomg(svn, len);
SV *tmp = sv_2mortal(newSV(1 + len));
len = strint_add_s(SvPVX(tmp), s, len, "1", 1, opix);
if (len > 0) {
SvCUR_set(tmp, len);
SvPOK_on(tmp);
*SvEND(tmp) = '\0';
return xs_to_canonical(aTHX_ tmp);
}
}
return NULL;
}
/* Return sign (0), oddness (1), or evenness (2). */
static int xs_sign_parity_result(pTHX_ SV* svn, const char* opname, int opix) {
UV n;
int status = _validate_and_set(&n, aTHX_ svn, IFLAG_ANY);
bool isodd;
if (status == 0) {
STRLEN len;
const char* s = SvPV(svn, len);
if (len == 0 || s == 0) croak("%s: invalid non-empty input", opname);
if (opix == 0) return strint_cmp(s, len, "0", 1);
isodd = (s[len-1] == '1' || s[len-1] == '3' || s[len-1] == '5' ||
s[len-1] == '7' || s[len-1] == '9');
return (opix == 1) ? isodd : !isodd;
}
isodd = n & 1;
if (opix == 0) return n != 0 ? status : 0; /* sign */
return (opix == 1) ? isodd : !isodd; /* odd/even */
}
static int xs_cmpint_result(pTHX_ SV *sva, SV *svb) {
int astatus, bstatus;
UV a, b;
astatus = _validate_and_set(&a, aTHX_ sva, IFLAG_ANY);
bstatus = _validate_and_set(&b, aTHX_ svb, IFLAG_ANY);
if (astatus != 0 && bstatus != 0) {
if (astatus > bstatus) return 1;
if (astatus < bstatus) return -1;
if (a == b) return 0;
return ((astatus == 1 && a > b) ||
(astatus == -1 && (IV)a > (IV)b)) ? 1 : -1;
} else {
STRLEN alen, blen;
const char *aptr, *bptr;
SV *acopy;
aptr = SvPV(sva, alen);
acopy = NULL;
if (SvROK(svb) || SvGMAGICAL(svb)) {
acopy = sv_2mortal(newSVpvn(aptr, alen));
aptr = SvPVX(acopy);
}
bptr = SvPV(svb, blen);
return strint_cmp(aptr, alen, bptr, blen);
}
}
/******************************************************************************/
#include "xs_xop.inc"
/******************************************************************************/
static void boot_register_custom_ops(pTHX) {
#if MPU_HAS_CUSTOM_OPS
int i;
CV *custom_cv;
for (i = 0; i < (int)(sizeof(xop_registrations)/sizeof(xop_registrations[0])); i++) {
xop_registration_t *xopreg = &xop_registrations[i];
XopENTRY_set(&xopreg->xop, xop_name, xopreg->xop_name);
XopENTRY_set(&xopreg->xop, xop_desc, xopreg->xop_desc);
Perl_custom_op_register(aTHX_ xopreg->ppfunc, &xopreg->xop);
custom_cv = get_cv(xopreg->cv_name, GV_ADD);
if (custom_cv != NULL)
cv_set_call_checker(custom_cv, xop_call_checker_exact_arity,
(SV*)custom_cv);
}
#else
PERL_UNUSED_CONTEXT;
#endif
}
/* Call a Perl sub to handle work for us. */
static int _vcallsubn(pTHX_ I32 flags, I32 stashflags, const char* name,
int nargs, int minversion, vcall_used_t *used)
{
GV* gv = NULL;
const char* classname = NULL;
dMY_CXT;
Size_t namelen = strlen(name);
/* Try GMP if (1) caller asks, (2) GMP enabled, (3) new enough version. */
int callgmp = (stashflags & VCALL_GMP) ? _XS_get_callgmp() : 0;
int try_gmp = callgmp > 0 && callgmp >= minversion;
int try_pp = stashflags & VCALL_PP;
assert(!(stashflags & ~(VCALL_PP|VCALL_GMP)));
if (used) *used = VCALL_USED_NONE;
if (try_gmp) {
if (hv_exists(MY_CXT.MPUGMP,name,namelen)) {
GV ** gvp = (GV**)hv_fetch(MY_CXT.MPUGMP,name,namelen,0);
if (gvp) {
gv = *gvp;
classname = "Math::Prime::Util::GMP";
if (used) *used = VCALL_USED_GMP;
}
}
/* Fall-through is ok here. */
}
if (!gv && try_pp) {
GV **gvp;
perl_require_pv("Math/Prime/Util/PP.pm");
gvp = (GV**)hv_fetch(MY_CXT.MPUPP, name, namelen, 0);
if (gvp) {
gv = *gvp;
classname = "Math::Prime::Util::PP";
if (used) *used = VCALL_USED_PP;
}
}
if (!gv && !try_pp) {
GV ** gvp = (GV**)hv_fetch(MY_CXT.MPUroot, name, namelen, 0);
if (gvp) {
gv = *gvp;
classname = "Math::Prime::Util";
if (used) *used = VCALL_USED_ROOT;
}
}
if (!gv) { /* If not found, die with a hopefully useful error message. */
classname = try_pp ? "Math::Prime::Util::PP" : "Math::Prime::Util";
if (try_gmp)
croak("internal callback '%s' not found in Math::Prime::Util::GMP or %s", name, classname);
croak("internal callback '%s' not found in %s", name, classname);
}
/* Use PL_stack_sp in PUSHMARK macro directly.
It will be read after the possible mark stack extend. */
PUSHMARK(PL_stack_sp-nargs);
/* No PUTBACK because we didn't move global SP. */
return call_sv((SV*)gv, flags);
}
static NOINLINE const char* _subname(pTHX_ const CV *cv) { return GvNAME(CvGV(cv)); }
#define SUBNAME _subname(aTHX_ cv)
/* -1 if not found, array entry if found */
static int find_gmp_info(const char *name) {
const int ngmpinfo = sizeof(gmp_info)/sizeof(gmp_info[0]);
int i;
/* Stupid linear scan */
for (i = 0; i < ngmpinfo; i++)
if (strcmp(gmp_info[i].name, name) == 0)
return i;
return -1;
}
static NOINLINE int dispatch_external(pTHX_ const CV* thiscv, I32 ax,
I32 context, int nitems, bool gmp_is_ok)
{
const char *name = GvNAME(CvGV(thiscv));
const int ginfoi = find_gmp_info(name);
I32 callflags = VCALL_PP;
uint32_t ver = 0;
bool usegmp = ginfoi >= 0 && gmp_is_ok;
vcall_used_t used = VCALL_USED_NONE;
int nret, i;
if (usegmp) {
ver = gmp_info[ginfoi].version;
callflags |= VCALL_GMP;
}
nret = _vcallsubn(aTHX_ context, callflags, name, nitems, ver, &used);
/* PP handles its own return policy. Normalize GMP bigint returns here. */
if (used == VCALL_USED_GMP && ginfoi >= 0) {
if (gmp_info[ginfoi].rettype == R_BIGINT) {
for (i = 0; i < nret; i++) {
SV* out = xs_to_canonical(aTHX_ PL_stack_base[ax + i]);
PL_stack_base[ax + i] = out;
}
} else if (gmp_info[ginfoi].rettype == R_AREF) {
if (nret != 1)
croak("internal error: %s returned %d values, expected 1 array reference", name, nret);
xs_aref_to_canonical(aTHX_ PL_stack_base[ax], name);
}
}
return nret;
}
#define DISPATCHPP_RETURN() \
do { \
int nr_ = dispatch_external(aTHX_ cv, ax, GIMME_V, items, TRUE); \
XSRETURN(nr_); \
} while (0)
#define DISPATCHPP_RETURN_GMPIF(expr) \
do { \
int nr_ = dispatch_external(aTHX_ cv, ax, GIMME_V, items, !!(expr)); \
XSRETURN(nr_); \
} while (0)
#define DISPATCHPP_RETURN_VOID() \
do { \
(void)_vcallsubn(aTHX_ G_VOID|G_DISCARD, VCALL_PP, SUBNAME, items, 0, NULL); \
XSRETURN(0); \
} while (0)
#define SEED_GMP_CSPRNG(bytes, data) \
do { \
uint32_t seedgmp_bytes_ = (bytes); \
if (_XS_get_callgmp() >= 42) { \
XPUSHs(sv_2mortal(newSVuv(seedgmp_bytes_))); \
XPUSHs(sv_2mortal(newSVpvn((const char*)(data), seedgmp_bytes_))); \
PUTBACK; \
(void)_vcallsubn(aTHX_ G_VOID|G_DISCARD, VCALL_GMP, \
"seed_csprng", 2, 42, NULL); \
SPAGAIN; \
} \
} while (0)
/******************************************************************************/
#define SETSUBREF(cv, block) \
do { \
GV *gv_; \
HV *stash_; \