forked from rurban/perl-compiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCC.pm
3605 lines (3223 loc) · 104 KB
/
CC.pm
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
# CC.pm
#
# Copyright (c) 1996, 1997, 1998 Malcolm Beattie
# Copyright (c) 2009, 2010, 2011 Reini Urban
# Copyright (c) 2010 Heinz Knutzen
# Copyright (c) 2012 cPanel Inc
#
# You may distribute under the terms of either the GNU General Public
# License or the Artistic License, as specified in the README file.
=head1 NAME
B::CC - Perl compiler's optimized C translation backend
=head1 SYNOPSIS
perl -MO=CC[,OPTIONS] foo.pl
=head1 DESCRIPTION
This compiler backend takes Perl source and generates C source code
corresponding to the flow of your program with unrolled ops and optimised
stack handling and lexicals variable types. In other words, this backend is
somewhat a "real" compiler in the sense that many people think about
compilers. Note however that, currently, it is a very poor compiler in that
although it generates (mostly, or at least sometimes) correct code, it
performs relatively few optimisations. This will change as the compiler and
the types develops. The result is that running an executable compiled with
this backend may start up more quickly than running the original Perl program
(a feature shared by the B<C> compiler backend--see L<B::C>) and may also
execute slightly faster. This is by no means a good optimising compiler--yet.
=head1 OPTIONS
If there are any non-option arguments, they are taken to be
names of objects to be saved (probably doesn't work properly yet).
Without extra arguments, it saves the main program.
=over 4
=item B<-ofilename>
Output to filename instead of STDOUT
=item B<-c>
Check and abort.
Compiles and prints only warnings, but does not emit C code.
=item B<-v>
Verbose compilation (prints a few compilation stages).
=item B<-->
Force end of options
=item B<-uPackname>
Force apparently unused subs from package Packname to be compiled.
This allows programs to use eval "foo()" even when sub foo is never
seen to be used at compile time. The down side is that any subs which
really are never used also have code generated. This option is
necessary, for example, if you have a signal handler foo which you
initialise with C<$SIG{BAR} = "foo">. A better fix, though, is just
to change it to C<$SIG{BAR} = \&foo>. You can have multiple B<-u>
options. The compiler tries to figure out which packages may possibly
have subs in which need compiling but the current version doesn't do
it very well. In particular, it is confused by nested packages (i.e.
of the form C<A::B>) where package C<A> does not contain any subs.
=item B<-UPackname> "unuse" skip Package
Ignore all subs from Package to be compiled.
Certain packages might not be needed at run-time, even if the pessimistic
walker detects it.
=item B<-mModulename>
Instead of generating source for a runnable executable, generate
source for an XSUB module. The boot_Modulename function (which
DynaLoader can look for) does the appropriate initialisation and runs
the main part of the Perl source that is being compiled.
=item B<-nInitname>
Provide a different init name for additional objects added via cmdline.
=item B<-strict>
With a DEBUGGING perl compile-time errors for range and flip without
compile-time context are only warnings.
With C<-strict> these warnings are fatal, otherwise only run-time errors occur.
=item B<-On>
Optimisation level (n = 0, 1, 2). B<-O> means B<-O1>.
The following L<B::C> optimisations are applied automatically:
optimize_warn_sv save_data_fh av-init2|av_init save_sig destruct
pv_copy_on_grow
B<-O1> sets B<-ffreetmps-each-bblock>.
B<-O2> adds B<-ffreetmps-each-loop> and B<-fno-destruct> from L<B::C>.
The following options must be set explicitly:
B<-fno-taint> or B<-fomit-taint>,
B<-fslow-signals>,
B<-no-autovivify>,
B<-fno-magic>.
=item B<-f>C<OPTIM>
Force optimisations on or off one at a time.
Unknown optimizations are passed down to L<B::C>.
=item B<-ffreetmps-each-bblock>
Delays FREETMPS from the end of each statement to the end of the each
basic block.
Enabled with B<-O1>.
=item B<-ffreetmps-each-loop>
Delays FREETMPS from the end of each statement to the end of the group
of basic blocks forming a loop. At most one of the freetmps-each-*
options can be used.
Enabled with B<-O2>.
=item B<-fno-inline-ops>
Do not inline calls to certain small pp ops.
Most of the inlinable ops were already inlined.
Turns off inlining for some new ops.
AUTOMATICALLY inlined:
pp_null pp_stub pp_unstack pp_and pp_andassign pp_or pp_orassign pp_cond_expr
pp_padsv pp_const pp_nextstate pp_dbstate pp_rv2gv pp_sort pp_gv pp_gvsv
pp_aelemfast pp_ncmp pp_add pp_subtract pp_multiply pp_divide pp_modulo
pp_left_shift pp_right_shift pp_i_add pp_i_subtract pp_i_multiply pp_i_divide
pp_i_modulo pp_eq pp_ne pp_lt pp_gt pp_le pp_ge pp_i_eq pp_i_ne pp_i_lt
pp_i_gt pp_i_le pp_i_ge pp_scmp pp_slt pp_sgt pp_sle pp_sge pp_seq pp_sne
pp_sassign pp_preinc pp_pushmark pp_list pp_entersub pp_formline pp_goto
pp_enterwrite pp_leavesub pp_leavewrite pp_entergiven pp_leavegiven
pp_entereval pp_dofile pp_require pp_entertry pp_leavetry pp_grepstart
pp_mapstart pp_grepwhile pp_mapwhile pp_return pp_range pp_flip pp_flop
pp_enterloop pp_enteriter pp_leaveloop pp_next pp_redo pp_last pp_subst
pp_substcont
DONE with -finline-ops:
pp_enter pp_reset pp_regcreset pp_stringify
TODO with -finline-ops:
pp_anoncode pp_wantarray pp_srefgen pp_refgen pp_ref pp_trans pp_schop pp_chop
pp_schomp pp_chomp pp_not pp_sprintf pp_anonlist pp_shift pp_once pp_lock
pp_rcatline pp_close pp_time pp_alarm pp_av2arylen: no lvalue, pp_length: no
magic
=item B<-fomit-taint>
Omits generating code for handling perl's tainting mechanism.
=item B<-fslow-signals>
Add PERL_ASYNC_CHECK after every op as in the old Perl runloop before 5.13.
perl "Safe signals" check the state of incoming signals after every op.
See L<http://perldoc.perl.org/perlipc.html#Deferred-Signals-(Safe-Signals)>
We trade safety for more speed and delay the execution of non-IO signals
(IO signals are already handled in PerlIO) from after every single Perl op
to the same ops as used in 5.14.
Only with -fslow-signals we get the old slow and safe behaviour.
=item B<-fno-name-magic>
With the default C<-fname-magic> we infer the SCALAR type for specially named
locals vars and most ops use C vars then, not the perl vars.
Arithmetic and comparison is inlined. Scalar magic is bypassed.
With C<-fno-name-magic> do not infer a local variable type from its name:
B<_i> suffix for int, B<_d> for double, B<_ir> for register int
See the experimental C<-ftype-attr> type attributes.
Currently supported are B<int> and B<double> only. See </load_pad>.
=item B<-ftype-attr> (DOES NOT WORK YET)
Experimentally support B<type attributes> for B<int> and B<double>,
SCALAR only so far.
For most ops new C vars are used then, not the fat perl vars.
Very awkward to use until the basic type classes are supported from
within core or use types.
Enabled with B<-O2>. See L<TYPES> and </load_pad>.
=item B<-fno-autovivify>
Do not vivify array and soon also hash elements when accessing them.
Beware: Vivified elements default to undef, unvivified elements are
invalid.
This is the same as the pragma "no autovivification" and allows
very fast array accesses, 4-6 times faster, without the overhead of
autovivification.pm
=item B<-fno-magic>
Assume certain data being optimized is never tied or is holding other magic.
This mainly holds for arrays being optimized, but in the future hashes also.
=item B<-D>
Debug options (concatenated or separate flags like C<perl -D>).
Verbose debugging options are crucial, because the interactive
debugger L<Od> adds a lot of ballast to the resulting code.
=item B<-Dr>
Writes debugging output to STDERR just as it's about to write to the
program's runtime (otherwise writes debugging info as comments in
its C output).
=item B<-DO>
Outputs each OP as it's compiled
=item B<-Ds>
Outputs the contents of the shadow stack at each OP
=item B<-Dp>
Outputs the contents of the shadow pad of lexicals as it's loaded for
each sub or the main program.
=item B<-Dq>
Outputs the name of each fake PP function in the queue as it's about
to process it.
=item B<-Dl>
Output the filename and line number of each original line of Perl
code as it's processed (C<pp_nextstate>).
=item B<-Dt>
Outputs timing information of compilation stages.
=item B<-DF>
Add Flags info to the code.
=back
=head1 NOTABLE FUNCTIONS
=cut
package B::CC;
our $VERSION = '1.13';
# Start registering the L<types> namespaces.
$main::int::B_CC = $main::double::B_CC = $main::string::B_CC = $VERSION;
use Config;
use strict;
#use 5.008;
use B qw(main_start main_root class comppadlist peekop svref_2object
timing_info init_av end_av sv_undef
OPf_WANT_VOID OPf_WANT_SCALAR OPf_WANT_LIST OPf_WANT
OPf_MOD OPf_STACKED OPf_SPECIAL OPpLVAL_DEFER OPpLVAL_INTRO
OPpASSIGN_BACKWARDS OPpLVAL_INTRO OPpDEREF_AV OPpDEREF_HV
OPpDEREF OPpFLIP_LINENUM G_VOID G_SCALAR G_ARRAY );
#CXt_NULL CXt_SUB CXt_EVAL CXt_SUBST CXt_BLOCK
use B::C qw(save_unused_subs objsym init_sections mark_unused mark_skip
output_all output_boilerplate output_main output_main_rest fixup_ppaddr save_sig
inc_cleanup);
use B::Bblock qw(find_leaders);
use B::Stackobj qw(:types :flags);
use B::C::Flags;
# use attributes qw(get reftype);
@B::OP::ISA = qw(B); # support -Do
@B::LISTOP::ISA = qw(B::BINOP B); # support -Do
push @B::OP::ISA, 'B::NULLOP' if exists $main::B::{'NULLOP'};
# These should probably be elsewhere
# Flags for $op->flags
my $module; # module name (when compiled with -m)
my %done; # hash keyed by $$op of leaders of basic blocks
# which have already been done.
my $leaders; # ref to hash of basic block leaders. Keys are $$op
# addresses, values are the $op objects themselves.
my @bblock_todo; # list of leaders of basic blocks that need visiting
# sometime.
my @cc_todo; # list of tuples defining what PP code needs to be
# saved (e.g. CV, main or PMOP repl code). Each tuple
# is [$name, $root, $start, @padlist]. PMOP repl code
# tuples inherit padlist.
my %cc_pp_sub; # hashed names of pp_sub functions already saved
my @stack; # shadows perl's stack when contents are known.
# Values are objects derived from class B::Stackobj
my @pad; # Lexicals in current pad as Stackobj-derived objects
my @padlist; # Copy of current padlist so PMOP repl code can find it
my @cxstack; # Shadows the (compile-time) cxstack for next,last,redo
# This covers only a small part of the perl cxstack
my $labels; # hashref to array of op labels
my %constobj; # OP_CONST constants as Stackobj-derived objects
# keyed by $$sv.
my $need_freetmps = 0; # We may postpone FREETMPS to the end of each basic
# block or even to the end of each loop of blocks,
# depending on optimisation options.
my $know_op = 0; # Set when C variable op already holds the right op
# (from an immediately preceding DOOP(ppname)).
my $errors = 0; # Number of errors encountered
my $op_count = 0; # for B::compile_stats on verbose
my %no_stack; # PP names which don't need save pp restore stack
my %skip_stack; # PP names which don't need write_back_stack (empty)
my %skip_lexicals; # PP names which don't need write_back_lexicals
my %skip_invalidate; # PP names which don't need invalidate_lexicals
my %ignore_op; # ops which do nothing except returning op_next
my %need_curcop; # ops which need PL_curcop
my $package_pv; # sv->pv of previous op for method_named
my %lexstate; # state of padsvs at the start of a bblock
my ( $verbose, $check );
my ( $entertry_defined, $vivify_ref_defined );
my ( $init_name, %debug, $strict );
# Optimisation options. On the command line, use hyphens instead of
# underscores for compatibility with gcc-style options. We use
# underscores here because they are OK in (strict) barewords.
# Disable with -fno-
my ( $freetmps_each_bblock, $freetmps_each_loop, $inline_ops, $opt_taint, $opt_omit_taint,
$opt_slow_signals, $opt_name_magic, $opt_type_attr, $opt_autovivify, $opt_magic,
%c_optimise );
$inline_ops = 1 unless $^O eq 'MSWin32'; # Win32 cannot link to unexported pp_op() XXX
$opt_name_magic = 1;
my %optimise = (
freetmps_each_bblock => \$freetmps_each_bblock, # -O1
freetmps_each_loop => \$freetmps_each_loop, # -O2
inline_ops => \$inline_ops, # not on Win32
omit_taint => \$opt_omit_taint,
taint => \$opt_taint,
slow_signals => \$opt_slow_signals,
name_magic => \$opt_name_magic,
type_attr => \$opt_type_attr,
autovivify => \$opt_autovivify,
magic => \$opt_magic,
);
my %async_signals = map { $_ => 1 } # 5.14 ops which do PERL_ASYNC_CHECK
qw(wait waitpid nextstate and cond_expr unstack or subst dorassign);
$async_signals{$_} = 1 for # more 5.16 ops which do PERL_ASYNC_CHECK
qw(substcont next redo goto leavewhen);
# perl patchlevel to generate code for (defaults to current patchlevel)
my $patchlevel = int( 0.5 + 1000 * ( $] - 5 ) ); # XXX unused?
my $MULTI = $Config{usemultiplicity};
my $ITHREADS = $Config{useithreads};
my $PERL510 = ( $] >= 5.009005 );
my $PERL512 = ( $] >= 5.011 );
my $SVt_PVLV = $PERL510 ? 10 : 9;
my $SVt_PVAV = $PERL510 ? 11 : 10;
# use sub qw(CXt_LOOP_PLAIN CXt_LOOP);
if ($PERL512) {
sub CXt_LOOP_PLAIN {5} # CXt_LOOP_FOR CXt_LOOP_LAZYSV CXt_LOOP_LAZYIV
} else {
sub CXt_LOOP {3}
}
sub CxTYPE_no_LOOP {
$PERL512
? ( $_[0]->{type} < 4 or $_[0]->{type} > 7 )
: $_[0]->{type} != 3
}
if ($PERL510) {
sub SVs_RMG {0x00800000}
} else {
sub SVs_RMG {0x8000}
}
# Could rewrite push_runtime() and output_runtime() to use a
# temporary file if memory is at a premium.
my $ppname; # name of current fake PP function
my $runtime_list_ref;
my $declare_ref; # Hash ref keyed by C variable type of declarations.
my @pp_list; # list of [$ppname, $runtime_list_ref, $declare_ref]
# tuples to be written out.
my ( $init, $decl );
sub init_hash {
map { $_ => 1 } @_;
}
#
# Initialise the hashes for the default PP functions where we can avoid
# either stack save/restore,write_back_stack, write_back_lexicals or invalidate_lexicals.
# XXX We should really take some of this info from Opcodes (was: CORE opcode.pl)
#
# no args and no return value = Opcodes::argnum 0
%no_stack = init_hash qw(pp_unstack pp_break pp_continue);
# pp_enter pp_leave, use/change global stack.
#skip write_back_stack (no args)
%skip_stack = init_hash qw(pp_enter pp_leave pp_nextstate pp_dbstate);
# which ops do not read pad vars
%skip_lexicals = init_hash qw(pp_enter pp_enterloop pp_leave pp_nextstate pp_dbstate);
# which ops no not write to pad vars
%skip_invalidate = init_hash qw(pp_enter pp_enterloop pp_leave pp_nextstate pp_dbstate
pp_return pp_leavesub pp_list pp_pushmark
pp_anonlist
);
%need_curcop = init_hash qw(pp_rv2gv pp_bless pp_repeat pp_sort pp_caller
pp_reset pp_rv2cv pp_entereval pp_require pp_dofile
pp_entertry pp_enterloop pp_enteriter pp_entersub pp_entergiven
pp_enter pp_method);
%ignore_op = init_hash qw(pp_scalar pp_regcmaybe pp_lineseq pp_scope pp_null);
{ # block necessary for caller to work
my $caller = caller;
if ( $caller eq 'O' ) {
require XSLoader;
XSLoader::load('B::C'); # for r-magic only
}
}
sub debug {
if ( $debug{runtime} ) {
# TODO: fix COP to callers line number
warn(@_) if $verbose;
}
else {
my @tmp = @_;
runtime( map { chomp; "/* $_ */" } @tmp );
}
}
sub declare {
my ( $type, $var ) = @_;
push( @{ $declare_ref->{$type} }, $var );
}
sub push_runtime {
push( @$runtime_list_ref, @_ );
warn join( "\n", @_ ) . "\n" if $debug{runtime};
}
sub save_runtime {
push( @pp_list, [ $ppname, $runtime_list_ref, $declare_ref ] );
}
sub output_runtime {
my $ppdata;
print qq(\n#include "cc_runtime.h"\n);
# CC coverage: 12, 32
# Perls >=5.8.9 have a broken PP_ENTERTRY. See PERL_FLEXIBLE_EXCEPTIONS in cop.h
# Fixed in CORE with 5.11.4
print'
#undef PP_ENTERTRY
#define PP_ENTERTRY(label) \
STMT_START { \
dJMPENV; \
int ret; \
JMPENV_PUSH(ret); \
switch (ret) { \
case 1: JMPENV_POP; JMPENV_JUMP(1);\
case 2: JMPENV_POP; JMPENV_JUMP(2);\
case 3: JMPENV_POP; SPAGAIN; goto label;\
} \
} STMT_END'
if $entertry_defined and $] < 5.011004;
# XXX need to find out when PERL_FLEXIBLE_EXCEPTIONS were actually active.
# 5.6.2 not, 5.8.9 not. coverage 32
# test 12. Used by entereval + dofile
if ($PERL510 or $MULTI) {
# Threads error Bug#55302: too few arguments to function
# CALLRUNOPS()=>CALLRUNOPS(aTHX)
# fixed with 5.11.4
print '
#undef PP_EVAL
#define PP_EVAL(ppaddr, nxt) do { \
dJMPENV; \
int ret; \
PUTBACK; \
JMPENV_PUSH(ret); \
switch (ret) { \
case 0: \
PL_op = ppaddr(aTHX); \\';
if ($PERL510) {
# pp_leaveeval sets: retop = cx->blk_eval.retop
print '
cxstack[cxstack_ix].blk_eval.retop = Nullop; \\';
} else {
# up to 5.8 pp_entereval did set the retstack to next.
# nullify that so that we can now exec the rest of this bblock.
# (nextstate .. leaveeval)
print '
PL_retstack[PL_retstack_ix - 1] = Nullop; \\';
}
print '
if (PL_op != nxt) CALLRUNOPS(aTHX); \
JMPENV_POP; \
break; \
case 1: JMPENV_POP; JMPENV_JUMP(1); \
case 2: JMPENV_POP; JMPENV_JUMP(2); \
case 3: \
JMPENV_POP; \
if (PL_restartop && PL_restartop != nxt) \
JMPENV_JUMP(3); \
} \
PL_op = nxt; \
SPAGAIN; \
} while (0)
';
}
# Perl_vivify_ref not exported on MSWin32
# coverage: 18
if ($PERL510 and $^O eq 'MSWin32') {
# CC coverage: 18, 29
print << '__EOV' if $vivify_ref_defined;
/* Code to take a scalar and ready it to hold a reference */
# ifndef SVt_RV
# define SVt_RV SVt_IV
# endif
# define prepare_SV_for_RV(sv) \
STMT_START { \
if (SvTYPE(sv) < SVt_RV) \
sv_upgrade(sv, SVt_RV); \
else if (SvPVX_const(sv)) { \
SvPV_free(sv); \
SvLEN_set(sv, 0); \
SvCUR_set(sv, 0); \
} \
} STMT_END
#if (PERL_VERSION > 15) || ((PERL_VERSION == 15) && (PERL_SUBVERSION >= 2))
SV*
#else
void
#endif
Perl_vivify_ref(pTHX_ SV *sv, U32 to_what)
{
SvGETMAGIC(sv);
if (!SvOK(sv)) {
if (SvREADONLY(sv))
Perl_croak(aTHX_ "%s", PL_no_modify);
prepare_SV_for_RV(sv);
switch (to_what) {
case OPpDEREF_SV:
SvRV_set(sv, newSV(0));
break;
case OPpDEREF_AV:
SvRV_set(sv, newAV());
break;
case OPpDEREF_HV:
SvRV_set(sv, newHV());
break;
}
SvROK_on(sv);
SvSETMAGIC(sv);
}
}
__EOV
}
print '
OP *Perl_pp_aelem_nolval(aTHX);
#ifndef SVfARG
# define SVfARG(x) (void *)x
#endif
#ifndef MUTABLE_AV
# define MUTABLE_AV(av) av
#endif
PP(pp_aelem_nolval)
{
dSP;
SV** svp;
SV* const elemsv = POPs;
IV elem = SvIV(elemsv);
AV *const av = MUTABLE_AV(POPs);
SV *sv;
#if PERL_VERSION > 6
if (SvROK(elemsv) && !SvGAMAGIC(elemsv) && ckWARN(WARN_MISC))
Perl_warner(aTHX_ packWARN(WARN_MISC),
"Use of reference \"%"SVf"\" as array index",
SVfARG(elemsv));
#endif
if (SvTYPE(av) != SVt_PVAV) RETPUSHUNDEF;
svp = av_fetch(av, elem, 0);
sv = (svp ? *svp : &PL_sv_undef);
if (SvRMAGICAL(av) && SvGMAGICAL(sv)) mg_get(sv);
PUSHs(sv);
RETURN;
}
' if 0;
foreach $ppdata (@pp_list) {
my ( $name, $runtime, $declare ) = @$ppdata;
print "\nstatic\nCCPP($name)\n{\n";
my ( $type, $varlist, $line );
while ( ( $type, $varlist ) = each %$declare ) {
print "\t$type ", join( ", ", @$varlist ), ";\n";
}
foreach $line (@$runtime) {
print $line, "\n";
}
print "}\n";
}
}
sub runtime {
my $line;
foreach $line (@_) {
push_runtime("\t$line");
}
}
sub init_pp {
$ppname = shift;
$runtime_list_ref = [];
$declare_ref = {};
runtime("dSP;");
declare( "I32", "oldsave" );
map { declare( "SV", "*$_" ) } qw(sv src dst left right);
declare( "MAGIC", "*mg" );
$decl->add( "#undef cxinc", "#define cxinc() Perl_cxinc(aTHX)")
if $] < 5.011001 and $inline_ops;
declare( "PERL_CONTEXT", "*cx" );
declare( "I32", "gimme");
$decl->add("static OP * $ppname (pTHX);");
debug "init_pp: $ppname\n" if $debug{queue};
}
# Initialise runtime_callback function for Stackobj class
BEGIN { B::Stackobj::set_callback( \&runtime ) }
=head2 cc_queue
Creates a new ccpp optree.
Initialised by saveoptree_callback in L<B::C>, replaces B::C::walk_and_save_optree.
Called by every C<CV::save> if ROOT.
B<blocksort> also creates its block closure with cc_queue.
=cut
# coverage: test 18, 28 (fixed with B-C-1.30 r971)
sub cc_queue {
my ( $name, $root, $start, @pl ) = @_;
debug "cc_queue: name $name, root $root, start $start, padlist (@pl)\n"
if $debug{queue};
if ( $name eq "*ignore*" or $name =~ /^pp_sub_.*(FETCH|MODIFY)_SCALAR_ATTRIBUTES$/) {
$name = '';
} else {
push( @cc_todo, [ $name, $root, $start, ( @pl ? @pl : @padlist ) ] );
}
my $fakeop = B::FAKEOP->new( "next" => 0, sibling => 0, ppaddr => $name,
targ=>0, type=>0, flags=>0, private=>0);
$start = $fakeop->save;
debug "cc_queue: name $name returns $start\n" if $debug{queue};
return $start;
}
BEGIN { B::C::set_callback( \&cc_queue ) }
sub valid_int { $_[0]->{flags} & VALID_INT }
sub valid_double { $_[0]->{flags} & VALID_DOUBLE }
sub valid_numeric { $_[0]->{flags} & ( VALID_INT | VALID_DOUBLE ) }
sub valid_sv { $_[0]->{flags} & VALID_SV }
sub top_int { @stack ? $stack[-1]->as_int : "TOPi" }
sub top_double { @stack ? $stack[-1]->as_double : "TOPn" }
sub top_numeric { @stack ? $stack[-1]->as_numeric : "TOPn" }
sub top_sv { @stack ? $stack[-1]->as_sv : "TOPs" }
sub top_bool { @stack ? $stack[-1]->as_bool : "SvTRUE(TOPs)" }
sub pop_int { @stack ? ( pop @stack )->as_int : "POPi" }
sub pop_double { @stack ? ( pop @stack )->as_double : "POPn" }
sub pop_numeric { @stack ? ( pop @stack )->as_numeric : "POPn" }
sub pop_sv { @stack ? ( pop @stack )->as_sv : "POPs" }
sub pop_bool {
if (@stack) {
return ( ( pop @stack )->as_bool );
}
else {
# Careful: POPs has an auto-decrement and SvTRUE evaluates
# its argument more than once.
runtime("sv = POPs;");
return "SvTRUE(sv)";
}
}
sub write_back_lexicals {
my $avoid = shift || 0;
debug "write_back_lexicals($avoid) called from @{[(caller(1))[3]]}\n"
if $debug{shadow};
my $lex;
foreach $lex (@pad) {
next unless ref($lex);
$lex->write_back unless $lex->{flags} & $avoid;
}
}
=head1 save_or_restore_lexical_state
The compiler tracks state of lexical variables in @pad to generate optimised
code. But multiple execution paths lead to the entry point of a basic block.
The state of the first execution path is saved and all other execution
paths are restored to the state of the first one.
Missing flags are regenerated by loading values.
Added flags must are removed; otherwise the compiler would be too optimistic,
hence generating code which doesn't match state of the other execution paths.
=cut
sub save_or_restore_lexical_state {
my $bblock = shift;
unless ( exists $lexstate{$bblock} ) {
foreach my $lex (@pad) {
next unless ref($lex);
${ $lexstate{$bblock} }{ $lex->{iv} } = $lex->{flags};
}
}
else {
foreach my $lex (@pad) {
next unless ref($lex);
my $old_flags = ${ $lexstate{$bblock} }{ $lex->{iv} };
next if ( $old_flags eq $lex->{flags} );
my $changed = $old_flags ^ $lex->{flags};
if ( $changed & VALID_SV ) {
( $old_flags & VALID_SV ) ? $lex->write_back : $lex->invalidate;
}
if ( $changed & VALID_DOUBLE ) {
( $old_flags & VALID_DOUBLE ) ? $lex->load_double : $lex->invalidate_double;
}
if ( $changed & VALID_INT ) {
( $old_flags & VALID_INT ) ? $lex->load_int : $lex->invalidate_int;
}
}
}
}
sub write_back_stack {
debug "write_back_stack() ".scalar(@stack)." called from @{[(caller(1))[3]]}\n"
if $debug{shadow};
return unless @stack;
runtime( sprintf( "EXTEND(sp, %d);", scalar(@stack) ) );
foreach my $obj (@stack) {
runtime( sprintf( "PUSHs((SV*)%s);", $obj->as_sv ) );
}
@stack = ();
}
sub invalidate_lexicals {
my $avoid = shift || 0;
debug "invalidate_lexicals($avoid) called from @{[(caller(1))[3]]}\n"
if $debug{shadow};
my $lex;
foreach $lex (@pad) {
next unless ref($lex);
$lex->invalidate unless $lex->{flags} & $avoid;
}
}
sub reload_lexicals {
my $lex;
foreach $lex (@pad) {
next unless ref($lex);
my $type = $lex->{type};
if ( $type == T_INT ) {
$lex->as_int;
}
elsif ( $type == T_DOUBLE ) {
$lex->as_double;
}
else {
$lex->as_sv;
}
}
}
{
package B::Pseudoreg;
#
# This class allocates pseudo-registers (OK, so they're C variables).
#
my %alloc; # Keyed by variable name. A value of 1 means the
# variable has been declared. A value of 2 means
# it's in use.
sub new_scope { %alloc = () }
sub new ($$$) {
my ( $class, $type, $prefix ) = @_;
my ( $ptr, $i, $varname, $status, $obj );
$prefix =~ s/^(\**)//;
$ptr = $1;
$i = 0;
do {
$varname = "$prefix$i";
$status = exists $alloc{$varname} ? $alloc{$varname} : 0;
} while $status == 2;
if ( $status != 1 ) {
# Not declared yet
B::CC::declare( $type, "$ptr$varname" );
$alloc{$varname} = 2; # declared and in use
}
$obj = bless \$varname, $class;
return $obj;
}
sub DESTROY {
my $obj = shift;
$alloc{$$obj} = 1; # no longer in use but still declared
}
}
{
package B::Shadow;
#
# This class gives a standard API for a perl object to shadow a
# C variable and only generate reloads/write-backs when necessary.
#
# Use $obj->load($foo) instead of runtime("shadowed_c_var = foo").
# Use $obj->write_back whenever shadowed_c_var needs to be up to date.
# Use $obj->invalidate whenever an unknown function may have
# set shadow itself.
sub new {
my ( $class, $write_back ) = @_;
# Object fields are perl shadow variable, validity flag
# (for *C* variable) and callback sub for write_back
# (passed perl shadow variable as argument).
bless [ undef, 1, $write_back ], $class;
}
sub load {
my ( $obj, $newval ) = @_;
$obj->[1] = 0; # C variable no longer valid
$obj->[0] = $newval;
}
sub value {
return $_[0]->[0];
}
sub write_back {
my $obj = shift;
if ( !( $obj->[1] ) ) {
$obj->[1] = 1; # C variable will now be valid
&{ $obj->[2] }( $obj->[0] );
}
}
sub invalidate { $_[0]->[1] = 0 } # force C variable to be invalid
}
my $curcop = B::Shadow->new(
sub {
my $op = shift;
my $opsym = $op->save;
runtime("PL_curcop = (COP*)$opsym;");
}
);
#
# Context stack shadowing. Mimics stuff in pp_ctl.c, cop.h and so on.
#
sub dopoptoloop {
my $cxix = $#cxstack;
while ( $cxix >= 0 && CxTYPE_no_LOOP( $cxstack[$cxix] ) ) {
$cxix--;
}
debug "dopoptoloop: returning $cxix" if $debug{cxstack};
return $cxix;
}
sub dopoptolabel {
my $label = shift;
my $cxix = $#cxstack;
while (
$cxix >= 0
&& ( CxTYPE_no_LOOP( $cxstack[$cxix] )
|| $cxstack[$cxix]->{label} ne $label )
)
{
$cxix--;
}
debug "dopoptolabel: returning $cxix\n" if $debug{cxstack};
if ($cxix < 0 and $debug{cxstack}) {
for my $cx (0 .. $#cxstack) {
debug "$cx: ",$cxstack[$cx]->{label},"\n";
}
for my $op (keys %{$labels->{label}}) {
debug $labels->{label}->{$op},"\n";
}
}
return $cxix;
}
sub push_label {
my $op = shift;
my $type = shift;
push @{$labels->{$type}}, ( $op );
}
sub pop_label {
my $type = shift;
my $op = pop @{$labels->{$type}};
write_label ($op); # avoids duplicate labels
}
sub error {
my $format = shift;
my $file = $curcop->[0]->file;
my $line = $curcop->[0]->line;
$errors++;
if (@_) {
warn sprintf( "ERROR at %s:%d: $format\n", $file, $line, @_ );
}
else {
warn sprintf( "ERROR at %s:%d: %s\n", $file, $line, $format );
}
}
# run-time eval is too late for attrs being checked by perlcore. BEGIN does not help.
# use types is the right approach. But until types is fixed we use this hack.
# Note that we also need a new CHECK_SCALAR_ATTRIBUTES hook, starting with v5.18.
sub init_type_attrs {
eval q[
our $valid_attr = '^(int|double|string|unsigned|register|temporary|ro|readonly|const)$';
sub MODIFY_SCALAR_ATTRIBUTES {
my $pkg = shift;
my $v = shift;
my $attr = $B::CC::valid_attr;
$attr =~ s/\b$pkg\b//;
if (my @bad = grep !/$attr/, @_) {
return @bad;
} else {
no strict 'refs';
push @{"$pkg\::$v\::attributes"}, @_; # create a magic glob
return ();
}
}
sub FETCH_SCALAR_ATTRIBUTES {
my ($pkg, $v) = @_;
no strict 'refs';
return @{"$pkg\::$v\::attributes"};
}
# pollute our callers namespace for attributes to be accepted with -MB::CC
*main::MODIFY_SCALAR_ATTRIBUTES = \&B::CC::MODIFY_SCALAR_ATTRIBUTES;
*main::FETCH_SCALAR_ATTRIBUTES = \&B::CC::FETCH_SCALAR_ATTRIBUTES;
# my int $i : register : ro;
*int::MODIFY_SCALAR_ATTRIBUTES = \&B::CC::MODIFY_SCALAR_ATTRIBUTES;
*int::FETCH_SCALAR_ATTRIBUTES = \&B::CC::FETCH_SCALAR_ATTRIBUTES;
# my double $d : ro;
*double::MODIFY_SCALAR_ATTRIBUTES = \&B::CC::MODIFY_SCALAR_ATTRIBUTES;
*double::FETCH_SCALAR_ATTRIBUTES = \&B::CC::FETCH_SCALAR_ATTRIBUTES;
*string::MODIFY_SCALAR_ATTRIBUTES = \&B::CC::MODIFY_SCALAR_ATTRIBUTES;
*string::FETCH_SCALAR_ATTRIBUTES = \&B::CC::FETCH_SCALAR_ATTRIBUTES;