optimize XSUBs to use targets if the -nooptimize xsubpp option is
[p5sagit/p5-mst-13.2.git] / lib / ExtUtils / xsubpp
index 774ba79..ff9b452 100755 (executable)
@@ -6,10 +6,12 @@ xsubpp - compiler to convert Perl XS code into C code
 
 =head1 SYNOPSIS
 
-B<xsubpp> [B<-v>] [B<-C++>] [B<-except>] [B<-s pattern>] [B<-prototypes>] [B<-noversioncheck>] [B<-nolinenumbers>] [B<-typemap typemap>] [B<-object_capi>]... file.xs
+B<xsubpp> [B<-v>] [B<-C++>] [B<-except>] [B<-s pattern>] [B<-prototypes>] [B<-noversioncheck>] [B<-nolinenumbers>] [B<-nooptimize>] [B<-typemap typemap>] ... file.xs
 
 =head1 DESCRIPTION
 
+This compiler is typically run by the makefiles created by L<ExtUtils::MakeMaker>.
+
 I<xsubpp> will compile XS code into C code by embedding the constructs
 necessary to let C functions manipulate Perl values and creates the glue
 necessary to let Perl access those functions.  The compiler uses typemaps to
@@ -23,13 +25,15 @@ typemap taking precedence.
 
 =head1 OPTIONS
 
+Note that the C<XSOPT> MakeMaker option may be used to add these options to
+any makefiles generated by MakeMaker.
+
 =over 5
 
 =item B<-C++>
 
 Adds ``extern "C"'' to the C code.
 
-
 =item B<-except>
 
 Adds exception handling stubs to the C code.
@@ -59,11 +63,14 @@ number.
 
 Prevents the inclusion of `#line' directives in the output.
 
-=item B<-object_capi>
+=item B<-nooptimize>
 
-Compile code as C in a PERL_OBJECT environment.
+Disables certain optimizations.  The only optimization that is currently
+affected is the use of I<target>s by the output C code (see L<perlguts>).
+This may significantly slow down the generated code, but this is the way
+B<xsubpp> of 5.005 and earlier operated.
 
-back
+=back
 
 =head1 ENVIRONMENT
 
@@ -86,6 +93,7 @@ perl(1), perlxs(1), perlxstut(1)
 require 5.002;
 use Cwd;
 use vars '$cplusplus';
+use vars '%v';
 
 use Config;
 
@@ -106,7 +114,7 @@ if ($^O eq 'VMS') {
 
 $FH = 'File0000' ;
 
-$usage = "Usage: xsubpp [-v] [-C++] [-except] [-prototypes] [-noversioncheck] [-nolinenumbers] [-s pattern] [-typemap typemap]... file.xs\n";
+$usage = "Usage: xsubpp [-v] [-C++] [-except] [-prototypes] [-noversioncheck] [-nolinenumbers] [-nooptimize] [-s pattern] [-typemap typemap]... file.xs\n";
 
 $proto_re = "[" . quotemeta('\$%&*@;') . "]" ;
 # mjn
@@ -117,6 +125,7 @@ $WantPrototypes = -1 ;
 $WantVersionChk = 1 ;
 $ProtoUsed = 0 ;
 $WantLineNumbers = 1 ;
+$WantOptimize = 1 ;
 SWITCH: while (@ARGV and $ARGV[0] =~ /^-./) {
     $flag = shift @ARGV;
     $flag =~ s/^-// ;
@@ -126,12 +135,15 @@ SWITCH: while (@ARGV and $ARGV[0] =~ /^-./) {
     $WantPrototypes = 1, next SWITCH   if $flag eq 'prototypes';
     $WantVersionChk = 0, next SWITCH   if $flag eq 'noversioncheck';
     $WantVersionChk = 1, next SWITCH   if $flag eq 'versioncheck';
+    # XXX left this in for compat
     $WantCAPI = 1, next SWITCH    if $flag eq 'object_capi';
     $except = " TRY",  next SWITCH     if $flag eq 'except';
     push(@tm,shift),   next SWITCH     if $flag eq 'typemap';
     $WantLineNumbers = 0, next SWITCH  if $flag eq 'nolinenumbers';
     $WantLineNumbers = 1, next SWITCH  if $flag eq 'linenumbers';
-    (print "xsubpp version $XSUBPP_version\n"), exit   
+    $WantOptimize = 0, next SWITCH     if $flag eq 'nooptimize';
+    $WantOptimize = 1, next SWITCH     if $flag eq 'optimize';
+    (print "xsubpp version $XSUBPP_version\n"), exit
        if $flag eq 'v';
     die $usage;
 }
@@ -237,6 +249,24 @@ foreach $key (keys %input_expr) {
     $input_expr{$key} =~ s/\n+$//;
 }
 
+$bal = qr[(?:(?>[^()]+)|\((?p{ $bal })\))*];   # ()-balanced
+$cast = qr[(?:\(\s*SV\s*\*\s*\)\s*)?];         # Optional (SV*) cast
+$size = qr[,\s* (?p{ $bal }) ]x;               # Third arg (to setpvn)
+
+foreach $key (keys %output_expr) {
+    use re 'eval';
+
+    my ($t, $with_size, $arg, $sarg) =
+      ($output_expr{$key} =~
+        m[^ \s+ sv_set ( [iunp] ) v (n)?       # Type, is_setpvn
+            \s* \( \s* $cast \$arg \s* ,
+            \s* ( (?p{ $bal }) )               # Set from
+            ( (?p{ $size }) )?                 # Possible sizeof set-from
+            \) \s* ; \s* $
+         ]x);
+    $targetable{$key} = [$t, $with_size, $arg, $sarg] if $t;
+}
+
 $END = "!End!\n\n";            # "impossible" keyword (multiple newline)
 
 # Match an XS keyword
@@ -351,11 +381,11 @@ sub INPUT_handler {
        my $line = $_ ;
 
        # remove trailing semicolon if no initialisation
-       s/\s*;$//g unless /=/ ;
+       s/\s*;$//g unless /[=;+].*\S/ ;
 
        # check for optional initialisation code
        my $var_init = '' ;
-       $var_init = $1 if s/\s*(=.*)$//s ;
+       $var_init = $1 if s/\s*([=;+].*)$//s ;
        $var_init =~ s/"/\\"/g;
 
        s/\s+/ /g;
@@ -369,7 +399,17 @@ sub INPUT_handler {
        $thisdone |= $var_name eq "THIS";
        $retvaldone |= $var_name eq "RETVAL";
        $var_types{$var_name} = $var_type;
-       print "\t" . &map_type($var_type);
+       # XXXX This check is a safeguard against the unfinished conversion of
+       # generate_init().  When generate_init() is fixed,
+       # one can use 2-args map_type() unconditionally.
+       if ($var_type =~ / \( \s* \* \s* \) /x) {
+         # Function pointers are not yet supported with &output_init!
+         print "\t" . &map_type($var_type, $var_name);
+         $name_printed = 1;
+       } else {
+         print "\t" . &map_type($var_type);
+         $name_printed = 0;
+       }
        $var_num = $args_match{$var_name};
 
         $proto_arg[$var_num] = ProtoString($var_type) 
@@ -378,13 +418,17 @@ sub INPUT_handler {
            $var_addr{$var_name} = 1;
            $func_args =~ s/\b($var_name)\b/&$1/;
        }
-       if ($var_init =~ /^=\s*NO_INIT\s*;?\s*$/) {
+       if ($var_init =~ /^[=;]\s*NO_INIT\s*;?\s*$/) {
+         if ($name_printed) {
+           print ";\n";
+         } else {
            print "\t$var_name;\n";
+         }
        } elsif ($var_init =~ /\S/) {
-           &output_init($var_type, $var_num, "$var_name $var_init");
+           &output_init($var_type, $var_num, $var_name, $var_init, $name_printed);
        } elsif ($var_num) {
            # generate initialization code
-           &generate_init($var_type, $var_num, $var_name);
+           &generate_init($var_type, $var_num, $var_name, $name_printed);
        } else {
            print ";\n";
        }
@@ -775,7 +819,7 @@ while (<$FH>) {
        /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
 
     if ($OBJ) {
-        s/#if(?:def|\s+defined)\s+(\(__cplusplus\)|__cplusplus)/#if defined(__cplusplus) && !defined(PERL_OBJECT)/;
+        s/#if(?:def\s|\s+defined)\s*(\(__cplusplus\)|__cplusplus)/#if defined(__cplusplus) && !defined(PERL_OBJECT)/;
     }
     print $_;
 }
@@ -1023,12 +1067,12 @@ EOF
     if ($ALIAS) 
       { print Q<<"EOF" if $cond }
 #    if ($cond)
-#       croak("Usage: %s($orig_args)", GvNAME(CvGV(cv)));
+#       Perl_croak(aTHX_ "Usage: %s($orig_args)", GvNAME(CvGV(cv)));
 EOF
     else 
       { print Q<<"EOF" if $cond }
 #    if ($cond)
-#      croak("Usage: $pname($orig_args)");
+#      Perl_croak(aTHX_ "Usage: $pname($orig_args)");
 EOF
 
     print Q<<"EOF" if $PPCODE;
@@ -1079,14 +1123,16 @@ EOF
 
        # do code
        if (/^\s*NOT_IMPLEMENTED_YET/) {
-               print "\n\tcroak(\"$pname: not implemented yet\");\n";
+               print "\n\tPerl_croak(aTHX_ \"$pname: not implemented yet\");\n";
                $_ = '' ;
        } else {
                if ($ret_type ne "void") {
-                       print "\t" . &map_type($ret_type) . "\tRETVAL;\n"
+                       print "\t" . &map_type($ret_type, 'RETVAL') . ";\n"
                                if !$retvaldone;
                        $args_match{"RETVAL"} = 0;
                        $var_types{"RETVAL"} = $ret_type;
+                       print "\tdXSTARG;\n"
+                               if $WantOptimize and $targetable{$type_kind{$ret_type}};
                }
 
                print $deferred;
@@ -1139,8 +1185,32 @@ EOF
        if ($gotRETVAL && $RETVAL_code) {
            print "\t$RETVAL_code\n";
        } elsif ($gotRETVAL || $wantRETVAL) {
-           # RETVAL almost never needs SvSETMAGIC()
-           &generate_output($ret_type, 0, 'RETVAL', 0);
+           my $t = $WantOptimize && $targetable{$type_kind{$ret_type}};
+           my $var = 'RETVAL';
+           my $type = $ret_type;
+
+           # 0: type, 1: with_size, 2: how, 3: how_size
+           if ($t and not $t->[1] and $t->[0] eq 'p') {
+               # PUSHp corresponds to setpvn.  Treate setpv directly
+               my $what = eval qq("$t->[2]");
+               warn $@ if $@;
+
+               print "\tsv_setpv(TARG, $what); XSprePUSH; PUSHTARG;\n";
+           }
+           elsif ($t) {
+               my $what = eval qq("$t->[2]");
+               warn $@ if $@;
+
+               my $size = $t->[3];
+               $size = '' unless defined $size;
+               $size = eval qq("$size");
+               warn $@ if $@;
+               print "\tXSprePUSH; PUSH$t->[0]($what$size);\n";
+           }
+           else {
+               # RETVAL almost never needs SvSETMAGIC()
+               &generate_output($ret_type, 0, 'RETVAL', 0);
+           }
        }
 
        # do cleanup
@@ -1175,7 +1245,7 @@ EOF
 
     print Q<<EOF if $except;
 #    if (errbuf[0])
-#      croak(errbuf);
+#      Perl_croak(aTHX_ errbuf);
 EOF
 
     if ($ret_type ne "void" or $EXPLICIT_RETURN) {
@@ -1253,30 +1323,23 @@ EOF
 }
 
 # print initialization routine
-if ($WantCAPI) {
+
 print Q<<"EOF";
-#
 ##ifdef __cplusplus
 #extern "C"
 ##endif
-#XS(boot__CAPI_entry)
-#[[
-#    dXSARGS;
-#    char* file = __FILE__;
-#
 EOF
-} else {
+
 print Q<<"EOF";
-##ifdef __cplusplus
-#extern "C"
-##endif
 #XS(boot_$Module_cname)
+EOF
+
+print Q<<"EOF";
 #[[
 #    dXSARGS;
 #    char* file = __FILE__;
 #
 EOF
-}
 
 print Q<<"EOF" if $WantVersionChk ;
 #    XS_VERSION_BOOTCHECK ;
@@ -1304,39 +1367,40 @@ if (@BootCode)
 }
 
 print Q<<"EOF";;
-#    ST(0) = &sv_yes;
-#    XSRETURN(1);
+#    XSRETURN_YES;
 #]]
 #
 EOF
 
-if ($WantCAPI) { 
-print Q<<"EOF";
-#
-##define XSCAPI(name) void name(CV* cv, void* pPerl)
-#
-##ifdef __cplusplus
-#extern "C"
-##endif
-#XSCAPI(boot_$Module_cname)
-#[[
-#    SetCPerlObj(pPerl);
-#    boot__CAPI_entry(cv);
-#]]
-#
-EOF
-}
-
 warn("Please specify prototyping behavior for $filename (see perlxs manual)\n") 
     unless $ProtoUsed ;
 &Exit;
 
-
 sub output_init {
-    local($type, $num, $init) = @_;
+    local($type, $num, $var, $init, $name_printed) = @_;
     local($arg) = "ST(" . ($num - 1) . ")";
 
-    eval qq/print " $init\\\n"/;
+    if(  $init =~ /^=/  ) {
+        if ($name_printed) {
+         eval qq/print " $init\\n"/;
+       } else {
+         eval qq/print "\\t$var $init\\n"/;
+       }
+       warn $@   if  $@;
+    } else {
+       if(  $init =~ s/^\+//  &&  $num  ) {
+           &generate_init($type, $num, $var, $name_printed);
+       } elsif ($name_printed) {
+           print ";\n";
+           $init =~ s/^;//;
+       } else {
+           eval qq/print "\\t$var;\\n"/;
+           warn $@   if  $@;
+           $init =~ s/^;//;
+       }
+       $deferred .= eval qq/"\\n\\t$init\\n"/;
+       warn $@   if  $@;
+    }
 }
 
 sub Warn
@@ -1397,13 +1461,28 @@ sub generate_init {
     if (defined($defaults{$var})) {
            $expr =~ s/(\t+)/$1    /g;
            $expr =~ s/        /\t/g;
-           eval qq/print "\\t$var;\\n"/;
+           if ($name_printed) {
+             print ";\n";
+           } else {
+             eval qq/print "\\t$var;\\n"/;
+             warn $@   if  $@;
+           }
            $deferred .= eval qq/"\\n\\tif (items < $num)\\n\\t    $var = $defaults{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
+           warn $@   if  $@;
     } elsif ($ScopeThisXSUB or $expr !~ /^\t\$var =/) {
-           eval qq/print "\\t$var;\\n"/;
+           if ($name_printed) {
+             print ";\n";
+           } else {
+             eval qq/print "\\t$var;\\n"/;
+             warn $@   if  $@;
+           }
            $deferred .= eval qq/"\\n$expr;\\n"/;
+           warn $@   if  $@;
     } else {
+           die "panic: do not know how to handle this branch for function pointers"
+             if $name_printed;
            eval qq/print "$expr;\\n"/;
+           warn $@   if  $@;
     }
 }
 
@@ -1415,7 +1494,7 @@ sub generate_output {
 
     $type = TidyType($type) ;
     if ($type =~ /^array\(([^,]*),(.*)\)/) {
-           print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1)), XFree((char *)$var);\n";
+           print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1));\n";
            print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
     } else {
            blurt("Error: '$type' not in typemap"), return
@@ -1438,6 +1517,7 @@ sub generate_output {
                $subexpr =~ s/\n\t/\n\t\t/g;
                $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
                eval "print qq\a$expr\a";
+               warn $@   if  $@;
                print "\t\tSvSETMAGIC(ST(ix_$var));\n" if $do_setmagic;
            }
            elsif ($var eq 'RETVAL') {
@@ -1445,6 +1525,7 @@ sub generate_output {
                    # We expect that $arg has refcnt 1, so we need to
                    # mortalize it.
                    eval "print qq\a$expr\a";
+                   warn $@   if  $@;
                    print "\tsv_2mortal(ST(0));\n";
                    print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
                }
@@ -1452,6 +1533,7 @@ sub generate_output {
                    # We expect that $arg has refcnt >=1, so we need
                    # to mortalize it!
                    eval "print qq\a$expr\a";
+                   warn $@   if  $@;
                    print "\tsv_2mortal(ST(0));\n";
                    print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
                }
@@ -1462,21 +1544,30 @@ sub generate_output {
                    # works too.
                    print "\tST(0) = sv_newmortal();\n";
                    eval "print qq\a$expr\a";
+                   warn $@   if  $@;
                    # new mortals don't have set magic
                }
            }
            elsif ($arg =~ /^ST\(\d+\)$/) {
                eval "print qq\a$expr\a";
+               warn $@   if  $@;
                print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
            }
     }
 }
 
 sub map_type {
-    my($type) = @_;
+    my($type, $varname) = @_;
 
     $type =~ tr/:/_/;
     $type =~ s/^array\(([^,]*),(.*)\).*/$1 */s;
+    if ($varname) {
+      if ($varname && $type =~ / \( \s* \* (?= \s* \) ) /xg) {
+       (substr $type, pos $type, 0) = " $varname ";
+      } else {
+       $type .= "\t$varname";
+      }
+    }
     $type;
 }