Compare commits

..

2 Commits

Author SHA1 Message Date
fur%netscape.com
1c43d4984f This is a copy of regalloc_code2_BRANCH from Netscape's private repository,
as it existed in January of 1998.


git-svn-id: svn://10.0.0.236/branches/regalloc_code2_BRANCH@22571 18797224-902f-48f8-a5cc-f745e15eee43
1999-03-02 16:12:08 +00:00
(no author)
cfe021ff88 This commit was manufactured by cvs2svn to create branch
'regalloc_code2_BRANCH'.

git-svn-id: svn://10.0.0.236/branches/regalloc_code2_BRANCH@22567 18797224-902f-48f8-a5cc-f745e15eee43
1999-03-02 15:57:58 +00:00
53 changed files with 5324 additions and 9122 deletions

View File

@@ -1,80 +0,0 @@
#!perl
#
# The contents of this file are subject to the Netscape Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
# Simon Fraser <sfraser@netscape.com>
#
require 5.004;
use strict;
use Cwd;
use Moz::BuildUtils;
use Moz::BuildCore;
#-------------------------------------------------------------
# Where have the build options gone?
#
# The various build flags have been centralized into one place.
# The master list of options is in MozBuildFlags.txt. However,
# you should never need to edit that file, or this one.
#
# To customize what gets built, or where to start the build,
# edit the $prefs_file_name file in
# System Folder:Preferences:Mozilla build prefs:
# Documentation is provided in that file.
#-------------------------------------------------------------
my($prefs_file_name) = "Mozilla opt build prefs";
my($config_header_file_name) = ":mozilla:config:mac:DefinesOptions.h";
#-------------------------------------------------------------
# hashes to hold build options
#-------------------------------------------------------------
my(%build);
my(%options);
my(%filepaths);
my(%optiondefines);
# Hash of input files for this build. Eventually, there will be
# input files for manifests, and projects too.
my(%inputfiles) = (
"buildflags", "MozillaBuildFlags.txt",
"checkoutdata", "MozillaCheckoutList.txt",
"buildprogress", "¥ Mozilla opt progress",
"buildmodule", "MozillaBuildList.pm",
"checkouttime", "Mozilla last checkout"
);
#-------------------------------------------------------------
# end build hashes
#-------------------------------------------------------------
# set the build root directory, which is the the dir above mozilla
SetupBuildRootDir(":mozilla:build:mac:build_scripts");
# Set up all the flags on $main::, like DEBUG, CARBON etc.
# Override the defaults using the preferences files.
SetupDefaultBuildOptions(0, ":mozilla:dist:viewer:", $config_header_file_name);
my($do_checkout) = 0;
my($do_build) = 1;
RunBuild($do_checkout, $do_build, \%inputfiles, $prefs_file_name);

View File

@@ -1,80 +0,0 @@
#!perl
#
# The contents of this file are subject to the Netscape Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
# Simon Fraser <sfraser@netscape.com>
#
require 5.004;
use strict;
use Cwd;
use Moz::BuildUtils;
use Moz::BuildCore;
#-------------------------------------------------------------
# Where have the build options gone?
#
# The various build flags have been centralized into one place.
# The master list of options is in MozBuildFlags.txt. However,
# you should never need to edit that file, or this one.
#
# To customize what gets built, or where to start the build,
# edit the $prefs_file_name file in
# System Folder:Preferences:Mozilla build prefs:
# Documentation is provided in that file.
#-------------------------------------------------------------
my($prefs_file_name) = "Mozilla debug build prefs";
my($config_header_file_name) = ":mozilla:config:mac:DefinesOptionsDebug.h";
#-------------------------------------------------------------
# hashes to hold build options
#-------------------------------------------------------------
my(%build);
my(%options);
my(%filepaths);
my(%optiondefines);
# Hash of input files for this build. Eventually, there will be
# input files for manifests, and projects too.
my(%inputfiles) = (
"buildflags", "MozillaBuildFlags.txt",
"checkoutdata", "MozillaCheckoutList.txt",
"buildprogress", "¥ Mozilla debug progress",
"buildmodule", "MozillaBuildList.pm",
"checkouttime", "Mozilla last checkout"
);
#-------------------------------------------------------------
# end build hashes
#-------------------------------------------------------------
# set the build root directory, which is the the dir above mozilla
SetupBuildRootDir(":mozilla:build:mac:build_scripts");
# Set up all the flags on $main::, like DEBUG, CARBON etc.
# Override the defaults using the preferences files.
SetupDefaultBuildOptions(1, ":mozilla:dist:viewer_debug:", $config_header_file_name);
my($do_pull) = 0; # overridden by flags and prefs
my($do_build) = 1;
RunBuild($do_pull, $do_build, \%inputfiles, $prefs_file_name);

View File

@@ -1,595 +0,0 @@
#!perl -w
package Moz::BuildCore;
require 5.004;
require Exporter;
use strict;
use vars qw( @ISA @EXPORT );
# perl includes
use Cwd;
use POSIX;
use Time::Local;
use File::Basename;
use LWP::Simple;
# homegrown
use Moz::Moz;
use Moz::Jar;
use Moz::BuildFlags;
use Moz::BuildUtils;
use Moz::CodeWarriorLib;
# use MozillaBuildList; # eventually, this should go away, and be replaced by data input
@ISA = qw(Exporter);
@EXPORT = qw(
RunBuild
);
#//--------------------------------------------------------------------------------------------------
#// DoPrebuildCheck
#//
#// Check the build tools etc before running the build.
#//--------------------------------------------------------------------------------------------------
sub DoPrebuildCheck()
{
SanityCheckBuildOptions();
# launch codewarrior and persist its location. Have to call this before first
# call to getCodeWarriorPath().
my($ide_path_file) = $main::filepaths{"idepath"};
$ide_path_file = full_path_to($ide_path_file);
LaunchCodeWarrior($ide_path_file);
}
#//--------------------------------------------------------------------------------------------------
#// SanityCheckBuildOptions
#//--------------------------------------------------------------------------------------------------
sub SanityCheckBuildOptions()
{
my($bad_options) = 0;
# Jar options
if (!$main::options{chrome_jars} && !$main::options{chrome_files})
{
print "Warning: Both \$options{chrome_jars} and \$options{chrome_files} are off. You won't get any chrome.\n";
$bad_options = 1;
}
if (!$main::options{chrome_jars} && $main::options{use_jars})
{
print "Warning: \$options{chrome_jars} is off but \$options{use_jars} is on. Your build won't run (expects jars, got files).\n";
$bad_options = 1;
}
if (!$main::options{chrome_files} && !$main::options{use_jars})
{
print "Warning: \$options{chrome_jars} is off but \$options{chrome_files} is on. Your build won't run (expects files, got jars).\n";
$bad_options = 1;
}
if ($main::options{ldap_experimental} && !$main::options{ldap})
{
print "Warning: \$options{ldap_experimental} is on but \$options{ldap} is off. LDAP experimental features will not be built.\n";
$bad_options = 1;
}
if ($main::options{wsp} && !$main::options{xmlextras})
{
print "Warning: \$options{wsp} is on but \$options{xmlextras} is off. wsp will not be built.\n";
$bad_options = 1;
}
if ($bad_options) {
print "Build will start in 5 seconds. Press command-. to stop\n";
DelayFor(5);
}
}
#//--------------------------------------------------------------------------------------------------
#// GenBuildSystemInfo
#//--------------------------------------------------------------------------------------------------
sub GenBuildSystemInfo()
{
# always rebuild the configuration program.
BuildProjectClean(":mozilla:build:mac:tools:BuildSystemInfo:BuildSystemInfo.mcp", "BuildSystemInfo");
# delete the configuration file.
unlink(":mozilla:build:mac:BuildSystemInfo.pm");
# run the program.
system(":mozilla:build:mac:BuildSystemInfo");
# wait for the file to be created.
while (!(-e ":mozilla:build:mac:BuildSystemInfo.pm")) { WaitNextEvent(); }
# wait for BuildSystemInfo to finish, so that we see correct results.
while (IsProcessRunning("BuildSystemInfo")) { WaitNextEvent(); }
# now, evaluate the contents of the file.
open(F, ":mozilla:build:mac:BuildSystemInfo.pm");
while (<F>) { eval; }
close(F);
}
#//--------------------------------------------------------------------------------------------------
#// Make library aliases
#//--------------------------------------------------------------------------------------------------
sub MakeLibAliases()
{
my($dist_dir) = GetBinDirectory();
#// ProfilerLib
if ($main::PROFILE)
{
my($profilerlibpath) = Moz::CodeWarriorLib::getCodeWarriorPath("MacOS Support:Profiler:Profiler Common:ProfilerLib");
MakeAlias("$profilerlibpath", "$dist_dir"."Essential Files:");
}
}
#//--------------------------------------------------------------------------------------------------
#// ConfigureBuildSystem
#//
#// defines some build-system configuration variables.
#//--------------------------------------------------------------------------------------------------
sub ConfigureBuildSystem()
{
#// In the future, we may want to do configurations based on the actual build system itself.
#// GenBuildSystemInfo();
#// For now, if we discover a newer header file than existed in Universal Interfaces 3.2,
#// we'll assume that 3.3 or later is in use.
my($universal_interfaces) = Moz::CodeWarriorLib::getCodeWarriorPath("MacOS Support:Universal:Interfaces:CIncludes:");
if (-e ($universal_interfaces . "ControlDefinitions.h")) {
$main::UNIVERSAL_INTERFACES_VERSION = 0x0330;
}
#// Rename IC SDK folder in the Mac OS Support folder
my($ic_sdk_folder) = Moz::CodeWarriorLib::getCodeWarriorPath("MacOS Support:ICProgKit2.0.2");
if( -e $ic_sdk_folder)
{
my($new_ic_folder_name) = Moz::CodeWarriorLib::getCodeWarriorPath("MacOS Support:(ICProgKit2.0.2)");
rename ($ic_sdk_folder, $new_ic_folder_name);
# note that CodeWarrior doesn't descend into folders with () the name
print "Mozilla no longer needs the Internet Config SDK to build:\n Renaming the 'ICProgKit2.0.2' folder to '(ICProgKit2.0.2)'\n";
}
printf("UNIVERSAL_INTERFACES_VERSION = 0x%04X\n", $main::UNIVERSAL_INTERFACES_VERSION);
# alias required CodeWarrior libs into the Essential Files folder (only the Profiler lib now)
MakeLibAliases();
}
#//--------------------------------------------------------------------------------------------------
#// CheckOutModule. Takes variable number of args; first two are required
#//--------------------------------------------------------------------------------------------------
sub CheckOutModule($$$$)
{
my($session, $module, $revision, $date) = @_;
my($result) = $session->checkout($module, $revision, $date);
# result of 1 is success
if ($result) { return; }
my($checkout_err) = $session->getLastError();
if ($checkout_err == 708) {
die "Error: Checkout was cancelled.\n";
} elsif ($checkout_err == 911) {
die "Error: CVS session settings are incorrect. Check your password, and the CVS root settings.\n";
} elsif ($checkout_err == 703) {
die "Error: CVS checkout failed. Unknown module, unknown tag, bad username, or other CVS error.\n";
} elsif ($checkout_err == 711) {
print "Checkout of '$module' failed.\n";
}
}
#//--------------------------------------------------------------------------------------------------
#// getScriptFolder
#//--------------------------------------------------------------------------------------------------
sub getScriptFolder()
{
return dirname($0);
}
#//--------------------------------------------------------------------------------------------------
#// getScriptFolder
#//--------------------------------------------------------------------------------------------------
sub get_url_contents($)
{
my($url) = @_;
my($url_contents) = LWP::Simple::get($url);
$url_contents =~ s/\r\n/\n/g; # normalize linebreaks
$url_contents =~ s/\r/\n/g; # normalize linebreaks
return $url_contents;
}
#//--------------------------------------------------------------------------------------------------
#// get_files_from_content
#//--------------------------------------------------------------------------------------------------
sub uniq
{
my $lastval;
grep(($_ ne $lastval, $lastval = $_)[$[], @_);
}
#//--------------------------------------------------------------------------------------------------
#// get_files_from_content
#//--------------------------------------------------------------------------------------------------
sub get_files_from_content($)
{
my($content) = @_;
my(@jscalls) = grep (/return js_file_menu[^{]*/, split(/\n/, $content));
my $i;
for ($i = 0; $i < @jscalls ; $i++)
{
$jscalls[$i] =~ s/.*\(|\).*//g;
my(@callparams) = split(/,/, $jscalls[$i]);
my ($repos, $dir, $file, $rev) = grep(s/['\s]//g, @callparams);
$jscalls[$i] = "$dir/$file";
}
&uniq(sort(@jscalls));
}
#//--------------------------------------------------------------------------------------------------
#// getLastUpdateTime
#//
#// Get the last time we updated. Return 0 on failure
#//--------------------------------------------------------------------------------------------------
sub getLastUpdateTime($)
{
my($timestamp_file) = @_;
my($time_string);
local(*TIMESTAMP_FILE);
unless (open(TIMESTAMP_FILE, "< $timestamp_file")) { return 0; }
while (<TIMESTAMP_FILE>)
{
my($line) = $_;
chomp($line);
# ignore comments and empty lines
if ($line =~ /^\#/ || $line =~ /^\s*$/) {
next;
}
$time_string = $line;
}
# get the epoch seconds
my($last_update_secs) = $time_string;
$last_update_secs =~ s/\s#.+$//;
print "FAST_UPDATE found that you last updated at ".localtime($last_update_secs)."\n";
# how long ago was this, in hours?
my($gm_now) = time();
my($update_hours) = 1 + ceil(($gm_now - $last_update_secs) / (60 * 60));
return $update_hours;
}
#//--------------------------------------------------------------------------------------------------
#// saveCheckoutTimestamp
#//
#// Create a file on disk containing the current time. Param is time(), which is an Epoch seconds
#// (and therefore in GMT).
#//
#//--------------------------------------------------------------------------------------------------
sub saveCheckoutTimestamp($$)
{
my($gm_secs, $timestamp_file) = @_;
local(*TIMESTAMP_FILE);
open(TIMESTAMP_FILE, ">$timestamp_file") || die "Failed to open $timestamp_file\n";
print(TIMESTAMP_FILE "# time of last checkout or update, in GMT. Used by FAST_UPDATE\n");
print(TIMESTAMP_FILE "$gm_secs \# around ".localtime()." local time\n");
close(TIMESTAMP_FILE);
}
#//--------------------------------------------------------------------------------------------------
#// FastUpdate
#//
#// Use Bonsai url data to update only those dirs which have new files
#//
#//--------------------------------------------------------------------------------------------------
sub FastUpdate($$)
{
my($modules, $timestamp_file) = @_; # list of modules to check out
my($num_hours) = getLastUpdateTime($timestamp_file);
if ($num_hours == 0 || $num_hours > 170) {
print "Can't fast_update; last update was too long ago, or never. Doing normal checkout.\n";
return 0;
}
print "Doing fast update, pulling files changed in the last $num_hours hours\n";
my($cvsfile) = AskAndPersistFile($main::filepaths{"sessionpath"});
my($session) = Moz::MacCVS->new( $cvsfile );
unless (defined($session)) { die "Error: Checkout aborted. Cannot create session file: $session" }
# activate MacCVS
ActivateApplication('Mcvs');
my($checkout_start_time) = time();
#print "Time now is $checkout_start_time ($checkout_start_time + 0)\n";
my($this_co);
foreach $this_co (@$modules)
{
my($module, $revision, $date) = ($this_co->[0], $this_co->[1], $this_co->[2]);
# assume that things pulled by date wont change
if ($date ne "") {
print "$module is pulled by date, so ignoring in FastUpdate.\n";
next;
}
my($search_type) = "hours";
my($min_date) = "";
my($max_date) = "";
my($url) = "http://bonsai.mozilla.org/cvsquery.cgi?treeid=default&module=${module}&branch=${revision}&branchtype=match&dir=&file=&filetype=match&who=&whotype=match&sortby=Date&hours=${num_hours}&date=${search_type}&mindate=${min_date}&maxdate=${max_date}&cvsroot=%2Fcvsroot";
if ($revision eq "") {
print "Getting list of checkins to $module from Bonsai...\n";
} else {
print "Getting list of checkins to $module on branch $revision from Bonsai...\n";
}
my(@files) = &get_files_from_content(&get_url_contents($url));
if ($#files > 0)
{
my(@cvs_co_list);
my($co_file);
foreach $co_file (@files)
{
print "Updating $co_file\n";
push(@cvs_co_list, $co_file);
}
my($result) = $session->update($revision, \@cvs_co_list);
# result of 1 is success
if (!$result) { die "Error: Fast update failed\n"; }
} else {
print "No files in this module changed\n";
}
}
saveCheckoutTimestamp($checkout_start_time, $timestamp_file);
return 1;
}
#//--------------------------------------------------------------------------------------------------
#// Checkout
#//--------------------------------------------------------------------------------------------------
sub CheckoutModules($$$)
{
my($modules, $pull_date, $timestamp_file) = @_; # list of modules to check out
my($start_time) = TimeStart();
# assertRightDirectory();
my($cvsfile) = AskAndPersistFile($main::filepaths{"sessionpath"});
my($session) = Moz::MacCVS->new( $cvsfile );
unless (defined($session)) { die "Error: Checkout aborted. Cannot create session file: $session" }
my($checkout_start_time) = time();
# activate MacCVS
ActivateApplication('Mcvs');
my($this_co);
foreach $this_co (@$modules)
{
my($module, $revision, $date) = ($this_co->[0], $this_co->[1], $this_co->[2]);
if ($date eq "") {
$date = $pull_date;
}
CheckOutModule($session, $module, $revision, $date);
# print "Checking out $module with ref $revision, date $date\n";
}
saveCheckoutTimestamp($checkout_start_time, $timestamp_file);
TimeEnd($start_time, "Checkout");
}
#//--------------------------------------------------------------------------------------------------
#// ReadCheckoutModulesFile
#//--------------------------------------------------------------------------------------------------
sub ReadCheckoutModulesFile($$)
{
my($modules_file, $co_list) = @_;
my($checkout_file) = getScriptFolder().":".$modules_file;
local(*CHECKOUT_FILE);
open(CHECKOUT_FILE, "< $checkout_file") || die "Error: failed to open checkout list $checkout_file\n";
while (<CHECKOUT_FILE>)
{
my($line) = $_;
chomp($line);
# ignore comments and empty lines
if ($line =~ /^\#/ || $line =~ /^\s*$/) {
next;
}
my(@cvs_co) = ["", "", ""];
my($module, $revision, $date) = (0, 1, 2);
if ($line =~ /\s*([^#,\s]+)\s*\,\s*([^#,\s]+)\s*\,\s*([^#]+)/)
{
@cvs_co[$module] = $1;
@cvs_co[$revision] = $2;
@cvs_co[$date] = $3;
}
elsif ($line =~ /\s*([^#,\s]+)\s*\,\s*([^#,\s]+)\s*(#.+)?/)
{
@cvs_co[$module] = $1;
@cvs_co[$revision] = $2;
}
elsif ($line =~ /\s*([^#,\s]+)\s*\,\s*,\s*([^#,]+)/)
{
@cvs_co[$module] = $1;
@cvs_co[$date] = $2;
}
elsif ($line =~ /\s*([^#,\s]+)/)
{
@cvs_co[$module] = $1;
}
else
{
die "Error: unrecognized line '$line' in $modules_file\n";
}
# strip surrounding space from date
@cvs_co[$date] =~ s/^\s*|\s*$//g;
# print "Going to check out '@cvs_co[$module]', '@cvs_co[$revision]', '@cvs_co[$date]'\n";
push(@$co_list, \@cvs_co);
}
close(CHECKOUT_FILE);
}
#//--------------------------------------------------------------------------------------------------
#// PullFromCVS
#//--------------------------------------------------------------------------------------------------
sub PullFromCVS($$)
{
unless ( $main::build{pull} ) { return; }
my($modules_file, $timestamp_file) = @_;
StartBuildModule("pull");
my(@cvs_co_list);
ReadCheckoutModulesFile($modules_file, \@cvs_co_list);
if ($main::FAST_UPDATE && $main::options{pull_by_date})
{
die "Error: you can't use FAST_UPDATE if you are pulling by date.\n";
}
my($did_fast_update) = $main::FAST_UPDATE && FastUpdate(\@cvs_co_list, $timestamp_file);
if (!$did_fast_update)
{
my($pull_date) = "";
if ($main::options{pull_by_date})
{
# acceptable CVS date formats are (in local time):
# ISO8601 (e.g. "1972-09-24 20:05") and Internet (e.g. "24 Sep 1972 20:05").
# Perl's localtime() string format also seems to work.
$pull_date = localtime().""; # force string interp.
print "Pulling by date $pull_date\n";
}
CheckoutModules(\@cvs_co_list, $pull_date, $timestamp_file);
}
EndBuildModule("pull");
}
#//--------------------------------------------------------------------------------------------------
#// RunBuild
#//--------------------------------------------------------------------------------------------------
sub RunBuild($$$$)
{
my($do_pull, $do_build, $input_files, $build_prefs) = @_;
InitBuildProgress($input_files->{"buildprogress"});
# if we are pulling, we probably want to do a full build, so clear the build progress
if ($do_pull) {
ClearBuildProgress();
}
# read local prefs, and the build progress file, and set flags to say what to build
SetupBuildParams(\%main::build,
\%main::options,
\%main::optiondefines,
\%main::filepaths,
$input_files->{"buildflags"},
$build_prefs);
# If we were told to pull, make sure we do, overriding prefs etc.
if ($do_pull)
{
$main::build{"pull"} = 1;
}
# transfer this flag
$CodeWarriorLib::CLOSE_PROJECTS_FIRST = $main::CLOSE_PROJECTS_FIRST;
# setup the build log
SetupBuildLog($main::filepaths{"buildlogfilepath"}, $main::USE_TIMESTAMPED_LOGS);
StopForErrors();
if ($main::LOG_TO_FILE) {
RedirectOutputToFile($main::filepaths{"scriptlogfilepath"});
}
# run a pre-build check to see that the tools etc are in order
DoPrebuildCheck();
# do the pull
PullFromCVS($input_files->{"checkoutdata"}, $input_files->{"checkouttime"});
unless ($do_build) { return; }
my($build_start) = TimeStart();
# check the build environment
ConfigureBuildSystem();
# here we load and call methods in the build module indirectly.
# we have to use indirection because the build module can be named
# differently for different builds.
chdir(dirname($0)); # change to the script dir
my($build_module) = $input_files->{"buildmodule"};
# load the build module
require $build_module;
{ # scope for no strict 'refs'
no strict 'refs';
my($package_name) = $build_module;
$package_name =~ s/\.pm$//;
chdir($main::MOZ_SRC);
&{$package_name."::BuildDist"}();
chdir($main::MOZ_SRC);
&{$package_name."::BuildProjects"}();
}
# the build finished, so clear the build progress state
ClearBuildProgress();
TimeEnd($build_start, "Build");
print "Build complete\n";
}
1;

View File

@@ -1,425 +0,0 @@
#!perl -w
package Moz::BuildFlags;
require 5.004;
require Exporter;
# Package that attempts to read a file from the Preferences folder,
# and get build settings out of it
use strict;
use Exporter;
use Cwd;
use File::Basename;
use Moz::Moz;
use Moz::Prefs;
use vars qw(@ISA @EXPORT);
@ISA = qw(Exporter);
@EXPORT = qw(
SetupBuildParams
InitBuildProgress
WriteBuildProgress
ClearBuildProgress
ReadBuildProgress
);
my(@build_flags);
my(@options_flags);
my(@filepath_flags);
my(%arrays_list) = (
"build_flags", \@build_flags,
"options_flags", \@options_flags,
"filepath_flags", \@filepath_flags
);
my($progress_file) = "¥ÊBuild progress";
#-------------------------------------------------------------------------------
# appendArrayFlag
#
# Set a flag in the array
#-------------------------------------------------------------------------------
sub appendArrayFlag(@)
{
my($array_name) = shift;
my($setting) = shift;
my($value) = shift;
my(@optional_values);
foreach (@_) {
push(@optional_values, $_);
}
my(@this_flag) = [$setting, $value, @optional_values];
my($flags_array) = $arrays_list{$array_name};
if ($flags_array)
{
push(@{$flags_array}, @this_flag) || die "Failed to append\n";
}
else
{
die "Error: unknown build flags array $array_name\n";
}
}
#-------------------------------------------------------------------------------
# readFlagsFile
#
# Read the file of build flags from disk. File path is relative to the
# script directory.
#-------------------------------------------------------------------------------
sub readFlagsFile($)
{
my($flags_file) = @_;
my($file_path) = $0;
$file_path =~ s/[^:]+$/$flags_file/;
print "Reading build flags from '$file_path'\n";
local(*FLAGS_FILE);
open(FLAGS_FILE, "< $file_path") || die "Error: failed to open flags file $file_path\n";
my($cur_array) = "";
while(<FLAGS_FILE>)
{
my($line) = $_;
chomp($line);
# ignore comments and empty lines
if ($line =~ /^\#/ || $line =~ /^\s*$/) {
next;
}
# 1-word line, probably array name
if ($line =~ /^([^#\s]+)\s*$/)
{
$cur_array = $1;
next;
}
elsif ($line =~ /^([^#\s]+)\s+\"(.+)\"(\s+#.+)?$/) # quoted option, possible comment
{
my($flag) = $1;
my($setting) = $2;
appendArrayFlag($cur_array, $flag, $setting);
}
elsif ($line =~ /^([^#\s]+)((\s+[^#\s]+)+)(\s+#.+)?$/) # multiple word line, possible comment
{
my($flag) = $1;
appendArrayFlag($cur_array, $flag, split(' ', $2));
}
else
{
die "Error: unknown build flag at '$line'\n";
}
}
close(FLAGS_FILE);
}
#-------------------------------------------------------------------------------
# flagsArrayToHash
#
# Utility routine to migrate flag from a 2D array to a hash, where
# item[n][0] is the hash entry name, and item[n][1] is the hash entry value.
#-------------------------------------------------------------------------------
sub flagsArrayToHash($$)
{
my($src_array, $dest_hash) = @_;
my($item);
foreach $item (@$src_array)
{
$dest_hash->{$item->[0]} = $item->[1];
}
}
#-----------------------------------------------
# printHash
#
# Utility routine to print a hash
#-----------------------------------------------
sub printHash($)
{
my($hash_ref) = @_;
print "Printing hash:\n";
my($key, $value);
while (($key, $value) = each (%$hash_ref))
{
print " $key $value\n";
}
}
#-----------------------------------------------
# printBuildArray
#
# Utility routine to print a 2D array
#-----------------------------------------------
sub printBuildArray($)
{
my($build_array) = @_;
my($entry);
foreach $entry (@$build_array)
{
print "$entry->[0] = $entry->[1]\n";
}
}
#-------------------------------------------------------------------------------
# SetBuildFlags
#-------------------------------------------------------------------------------
sub SetBuildFlags($)
{
my($build) = @_;
flagsArrayToHash(\@build_flags, $build);
}
#-------------------------------------------------------------------------------
# SetBuildOptions
#-------------------------------------------------------------------------------
sub SetBuildOptions($)
{
my($options) = @_;
flagsArrayToHash(\@options_flags, $options);
}
#-------------------------------------------------------------------------------
# SetFilepathFlags
#-------------------------------------------------------------------------------
sub SetFilepathFlags($)
{
my($filepath) = @_;
flagsArrayToHash(\@filepath_flags, $filepath);
}
#-------------------------------------------------------------------------------
# SetOptionDefines
#-------------------------------------------------------------------------------
sub SetOptionDefines($)
{
my($optiondefines) = @_;
foreach my $entry (@options_flags)
{
if (defined($entry->[2])) {
$optiondefines->{$entry->[0]}{$entry->[2]} = 1;
}
}
}
#-------------------------------------------------------------------------------
# PropagateAllFlags
#-------------------------------------------------------------------------------
sub PropagateAllFlags($)
{
my($build_array) = @_;
# if "all" is set, set all the flags to 1
unless ($build_array->[0][0] eq "all") { die "Error: 'all' must come first in the flags array\n"; }
if ($build_array->[0][1] == 1)
{
my($index);
foreach $index (@$build_array)
{
$index->[1] = 1;
}
}
}
#//--------------------------------------------------------------------------------------------------
#// _getBuildProgressFile
#//--------------------------------------------------------------------------------------------------
sub _getBuildProgressFile()
{
return $progress_file;
}
#//--------------------------------------------------------------------------------------------------
#// setBuildProgressStart
#//
#// This automagically sets $build{"all"} to 0
#//--------------------------------------------------------------------------------------------------
sub setBuildProgressStart($$)
{
my($build_array, $name) = @_;
my($index);
foreach $index (@$build_array)
{
$index->[1] = 0;
if ($index->[0] eq $name) {
last;
}
}
print "Building from module after $name, as specified by build progress\n";
}
#//--------------------------------------------------------------------------------------------------
#// InitBuildProgress
#//--------------------------------------------------------------------------------------------------
sub InitBuildProgress($)
{
my($prog_file) = @_;
if ($prog_file ne "") {
$progress_file = full_path_to($prog_file);
print "Writing build progress to $progress_file\n";
}
}
#//--------------------------------------------------------------------------------------------------
#// WriteBuildProgress
#//--------------------------------------------------------------------------------------------------
sub WriteBuildProgress($)
{
my($module_built) = @_;
my($progress_file) = _getBuildProgressFile();
if ($progress_file ne "")
{
open(PROGRESS_FILE, ">>$progress_file") || die "Failed to open $progress_file\n";
print(PROGRESS_FILE "$module_built\n");
close(PROGRESS_FILE);
}
}
#//--------------------------------------------------------------------------------------------------
#// ClearBuildProgress
#//--------------------------------------------------------------------------------------------------
sub ClearBuildProgress()
{
my($progress_file) = _getBuildProgressFile();
if ($progress_file ne "") {
unlink $progress_file;
}
}
#//--------------------------------------------------------------------------------------------------
#// WipeBuildProgress
#//--------------------------------------------------------------------------------------------------
sub WipeBuildProgress()
{
print "Ignoring build progress\n";
ClearBuildProgress();
$progress_file = "";
}
#//--------------------------------------------------------------------------------------------------
#// ReadBuildProgress
#//--------------------------------------------------------------------------------------------------
sub ReadBuildProgress($)
{
my($build_array) = @_;
my($progress_file) = _getBuildProgressFile();
my($last_module);
if (open(PROGRESS_FILE, "< $progress_file"))
{
print "Getting build progress from $progress_file\n";
while (<PROGRESS_FILE>)
{
my($line) = $_;
chomp($line);
$last_module = $line;
}
close(PROGRESS_FILE);
}
if ($last_module)
{
setBuildProgressStart($build_array, $last_module);
}
}
#-------------------------------------------------------------------------------
# clearOldBuildSettings
#-------------------------------------------------------------------------------
sub clearOldBuildSettings($$$$)
{
my($build, $options, $optiondefines, $filepaths) = @_;
# empty the arrays in case we're being called twice
@build_flags = ();
@options_flags = ();
@filepath_flags = ();
# and empty the hashes
%$build = ();
%$options = ();
%$optiondefines = ();
%$filepaths = ();
}
#-------------------------------------------------------------------------------
# SetupBuildParams
#-------------------------------------------------------------------------------
sub SetupBuildParams($$$$$$)
{
my($build, $options, $optiondefines, $filepaths, $flags_file, $prefs_file) = @_;
# Empty the hashes and arrays, to wipe out any stale data.
# Needed because these structures persist across two build scripts
# called using 'do' from a parent script.
clearOldBuildSettings($build, $options, $optiondefines, $filepaths);
# Read from the flags file, which sets up the various arrays
readFlagsFile($flags_file);
# If 'all' is set in the build array, propagate that to all entries
PropagateAllFlags(\@build_flags);
# read the user pref file, that can change values in the array
ReadMozUserPrefs($prefs_file, \@build_flags, \@options_flags, \@filepath_flags);
# If build progress exists, this clears flags in the array up to a certain point
if ($main::USE_BUILD_PROGRESS) {
ReadBuildProgress(\@build_flags);
} else {
WipeBuildProgress();
}
# printBuildArray(\@build_flags);
# printBuildArray(\@options_flags);
SetBuildFlags($build);
SetBuildOptions($options);
SetOptionDefines($optiondefines);
SetFilepathFlags($filepaths);
# printHash($build);
# printHash($options);
}
1;

View File

@@ -1,786 +0,0 @@
package Moz::BuildUtils;
require 5.004;
require Exporter;
# Package that contains build util functions specific to the Mozilla build
# process.
use strict;
use Exporter;
use Cwd;
use File::Path;
use File::Basename;
use Mac::Events;
use Mac::StandardFile;
use Moz::Moz;
use Moz::BuildFlags;
use Moz::MacCVS;
#use Moz::ProjectXML; #optional; required for static build only
use vars qw(@ISA @EXPORT);
@ISA = qw(Exporter);
@EXPORT = qw(
SetupDefaultBuildOptions
SetupBuildRootDir
StartBuildModule
EndBuildModule
GetBinDirectory
BuildOneProjectWithOutput
BuildOneProject
BuildProject
BuildProjectClean
BuildIDLProject
BuildFolderResourceAliases
AskAndPersistFile
DelayFor
TimeStart
TimeEnd
EmptyTree
SetupBuildLog
SetBuildNumber
SetTimeBomb
UpdateConfigHeader
);
#//--------------------------------------------------------------------------------------------------
#// SetupDefaultBuildOptions
#//--------------------------------------------------------------------------------------------------
sub SetupDefaultBuildOptions($$$)
{
my($debug, $bin_dir, $config_header_file_name) = @_;
# Here we set up defaults for the various build flags.
# If you want to override any of these, it's best to do
# so via the relevant preferences file, which lives in
# System Folder:Preferences:Mozilla build prefs:{build prefs file}.
# For the name of the prefs file, see the .pl script that you
# run to start this build. The prefs files are created when
# you run the build, and contain some documentation.
#-------------------------------------------------------------
# configuration variables that globally affect what is built
#-------------------------------------------------------------
$main::DEBUG = $debug;
$main::PROFILE = 0;
$main::RUNTIME = 0; # turn on to just build runtime support and NSPR projects
$main::GC_LEAK_DETECTOR = 0; # turn on to use GC leak detection
$main::MOZILLA_OFFICIAL = 0; # generate build number
$main::LOG_TO_FILE = 0; # write perl output to a file
#-------------------------------------------------------------
# configuration variables that affect the manner of building,
# but possibly affecting the outcome.
#-------------------------------------------------------------
$main::ALIAS_SYM_FILES = $main::DEBUG;
$main::CLOBBER_LIBS = 1; # turn on to clobber existing libs and .xSYM files before
# building each project
# The following two options will delete all dist files (if you have $main::build{dist} turned on),
# but leave the directory structure intact.
$main::CLOBBER_DIST_ALL = 1; # turn on to clobber all aliases/files inside dist (headers/xsym/libs)
$main::CLOBBER_DIST_LIBS = 0; # turn on to clobber only aliases/files for libraries/sym files in dist
$main::CLOBBER_IDL_PROJECTS = 0; # turn on to clobber all IDL projects.
$main::CLOBBER_PROJECTS = 0; # turn on to remove object code from each project before building it
$main::UNIVERSAL_INTERFACES_VERSION = 0x0320;
#-------------------------------------------------------------
# configuration variables that are preferences for the build,
# style and do not affect what is built.
#-------------------------------------------------------------
$main::CLOSE_PROJECTS_FIRST = 0;
# 1 = close then make (for development),
# 0 = make then close (for tinderbox).
$main::USE_TIMESTAMPED_LOGS = 0;
$main::USE_BUILD_PROGRESS = 1; # track build progress for restartable builds
#-------------------------------------------------------------
# END OF CONFIG SWITCHES
#-------------------------------------------------------------
$main::BIN_DIRECTORY = $bin_dir;
$main::DEFINESOPTIONS_FILE = $config_header_file_name;
}
#//--------------------------------------------------------------------------------------------------
#// SetupBuildRootDir
#//--------------------------------------------------------------------------------------------------
sub SetupBuildRootDir($)
{
my($rel_path_to_script) = @_;
my($cur_dir) = cwd();
$cur_dir =~ s/$rel_path_to_script$//;
chdir($cur_dir) || die "Error: failed to set build root directory to '$cur_dir'.\nYou probably need to put 'mozilla' one level down (in a folder).\n";
$main::MOZ_SRC = cwd();
}
#//--------------------------------------------------------------------------------------------------
#// StartBuildModule
#//--------------------------------------------------------------------------------------------------
sub StartBuildModule($)
{
my($module) = @_;
print("---- Start of $module ----\n");
}
#//--------------------------------------------------------------------------------------------------
#// EndBuildModule
#//--------------------------------------------------------------------------------------------------
sub EndBuildModule($)
{
my($module) = @_;
WriteBuildProgress($module);
print("---- End of $module ----\n");
}
#--------------------------------------------------------------------------------------------------
# GetBinDirectory
#--------------------------------------------------------------------------------------------------
sub GetBinDirectory()
{
if ($main::BIN_DIRECTORY eq "") { die "Dist directory not set\n"; }
return $main::BIN_DIRECTORY;
}
#--------------------------------------------------------------------------------------------------
# AskAndPersistFile stores the information about the user pick inside
# the file $session_storage
#--------------------------------------------------------------------------------------------------
sub AskAndPersistFile($)
{
my ($sessionStorage) = @_;
my $cvsfile;
if (( -e $sessionStorage) &&
open( SESSIONFILE, $sessionStorage ))
{
# Read in the path if available
$cvsfile = <SESSIONFILE>;
chomp $cvsfile;
close SESSIONFILE;
if ( ! -e $cvsfile )
{
print STDERR "$cvsfile has disappeared\n";
undef $cvsfile;
}
}
unless (defined ($cvsfile))
{
# make sure that MacPerl is a front process
ActivateApplication('McPL');
MacPerl::Answer("Could not find your MacCVS session file. Please choose one", "OK");
# prompt user for the file name, and store it
my $macFile = StandardGetFile( 0, "McvD");
if ( $macFile->sfGood() )
{
$cvsfile = $macFile->sfFile();
# save the choice if we can
if ( open (SESSIONFILE, ">" . $sessionStorage))
{
printf SESSIONFILE $cvsfile, "\n";
close SESSIONFILE;
}
else
{
print STDERR "Could not open storage file $sessionStorage for saving $cvsfile\n";
}
}
}
return $cvsfile;
}
#--------------------------------------------------------------------------------------------------
# BuildIDLProject
#
#--------------------------------------------------------------------------------------------------
sub BuildIDLProject($$)
{
my ($project_path, $module_name) = @_;
if ($main::CLOBBER_IDL_PROJECTS)
{
my (@suffix_list) = (".mcp", ".xml");
my ($project_name, $project_dir, $suffix) = fileparse($project_path, @suffix_list);
if ($suffix eq "") { die "Error: Project, $project_path must end in .xml or .mcp\n"; }
my($datafolder_path);
if ($suffix eq ".xml")
{
$datafolder_path = $project_dir . "_" . $project_name . " Data:";
}
else {
$datafolder_path = $project_dir . $project_name . " Data:";
}
print STDERR "Deleting IDL data folder: $datafolder_path\n";
EmptyTree($datafolder_path);
}
BuildOneProject($project_path, "headers", 0, 0, 0);
BuildOneProject($project_path, $module_name.".xpt", 1, 0, 1);
}
#--------------------------------------------------------------------------------------------------
# CreateStaticLibTargets
#
#--------------------------------------------------------------------------------------------------
sub CreateXMLStaticLibTargets($)
{
my($xml_path) = @_;
my (@suffix_list) = (".xml");
my ($project_name, $project_dir, $suffix) = fileparse($xml_path, @suffix_list);
if ($suffix eq "") { die "XML munging: $xml_path must end in .xml\n"; }
#sniff the file to see if we need to fix up broken Pro5-exported XML
print "Parsing $xml_path\n";
my $ide_version = Moz::ProjectXML::SniffProjectXMLIDEVersion($xml_path);
if ($ide_version eq "4.0")
{
my $new_file = $project_dir.$project_name."2.xml";
print "Cleaning up Pro 5 xml to $new_file\n";
Moz::ProjectXML::CleanupPro5XML($xml_path, $new_file);
unlink $xml_path;
rename ($new_file, $xml_path);
}
my $doc = Moz::ProjectXML::ParseXMLDocument($xml_path);
my @target_list = Moz::ProjectXML::GetTargetsList($doc);
my $target;
my %target_hash; # for easy lookups below
foreach $target (@target_list) { $target_hash{$target} = 1; }
foreach $target (@target_list)
{
if ($target =~ /(.+).shlb$/) # if this is a shared lib target
{
my $target_base = $1;
my $static_target = $target_base.".o";
# ensure that this does not exist already
if ($target_hash{$static_target}) {
print "Static target $static_target already exists in project. Not making\n";
next;
}
print "Making static target '$static_target' from target '$target'\n";
Moz::ProjectXML::CloneTarget($doc, $target, $static_target);
Moz::ProjectXML::SetAsStaticLibraryTarget($doc, $static_target, $static_target);
}
}
print "Writing XML file to $xml_path\n";
my $temp_path = $project_dir."_".$project_name.".xml";
Moz::ProjectXML::WriteXMLDocument($doc, $temp_path, $ide_version);
Moz::ProjectXML::DisposeXMLDocument($doc);
if (-e $temp_path)
{
unlink $xml_path;
rename ($temp_path, $xml_path);
}
else
{
die "Error: Failed to add new targets to XML project\n";
}
}
#//--------------------------------------------------------------------------------------------------
#// ProcessProjectXML
#//
#// Helper routine to allow for XML pre-processing. This should read in the XML, process it,
#// and replace the original file with the processed version.
#//--------------------------------------------------------------------------------------------------
sub ProcessProjectXML($)
{
my($xml_path) = @_;
# we need to manually load Moz::ProjectXML, becaues not everyone will have the
# required perl modules in their distro.
my($cur_dir) = cwd();
chdir(dirname($0)); # change to the script dir
eval "require Moz::ProjectXML";
if ($@) { die "Error: could not do Project XML munging because you do not have the correct XML modules installed. Error is:\n################\n $@################"; }
chdir($cur_dir);
CreateXMLStaticLibTargets($xml_path);
}
#//--------------------------------------------------------------------------------------------------
#// Build one project, and make the alias. Parameters are project path, target name, shared library
#// name, make shlb alias (boolean), make xSYM alias (boolean), and is component (boolean).
#//--------------------------------------------------------------------------------------------------
sub BuildOneProjectWithOutput($$$$$$)
{
my ($project_path, $target_name, $output_name, $alias_lib, $alias_xSYM, $component) = @_;
unless ($project_path =~ m/^$main::BUILD_ROOT.+/) { return; }
my (@suffix_list) = (".mcp", ".xml");
my ($project_name, $project_dir, $suffix) = fileparse($project_path, @suffix_list);
if ($suffix eq "") { die "Error: Project, $project_path must end in .xml or .mcp\n"; }
my($dist_dir) = GetBinDirectory();
# Put libraries in "Essential Files" folder, Components in "Components" folder
my($output_dir) = $component ? "Components:" : "Essential Files:";
my($output_path) = $dist_dir.$output_dir;
if ($main::options{static_build})
{
if ($output_name =~ /\.o$/ || $output_name =~ /\.[Ll]ib$/)
{
$alias_xSYM = 0;
$alias_lib = 1;
$output_path = $main::DEBUG ? ":mozilla:dist:static_libs_debug:" : ":mozilla:dist:static_libs:";
}
}
# if the flag is on to export projects to XML, export and munge them
if ($main::EXPORT_PROJECTS && !($project_path =~ /IDL\.mcp$/))
{
my $xml_out_path = $project_path;
$xml_out_path =~ s/\.mcp$/\.xml/;
# only do this if project is newer?
if (! -e $xml_out_path)
{
ExportProjectToXML(full_path_to($project_path), full_path_to($xml_out_path));
ProcessProjectXML($xml_out_path);
}
}
# if the flag is set to use XML projects, default to XML if the file
# is present.
if ($main::USE_XML_PROJECTS && !($project_path =~ /IDL\.mcp$/))
{
my $xml_project_path = $project_dir.$project_name.".xml";
if (-e $xml_project_path)
{
$project_path = $xml_project_path;
$suffix = ".xml";
}
}
if ($suffix eq ".xml")
{
my($xml_path) = $project_path;
# Prepend an "_" onto the name of the generated project file so it doesn't conflict
$project_path = $project_dir . "_" . $project_name . ".mcp";
my($project_modtime) = (-e $project_path ? GetFileModDate($project_path) : 0);
my($xml_modtime) = (-e $xml_path ? GetFileModDate($xml_path) : 0);
if ($xml_modtime > $project_modtime)
{
print("Importing $project_path from $project_name.xml.\n");
unlink($project_path);
# Might want to delete the "xxx.mcp Data" dir ???
ImportXMLProject(full_path_to($xml_path), full_path_to($project_path));
}
}
if ($main::CLOBBER_LIBS)
{
unlink "$project_dir$output_name"; # it's OK if these fail
unlink "$project_dir$output_name.xSYM";
}
DoBuildProject($project_path, $target_name, $main::CLOBBER_PROJECTS);
$alias_lib ? MakeAlias("$project_dir$output_name", "$output_path") : 0;
$alias_xSYM ? MakeAlias("$project_dir$output_name.xSYM", "$output_path") : 0;
}
#//--------------------------------------------------------------------------------------------------
#// For compatiblity with existing scripts, BuildOneProject now just calls
#// BuildOneProjectWithOutput, with the output name and target name identical.
#// Note that this routine assumes that the target name and the shared libary name
#// are the same.
#//--------------------------------------------------------------------------------------------------
sub BuildOneProject($$$$$)
{
my ($project_path, $target_name, $alias_lib, $alias_xSYM, $component) = @_;
BuildOneProjectWithOutput($project_path, $target_name, $target_name,
$alias_lib, $alias_xSYM, $component);
}
#//--------------------------------------------------------------------------------------------------
#// For compatiblity with existing scripts, BuildProject now just calls
#// BuildOneProjectWithOutput, with the output name and target name identical.
#// Note that this routine assumes that the target name and the shared libary name
#// are the same. No aliases of the output are made.
#//--------------------------------------------------------------------------------------------------
sub BuildProject($$)
{
my ($project_path, $target_name) = @_;
BuildOneProjectWithOutput($project_path, $target_name, $target_name, 0, 0, 0);
}
#//--------------------------------------------------------------------------------------------------
#// Identical to BuildProject but clobbers the project before building it.
#//--------------------------------------------------------------------------------------------------
sub BuildProjectClean($$)
{
my ($project_path, $target_name) = @_;
my ($save_clobber_flag) = $main::CLOBBER_PROJECTS;
$main::CLOBBER_PROJECTS = 1;
BuildOneProjectWithOutput($project_path, $target_name, $target_name, 0, 0, 0);
$main::CLOBBER_PROJECTS = $save_clobber_flag;
}
#//--------------------------------------------------------------------------------------------------
#// Make resource aliases for one directory
#//--------------------------------------------------------------------------------------------------
sub BuildFolderResourceAliases($$)
{
my($src_dir, $dest_dir) = @_;
# get a list of all the resource files
opendir(SRCDIR, $src_dir) || die("can't open $src_dir");
my(@resource_files) = readdir(SRCDIR);
closedir(SRCDIR);
# make aliases for each one into the dest directory
print("Placing aliases to all files from $src_dir in $dest_dir\n");
for ( @resource_files )
{
next if $_ eq "CVS";
#print(" Doing $_\n");
if (-l $src_dir.$_)
{
print(" $_ is an alias\n");
next;
}
my($file_name) = $src_dir . $_;
MakeAlias($file_name, $dest_dir);
}
}
#//--------------------------------------------------------------------------------------------------
#// DelayFor
#//
#// Delay for the given number of seconds, allowing the script to be cancelled
#//--------------------------------------------------------------------------------------------------
sub DelayFor($)
{
my($delay_secs) = @_;
STDOUT->autoflush(1);
my($end_time) = time() + $delay_secs;
my($last_time) = 0;
my($cur_time) = time();
while ($cur_time < $end_time)
{
$cur_time = time();
if ($cur_time > $last_time)
{
print ".";
$last_time = $cur_time;
}
WaitNextEvent();
}
print "\n";
STDOUT->autoflush(0);
}
#//--------------------------------------------------------------------------------------------------
#// TimeStart
#//--------------------------------------------------------------------------------------------------
sub TimeStart()
{
return time();
}
#//--------------------------------------------------------------------------------------------------
#// TimeEnd
#//--------------------------------------------------------------------------------------------------
sub TimeEnd($$)
{
use integer;
my($start_time, $operation_name) = @_;
my($end_time) = time();
my($tot_sec) = $end_time - $start_time;
my($seconds) = $tot_sec;
my($hours) = $seconds / (60 * 60);
$seconds -= $hours * (60 * 60);
my($minutes) = $seconds / 60;
$seconds -= $minutes * 60;
print "$operation_name took $hours hours $minutes minutes and $seconds seconds\n";
}
#//--------------------------------------------------------------------------------------------------
#// Remove all files from a tree, leaving directories intact (except "CVS").
#//--------------------------------------------------------------------------------------------------
sub EmptyTree($)
{
my ($root) = @_;
#print "EmptyTree($root)\n";
opendir(DIR, $root);
my $sub;
foreach $sub (readdir(DIR))
{
my $fullpathname = $root.$sub; # -f, -d only work on full paths
# Don't call empty tree for the alias of a directory.
# -d returns true for the alias of a directory, false for a broken alias)
if (-d $fullpathname)
{
if (-l $fullpathname) # delete aliases
{
unlink $fullpathname;
next;
}
EmptyTree($fullpathname.":");
if ($sub eq "CVS")
{
#print "rmdir $fullpathname\n";
rmdir $fullpathname;
}
}
else
{
unless (unlink $fullpathname) { die "Failed to delete $fullpathname\n"; }
}
}
closedir(DIR);
}
#//--------------------------------------------------------------------------------------------------
#// Recurse through a directory hierarchy, looking for MANIFEST files.
#// Currently unused.
#//--------------------------------------------------------------------------------------------------
sub ScanForManifestFiles($$$$)
{
my($dir, $theme_root, $theme_name, $dist_dir) = @_;
opendir(DIR, $dir) or die "Cannot open dir $dir\n";
my @files = readdir(DIR);
closedir DIR;
my $file;
foreach $file (@files)
{
my $filepath = $dir.":".$file;
if (-d $filepath)
{
# print "Looking for MANIFEST files in $filepath\n";
ScanForManifestFiles($filepath, $theme_root, $theme_name, $dist_dir);
}
elsif ($file eq "MANIFEST")
{
# print "Doing manifest file $filepath\n";
# Get the dest path from the first line of the file
open(MANIFEST, $filepath) || die "Could not open file $file";
# Read in the path if available
my($dest_line) = <MANIFEST>;
chomp $dest_line;
close MANIFEST;
$dest_line =~ s|^#!dest[\t ]+|| || die "No destination line found in $filepath\n";
my($dest_path) = $dist_dir."chrome:skins:$theme_name:$dest_line";
# print " Destination is $dest_path\n";
InstallResources($filepath, "$dest_path", 0);
}
}
}
#-----------------------------------------------
# SetupBuildLog
#-----------------------------------------------
sub SetupBuildLog($$)
{
my($logfile_path, $timestamped_log) = @_;
my($logdir) = "";
my($logfile) = $logfile_path;
if ($logfile_path =~ /(.+?:)([^:]+)$/) # ? for non-greedy match
{
$logdir = $1;
$logfile = $2;
mkpath($logdir);
}
if ($timestamped_log)
{
#Use time-stamped names so that you don't clobber your previous log file!
my $now = localtime();
while ($now =~ s@:@.@) {} # replace all colons by periods
OpenErrorLog("${logdir}${now}");
}
else
{
OpenErrorLog("${logdir}${logfile}");
}
}
#-----------------------------------------------
# SetBuildNumber
#-----------------------------------------------
sub SetBuildNumber($$)
{
my($build_num_file, $files_to_touch) = @_;
# Make sure we add the config dir to search, to pick up mozBDate.pm
# Need to do this dynamically, because this module can be used before
# mozilla/config has been checked out.
my ($inc_path) = $0; # $0 is the path to the parent script
$inc_path =~ s/:build:mac:build_scripts:.+$/:config/;
push(@INC, $inc_path);
require mozBDate;
mozBDate::UpdateBuildNumber($build_num_file, $main::MOZILLA_OFFICIAL);
my($file);
foreach $file (@$files_to_touch)
{
print "Writing build number to $file from ${file}.in\n";
mozBDate::SubstituteBuildNumber($file, $build_num_file, "${file}.in");
}
}
#-----------------------------------------------
# SetTimeBomb
#-----------------------------------------------
sub SetTimeBomb($$)
{
my ($warn_days, $bomb_days) = @_;
system("perl :mozilla:config:mac-set-timebomb.pl $warn_days $bomb_days");
}
#//--------------------------------------------------------------------------------------------------
#// Regenerate a configuration header file if necessary
#//--------------------------------------------------------------------------------------------------
sub UpdateConfigHeader($)
{
my($config_path) = @_;
my($config, $oldconfig) = ("", "");
my($define, $definevalue, $defines);
my($k, $l,);
foreach $k (keys(%main::options))
{
if ($main::options{$k})
{
foreach $l (keys(%{$main::optiondefines{$k}}))
{
$my::defines{$l} = $main::optiondefines{$k}{$l};
print "Setting up my::defines{$l}\n";
}
}
}
my $config_headerfile = current_directory().$config_path;
if (-e $config_headerfile)
{
open(CONFIG_HEADER, "< $config_headerfile") || die "$config_headerfile: $!\n";
my($line);
while ($line = <CONFIG_HEADER>)
{
if ($line =~ m/#define\s+([^\s]*)\s+([^\s]*)\s*\n/)
{
$define = $1;
$definevalue = $2;
#canonicalize so that whitespace changes are not significant
my $canon_value = "#define " . $define . " " . $definevalue . "\n";
$oldconfig .= $canon_value;
if (exists ($my::defines{$define}) and ($my::defines{$define} == $definevalue))
{
delete $my::defines{$define};
$config .= $canon_value;
}
}
}
close(CONFIG_HEADER);
}
if (%my::defines)
{
foreach $k (keys(%my::defines))
{
$config .= "#define " . $k . " " . $my::defines{$k} . "\n";
}
}
my $file_name = basename($config_headerfile);
if (($config ne $oldconfig) || (!-e $config_headerfile))
{
printf("Writing new configuration header $file_name\n");
open(CONFIG_HEADER, "> $config_headerfile") || die "$config_headerfile: $!\n";
print(CONFIG_HEADER "/* This file is auto-generated based on build options. Do not edit. */\n");
print CONFIG_HEADER ($config);
close(CONFIG_HEADER);
MacPerl::SetFileInfo("CWIE", "TEXT", $config_headerfile);
}
else
{
printf("Configuration header $file_name is up-to-date\n");
}
}
1;

View File

@@ -1,660 +0,0 @@
#!perl
package Moz::CodeWarriorLib;
=pod
=head1 NAME
CodeWarriorLib - supply interface to CodeWarrior
=head1 SYNOPSIS
#!perl
use CodeWarriorLib;
CodeWarriorLib::activate();
$had_errors = CodeWarriorLib::build_project(
$project_path, $target_name, $recent_errors_file, $clean_build
);
=head1 DESCRIPTION
Replaces the AppleScript library I<CodeWarriorLib>.
=over 4
=cut
use strict;
use Cwd;
use File::Basename;
use Mac::Types;
use Mac::Events;
use Mac::AppleEvents;
use Mac::AppleEvents::Simple;
use Mac::Processes;
use Mac::MoreFiles;
use Mac::StandardFile;
use vars qw($VERSION);
$VERSION = '1.02';
my($app) = 'CWIE';
my($scriptDir) = cwd(); # could use $0 for this
my($ide_loc_file) = "";
# 0 == don't switch CWIE to front app in do_event(), 1 == do switch
# note: activate() still switches when called
$Mac::AppleEvents::Simple::SWITCH = 0;
# $Mac::AppleEvents::Simple::WARN = 1;
# supply your own path to the source here
#_test('PowerPudgeIV:mozilla:mozilla:');
# If you want to understand the gobbldeygook that's used to build Apple Events,
# you should start by reading the AEGizmos documentation.
=pod
=item _get_project($full_path)
A private routine returning a reference to the open project with the given name,
or else the empty string (when that project is not open)
full_path is a string identifying the project to be built and is of the form,
e.g., "HD:ProjectFolder:MyProject.mcp". It must be supplied.
=cut
sub _get_project ($) {
my(
$full_path, $candidate_projects
) = @_;
$candidate_projects = _doc_named(basename($full_path, '*'));
if ($candidate_projects) {
my($cps) = _get_dobj($candidate_projects);
my($num) = AECountItems($cps);
if ($num) { # is a list
foreach (1 .. AECountItems($cps)) {
my($cp) = AEGetNthDesc($cps, $_);
if (lc $full_path eq lc _full_path($cp)) {
return($cp);
}
}
} else { # is only one, not a list
if (lc $full_path eq lc _full_path($cps)) {
return($cps);
}
}
}
return;
}
=pod
=item build_project
Build a selected target of a project, saving any errors to a file, if supplied.
full_path is a string identifying the project to be built and is of the form,
e.g., "HD:ProjectFolder:MyProject.mcp". It must be supplied.
If target_name is the empty string, the current target of the selected project
will be built, else, target_name should be a string matching a target name in
the selected project.
If error_path is the empty string, errors will not be saved to a file,
else, error_path should be the full path of a file to save error messages into.
=cut
$CodeWarriorLib::CLOSE_PROJECTS_FIRST = 0; # If true we close then make. If false, make then close.
my $last_project_built = "";
my $last_project_was_closed = 0;
sub build_project ($;$$$) {
my(
$full_path, $target_name, $error_path,
$remove_object, $p, $project_was_closed, $had_errors
) = @_;
_close_errors_window();
if ($CodeWarriorLib::CLOSE_PROJECTS_FIRST && ($last_project_built ne $full_path))
{
# If we're in "close first" mode, we don't close if the current project
# is the same as the previous one.
if ($last_project_was_closed) {
$p = _get_project($last_project_built);
_close($p);
}
$last_project_built = $full_path;
$last_project_was_closed = 0; # now refers to the new project
}
$project_was_closed = 0;
while (1) {
$p = _get_project($full_path);
if (!$p) {
if ($project_was_closed) {
print "### Error - request for project document failed after opening\n";
die "### possibly CW Pro 4 bug: be sure to close your Find window\n";
}
$project_was_closed = 1;
$last_project_was_closed = 1;
_open_file($full_path);
} else {
last;
}
}
$had_errors = 0;
if ($target_name eq '') {
if ($remove_object) {_remove_object($p)}
_build($p);
} else {
if ($remove_object) {_remove_object($p, $target_name)}
_build($p, $target_name);
}
if ($error_path ne '') {
_save_errors_window($error_path);
}
$had_errors = _close_errors_window();
if (!$CodeWarriorLib::CLOSE_PROJECTS_FIRST)
{
if ($project_was_closed) {
$p = _get_project($full_path);
_close($p);
}
}
return($had_errors);
}
=pod
=item appIsRunning()
=cut
sub _appIsRunning($)
{
my ($appSignature) = @_;
my ($psi);
my ($found) = 0;
my ($appPSN);
foreach $psi (values(%Process))
{
if ($psi->processSignature() eq $appSignature)
{
$appPSN = $psi->processNumber();
$found = 1;
last;
}
}
return $found;
}
=pod
=item appIsFrontmost()
=cut
sub _appIsFrontmost($)
{
my ($appSignature) = @_;
my ($psi);
my ($found) = 0;
my ($appPSN);
foreach $psi (values(%Process))
{
if ($psi->processSignature() eq $appSignature)
{
$appPSN = $psi->processNumber();
$found = 1;
last;
}
}
return (GetFrontProcess() == $appPSN);
}
=pod
=item activate()
Launches CodeWarrior and brings it to the front.
Once found, path will be saved in $idepath_file for future reference.
Edit or delete this file to change the location of the IDE. If app is
moved, C<activate()> will prompt for a new location.
First looks for an open CodeWarrior app. Second, tries to open previously
saved location in ':idepath.txt'. Third, tries to find it and allow user
to choose it with Navigation Services (if present). Fourth, uses good old
GUSI routines built-in to MacPerl for a Choose Directory dialog box.
=cut
sub activate ($) {
$ide_loc_file = $_[0]; # save in global
my($filepath, $appath, $psi) = ($ide_loc_file);
foreach $psi (values(%Process)) {
if ($psi->processSignature() eq $app) {
$appath = $psi->processAppSpec();
_save_appath($filepath, $appath);
last;
}
}
if (!$appath || !-x $appath) {
$appath = _read_appath($filepath);
}
if (!$appath || ! -x $appath)
{
# make sure that MacPerl is a front process
#ActivateApplication('McPL');
MacPerl::Answer("Please locate the CodeWarrior application.", "OK");
# prompt user for the file name, and store it
my $macFile = StandardGetFile( 0, "APPL");
if ( $macFile->sfGood() )
{
$appath = $macFile->sfFile();
}
else
{
die "Operation canceled\n";
}
# if (eval {require Mac::Navigation}) {
# my($options, $nav);
# Mac::Navigation->import();
# $options = NavGetDefaultDialogOptions();
# $options->message('Where is CodeWarrior IDE?');
# $options->windowTitle('Find CodeWarrior IDE');
# $nav = NavChooseObject($Application{$app}, $options);
# die "CodeWarrior IDE not found.\n" if (!$nav || !$nav->file(1));
# $appath = $nav->file(1);
# } else {
# local(*D);
# my $cwd = `pwd`;
# $appath = _get_folder(
# 'Where is the CW IDE folder?',
# dirname($Application{$app})
# );
# die "CodeWarrior IDE not found.\n" if !$appath;
# opendir(D, $appath) or die $!;
# chdir($appath);
# foreach my $file (sort readdir (D)) {
# my(@app) = MacPerl::GetFileInfo($file);
# if ($app[0] && $app[1] &&
# $app[1] eq 'APPL' && $app[0] eq $app
# ) {
# $appath .= $file;
# last;
# }
# }
# chomp($cwd);
# chdir($cwd);
# }
_save_appath($filepath, $appath);
}
my($lp) = LaunchParam->new(
launchAppSpec => $appath,
launchControlFlags => launchContinue() + launchNoFileFlags()
);
unless (LaunchApplication($lp)) {
unlink($filepath);
die $^E;
}
# wait for CodeWarrior to show up in the list of processes
while (!_appIsRunning('CWIE'))
{
WaitNextEvent();
}
# wait for CodeWarrior to come to the front
while (!_appIsFrontmost('CWIE'))
{
WaitNextEvent();
}
}
=pod
=item getCodeWarriorPath()
Returns a file path relative to the CodeWarrior folder
=cut
sub getCodeWarriorPath($)
{
my($subfolder)=@_;
my($app_path) = _read_appath($ide_loc_file);
if ($app_path eq "") { die "Error: Failed to get CodeWarrior IDE path\n"; }
my($codewarrior_root) = $app_path;
$codewarrior_root =~ s/[^:]*$//;
return ($codewarrior_root . $subfolder);
}
=pod
=item getCodeWarriorIDEName()
Returns the name of the CodeWarrior application
=cut
sub getCodeWarriorIDEName()
{
my($subfolder)=@_;
my($app_path) = _read_appath($ide_loc_file);
if ($app_path eq "") { die "Error: Failed to get CodeWarrior IDE path\n"; }
my(@codewarrior_path) = split(/:/, $app_path);
return pop(@codewarrior_path);
}
=pod
=item quit()
Quits CodeWarrior.
=cut
sub quit() {
$last_project_built = "";
$last_project_was_closed = 0;
my($evt) = do_event(qw/aevt quit/, $app);
}
sub _build ($;$) {
my($evt);
if ($_[1]) {
my($prm) =
q"'----':obj {form:name, want:type(TRGT), seld:TEXT(@), from:" .
AEPrint($_[0]) . '}';
$evt = do_event(qw/CWIE MAKE/, $app, $prm, $_[1]);
} else {
my($prm) = q"'----':" . AEPrint($_[0]);
$evt = do_event(qw/CWIE MAKE/, $app, $prm);
}
}
sub _remove_object ($;$) {
my($evt);
if ($_[1]) {
my($prm) =
q"'----':obj {form:name, want:type(TRGT), seld:TEXT(@), from:" .
AEPrint($_[0]) . '}';
$evt = do_event(qw/CWIE RMOB/, $app, $prm, $_[1]);
} else {
my($prm) = q"'----':" . AEPrint($_[0]);
$evt = do_event(qw/CWIE RMOB/, $app, $prm);
}
}
sub _open_file ($) {
my($prm) =
q"'----':obj {form:name, want:type(alis), " .
q"seld:TEXT(@), from:'null'()}";
do_event(qw/aevt odoc/, $app, $prm, $_[0]);
}
sub import_project ($$) {
my($xml_file, $project_path) = @_;
my($prm) = "kocl:type(PRJD), rtyp:TEXT(@), data:TEXT(@), &subj:'null'()";
my($evt) = do_event(qw/core crel/, $app, $prm, $project_path, $xml_file);
my($result) = _get_event_result($evt);
if ($result eq "") {
_close(_get_project($project_path));
}
return $result;
}
sub export_project ($$) {
my($project_path, $xml_out_path) = @_;
my($p, $project_was_closed);
$project_was_closed = 0;
while (1) {
$p = _get_project($project_path);
if (!$p) {
if ($project_was_closed) {
print "### Error - request for project document failed after opening\n";
die "### possibly CW bug: be sure to close your Find window\n";
}
$project_was_closed = 1;
_open_file($project_path);
} else {
last;
}
}
# avoid problems with the Project Messages window
_close_named_window("Project Messages");
my($prm) =
q"'----':obj {form:indx, want:type(PRJD), " .
q"seld:1, from:'null'()}, kfil:TEXT(@)";
my($evt) = do_event(qw/CWIE EXPT/, $app, $prm, $xml_out_path);
if ($project_was_closed) {
$p = _get_project($project_path);
_close($p);
}
return _get_event_result($evt);
}
sub _doc_named ($) {
my($prm) =
q"'----':obj {form:test, want:type(docu), from:'null'(), " .
q"seld:cmpd{relo:'= ', 'obj1':obj {form:prop, want:type" .
q"(prop), seld:type(pnam), from:'exmn'()}, 'obj2':TEXT(@)}}";
my($evt) = do_event(qw/core getd/, $app, $prm, $_[0]);
return($evt->{REPLY} eq 'aevt\ansr{}' ? undef : $evt);
}
sub _full_path ($) {
my($obj) = $_[0];
my($prm) =
q"'----':obj {form:prop, want:type(prop), seld:type(FILE), " .
q"from:" . AEPrint($_[0]) . q"}, rtyp:type(TEXT)";
my($evt) = do_event(qw/core getd/, $app, $prm);
return MacPerl::MakePath(
MacUnpack('fss ', (
AEGetParamDesc($evt->{REP}, keyDirectObject()))->data()->get()
)
);
}
sub _save_errors_window ($) {
my($prm) =
q"'----':obj {form:name, want:type(alis), seld:TEXT(@), from:'null'()}";
do_event(qw/MMPR SvMs/, $app, $prm, $_[0]);
}
sub _close_errors_window () {
return _close_named_window('Errors & Warnings');
}
sub _close_named_window ($) {
my($window_name) = @_;
my($prm) =
q"'----':obj {form:name, want:type(cwin), " .
q"seld:TEXT(@), from:'null'()}";
my($evt) = do_event(qw/core clos/, $app, $prm, $window_name);
return($evt->{REPLY} eq 'aevt\ansr{}' ? 1 : 0);
}
sub _close () {
my($prm) = q"'----':" . AEPrint($_[0]);
do_event(qw/core clos/, $app, $prm);
}
sub _get_dobj ($) {
return(AEGetParamDesc($_[0]->{REP}, keyDirectObject()));
}
sub _get_folder ($$) {
require 'GUSI.ph';
my($prompt, $default) = @_;
MacPerl::Choose(
GUSI::AF_FILE(), 0, $prompt, '',
GUSI::CHOOSE_DIR() + ($default ? &GUSI::CHOOSE_DEFAULT : 0),
$default
);
}
sub _get_event_result ($)
{
my($evt) = @_;
my($result) = $evt->{ERROR};
if ( $result eq "" && $evt->{ERRNO} != 0 )
{
$result = "unknown error (".$evt->{ERRNO}.")";
}
return $result;
}
sub _save_appath ($$) {
my($cwd) = cwd(); # remember the current working dir
chdir($scriptDir); # change dir to the script dir
local(*F);
open(F, '>' . $_[0]) or die $!;
print F $_[1];
close(F);
chdir($cwd); # restore the cwd
}
sub _read_appath ($) {
my($filepath) = @_;
my($cwd) = cwd(); # remember the current working dir
chdir($scriptDir); # change dir to the script dir
if (! -e $filepath) {
return "";
}
local(*F);
open(F, $filepath);
my($appath) = <F>;
close(F);
chdir($cwd); # restore the cwd
return($appath);
}
sub _test ($) {
activate($ide_loc_file);
my($path) = $_[0];
build_project(
"${path}modules:xml:macbuild:XML.mcp", '',
"${path}build:mac:Mozilla.BuildLog.part"
);
}
1;
=pod
=back
=head1 HISTORY
=over 4
=item v1.02, September 23, 1998
Made fixes in finding and saving location of CodeWarrior IDE.
=item v1.01, June 1, 1998
Made fixes to C<chdir()> in C<activate()>, made C<activate()> more robust
in finding CodeWarrior IDE, added global variable to NOT switch to IDE
for each sent event, a few other fixes.
=item v1.00, May 30, 1998
First shot
=back
=head1 AUTHORS
Chris Nandor F<E<lt>pudge@pobox.comE<gt>>, and the author of the
original I<CodeWarriorLib>, Scott Collins F<E<lt>scc@netscape.comE<gt>>.
=head1 SEE ALSO
BuildProject L<Moz>.
=head1 COPYRIGHT
The contents of this file are subject to the Netscape Public
License Version 1.1 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS
IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
implied. See the License for the specific language governing
rights and limitations under the License.
The Original Code is Mozilla Communicator client code, released
March 31, 1998.
The Initial Developer of the Original Code is Netscape
Communications Corporation. Portions created by Netscape are
Copyright (C) 1998-1999 Netscape Communications Corporation. All
Rights Reserved.
Contributor(s):
=cut

View File

@@ -1,573 +0,0 @@
#!perl -w
package Moz::Jar;
#
# Module for creating jar files, either using a jar manifest, or
# simply jarring up folders on disk.
#
require 5.004;
require Exporter;
use strict;
use Archive::Zip;
use File::Path;
use Mac::Files;
use Moz::Moz;
use vars qw( @ISA @EXPORT );
@ISA = qw(Exporter);
@EXPORT = qw(
CreateJarFileFromDirectory
CreateJarFromManifest
WriteOutJarFiles
SanityCheckJarOptions
);
#-------------------------------------------------------------------------------
# Add the contents of a directory to the zip file
#
#-------------------------------------------------------------------------------
sub _addDirToJar($$$$)
{
my($dir, $jar_root, $zip, $compress) = @_;
opendir(DIR, $dir) or die "Error: Cannot open dir $dir\n";
my @files = readdir(DIR);
closedir DIR;
my $unix_jar_root = $jar_root;
$unix_jar_root =~ s|:|/|g; # colon to slash conversion
my $file;
foreach $file (@files)
{
my $filepath = $dir.":".$file;
if (-d $filepath)
{
print "Adding files to jar from $filepath\n";
_addDirToJar($filepath, $jar_root, $zip, $compress);
}
else
{
my $member = Archive::Zip::Member->newFromFile($filepath);
die "Error: Failed to create zip file member $filepath\n" unless $member;
my $unixName = $filepath;
$unixName =~ s|:|/|g; # colon to slash conversion
$unixName =~ s|^$unix_jar_root||; # relativise
$member->fileName($unixName);
# print "Adding $file as $unixName\n";
if ($compress) {
$member->desiredCompressionMethod(Archive::Zip::COMPRESSION_DEFLATED);
} else {
$member->desiredCompressionMethod(Archive::Zip::COMPRESSION_STORED);
}
$zip->addMember($member);
}
}
}
#-------------------------------------------------------------------------------
# Add the contents of a directory to the zip file
#
#-------------------------------------------------------------------------------
sub CreateJarFileFromDirectory($$$)
{
my($srcdir, $jarpath, $compress) = @_;
my $zip = Archive::Zip->new();
_addDirToJar($srcdir, $srcdir, $zip, $compress);
print "Saving zip file...\n";
my $status = $zip->writeToFileNamed($jarpath);
if ($status == 0) {
print "Zipping completed successfully\n";
} else {
print "Error saving zip file\n";
}
# set the file type/creator to something reasonable
MacPerl::SetFileInfo("ZIP ", "ZIP ", $jarpath);
}
#-------------------------------------------------------------------------------
# printZipContents
#
#-------------------------------------------------------------------------------
sub printZipContents($)
{
my($zip) = @_;
my(@members) = $zip->memberNames();
print "Zip contains:\n";
my($member);
foreach $member (@members)
{
print " $member\n";
}
}
#-------------------------------------------------------------------------------
# safeSaveJarFile
#
# Archive::Zip has a problem where you cannot save a zip file on top of
# an existing zip file that it has open, because it holds references
# into that zip. So we have to save to a temp file, then do a swap.
#
# Note that the zip will become invalid after this operation.
# If you want to do further operations on it, you'll have to reread it.
#-------------------------------------------------------------------------------
sub safeSaveJarFile($$)
{
my($zip, $full_dest_path) = @_;
my($temp_file_name) = $full_dest_path."_temp";
($zip->writeToFileNamed($temp_file_name) == Archive::Zip::AZ_OK) || die "Error: died writing jar to temp file $temp_file_name\n";
unlink $full_dest_path;
(rename $temp_file_name, $full_dest_path) || die "Error: Failed to rename $temp_file_name\n";
MacPerl::SetFileInfo("ZIP ", "ZIP ", $full_dest_path);
}
#-------------------------------------------------------------------------------
# addToJarFile
#
# Add a file to a jar file
#
# Parameters:
# 1. Jar ID. Unix path of jar file inside chrome.
# 2. Abs path to jar.mn file (i.e. source) (mac breaks)
# 3. File source, relative to jar.mn path (mac breaks)
# 4. Abs path to the resulting .jar file (mac breaks)
# 5. Relative file path within the jar (unix breaks)
# 6. Reference to hash of jar files
#
#-------------------------------------------------------------------------------
sub addToJarFile($$$$$$$)
{
my($jar_id, $jar_man_dir, $file_src, $jar_path, $file_jar_path, $override, $jars) = @_;
# print "addToJarFile with:\n $jar_man_dir\n $file_src\n $jar_path\n $file_jar_path\n";
unless ($jar_path =~ m/(.+:)([^:]+)$/) { die "Error: Bad jar path $jar_path\n"; }
my($target_dir) = $1;
my($jar_name) = $2;
$target_dir =~ s/[^:]+$//;
# print "¥ $target_dir $jar_name\n";
# find the source file
my($src) = $jar_man_dir.":".$file_src;
if ((!-e $src) && ($file_src =~ m/.+:([^:]+)$/)) # src does not exist. Fall back to looking for src in jar.mn dir
{
$file_src = $1;
$src = $jar_man_dir.":".$file_src;
if (!-e $src) {
die "Error: Can't find chrome file $src\n";
}
}
if ($main::options{chrome_jars})
{
my($zip) = $jars->{$jar_id};
unless ($zip) { die "Error: Can't find Zip entry for $jar_id\n"; }
# print "Adding $file_src to jar file $jar_path at $file_jar_path\n";
my($member) = Archive::Zip::Member->newFromFile($src);
unless ($member) { die "Error: Failed to create zip file member $src\n"; }
$member->fileName($file_jar_path);
my($compress) = 1;
if ($compress) {
$member->desiredCompressionMethod(Archive::Zip::COMPRESSION_DEFLATED);
$member->desiredCompressionLevel(Archive::Zip::COMPRESSION_LEVEL_DEFAULT); # defaults to 6
} else {
$member->desiredCompressionMethod(Archive::Zip::COMPRESSION_STORED);
}
my($old_member) = $zip->memberNamed($file_jar_path);
if ($override)
{
if ($old_member)
{
# print "Overriding $file_jar_path in jar file $jar_id\n";
# need to compare mod dates or use the + here
$zip->removeMember($old_member);
}
$zip->addMember($member);
}
else
{
if ($old_member)
{
#compare dates here
my($member_moddate) = $old_member->lastModTime();
my($file_moddate) = GetFileModDate($src);
if ($file_moddate > $member_moddate)
{
print "Updating older file $file_jar_path in $jar_id\n";
$zip->removeMember($old_member);
$zip->addMember($member);
}
else
{
print "File $file_jar_path in $jar_id is more recent. Not updating.\n";
}
}
else
{
$zip->addMember($member);
}
}
}
if ($main::options{chrome_files}) # we install raw files too
{
my($rel_path) = $file_jar_path;
$rel_path =~ s|/|:|g; # slash to colons
my($dir_name) = $jar_name;
$dir_name =~ s/\.jar$//;
my($dst) = $target_dir.$dir_name.":".$rel_path;
# print "Aliassing $src\n to\n$dst\n";
if ($override)
{
unlink $dst;
MakeAlias($src, $dst); # don't check errors, otherwise we fail on replacement
}
else
{
if (-e $dst)
{
#compare dates here
my($dst_moddate) = GetFileModDate($dst);
my($file_moddate) = GetFileModDate($src);
if ($file_moddate > $dst_moddate)
{
print "Updating older file $rel_path in $dir_name\n";
unlink $dst;
MakeAlias($src, $dst);
}
else
{
print "File $file_jar_path in $jar_id is more recent. Not updating.\n";
}
}
else
{
MakeAlias($src, $dst);
}
}
}
}
#-------------------------------------------------------------------------------
# setupJarFile
#
# setup a zip for writing
#-------------------------------------------------------------------------------
sub setupJarFile($$$)
{
my($jar_id, $dest_path, $jar_hash) = @_;
# print "Creating jar file $jar_id at $jar_path\n";
my($jar_file) = $jar_id;
$jar_file =~ s|/|:|g; # slash to colons
my($full_jar_path) = full_path_to($dest_path.":".$jar_file);
if ($main::options{chrome_jars})
{
my($zip) = $jar_hash->{$jar_id};
if (!$zip) # if we haven't made it already, do so
{
my($zip) = Archive::Zip->new();
$jar_hash->{$jar_id} = $zip;
# does the jar file exist already? If so, read it in
if (-e $full_jar_path)
{
print "Reading in jar file $jar_id\n";
if ($zip->read($full_jar_path) != Archive::Zip::AZ_OK) { die "Error: Failed to re-read $full_jar_path\n"; }
# printZipContents($zip);
}
}
}
else
{
# installing files.
# nothing to do. MakeAlias creates dirs as needed.
# add this jar to the list
$jar_hash->{$jar_id} = 1;
}
}
#-------------------------------------------------------------------------------
# closeJarFile
#
# We're done with this jar file _for this jar.mn_. We may add more entries
# to it later, so keep it open in the hash.
#-------------------------------------------------------------------------------
sub closeJarFile($$)
{
my($jar_path, $jar_hash) = @_;
# print "Closing jar file $jar_path\n";
if ($main::options{chrome_jars})
{
}
else
{
# installing files.
# nothing to do
}
}
#-------------------------------------------------------------------------------
# WriteOutJarFiles
#
# Now we dump out the jars
#-------------------------------------------------------------------------------
sub WriteOutJarFiles($$)
{
my($chrome_dir, $jars) = @_;
unless ($main::options{chrome_jars}) { return; }
my($full_chrome_path) = full_path_to($chrome_dir);
my($key);
foreach $key (keys %$jars)
{
my($zip) = $jars->{$key};
my($rel_path) = $key;
$rel_path =~ s/\//:/g;
my($output_path) = $full_chrome_path.":".$rel_path;
print "Writing zip file $key to $output_path\n";
# ensure the target dirs exist
my($path) = $output_path;
$path =~ s/[^:]+$//;
mkpath($path);
# unlink $output_path; # remove any existing jar
safeSaveJarFile($zip, $output_path);
# $zip is invalid after this operation, so nuke it here
$jars->{$key} = 0;
}
}
#-------------------------------------------------------------------------------
# registerChromePackage
#
# Enter a chrome package into the installed-chrome.txt file
#-------------------------------------------------------------------------------
sub registerChromePackage($$$$$$)
{
my($jar_file, $file_path, $chrome_dir, $jar_hash, $chrome_type, $pkg_name) = @_;
my($manifest_subdir) = $jar_file;
$manifest_subdir =~ s/:/\//g;
my($chrome_entry);
if ($main::options{use_jars}) {
$chrome_entry = "$chrome_type,install,url,jar:resource:/chrome/$manifest_subdir!/$chrome_type/$pkg_name";
} else {
$manifest_subdir =~ s/\.jar$//;
$chrome_entry = "$chrome_type,install,url,resource:/chrome/$manifest_subdir/$chrome_type/$pkg_name";
}
# print "Entering $chrome_entry in installed-chrome.txt\n";
# ensure chrome_dir exists
mkpath($chrome_dir);
my($inst_chrome) = ${chrome_dir}.":installed-chrome.txt";
if (open(CHROMEFILE, "<$inst_chrome")) {
while (<CHROMEFILE>) {
chomp;
if ($_ eq $chrome_entry) {
# $chrome_entry already appears in installed-chrome.txt file
# just update the mod date
my $now = time;
utime($now, $now, $inst_chrome) || die "Error: Couldn't touch $inst_chrome";
print "+++ updating chrome $inst_chrome\n+++\t\t$chrome_entry\n";
close(CHROMEFILE) || die "Error: can't close $inst_chrome: $!";
return 0;
}
}
close(CHROMEFILE) || die "Error: can't close $inst_chrome: $!";
}
open(CHROMEFILE, ">>${inst_chrome}") || die "Error: Failed to open $inst_chrome\n";
print(CHROMEFILE "${chrome_entry}\n");
close(CHROMEFILE) || die "Error: Failed to close $inst_chrome\n";
print "+++ adding chrome $inst_chrome\n+++\t\t$chrome_entry\n";
}
#-------------------------------------------------------------------------------
# Create or add to a jar file from a jar.mn file.
# Both arguments are relative to the mozilla root dir.
#
#
#-------------------------------------------------------------------------------
sub CreateJarFromManifest($$$)
{
my($jar_man_path, $dest_path, $jars) = @_;
if ($main::options{chrome_jars}) {
print "Jarring from $jar_man_path\n";
}
if ($main::options{chrome_files}) {
print "Installing files from $jar_man_path\n";
}
$jar_man_path = full_path_to($jar_man_path);
$dest_path = full_path_to($dest_path);
# if the jars hash is empty, nuke installed-chrome.txt
if (! scalar(%$jars))
{
print "Nuking installed-chrome.txt\n";
my($installed_chrome) = $dest_path.":installed-chrome.txt";
# unlink $installed_chrome;
}
my $jar_man_dir = "";
my $jar_man_file = "";
if ($jar_man_path =~ /(.+):([^:]+)$/)
{
$jar_man_dir = $1; # no trailing :
$jar_man_file = $2;
}
# Keep a hash of jar files, keyed on relative jar path (e.g. "packages/core.jar")
# Entries are open Archive::Zips (if zipping), and installed-chrome entries.
my($jar_id) = ""; # Current foo/bar.jar from jar.mn file
my($jar_file) = ""; # relative path to jar file (from $dest_path), with mac separators
my($full_jar_path);
open(FILE, "<$jar_man_path") || die "Error: could not open \"$jar_man_path\": $!";
while (<FILE>)
{
my($line) = $_;
chomp($line);
# print "$line\n";
if ($line =~ /^\s*\#.*$/) { # skip comments
next;
}
if ($line =~/^([\w\d.\-\_\\\/]+)\:\s*$/) # line start jar file entries
{
$jar_id = $1;
$jar_file = $jar_id;
$jar_file =~ s|/|:|g; # slash to colons
$full_jar_path = $dest_path.":".$jar_file;
setupJarFile($jar_id, $dest_path, $jars);
}
elsif ($line =~ /^(\+?)\s+([\w\d.\-\_\\\/]+)\s*(\([\w\d.\-\_\\\/]+\))?$\s*/) # jar file entry
{
my($override) = ($1 eq "+");
my($file_dest) = $2;
my($file_src) = $3;
if ($file_src) {
$file_src = substr($file_src, 1, -1); #strip the ()
} else {
$file_src = $file_dest;
}
$file_src =~ s|/|:|g;
if ($jar_file ne "") # if jar is open, add to jar
{
if ($file_dest =~ /([\w\d.\-\_]+)\/([\w\d.\-\_\\\/]+)contents.rdf/)
{
my $chrome_type = $1;
my $pkg_name = $2;
registerChromePackage($jar_file, $file_dest, $dest_path, $jars, $chrome_type, $pkg_name);
}
addToJarFile($jar_id, $jar_man_dir, $file_src, $full_jar_path, $file_dest, $override, $jars);
}
else
{
die "Error: bad jar.mn format at $line\n";
}
}
elsif ($line =~ /^\s*$/ ) # blank line
{
if ($jar_file ne "") #if a jar file is open, close it
{
closeJarFile($full_jar_path, $jars);
$jar_file = "";
$full_jar_path = "";
}
}
}
close(FILE);
if ($jar_file ne "") #if a jar file is open, close it
{
closeJarFile($full_jar_path, $jars);
}
}
1;

View File

@@ -1,228 +0,0 @@
#!perl -w
package Moz::MacCVS;
# package Mac::Apps::MacCVS; this should really be the name of the package
# but due to our directory hierarchy in mozilla, I am not doing it
require 5.004;
require Exporter;
use strict;
use Exporter;
use vars qw($VERSION @ISA @EXPORT);
use Cwd;
use File::Basename;
use Mac::StandardFile;
use Mac::AppleEvents;
use Mac::AppleEvents::Simple;
@ISA = qw(Exporter);
@EXPORT = qw(new describe checkout update);
$VERSION = "1.00";
# If you want to understand the gobbldeygook that's used to build Apple Events,
# you should start by reading the AEGizmos documentation.
# Architecture:
# cvs session object:
# name - session name
# session_file - session file
#
#
my($last_error) = 0;
my($gAppSig) = 'Mcvs'; # MacCVS Pro
#
# utility routines
#
sub _checkForEventError($)
{
my($evt) = @_;
if ($evt->{ERRNO} != 0)
{
print STDERR "Error. Script returned '$evt->{ERROR} (error $evt->{ERRNO})\n";
$last_error = $evt->{ERRNO};
return 0;
}
return 1; # success
}
#
# Session object methods
#
sub new
{
my ( $proto, $session_file) = @_;
my $class = ref($proto) || $proto;
my $self = {};
if ( defined($session_file) && ( -e $session_file) )
{
$self->{"name"} = basename( $session_file );
$self->{"session_file"} = $session_file;
bless $self, $class;
return $self;
}
else
{
print STDERR "MacCVS->new cvs file < $session_file > does not exist\n";
return;
}
}
# makes sure that the session is open
# assertSessionOpen()
# returns 1 on success
sub assertSessionOpen()
{
my ($self) = shift;
$last_error = 0;
my($prm) =
q"'----':obj {form:name, want:type(alis), seld:TEXT(@), from:'null'()}";
my($evt) = do_event(qw/aevt odoc/, $gAppSig, $prm, $self->{session_file});
return _checkForEventError($evt);
}
# prints the cvs object, used mostly for debugging
sub describe
{
my($self) = shift;
$last_error = 0;
print "MacCVS:: name: ", $self->{name}, " session file: ", $self->{session_file}, "\n";
}
# checkout( self, module, revision, date)
# MacCVS checkout command
# returns 1 on success.
sub checkout()
{
my($self, $module, $revision, $date ) = @_;
unless( defined ($module) ) { $module = ""; } # get rid of the pesky undefined warnings
unless( defined ($revision) ) { $revision = ""; }
unless( defined ($date) ) { $date = ""; }
$last_error = 0;
$self->assertSessionOpen() || die "Error: failed to open MacCVS session file at $self->{session_file}\n";
my($revstring) = ($revision ne "") ? $revision : "(none)";
my($datestring) = ($date ne "") ? $date : "(none)";
print "Checking out $module with revision $revstring, date $datestring\n";
my($prm) =
q"'----':obj {form:name, want:type(docu), seld:TEXT(@), from:'null'()}, ".
q"modl:'TEXT'(@), tagr:'TEXT'(@), tagd:'TEXT'(@) ";
my($evt) = do_event(qw/MCvs cout/, $gAppSig, $prm, $self->{name}, $module, $revision, $date);
return _checkForEventError($evt);
}
# update( self, branch tag, list of paths)
# MacCVS udate command
# returns 1 on success.
# NOTE: MacCVS Pro does not correctly support this stuff yet (as of version 2.7d5).
sub update()
{
my($self, $branch, $paths ) = @_;
$last_error = 0;
$self->assertSessionOpen() || die "Error: failed to open MacCVS session file at $self->{session_file}\n";
if ($branch eq "HEAD") {
$branch = "";
}
my($paths_list) = "";
my($path);
foreach $path (@$paths)
{
if ($paths_list ne "") {
$paths_list = $paths_list.", ";
}
$paths_list = $paths_list."Ò".$path."Ó";
}
my($prm) =
q"'----':obj {form:name, want:type(docu), seld:TEXT(@), from:'null'()}, ".
q"tagr:'TEXT'(@), tFls:[";
$prm = $prm.$paths_list."]";
my($evt) = do_event(qw/MCvs updt/, $gAppSig, $prm, $self->{name}, $branch);
return _checkForEventError($evt);
};
sub getLastError()
{
return $last_error;
}
1;
=pod
=head1 NAME
MacCVS - Interface to MacCVS
=head1 SYNOPSIS
use MacCVS;
$session = MacCVS->new( <session_file_path>) || die "cannot create session";
$session->checkout([module] [revision] [date]) || die "Could not check out";
=head1 DESCRIPTION
This is a MacCVS interface for talking to MacCVS Pro client.
MacCVSSession is the class used to manipulate the session
=item new
MacCVS->new( <cvs session file path>);
Creates a new session. Returns undef on failure.
=item checkout( <module> [revision] [date] )
cvs checkout command. Revision and date are optional
returns 0 on failure
=cut
=head1 SEE ALSO
=over
=item MacCVS Home Page
http://www.maccvs.org/
=back
=head1 AUTHORS
Aleks Totic atotic@netscape.com
Simon Fraser sfraser@netscape.com
=cut
__END__

View File

@@ -1,603 +0,0 @@
=head1 NAME
B<Moz> - routines for automating CodeWarrior builds, and some extra-curricular
activities related to building Mozilla
=head1 SYNOPSIS
use Moz;
OpenErrorLog(":::BuildLog");
StopForErrors();
$Moz::QUIET = 1;
InstallFromManifest(":projects:MANIFEST", $dist_dir);
BuildProjectClean(":projects:SomeProject.mcp", "SomeTarget");
MakeAlias(":projects:SomeProject.shlb", $dist_dir);
DontStopForErrors();
BuildProject(":projects:SomeOtherProject.mcp", "SomeTarget");
=head1 DESCRIPTION
B<Moz> comprises the routines needed to slap CodeWarrior around, force it
to build a sequence of projects, report the results, and a few other things.
This module should only contain functions that are generic to any build,
not just the Mozilla build.
=cut
package Moz::Moz;
require Exporter;
use Cwd;
use File::Copy;
use File::Path;
use File::Basename;
use Mac::Types;
use Mac::Events;
use Mac::Processes;
use ExtUtils::Manifest 'maniread';
use Moz::CodeWarriorLib;
@ISA = qw(Exporter);
@EXPORT = qw( LaunchCodeWarrior
GetCodeWarriorRelativePath
current_directory
full_path_to
DoBuildProject
ImportXMLProject
ExportProjectToXML
OpenErrorLog
MakeAlias
GetFileModDate
StopForErrors
DontStopForErrors
InstallFromManifest
InstallResources
RedirectOutputToFile
Delay
ActivateApplication
IsProcessRunning);
@EXPORT_OK = qw(CloseErrorLog QUIET);
sub current_directory()
{
my $current_directory = cwd();
chop($current_directory) if ( $current_directory =~ m/:$/ );
return $current_directory;
}
sub full_path_to($)
{
my ($path) = @_;
if ( $path =~ m/^[^:]+$/ )
{
$path = ":" . $path;
}
if ( $path =~ m/^:/ )
{
$path = current_directory() . $path;
}
return $path;
}
$logging = 0;
$recent_errors_file = "";
$stop_on_1st_error = 1;
$QUIET = 0;
=head2 Logging all the errors and warnings - C<OpenErrorLog($log_file)>, C<CloseErrorLog()>
The warnings and errors generated in the course of building projects can be logged to a file.
Tinderbox uses this facility to show why a remote build failed.
Logging is off by default.
Start logging at any point in your build process with C<OpenErrorLog($log_file)>.
Stop with C<CloseErrorLog()>.
You never need to close the log explicitly, unless you want to just log a couple of projects in the middle of a big list.
C<CloseErrorLog()> is not exported by default.
=cut
sub CloseErrorLog()
{
if ( $logging )
{
close(ERROR_LOG);
$logging = 0;
StopForErrors() if $stop_on_1st_error;
}
}
sub OpenErrorLog($)
{
my ($log_file) = @_;
CloseErrorLog();
if ( $log_file )
{
$log_file = full_path_to($log_file);
open(ERROR_LOG, ">$log_file") || die "Error: Can't open $log_file\n";
MacPerl::SetFileInfo("CWIE", "TEXT", $log_file);
$log_file =~ m/.+:(.+)/;
$recent_errors_file = full_path_to("$1.part");
$logging = 1;
}
}
=head2 Stopping before it's too late - C<StopForErrors()>, C<DontStopForErrors()>
When building a long list of projects, you decide whether to continue building subsequent projects when one fails.
By default, your build script will C<die> after the first project that generates an error while building.
Change this behavior with C<DontStopForErrors()>.
Re-enable it with C<StopForErrors()>.
=cut
sub StopForErrors()
{
$stop_on_1st_error = 1;
# Can't stop for errors unless we notice them.
# Can't notice them unless we are logging.
# If the user didn't explicitly request logging, log to a temporary file.
if ( ! $recent_errors_file )
{
OpenErrorLog("${TMPDIR}BuildResults");
}
}
sub DontStopForErrors()
{
$stop_on_1st_error = 0;
}
sub log_message($)
{
if ( $logging )
{
my ($message) = @_;
print ERROR_LOG $message;
}
}
sub log_message_with_time($)
{
if ( $logging )
{
my ($message) = @_;
my $time_stamp = localtime();
log_message("$message ($time_stamp)\n");
}
}
sub log_recent_errors($)
{
my ($project_name) = @_;
my $found_errors = 0;
if ( $logging )
{
open(RECENT_ERRORS, "<$recent_errors_file");
while( <RECENT_ERRORS> )
{
if ( /^Error/ || /^CouldnÕt find project file/ || /^Link Error/ )
{
# if (!$found_errors)
# print $_;
$found_errors = 1;
}
print ERROR_LOG $_;
}
close(RECENT_ERRORS);
unlink("$recent_errors_file");
}
if ( $stop_on_1st_error && $found_errors )
{
print ERROR_LOG "### Build failed.\n";
die "### Errors encountered building \"$project_name\".\n";
}
}
sub DoBuildProject($$$)
{
my ($project_path, $target_name, $clean_build) = @_;
$project_path = full_path_to($project_path);
# $project_path =~ m/.+:(.+)/;
# my $project_name = $1;
log_message_with_time("### Building \"$project_path\"");
# Check that the given project exists
if (! -e $project_path)
{
print ERROR_LOG "### Build failed.\n";
die "### Can't find project file \"$project_path\".\n";
}
print "Building \"$project_path\[$target_name\]\"\n";
$had_errors = Moz::CodeWarriorLib::build_project(
$project_path, $target_name, $recent_errors_file, $clean_build
);
WaitNextEvent();
# $had_errors =
#MacPerl::DoAppleScript(<<END_OF_APPLESCRIPT);
# tell (load script file "$CodeWarriorLib") to BuildProject("$project_path", "$project_name", "$target_name", "$recent_errors_file", $clean_build)
#END_OF_APPLESCRIPT
# Append any errors to the globally accumulated log file
# if ( $had_errors ) # Removed this test, because we want warnings, too. -- jrm
{
log_recent_errors($project_path);
}
}
sub ImportXMLProject($$)
{
my ($xml_path, $project_path) = @_;
# my ($codewarrior_ide_name) = Moz::CodeWarriorLib::getCodeWarriorIDEName();
# my $ascript = <<EOS;
# tell application "$codewarrior_ide_name"
# make new (project document) as ("$project_path") with data ("$xml_path")
# end tell
#EOS
# print $ascript."\n";
# my($result) = MacPerl::DoAppleScript($ascript);
# unless ($result) { die "Error: ImportXMLProject AppleScript failed $^E $result\n"; }
#
my($import_error) = Moz::CodeWarriorLib::import_project($xml_path, $project_path);
if ($import_error ne "") {
die "Error: ImportXMLProject failed with error $import_error\n";
}
}
sub ExportProjectToXML($$)
{
my ($project_path, $xml_path) = @_;
my (@suffix_list) = (".mcp");
my ($project_name, $project_dir, $suffix) = fileparse($project_path, @suffix_list);
if ($suffix eq "") { die "Project: $project_path doesn't look like a project file.\n"; }
if (-e $xml_path) {
print "$xml_path exists - not exporting $project_path\n";
}
else {
print "Exporting $project_path to $xml_path\n";
my($export_error) = Moz::CodeWarriorLib::export_project($project_path, $xml_path);
if ($export_error ne "") {
die "Error: export_project failed with error '$export_error'\n";
}
if (! -e $xml_path) {
die "Error: XML export to $xml_path failed\n";
}
}
}
=head2 Miscellaneous
C<MakeAlias($old_file, $new_file)> functions like C<symlink()>, except with better argument defaulting and more explicit error messages.
=cut
sub MakeAlias($$)
{
my ($old_file, $new_file) = @_;
# if the directory to hold $new_file doesn't exist, create it
if ( ($new_file =~ m/(.+:)/) && !-d $1 )
{
mkpath($1);
}
# if a leaf name wasn't specified for $new_file, use the leaf from $old_file
if ( ($new_file =~ m/:$/) && ($old_file =~ m/.+:(.+)/) )
{
$new_file .= $1;
}
my $message = "Can't create a Finder alias (at \"$new_file\")\n for \"$old_file\"; because ";
die "Error: $message \"$old_file\" doesn't exist.\n" unless -e $old_file;
die "Error: $message I won't replace an existing (non-alias) file with an alias.\n" if ( -e $new_file && ! -l $new_file );
# now: $old_file exists; $new_file doesn't (or else, is an alias already)
if ( -l $new_file )
{
# ...then see if it already points to $old_file
my $current_target = full_path_to(readlink($new_file));
my $new_target = full_path_to($old_file);
return if ( $current_target eq $new_target );
# if the desired alias already exists and points to the right thing, then we're done
unlink $new_file;
}
symlink($old_file, $new_file) || die "Error: $message symlink returned an unexpected error.\n";
}
=pod
C<InstallFromManifest()>
=cut
sub InstallFromManifest($;$$)
{
my ($manifest_file, $dest_dir, $flat) = @_;
$flat = 0 unless defined($flat); # if $flat, all rel. paths in MANIFEST get aliased to the root of $dest_dir
$dest_dir ||= ":";
$manifest_file =~ m/(.+):/;
my $source_dir = $1;
chop($dest_dir) if $dest_dir =~ m/:$/;
#Mac::Events->import();
WaitNextEvent();
if ($flat)
{
print "Doing manifest on \"$manifest_file\" FLAT\n" unless $QUIET;
}
else
{
print "Doing manifest on \"$manifest_file\"\n" unless $QUIET;
}
my $read = maniread(full_path_to($manifest_file));
foreach $file (keys %$read)
{
next unless $file;
$subdir = ":";
if (!$flat && ($file =~ /:.+:/ ))
{
$subdir = $&;
}
$file = ":$file" unless $file =~ m/^:/;
MakeAlias("$source_dir$file", "$dest_dir$subdir");
}
}
=pod
C<InstallResources()>
=cut
# parameters are path to MANIFEST file, destination dir, true (to make copies) or false (to make aliases)
sub InstallResources($;$;$)
{
my ($manifest_file, $dest_dir, $copy_files) = @_;
$dest_dir ||= ":";
mkpath($dest_dir) if !-d $dest_dir;
$manifest_file =~ m/(.+):/;
my $source_dir = $1;
chop($dest_dir) if $dest_dir =~ m/:$/;
WaitNextEvent();
print "Installing resources from \"$manifest_file\"\n" unless $QUIET;
my $read = maniread(full_path_to($manifest_file));
foreach $file (keys %$read)
{
next unless $file;
if ($copy_files)
{
copy("$source_dir:$file", "$dest_dir:$file");
}
else
{
MakeAlias("$source_dir:$file", "$dest_dir:$file");
}
}
}
#//--------------------------------------------------------------------------------------------------
#// Delay
#//--------------------------------------------------------------------------------------------------
sub Delay($)
{
my ($delay_seconds) = @_;
$now = time;
$exit_time = $now + $delay_seconds;
while ($exit_time > $now) {
$now = time;
}
}
#//--------------------------------------------------------------------------------------------------
#// GetFileModDate
#//--------------------------------------------------------------------------------------------------
sub GetFileModDate($)
{
my($filePath)=@_;
my($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
$atime,$mtime,$ctime,$blksize,$blocks) = stat($filePath);
return $mtime;
}
#//--------------------------------------------------------------------------------------------------
#// LaunchCodeWarrior
#//--------------------------------------------------------------------------------------------------
sub LaunchCodeWarrior($)
{
my($idepath_file) = @_; # full path to IDE location file
my($cur_dir) = cwd();
# this both launches and writes the IDE path file
Moz::CodeWarriorLib::activate($idepath_file);
chdir($cur_dir);
}
#//--------------------------------------------------------------------------------------------------
#// GetCodeWarriorRelativePath
#//--------------------------------------------------------------------------------------------------
sub GetCodeWarriorRelativePath($)
{
my($rel_path) = @_;
return Moz::CodeWarriorLib::getCodeWarriorPath($rel_path);
}
#//--------------------------------------------------------------------------------------------------
#// RedirectOutputToFile
#//--------------------------------------------------------------------------------------------------
sub RedirectOutputToFile($)
{
my($log_file) = @_;
# ensure that folders in the path exist
my($logdir) = "";
my($logfile) = $log_file;
if ($log_file =~ /(.+?:)([^:]+)$/) # ? for non-greedy match
{
$logdir = $1;
$logfile = $2;
mkpath($logdir);
}
print "Output is now being redirected to the file '$log_file'\n";
open(STDOUT, "> $log_file") || die "Can't redirect stdout";
open(STDERR, ">&STDOUT") || die "Can't dup stdout";
select(STDERR); $| = 1; # make unbuffered
select(STDOUT); $| = 1; # make unbuffered
MacPerl::SetFileInfo("CWIE", "TEXT", $log_file);
}
#//--------------------------------------------------------------------------------------------------
#// ActivateApplication
#//--------------------------------------------------------------------------------------------------
sub ActivateApplication($)
{
my ($appSignature) = @_;
my ($psi, $found);
my ($appPSN);
$found = 0;
foreach $psi (values(%Process))
{
if ($psi->processSignature() eq $appSignature)
{
$appPSN = $psi->processNumber();
$found = 1;
last;
}
}
if ($found == 0 || SameProcess($appPSN, GetFrontProcess()))
{
return;
}
SetFrontProcess($appPSN);
while (GetFrontProcess() != $appPSN)
{
WaitNextEvent();
}
}
#//--------------------------------------------------------------------------------------------------
#// IsProcessRunning
#//--------------------------------------------------------------------------------------------------
sub IsProcessRunning($)
{
my($processName, $psn, $psi) = @_;
while ( ($psn, $psi) = each(%Process) ) {
if ($psi->processName eq $processName) { return 1; }
}
return 0;
}
1;
=head1 AUTHORS
Scott Collins <scc@netscape.com>, Simon Fraser <sfraser@netscape.com>, Chris Yeh <cyeh@netscape.com>
=head1 SEE ALSO
BuildMozillaDebug.pl (et al), BuildList.pm, CodeWarriorLib (an AppleScript library)
=head1 COPYRIGHT
The contents of this file are subject to the Netscape Public
License Version 1.1 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS
IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
implied. See the License for the specific language governing
rights and limitations under the License.
The Original Code is Mozilla Communicator client code, released
March 31, 1998.
The Initial Developer of the Original Code is Netscape
Communications Corporation. Portions created by Netscape are
Copyright (C) 1998-1999 Netscape Communications Corporation. All
Rights Reserved.
Contributor(s):
=cut

View File

@@ -1,272 +0,0 @@
package Moz::Prefs;
require 5.004;
require Exporter;
# Package that attempts to read a file from the Preferences folder,
# and get build settings out of it
use strict;
use Exporter;
use File::Path;
use Mac::Files;
use vars qw(@ISA @EXPORT);
@ISA = qw(Exporter);
@EXPORT = qw(ReadMozUserPrefs);
#-------------------------------------------------------------------------------
#
# GetPrefsFolder
#
#-------------------------------------------------------------------------------
sub GetPrefsFolder()
{
my($prefs_folder) = FindFolder(kOnSystemDisk, kPreferencesFolderType, 1);
return $prefs_folder.":Mozilla build prefs";
}
#-------------------------------------------------------------------------------
#
# SetArrayValue
#
#-------------------------------------------------------------------------------
sub SetArrayValue($$$)
{
my($array_ref, $index1, $index2) = @_;
my($index);
foreach $index (@$array_ref)
{
if ($index->[0] eq $index1)
{
$index->[1] = $index2;
return 1;
}
}
return 0;
}
#-------------------------------------------------------------------------------
#
# WriteDefaultPrefsFile
#
#-------------------------------------------------------------------------------
sub WriteDefaultPrefsFile($)
{
my($file_path) = @_;
my($file_contents);
$file_contents = <<'EOS';
% You can use this file to customize the Mozilla build system.
% The following kinds of lines are allowable:
% Comment lines, which start with a '%' in the first column
% Lines which modify the default build settings. For the list of flags,
% see MozBuildFlags.pm. Examples are:
%
% build pull 0 % don't pull
% options mng 1 % turn mng on
%
% Line containing the special 'buildfrom' flag, which specifies
% where to start the build. Example:
%
% buildfrom nglayout % where to start the build
%
% Lines which specify the location of the files used to store paths
% to the CodeWarrior IDE, and the MacCVS Pro session file. Note quoting
% of paths containing whitespace. Examples:
%
% filepath idepath ::codewarrior.txt
% filepath sessionpath ":Some folder:MacCVS session path.txt"
%
% Lines which modify the build settings like %main::DEBUG.
% Any lines which do not match either of the above are assumed
% to set variables on $main::. Examples:
%
% MOZILLA_OFFICIAL 1
%
EOS
$file_contents =~ s/%/#/g;
local(*PREFS_FILE);
open(PREFS_FILE, "> $file_path") || die "Could not write default prefs file\n";
print PREFS_FILE ($file_contents);
close(PREFS_FILE);
MacPerl::SetFileInfo("McPL", "TEXT", $file_path);
}
#-------------------------------------------------------------------------------
#
# HandlePrefSet
#
#-------------------------------------------------------------------------------
sub HandlePrefSet($$$$)
{
my($flags, $name, $value, $desc) = @_;
if (SetArrayValue($flags, $name, $value)) {
print "Prefs set $desc flag '$name' to '$value'\n";
} else {
die "$desc setting '$name' is not a valid option\n";
}
}
#-------------------------------------------------------------------------------
#
# HandleBuildFromPref
#
#-------------------------------------------------------------------------------
sub HandleBuildFromPref($$)
{
my($build_array, $name) = @_;
my($setting) = 0;
my($index);
foreach $index (@$build_array)
{
if ($index->[0] eq $name) {
$setting = 1;
}
$index->[1] = $setting;
}
if ($setting == 1) {
print "Building from $name onwards, as specified by prefs\n";
} else {
printf "Failed to find buildfrom setting '$name'\n";
}
}
#-------------------------------------------------------------------------------
#
# ReadPrefsFile
#
#-------------------------------------------------------------------------------
sub ReadPrefsFile($$$$$)
{
my($file_path, $build_flags, $options_flags, $filepath_flags, $create_if_missing) = @_;
local(*PREFS_FILE);
if (open(PREFS_FILE, "< $file_path"))
{
print "Reading build prefs from '$file_path'\n";
while (<PREFS_FILE>)
{
my($line) = $_;
chomp($line);
if ($line =~ /^\#/ || $line =~ /^\s*$/) { # ignore comments and empty lines
next;
}
if (($line =~ /^\s*([^#\s]+)\s+([^#\s]+)\s+\"(.+)\"(\s+#.+)?/) ||
($line =~ /^\s*([^#\s]+)\s+([^#\s]+)\s+\'(.+)\'(\s+#.+)?/) ||
($line =~ /^\s*([^#\s]+)\s+([^#\s]+)\s+([^#\s]+)(\s+#.+)?/))
{
my($array_name) = $1;
my($option_name) = $2;
my($option_value) = $3;
# print "Read '$array_name' '$option_name' '$option_value'\n";
if ($array_name eq "build")
{
HandlePrefSet($build_flags, $option_name, $option_value, "Build");
}
elsif ($array_name eq "options")
{
HandlePrefSet($options_flags, $option_name, $option_value, "Options");
}
elsif ($array_name eq "filepath" && $option_name && $option_value)
{
HandlePrefSet($filepath_flags, $option_name, $option_value, "Filepath");
}
else
{
print "Unknown pref option at $line\n";
}
}
elsif ($line =~ /^\s*buildfrom\s+([^#\s]+)(\s+#.+)?/)
{
my($build_start) = $1;
HandleBuildFromPref($build_flags, $build_start);
}
elsif ($line =~ /^\s*([^#\s]+)\s+([^#\s]+)(\s+#.+)?/)
{
my($build_var) = $1;
my($var_setting) = $2;
print "Setting \$main::$build_var to $var_setting\n";
eval "\$main::$build_var = \"$var_setting\"";
}
else
{
print "Unrecognized input line at $line\n";
}
}
close(PREFS_FILE);
}
elsif ($create_if_missing)
{
print "No prefs file found at $file_path; using defaults\n";
my($folder_path) = $file_path;
$folder_path =~ s/[^:]+$//;
mkpath($folder_path);
WriteDefaultPrefsFile($file_path);
}
}
#-------------------------------------------------------------------------------
#
# ReadMozUserPrefs
#
#-------------------------------------------------------------------------------
sub ReadMozUserPrefs($$$$)
{
my($prefs_file_name, $build_flags, $options_flags, $filepath_flags) = @_;
if ($prefs_file_name eq "") { return; }
# if local prefs exist, just use those. Othewise, look in the prefs folder
if (-e $prefs_file_name)
{
# read local prefs
ReadPrefsFile($prefs_file_name, $build_flags, $options_flags, $filepath_flags, 0);
}
else
{
# first read prefs folder prefs
my($prefs_path) = GetPrefsFolder();
$prefs_path .= ":$prefs_file_name";
ReadPrefsFile($prefs_path, $build_flags, $options_flags, $filepath_flags, 1);
}
}
1;

View File

@@ -1,932 +0,0 @@
#!/usr/bin/perl
#
# The contents of this file are subject to the Netscape Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
# Simon Fraser <sfraser@netscape.com>
#
package Moz::ProjectXML;
require 5.004;
require Exporter;
use strict;
use Exporter;
use Cwd;
use XML::DOM;
use vars qw(@ISA @EXPORT);
@ISA = qw(Exporter);
@EXPORT = qw(
ParseXMLDocument
DisposeXMLDocument
WriteXMLDocument
CleanupPro5XML
GetTargetsList
CloneTarget
SetAsSharedLibraryTarget
SetAsStaticLibraryTarget
AddTarget
RemoveTarget
GetTargetSetting
SetTargetSetting
getChildElementTextContents
);
#--------------------------------------------------------------------------------------------------
# A module for reading, manipulating, and writing XML-format CodeWarrior project files.
#
# Sample usage:
#
# use ProjectXML;
#
# my $doc = ProjectXML::ParseXMLDocument("Test.mcp.xml");
# ProjectXML::CloneTarget($doc, "Test.shlb", "Test.lib");
# ProjectXML::SetAsStaticLibraryTarget($doc, "Test.lib", "TestOutput.lib");
# ProjectXML::WriteXMLDocument($doc, "Test_out.xml");
# ProjectXML::DisposeXMLDocument($doc);
#
#--------------------------------------------------------------------------------------------------
#//--------------------------------------------------------------------------------------------------
#// ParseXMLDocument
#// Note that the caller must call DisposeXMLDocument on the returned doc
#//--------------------------------------------------------------------------------------------------
sub ParseXMLDocument($)
{
my($doc_path) = @_;
my $parser = new XML::DOM::Parser(ErrorContext => 2);
my $doc = $parser->parsefile($doc_path);
return $doc;
}
#//--------------------------------------------------------------------------------------------------
#// DisposeXMLDocument
#// Needed to avoid memory leaks - cleanup circular references for garbage collection
#//--------------------------------------------------------------------------------------------------
sub DisposeXMLDocument($)
{
my($doc) = @_;
$doc->dispose();
}
#//--------------------------------------------------------------------------------------------------
#// WriteXMLDocument
#//--------------------------------------------------------------------------------------------------
sub _pro5_tag_compression($$)
{
return 1; # Pro 5 is broken and can't import XML with <foo/> style tags
}
sub _pro6plus_tag_compression($$)
{
return 0; # Pro 6 can deal with empty XML tags like <foo/>
}
sub WriteXMLDocument($$$)
{
my($doc, $file_path, $ide_version) = @_;
if ($ide_version eq "4.0")
{
XML::DOM::setTagCompression(\&_pro5_tag_compression);
}
else
{
XML::DOM::setTagCompression(\&_pro6plus_tag_compression);
}
$doc->printToFile($file_path);
}
#//--------------------------------------------------------------------------------------------------
#// CleanupPro5XML
#// XML Projects exported by Pro 5 contain garbage data under the MWMerge_MacOS_skipResources
#// setting. This routine cleans this up, saving the result to a new file
#//--------------------------------------------------------------------------------------------------
sub CleanupPro5XML($$)
{
my($xml_path, $out_path) = @_;
local(*XML_FILE);
open(XML_FILE, "< $xml_path") || die "Error: failed to open file $xml_path\n";
local(*CLEANED_FILE);
open(CLEANED_FILE, "> $out_path") || die "Error: failed to open file $out_path for writing\n";
my $in_skip_resources_settings = 0;
while(<XML_FILE>)
{
my($line) = $_;
if ($line =~ /^<\?codewarrior/) # is processing inst line
{
my $test_line = $line;
chomp($test_line);
my $out_line = $test_line;
if ($test_line =~ /^<\?codewarrior\s+exportversion=\"(.+)\"\s+ideversion=\"(.+)\"\s*\?>$/)
{
my $export_version = $1;
my $ide_version = $2;
$ide_version = "4.0_mozilla"; # pseudo IDE version so we know we touched it
$out_line = "<?codewarrior exportversion=\"".$export_version."\" ideversion=\"".$ide_version."\"?>";
}
print CLEANED_FILE "$out_line\n";
next;
}
if ($line =~ /MWMerge_MacOS_skipResources/)
{
$in_skip_resources_settings = 1;
print CLEANED_FILE "$line";
}
elsif($in_skip_resources_settings && $line =~ /<!-- Settings for/)
{
# leaving bad settings lines. Write closing tag
print CLEANED_FILE " <!-- Corrupted setting entries removed by script -->\n";
print CLEANED_FILE " </SETTING>\n\n";
print CLEANED_FILE "$line";
$in_skip_resources_settings = 0;
}
elsif (!$in_skip_resources_settings)
{
print CLEANED_FILE "$line";
}
}
close(XML_FILE);
close(CLEANED_FILE);
}
#--------------------------------------------------------------------------------------------------
# SniffProjectXMLIDEVersion
#
#--------------------------------------------------------------------------------------------------
sub SniffProjectXMLIDEVersion($)
{
my($xml_path) = @_;
my $found_version = "";
local(*XML_FILE);
open(XML_FILE, "< $xml_path") || die "Error: failed to open file $xml_path\n";
while(<XML_FILE>)
{
my($line) = $_;
chomp($line);
if ($line =~ /^<\?codewarrior/) # is processing inst line
{
unless ($line =~ /^<\?codewarrior\s+exportversion=\"(.+)\"\s+ideversion=\"(.+)\"\s*\?>$/)
{
die "Error: Failed to find ideversion in $xml_path in line $line\n";
}
my $export_version = $1;
my $ide_version = $2;
$found_version = $ide_version;
last;
}
}
close(XML_FILE);
return $found_version;
}
#//--------------------------------------------------------------------------------------------------
#// GetTargetsList
#// Returns an array of target names
#//--------------------------------------------------------------------------------------------------
sub GetTargetsList($)
{
my($doc) = @_;
my $nodes = $doc->getElementsByTagName("TARGET");
my $n = $nodes->getLength;
my @target_names;
for (my $i = 0; $i < $n; $i++)
{
my ($node) = $nodes->item($i);
my($target_name) = getChildElementTextContents($node, "NAME");
push(@target_names, $target_name);
}
return @target_names;
}
#//--------------------------------------------------------------------------------------------------
#// CloneTarget
#// Clone the named target, renaming it to 'new_name'
#//--------------------------------------------------------------------------------------------------
sub CloneTarget($$$)
{
my($doc, $target_name, $new_name) = @_;
my $target_node = getTargetNode($doc, $target_name);
# clone here
my $target_clone = $target_node->cloneNode(1); # deep clone
# -- munge target settings --
# set the target name field
setChildElementTextContents($doc, $target_clone, "NAME", $new_name);
# set the targetname pref
setTargetNodeSetting($doc, $target_clone, "Targetname", $new_name);
# -- insert new target subtree --
my $target_list = $target_node->getParentNode();
$target_list->appendChild($target_clone);
# -- now add to targetorder --
my (@target_order_nodes) = getChildOfDocument($doc, "TARGETORDER");
my $target_order = @target_order_nodes[0];
my $new_order = $doc->createElement("ORDEREDTARGET");
my $order_name = $doc->createElement("NAME");
$new_order->appendChild($order_name);
setChildElementTextContents($doc, $new_order, "NAME", $new_name);
$target_order->appendChild($new_order);
}
#//--------------------------------------------------------------------------------------------------
#// SetAsSharedLibraryTarget
#//
#//--------------------------------------------------------------------------------------------------
sub SetAsSharedLibraryTarget($$$)
{
my($doc, $target_name, $output_name) = @_;
my $target_node = getTargetNode($doc, $target_name);
setTargetNodeSetting($doc, $target_node, "MWProject_PPC_type", "SharedLibrary");
setTargetNodeSetting($doc, $target_node, "MWProject_PPC_filetype", "1936223330"); #'shlb'
setTargetNodeSetting($doc, $target_node, "MWProject_PPC_outfile", $output_name);
}
#//--------------------------------------------------------------------------------------------------
#// AddFileToTarget
#//
#// Add a file to the specified target(s).
#//
#//--------------------------------------------------------------------------------------------------
sub AddFileToTarget($$$)
{
my($doc, $target_list, $file_name) = @_;
# the file must be added in 3 places:
# 1. in <TARGET><FILELIST><FILE> (with linkage flags if necessary)
# 2. in <TARGET><LINKORDER><FILEREF>
# 3. in <GROUPLIST><GROUP><FILEREF>
die "Write me\n";
}
#//--------------------------------------------------------------------------------------------------
#// RemoveFileFromTarget
#//
#// Remove a file from the specified target, removing it from the entire project
#// if no other targets reference it.
#//
#//--------------------------------------------------------------------------------------------------
sub RemoveFileFromTarget($$$)
{
my($doc, $target_node, $file_name) = @_;
# the file must be removed in 3 places:
# 1. in <TARGET><FILELIST><FILE>
# 2. in <TARGET><LINKORDER><FILEREF>
# 3. in <GROUPLIST><GROUP><FILEREF>
# first, remove from <FILELIST>
my $filelist_node = getFirstChildElement($target_node, "FILELIST");
unless ($filelist_node) { die "Error: failed to find FILELIST node\n"; }
my $file_node = getChildNodeByGrandchildContents($doc, $filelist_node, "FILE", "PATH", $file_name);
unless ($file_node) { return; }
$filelist_node->removeChild($file_node);
# next, remove from <LINKORDER>
my $linkorder_node = getFirstChildElement($target_node, "LINKORDER");
unless ($linkorder_node) { die "Error: failed to find LINKORDER node\n"; }
my $fileref_node = getChildNodeByGrandchildContents($doc, $linkorder_node, "FILEREF", "PATH", $file_name);
unless ($fileref_node) { die "Error: link order node for file $file_name not found\n"; }
$linkorder_node->removeChild($fileref_node);
# last, remove from <GROUPLIST>
# <GROUPLIST> is cross-target, so we have to be careful here.
my $grouplist_node = getChildOfDocument($doc, "GROUPLIST");
unless ($grouplist_node) { die "Error: failed to find GROUPLIST node\n"; }
# if the file isn't in any other targets, remove it from the groups
if (!GetFileInUse($doc, $file_name))
{
print "File $file_name is in no other targest. Removing from project\n";
my @group_nodes;
getChildElementsOfType($doc, $grouplist_node, "GROUP", \@group_nodes);
my $group_node;
foreach $group_node (@group_nodes)
{
my @fileref_nodes;
getChildElementsOfType($doc, $group_node, "FILEREF", \@fileref_nodes);
my $fileref_node;
foreach $fileref_node (@fileref_nodes)
{
my $path_name = getChildElementTextContents($fileref_node, "PATH");
if ($path_name eq $file_name)
{
print "Removing $file_name from project group list\n";
$group_node->removeChild($fileref_node);
last;
}
}
# can a file appear in more than one group?
}
}
}
#//--------------------------------------------------------------------------------------------------
#// SetAsStaticLibraryTarget
#//
#//--------------------------------------------------------------------------------------------------
sub SetAsStaticLibraryTarget($$$)
{
my($doc, $target_name, $output_name) = @_;
my $target_node = getTargetNode($doc, $target_name);
setTargetNodeSetting($doc, $target_node, "MWProject_PPC_type", "Library");
setTargetNodeSetting($doc, $target_node, "MWProject_PPC_filetype", "1061109567"); #'????'
setTargetNodeSetting($doc, $target_node, "MWProject_PPC_outfile", $output_name);
# static targets don't need any library linkage, so we can remove linkage
# with all .shlb and .Lib files.
my(@obsolete_files) = ("NSStdLibStubs", "InterfacesStubs", "InterfaceLib", "InternetConfigLib");
print " Removing libraries etc. from target\n";
# get all files in target
my @target_files = GetTargetFilesList($doc, $target_name);
my $target_file;
foreach $target_file (@target_files)
{
if ($target_file =~ /(\.shlb|\.lib|\.Lib|\.o|\.exp)$/)
{
RemoveFileFromTarget($doc, $target_node, $target_file);
}
}
print " Removing stub libraries from target\n";
# then remove files with known names
my $obs_file;
foreach $obs_file (@obsolete_files)
{
RemoveFileFromTarget($doc, $target_node, $obs_file);
}
}
#//--------------------------------------------------------------------------------------------------
#// AddTarget
#//
#//--------------------------------------------------------------------------------------------------
sub AddTarget($$)
{
my($doc, $target_name) = @_;
die "Write me\n";
}
#//--------------------------------------------------------------------------------------------------
#// RemoveTarget
#//
#//--------------------------------------------------------------------------------------------------
sub RemoveTarget($$)
{
my($doc, $target_name) = @_;
die "Write me\n";
}
#//--------------------------------------------------------------------------------------------------
#// GetTargetSetting
#// Get the value for the specified setting in the specified target
#//--------------------------------------------------------------------------------------------------
sub GetTargetSetting($$$)
{
my($doc, $target_name, $setting_name) = @_;
my $target_node = getTargetNode($doc, $target_name);
return getTargetNodeSetting($target_node, "VALUE");
}
#//--------------------------------------------------------------------------------------------------
#// SetTargetSetting
#// Set the value for the specified setting in the specified target
#//--------------------------------------------------------------------------------------------------
sub SetTargetSetting($$$$)
{
my($doc, $target_name, $setting_name, $new_value) = @_;
my $target_node = getTargetNode($doc, $target_name);
setTargetNodeSetting($doc, $target_node, "VALUE", $new_value);
}
#//--------------------------------------------------------------------------------------------------
#// GetTargetFilesList
#// Return an array of the files in the target (in filelist order)
#//--------------------------------------------------------------------------------------------------
sub GetTargetFilesList($$)
{
my($doc, $target_name) = @_;
my $target_node = getTargetNode($doc, $target_name);
my @files_list;
my $filelist_node = getFirstChildElement($target_node, "FILELIST");
unless ($filelist_node) { die "Error: failed to find FILELIST node\n"; }
my @file_nodes;
getChildElementsOfType($doc, $filelist_node, "FILE", \@file_nodes);
my $node;
foreach $node (@file_nodes)
{
my $file_name = getChildElementTextContents($node, "PATH");
push(@files_list, $file_name);
}
return @files_list;
}
#//--------------------------------------------------------------------------------------------------
#// FileIsInTarget
#//
#//--------------------------------------------------------------------------------------------------
sub FileIsInTarget($$$)
{
my($doc, $file_name, $target_name) = @_;
my $target_node = getTargetNode($doc, $target_name);
unless ($target_node) { die "Error: no target found called $target_name\n"; }
my $file_node = GetTargetFileNode($doc, $target_node, $file_name);
if ($file_node) {
return 1;
}
return 0;
}
#//--------------------------------------------------------------------------------------------------
#// GetFileTargetsList
#// Return an array of the targets that a file is in (expensive)
#//--------------------------------------------------------------------------------------------------
sub GetFileTargetsList($$)
{
my ($doc, $file_name) = @_;
my @target_list;
my @targets = GetTargetsList($doc);
my $target;
foreach $target (@targets)
{
if (FileIsInTarget($doc, $file_name, $target))
{
push(@target_list, $target);
}
}
return @target_list;
}
#//--------------------------------------------------------------------------------------------------
#// GetTargetFileNode
#//
#//--------------------------------------------------------------------------------------------------
sub GetTargetFileNode($$$)
{
my($doc, $target_node, $file_name) = @_;
my $filelist_node = getFirstChildElement($target_node, "FILELIST");
unless ($filelist_node) { die "Error: failed to find FILELIST node\n"; }
my $file_node = getChildNodeByGrandchildContents($doc, $filelist_node, "FILE", "PATH", $file_name);
return $file_node;
}
#//--------------------------------------------------------------------------------------------------
#// GetFileInUse
#// Return true if the file is used by any target
#//--------------------------------------------------------------------------------------------------
sub GetFileInUse($$)
{
my($doc, $file_name) = @_;
my $targetlist_node = getChildOfDocument($doc, "TARGETLIST");
my $target_node = $targetlist_node->getFirstChild();
while ($target_node)
{
if ($target_node->getNodeTypeName eq "ELEMENT_NODE" &&
$target_node->getTagName() eq "TARGET")
{
# if this is a target node
my $file_node = GetTargetFileNode($doc, $target_node, $file_name);
if ($file_node) {
return 1; # found it
}
}
$target_node = $target_node->getNextSibling();
}
# not found
return 0;
}
#//--------------------------------------------------------------------------------------------------
#// getChildOfDocument
#//--------------------------------------------------------------------------------------------------
sub getChildOfDocument($$)
{
my($doc, $child_type) = @_;
return getFirstChildElement($doc->getDocumentElement(), $child_type);
}
#//--------------------------------------------------------------------------------------------------
#// getFirstChildElement
#//--------------------------------------------------------------------------------------------------
sub getFirstChildElement($$)
{
my($node, $element_name) = @_;
my $found_node;
unless ($node) { die "getFirstChildElement called with empty node\n"; }
#look for the first "element_name" child
my $child_node = $node->getFirstChild();
while ($child_node)
{
if ($child_node->getNodeTypeName eq "ELEMENT_NODE" &&
$child_node->getTagName() eq $element_name)
{
$found_node = $child_node;
last;
}
$child_node = $child_node->getNextSibling();
}
return $found_node;
}
#//--------------------------------------------------------------------------------------------------
#// getChildElementsOfType
#//
#// Return an array of refs to child nodes of the given type
#//--------------------------------------------------------------------------------------------------
sub getChildElementsOfType($$$$)
{
my($doc, $node, $child_type, $array_ref) = @_;
my $child_node = $node->getFirstChild();
while ($child_node)
{
if ($child_node->getNodeTypeName eq "ELEMENT_NODE" &&
$child_node->getTagName() eq $child_type)
{
push(@$array_ref, $child_node);
}
$child_node = $child_node->getNextSibling();
}
}
#//--------------------------------------------------------------------------------------------------
#// getChildElementTextContents
#//--------------------------------------------------------------------------------------------------
#
# Given <FOOPY><NERD>Hi!</NERD></FOOPY>, where $node is <FOOPY>,
# returns "Hi!". If > 1 <NERD> node, returns the contents of the first.
#
sub getChildElementTextContents($$)
{
my($node, $tag_name) = @_;
my $first_element = getFirstChildElement($node, $tag_name);
my $text_node = $first_element->getFirstChild();
my $text_contents = "";
# concat adjacent text nodes
while ($text_node)
{
if ($text_node->getNodeTypeName() ne "TEXT_NODE")
{
last;
}
$text_contents = $text_contents.$text_node->getData();
$text_node = $text_node->getNextSibling();
}
return $text_contents;
}
#//--------------------------------------------------------------------------------------------------
#// setChildElementTextContents
#//--------------------------------------------------------------------------------------------------
sub setChildElementTextContents($$$$)
{
my($doc, $node, $tag_name, $contents_text) = @_;
my $first_element = getFirstChildElement($node, $tag_name);
my $new_text_node = $doc->createTextNode($contents_text);
# replace all child elements with a text element
removeAllChildren($first_element);
$first_element->appendChild($new_text_node);
}
#//--------------------------------------------------------------------------------------------------
#// getChildNodeByContents
#//
#// Consider <foo><bar><baz>Foopy</baz></bar><bar><baz>Loopy</baz></bar></foo>
#// This function, when called with getChildNodeByContents($foonode, "bar", "baz", "Loopy")
#// returns the second <bar> node.
#//--------------------------------------------------------------------------------------------------
sub getChildNodeByGrandchildContents($$$$$)
{
my($doc, $node, $child_type, $gc_type, $gc_contents) = @_; # gc = grandchild
my $found_node;
my $child_node = $node->getFirstChild();
while ($child_node)
{
if ($child_node->getNodeTypeName eq "ELEMENT_NODE" &&
$child_node->getTagName() eq $child_type)
{
# check for a child of this node of type
my $child_contents = getChildElementTextContents($child_node, $gc_type);
if ($child_contents eq $gc_contents)
{
$found_node = $child_node;
last;
}
}
$child_node = $child_node->getNextSibling();
}
return $found_node;
}
#//--------------------------------------------------------------------------------------------------
#// getTargetNode
#//--------------------------------------------------------------------------------------------------
sub getTargetNode($$)
{
my($doc, $target_name) = @_;
my $targetlist_node = getChildOfDocument($doc, "TARGETLIST");
return getChildNodeByGrandchildContents($doc, $targetlist_node, "TARGET", "NAME", $target_name);
}
#//--------------------------------------------------------------------------------------------------
#// getTargetNamedSettingNode
#//--------------------------------------------------------------------------------------------------
sub getTargetNamedSettingNode($$)
{
my($target_node, $setting_name) = @_;
my $setting_node;
my $settinglist_node = getFirstChildElement($target_node, "SETTINGLIST");
my $child_node = $settinglist_node->getFirstChild();
while ($child_node)
{
if ($child_node->getNodeTypeName ne "ELEMENT_NODE")
{
$child_node = $child_node->getNextSibling();
next;
}
if ($child_node->getTagName() eq "SETTING")
{
my $set_name = getChildElementTextContents($child_node, "NAME");
if ($set_name eq $setting_name)
{
$setting_node = $child_node;
last;
}
}
$child_node = $child_node->getNextSibling();
}
return $setting_node;
}
#//--------------------------------------------------------------------------------------------------
#// getTargetNodeSetting
#//--------------------------------------------------------------------------------------------------
sub getTargetNodeSetting($$)
{
my($target_node, $setting_name) = @_;
my $setting_node = getTargetNamedSettingNode($target_node, $setting_name);
return getChildElementTextContents($setting_node, "VALUE");
}
#//--------------------------------------------------------------------------------------------------
#// setTargetNodeSetting
#//--------------------------------------------------------------------------------------------------
sub setTargetNodeSetting($$$$)
{
my($doc, $target_node, $setting_name, $new_value) = @_;
my $setting_node = getTargetNamedSettingNode($target_node, $setting_name);
setChildElementTextContents($doc, $setting_node, "VALUE", $new_value);
}
#//--------------------------------------------------------------------------------------------------
#// elementInArray
#//--------------------------------------------------------------------------------------------------
sub elementInArray($$)
{
my($element, $array) = @_;
my $test;
foreach $test (@$array)
{
if ($test eq $element) {
return 1;
}
}
return 0;
}
#//--------------------------------------------------------------------------------------------------
#// removeAllChildren
#//--------------------------------------------------------------------------------------------------
sub removeAllChildren($)
{
my($node) = @_;
my $child_node = $node->getFirstChild();
while ($child_node)
{
$node->removeChild($child_node);
$child_node = $node->getFirstChild();
}
}
#//--------------------------------------------------------------------------------------------------
#// dumpNodeData
#//--------------------------------------------------------------------------------------------------
sub dumpNodeData($)
{
my($node) = @_;
unless ($node) { die "Null node passed to dumpNodeData\n"; }
print "Dumping node $node\n";
my($node_type) = $node->getNodeTypeName();
if ($node_type eq "ELEMENT_NODE")
{
my($node_name) = $node->getTagName();
print "Element $node_name\n";
}
elsif ($node_type eq "TEXT_NODE")
{
my($node_data) = $node->getData;
# my(@node_vals) = unpack("C*", $node_data);
print "Text '$node_data'\n"; # may contain LF chars
}
else
{
print "Node $node_type\n";
}
}
#//--------------------------------------------------------------------------------------------------
#// dumpNodeTree
#//--------------------------------------------------------------------------------------------------
sub dumpNodeTree($)
{
my($node) = @_;
my($child_node) = $node->getFirstChild();
unless ($child_node) { return; }
# recurse
dumpNodeData($child_node);
# then go through child nodes
while ($child_node)
{
dumpNodeTree($child_node);
$child_node = $child_node->getNextSibling();
}
}
1;

View File

@@ -1,90 +0,0 @@
#-------------------------------------------------------------------------------
# These 3 lists are the 'master lists' to control what gets built.
#
# Ordering in these arrays is important; it has to reflect the order in
# which the build occurs.
#
# Setting containing spaces must be quoted with double quotes.
#-------------------------------------------------------------------------------
build_flags
all 1
pull 0
dist 0
config 0
xpidl 0
idl 0
stubs 0
runtime 0
common 0
imglib 0
libimg2 0
necko 0
security 0
browserutils 0
intl 0
nglayout 0
accessiblity 0
editor 0
embedding 0
viewer 0
xpapp 0
extensions 0
plugins 0
mailnews 0
apprunner 0
resources 0
options_flags
pull_by_date 0
chrome_jars 1
chrome_files 0
use_jars 1
transformiix 1
mathml 0 MOZ_MATHML
svg 0 MOZ_SVG
# svg requires libart, which is an lgpl library. You need to pull it
# explicitly.
libart_lgpl 0
mng 1
ldap 1 MOZ_LDAP_XPCOM
ldap_experimental 0 MOZ_LDAP_XPCOM_EXPERIMENTAL
xmlextras 1
wsp 0 MOZ_WSP
inspector 1
mailextras 1
xptlink 0
psm 0 MOZ_PSM
embedding_test 1
embedding_chrome 0
embedding_xulprefs 0
embedding_xulsecurity 0
carbon 0 TARGET_CARBON
useimg2 1 USE_IMG2
lowmem 0 MOZ_MAC_LOWMEM
accessible 1 ACCESSIBILITY
bidi 1 IBMBIDI
p3p 0
jsd 1
venkman 1
moz_logging 1 MOZ_LOGGING
chatzilla 1
content_packs 1
xml_rpc 1
cview 1
help 1
timeline 0 MOZ_TIMELINE
static_build 0 MOZ_STATIC_COMPONENT_LIBS
string_debug 0 DEBUG_STRING
string_stats 0 DEBUG_STRING_STATS
xpctools 0 XPC_TOOLS_SUPPORT
smime 1
mdn 1
print_preview 1 NS_PRINT_PREVIEW
moz_xul 1 MOZ_XUL
filepath_flags
idepath ":CodeWarrior IDE Path.txt"
sessionpath ":Mozilla session path.txt"
buildlogfilepath ":Build Logs:Mozilla build log.txt" # this is a path
scriptlogfilepath ":Build Logs:Mozilla script log.txt"

File diff suppressed because it is too large Load Diff

View File

@@ -1,22 +0,0 @@
# List of modules to check out. Format is
# module, (tag), (date)
# where tag and date are optional (non-trailing commas are required)
#
# Examples:
# mozilla/nsprpub, NSPRPUB_CLIENT_TAG
# mozilla/gc, , 10/25/2000 12:00:00
#
mozilla/nsprpub, NETSCAPE_7_0_RTM
mozilla/security/nss, NETSCAPE_7_0_RTM
mozilla/security/manager, NETSCAPE_7_0_RTM
mozilla/accessible, NETSCAPE_7_0_RTM
mozilla/directory/c-sdk, NETSCAPE_7_0_RTM
mozilla/lib/mac/Instrumentation, NETSCAPE_7_0_RTM
mozilla/gfx2, NETSCAPE_7_0_RTM
mozilla/modules/libpr0n, NETSCAPE_7_0_RTM
SeaMonkeyAll, NETSCAPE_7_0_RTM
## You need this if you want to be able to use SVG
## Note that this library is under the LGPL, not the MPL
#mozilla/other-licenses/libart_lgpl

View File

@@ -1,79 +0,0 @@
#!perl
#
# The contents of this file are subject to the Netscape Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
# Simon Fraser <sfraser@netscape.com>
#
require 5.004;
use strict;
use Cwd;
use Moz::BuildUtils;
use Moz::BuildCore;
#-------------------------------------------------------------
# Where have the build options gone?
#
# The various build flags have been centralized into one place.
# The master list of options is in MozBuildFlags.txt. However,
# you should never need to edit that file, or this one.
#
# To customize what gets built, or where to start the build,
# edit the $prefs_file_name file in
# System Folder:Preferences:Mozilla build prefs:
# Documentation is provided in that file.
#-------------------------------------------------------------
my($prefs_file_name) = "Mozilla pull prefs";
#-------------------------------------------------------------
# hashes to hold build options
#-------------------------------------------------------------
my(%build);
my(%options);
my(%filepaths);
my(%optiondefines);
# Hash of input files for this build. Eventually, there will be
# input files for manifests, and projects too.
my(%inputfiles) = (
"buildflags", "MozillaBuildFlags.txt",
"checkoutdata", "MozillaCheckoutList.txt",
"buildprogress", "",
"buildmodule", "MozillaBuildList.pm",
"checkouttime", "Mozilla last checkout"
);
#-------------------------------------------------------------
# end build hashes
#-------------------------------------------------------------
# set the build root directory, which is the the dir above mozilla
SetupBuildRootDir(":mozilla:build:mac:build_scripts");
# Set up all the flags on $main::, like DEBUG, CARBON etc.
# Override the defaults using the preferences files.
SetupDefaultBuildOptions(0, ":mozilla:dist:viewer:", "");
my($do_checkout) = 1;
my($do_build) = 0;
RunBuild($do_checkout, $do_build, \%inputfiles, $prefs_file_name);

View File

@@ -1,511 +0,0 @@
# The contents of this file are subject to the Netscape Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
DEPTH=.
!if !defined(MOZ_TOP)
#enable builds from changed top level directories
MOZ_TOP=mozilla
!endif
MOZ_SRC_FLIPPED = $(MOZ_SRC:\=/)
MOZ_DIST_FLIPPED = $(MOZ_SRC_FLIPPED)/mozilla/dist
!ifdef MOZ_DEBUG
MOZ_OBJDIR = WIN32_D.OBJ
!else
MOZ_OBJDIR = WIN32_O.OBJ
!endif
#
# Command macro defines
#
#//------------------------------------------------------------------------
#// Figure out how to do the pull.
#//------------------------------------------------------------------------
# uncomment these, modify branch tag, and check in to branch for milestones
MOZ_BRANCH=NETSCAPE_7_0_RTM
NSPR_CO_TAG=NETSCAPE_7_0_RTM
PSM_CO_TAG=NETSCAPE_7_0_RTM
NSS_CO_TAG=NETSCAPE_7_0_RTM
LDAPCSDK_CO_TAG=NETSCAPE_7_0_RTM
ACCESSIBLE_CO_TAG=NETSCAPE_7_0_RTM
IMGLIB2_CO_TAG=NETSCAPE_7_0_RTM
GFX2_CO_TAG=NETSCAPE_7_0_RTM
!ifdef MOZ_BRANCH
CVS_BRANCH=-r $(MOZ_BRANCH)
!endif
!ifdef MOZ_DATE
CVS_BRANCH=$(CVS_BRANCH) -D "$(MOZ_DATE)"
!endif
# default pull is "quiet" but it can be overridden with MOZ_CVS_VERBOSE
!ifndef MOZ_CVS_VERBOSE
CVS_FLAGS=-q
!endif
# honor any user-defined CVS flags
!ifdef MOZ_CVS_FLAGS
CVS_FLAGS=$(CVS_FLAGS) $(MOZ_CVS_FLAGS)
!endif
# let's be explicit about CVSROOT... some windows cvs clients
# are too stupid to correctly work without the -d option
#
# if they are too stupid, they should fail. I am
# commenting this out because this does not work
# under 4nt. (%'s are evaluted differently)
#
# If it breaks you, mail dougt@netscape.com
# and leaf@mozilla.org
#
!if 0
!if defined(CVSROOT)
CVS_FLAGS=$(CVS_FLAGS) -d "$(CVSROOT)"
!endif
!endif
!ifndef MOZ_CO_FLAGS
MOZ_CO_FLAGS = -P
!endif
CVSCO = cvs $(CVS_FLAGS) co $(MOZ_CO_FLAGS) $(CVS_BRANCH)
#//------------------------------------------------------------------------
#// Figure out how to pull NSPR.
#// If no NSPR_CO_TAG is specified, use the default static tag
#//------------------------------------------------------------------------
!ifndef NSPR_CO_FLAGS
NSPR_CO_FLAGS=$(MOZ_CO_FLAGS)
!endif
NSPR_CO_FLAGS=$(NSPR_CO_FLAGS) $(CVS_BRANCH)
CVSCO_NSPR = cvs $(CVS_FLAGS) co $(NSPR_CO_FLAGS)
#//------------------------------------------------------------------------
#// Figure out how to pull NSS and PSM libs.
#// If no NSS_CO_TAG or PSM_CO_TAG is specified, use the default static tag
#//------------------------------------------------------------------------
!ifndef NSS_CO_FLAGS
NSS_CO_FLAGS=$(MOZ_CO_FLAGS)
!endif
NSS_CO_FLAGS=$(NSS_CO_FLAGS) $(CVS_BRANCH)
CVSCO_NSS = cvs $(CVS_FLAGS) co $(NSS_CO_FLAGS)
!ifndef PSM_CO_FLAGS
PSM_CO_FLAGS=$(MOZ_CO_FLAGS)
!endif
PSM_CO_FLAGS=$(PSM_CO_FLAGS) $(CVS_BRANCH)
CVSCO_PSM = cvs $(CVS_FLAGS) co $(PSM_CO_FLAGS)
#//------------------------------------------------------------------------
#// Figure out how to pull LDAP C SDK client libs.
#// If no LDAPCSDK_CO_TAG is specified, use the default tag
#//------------------------------------------------------------------------
!ifndef LDAPCSDK_CO_FLAGS
LDAPCSDK_CO_FLAGS=$(MOZ_CO_FLAGS)
!endif
LDAPCSDK_CO_FLAGS=$(LDAPCSDK_CO_FLAGS) $(CVS_BRANCH)
CVSCO_LDAPCSDK = cvs $(CVS_FLAGS) co $(LDAPCSDK_CO_FLAGS)
#//------------------------------------------------------------------------
#// Figure out how to pull accessibility libs.
#// If no ACCESSIBLE_CO_TAG is specified, use the default tag
#//------------------------------------------------------------------------
!ifndef ACCESSIBLE_CO_FLAGS
ACCESSIBLE_CO_FLAGS=$(MOZ_CO_FLAGS)
!endif
ACCESSIBLE_CO_FLAGS=$(ACCESSIBLE_CO_FLAGS) $(CVS_BRANCH)
CVSCO_ACCESSIBLE = cvs $(CVS_FLAGS) co $(ACCESSIBLE_CO_FLAGS)
#//------------------------------------------------------------------------
#// Figure out how to pull new image library.
#// If no IMGLIB2_CO_TAG is specified, use the default tag
#//------------------------------------------------------------------------
!ifndef IMGLIB2_CO_FLAGS
IMGLIB2_CO_FLAGS=$(MOZ_CO_FLAGS)
!endif
IMGLIB2_CO_FLAGS=$(IMGLIB2_CO_FLAGS) $(CVS_BRANCH)
CVSCO_IMGLIB2 = cvs $(CVS_FLAGS) co $(IMGLIB2_CO_FLAGS)
#//------------------------------------------------------------------------
#// Figure out how to pull new image library.
#// If no GFX2_CO_TAG is specified, use the default tag
#//------------------------------------------------------------------------
!ifndef GFX2_CO_FLAGS
GFX2_CO_FLAGS=$(MOZ_CO_FLAGS)
!endif
GFX2_CO_FLAGS=$(GFX2_CO_FLAGS) $(CVS_BRANCH)
CVSCO_GFX2 = cvs $(CVS_FLAGS) co $(GFX2_CO_FLAGS)
#//------------------------------------------------------------------------
#// Figure out how to pull the internal libart
#// (only pulled and built if MOZ_INTERNAL_LIBART_LGPL is set)
#// If no MOZ_INTERNAL_LIBART_CO_TAG is specified, use the default tag
#//------------------------------------------------------------------------
!if defined(MOZ_SVG) && !defined(MOZ_INTERNAL_LIBART_LGPL)
ERR_MESSAGE = ^
You are trying to build Mozilla with SVG support (MOZ_SVG=1), but you ^
haven not specified that mozilla/other-licenses/libart_lgpl should be ^
pulled and built. At the moment Mozilla SVG builds need this patched ^
version of libart. You either need to disable SVG support (unset MOZ_SVG) ^
or enable pulling and building by setting MOZ_INTERNAL_LIBART_LGPL=1.^
^
If you choose to pull and build libart, note that it is only licensed^
under the terms of the LGPL, not the MPL. (Which is why you have to opt^
in explicitly.)
!endif
!if defined(MOZ_INTERNAL_LIBART_LGPL)
!ifndef MOZ_INTERNAL_LIBART_CO_FLAGS
MOZ_INTERNAL_LIBART_CO_FLAGS=$(MOZ_CO_FLAGS)
!endif
!if "$(MOZ_INTERNAL_LIBART_CO_TAG)" != ""
MOZ_INTERNAL_LIBART_CO_FLAGS=$(MOZ_INTERNAL_LIBART_CO_FLAGS) -r $(MOZ_INTERNAL_LIBART_CO_TAG)
!else
MOZ_INTERNAL_LIBART_CO_FLAGS=$(MOZ_INTERNAL_LIBART_CO_FLAGS) $(CVS_BRANCH)
!endif
CVSCO_MOZ_INTERNAL_LIBART = cvs $(CVS_FLAGS) co $(MOZ_INTERNAL_LIBART_CO_FLAGS)
!endif
## The master target
############################################################
pull_and_build_all: pull_all build_all_dep
## Rules for pulling the source from the cvs repository
############################################################
pull_clobber_and_build_all: pull_all clobber_all build_all
!if !defined(MOZ_INTERNAL_LIBART_LGPL)
pull_all: pull_nspr pull_psm pull_ldapcsdk pull_accessible pull_gfx2 pull_imglib2 pull_seamonkey
!else
pull_all: pull_nspr pull_psm pull_ldapcsdk pull_accessible pull_gfx2 pull_imglib2 pull_moz_internal_libart pull_seamonkey
!endif
pull_nspr: pull_clientmak
cd $(MOZ_SRC)\.
$(CVSCO_NSPR) mozilla/nsprpub
pull_nss:
cd $(MOZ_SRC)\.
$(CVSCO_NSS) mozilla/security/coreconf
$(CVSCO_NSS) mozilla/security/nss
pull_psm: pull_nss
cd $(MOZ_SRC)\.
$(CVSCO_PSM) mozilla/security/manager
$(CVSCO_PSM) mozilla/security/makefile.win
pull_ldapcsdk:
cd $(MOZ_SRC)\.
$(CVSCO_LDAPCSDK) mozilla/directory/c-sdk
pull_accessible:
cd $(MOZ_SRC)\.
$(CVSCO_ACCESSIBLE) mozilla/accessible
pull_gfx2:
cd $(MOZ_SRC)\.
$(CVSCO_GFX2) mozilla/gfx2
pull_imglib2:
cd $(MOZ_SRC)\.
$(CVSCO_IMGLIB2) mozilla/modules/libpr0n
!if defined(MOZ_INTERNAL_LIBART_LGPL)
pull_moz_internal_libart:
cd $(MOZ_SRC)\.
$(CVSCO_MOZ_INTERNAL_LIBART) mozilla/other-licenses/libart_lgpl
!endif
pull_xpconnect: pull_nspr
cd $(MOZ_SRC)\.
$(CVSCO) mozilla/include
$(CVSCO) mozilla/config
$(CVSCO) -l mozilla/js
$(CVSCO) -l mozilla/js/src
$(CVSCO) mozilla/js/src/fdlibm
$(CVSCO) mozilla/js/src/xpconnect
$(CVSCO) mozilla/modules/libreg
$(CVSCO) mozilla/xpcom
$(CVSCO) mozilla/string
# pull either layout only or seamonkey the browser
pull_layout:
cd $(MOZ_SRC)\.
$(CVSCO) RaptorWin
pull_seamonkey: pull_clientmak
cd $(MOZ_SRC)\.
$(CVSCO) SeaMonkeyAll
pull_clientmak:
cd $(MOZ_SRC)\.
$(CVSCO) mozilla/client.mak
############################################################
# nmake has to be hardcoded, or we have to depend on mozilla/config
# being pulled already to figure out what $(NMAKE) should be.
clobber_all: clobber_nspr clobber_ldapcsdk clobber_psm clobber_seamonkey
build_all: build_nspr build_ldapcsdk build_seamonkey
build_all_dep: depend libs
distclean:
@cd $(MOZ_SRC)\$(MOZ_TOP)\directory\c-sdk
gmake -f gmakefile.win distclean MOZ_SRC_FLIPPED=$(MOZ_SRC_FLIPPED)
@cd $(MOZ_SRC)\$(MOZ_TOP)\nsprpub
gmake -f gmakefile.win distclean MOZ_SRC_FLIPPED=$(MOZ_SRC_FLIPPED)
@cd $(MOZ_SRC)\$(MOZ_TOP)
nmake /f client.mak clobber_psm
nmake /f client.mak clobber_seamonkey
clobber_ldapcsdk:
@cd $(MOZ_SRC)\$(MOZ_TOP)\directory\c-sdk
gmake -f gmakefile.win clobber_all MOZ_SRC_FLIPPED=$(MOZ_SRC_FLIPPED) \
SHELL=sh
clobber_nspr:
@cd $(MOZ_SRC)\$(MOZ_TOP)\nsprpub
gmake -f gmakefile.win clobber_all MOZ_SRC_FLIPPED=$(MOZ_SRC_FLIPPED)
clobber_psm:
@cd $(MOZ_SRC)\$(MOZ_TOP)\security
nmake -f makefile.win clobber_all
clobber_xpconnect:
@cd $(MOZ_SRC)\$(MOZ_TOP)\.
-rd /s /q dist
@cd $(MOZ_SRC)\$(MOZ_TOP)\nsprpub
gmake -f gmakefile.win clobber_all MOZ_SRC_FLIPPED=$(MOZ_SRC_FLIPPED)
@cd $(MOZ_SRC)\$(MOZ_TOP)\include
nmake -f makefile.win clobber_all
@cd $(MOZ_SRC)\$(MOZ_TOP)\modules\libreg
nmake -f makefile.win clobber_all
@cd $(MOZ_SRC)\$(MOZ_TOP)\string
nmake -f makefile.win clobber_all
@cd $(MOZ_SRC)\$(MOZ_TOP)\xpcom
nmake -f makefile.win clobber_all
@cd $(MOZ_SRC)\$(MOZ_TOP)\js
nmake -f makefile.win clobber_all
@cd $(MOZ_SRC)\$(MOZ_TOP)\js\src\xpconnect
nmake -f makefile.win clobber_all
clobber_seamonkey:
@cd $(MOZ_SRC)\$(MOZ_TOP)\.
-rd /s /q dist
nmake -f makefile.win clobber_all
depend: export
@cd $(MOZ_SRC)\$(MOZ_TOP)\.
nmake -f makefile.win depend
depend_xpconnect:
@cd $(MOZ_SRC)\$(MOZ_TOP)\include
nmake -f makefile.win depend
@cd $(MOZ_SRC)\$(MOZ_TOP)\modules\libreg
nmake -f makefile.win depend
@cd $(MOZ_SRC)\$(MOZ_TOP)\string
nmake -f makefile.win depend
@cd $(MOZ_SRC)\$(MOZ_TOP)\xpcom
nmake -f makefile.win depend
@cd $(MOZ_SRC)\$(MOZ_TOP)\js\src
nmake -f makefile.win depend
@cd $(MOZ_SRC)\$(MOZ_TOP)\js\src\xpconnect
nmake -f makefile.win depend
build_nspr:
@cd $(MOZ_SRC)\$(MOZ_TOP)\nsprpub
gmake -f gmakefile.win MOZ_SRC_FLIPPED=$(MOZ_SRC_FLIPPED)
build_ldapcsdk:
@cd $(MOZ_SRC)\$(MOZ_TOP)\directory\c-sdk
gmake -f gmakefile.win MOZ_SRC_FLIPPED=$(MOZ_SRC_FLIPPED) SHELL=sh
build_psm:
@cd $(MOZ_SRC)\$(MOZ_TOP)\security
nmake -f makefile.win
build_xpconnect: build_nspr
@cd $(MOZ_SRC)\$(MOZ_TOP)\include
nmake -f makefile.win all
@cd $(MOZ_SRC)\$(MOZ_TOP)\modules\libreg
nmake -f makefile.win all
@cd $(MOZ_SRC)\$(MOZ_TOP)\xpcom
nmake -f makefile.win export
@cd $(MOZ_SRC)\$(MOZ_TOP)\string
nmake -f makefile.win all
@cd $(MOZ_SRC)\$(MOZ_TOP)\xpcom
nmake -f makefile.win libs
@cd $(MOZ_SRC)\$(MOZ_TOP)\js\src
nmake -f makefile.win all
@cd $(MOZ_SRC)\$(MOZ_TOP)\js\src\xpconnect
nmake -f makefile.win all
build_seamonkey:
@cd $(MOZ_SRC)\$(MOZ_TOP)\.
nmake -f makefile.win all
build_client:
@cd $(MOZ_SRC)\mozilla\.
nmake -f makefile.win all
build_layout:
@cd $(MOZ_SRC)\mozilla\.
nmake -f makefile.win all
build_dist:
@cd $(MOZ_SRC)\mozilla\.
nmake -f makefile.win all
libs:
@cd $(MOZ_SRC)\$(MOZ_TOP)\.
nmake -f makefile.win libs
export: build_nspr build_ldapcsdk
@cd $(MOZ_SRC)\$(MOZ_TOP)\.
nmake -f makefile.win export
clobber_dist:
@cd $(MOZ_SRC)\mozilla\.
nmake -f makefile.win clobber_all
clobber_client:
@cd $(MOZ_SRC)\mozilla\.
nmake -f makefile.win clobber_all
clobber_layout:
@cd $(MOZ_SRC)\mozilla\.
nmake -f makefile.win clobber_all
browse_info::
cd $(MOZ_SRC)\$(MOZ_TOP)
-dir /s /b *.sbr > sbrlist.tmp
-bscmake /Es /o mozilla.bsc @sbrlist.tmp
-rm sbrlist.tmp
regchrome::
@cd $(MOZ_SRC)\mozilla\.
nmake /f makefile.win regchrome
deliver::
@cd $(MOZ_SRC)\mozilla\.
nmake /f makefile.win splitsymbols
#//------------------------------------------------------------------------
#// Utility stuff...
#//------------------------------------------------------------------------
#//------------------------------------------------------------------------
# Verify that MOZ_SRC is set correctly
#//------------------------------------------------------------------------
# Check to see if it is set at all
!if "$(MOZ_SRC)"==""
MOZ_SRC = $(MAKEDIR)\..
!endif
#
# create a temp file at the root and make sure it is visible from MOZ_SRC
#
!if [copy $(MAKEDIR)\client.mak $(MAKEDIR)\xyzzy.tmp > NUL] == 0
!endif
!if !EXIST( $(MOZ_SRC)\mozilla\xyzzy.tmp )
ERR_MESSAGE=$(ERR_MESSAGE)^
MOZ_SRC isn't set correctly: [$(MOZ_SRC)\mozilla]!=[$(MAKEDIR)]
!endif
!if [del $(MAKEDIR)\xyzzy.tmp]
!endif
#//------------------------------------------------------------------------
# Verify that MOZ_BITS is set
#//------------------------------------------------------------------------
!if !defined(MOZ_BITS)
ERR_MESSAGE=$(ERR_MESSAGE)^
Environment variable MOZ_BITS isn't set.
!endif
!if !defined(MOZ_TOOLS)
ERR_MESSAGE=$(ERR_MESSAGE)^
Environment variable MOZ_TOOLS isn't set.
!endif
#//------------------------------------------------------------------------
#// Display error
#//------------------------------------------------------------------------
!if "$(ERR_MESSAGE)" != ""
ERR_MESSAGE = ^
client.mak: ^
$(ERR_MESSAGE) ^
^
client.mak: usage^
^
nmake -f client.mak [MOZ_BRANCH=<cvs_branch_name>] ^
[MOZ_DATE=<cvs_date>]^
[pull_and_build_all]^
[pull_all]^
[build_all]^
^
Environment variables:^
^
MOZ_BITS set to 32^
MOZ_TOOLS set to the directory containing the needed tools ^
!ERROR $(ERR_MESSAGE)
!endif

View File

@@ -1,650 +0,0 @@
# The contents of this file are subject to the Netscape Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s): Stephen Lamm
# Build the Mozilla client.
#
# This needs CVSROOT set to work, e.g.,
# setenv CVSROOT :pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot
# or
# setenv CVSROOT :pserver:username%somedomain.org@cvs.mozilla.org:/cvsroot
#
# To checkout and build a tree,
# 1. cvs co mozilla/client.mk
# 2. cd mozilla
# 3. gmake -f client.mk
#
# Other targets (gmake -f client.mk [targets...]),
# checkout
# build
# clean (realclean is now the same as clean)
# distclean
#
# See http://www.mozilla.org/build/unix.html for more information.
#
# Options:
# MOZ_OBJDIR - Destination object directory
# MOZ_CO_DATE - Date tag to use for checkout (default: none)
# MOZ_CO_MODULE - Module to checkout (default: SeaMonkeyAll)
# MOZ_CVS_FLAGS - Flags to pass cvs (default: -q -z3)
# MOZ_CO_FLAGS - Flags to pass after 'cvs co' (default: -P)
# MOZ_MAKE_FLAGS - Flags to pass to $(MAKE)
# MOZ_CO_BRANCH - Branch tag (Deprecated. Use MOZ_CO_TAG below.)
#
#######################################################################
# Checkout Tags
#
# For branches, uncomment the MOZ_CO_TAG line with the proper tag,
# and commit this file on that tag.
MOZ_CO_TAG = NETSCAPE_7_0_RTM
NSPR_CO_TAG = NETSCAPE_7_0_RTM
PSM_CO_TAG = NETSCAPE_7_0_RTM
NSS_CO_TAG = NETSCAPE_7_0_RTM
LDAPCSDK_CO_TAG = NETSCAPE_7_0_RTM
ACCESSIBLE_CO_TAG = NETSCAPE_7_0_RTM
GFX2_CO_TAG = NETSCAPE_7_0_RTM
IMGLIB2_CO_TAG = NETSCAPE_7_0_RTM
BUILD_MODULES = all
#######################################################################
# Defines
#
CVS = cvs
CWD := $(shell pwd)
ifeq "$(CWD)" "/"
CWD := /.
endif
ifneq (, $(wildcard client.mk))
# Ran from mozilla directory
ROOTDIR := $(shell dirname $(CWD))
TOPSRCDIR := $(CWD)
else
# Ran from mozilla/.. directory (?)
ROOTDIR := $(CWD)
TOPSRCDIR := $(CWD)/mozilla
endif
# on os2, TOPSRCDIR may have two forward slashes in a row, which doesn't
# work; replace first instance with one forward slash
TOPSRCDIR := $(shell echo "$(TOPSRCDIR)" | sed -e 's%//%/%')
ifndef TOPSRCDIR_MOZ
TOPSRCDIR_MOZ=$(TOPSRCDIR)
endif
# if ROOTDIR equals only drive letter (i.e. "C:"), set to "/"
DIRNAME := $(shell echo "$(ROOTDIR)" | sed -e 's/^.://')
ifeq ($(DIRNAME),)
ROOTDIR := /.
endif
AUTOCONF := autoconf
MKDIR := mkdir
SH := /bin/sh
ifndef MAKE
MAKE := gmake
endif
CONFIG_GUESS_SCRIPT := $(wildcard $(TOPSRCDIR)/build/autoconf/config.guess)
ifdef CONFIG_GUESS_SCRIPT
CONFIG_GUESS = $(shell $(CONFIG_GUESS_SCRIPT))
else
_IS_FIRST_CHECKOUT := 1
endif
####################################
# CVS
# Add the CVS root to CVS_FLAGS if needed
CVS_ROOT_IN_TREE := $(shell cat $(TOPSRCDIR)/CVS/Root 2>/dev/null)
ifneq ($(CVS_ROOT_IN_TREE),)
ifneq ($(CVS_ROOT_IN_TREE),$(CVSROOT))
CVS_FLAGS := -d $(CVS_ROOT_IN_TREE)
endif
endif
CVSCO = $(strip $(CVS) $(CVS_FLAGS) co $(CVS_CO_FLAGS))
CVSCO_LOGFILE := $(ROOTDIR)/cvsco.log
CVSCO_LOGFILE := $(shell echo $(CVSCO_LOGFILE) | sed s%//%/%)
ifdef MOZ_CO_TAG
CVS_CO_FLAGS := -r $(MOZ_CO_TAG)
endif
####################################
# Load mozconfig Options
# See build pages, http://www.mozilla.org/build/unix.html,
# for how to set up mozconfig.
MOZCONFIG_LOADER := mozilla/build/autoconf/mozconfig2client-mk
MOZCONFIG_FINDER := mozilla/build/autoconf/mozconfig-find
MOZCONFIG_MODULES := mozilla/build/unix/modules.mk
run_for_side_effects := \
$(shell cd $(ROOTDIR); \
if test "$(_IS_FIRST_CHECKOUT)"; then \
$(CVSCO) $(MOZCONFIG_FINDER) $(MOZCONFIG_LOADER) $(MOZCONFIG_MODULES); \
else true; \
fi; \
$(MOZCONFIG_LOADER) $(TOPSRCDIR) mozilla/.mozconfig.mk > mozilla/.mozconfig.out)
include $(TOPSRCDIR)/.mozconfig.mk
include $(TOPSRCDIR)/build/unix/modules.mk
####################################
# Options that may come from mozconfig
# Change CVS flags if anonymous root is requested
ifdef MOZ_CO_USE_MIRROR
CVS_FLAGS := -d :pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot
endif
# MOZ_CVS_FLAGS - Basic CVS flags
ifeq "$(origin MOZ_CVS_FLAGS)" "undefined"
CVS_FLAGS := $(CVS_FLAGS) -q -z 3
else
CVS_FLAGS := $(MOZ_CVS_FLAGS)
endif
# This option is deprecated. The best way to have client.mk pull a tag
# is to set MOZ_CO_TAG (see above) and commit that change on the tag.
ifdef MOZ_CO_BRANCH
$(warning Use MOZ_CO_TAG instead of MOZ_CO_BRANCH)
CVS_CO_FLAGS := -r $(MOZ_CO_BRANCH)
endif
# MOZ_CO_FLAGS - Anything that we should use on all checkouts
ifeq "$(origin MOZ_CO_FLAGS)" "undefined"
CVS_CO_FLAGS := $(CVS_CO_FLAGS) -P
else
CVS_CO_FLAGS := $(CVS_CO_FLAGS) $(MOZ_CO_FLAGS)
endif
ifdef MOZ_CO_DATE
CVS_CO_DATE_FLAGS := -D "$(MOZ_CO_DATE)"
endif
ifdef MOZ_OBJDIR
OBJDIR := $(MOZ_OBJDIR)
MOZ_MAKE := $(MAKE) $(MOZ_MAKE_FLAGS) -C $(OBJDIR)
else
OBJDIR := $(TOPSRCDIR)
MOZ_MAKE := $(MAKE) $(MOZ_MAKE_FLAGS)
endif
####################################
# CVS defines for PSM
#
PSM_CO_MODULE= mozilla/security/manager
PSM_CO_FLAGS := -P -A
ifdef MOZ_CO_FLAGS
PSM_CO_FLAGS := $(MOZ_CO_FLAGS)
endif
ifdef PSM_CO_TAG
PSM_CO_FLAGS := $(PSM_CO_FLAGS) -r $(PSM_CO_TAG)
endif
CVSCO_PSM = $(CVS) $(CVS_FLAGS) co $(PSM_CO_FLAGS) $(CVS_CO_DATE_FLAGS) $(PSM_CO_MODULE)
####################################
# CVS defines for NSS
#
NSS_CO_MODULE = mozilla/security/nss \
mozilla/security/coreconf \
$(NULL)
NSS_CO_FLAGS := -P
ifdef MOZ_CO_FLAGS
NSS_CO_FLAGS := $(MOZ_CO_FLAGS)
endif
ifdef NSS_CO_TAG
NSS_CO_FLAGS := $(NSS_CO_FLAGS) -r $(NSS_CO_TAG)
endif
# Cannot pull static tags by date
ifeq ($(NSS_CO_TAG),NSS_CLIENT_TAG)
CVSCO_NSS = $(CVS) $(CVS_FLAGS) co $(NSS_CO_FLAGS) $(NSS_CO_MODULE)
else
CVSCO_NSS = $(CVS) $(CVS_FLAGS) co $(NSS_CO_FLAGS) $(CVS_CO_DATE_FLAGS) $(NSS_CO_MODULE)
endif
####################################
# CVS defines for NSPR
#
NSPR_CO_MODULE = mozilla/nsprpub
NSPR_CO_FLAGS := -P
ifdef MOZ_CO_FLAGS
NSPR_CO_FLAGS := $(MOZ_CO_FLAGS)
endif
ifdef NSPR_CO_TAG
NSPR_CO_FLAGS := $(NSPR_CO_FLAGS) -r $(NSPR_CO_TAG)
endif
# Cannot pull static tags by date
ifeq ($(NSPR_CO_TAG),NSPRPUB_CLIENT_TAG)
CVSCO_NSPR = $(CVS) $(CVS_FLAGS) co $(NSPR_CO_FLAGS) $(NSPR_CO_MODULE)
else
CVSCO_NSPR = $(CVS) $(CVS_FLAGS) co $(NSPR_CO_FLAGS) $(CVS_CO_DATE_FLAGS) $(NSPR_CO_MODULE)
endif
####################################
# CVS defines for the C LDAP SDK
#
LDAPCSDK_CO_MODULE = mozilla/directory/c-sdk
LDAPCSDK_CO_FLAGS := -P
ifdef MOZ_CO_FLAGS
LDAPCSDK_CO_FLAGS := $(MOZ_CO_FLAGS)
endif
ifdef LDAPCSDK_CO_TAG
LDAPCSDK_CO_FLAGS := $(LDAPCSDK_CO_FLAGS) -r $(LDAPCSDK_CO_TAG)
endif
CVSCO_LDAPCSDK = $(CVS) $(CVS_FLAGS) co $(LDAPCSDK_CO_FLAGS) $(CVS_CO_DATE_FLAGS) $(LDAPCSDK_CO_MODULE)
####################################
# CVS defines for the C LDAP SDK
#
ACCESSIBLE_CO_MODULE = mozilla/accessible
ACCESSIBLE_CO_FLAGS := -P
ifdef MOZ_CO_FLAGS
ACCESSIBLE_CO_FLAGS := $(MOZ_CO_FLAGS)
endif
ifdef ACCESSIBLE_CO_TAG
ACCESSIBLE_CO_FLAGS := $(ACCESSIBLE_CO_FLAGS) -r $(ACCESSIBLE_CO_TAG)
endif
CVSCO_ACCESSIBLE = $(CVS) $(CVS_FLAGS) co $(ACCESSIBLE_CO_FLAGS) $(CVS_CO_DATE_FLAGS) $(ACCESSIBLE_CO_MODULE)
####################################
# CVS defines for gfx2
#
GFX2_CO_MODULE = mozilla/gfx2
GFX2_CO_FLAGS := -P
ifdef MOZ_CO_FLAGS
GFX2_CO_FLAGS := $(MOZ_CO_FLAGS)
endif
ifdef GFX2_CO_TAG
GFX2_CO_FLAGS := $(GFX2_CO_FLAGS) -r $(GFX2_CO_TAG)
endif
CVSCO_GFX2 = $(CVS) $(CVS_FLAGS) co $(GFX2_CO_FLAGS) $(CVS_CO_DATE_FLAGS) $(GFX2_CO_MODULE)
####################################
# CVS defines for new image library
#
IMGLIB2_CO_MODULE = mozilla/modules/libpr0n
IMGLIB2_CO_FLAGS := -P
ifdef MOZ_CO_FLAGS
IMGLIB2_CO_FLAGS := $(MOZ_CO_FLAGS)
endif
ifdef IMGLIB2_CO_TAG
IMGLIB2_CO_FLAGS := $(IMGLIB2_CO_FLAGS) -r $(IMGLIB2_CO_TAG)
endif
CVSCO_IMGLIB2 = $(CVS) $(CVS_FLAGS) co $(IMGLIB2_CO_FLAGS) $(CVS_CO_DATE_FLAGS) $(IMGLIB2_CO_MODULE)
####################################
# CVS defines for standalone modules
#
ifneq ($(BUILD_MODULES),all)
MOZ_CO_MODULE := $(filter-out $(NSPRPUB_DIR) security directory/c-sdk, $(BUILD_MODULE_CVS))
MOZ_CO_MODULE += allmakefiles.sh client.mk aclocal.m4 configure configure.in
MOZ_CO_MODULE += Makefile.in
MOZ_CO_MODULE := $(addprefix mozilla/, $(MOZ_CO_MODULE))
NOSUBDIRS_MODULE := $(addprefix mozilla/, $(BUILD_MODULE_CVS_NS))
ifneq ($(NOSUBDIRS_MODULE),)
CVSCO_NOSUBDIRS := $(CVSCO) -l $(CVS_CO_DATE_FLAGS) $(NOSUBDIRS_MODULE)
endif
ifeq (,$(filter $(NSPRPUB_DIR), $(BUILD_MODULE_CVS)))
CVSCO_NSPR :=
endif
ifeq (,$(filter security security/manager, $(BUILD_MODULE_CVS)))
CVSCO_PSM :=
CVSCO_NSS :=
endif
ifeq (,$(filter directory/c-sdk, $(BUILD_MODULE_CVS)))
CVSCO_LDAPCSDK :=
endif
ifeq (,$(filter accessible, $(BUILD_MODULE_CVS)))
CVSCO_ACCESSIBLE :=
endif
ifeq (,$(filter gfx2, $(BUILD_MODULE_CVS)))
CVSCO_GFX2 :=
endif
ifeq (,$(filter modules/libpr0n, $(BUILD_MODULE_CVS)))
CVSCO_IMGLIB2 :=
endif
endif
####################################
# CVS defines for SeaMonkey
#
ifeq ($(MOZ_CO_MODULE),)
MOZ_CO_MODULE := SeaMonkeyAll
endif
CVSCO_SEAMONKEY := $(CVSCO) $(CVS_CO_DATE_FLAGS) $(MOZ_CO_MODULE)
####################################
# CVS defined for libart (pulled and built if MOZ_INTERNAL_LIBART_LGPL is set)
#
CVSCO_LIBART := $(CVSCO) $(CVS_CO_DATE_FLAGS) mozilla/other-licenses/libart_lgpl
ifdef MOZ_INTERNAL_LIBART_LGPL
FASTUPDATE_LIBART := fast_update $(CVSCO_LIBART)
CHECKOUT_LIBART := cvs_co $(CVSCO_LIBART)
else
CHECKOUT_LIBART := true
FASTUPDATE_LIBART := true
endif
####################################
# CVS defines for Calendar (pulled and built if MOZ_CALENDAR is set)
#
CVSCO_CALENDAR := $(CVSCO) $(CVS_CO_DATE_FLAGS) mozilla/calendar
ifdef MOZ_CALENDAR
FASTUPDATE_CALENDAR := fast_update $(CVSCO_CALENDAR)
CHECKOUT_CALENDAR := cvs_co $(CVSCO_CALENDAR)
else
CHECKOUT_CALENDAR := true
FASTUPDATE_CALENDAR := true
endif
# because some cygwin tools can't handle native dos-drive paths & vice-versa
# force configure to use a relative path for --srcdir
# need a better check for win32
# and we need to get OBJDIR earlier
ifdef MOZ_TOOLS
_tmpobjdir := $(shell cygpath -u $(OBJDIR))
_abs2rel := $(shell cygpath -w $(TOPSRCDIR)/build/unix/abs2rel.pl | sed -e 's|\\|/|g')
_OBJ2SRCPATH := $(shell $(_abs2rel) $(TOPSRCDIR) $(_tmpobjdir))
endif
#######################################################################
# Rules
#
# Print out any options loaded from mozconfig.
all build checkout clean depend distclean export libs install realclean::
@if test -f .mozconfig.out; then \
cat .mozconfig.out; \
rm -f .mozconfig.out; \
else true; \
fi
ifdef _IS_FIRST_CHECKOUT
all:: checkout build
else
all:: checkout alldep
endif
# Windows equivalents
pull_all: checkout
build_all: build
build_all_dep: alldep
build_all_depend: alldep
clobber clobber_all: clean
pull_and_build_all: checkout alldep
# Do everything from scratch
everything: checkout clean build
####################################
# CVS checkout
#
checkout::
# @: Backup the last checkout log.
@if test -f $(CVSCO_LOGFILE) ; then \
mv $(CVSCO_LOGFILE) $(CVSCO_LOGFILE).old; \
else true; \
fi
ifdef RUN_AUTOCONF_LOCALLY
@echo "Removing local configures" ; \
cd $(ROOTDIR) && \
$(RM) -f mozilla/configure mozilla/nsprpub/configure \
mozilla/directory/c-sdk/configure
endif
@echo "checkout start: "`date` | tee $(CVSCO_LOGFILE)
@echo '$(CVSCO) mozilla/client.mk mozilla/build/unix/modules.mk'; \
cd $(ROOTDIR) && \
$(CVSCO) mozilla/client.mk mozilla/build/unix/modules.mk
@cd $(ROOTDIR) && $(MAKE) -f mozilla/client.mk real_checkout
real_checkout:
# @: Start the checkout. Split the output to the tty and a log file. \
# : If it fails, touch an error file because "tee" hides the error.
@failed=.cvs-failed.tmp; rm -f $$failed*; \
cvs_co() { echo "$$@" ; \
("$$@" || touch $$failed) 2>&1 | tee -a $(CVSCO_LOGFILE) && \
if test -f $$failed; then false; else true; fi; }; \
cvs_co $(CVSCO_NSPR) && \
cvs_co $(CVSCO_NSS) && \
cvs_co $(CVSCO_PSM) && \
cvs_co $(CVSCO_LDAPCSDK) && \
cvs_co $(CVSCO_ACCESSIBLE) && \
cvs_co $(CVSCO_GFX2) && \
cvs_co $(CVSCO_IMGLIB2) && \
$(CHECKOUT_CALENDAR) && \
$(CHECKOUT_LIBART) && \
cvs_co $(CVSCO_SEAMONKEY) && \
cvs_co $(CVSCO_NOSUBDIRS)
@echo "checkout finish: "`date` | tee -a $(CVSCO_LOGFILE)
# @: Check the log for conflicts. ;
@conflicts=`egrep "^C " $(CVSCO_LOGFILE)` ;\
if test "$$conflicts" ; then \
echo "$(MAKE): *** Conflicts during checkout." ;\
echo "$$conflicts" ;\
echo "$(MAKE): Refer to $(CVSCO_LOGFILE) for full log." ;\
false; \
else true; \
fi
ifdef RUN_AUTOCONF_LOCALLY
@echo Generating configures using $(AUTOCONF) ; \
cd $(TOPSRCDIR) && $(AUTOCONF) && \
cd $(TOPSRCDIR)/nsprpub && $(AUTOCONF) && \
cd $(TOPSRCDIR)/directory/c-sdk && $(AUTOCONF)
endif
fast-update:
# @: Backup the last checkout log.
@if test -f $(CVSCO_LOGFILE) ; then \
mv $(CVSCO_LOGFILE) $(CVSCO_LOGFILE).old; \
else true; \
fi
ifdef RUN_AUTOCONF_LOCALLY
@echo "Removing local configures" ; \
cd $(ROOTDIR) && \
$(RM) -f mozilla/configure mozilla/nsprpub/configure \
mozilla/directory/c-sdk/configure
endif
@echo "checkout start: "`date` | tee $(CVSCO_LOGFILE)
@echo '$(CVSCO) mozilla/client.mk mozilla/build/unix/modules.mk'; \
cd $(ROOTDIR) && \
$(CVSCO) mozilla/client.mk mozilla/build/unix/modules.mk
@cd $(TOPSRCDIR) && \
$(MAKE) -f client.mk real_fast-update
real_fast-update:
# @: Start the update. Split the output to the tty and a log file. \
# : If it fails, touch an error file because "tee" hides the error.
@failed=.fast_update-failed.tmp; rm -f $$failed*; \
fast_update() { (config/cvsco-fast-update.pl $$@ || touch $$failed) 2>&1 | tee -a $(CVSCO_LOGFILE) && \
if test -f $$failed; then false; else true; fi; }; \
cvs_co() { echo "$$@" ; \
("$$@" || touch $$failed) 2>&1 | tee -a $(CVSCO_LOGFILE) && \
if test -f $$failed; then false; else true; fi; }; \
fast_update $(CVSCO_NSPR) && \
cd $(ROOTDIR) && \
failed=mozilla/.fast_update-failed.tmp && \
cvs_co $(CVSCO_NSS) && \
failed=.fast_update-failed.tmp && \
cd mozilla && \
fast_update $(CVSCO_PSM) && \
fast_update $(CVSCO_LDAPCSDK) && \
fast_update $(CVSCO_ACCESSIBLE) && \
fast_update $(CVSCO_GFX2) && \
fast_update $(CVSCO_IMGLIB2) && \
$(FASTUPDATE_CALENDAR) && \
$(FASTUPDATE_LIBART) && \
fast_update $(CVSCO_SEAMONKEY) && \
fast_update $(CVSCO_NOSUBDIRS)
@echo "fast_update finish: "`date` | tee -a $(CVSCO_LOGFILE)
# @: Check the log for conflicts. ;
@conflicts=`egrep "^C " $(CVSCO_LOGFILE)` ;\
if test "$$conflicts" ; then \
echo "$(MAKE): *** Conflicts during fast-update." ;\
echo "$$conflicts" ;\
echo "$(MAKE): Refer to $(CVSCO_LOGFILE) for full log." ;\
false; \
else true; \
fi
ifdef RUN_AUTOCONF_LOCALLY
@echo Generating configures using $(AUTOCONF) ; \
cd $(TOPSRCDIR) && $(AUTOCONF) && \
cd $(TOPSRCDIR)/nsprpub && $(AUTOCONF) && \
cd $(TOPSRCDIR)/directory/c-sdk && $(AUTOCONF)
endif
####################################
# Web configure
WEBCONFIG_FILE := $(HOME)/.mozconfig
MOZCONFIG2CONFIGURATOR := build/autoconf/mozconfig2configurator
webconfig:
@cd $(TOPSRCDIR); \
url=`$(MOZCONFIG2CONFIGURATOR) $(TOPSRCDIR)`; \
echo Running mozilla with the following url: ;\
echo ;\
echo $$url ;\
mozilla -remote "openURL($$url)" || \
netscape -remote "openURL($$url)" || \
mozilla $$url || \
netscape $$url ;\
echo ;\
echo 1. Fill out the form on the browser. ;\
echo 2. Save the results to $(WEBCONFIG_FILE)
#####################################################
# First Checkout
ifdef _IS_FIRST_CHECKOUT
# First time, do build target in a new process to pick up new files.
build::
$(MAKE) -f $(TOPSRCDIR)/client.mk build
else
#####################################################
# After First Checkout
####################################
# Configure
CONFIG_STATUS := $(wildcard $(OBJDIR)/config.status)
CONFIG_CACHE := $(wildcard $(OBJDIR)/config.cache)
ifdef RUN_AUTOCONF_LOCALLY
EXTRA_CONFIG_DEPS := \
$(TOPSRCDIR)/aclocal.m4 \
$(wildcard $(TOPSRCDIR)/build/autoconf/*.m4) \
$(NULL)
$(TOPSRCDIR)/configure: $(TOPSRCDIR)/configure.in $(EXTRA_CONFIG_DEPS)
@echo Generating $@ using autoconf
cd $(TOPSRCDIR); $(AUTOCONF)
endif
CONFIG_STATUS_DEPS_L10N := $(wildcard $(TOPSRCDIR)/l10n/makefiles.all)
CONFIG_STATUS_DEPS := \
$(TOPSRCDIR)/configure \
$(TOPSRCDIR)/allmakefiles.sh \
$(TOPSRCDIR)/.mozconfig.mk \
$(wildcard $(TOPSRCDIR)/nsprpub/configure) \
$(wildcard $(TOPSRCDIR)/directory/c-sdk/configure) \
$(wildcard $(TOPSRCDIR)/mailnews/makefiles) \
$(CONFIG_STATUS_DEPS_L10N) \
$(wildcard $(TOPSRCDIR)/themes/makefiles) \
$(NULL)
# configure uses the program name to determine @srcdir@. Calling it without
# $(TOPSRCDIR) will set @srcdir@ to "."; otherwise, it is set to the full
# path of $(TOPSRCDIR).
ifeq ($(TOPSRCDIR),$(OBJDIR))
CONFIGURE := ./configure
else
CONFIGURE := $(TOPSRCDIR)/configure
endif
ifdef _OBJ2SRCPATH
CONFIGURE_ARGS := --srcdir=$(_OBJ2SRCPATH) $(CONFIGURE_ARGS)
endif
$(OBJDIR)/Makefile $(OBJDIR)/config.status: $(CONFIG_STATUS_DEPS)
@if test ! -d $(OBJDIR); then $(MKDIR) $(OBJDIR); else true; fi
@echo cd $(OBJDIR);
@echo $(CONFIGURE) $(CONFIGURE_ARGS)
@cd $(OBJDIR) && $(CONFIGURE_ENV_ARGS) $(CONFIGURE) $(CONFIGURE_ARGS) \
|| ( echo "*** Fix above errors and then restart with\
\"$(MAKE) -f client.mk build\"" && exit 1 )
@touch $(OBJDIR)/Makefile
ifdef CONFIG_STATUS
$(OBJDIR)/config/autoconf.mk: $(TOPSRCDIR)/config/autoconf.mk.in
cd $(OBJDIR); \
CONFIG_FILES=config/autoconf.mk ./config.status
endif
####################################
# Depend
depend:: $(OBJDIR)/Makefile $(OBJDIR)/config.status
$(MOZ_MAKE) export && $(MOZ_MAKE) depend
####################################
# Build it
build:: $(OBJDIR)/Makefile $(OBJDIR)/config.status
$(MOZ_MAKE)
####################################
# Other targets
# Pass these target onto the real build system
install export libs clean realclean distclean alldep:: $(OBJDIR)/Makefile $(OBJDIR)/config.status
$(MOZ_MAKE) $@
cleansrcdir:
@cd $(TOPSRCDIR); \
if [ -f webshell/embed/gtk/Makefile ]; then \
$(MAKE) -C webshell/embed/gtk distclean; \
fi; \
if [ -f Makefile ]; then \
$(MAKE) distclean ; \
else \
echo "Removing object files from srcdir..."; \
rm -fr `find . -type d \( -name .deps -print -o -name CVS \
-o -exec test ! -d {}/CVS \; \) -prune \
-o \( -name '*.[ao]' -o -name '*.so' \) -type f -print`; \
build/autoconf/clean-config.sh; \
fi;
# (! IS_FIRST_CHECKOUT)
endif
.PHONY: checkout real_checkout depend build export libs alldep install clean realclean distclean cleansrcdir pull_all build_all clobber clobber_all pull_and_build_all everything

View File

@@ -0,0 +1,134 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "Fundamentals.h"
#include "BitSet.h"
// Return the next bit after index set to true or -1 if none.
//
Int32 BitSet::nextOne(Int32 pos) const
{
++pos;
if (pos < 0 || Uint32(pos) >= universeSize)
return -1;
Uint32 offset = getWordOffset(pos);
Uint8 index = getBitOffset(pos);
Word* ptr = &word[offset];
Word currentWord = *ptr++ >> index;
if (currentWord != Word(0)) {
while ((currentWord & Word(1)) == 0) {
++index;
currentWord >>= 1;
}
return (offset << nBitsInWordLog2) + index;
}
Word* limit = &word[getSizeInWords(universeSize)];
while (ptr < limit) {
++offset;
currentWord = *ptr++;
if (currentWord != Word(0)) {
index = 0;
while ((currentWord & Word(1)) == 0) {
++index;
currentWord >>= 1;
}
return (offset << nBitsInWordLog2) + index;
}
}
return -1;
}
// Return the next bit after index set to false or -1 if none.
//
Int32 BitSet::nextZero(Int32 pos) const
{
++pos;
if (pos < 0 || Uint32(pos) >= universeSize)
return -1;
Uint32 offset = getWordOffset(pos);
Uint8 index = getBitOffset(pos);
Word* ptr = &word[offset];
Word currentWord = *ptr++ >> index;
if (currentWord != Word(~0)) {
for (; index < nBitsInWord; ++index) {
if ((currentWord & Word(1)) == 0) {
Int32 ret = (offset << nBitsInWordLog2) + index;
return (Uint32(ret) < universeSize) ? ret : -1;
}
currentWord >>= 1;
}
}
Word* limit = &word[getSizeInWords(universeSize)];
while (ptr < limit) {
++offset;
currentWord = *ptr++;
if (currentWord != Word(~0)) {
for (index = 0; index < nBitsInWord; ++index) {
if ((currentWord & Word(1)) == 0) {
Int32 ret = (offset << nBitsInWordLog2) + index;
return (Uint32(ret) < universeSize) ? ret : -1;
}
currentWord >>= 1;
}
}
}
return -1;
}
#ifdef DEBUG_LOG
// Print the set.
//
void BitSet::printPretty(LogModuleObject log)
{
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("[ "));
for (Int32 i = firstOne(); i != -1; i = nextOne(i)) {
Int32 currentBit = i;
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("%d", currentBit));
Int32 nextBit = nextOne(currentBit);
if (nextBit != currentBit + 1) {
UT_OBJECTLOG(log, PR_LOG_ALWAYS, (" "));
continue;
}
while ((nextBit != -1) && (nextBit == (currentBit + 1))) {
currentBit = nextBit;
nextBit = nextOne(nextBit);
}
if (currentBit > (i+1))
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("-%d ", currentBit));
else
UT_OBJECTLOG(log, PR_LOG_ALWAYS, (" %d ", currentBit));
i = currentBit;
}
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("]\n"));
}
#endif // DEBUG_LOG

View File

@@ -0,0 +1,195 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _BITSET_H_
#define _BITSET_H_
#include "Fundamentals.h"
#include "LogModule.h"
#include "Pool.h"
#include <string.h>
//------------------------------------------------------------------------------
// BitSet -
class BitSet
{
private:
#if (PR_BITS_PER_WORD == 64)
typedef Uint64 Word;
#elif (PR_BITS_PER_WORD == 32)
typedef Uint32 Word;
#endif
static const nBitsInWord = PR_BITS_PER_WORD;
static const nBytesInWord = PR_BYTES_PER_WORD;
static const nBitsInWordLog2 = PR_BITS_PER_WORD_LOG2;
static const nBytesInWordLog2 = PR_BYTES_PER_WORD_LOG2;
// Return the number of Word need to store the universe.
static Uint32 getSizeInWords(Uint32 sizeOfUniverse) {return (sizeOfUniverse + (nBitsInWord - 1)) >> nBitsInWordLog2;}
// Return the given element offset in its containing Word.
static Uint32 getBitOffset(Uint32 element) {return element & (nBitsInWord - 1);}
// Return the Word offset for the given element int the universe.
static Uint32 getWordOffset(Uint32 element) {return element >> nBitsInWordLog2;}
// Return the mask for the given bit index.
static Word getMask(Uint8 index) {return Word(1) << index;}
private:
Uint32 universeSize; // Size of the universe
Word* word; // universe memory.
private:
// No copy constructor.
BitSet(const BitSet&);
// Check if the given set's universe is of the same size than this universe.
void checkUniverseCompatibility(const BitSet& set) const {assert(set.universeSize == universeSize);}
// Check if pos is valid for this set's universe.
void checkMember(Int32 pos) const {assert(pos >=0 && Uint32(pos) < universeSize);}
public:
// Create a bitset of universeSize bits.
BitSet(Pool& pool, Uint32 universeSize) : universeSize(universeSize) {word = new(pool) Word[getSizeInWords(universeSize)]; clear();}
// Return the size of this bitset.
Uint32 getSize() const {return universeSize;}
// Clear the bitset.
void clear() {memset(word, 0x00, getSizeInWords(universeSize) << nBytesInWordLog2);}
// Clear the bit at index.
void clear(Uint32 index) {checkMember(index); word[getWordOffset(index)] &= ~getMask(index);}
// Set the bitset.
void set() {memset(word, 0xFF, getSizeInWords(universeSize) << nBytesInWordLog2);}
// Set the bit at index.
void set(Uint32 index) {checkMember(index); word[getWordOffset(index)] |= getMask(index);}
// Return true if the bit at index is set.
bool test(Uint32 index) const {checkMember(index); return (word[getWordOffset(index)] & getMask(index)) != 0;}
// Union with the given bitset.
inline void or(const BitSet& set);
// Intersection with the given bitset.
inline void and(const BitSet& set);
// Difference with the given bitset.
inline void difference(const BitSet& set);
// Copy set.
inline BitSet& operator = (const BitSet& set);
// Return true if the bitset are identical.
friend bool operator == (const BitSet& set1, const BitSet& set2);
// Return true if the bitset are different.
friend bool operator != (const BitSet& set1, const BitSet& set2);
// Logical operators.
BitSet& operator |= (const BitSet& set) {or(set); return *this;}
BitSet& operator &= (const BitSet& set) {and(set); return *this;}
BitSet& operator -= (const BitSet& set) {difference(set); return *this;}
// Return the first bit at set to true or -1 if none.
Int32 firstOne() const {return nextOne(-1);}
// Return the next bit after index set to true or -1 if none.
Int32 nextOne(Int32 pos) const;
// Return the first bit at set to false or -1 if none.
Int32 firstZero() const {return nextZero(-1);}
// Return the next bit after index set to false or -1 if none.
Int32 nextZero(Int32 pos) const;
// Iterator to conform with the set API.
typedef Int32 iterator;
// Return true if the walk is ordered.
static bool isOrdered() {return true;}
// Return the iterator for the first element of this set.
iterator begin() const {return firstOne();}
// Return the next iterator.
iterator advance(iterator pos) const {return nextOne(pos);}
// Return true if the iterator is at the end of the set.
bool done(iterator pos) const {return pos == -1;}
// Return the element corresponding to the given iterator.
Uint32 get(iterator pos) const {return pos;}
#ifdef DEBUG_LOG
// Print the set.
void printPretty(LogModuleObject log);
#endif // DEBUG_LOG
};
// Union with the given bitset.
//
inline void BitSet::or(const BitSet& set)
{
checkUniverseCompatibility(set);
Word* src = set.word;
Word* dst = word;
Word* limit = &src[getSizeInWords(universeSize)];
while (src < limit)
*dst++ |= *src++;
}
// Intersection with the given bitset.
//
inline void BitSet::and(const BitSet& set)
{
checkUniverseCompatibility(set);
Word* src = set.word;
Word* dst = word;
Word* limit = &src[getSizeInWords(universeSize)];
while (src < limit)
*dst++ &= *src++;
}
// Difference with the given bitset.
//
inline void BitSet::difference(const BitSet& set)
{
checkUniverseCompatibility(set);
Word* src = set.word;
Word* dst = word;
Word* limit = &src[getSizeInWords(universeSize)];
while (src < limit)
*dst++ &= ~*src++;
}
// Copy the given set into this set.
//
inline BitSet& BitSet::operator = (const BitSet& set)
{
checkUniverseCompatibility(set);
if (this != &set)
memcpy(word, set.word, getSizeInWords(universeSize) << nBytesInWordLog2);
return *this;
}
// Return true if the given set is identical to this set.
inline bool operator == (const BitSet& set1, const BitSet& set2)
{
set1.checkUniverseCompatibility(set2);
if (&set1 == &set2)
return true;
return memcmp(set1.word, set2.word, BitSet::getSizeInWords(set1.universeSize) << BitSet::nBytesInWordLog2) == 0;
}
inline bool operator != (const BitSet& set1, const BitSet& set2) {return !(set1 == set2);}
#endif // _BITSET_H

View File

@@ -0,0 +1,159 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _COALESCING_H_
#define _COALESCING_H_
#include "Fundamentals.h"
#include "Pool.h"
#include "RegisterPressure.h"
#include "InterferenceGraph.h"
#include "ControlGraph.h"
#include "ControlNodes.h"
#include "Instruction.h"
#include "SparseSet.h"
#include "RegisterAllocator.h"
#include "RegisterAllocatorTools.h"
#if 1
// Performing an ultra conservative coalescing meens that when we look at
// candidates (source,destination) for coalescing we need to make sure
// that the combined interference of the source and destination register
// will not exceed the total number of register available for the register
// class.
#define ULTRA_CONSERVATIVE_COALESCING
#else
// If we are not doing an ultra conservative coalescing we have to make sure
// that the total number of neighbor whose degree is greater than the total
// number of register is not greater than the total number of register.
#undef ULTRA_CONSERVATIVE_COALESCING
#endif
template <class RegisterPressure>
struct Coalescing
{
static bool coalesce(RegisterAllocator& registerAllocator);
};
template <class RegisterPressure>
bool Coalescing<RegisterPressure>::coalesce(RegisterAllocator& registerAllocator)
{
Pool& pool = registerAllocator.pool;
// Initialize the lookup table
//
Uint32 rangeCount = registerAllocator.rangeCount;
RegisterName* newRange = new RegisterName[2 * rangeCount];
RegisterName* coalescedRange = &newRange[rangeCount];
RegisterName* name2range = registerAllocator.name2range;
init(coalescedRange, rangeCount);
SparseSet interferences(pool, rangeCount);
InterferenceGraph<RegisterPressure>& iGraph = registerAllocator.iGraph;
bool removedInstructions = false;
ControlGraph& controlGraph = registerAllocator.controlGraph;
ControlNode** nodes = controlGraph.lndList;
Uint32 nNodes = controlGraph.nNodes;
// Walk the nodes in the loop nesting depth list.
for (Int32 n = nNodes - 1; n >= 0; n--) {
InstructionList& instructions = nodes[n]->getInstructions();
InstructionList::iterator it = instructions.begin();
while (!instructions.done(it)) {
Instruction& instruction = instructions.get(it);
it = instructions.advance(it);
if ((instruction.getFlags() & ifCopy) != 0) {
assert(instruction.getInstructionUseBegin() != instruction.getInstructionUseEnd() && instruction.getInstructionUseBegin()[0].isRegister());
assert(instruction.getInstructionDefineBegin() != instruction.getInstructionDefineEnd() && instruction.getInstructionDefineBegin()[0].isRegister());
RegisterName source = findRoot(name2range[instruction.getInstructionUseBegin()[0].getRegisterName()], coalescedRange);
RegisterName destination = findRoot(name2range[instruction.getInstructionDefineBegin()[0].getRegisterName()], coalescedRange);
if (source == destination) {
instruction.remove();
} else if (!iGraph.interfere(source, destination)) {
InterferenceVector* sourceVector = iGraph.getInterferenceVector(source);
InterferenceVector* destinationVector = iGraph.getInterferenceVector(destination);
#ifdef ULTRA_CONSERVATIVE_COALESCING
interferences.clear();
InterferenceVector* vector;
for (vector = sourceVector; vector != NULL; vector = vector->next) {
RegisterName* neighbors = vector->neighbors;
for (Uint32 i = 0; i < vector->count; i++)
interferences.set(findRoot(neighbors[i], coalescedRange));
}
for (vector = destinationVector; vector != NULL; vector = vector->next) {
RegisterName* neighbors = vector->neighbors;
for (Uint32 i = 0; i < vector->count; i++)
interferences.set(findRoot(neighbors[i], coalescedRange));
}
Uint32 count = interferences.getSize();
#else // ULTRA_CONSERVATIVE_COALESCING
trespass("not implemented");
Uint32 count = 0;
#endif // ULTRA_CONSERVATIVE_COALESCING
if (count < 6 /* FIX: should get the number from the class */) {
// Update the interferences vector.
if (sourceVector == NULL) {
iGraph.setInterferenceVector(source, destinationVector);
sourceVector = destinationVector;
} else if (destinationVector == NULL)
iGraph.setInterferenceVector(destination, sourceVector);
else {
InterferenceVector* last = NULL;
for (InterferenceVector* v = sourceVector; v != NULL; v = v->next)
last = v;
assert(last);
last->next = destinationVector;
iGraph.setInterferenceVector(destination, sourceVector);
}
// Update the interference matrix.
for (InterferenceVector* v = sourceVector; v != NULL; v = v->next) {
RegisterName* neighbors = v->neighbors;
for (Uint32 i = 0; i < v->count; i++) {
RegisterName neighbor = findRoot(neighbors[i], coalescedRange);
iGraph.setInterference(neighbor, source);
iGraph.setInterference(neighbor, destination);
}
}
instruction.remove();
coalescedRange[source] = destination;
removedInstructions = true;
}
}
}
}
}
registerAllocator.rangeCount = compress(registerAllocator.name2range, coalescedRange, registerAllocator.nameCount, rangeCount);
delete newRange;
return removedInstructions;
}
#endif // _COALESCING_H_

View File

@@ -0,0 +1,283 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef NEW_LAURENTM_CODE
#include "Coloring.h"
#include "VirtualRegister.h"
#include "FastBitSet.h"
#include "FastBitMatrix.h"
#include "CpuInfo.h"
bool Coloring::
assignRegisters(FastBitMatrix& interferenceMatrix)
{
PRUint32 *stackPtr = new(pool) PRUint32[vRegManager.count()];
return select(interferenceMatrix, stackPtr, simplify(interferenceMatrix, stackPtr));
}
PRInt32 Coloring::
getLowestSpillCostRegister(FastBitSet& bitset)
{
PRInt32 lowest = bitset.firstOne();
if (lowest != -1)
{
Flt32 cost = vRegManager.getVirtualRegister(lowest).spillInfo.spillCost;
for (PRInt32 r = bitset.nextOne(lowest); r != -1; r = bitset.nextOne(r))
{
VirtualRegister& vReg = vRegManager.getVirtualRegister(r);
if (!vReg.spillInfo.infiniteSpillCost && (vReg.spillInfo.spillCost < cost))
{
cost = vReg.spillInfo.spillCost;
lowest = r;
}
}
}
return lowest;
}
PRUint32* Coloring::
simplify(FastBitMatrix interferenceMatrix, PRUint32* stackPtr)
{
// first we construct the sets low and high. low contains all nodes of degree
// inferior to the number of register available on the processor. All the
// nodes with an high degree and a finite spill cost are placed in high.
// Nodes of high degree and infinite spill cost are not included in either sets.
PRUint32 nRegisters = vRegManager.count();
FastBitSet low(pool, nRegisters);
FastBitSet high(pool, nRegisters);
FastBitSet stack(pool, nRegisters);
for (VirtualRegisterManager::iterator i = vRegManager.begin(); !vRegManager.done(i); i = vRegManager.advance(i))
{
VirtualRegister& vReg = vRegManager.getVirtualRegister(i);
if (vReg.getClass() == vrcStackSlot)
{
stack.set(i);
vReg.colorRegister(nRegisters);
}
else
{
if (vReg.colorInfo.interferenceDegree < NUMBER_OF_REGISTERS)
low.set(i);
else // if (!vReg.spillInfo.infiniteSpillCost)
high.set(i);
// Set coloring info.
vReg.spillInfo.willSpill = false;
switch(vReg.getClass())
{
case vrcInteger:
vReg.colorRegister(LAST_GREGISTER + 1);
break;
case vrcFloatingPoint:
case vrcFixedPoint:
vReg.colorRegister(LAST_FPREGISTER + 1);
break;
default:
PR_ASSERT(false); // Cannot happen.
}
}
}
// push the stack registers
PRInt32 j;
for (j = stack.firstOne(); j != -1; j = stack.nextOne(j))
*stackPtr++ = j;
// simplify
while (true)
{
PRInt32 r;
while ((r = getLowestSpillCostRegister(low)) != -1)
{
VirtualRegister& vReg = vRegManager.getVirtualRegister(r);
/* update low and high */
FastBitSet inter(interferenceMatrix.getRow(r), nRegisters);
for (j = inter.firstOne(); j != -1; j = inter.nextOne(j))
{
VirtualRegister& neighbor = vRegManager.getVirtualRegister(j);
// if the new interference degree of one of his neighbor becomes
// NUMBER_OF_REGISTERS - 1 then it is added to the set 'low'.
PRUint32 maxInterference = 0;
switch (neighbor.getClass())
{
case vrcInteger:
maxInterference = NUMBER_OF_GREGISTERS;
break;
case vrcFloatingPoint:
case vrcFixedPoint:
maxInterference = NUMBER_OF_FPREGISTERS;
break;
default:
PR_ASSERT(false);
}
if ((vRegManager.getVirtualRegister(j).colorInfo.interferenceDegree-- == maxInterference))
{
high.clear(j);
low.set(j);
}
vReg.colorInfo.interferenceDegree--;
interferenceMatrix.clear(r, j);
interferenceMatrix.clear(j, r);
}
low.clear(r);
// Push this register.
*stackPtr++ = r;
}
if ((r = getLowestSpillCostRegister(high)) != -1)
{
high.clear(r);
low.set(r);
}
else
break;
}
return stackPtr;
}
bool Coloring::
select(FastBitMatrix& interferenceMatrix, PRUint32* stackBase, PRUint32* stackPtr)
{
PRUint32 nRegisters = vRegManager.count();
FastBitSet usedRegisters(NUMBER_OF_REGISTERS + 1); // usedRegisters if used for both GR & FPR.
FastBitSet preColoredRegisters(NUMBER_OF_REGISTERS + 1);
FastBitSet usedStack(nRegisters + 1);
bool success = true;
Int32 lastUsedSSR = -1;
// select
while (stackPtr != stackBase)
{
// Pop one register.
PRUint32 r = *--stackPtr;
VirtualRegister& vReg = vRegManager.getVirtualRegister(r);
FastBitSet neighbors(interferenceMatrix.getRow(r), nRegisters);
if (vReg.getClass() == vrcStackSlot)
// Stack slots coloring.
{
usedStack.clear();
for (PRInt32 i = neighbors.firstOne(); i != -1; i = neighbors.nextOne(i))
usedStack.set(vRegManager.getVirtualRegister(i).getColor());
Int32 color = usedStack.firstZero();
vReg.colorRegister(color);
if (color > lastUsedSSR)
lastUsedSSR = color;
}
else
// Integer & Floating point register coloring.
{
usedRegisters.clear();
preColoredRegisters.clear();
for (PRInt32 i = neighbors.firstOne(); i != -1; i = neighbors.nextOne(i))
{
VirtualRegister& nvReg = vRegManager.getVirtualRegister(i);
usedRegisters.set(nvReg.getColor());
if (nvReg.isPreColored())
preColoredRegisters.set(nvReg.getPreColor());
}
if (vReg.hasSpecialInterference)
usedRegisters |= vReg.specialInterference;
PRInt8 c = -1;
PRInt8 maxColor = 0;
PRInt8 firstColor = 0;
switch (vReg.getClass())
{
case vrcInteger:
firstColor = FIRST_GREGISTER;
maxColor = LAST_GREGISTER;
break;
case vrcFloatingPoint:
case vrcFixedPoint:
firstColor = FIRST_FPREGISTER;
maxColor = LAST_FPREGISTER;
break;
default:
PR_ASSERT(false);
}
if (vReg.isPreColored())
{
c = vReg.getPreColor();
if (usedRegisters.test(c))
c = -1;
}
else
{
for (c = usedRegisters.nextZero(firstColor - 1); (c >= 0) && (c <= maxColor) && (preColoredRegisters.test(c));
c = usedRegisters.nextZero(c)) {}
}
if ((c >= 0) && (c <= maxColor))
{
vReg.colorRegister(c);
}
else
{
VirtualRegister& stackRegister = vRegManager.newVirtualRegister(vrcStackSlot);
vReg.equivalentRegister[vrcStackSlot] = &stackRegister;
vReg.spillInfo.willSpill = true;
success = false;
}
}
}
#ifdef DEBUG
if (success)
{
for (VirtualRegisterManager::iterator i = vRegManager.begin(); !vRegManager.done(i); i = vRegManager.advance(i))
{
VirtualRegister& vReg = vRegManager.getVirtualRegister(i);
switch (vReg.getClass())
{
case vrcInteger:
if (vReg.getColor() > LAST_GREGISTER)
PR_ASSERT(false);
break;
case vrcFloatingPoint:
case vrcFixedPoint:
#if NUMBER_OF_FPREGISTERS != 0
if (vReg.getColor() > LAST_FPREGISTER)
PR_ASSERT(false);
#endif
break;
default:
break;
}
}
}
#endif
vRegManager.nUsedStackSlots = lastUsedSSR + 1;
return success;
}
#endif // NEW_LAURENTM_CODE

View File

@@ -0,0 +1,284 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "Fundamentals.h"
#include "ControlGraph.h"
#include "ControlNodes.h"
#include "Instruction.h"
#include "RegisterAllocator.h"
#include "VirtualRegister.h"
#include "InterferenceGraph.h"
#include "SparseSet.h"
#include "Spilling.h"
#include "Splits.h"
UT_EXTERN_LOG_MODULE(RegAlloc);
template <class RegisterPressure>
class Coloring
{
private:
static RegisterName* simplify(RegisterAllocator& registerAllocator, RegisterName* coloringStack);
static bool select(RegisterAllocator& registerAllocator, RegisterName* coloringStack, RegisterName* coloringStackPtr);
public:
static bool color(RegisterAllocator& registerAllocator);
static void finalColoring(RegisterAllocator& registerAllocator);
};
template <class RegisterPressure>
void Coloring<RegisterPressure>::finalColoring(RegisterAllocator& registerAllocator)
{
RegisterName* color = registerAllocator.color;
RegisterName* name2range = registerAllocator.name2range;
ControlGraph& controlGraph = registerAllocator.controlGraph;
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
for (Uint32 n = 0; n < nNodes; n++) {
InstructionList& instructions = nodes[n]->getInstructions();
for (InstructionList::iterator i = instructions.begin(); !instructions.done(i); i = instructions.advance(i)) {
Instruction& instruction = instructions.get(i);
InstructionUse* useEnd = instruction.getInstructionUseEnd();
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
if (usePtr->isRegister()) {
usePtr->setRegisterName(color[name2range[usePtr->getRegisterName()]]);
#ifdef DEBUG
RegisterID rid = usePtr->getRegisterID();
setColoredRegister(rid);
usePtr->setRegisterID(rid);
#endif // DEBUG
}
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
for (InstructionDefine* definePtr = instruction.getInstructionDefineBegin(); definePtr < defineEnd; definePtr++)
if (definePtr->isRegister()) {
definePtr->setRegisterName(color[name2range[definePtr->getRegisterName()]]);
#ifdef DEBUG
RegisterID rid = definePtr->getRegisterID();
setColoredRegister(rid);
definePtr->setRegisterID(rid);
#endif // DEBUG
}
}
}
}
template <class RegisterPressure>
bool Coloring<RegisterPressure>::select(RegisterAllocator& registerAllocator, RegisterName* coloringStack, RegisterName* coloringStackPtr)
{
Uint32 rangeCount = registerAllocator.rangeCount;
RegisterName* color = new RegisterName[rangeCount];
registerAllocator.color = color;
for (Uint32 r = 1; r < rangeCount; r++)
color[r] = RegisterName(6); // FIX;
// Color the preColored registers.
//
VirtualRegisterManager& vrManager = registerAllocator.vrManager;
RegisterName* name2range = registerAllocator.name2range;
PreColoredRegister* machineEnd = vrManager.getMachineRegistersEnd();
for (PreColoredRegister* machinePtr = vrManager.getMachineRegistersBegin(); machinePtr < machineEnd; machinePtr++)
if (machinePtr->id != invalidID) {
color[name2range[getName(machinePtr->id)]] = machinePtr->color;
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\twill preColor range %d as %d\n", name2range[getName(machinePtr->id)], machinePtr->color));
}
SpillCost* cost = registerAllocator.spillCost;
Pool& pool = registerAllocator.pool;
SparseSet& spill = *new(pool) SparseSet(pool, rangeCount);
registerAllocator.willSpill = &spill;
SparseSet neighborColors(pool, 6); // FIX
InterferenceGraph<RegisterPressure>& iGraph = registerAllocator.iGraph;
bool coloringFailed = false;
while (coloringStackPtr > coloringStack) {
RegisterName range = *--coloringStackPtr;
if (!cost[range].infinite && cost[range].cost < 0) {
coloringFailed = true;
spill.set(range);
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\tfailed to color %d, will spill.\n", range));
} else {
neighborColors.clear();
for (InterferenceVector* vector = iGraph.getInterferenceVector(range); vector != NULL; vector = vector->next)
for (Int32 i = vector->count - 1; i >= 0; --i) {
RegisterName neighborColor = color[vector->neighbors[i]];
if (neighborColor < 6) // FIX
neighborColors.set(neighborColor);
}
if (neighborColors.getSize() == 6) { // FIX
coloringFailed = true;
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\tfailed to color %d, ", range));
if (!Splits<RegisterPressure>::findSplit(registerAllocator, color, range)) {
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("will spill.\n"));
spill.set(range);
} else
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("will split.\n"));
} else {
for (Uint32 i = 0; i < 6; i++) // FIX
if (!neighborColors.test(i)) {
fprintf(stdout, "\twill color %d as %d\n", range, i);
color[range] = RegisterName(i);
break;
}
}
}
}
#ifdef DEBUG_LOG
if (coloringFailed) {
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("Coloring failed:\n"));
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\twill spill: "));
spill.printPretty(UT_LOG_MODULE(RegAlloc));
} else {
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("Coloring succeeded:\n"));
for (Uint32 i = 1; i < rangeCount; i++)
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\trange %d colored as %d\n", i, color[i]));
}
#endif
return !coloringFailed;
}
template <class RegisterPressure>
RegisterName* Coloring<RegisterPressure>::simplify(RegisterAllocator& registerAllocator, RegisterName* coloringStack)
{
InterferenceGraph<RegisterPressure>& iGraph = registerAllocator.iGraph;
SpillCost* spillCost = registerAllocator.spillCost;
Uint32 rangeCount = registerAllocator.rangeCount;
Uint32* degree = new Uint32[rangeCount];
for (RegisterName i = RegisterName(1); i < rangeCount; i = RegisterName(i + 1)) {
InterferenceVector* vector = iGraph.getInterferenceVector(i);
degree[i] = (vector != NULL) ? vector->count : 0;
}
Pool& pool = registerAllocator.pool;
SparseSet low(pool, rangeCount);
SparseSet high(pool, rangeCount);
SparseSet highInfinite(pool, rangeCount);
SparseSet preColored(pool, rangeCount);
// Get the precolored registers.
//
VirtualRegisterManager& vrManager = registerAllocator.vrManager;
RegisterName* name2range = registerAllocator.name2range;
PreColoredRegister* machineEnd = vrManager.getMachineRegistersEnd();
for (PreColoredRegister* machinePtr = vrManager.getMachineRegistersBegin(); machinePtr < machineEnd; machinePtr++)
if (machinePtr->id != invalidID)
preColored.set(name2range[getName(machinePtr->id)]);
// Insert the live ranges in the sets.
//
for (Uint32 range = 1; range < rangeCount; range++)
if (!preColored.test(range))
if (degree[range] < 6) // FIX
low.set(range);
else if (!spillCost[range].infinite)
high.set(range);
else
highInfinite.set(range);
#ifdef DEBUG_LOG
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("Coloring sets:\n\tlow = "));
low.printPretty(UT_LOG_MODULE(RegAlloc));
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\thigh = "));
high.printPretty(UT_LOG_MODULE(RegAlloc));
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\thighInfinite = "));
highInfinite.printPretty(UT_LOG_MODULE(RegAlloc));
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\tpreColored = "));
preColored.printPretty(UT_LOG_MODULE(RegAlloc));
#endif // DEBUG_LOG
RegisterName* coloringStackPtr = coloringStack;
while (low.getSize() != 0 || high.getSize() != 0) {
while (low.getSize() != 0) {
RegisterName range = RegisterName(low.getOne());
low.clear(range);
*coloringStackPtr++ = range;
for (InterferenceVector* vector = iGraph.getInterferenceVector(range); vector != NULL; vector = vector->next)
for (Int32 i = (vector->count - 1); i >= 0; --i) {
RegisterName neighbor = vector->neighbors[i];
degree[neighbor]--;
if (degree[neighbor] < 6) // FIX
if (high.test(neighbor)) {
high.clear(neighbor);
low.set(neighbor);
} else if (highInfinite.test(neighbor)) {
highInfinite.clear(neighbor);
low.set(neighbor);
}
}
}
if (high.getSize() != 0) {
RegisterName best = RegisterName(high.getOne());
double bestCost = spillCost[best].cost;
double bestDegree = degree[best];
// Choose the next best candidate.
//
for (SparseSet::iterator i = high.begin(); !high.done(i); i = high.advance(i)) {
RegisterName range = RegisterName(high.get(i));
double thisCost = spillCost[range].cost;
double thisDegree = degree[range];
if (thisCost * bestDegree < bestCost * thisDegree) {
best = range;
bestCost = thisCost;
bestDegree = thisDegree;
}
}
high.clear(best);
low.set(best);
}
}
assert(highInfinite.getSize() == 0);
delete degree;
#ifdef DEBUG_LOG
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("Coloring stack:\n\t"));
for (RegisterName* sp = coloringStack; sp < coloringStackPtr; ++sp)
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("%d ", *sp));
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\n"));
#endif // DEBUG_LOG
return coloringStackPtr;
}
template <class RegisterPressure>
bool Coloring<RegisterPressure>::color(RegisterAllocator& registerAllocator)
{
RegisterName* coloringStack = new RegisterName[registerAllocator.rangeCount];
return select(registerAllocator, coloringStack, simplify(registerAllocator, coloringStack));
}

View File

@@ -0,0 +1,212 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "Fundamentals.h"
#include <string.h>
#include "ControlGraph.h"
#include "ControlNodes.h"
#include "DominatorGraph.h"
DominatorGraph::DominatorGraph(ControlGraph& controlGraph) : controlGraph(controlGraph)
{
Uint32 nNodes = controlGraph.nNodes;
GtoV = new Uint32[nNodes + 1];
VtoG = new Uint32[nNodes + 1];
Uint32 v = 1;
for (Uint32 n = 0; n < nNodes; n++) {
VtoG[v] = n;
GtoV[n] = v++;
}
// Initialize all the 1-based arrays.
//
parent = new Uint32[v];
semi = new Uint32[v];
vertex = new Uint32[v];
label = new Uint32[v];
size = new Uint32[v];
ancestor = new Uint32[v];
child = new Uint32[v];
dom = new Uint32[v];
bucket = new DGLinkedList*[v];
memset(semi, '\0', v * sizeof(Uint32));
memset(bucket, '\0', v * sizeof(DGLinkedList*));
vCount = v;
build();
delete parent;
delete semi;
delete vertex;
delete label;
delete size;
delete ancestor;
delete child;
delete dom;
delete bucket;
}
Uint32 DominatorGraph::DFS(Uint32 vx, Uint32 n)
{
semi[vx] = ++n;
vertex[n] = label[vx] = vx;
ancestor[vx] = child[vx] = 0;
size[vx] = 1;
ControlNode& node = *controlGraph.dfsList[VtoG[vx]];
ControlEdge* successorEnd = node.getSuccessorsEnd();
for (ControlEdge* successorPtr = node.getSuccessorsBegin(); successorPtr < successorEnd; successorPtr++) {
Uint32 w = GtoV[successorPtr->getTarget().dfsNum];
if (semi[w] == 0) {
parent[w] = vx;
n = DFS(w, n);
}
}
return n;
}
void DominatorGraph::LINK(Uint32 vx, Uint32 w)
{
Uint32 s = w;
while (semi[label[w]] < semi[label[child[s]]]) {
if (size[s] + size[child[child[s]]] >= (size[child[s]] << 1)) {
ancestor[child[s]] = s;
child[s] = child[child[s]];
} else {
size[child[s]] = size[s];
s = ancestor[s] = child[s];
}
}
label[s] = label[w];
size[vx] += size[w];
if(size[vx] < (size[w] << 1)) {
Uint32 t = s;
s = child[vx];
child[vx] = t;
}
while( s != 0 ) {
ancestor[s] = vx;
s = child[s];
}
}
void DominatorGraph::COMPRESS(Uint32 vx)
{
if(ancestor[ancestor[vx]] != 0) {
COMPRESS(ancestor[vx]);
if(semi[label[ancestor[vx]]] < semi[label[vx]])
label[vx] = label[ancestor[vx]];
ancestor[vx] = ancestor[ancestor[vx]];
}
}
Uint32 DominatorGraph::EVAL(Uint32 vx)
{
if(ancestor[vx] == 0)
return label[vx];
COMPRESS(vx);
return (semi[label[ancestor[vx]]] >= semi[label[vx]]) ? label[vx] : label[ancestor[vx]];
}
void DominatorGraph::build()
{
Uint32 n = DFS(GtoV[0], 0);
size[0] = label[0] = semi[0];
for (Uint32 i = n; i >= 2; i--) {
Uint32 w = vertex[i];
ControlNode& node = *controlGraph.dfsList[VtoG[w]];
const DoublyLinkedList<ControlEdge>& predecessors = node.getPredecessors();
for (DoublyLinkedList<ControlEdge>::iterator p = predecessors.begin(); !predecessors.done(p); p = predecessors.advance(p)) {
Uint32 vx = GtoV[predecessors.get(p).getSource().dfsNum];
Uint32 u = EVAL(vx);
if(semi[u] < semi[w])
semi[w] = semi[u];
}
DGLinkedList* elem = new DGLinkedList();
elem->next = bucket[vertex[semi[w]]];
elem->index = w;
bucket[vertex[semi[w]]] = elem;
LINK(parent[w], w);
elem = bucket[parent[w]];
while(elem != NULL) {
Uint32 vx = elem->index;
Uint32 u = EVAL(vx);
dom[vx] = (semi[u] < semi[vx]) ? u : parent[w];
elem = elem->next;
}
}
memset(size, '\0', n * sizeof(Uint32));
Pool& pool = controlGraph.pool;
nodes = new(pool) DGNode[n];
for(Uint32 j = 2; j <= n; j++) {
Uint32 w = vertex[j];
Uint32 d = dom[w];
if(d != vertex[semi[w]]) {
d = dom[d];
dom[w] = d;
}
size[d]++;
}
dom[GtoV[0]] = 0;
for (Uint32 k = 1; k <= n; k++) {
DGNode& node = nodes[VtoG[k]];
Uint32 count = size[k];
node.successorsEnd = node.successorsBegin = (count) ? new(pool) Uint32[count] : (Uint32*) 0;
}
for (Uint32 l = 2; l <= n; l++)
*(nodes[VtoG[dom[l]]].successorsEnd)++ = VtoG[l];
}
#ifdef DEBUG_LOG
void DominatorGraph::printPretty(LogModuleObject log)
{
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("Dominator Graph:\n"));
Uint32 nNodes = controlGraph.nNodes;
for (Uint32 i = 0; i < nNodes; i++) {
DGNode& node = nodes[i];
if (node.successorsBegin != node.successorsEnd) {
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\tN%d dominates ", i));
for (Uint32* successorsPtr = node.successorsBegin; successorsPtr < node.successorsEnd; successorsPtr++)
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("N%d ", *successorsPtr));
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\n"));
}
}
}
#endif // DEBUG_LOG

View File

@@ -0,0 +1,80 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _DOMINATOR_GRAPH_H_
#define _DOMINATOR_GRAPH_H_
#include "LogModule.h"
class ControlGraph;
struct DGNode
{
Uint32* successorsBegin;
Uint32* successorsEnd;
};
struct DGLinkedList
{
DGLinkedList* next;
Uint32 index;
};
class DominatorGraph
{
private:
ControlGraph& controlGraph;
Uint32 vCount;
Uint32* VtoG;
Uint32* GtoV;
Uint32* parent;
Uint32* semi;
Uint32* vertex;
Uint32* label;
Uint32* size;
Uint32* ancestor;
Uint32* child;
Uint32* dom;
DGLinkedList** bucket;
DGNode* nodes;
private:
void build();
Uint32 DFS(Uint32 vx, Uint32 n);
void LINK(Uint32 vx, Uint32 w);
void COMPRESS(Uint32 vx);
Uint32 EVAL(Uint32 vx);
public:
DominatorGraph(ControlGraph& controlGraph);
Uint32* getSuccessorsBegin(Uint32 n) const {return nodes[n].successorsBegin;}
Uint32* getSuccessorsEnd(Uint32 n) const {return nodes[n].successorsEnd;}
#ifdef DEBUG_LOG
void printPretty(LogModuleObject log);
#endif // DEBUG_LOG
};
#endif // _DOMINATOR_GRAPH_H_

View File

@@ -0,0 +1,20 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "Fundamentals.h"
#include "HashSet.h"

View File

@@ -0,0 +1,97 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _HASH_SET_H_
#define _HASH_SET_H_
#include "Fundamentals.h"
#include "Pool.h"
#include <string.h>
struct HashSetElement
{
Uint32 index;
HashSetElement* next;
};
class HashSet
{
private:
static const hashSize = 64;
// Return the hash code for the given element index.
static Uint32 getHashCode(Uint32 index) {return index & (hashSize - 1);} // Could be better !
private:
Pool& allocationPool;
HashSetElement** bucket;
HashSetElement* free;
private:
// No copy constructor.
HashSet(const HashSet&);
// No copy operator.
void operator = (const HashSet&);
public:
// Create a new HashSet.
inline HashSet(Pool& pool, Uint32 universeSize);
// Clear the hashset.
void clear();
// Clear the element for the given index.
void clear(Uint32 index);
// Set the element for the given index.
void set(Uint32 index);
// Return true if the element at index is a member.
bool test(Uint32 index) const;
// Union with the given hashset.
inline void or(const HashSet& set);
// Intersection with the given hashset.
inline void and(const HashSet& set);
// Difference with the given hashset.
inline void difference(const HashSet& set);
// Logical operators.
HashSet& operator |= (const HashSet& set) {or(set); return *this;}
HashSet& operator &= (const HashSet& set) {and(set); return *this;}
HashSet& operator -= (const HashSet& set) {difference(set); return *this;}
// Iterator to conform with the set API.
typedef HashSetElement* iterator;
// Return the iterator for the first element of this set.
iterator begin() const;
// Return the next iterator.
iterator advance(iterator pos) const;
// Return true if the iterator is at the end of the set.
bool done(iterator pos) const {return pos == NULL;}
};
inline HashSet::HashSet(Pool& pool, Uint32 /*universeSize*/)
: allocationPool(pool), free(NULL)
{
bucket = new(pool) HashSetElement*[hashSize];
memset(bucket, '\0', sizeof(HashSetElement*));
}
#endif // _HASH_SET_H_

View File

@@ -0,0 +1,213 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _INDEXED_POOL_H_
#define _INDEXED_POOL_H_
#include "Fundamentals.h"
#include <string.h>
#include <stdlib.h>
//------------------------------------------------------------------------------
// IndexedPool<IndexedObjectSubclass> is an indexed pool of objects. The
// template parameter 'IndexedObjectSubclass' must be a subclass of the struct
// IndexedObject.
//
// When the indexed pool is ask to allocate and initialize a new object (using
// the operator new(anIndexedPool) it will zero the memory used to store the
// object and initialize the field 'index' of this object to its position in
// the pool.
//
// An object allocated by the indexed pool can be freed by calling the method
// IndexedPool::release(IndexedElement& objectIndex).
//
// example:
//
// IndexedPool<IndexedElement> elementPool;
//
// IndexedElement& element1 = *new(elementPool) IndexedElement();
// IndexedElement& element2 = *new(elementPool) IndexedElement();
//
// indexedPool.release(element1);
// IndexedElement& element3 = *new(elementPool) IndexedElement();
//
// At this point element1 is no longer a valid object, element2 is at
// index 2 and element3 is at index 1.
//
//------------------------------------------------------------------------------
// IndexedObject -
//
template<class Object>
struct IndexedObject
{
Uint32 index; // Index in the pool.
Object* next; // Used to link IndexedObject together.
Uint32 getIndex() {return index;}
};
//------------------------------------------------------------------------------
// IndexedPool<IndexedObject> -
//
template <class IndexedObject>
class IndexedPool
{
private:
static const blockSize = 4; // Size of one block.
Uint32 nBlocks; // Number of blocks in the pool.
IndexedObject** block; // Array of block pointers.
IndexedObject* freeObjects; // Chained list of free IndexedObjects.
Uint32 nextIndex; // Index of the next free object in the last block.
private:
void allocateAnotherBlock();
IndexedObject& newObject();
public:
IndexedPool() : nBlocks(0), block(NULL), freeObjects(NULL), nextIndex(1) {}
~IndexedPool();
IndexedObject& get(Uint32 index) const;
void release(IndexedObject& object);
void setSize(Uint32 size) {assert(size < nextIndex); nextIndex = size;}
// Return the universe size.
Uint32 getSize() {return nextIndex;}
friend void* operator new(size_t, IndexedPool<IndexedObject>& pool); // Needs to call newObject().
};
// Free all the memory allocated for this object.
//
template <class IndexedObject>
IndexedPool<IndexedObject>::~IndexedPool()
{
for (Uint32 n = 0; n < nBlocks; n++)
free(&((IndexedObject **) &block[n][n*blockSize])[-(n + 1)]);
}
// Release the given. This object will be iserted in the chained
// list of free IndexedObjects. To minimize the fragmentation the chained list
// is ordered by ascending indexes.
//
template <class IndexedObject>
void IndexedPool<IndexedObject>::release(IndexedObject& object)
{
Uint32 index = object.index;
IndexedObject* list = freeObjects;
assert(&object == &get(index)); // Make sure that object is owned by this pool.
if (list == NULL) { // The list is empty.
freeObjects = &object;
object.next = NULL;
} else { // The list contains at least 1 element.
if (index < list->index) { // insert as first element.
freeObjects = &object;
object.next = list;
} else { // Find this object's place.
while ((list->next) != NULL && (list->next->index < index))
list = list->next;
object.next = list->next;
list->next = &object;
}
}
#ifdef DEBUG
// Sanity check to be sure that the list is correctly ordered.
for (IndexedObject* obj = freeObjects; obj != NULL; obj = obj->next)
if (obj->next != NULL)
assert(obj->index < obj->next->index);
#endif
}
// Create a new block of IndexedObjects. We will allocate the memory to
// store IndexedPool::blockSize IndexedObject and the new Array of block
// pointers.
// The newly created IndexedObjects will not be initialized.
//
template <class IndexedObject>
void IndexedPool<IndexedObject>::allocateAnotherBlock()
{
void* memory = (void *) malloc((nBlocks + 1) * sizeof(Uint32) + blockSize * sizeof(IndexedObject));
memcpy(memory, block, nBlocks * sizeof(Uint32));
block = (IndexedObject **) memory;
IndexedObject* objects = (IndexedObject *) &block[nBlocks + 1];
block[nBlocks] = &objects[-(nBlocks * blockSize)];
nBlocks++;
}
// Return the IndexedObject at the position 'index' in the pool.
//
template <class IndexedObject>
IndexedObject& IndexedPool<IndexedObject>::get(Uint32 index) const
{
Uint32 blockIndex = index / blockSize;
assert(blockIndex < nBlocks);
return block[blockIndex][index];
}
// Return the reference of an unused object in the pool.
//
template <class IndexedObject>
IndexedObject& IndexedPool<IndexedObject>::newObject()
{
if (freeObjects != NULL) {
IndexedObject& newObject = *freeObjects;
freeObjects = newObject.next;
return newObject;
}
Uint32 nextIndex = this->nextIndex++;
Uint32 blockIndex = nextIndex / blockSize;
while (blockIndex >= nBlocks)
allocateAnotherBlock();
IndexedObject& newObject = block[blockIndex][nextIndex];
newObject.index = nextIndex;
return newObject;
}
// Return the address of the next unsused object in the given
// indexed pool. The field index of the newly allocated object
// will be initialized to the corresponding index of this object
// in the pool.
//
template <class IndexedObject>
void* operator new(size_t size, IndexedPool<IndexedObject>& pool)
{
assert(size == sizeof(IndexedObject));
return (void *) &pool.newObject();
}
#endif // _INDEXED_POOL_H_

View File

@@ -0,0 +1,258 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _INTERFERENCE_GRAPH_H_
#define _INTERFERENCE_GRAPH_H_
#include "Fundamentals.h"
#include "ControlGraph.h"
#include "Primitives.h"
#include "Instruction.h"
#include "VirtualRegister.h"
#include "RegisterPressure.h"
#include "SparseSet.h"
#include <string.h>
struct InterferenceVector
{
Uint32 count;
InterferenceVector* next;
RegisterName* neighbors;
InterferenceVector() : count(0), next(NULL) {}
};
class RegisterAllocator;
template <class RegisterPressure>
class InterferenceGraph
{
private:
RegisterAllocator& registerAllocator;
RegisterPressure::Set* interferences;
InterferenceVector** vector;
Uint32* offset;
Uint32 rangeCount;
private:
// No copy constructor.
InterferenceGraph(const InterferenceGraph&);
// No copy operator.
void operator = (const InterferenceGraph&);
// Check if reg is a member of the universe.
void checkMember(RegisterName name) {assert(name < rangeCount);}
// Return the edge index for the interference between name1 and name2.
Uint32 getEdgeIndex(RegisterName name1, RegisterName name2);
public:
InterferenceGraph(RegisterAllocator& registerAllocator) : registerAllocator(registerAllocator) {}
// Calculate the interferences.
void build();
// Return true if reg1 and reg2 interfere.
bool interfere(RegisterName name1, RegisterName name2);
// Return the interference vector for the given register or NULL if there is none.
InterferenceVector* getInterferenceVector(RegisterName name) {return vector[name];}
// Set the interference between name1 and name2.
void setInterference(RegisterName name1, RegisterName name2);
// Set the interference vector for the given register.
void setInterferenceVector(RegisterName name, InterferenceVector* v) {vector[name] = v;}
#ifdef DEBUG_LOG
// Print the interferences.
void printPretty(LogModuleObject log);
#endif // DEBUG_LOG
};
template <class RegisterPressure>
void InterferenceGraph<RegisterPressure>::build()
{
Pool& pool = registerAllocator.pool;
Uint32 rangeCount = registerAllocator.rangeCount;
this->rangeCount = rangeCount;
// Initialize the structures.
//
offset = new(pool) Uint32[rangeCount + 1];
vector = new(pool) InterferenceVector*[rangeCount];
memset(vector, '\0', sizeof(InterferenceVector*) * rangeCount);
Uint32 o = 0;
offset[0] = 0;
for (Uint32 i = 1; i <= rangeCount; ++i) {
offset[i] = o;
o += i;
}
interferences = new(pool) RegisterPressure::Set(pool, (rangeCount * rangeCount) / 2);
ControlGraph& controlGraph = registerAllocator.controlGraph;
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
RegisterName* name2range = registerAllocator.name2range;
LivenessInfo<RegisterPressure> liveness = Liveness<RegisterPressure>::analysis(controlGraph, rangeCount, name2range);
registerAllocator.liveness = liveness;
SparseSet currentLive(pool, rangeCount);
for (Uint32 n = 0; n < nNodes; n++) {
ControlNode& node = *nodes[n];
currentLive = liveness.liveOut[n];
InstructionList& instructions = node.getInstructions();
for (InstructionList::iterator i = instructions.end(); !instructions.done(i); i = instructions.retreat(i)) {
Instruction& instruction = instructions.get(i);
InstructionUse* useBegin = instruction.getInstructionUseBegin();
InstructionUse* useEnd = instruction.getInstructionUseEnd();
InstructionUse* usePtr;
InstructionDefine* defineBegin = instruction.getInstructionDefineBegin();
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
InstructionDefine* definePtr;
// Handle the copy instruction to avoid unnecessary interference between the 2 registers.
if ((instruction.getFlags() & ifCopy) != 0) {
assert(useBegin != useEnd && useBegin[0].isRegister());
currentLive.clear(name2range[useBegin[0].getRegisterName()]);
}
// Create the interferences.
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
if (definePtr->isRegister()) {
RegisterName define = name2range[definePtr->getRegisterName()];
for (SparseSet::iterator e = currentLive.begin(); !currentLive.done(e); e = currentLive.advance(e)) {
RegisterName live = RegisterName(currentLive.get(e));
if ((live != define) && !interfere(live, define) && registerAllocator.canInterfere(live, define)) {
if (vector[define] == NULL)
vector[define] = new(pool) InterferenceVector();
vector[define]->count++;
if (vector[live] == NULL)
vector[live] = new(pool) InterferenceVector();
vector[live]->count++;
setInterference(live, define);
}
}
}
// Now update the liveness.
//
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
if (definePtr->isRegister())
currentLive.clear(name2range[definePtr->getRegisterName()]);
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
if (usePtr->isRegister())
currentLive.set(name2range[usePtr->getRegisterName()]);
}
}
// Allocate the memory to store the interferences.
//
for (Uint32 e = 0; e < rangeCount; e++)
if (vector[e] != NULL) {
InterferenceVector& v = *vector[e];
v.neighbors = new(pool) RegisterName[v.count];
v.count = 0;
}
// Initialize the edges.
//
if (RegisterPressure::Set::isOrdered()) {
RegisterName name1 = RegisterName(0);
for (RegisterPressure::Set::iterator i = interferences->begin(); !interferences->done(i); i = interferences->advance(i)) {
Uint32 interferenceIndex = interferences->get(i);
while(interferenceIndex >= offset[name1 + 1])
name1 = RegisterName(name1 + 1);
assert((interferenceIndex >= offset[name1]) && (interferenceIndex < offset[name1 + 1]));
RegisterName name2 = RegisterName(interferenceIndex - offset[name1]);
assert(interfere(name1, name2));
InterferenceVector& vector1 = *vector[name1];
vector1.neighbors[vector1.count++] = name2;
InterferenceVector& vector2 = *vector[name2];
vector2.neighbors[vector2.count++] = name1;
}
} else {
trespass("not Implemented"); // FIX: need one more pass to initialize the vectors.
}
}
template <class RegisterPressure>
Uint32 InterferenceGraph<RegisterPressure>::getEdgeIndex(RegisterName name1, RegisterName name2)
{
checkMember(name1); checkMember(name2);
assert(name1 != name2); // This is not possible.
return (name1 < name2) ? offset[name2] + name1 : offset[name1] + name2;
}
template <class RegisterPressure>
void InterferenceGraph<RegisterPressure>::setInterference(RegisterName name1, RegisterName name2)
{
interferences->set(getEdgeIndex(name1, name2));
}
template <class RegisterPressure>
bool InterferenceGraph<RegisterPressure>::interfere(RegisterName name1, RegisterName name2)
{
return interferences->test(getEdgeIndex(name1, name2));
}
#ifdef DEBUG_LOG
template <class RegisterPressure>
void InterferenceGraph<RegisterPressure>::printPretty(LogModuleObject log)
{
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("Interference Vectors:\n"));
for (Uint32 i = 1; i < rangeCount; i++) {
if (vector[i] != NULL) {
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\tvr%d: (", i));
for (InterferenceVector* v = vector[i]; v != NULL; v = v->next)
for (Uint32 j = 0; j < v->count; j++) {
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("%d", v->neighbors[j]));
if (v->next != NULL || j != (v->count - 1))
UT_OBJECTLOG(log, PR_LOG_ALWAYS, (","));
}
UT_OBJECTLOG(log, PR_LOG_ALWAYS, (")\n"));
}
}
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("Interference Matrix:\n"));
for (RegisterName name1 = RegisterName(1); name1 < rangeCount; name1 = RegisterName(name1 + 1)) {
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\t%d:\t", name1));
for (RegisterName name2 = RegisterName(1); name2 < rangeCount; name2 = RegisterName(name2 + 1))
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("%c", ((name1 != name2) && interfere(name1, name2)) ? '1' : '0'));
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\n"));
}
}
#endif // DEBUG_LOG
#endif // _INTERFERENCE_GRAPH_H_

View File

@@ -0,0 +1,87 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _LIVE_RANGE_H_
#define _LIVE_RANGE_H_
#include "Fundamentals.h"
#include "ControlGraph.h"
#include "ControlNodes.h"
#include "Primitives.h"
#include "Instruction.h"
#include "RegisterAllocator.h"
#include "RegisterAllocatorTools.h"
template <class RegisterPressure>
struct LiveRange
{
static void build(RegisterAllocator& registerAllocator);
};
template <class RegisterPressure>
void LiveRange<RegisterPressure>::build(RegisterAllocator& registerAllocator)
{
// Intialize the lookup table.
//
Uint32 nameCount = registerAllocator.nameCount;
RegisterName* nameTable = new(registerAllocator.pool) RegisterName[2*nameCount];
RegisterName* rangeName = &nameTable[nameCount];
init(rangeName, nameCount);
// Walk the graph.
//
ControlGraph& controlGraph = registerAllocator.controlGraph;
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
SparseSet destination(registerAllocator.pool, nameCount);
for (Uint32 n = 0; n < nNodes; n++) {
InstructionList& phiNodes = nodes[n]->getPhiNodeInstructions();
destination.clear();
for (InstructionList::iterator i = phiNodes.begin(); !phiNodes.done(i); i = phiNodes.advance(i)) {
Instruction& phiNode = phiNodes.get(i);
assert(phiNode.getInstructionDefineBegin() != phiNode.getInstructionDefineEnd() && phiNode.getInstructionDefineBegin()[0].isRegister());
destination.set(findRoot(phiNode.getInstructionDefineBegin()[0].getRegisterName(), rangeName));
}
for (InstructionList::iterator p = phiNodes.begin(); !phiNodes.done(p); p = phiNodes.advance(p)) {
Instruction& phiNode = phiNodes.get(p);
assert(phiNode.getInstructionDefineBegin() != phiNode.getInstructionDefineEnd() && phiNode.getInstructionDefineBegin()[0].isRegister());
RegisterName destinationName = phiNode.getInstructionDefineBegin()[0].getRegisterName();
RegisterName destinationRoot = findRoot(destinationName, rangeName);
InstructionUse* useEnd = phiNode.getInstructionUseEnd();
for (InstructionUse* usePtr = phiNode.getInstructionUseBegin(); usePtr < useEnd; usePtr++) {
assert(usePtr->isRegister());
RegisterName sourceName = usePtr->getRegisterName();
RegisterName sourceRoot = findRoot(sourceName, rangeName);
if (sourceRoot != destinationRoot && !destination.test(sourceRoot))
rangeName[sourceRoot] = destinationRoot;
}
}
}
registerAllocator.rangeCount = compress(registerAllocator.name2range, rangeName, nameCount, nameCount);
}
#endif // _LIVE_RANGE_H_

View File

@@ -0,0 +1,163 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _LIVE_RANGE_GRAPH_
#define _LIVE_RANGE_GRAPH_
#include "Fundamentals.h"
#include "Pool.h"
#include "ControlGraph.h"
#include "ControlNodes.h"
#include "Instruction.h"
#include "RegisterTypes.h"
class RegisterAllocator;
template <class RegisterPressure>
class LiveRangeGraph
{
private:
RegisterAllocator& registerAllocator;
RegisterPressure::Set* edges;
Uint32 rangeCount;
public:
//
//
LiveRangeGraph(RegisterAllocator& registerAllocator) : registerAllocator(registerAllocator) {}
//
//
void build();
//
//
void addEdge(RegisterName name1, RegisterName name2);
//
//
bool haveEdge(RegisterName name1, RegisterName name2);
#ifdef DEBUG_LOG
//
//
void printPretty(LogModuleObject log);
#endif // DEBUG_LOG
};
template <class RegisterPressure>
void LiveRangeGraph<RegisterPressure>::build()
{
Pool& pool = registerAllocator.pool;
Uint32 rangeCount = registerAllocator.rangeCount;
this->rangeCount = rangeCount;
edges = new(pool) RegisterPressure::Set(pool, rangeCount * rangeCount);
ControlGraph& controlGraph = registerAllocator.controlGraph;
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
RegisterName* name2range = registerAllocator.name2range;
LivenessInfo<RegisterPressure>& liveness = registerAllocator.liveness;
SparseSet currentLive(pool, rangeCount);
for (Uint32 n = 0; n < nNodes; n++) {
ControlNode& node = *nodes[n];
currentLive = liveness.liveOut[n];
InstructionList& instructions = node.getInstructions();
for (InstructionList::iterator i = instructions.end(); !instructions.done(i); i = instructions.retreat(i)) {
Instruction& instruction = instructions.get(i);
InstructionUse* useBegin = instruction.getInstructionUseBegin();
InstructionUse* useEnd = instruction.getInstructionUseEnd();
InstructionUse* usePtr;
InstructionDefine* defineBegin = instruction.getInstructionDefineBegin();
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
InstructionDefine* definePtr;
if ((instruction.getFlags() & ifCopy) != 0) {
assert(useBegin != useEnd && useBegin[0].isRegister());
currentLive.clear(name2range[useBegin[0].getRegisterName()]);
}
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
if (definePtr->isRegister()) {
RegisterName define = name2range[definePtr->getRegisterName()];
for (SparseSet::iterator l = currentLive.begin(); !currentLive.done(l); l = currentLive.advance(l)) {
RegisterName live = RegisterName(currentLive.get(l));
if (define != live && registerAllocator.canInterfere(define, live))
addEdge(define, live);
}
}
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
if (definePtr->isRegister())
currentLive.clear(name2range[definePtr->getRegisterName()]);
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
if (usePtr->isRegister())
currentLive.set(name2range[usePtr->getRegisterName()]);
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
if (usePtr->isRegister()) {
RegisterName use = name2range[usePtr->getRegisterName()];
for (SparseSet::iterator l = currentLive.begin(); !currentLive.done(l); l = currentLive.advance(l)) {
RegisterName live = RegisterName(currentLive.get(l));
if (use != live && registerAllocator.canInterfere(use, live))
addEdge(use, live);
}
}
}
}
}
template <class RegisterPressure>
void LiveRangeGraph<RegisterPressure>::addEdge(RegisterName name1, RegisterName name2)
{
assert(name1 != name2);
edges->set(name1 * rangeCount + name2);
}
template <class RegisterPressure>
bool LiveRangeGraph<RegisterPressure>::haveEdge(RegisterName name1, RegisterName name2)
{
assert(name1 != name2);
return edges->test(name1 * rangeCount + name2);
}
#ifdef DEBUG_LOG
template <class RegisterPressure>
void LiveRangeGraph<RegisterPressure>::printPretty(LogModuleObject log)
{
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("Live ranges graph:\n"));
for (RegisterName name1 = RegisterName(1); name1 < rangeCount; name1 = RegisterName(name1 + 1)) {
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\t%d:\t", name1));
for (RegisterName name2 = RegisterName(1); name2 < rangeCount; name2 = RegisterName(name2 + 1))
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("%c", ((name1 != name2) && haveEdge(name1, name2)) ? '1' : '0'));
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\n"));
}
}
#endif // DEBUG_LOG
#endif // _LIVE_RANGE_GRAPH_

View File

@@ -0,0 +1,21 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "Fundamentals.h"
#include "Liveness.h"

View File

@@ -0,0 +1,301 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _LIVENESS_H_
#define _LIVENESS_H_
#include "Fundamentals.h"
#include "ControlGraph.h"
#include "ControlNodes.h"
#include "Instruction.h"
#include "RegisterTypes.h"
// ----------------------------------------------------------------------------
// LivenessInfo -
template <class RegisterPressure>
struct LivenessInfo
{
RegisterPressure::Set* liveIn;
RegisterPressure::Set* liveOut;
DEBUG_LOG_ONLY(Uint32 size);
#ifdef DEBUG_LOG
void printPretty(LogModuleObject log);
#endif // DEBUG_LOG
};
// ----------------------------------------------------------------------------
// Liveness
//
// The liveness is defined by the following data-flow equations:
//
// LiveIn(n) = LocalLive(n) U (LiveOut(n) - Killed(n)).
// LiveOut(n) = U LiveIn(s) (s a successor of n).
//
// where LocalLive(n) is the set of used registers in the block n, Killed(n)
// is the set of defined registers in the block n, LiveIn(n) is the set of
// live registers at the begining of the block n and LiveOut(n) is the set
// of live registers at the end of the block n.
//
//
// We will compute the liveness analysis in two stages:
//
// 1- Build LocalLive(n) (wich is an approximation of LiveIn(n)) and Killed(n)
// for each block n.
// 2- Perform a backward data-flow analysis to propagate the liveness information
// through the entire control-flow graph.
//
template <class RegisterPressure>
struct Liveness
{
static LivenessInfo<RegisterPressure> analysis(ControlGraph& controlGraph, Uint32 rangeCount, const RegisterName* name2range);
static LivenessInfo<RegisterPressure> analysis(ControlGraph& controlGraph, Uint32 nameCount);
};
template <class RegisterPressure>
LivenessInfo<RegisterPressure> Liveness<RegisterPressure>::analysis(ControlGraph& controlGraph, Uint32 rangeCount, const RegisterName* name2range)
{
Pool& pool = controlGraph.pool;
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
// Allocate the temporary sets.
RegisterPressure::Set* killed = new(pool) RegisterPressure::Set[nNodes](pool, rangeCount);
// Allocate the globals sets.
RegisterPressure::Set* liveIn = new(pool) RegisterPressure::Set[nNodes](pool, rangeCount);
RegisterPressure::Set* liveOut = new(pool) RegisterPressure::Set[nNodes](pool, rangeCount);
// First stage of the liveness analysis: Compute the sets LocalLive(stored in LiveIn) and Killed.
//
for (Uint32 n = 0; n < (nNodes - 1); n++) {
ControlNode& node = *nodes[n];
RegisterPressure::Set& currentLocalLive = liveIn[n];
RegisterPressure::Set& currentKilled = killed[n];
// Find the instructions contributions to the sets LocalLive and Killed.
//
InstructionList& instructions = node.getInstructions();
for (InstructionList::iterator i = instructions.begin(); !instructions.done(i); i = instructions.advance(i)) {
Instruction& instruction = instructions.get(i);
// If a VirtualRegister is 'used' before being 'defined' then we add it to set LocalLive.
InstructionUse* useEnd = instruction.getInstructionUseEnd();
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
if (usePtr->isRegister()) {
Uint32 index = name2range[usePtr->getRegisterName()];
if (!currentKilled.test(index))
currentLocalLive.set(index);
}
// If a Virtualregister is 'defined' then we add it to the set Killed.
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
for (InstructionDefine* definePtr = instruction.getInstructionDefineBegin(); definePtr < defineEnd; definePtr++)
if (definePtr->isRegister())
currentKilled.set(name2range[definePtr->getRegisterName()]);
}
}
// Second stage of the liveness analysis: We propagate the LiveIn & LiveOut through the entire
// control-flow graph.
//
RegisterPressure::Set temp(pool, rangeCount);
bool changed;
do {
changed = false;
// For all nodes is this graph except the endNode.
for (Int32 n = (nNodes - 2); n >= 0; n--) {
ControlNode& node = *nodes[n];
RegisterPressure::Set& currentLiveIn = liveIn[n];
RegisterPressure::Set& currentLiveOut = liveOut[n];
// Compute temp = Union of LiveIn(s) (s a successor of this node) | usedByPhiNodes(n).
// temp will be the new LiveOut(n).
Uint32 nSuccessors = node.nSuccessors();
if (nSuccessors != 0) {
temp = liveIn[node.nthSuccessor(0).getTarget().dfsNum];
for (Uint32 s = 1; s < nSuccessors; s++)
temp |= liveIn[node.nthSuccessor(s).getTarget().dfsNum];
} else
temp.clear();
// If temp and LiveOut(n) differ then set LiveOut(n) = temp and recalculate the
// new LiveIn(n).
if (currentLiveOut != temp) {
currentLiveOut = temp;
temp -= killed[n]; // FIX: could be optimized with one call to unionDiff !
temp |= currentLiveIn;
if (currentLiveIn != temp) {
currentLiveIn = temp;
changed = true;
}
}
}
} while(changed);
LivenessInfo<RegisterPressure> liveness;
liveness.liveIn = liveIn;
liveness.liveOut = liveOut;
DEBUG_LOG_ONLY(liveness.size = nNodes);
return liveness;
}
template <class RegisterPressure>
LivenessInfo<RegisterPressure> Liveness<RegisterPressure>::analysis(ControlGraph& controlGraph, Uint32 nameCount)
{
Pool& pool = controlGraph.pool;
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
// Allocate the temporary sets.
RegisterPressure::Set* killed = new(pool) RegisterPressure::Set[nNodes](pool, nameCount);
RegisterPressure::Set* usedByPhiNodes = NULL;
// Allocate the globals sets.
RegisterPressure::Set* liveIn = new(pool) RegisterPressure::Set[nNodes](pool, nameCount);
RegisterPressure::Set* liveOut = new(pool) RegisterPressure::Set[nNodes](pool, nameCount);
// First stage of the liveness analysis: Compute the sets LocalLive(stored in LiveIn) and Killed.
//
for (Uint32 n = 0; n < (nNodes - 1); n++) {
ControlNode& node = *nodes[n];
RegisterPressure::Set& currentLocalLive = liveIn[n];
RegisterPressure::Set& currentKilled = killed[n];
InstructionList& phiNodes = node.getPhiNodeInstructions();
if ((usedByPhiNodes == NULL) && !phiNodes.empty())
usedByPhiNodes = new(pool) RegisterPressure::Set[nNodes](pool, nameCount);
for (InstructionList::iterator p = phiNodes.begin(); !phiNodes.done(p); p = phiNodes.advance(p)) {
Instruction& phiNode = phiNodes.get(p);
InstructionDefine& define = phiNode.getInstructionDefineBegin()[0];
currentKilled.set(define.getRegisterName());
typedef DoublyLinkedList<ControlEdge> ControlEdgeList;
const ControlEdgeList& predecessors = node.getPredecessors();
ControlEdgeList::iterator p = predecessors.begin();
InstructionUse* useEnd = phiNode.getInstructionUseEnd();
for (InstructionUse* usePtr = phiNode.getInstructionUseBegin(); usePtr < useEnd; usePtr++, p = predecessors.advance(p))
if (usePtr->isRegister())
usedByPhiNodes[predecessors.get(p).getSource().dfsNum].set(usePtr->getRegisterName());
}
// Find the instructions contributions to the sets LocalLive and Killed.
//
InstructionList& instructions = node.getInstructions();
for (InstructionList::iterator i = instructions.begin(); !instructions.done(i); i = instructions.advance(i)) {
Instruction& instruction = instructions.get(i);
// If a VirtualRegister is 'used' before being 'defined' then we add it to set LocalLive.
InstructionUse* useEnd = instruction.getInstructionUseEnd();
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
if (usePtr->isRegister()) {
Uint32 index = usePtr->getRegisterName();
if (!currentKilled.test(index))
currentLocalLive.set(index);
}
// If a Virtualregister is 'defined' then we add it to the set Killed.
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
for (InstructionDefine* definePtr = instruction.getInstructionDefineBegin(); definePtr < defineEnd; definePtr++)
if (definePtr->isRegister())
currentKilled.set(definePtr->getRegisterName());
}
}
// Second stage of the liveness analysis: We propagate the LiveIn & LiveOut through the entire
// control-flow graph.
//
RegisterPressure::Set temp(pool, nameCount);
bool changed;
do {
changed = false;
// For all nodes is this graph except the endNode.
for (Int32 n = (nNodes - 2); n >= 0; n--) {
ControlNode& node = *nodes[n];
RegisterPressure::Set& currentLiveIn = liveIn[n];
RegisterPressure::Set& currentLiveOut = liveOut[n];
// Compute temp = Union of LiveIn(s) (s a successor of this node) | usedByPhiNodes(n).
// temp will be the new LiveOut(n).
Uint32 nSuccessors = node.nSuccessors();
if (nSuccessors != 0) {
temp = liveIn[node.nthSuccessor(0).getTarget().dfsNum];
for (Uint32 s = 1; s < nSuccessors; s++)
temp |= liveIn[node.nthSuccessor(s).getTarget().dfsNum];
} else
temp.clear();
// Insert the phiNodes contribution.
if (usedByPhiNodes != NULL)
temp |= usedByPhiNodes[n];
// If temp and LiveOut(n) differ then set LiveOut(n) = temp and recalculate the
// new LiveIn(n).
if (currentLiveOut != temp) {
currentLiveOut = temp;
temp -= killed[n]; // FIX: could be optimized with one call to unionDiff !
temp |= currentLiveIn;
if (currentLiveIn != temp) {
currentLiveIn = temp;
changed = true;
}
}
}
} while(changed);
LivenessInfo<RegisterPressure> liveness;
liveness.liveIn = liveIn;
liveness.liveOut = liveOut;
DEBUG_LOG_ONLY(liveness.size = nNodes);
return liveness;
}
#ifdef DEBUG_LOG
template <class RegisterPressure>
void LivenessInfo<RegisterPressure>::printPretty(LogModuleObject log)
{
for (Uint32 n = 0; n < size; n++) {
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("Node N%d:\n\tliveIn = ", n));
liveIn[n].printPretty(log);
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\tliveOut = "));
liveOut[n].printPretty(log);
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\n"));
}
}
#endif // DEBUG_LOG
#endif // _LIVENESS_H_

View File

@@ -0,0 +1,40 @@
#! gmake
DEPTH = ../..
MODULE_NAME = RegisterAllocator
include $(DEPTH)/config/config.mk
INCLUDES += \
-I$(DEPTH)/Utilities/General \
-I$(DEPTH)/Utilities/zlib \
-I$(DEPTH)/Runtime/ClassReader \
-I$(DEPTH)/Runtime/NativeMethods \
-I$(DEPTH)/Runtime/System \
-I$(DEPTH)/Runtime/ClassInfo \
-I$(DEPTH)/Runtime/FileReader \
-I$(DEPTH)/Compiler/PrimitiveGraph \
-I$(DEPTH)/Compiler/FrontEnd \
-I$(DEPTH)/Compiler/Optimizer \
-I$(DEPTH)/Compiler/CodeGenerator \
-I$(DEPTH)/Compiler/CodeGenerator/md \
-I$(DEPTH)/Compiler/CodeGenerator/md/$(CPU_ARCH) \
-I$(DEPTH)/Compiler/RegisterAllocator \
-I$(DEPTH)/Driver/StandAloneJava \
-I$(DEPTH)/Debugger \
$(NULL)
CXXSRCS = \
RegisterAllocator.cpp \
RegisterAllocatorTools.cpp \
DominatorGraph.cpp \
VirtualRegister.cpp \
BitSet.cpp \
SparseSet.cpp \
$(NULL)
include $(DEPTH)/config/rules.mk
libs:: $(MODULE)

View File

@@ -0,0 +1,392 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _PHI_NODE_REMOVER_H_
#define _PHI_NODE_REMOVER_H_
#include "Fundamentals.h"
#include "Pool.h"
#include "ControlGraph.h"
#include "DominatorGraph.h"
#include "VirtualRegister.h"
#include "RegisterPressure.h"
#include "Liveness.h"
#include "Instruction.h"
#include "InstructionEmitter.h"
#include "SparseSet.h"
#include <string.h>
//------------------------------------------------------------------------------
// RegisterNameNode -
struct RegisterNameNode
{
RegisterNameNode* next;
RegisterName newName;
Uint32 nextPushed;
};
//------------------------------------------------------------------------------
// CopyData -
struct CopyData
{
RegisterName source;
RegisterClassKind classKind;
Uint32 useCount;
bool isLiveOut;
RegisterName sourceNameToUse;
RegisterName temporaryName;
RegisterNameNode* newName;
};
//------------------------------------------------------------------------------
// PhiNodeRemover<RegisterPressure> -
template <class RegisterPressure>
struct PhiNodeRemover
{
// Replace the phi nodes by copy instructions.
static void replacePhiNodes(ControlGraph& controlGraph, VirtualRegisterManager& vrManager, InstructionEmitter& emitter);
};
// Split some of the critical edges and return true if there are still some
// in the graph after that.
//
static bool splitCriticalEdges(ControlGraph& /*cg*/)
{
// FIX: not implemented.
return true;
}
inline void pushName(Pool& pool, RegisterNameNode** stack, SparseSet& pushed, Uint32* nodeListPointer, RegisterName oldName, RegisterName newName)
{
RegisterNameNode& newNode = *new(pool) RegisterNameNode();
if (pushed.test(oldName))
(*stack)->newName = newName;
else {
newNode.newName = newName;
newNode.nextPushed = *nodeListPointer;
*nodeListPointer = oldName;
newNode.next = *stack;
*stack = &newNode;
pushed.set(oldName);
}
}
template <class RegisterPressure>
void PhiNodeRemover<RegisterPressure>::replacePhiNodes(ControlGraph& controlGraph, VirtualRegisterManager& vrManager, InstructionEmitter& emitter)
{
Pool& pool = controlGraph.pool;
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
// Initialize the local variables.
//
// When we insert the copies we will also need to create new VirtualRegisters for
// the insertion of temporaries. The maximum number of temporary register will not
// exceed the number of phiNodes in the primitive graph.
Uint32 nameCount = vrManager.getSize();
Uint32 maxNameCount = nameCount;
for (Uint32 n = 0; n < nNodes; n++)
maxNameCount += nodes[n]->getPhiNodes().length();
// If the CFG contains some critical edges (backward edge which source has more than one
// outgoing edge and destination has more than one incomimg edge) then we need the liveness
// information to be able to insert temporary copies.
RegisterPressure::Set* liveOut = NULL;
if (splitCriticalEdges(controlGraph))
liveOut = Liveness<LowRegisterPressure>::analysis(controlGraph, nameCount).liveOut;
DominatorGraph dGraph(controlGraph);
SparseSet pushed(pool, maxNameCount);
SparseSet destinationList(pool, maxNameCount);
SparseSet workList(pool, maxNameCount);
CopyData* copyStats = new(pool) CopyData[maxNameCount];
memset(copyStats, '\0', maxNameCount*sizeof(CopyData));
struct NodeStack {
Uint32* next;
Uint32* limit;
Uint32 pushedList;
};
// Allocate the node stack and initialize the node stack pointer.
NodeStack* nodeStack = new(pool) NodeStack[nNodes + 1];
NodeStack* nodeStackPtr = nodeStack;
// We start by the begin node.
Uint32 startNode = 0;
Uint32* next = &startNode;
Uint32* limit = &startNode + 1;
while (true) {
if (next == limit) {
// If there are no more node in the sibling, we have to pop the current
// frame from the stack and update the copyStats of the pushed nodes.
//
if (nodeStackPtr == nodeStack)
// We are at the bottom of the stack and there are no more nodes
// to look at. We are done !
break;
--nodeStackPtr;
// We are done with all the children of this node in the dominator tree.
// We need to update the copy information of all the new names pushed
// during the walk over this node.
Uint32 pushedList = nodeStackPtr->pushedList;
while (pushedList != 0) {
Uint32 nextName = copyStats[pushedList].newName->nextPushed;
copyStats[pushedList].newName = copyStats[pushedList].newName->next;
pushedList = nextName;
}
// restore the previous frame.
next = nodeStackPtr->next;
limit = nodeStackPtr->limit;
} else {
Uint32 currentNode = *next++;
Uint32 pushedList = 0;
// Initialize the sets.
pushed.clear();
destinationList.clear();
// STEP1:
// Walk the instruction list and to replace all the instruction uses with their new name.
// If the instruction is a phi node and its defined register is alive at the end of this
// block then we push the defined register into the stack.
//
ControlNode& node = *nodes[currentNode];
RegisterPressure::Set* currentLiveOut = (liveOut != NULL) ? &liveOut[currentNode] : (RegisterPressure::Set*) 0;
InstructionList& phiNodes = node.getPhiNodeInstructions();
for (InstructionList::iterator p = phiNodes.begin(); !phiNodes.done(p); p = phiNodes.advance(p)) {
Instruction& phiNode = phiNodes.get(p);
InstructionUse* useEnd = phiNode.getInstructionUseEnd();
for (InstructionUse* usePtr = phiNode.getInstructionUseBegin(); usePtr < useEnd; usePtr++) {
assert(usePtr->isRegister());
RegisterName name = usePtr->getRegisterName();
if (copyStats[name].newName != NULL && copyStats[name].newName->newName != name)
usePtr->setRegisterName(copyStats[name].newName->newName);
}
if (currentLiveOut != NULL) {
// This is a phi node and we have to push its defined name if it is live
// at the end of the node. We only need to do this if the CFG has critical edges.
assert(phiNode.getInstructionDefineBegin() != phiNode.getInstructionDefineEnd() && phiNode.getInstructionDefineBegin()[0].isRegister());
RegisterName name = phiNode.getInstructionDefineBegin()[0].getRegisterName();
if (currentLiveOut->test(name))
pushName(pool, &(copyStats[name].newName), pushed, &pushedList, name, name);
}
}
InstructionList& instructions = node.getInstructions();
for (InstructionList::iterator i = instructions.begin(); !instructions.done(i); i = instructions.advance(i)) {
Instruction& instruction = instructions.get(i);
InstructionUse* useEnd = instruction.getInstructionUseEnd();
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
if (usePtr->isRegister()) {
RegisterName name = usePtr->getRegisterName();
if (copyStats[name].newName != NULL && copyStats[name].newName->newName != name)
usePtr->setRegisterName(copyStats[name].newName->newName);
}
}
// STEP2:
// Look at this node's successors' phiNodes. We keep track of the number of time
// a VR will be used by another copy instruction and insert each definition into the
// destinationList. This is the only pass over this node's successors as we will
// get all the information we need in the CopyData structures.
//
ControlEdge* successorEdgeEnd = node.getSuccessorsEnd();
for (ControlEdge* successorEdgePtr = node.getSuccessorsBegin(); successorEdgePtr < successorEdgeEnd; successorEdgePtr++) {
Uint32 useIndex = successorEdgePtr->getIndex();
ControlNode& successor = successorEdgePtr->getTarget();
// Look at its phi nodes. The phi nodes are at the top of the instruction list. We exit
// as soon as we find an instruction which is not a phi node
InstructionList& phiNodes = successor.getPhiNodeInstructions();
for (InstructionList::iterator p = phiNodes.begin(); !phiNodes.done(p); p = phiNodes.advance(p)) {
Instruction& phiNode = phiNodes.get(p);
assert((phiNode.getInstructionUseBegin() + useIndex) < phiNode.getInstructionUseEnd());
assert(phiNode.getInstructionDefineBegin() != phiNode.getInstructionDefineEnd());
InstructionUse& source = phiNode.getInstructionUseBegin()[useIndex];
InstructionDefine& destination = phiNode.getInstructionDefineBegin()[0];
assert(source.isRegister() && destination.isRegister());
RegisterName sourceName = source.getRegisterName();
RegisterName destinationName = destination.getRegisterName();
// Get the correct name for the source.
if (copyStats[sourceName].newName != NULL)
sourceName = copyStats[sourceName].newName->newName;
// Update the CopyData structures.
if ((sourceName != rnInvalid) && (sourceName != destinationName)) {
copyStats[destinationName].source = sourceName;
copyStats[destinationName].classKind = destination.getRegisterClass();
copyStats[destinationName].isLiveOut = (currentLiveOut != NULL) ? currentLiveOut->test(destinationName) : false;
copyStats[destinationName].sourceNameToUse = destinationName;
copyStats[sourceName].sourceNameToUse = sourceName;
copyStats[sourceName].useCount++;
destinationList.set(destinationName);
}
}
}
// STEP3:
// Insert into the worklist only the destination registers that will be not used in
// another copy instruction in this block.
//
assert(workList.getSize() == 0);
for (SparseSet::iterator d = destinationList.begin(); !destinationList.done(d); d = destinationList.advance(d)) {
Uint32 dest = destinationList.get(d);
if (copyStats[dest].useCount == 0)
workList.set(dest);
}
// STEP4:
// Insert the copy instructions.
//
Uint32 destinationListSize = destinationList.getSize();
InstructionList::iterator endOfTheNode = instructions.end();
// Find the right place to insert the copy instructions.
if (destinationListSize != 0)
while (instructions.get(endOfTheNode).getFlags() & ifControl)
endOfTheNode = instructions.retreat(endOfTheNode);
while (destinationListSize != 0) {
while(workList.getSize()) {
RegisterName destinationName = RegisterName(workList.getOne());
RegisterName sourceName = copyStats[destinationName].source;
workList.clear(destinationName);
if (copyStats[destinationName].isLiveOut && !copyStats[destinationName].temporaryName) {
// Lost copy problem.
copyStats[destinationName].isLiveOut = false;
RegisterName sourceName = destinationName;
RegisterClassKind classKind = copyStats[sourceName].classKind;
RegisterName destinationName = getName(vrManager.newVirtualRegister(classKind));
assert(destinationName < maxNameCount);
copyStats[destinationName].classKind = classKind;
copyStats[sourceName].useCount = 0;
// We need to insert a copy to a temporary register to keep the
// source register valid at the end of the node defining it.
// This copy will be inserted right after the phi node defining it.
RegisterName from = copyStats[sourceName].sourceNameToUse;
Instruction* definingPhiNode = vrManager.getVirtualRegister(from).getDefiningInstruction();
assert(definingPhiNode && (definingPhiNode->getFlags() & ifPhiNode) != 0);
RegisterID fromID = buildRegisterID(from, classKind);
RegisterID toID = buildRegisterID(destinationName, classKind);
Instruction& copy = emitter.newCopy(*definingPhiNode->getPrimitive(), fromID, toID);
vrManager.getVirtualRegister(destinationName).setDefiningInstruction(copy);
definingPhiNode->getPrimitive()->getContainer()->getInstructions().addFirst(copy);
copyStats[sourceName].temporaryName = destinationName;
copyStats[sourceName].sourceNameToUse = destinationName;
pushName(pool, &(copyStats[sourceName].newName), pushed, &pushedList, sourceName, destinationName);
}
// Insert the copy instruction at the end of the current node.
RegisterName from = copyStats[sourceName].sourceNameToUse;
RegisterClassKind classKind = copyStats[destinationName].classKind;
RegisterID fromID = buildRegisterID(from, classKind);
RegisterID toID = buildRegisterID(destinationName, classKind);
Instruction& copy = emitter.newCopy(*vrManager.getVirtualRegister(from).getDefiningInstruction()->getPrimitive(), fromID, toID);
instructions.insertAfter(copy, endOfTheNode);
endOfTheNode = instructions.advance(endOfTheNode);
copyStats[sourceName].useCount = 0;
if (destinationList.test(sourceName) && copyStats[sourceName].isLiveOut)
pushName(pool, &(copyStats[sourceName].newName), pushed, &pushedList, sourceName, destinationName);
copyStats[sourceName].isLiveOut = false;
copyStats[sourceName].sourceNameToUse = destinationName;
if (destinationList.test(sourceName))
workList.set(sourceName);
destinationList.clear(destinationName);
}
destinationListSize = destinationList.getSize();
if (destinationListSize != 0) {
RegisterName sourceName = RegisterName(destinationList.getOne());
RegisterName destinationName;
if (!copyStats[sourceName].temporaryName) {
// Cycle problem.
RegisterClassKind classKind = copyStats[sourceName].classKind;
destinationName = getName(vrManager.newVirtualRegister(classKind));
assert(destinationName < maxNameCount);
copyStats[destinationName].classKind = classKind;
copyStats[sourceName].temporaryName = destinationName;
// Insert the copy instruction at the end of the current node.
RegisterName from = copyStats[sourceName].sourceNameToUse;
RegisterID fromID = buildRegisterID(from, classKind);
RegisterID toID = buildRegisterID(destinationName, classKind);
Instruction& copy = emitter.newCopy(*vrManager.getVirtualRegister(from).getDefiningInstruction()->getPrimitive(), fromID, toID);
vrManager.getVirtualRegister(destinationName).setDefiningInstruction(copy);
instructions.insertAfter(copy, endOfTheNode);
endOfTheNode = instructions.advance(endOfTheNode);
} else
destinationName = copyStats[sourceName].temporaryName;
copyStats[sourceName].useCount = 0;
copyStats[sourceName].isLiveOut = false;
copyStats[sourceName].sourceNameToUse = destinationName;
pushName(pool, &(copyStats[sourceName].newName), pushed, &pushedList, sourceName, destinationName);
workList.set(sourceName);
}
}
nodeStackPtr->pushedList = pushedList;
nodeStackPtr->next = next;
nodeStackPtr->limit = limit;
++nodeStackPtr;
next = dGraph.getSuccessorsBegin(currentNode);
limit = dGraph.getSuccessorsEnd(currentNode);
}
}
}
#endif // _PHI_NODE_REMOVER_H_

View File

@@ -0,0 +1,155 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "Fundamentals.h"
#include "LogModule.h"
#include "RegisterAllocator.h"
#include "RegisterPressure.h"
#include "RegisterAllocatorTools.h"
#include "PhiNodeRemover.h"
#include "LiveRange.h"
#include "Liveness.h"
#include "InterferenceGraph.h"
#include "LiveRangeGraph.h"
#include "Coalescing.h"
#include "Spilling.h"
#include "Coloring.h"
#include "Splits.h"
class Pool;
class ControlGraph;
class VirtualRegisterManager;
class InstructionEmitter;
UT_DEFINE_LOG_MODULE(RegAlloc);
void RegisterAllocator::allocateRegisters(Pool& pool, ControlGraph& controlGraph, VirtualRegisterManager& vrManager, InstructionEmitter& emitter)
{
// Insert the phi node instructions. We want to do this to have a single defined register per instruction.
// If we keep the PhiNode (as a DataNode) and a PhiNode is of DoubleWordKind then we have to execute
// some special code for the high word annotation.
//
RegisterAllocatorTools::insertPhiNodeInstructions(controlGraph, emitter);
// Perform some tests on the instruction graph.
//
DEBUG_ONLY(RegisterAllocatorTools::testTheInstructionGraph(controlGraph, vrManager));
// Replace the phi node instructions by their equivalent copy instructions.
//
PhiNodeRemover<LowRegisterPressure>::replacePhiNodes(controlGraph, vrManager, emitter);
// Do the register allocation.
//
RegisterAllocator registerAllocator(pool, controlGraph, vrManager, emitter);
registerAllocator.doGraphColoring();
}
void RegisterAllocator::doGraphColoring()
{
// Initialize the liverange map.
//
initLiveRanges();
// Build the live ranges. We do this to compress the number of RegisterNames
// used in the insterference graph.
//
LiveRange<LowRegisterPressure>::build(*this);
// Remove unnecessary copies.
//
RegisterAllocatorTools::removeUnnecessaryCopies(*this);
for (Uint8 loop = 0; loop < 10; loop++) {
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("********* RegisterAllocator loop %d *********\n", loop));
while(true) {
// Build the interference graph.
//
iGraph.build();
// Coalesce the copy instructions.
//
if (!Coalescing<LowRegisterPressure>::coalesce(*this))
break;
}
// Print the interference graph.
//
DEBUG_LOG_ONLY(iGraph.printPretty(UT_LOG_MODULE(RegAlloc)));
// Calculate the spill costs.
//
Spilling<LowRegisterPressure>::calculateSpillCosts(*this);
DEBUG_LOG_ONLY(RegisterAllocatorTools::printSpillCosts(*this));
// Calculate the split costs.
//
Splits<LowRegisterPressure>::calculateSplitCosts(*this);
DEBUG_LOG_ONLY(RegisterAllocatorTools::printSplitCosts(*this));
// Build the live range graph.
//
lGraph.build();
DEBUG_LOG_ONLY(lGraph.printPretty(UT_LOG_MODULE(RegAlloc)));
// Color the graph. If it succeeds then we're done with the
// register allocation.
//
if (Coloring<LowRegisterPressure>::color(*this)) {
// Write the final colors in the instruction graph.
//
Coloring<LowRegisterPressure>::finalColoring(*this);
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("********** RegisterAllocator done **********\n"));
DEBUG_LOG_ONLY(RegisterAllocatorTools::printInstructions(*this));
return;
}
// We need to spill some registers.
//
Spilling<LowRegisterPressure>::insertSpillCode(*this);
// Insert the split instructions.
//
Splits<LowRegisterPressure>::insertSplitCode(*this);
// Update the live ranges.
//
// FIX
}
#ifdef DEBUG_LOG
RegisterAllocatorTools::updateInstructionGraph(*this);
RegisterAllocatorTools::printInstructions(*this);
#endif
fprintf(stderr, "!!! Coloring failed after 10 loops !!!\n");
abort();
}
void RegisterAllocator::initLiveRanges()
{
Uint32 count = this->nameCount;
RegisterName* name2range = new(pool) RegisterName[nameCount];
for (RegisterName r = RegisterName(1); r < count; r = RegisterName(r + 1))
name2range[r] = r;
this->name2range = name2range;
rangeCount = count;
}

View File

@@ -0,0 +1,88 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _REGISTER_ALLOCATOR_H_
#define _REGISTER_ALLOCATOR_H_
class Pool;
class ControlGraph;
class InstructionEmitter;
struct SpillCost;
struct SplitCost;
#include "Liveness.h"
#include "VirtualRegister.h"
#include "RegisterPressure.h" // This should included by Backend.cpp
#include "InterferenceGraph.h"
#include "LiveRangeGraph.h"
//template <class RegisterPressure>
class RegisterAllocator
{
public:
Pool& pool; //
ControlGraph& controlGraph; //
VirtualRegisterManager& vrManager; //
InstructionEmitter& emitter; //
RegisterName* name2range; //
RegisterName* color; //
SpillCost* spillCost; //
SparseSet* willSpill; //
SplitCost* splitCost; //
NameLinkedList** splitAround; //
InterferenceGraph<LowRegisterPressure> iGraph; //
LiveRangeGraph<LowRegisterPressure> lGraph; //
LivenessInfo<LowRegisterPressure> liveness; //
Uint32 nameCount; //
Uint32 rangeCount; //
bool splitFound; //
private:
//
//
void doGraphColoring();
public:
//
//
inline RegisterAllocator(Pool& pool, ControlGraph& controlGraph, VirtualRegisterManager& vrManager, InstructionEmitter& emitter);
//
//
bool canInterfere(RegisterName /*name1*/, RegisterName /*name2*/) const {return true;}
//
//
void initLiveRanges();
//
//
static void allocateRegisters(Pool& pool, ControlGraph& controlGraph, VirtualRegisterManager& vrManager, InstructionEmitter& emitter);
};
//
//
inline RegisterAllocator::RegisterAllocator(Pool& pool, ControlGraph& controlGraph, VirtualRegisterManager& vrManager, InstructionEmitter& emitter)
: pool(pool), controlGraph(controlGraph), vrManager(vrManager), emitter(emitter), iGraph(*this), lGraph(*this), nameCount(vrManager.getSize()) {}
#endif // _REGISTER_ALLOCATOR_H_

View File

@@ -0,0 +1,355 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "Fundamentals.h"
#include "LogModule.h"
#include "RegisterAllocatorTools.h"
#include "Pool.h"
#include "ControlGraph.h"
#include "ControlNodes.h"
#include "Primitives.h"
#include "InstructionEmitter.h"
#include "Instruction.h"
#include "RegisterAllocator.h"
#include "Spilling.h"
#include "Splits.h"
#include "BitSet.h"
UT_EXTERN_LOG_MODULE(RegAlloc);
#ifdef DEBUG
void RegisterAllocatorTools::testTheInstructionGraph(ControlGraph& controlGraph, VirtualRegisterManager& vrManager)
{
// Test the declared VirtualRegisters. The register allocator tries to condense the register universe.
// Any gap in the VirtualRegister names will be a loss of efficiency !!!!
Uint32 nameCount = vrManager.getSize();
BitSet registerSeen(controlGraph.pool, nameCount);
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
for (Uint32 n = 0; n < nNodes; n++) {
InstructionList& instructions = nodes[n]->getInstructions();
for (InstructionList::iterator i = instructions.begin(); !instructions.done(i); i = instructions.advance(i)) {
Instruction& instruction = instructions.get(i);
InstructionUse* useEnd = instruction.getInstructionUseEnd();
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
if (usePtr->isRegister())
registerSeen.set(usePtr->getRegisterName());
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
for (InstructionDefine* definePtr = instruction.getInstructionDefineBegin(); definePtr < defineEnd; definePtr++)
if (definePtr->isRegister())
registerSeen.set(definePtr->getRegisterName());
}
InstructionList& phiNodes = nodes[n]->getPhiNodeInstructions();
for (InstructionList::iterator p = phiNodes.begin(); !phiNodes.done(p); p = phiNodes.advance(p)) {
Instruction& instruction = phiNodes.get(p);
InstructionUse* useEnd = instruction.getInstructionUseEnd();
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
if (usePtr->isRegister())
registerSeen.set(usePtr->getRegisterName());
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
for (InstructionDefine* definePtr = instruction.getInstructionDefineBegin(); definePtr < defineEnd; definePtr++)
if (definePtr->isRegister())
registerSeen.set(definePtr->getRegisterName());
}
}
bool renameRegisters = false;
for (BitSet::iterator i = registerSeen.nextZero(0); !registerSeen.done(i); i = registerSeen.nextZero(i)) {
renameRegisters = true;
fprintf(stderr,
"WARNING: The VirtualRegister vr%d has been allocated during CodeGeneration but\n"
" is never used nor defined by any instruction in the instruction graph\n"
" PLEASE FIX \n",
i);
}
if (renameRegisters) {
Instruction** definingInstruction = new Instruction*[nameCount];
memset(definingInstruction, '\0', nameCount * sizeof(Instruction*));
RegisterName* newName = new RegisterName[nameCount];
memset(newName, '\0', nameCount * sizeof(RegisterName));
RegisterName nextName = RegisterName(1);
for (Uint32 n = 0; n < nNodes; n++) {
InstructionList& instructions = nodes[n]->getInstructions();
for (InstructionList::iterator i = instructions.begin(); !instructions.done(i); i = instructions.advance(i)) {
Instruction& instruction = instructions.get(i);
InstructionUse* useEnd = instruction.getInstructionUseEnd();
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
if (usePtr->isRegister()) {
RegisterName name = usePtr->getRegisterName();
if (newName[name] == rnInvalid) {
newName[name] = nextName;
definingInstruction[nextName] = vrManager.getVirtualRegister(name).getDefiningInstruction();
nextName = RegisterName(nextName + 1);
}
usePtr->setRegisterName(newName[name]);
}
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
for (InstructionDefine* definePtr = instruction.getInstructionDefineBegin(); definePtr < defineEnd; definePtr++)
if (definePtr->isRegister()) {
RegisterName name = definePtr->getRegisterName();
if (newName[name] == rnInvalid) {
newName[name] = nextName;
definingInstruction[nextName] = vrManager.getVirtualRegister(name).getDefiningInstruction();
nextName = RegisterName(nextName + 1);
}
definePtr->setRegisterName(newName[name]);
}
}
InstructionList& phiNodes = nodes[n]->getPhiNodeInstructions();
for (InstructionList::iterator p = phiNodes.begin(); !phiNodes.done(p); p = phiNodes.advance(p)) {
Instruction& instruction = phiNodes.get(p);
InstructionUse* useEnd = instruction.getInstructionUseEnd();
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
if (usePtr->isRegister()) {
RegisterName name = usePtr->getRegisterName();
if (newName[name] == rnInvalid) {
newName[name] = nextName;
definingInstruction[nextName] = vrManager.getVirtualRegister(name).getDefiningInstruction();
nextName = RegisterName(nextName + 1);
}
usePtr->setRegisterName(newName[name]);
}
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
for (InstructionDefine* definePtr = instruction.getInstructionDefineBegin(); definePtr < defineEnd; definePtr++)
if (definePtr->isRegister()) {
RegisterName name = definePtr->getRegisterName();
if (newName[name] == rnInvalid) {
newName[name] = nextName;
definingInstruction[nextName] = vrManager.getVirtualRegister(name).getDefiningInstruction();
nextName = RegisterName(nextName + 1);
}
definePtr->setRegisterName(newName[name]);
}
}
}
vrManager.setSize(nextName);
for (RegisterName r = RegisterName(1); r < nextName; r = RegisterName(r + 1))
vrManager.getVirtualRegister(r).definingInstruction = definingInstruction[r];
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("RegisterMap:\n"));
for (Uint32 i = 1; i < nameCount; i++)
if (newName[i] != 0)
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\tvr%d becomes vr%d.\n", i, newName[i]));
else
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\tvr%d is dead.\n", i));
delete newName;
delete definingInstruction;
}
}
#endif // DEBUG
void RegisterAllocatorTools::removeUnnecessaryCopies(RegisterAllocator& registerAllocator)
{
ControlGraph& controlGraph = registerAllocator.controlGraph;
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
RegisterName* name2range = registerAllocator.name2range;
for (Uint32 n = 0; n < nNodes; n++) {
InstructionList& instructions = nodes[n]->getInstructions();
for (InstructionList::iterator i = instructions.begin(); !instructions.done(i);) {
Instruction& instruction = instructions.get(i);
i = instructions.advance(i);
if (instruction.getFlags() & ifCopy) {
assert(instruction.getInstructionUseBegin() != instruction.getInstructionUseEnd() && instruction.getInstructionUseBegin()[0].isRegister());
assert(instruction.getInstructionDefineBegin() != instruction.getInstructionDefineEnd() && instruction.getInstructionDefineBegin()[0].isRegister());
RegisterName source = name2range[instruction.getInstructionUseBegin()[0].getRegisterName()];
RegisterName destination = name2range[instruction.getInstructionDefineBegin()[0].getRegisterName()];
if (source == destination)
instruction.remove();
}
}
}
}
void RegisterAllocatorTools::updateInstructionGraph(RegisterAllocator& registerAllocator)
{
ControlGraph& controlGraph = registerAllocator.controlGraph;
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
RegisterName* name2range = registerAllocator.name2range;
for (Uint32 n = 0; n < nNodes; n++) {
InstructionList& instructions = nodes[n]->getInstructions();
for (InstructionList::iterator i = instructions.begin(); !instructions.done(i); i = instructions.advance(i)) {
Instruction& instruction = instructions.get(i);
InstructionUse* useEnd = instruction.getInstructionUseEnd();
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
if (usePtr->isRegister())
usePtr->setRegisterName(name2range[usePtr->getRegisterName()]);
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
for (InstructionDefine* definePtr = instruction.getInstructionDefineBegin(); definePtr < defineEnd; definePtr++)
if (definePtr->isRegister())
definePtr->setRegisterName(name2range[definePtr->getRegisterName()]);
}
InstructionList& phiNodes = nodes[n]->getPhiNodeInstructions();
for (InstructionList::iterator p = phiNodes.begin(); !phiNodes.done(p); p = phiNodes.advance(p)) {
Instruction& instruction = phiNodes.get(p);
InstructionUse* useEnd = instruction.getInstructionUseEnd();
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
if (usePtr->isRegister())
usePtr->setRegisterName(name2range[usePtr->getRegisterName()]);
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
for (InstructionDefine* definePtr = instruction.getInstructionDefineBegin(); definePtr < defineEnd; definePtr++)
if (definePtr->isRegister())
definePtr->setRegisterName(name2range[definePtr->getRegisterName()]);
}
}
}
void RegisterAllocatorTools::insertPhiNodeInstructions(ControlGraph& controlGraph, InstructionEmitter& emitter)
{
Pool& pool = controlGraph.pool;
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
for (Uint32 n = 0; n < nNodes; n++) {
ControlNode& node = *nodes[n];
DoublyLinkedList<PhiNode>& phiNodes = node.getPhiNodes();
if (!phiNodes.empty()) {
// Set the index of the incoming edges.
Uint32 index = 0;
const DoublyLinkedList<ControlEdge>& predecessors = node.getPredecessors();
for (DoublyLinkedList<ControlEdge>::iterator p = predecessors.begin(); !predecessors.done(p); p = predecessors.advance(p))
predecessors.get(p).setIndex(index++);
// Insert the phi node instruction in the instruction list.
for (DoublyLinkedList<PhiNode>::iterator i = phiNodes.begin(); !phiNodes.done(i); i = phiNodes.advance(i)) {
PhiNode& phiNode = phiNodes.get(i);
ValueKind kind = phiNode.getKind();
if (!isStorableKind(kind))
continue;
RegisterClassKind classKind = rckGeneral; // FIX: get class kind from phi node kind.
Uint32 nInputs = phiNode.nInputs();
PhiNodeInstruction& phiNodeInstruction = *new(pool) PhiNodeInstruction(&phiNode, pool, nInputs);
emitter.defineProducer(phiNode, phiNodeInstruction, 0, classKind, drLow);
for (Uint32 whichInput = 0; whichInput < nInputs; whichInput++)
emitter.useProducer(phiNode.nthInputVariable(whichInput), phiNodeInstruction, whichInput, classKind, drLow);
node.addPhiNodeInstruction(phiNodeInstruction);
if (isDoublewordKind(kind)) {
PhiNodeInstruction& phiNodeInstruction = *new(pool) PhiNodeInstruction(&phiNode, pool, nInputs);
emitter.defineProducer(phiNode, phiNodeInstruction, 0, classKind, drHigh);
for (Uint32 whichInput = 0; whichInput < nInputs; whichInput++)
emitter.useProducer(phiNode.nthInputVariable(whichInput), phiNodeInstruction, whichInput, classKind, drHigh);
node.addPhiNodeInstruction(phiNodeInstruction);
}
}
}
}
}
#ifdef DEBUG_LOG
void RegisterAllocatorTools::printSpillCosts(RegisterAllocator& registerAllocator)
{
LogModuleObject log = UT_LOG_MODULE(RegAlloc);
Uint32 rangeCount = registerAllocator.rangeCount;
SpillCost* cost = registerAllocator.spillCost;
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("Spill costs:\n"));
for (Uint32 i = 1; i < rangeCount; i++) {
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\trange %d : ", i));
if (cost[i].infinite)
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("infinite\n"));
else
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("%f\n", cost[i].cost));
}
}
void RegisterAllocatorTools::printSplitCosts(RegisterAllocator& registerAllocator)
{
LogModuleObject log = UT_LOG_MODULE(RegAlloc);
Uint32 rangeCount = registerAllocator.rangeCount;
SplitCost* cost = registerAllocator.splitCost;
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("Split costs:\n"));
for (Uint32 i = 1; i < rangeCount; i++) {
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\trange %d : loads = %f stores = %f\n", i, cost[i].loads, cost[i].stores));
}
}
void RegisterAllocatorTools::printInstructions(RegisterAllocator& registerAllocator)
{
LogModuleObject log = UT_LOG_MODULE(RegAlloc);
ControlNode** nodes = registerAllocator.controlGraph.dfsList;
Uint32 nNodes = registerAllocator.controlGraph.nNodes;
for (Uint32 n = 0; n < nNodes; n++) {
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("N%d:\n", n));
InstructionList& phiNodes = nodes[n]->getPhiNodeInstructions();
InstructionList& instructions = nodes[n]->getInstructions();
if (!phiNodes.empty()) {
UT_OBJECTLOG(log, PR_LOG_ALWAYS, (" PhiNodes:\n", n));
for(InstructionList::iterator i = phiNodes.begin(); !phiNodes.done(i); i = phiNodes.advance(i)) {
phiNodes.get(i).printPretty(log);
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\n"));
}
if (!instructions.empty())
UT_OBJECTLOG(log, PR_LOG_ALWAYS, (" Instructions:\n", n));
}
for(InstructionList::iterator i = instructions.begin(); !instructions.done(i); i = instructions.advance(i)) {
instructions.get(i).printPretty(log);
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\n"));
}
}
}
#endif // DEBUG_LOG

View File

@@ -0,0 +1,117 @@
// -*- mode:C++; tab-width:4; truncate-lines:t -*-
//
// CONFIDENTIAL AND PROPRIETARY SOURCE CODE OF
// NETSCAPE COMMUNICATIONS CORPORATION
// Copyright © 1996, 1997 Netscape Communications Corporation. All Rights
// Reserved. Use of this Source Code is subject to the terms of the
// applicable license agreement from Netscape Communications Corporation.
// The copyright notice(s) in this Source Code does not indicate actual or
// intended publication of this Source Code.
//
// $Id: RegisterAllocatorTools.h,v 1.1.2.1 1999-03-02 16:12:05 fur%netscape.com Exp $
//
#ifndef _REGISTER_ALLOCATOR_TOOLS_H_
#define _REGISTER_ALLOCATOR_TOOLS_H_
#include "LogModule.h"
#include "RegisterTypes.h"
#include <string.h>
class RegisterAllocator;
class ControlGraph;
class InstructionEmitter;
class VirtualRegisterManager;
struct RegisterAllocatorTools
{
//
//
static void insertPhiNodeInstructions(ControlGraph& controlGraph, InstructionEmitter& emitter);
//
//
static void updateInstructionGraph(RegisterAllocator& registerAllocator);
//
//
static void removeUnnecessaryCopies(RegisterAllocator& registerAllocator);
#ifdef DEBUG
//
//
static void testTheInstructionGraph(ControlGraph& controlGraph, VirtualRegisterManager& vrManager);
#endif // DEBUG
#ifdef DEBUG_LOG
//
//
static void printInstructions(RegisterAllocator& registerAllocator);
//
//
static void printSpillCosts(RegisterAllocator& registerAllocator);
//
//
static void printSplitCosts(RegisterAllocator& registerAllocator);
#endif // DEBUG_LOG
};
//
// FIX: this should go in a class (LookupTable ?)
//
inline RegisterName findRoot(RegisterName name, RegisterName* table)
{
RegisterName* stack = table;
RegisterName* stackPtr = stack;
RegisterName newName;
while((newName = table[name]) != name) {
*--stackPtr = name;
name = newName;
}
while (stackPtr != stack)
table[*stackPtr++] = name;
return name;
}
inline void init(RegisterName* table, Uint32 nameCount)
{
for (RegisterName r = RegisterName(0); r < nameCount; r = RegisterName(r + 1))
table[r] = r;
}
inline Uint32 compress(RegisterName* name2range, RegisterName* table, Uint32 nameCount, Uint32 tableSize)
{
RegisterName* liveRange = new RegisterName[tableSize];
memset(liveRange, '\0', tableSize * sizeof(RegisterName));
// Update the lookup table.
for (RegisterName r = RegisterName(1); r < tableSize; r = RegisterName(r + 1))
findRoot(r, table);
// Count the liveranges.
Uint32 liveRangeCount = 1;
for (RegisterName s = RegisterName(1); s < tableSize; s = RegisterName(s + 1))
if (table[s] == s)
liveRange[s] = RegisterName(liveRangeCount++);
for (RegisterName t = RegisterName(1); t < nameCount; t = RegisterName(t + 1))
name2range[t] = liveRange[table[name2range[t]]];
return liveRangeCount;
}
inline double doLog10(Uint32 power)
{
double log = 1.0;
while (power--)
log *= 10.0;
return log;
}
#endif // _REGISTER_ALLOCATOR_TOOLS_H_

View File

@@ -0,0 +1,38 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _REGISTER_ASSIGNER_H_
#define _REGISTER_ASSIGNER_H_
#include "Fundamentals.h"
#include "VirtualRegister.h"
class FastBitMatrix;
class RegisterAssigner
{
protected:
VirtualRegisterManager& vRegManager;
public:
RegisterAssigner(VirtualRegisterManager& vrMan) : vRegManager(vrMan) {}
virtual bool assignRegisters(FastBitMatrix& interferenceMatrix) = 0;
};
#endif /* _REGISTER_ASSIGNER_H_ */

View File

@@ -0,0 +1,25 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _REGISTER_CLASS_H_
#define _REGISTER_CLASS_H_
#include "Fundamentals.h"
#include "RegisterTypes.h"
#endif // _REGISTER_CLASS_H_

View File

@@ -0,0 +1,37 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _REGISTER_PRESSURE_H_
#define _REGISTER_PRESSURE_H_
#include "BitSet.h"
#include "HashSet.h"
struct LowRegisterPressure
{
typedef BitSet Set;
static const bool setIsOrdered = true;
};
struct HighRegisterPressure
{
typedef HashSet Set;
static const bool setIsOrdered = false;
};
#endif // _REGISTER_PRESSURE_H_

View File

@@ -0,0 +1,104 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _REGISTER_TYPES_H_
#define _REGISTER_TYPES_H_
#include "Fundamentals.h"
//------------------------------------------------------------------------------
// RegisterName -
//
enum RegisterName {
rnInvalid = 0,
};
//------------------------------------------------------------------------------
// RegisterClassKind -
//
enum RegisterClassKind {
rckInvalid = 0,
rckGeneral,
rckStackSlot,
nRegisterClassKind
};
//------------------------------------------------------------------------------
// RegisterID -
//
enum RegisterID {
invalidID = 0
};
//------------------------------------------------------------------------------
// RegisterKind -
//
enum RegisterKind {
rkCallerSave = 0,
rkCalleeSave,
};
struct NameLinkedList {
RegisterName name;
NameLinkedList* next;
};
#ifdef DEBUG
const registerNameMask = 0x03ffffff;
const coloredRegisterMask = 0x04000000;
const machineRegisterMask = 0x08000000;
const registerClassMask = 0xf0000000;
const registerNameShift = 0;
const coloredRegisterShift = 26;
const machineRegisterShift = 27;
const registerClassShift = 28;
#else // DEBUG
const registerNameMask = 0x0fffffff;
const registerClassMask = 0xf0000000;
const registerNameShift = 0;
const registerClassShift = 28;
#endif // DEBUG
inline RegisterClassKind getClass(RegisterID registerID) {return RegisterClassKind((registerID & registerClassMask) >> registerClassShift);}
inline RegisterName getName(RegisterID registerID) {return RegisterName((registerID & registerNameMask) >> registerNameShift);}
inline void setClass(RegisterID& registerID, RegisterClassKind classKind) {registerID = RegisterID((registerID & ~registerClassMask) | ((classKind << registerClassShift) & registerClassMask));}
inline void setName(RegisterID& registerID, RegisterName name) {assert((name & ~registerNameMask) == 0); registerID = RegisterID((registerID & ~registerNameMask) | ((name << registerNameShift) & registerNameMask));}
inline RegisterID buildRegisterID(RegisterName name, RegisterClassKind classKind) {return RegisterID(((classKind << registerClassShift) & registerClassMask) | ((name << registerNameShift) & registerNameMask));}
#ifdef DEBUG
inline bool isMachineRegister(RegisterID rid) {return (rid & machineRegisterMask) != 0;}
inline void setMachineRegister(RegisterID& rid) {rid = RegisterID(rid | machineRegisterMask);}
inline bool isColoredRegister(RegisterID rid) {return (rid & coloredRegisterMask) != 0;}
inline void setColoredRegister(RegisterID& rid) {rid = RegisterID(rid | coloredRegisterMask);}
#endif // DEBUG
#endif // _REGISTER_TYPES_H_

View File

@@ -0,0 +1,32 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "Fundamentals.h"
#include "SSATools.h"
#include "ControlGraph.h"
#include "VirtualRegister.h"
#include "Liveness.h"
void replacePhiNodes(ControlGraph& controlGraph, VirtualRegisterManager& vrManager)
{
if (!controlGraph.hasBackEdges)
return;
Liveness liveness(controlGraph.pool);
liveness.buildLivenessAnalysis(controlGraph, vrManager);
}

View File

@@ -0,0 +1,29 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _SSA_TOOLS_H_
#define _SSA_TOOLS_H_
#include "Fundamentals.h"
class ControlGraph;
class VirtualRegisterManager;
extern void replacePhiNodes(ControlGraph& controlGraph, VirtualRegisterManager& vrManager);
#endif // _SSA_TOOLS_H_

View File

@@ -0,0 +1,37 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "Fundamentals.h"
#include "SparseSet.h"
#include "BitSet.h"
#include "Pool.h"
#ifdef DEBUG_LOG
// Print the set.
//
void SparseSet::printPretty(LogModuleObject log)
{
Pool pool;
BitSet set(pool, universeSize);
for (Uint32 i = 0; i < count; i++)
set.set(node[i].element);
set.printPretty(log);
}
#endif // DEBUG_LOG

View File

@@ -0,0 +1,168 @@
// -*- mode:C++; tab-width:4; truncate-lines:t -*-
//
// CONFIDENTIAL AND PROPRIETARY SOURCE CODE OF
// NETSCAPE COMMUNICATIONS CORPORATION
// Copyright © 1996, 1997 Netscape Communications Corporation. All Rights
// Reserved. Use of this Source Code is subject to the terms of the
// applicable license agreement from Netscape Communications Corporation.
// The copyright notice(s) in this Source Code does not indicate actual or
// intended publication of this Source Code.
//
// $Id: SparseSet.h,v 1.1.2.1 1999-03-02 16:12:07 fur%netscape.com Exp $
//
#ifndef _SPARSE_SET_H_
#define _SPARSE_SET_H_
#include "Fundamentals.h"
#include "Pool.h"
#include "LogModule.h"
#include "BitSet.h"
class SparseSet
{
private:
struct Node {
Uint32 element;
Uint32 stackIndex;
};
Node* node;
Uint32 count;
Uint32 universeSize;
private:
// No copy constructor.
SparseSet(const SparseSet&);
// Check if the given set's universe is of the same size than this universe.
void checkUniverseCompatibility(const SparseSet& set) const {assert(set.universeSize == universeSize);}
// Check if pos is valid for this set's universe.
void checkMember(Int32 pos) const {assert(pos >=0 && Uint32(pos) < universeSize);}
public:
SparseSet(Pool& pool, Uint32 universeSize) : universeSize(universeSize) {node = new(pool) Node[universeSize]; clear();}
// Clear the sparse set.
void clear() {count = 0;}
// Clear the element at index.
inline void clear(Uint32 index);
// Set the element at index.
inline void set(Uint32 index);
// Return true if the element at index is set.
inline bool test(Uint32 index) const;
// Union with the given sparse set.
inline void or(const SparseSet& set);
// Intersection with the given sparse set.
inline void and(const SparseSet& set);
// Difference with the given sparse set.
inline void difference(const SparseSet& set);
// Copy set.
inline SparseSet& operator = (const SparseSet& set);
inline SparseSet& operator = (const BitSet& set);
// Return true if the sparse sets are identical.
friend bool operator == (const SparseSet& set1, const SparseSet& set2);
// Return true if the sparse sets are different.
friend bool operator != (const SparseSet& set1, const SparseSet& set2);
// Logical operators.
SparseSet& operator |= (const SparseSet& set) {or(set); return *this;}
SparseSet& operator &= (const SparseSet& set) {and(set); return *this;}
SparseSet& operator -= (const SparseSet& set) {difference(set); return *this;}
// Iterator to conform with the set API.
typedef Int32 iterator;
// Return the iterator for the first element of this set.
iterator begin() const {return count - 1;}
// Return the next iterator.
iterator advance(iterator pos) const {return --pos;}
// Return true if the iterator is at the end of the set.
bool done(iterator pos) const {return pos < 0;}
// Return the element for the given iterator;
Uint32 get(iterator pos) const {return node[pos].element;}
// Return one element of this set.
Uint32 getOne() const {assert(count > 0); return node[0].element;}
// Return the size of this set.
Uint32 getSize() const {return count;}
#ifdef DEBUG_LOG
// Print the set.
void printPretty(LogModuleObject log);
#endif // DEBUG_LOG
};
inline void SparseSet::clear(Uint32 element)
{
checkMember(element);
Uint32 count = this->count;
Node* node = this->node;
Uint32 stackIndex = node[element].stackIndex;
if ((stackIndex < count) && (node[stackIndex].element == element)) {
Uint32 stackTop = node[count - 1].element;
node[stackIndex].element = stackTop;
node[stackTop].stackIndex = stackIndex;
this->count = count - 1;
}
}
inline void SparseSet::set(Uint32 element)
{
checkMember(element);
Uint32 count = this->count;
Node* node = this->node;
Uint32 stackIndex = node[element].stackIndex;
if ((stackIndex >= count) || (node[stackIndex].element != element)) {
node[count].element = element;
node[element].stackIndex = count;
this->count = count + 1;
}
}
inline bool SparseSet::test(Uint32 element) const
{
checkMember(element);
Node* node = this->node;
Uint32 stackIndex = node[element].stackIndex;
return ((stackIndex < count) && (node[stackIndex].element == element));
}
inline SparseSet& SparseSet::operator = (const SparseSet& set)
{
checkUniverseCompatibility(set);
Uint32 sourceCount = set.getSize();
Node* node = this->node;
memcpy(node, set.node, sourceCount * sizeof(Node));
for (Uint32 i = 0; i < sourceCount; i++) {
Uint32 element = node[i].element;
node[element].stackIndex = i;
}
count = sourceCount;
return *this;
}
inline SparseSet& SparseSet::operator = (const BitSet& set)
{
// FIX: there's room for optimization here.
assert(universeSize == set.getSize());
clear();
for (Int32 i = set.firstOne(); i != -1; i = set.nextOne(i))
this->set(i);
return *this;
}
#endif // _SPARSE_SET_H_

View File

@@ -0,0 +1,270 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef NEW_LAURENTM_CODE
#define INCLUDE_EMITTER
#include "CpuInfo.h"
#include "Fundamentals.h"
#include "ControlNodes.h"
#include "Instruction.h"
#include "InstructionEmitter.h"
#include "Spilling.h"
void Spilling::
insertSpillCode(ControlNode** dfsList, Uint32 nNodes)
{
PRUint32 nVirtualRegisters = vRegManager.count();
FastBitSet currentLive(vRegManager.pool, nVirtualRegisters);
FastBitSet usedInThisInstruction(vRegManager.pool, nVirtualRegisters);
RegisterFifo grNeedLoad(nVirtualRegisters);
RegisterFifo fpNeedLoad(nVirtualRegisters);
for (PRInt32 n = nNodes - 1; n >= 0; n--)
{
PR_ASSERT(grNeedLoad.empty() & fpNeedLoad.empty());
ControlNode& node = *dfsList[n];
currentLive = node.liveAtEnd;
PRUint32 nGeneralAlive = 0;
PRUint32 nFloatingPointAlive = 0;
// Get the number of registers alive at the end of this node.
for (PRInt32 j = currentLive.firstOne(); j != -1; j = currentLive.nextOne(j))
{
VirtualRegister& vReg = vRegManager.getVirtualRegister(j);
if (vReg.spillInfo.willSpill)
{
currentLive.clear(j);
}
else
{
switch (vReg.getClass())
{
case vrcInteger:
nGeneralAlive++;
break;
case vrcFloatingPoint:
case vrcFixedPoint:
nFloatingPointAlive++;
break;
default:
break;
}
}
}
// if(node.dfsNum == 8) printf("\n________Begin Node %d________\n", node.dfsNum);
InstructionList& instructions = node.getInstructions();
for (InstructionList::iterator i = instructions.end(); !instructions.done(i); i = instructions.retreat(i))
{
Instruction& instruction = instructions.get(i);
InstructionUse* useBegin = instruction.getInstructionUseBegin();
InstructionUse* useEnd = instruction.getInstructionUseEnd();
InstructionUse* usePtr;
InstructionDefine* defBegin = instruction.getInstructionDefineBegin();
InstructionDefine* defEnd = instruction.getInstructionDefineEnd();
InstructionDefine* defPtr;
// if(node.dfsNum == 8) { printf("\n");
// instruction.printPretty(stdout);
// printf("\n"); }
// Handle definitions
for (defPtr = defBegin; defPtr < defEnd; defPtr++)
if (defPtr->isVirtualRegister())
{
VirtualRegister& vReg = defPtr->getVirtualRegister();
currentLive.clear(vReg.getRegisterIndex());
switch (vReg.getClass())
{
case vrcInteger:
nGeneralAlive--;
break;
case vrcFloatingPoint:
case vrcFixedPoint:
nFloatingPointAlive--;
break;
default:
break;
}
}
// Check for deaths
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
if (usePtr->isVirtualRegister())
{
VirtualRegister& vReg = usePtr->getVirtualRegister();
if (!currentLive.test(vReg.getRegisterIndex()))
// This is the last use of this register.
{
currentLive.set(vReg.getRegisterIndex());
switch (vReg.getClass())
{
case vrcInteger:
nGeneralAlive++;
while (/*(nGeneralAlive > NUMBER_OF_GREGISTERS) &&*/ !grNeedLoad.empty())
{
PRUint32 toLoad = grNeedLoad.get();
currentLive.clear(toLoad);
nGeneralAlive--;
VirtualRegister& nReg = vRegManager.getVirtualRegister(toLoad);
Instruction& lastUsingInstruction = *nReg.spillInfo.lastUsingInstruction;
emitter.emitLoadAfter(*lastUsingInstruction.getPrimitive(), lastUsingInstruction.getLinks().prev,
nReg.getAlias(), *nReg.equivalentRegister[vrcStackSlot]);
nReg.releaseSelf();
}
break;
case vrcFloatingPoint:
case vrcFixedPoint:
nFloatingPointAlive++;
while (/*(nFloatingPointAlive > NUMBER_OF_FPREGISTERS) &&*/ !fpNeedLoad.empty())
{
PRUint32 toLoad = fpNeedLoad.get();
currentLive.clear(toLoad);
nFloatingPointAlive--;
VirtualRegister& nReg = vRegManager.getVirtualRegister(toLoad);
Instruction& lastUsingInstruction = *nReg.spillInfo.lastUsingInstruction;
emitter.emitLoadAfter(*lastUsingInstruction.getPrimitive(), lastUsingInstruction.getLinks().prev,
nReg.getAlias(), *nReg.equivalentRegister[vrcStackSlot]);
nReg.releaseSelf();
}
break;
default:
break;
}
}
}
// Handle uses
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
if (usePtr->isVirtualRegister())
{
VirtualRegister& vReg = usePtr->getVirtualRegister();
PRUint32 registerIndex = vReg.getRegisterIndex();
if (vReg.spillInfo.willSpill) {
#if defined(GENERATE_FOR_X86)
if (!instruction.switchUseToSpill((usePtr - useBegin), *vReg.equivalentRegister[vrcStackSlot]))
#endif
{
switch (vReg.getClass())
{
case vrcInteger:
if (!grNeedLoad.test(registerIndex))
{
grNeedLoad.put(registerIndex);
VirtualRegister& alias = vRegManager.newVirtualRegister(vrcInteger);
if (vReg.isPreColored())
alias.preColorRegister(vReg.getPreColor());
/* if (vReg.hasSpecialInterference) {
alias.specialInterference.sizeTo(NUMBER_OF_REGISTERS);
alias.specialInterference = vReg.specialInterference;
alias.hasSpecialInterference = true;
} */
vReg.setAlias(alias);
vReg.retainSelf();
}
break;
case vrcFloatingPoint:
case vrcFixedPoint:
if (!fpNeedLoad.test(registerIndex))
{
fpNeedLoad.put(registerIndex);
VirtualRegister& alias = vRegManager.newVirtualRegister(vReg.getClass());
if (vReg.isPreColored())
alias.preColorRegister(vReg.getPreColor());
/*if (vReg.hasSpecialInterference) {
alias.specialInterference.sizeTo(NUMBER_OF_REGISTERS);
alias.specialInterference = vReg.specialInterference;
alias.hasSpecialInterference = true;
} */
vReg.setAlias(alias);
vReg.retainSelf();
}
break;
default:
break;
}
usePtr->getVirtualRegisterPtr().initialize(vReg.getAlias());
usedInThisInstruction.set(registerIndex);
vReg.spillInfo.lastUsingInstruction = &instruction;
}
currentLive.clear(registerIndex);
} else { // will not spill
currentLive.set(registerIndex);
}
}
// Handle definitions
for (defPtr = defBegin; defPtr < defEnd; defPtr++)
if (defPtr->isVirtualRegister())
{
VirtualRegister& vReg = defPtr->getVirtualRegister();
if (vReg.spillInfo.willSpill)
#if defined(GENERATE_FOR_X86)
if (!instruction.switchDefineToSpill((defPtr - defBegin), *vReg.equivalentRegister[vrcStackSlot]))
#endif
{
if (usedInThisInstruction.test(vReg.getRegisterIndex()))
// this virtualRegister was used in this instruction and is also defined. We need to move
// this virtual register to its alias first and then save it to memory.
{
emitter.emitStoreAfter(*instruction.getPrimitive(), &instruction.getLinks(),
vReg.getAlias(), *vReg.equivalentRegister[vrcStackSlot]);
defPtr->getVirtualRegisterPtr().initialize(vReg.getAlias());
}
else
{
emitter.emitStoreAfter(*instruction.getPrimitive(), &instruction.getLinks(),
vReg, *vReg.equivalentRegister[vrcStackSlot]);
}
}
}
}
while (!grNeedLoad.empty())
{
PRUint32 nl = grNeedLoad.get();
VirtualRegister& nlReg = vRegManager.getVirtualRegister(nl);
Instruction& lastUse = *nlReg.spillInfo.lastUsingInstruction;
emitter.emitLoadAfter(*lastUse.getPrimitive(), lastUse.getLinks().prev,
nlReg.getAlias(), *nlReg.equivalentRegister[vrcStackSlot]);
nlReg.releaseSelf();
}
while (!fpNeedLoad.empty())
{
PRUint32 nl = fpNeedLoad.get();
VirtualRegister& nlReg = vRegManager.getVirtualRegister(nl);
Instruction& lastUse = *nlReg.spillInfo.lastUsingInstruction;
emitter.emitLoadAfter(*lastUse.getPrimitive(), lastUse.getLinks().prev,
nlReg.getAlias(), *nlReg.equivalentRegister[vrcStackSlot]);
nlReg.releaseSelf();
}
// if(node.dfsNum == 8) printf("\n________End Node %d________\n", node.dfsNum);
}
}
#endif

View File

@@ -0,0 +1,269 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _SPILLING_H_
#define _SPILLING_H_
#include "Fundamentals.h"
#include <string.h>
#include "RegisterAllocator.h"
#include "RegisterAllocatorTools.h"
#include "ControlGraph.h"
#include "ControlNodes.h"
#include "Instruction.h"
#include "SparseSet.h"
template <class RegisterPressure>
class Spilling
{
private:
static void insertStoreAfter(Instruction& instruction, RegisterName name);
static void insertLoadBefore(Instruction& instruction, RegisterName name);
public:
static void calculateSpillCosts(RegisterAllocator& registerAllocator);
static void insertSpillCode(RegisterAllocator& registerAllocator);
};
struct SpillCost
{
double loads;
double stores;
double copies;
double cost;
bool infinite;
};
template <class RegisterPressure>
void Spilling<RegisterPressure>::insertSpillCode(RegisterAllocator& registerAllocator)
{
Uint32 rangeCount = registerAllocator.rangeCount;
RegisterName* name2range = registerAllocator.name2range;
Pool& pool = registerAllocator.pool;
SparseSet currentLive(pool, rangeCount);
SparseSet needLoad(pool, rangeCount);
SparseSet mustSpill(pool, rangeCount);
SparseSet& willSpill = *registerAllocator.willSpill;
ControlGraph& controlGraph = registerAllocator.controlGraph;
RegisterPressure::Set* liveOut = registerAllocator.liveness.liveOut;
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
for (Uint32 n = 0; n < nNodes; n++) {
needLoad.clear();
currentLive = liveOut[n];
mustSpill = currentLive;
InstructionList& instructions = nodes[n]->getInstructions();
for (InstructionList::iterator i = instructions.end(); !instructions.done(i);) {
Instruction& instruction = instructions.get(i);
i = instructions.retreat(i);
InstructionUse* useBegin = instruction.getInstructionUseBegin();
InstructionUse* useEnd = instruction.getInstructionUseEnd();
InstructionUse* usePtr;
InstructionDefine* defineBegin = instruction.getInstructionDefineBegin();
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
InstructionDefine* definePtr;
bool foundLiveDefine = false;
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
if (definePtr->isRegister()) {
if (currentLive.test(name2range[definePtr->getRegisterName()])) {
foundLiveDefine = true;
break;
}
} else {
foundLiveDefine = true;
break;
}
if (defineBegin != defineEnd && !foundLiveDefine) {
fprintf(stderr, "!!! Removed instruction because it was only defining unused registers !!!\n");
instruction.remove();
}
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
if (definePtr->isRegister()) {
RegisterName range = name2range[definePtr->getRegisterName()];
#ifdef DEBUG
if (needLoad.test(range))
if (!mustSpill.test(range) && registerAllocator.spillCost[range].infinite && willSpill.test(range)) {
fprintf(stderr, "Tried to spill a register with infinite spill cost\n");
abort();
}
#endif // DEBUG
if (willSpill.test(range))
insertStoreAfter(instruction, range);
needLoad.clear(range);
}
if (instruction.getFlags() & ifCopy)
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
if (usePtr->isRegister()) {
RegisterName range = name2range[usePtr->getRegisterName()];
if (!currentLive.test(range))
for (SparseSet::iterator r = needLoad.begin(); !needLoad.done(r); r = needLoad.advance(r)) {
RegisterName load = RegisterName(needLoad.get(r));
if (willSpill.test(load))
insertLoadBefore(instruction, load);
mustSpill.set(load);
}
needLoad.clear();
}
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
if (definePtr->isRegister())
currentLive.clear(name2range[definePtr->getRegisterName()]);
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
if (usePtr->isRegister()) {
RegisterName range = name2range[usePtr->getRegisterName()];
currentLive.set(range);
needLoad.set(range);
}
}
for (SparseSet::iterator l = needLoad.begin(); !needLoad.done(l); l = needLoad.advance(l)) {
RegisterName load = RegisterName(needLoad.get(l));
if (willSpill.test(load))
insertLoadBefore(instructions.first(), load);
}
}
}
template <class RegisterPressure>
void Spilling<RegisterPressure>::insertLoadBefore(Instruction& /*instruction*/, RegisterName name)
{
fprintf(stdout, "will insert load for range %d\n", name);
}
template <class RegisterPressure>
void Spilling<RegisterPressure>::insertStoreAfter(Instruction& /*instruction*/, RegisterName name)
{
fprintf(stdout, "will insert store for range %d\n", name);
}
template <class RegisterPressure>
void Spilling<RegisterPressure>::calculateSpillCosts(RegisterAllocator& registerAllocator)
{
Uint32 rangeCount = registerAllocator.rangeCount;
RegisterName* name2range = registerAllocator.name2range;
Pool& pool = registerAllocator.pool;
SparseSet live(pool, rangeCount);
SparseSet needLoad(pool, rangeCount);
SparseSet mustSpill(pool, rangeCount);
SparseSet alreadyStored(pool, rangeCount); // FIX: should get this from previous spilling.
SpillCost* cost = new SpillCost[rangeCount];
memset(cost, '\0', rangeCount * sizeof(SpillCost));
ControlGraph& controlGraph = registerAllocator.controlGraph;
RegisterPressure::Set* liveOut = registerAllocator.liveness.liveOut;
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
for (Uint32 n = 0; n < nNodes; n++) {
ControlNode& node = *nodes[n];
double weight = doLog10(node.loopDepth);
needLoad.clear();
live = liveOut[n];
mustSpill = live;
InstructionList& instructions = nodes[n]->getInstructions();
for (InstructionList::iterator i = instructions.end(); !instructions.done(i); i = instructions.retreat(i)) {
Instruction& instruction = instructions.get(i);
InstructionUse* useBegin = instruction.getInstructionUseBegin();
InstructionUse* useEnd = instruction.getInstructionUseEnd();
InstructionUse* usePtr;
InstructionDefine* defineBegin = instruction.getInstructionDefineBegin();
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
InstructionDefine* definePtr;
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
if (definePtr->isRegister()) {
RegisterName range = name2range[definePtr->getRegisterName()];
if (needLoad.test(range))
if (!mustSpill.test(range))
cost[range].infinite = true;
if ((false /* !rematerializable(range) */ || !needLoad.test(range)) && !alreadyStored.test(range))
cost[range].stores += weight;
needLoad.clear(range);
}
if (instruction.getFlags() & ifCopy)
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
if (usePtr->isRegister())
if (!live.test(name2range[usePtr->getRegisterName()])) {
for (SparseSet::iterator l = needLoad.begin(); !needLoad.done(l); l = needLoad.advance(l)) {
Uint32 range = needLoad.get(l);
cost[range].loads += weight;
mustSpill.set(range);
}
needLoad.clear();
}
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
if (definePtr->isRegister())
live.clear(name2range[definePtr->getRegisterName()]);
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
if (usePtr->isRegister()) {
RegisterName range = name2range[usePtr->getRegisterName()];
live.set(range);
needLoad.set(range);
}
if (instruction.getFlags() & ifCopy) {
assert(useBegin != useEnd && useBegin[0].isRegister());
assert(defineBegin != defineEnd && defineBegin[0].isRegister());
RegisterName source = name2range[useBegin[0].getRegisterName()];
RegisterName destination = name2range[defineBegin[0].getRegisterName()];
cost[source].copies += weight;
cost[destination].copies += weight;
}
}
for (SparseSet::iterator s = needLoad.begin(); !needLoad.done(s); s = needLoad.advance(s))
cost[needLoad.get(s)].loads += weight;
}
for (Uint32 r = 0; r < rangeCount; r++) {
SpillCost& c = cost[r];
c.cost = 2 * (c.loads + c.stores) - c.copies;
}
registerAllocator.spillCost = cost;
}
#endif // _SPILLING_H_

View File

@@ -0,0 +1,239 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _SPLITS_H_
#define _SPLITS_H_
#include "Fundamentals.h"
#include <string.h>
#include "Pool.h"
#include "ControlGraph.h"
#include "ControlNodes.h"
#include "Instruction.h"
#include "RegisterAllocator.h"
#include "RegisterAllocatorTools.h"
UT_EXTERN_LOG_MODULE(RegAlloc);
template <class RegisterPressure>
struct Splits
{
static void calculateSplitCosts(RegisterAllocator& registerAllocator);
static bool findSplit(RegisterAllocator& registerAllocator, RegisterName* color, RegisterName range);
static void insertSplitCode(RegisterAllocator& registerAllocator);
};
struct SplitCost
{
double loads;
double stores;
};
template <class RegisterPressure>
void Splits<RegisterPressure>::insertSplitCode(RegisterAllocator& /*registerAllocator*/)
{
// FIX
}
template <class RegisterPressure>
bool Splits<RegisterPressure>::findSplit(RegisterAllocator& registerAllocator, RegisterName* color, RegisterName range)
{
Pool& pool = registerAllocator.pool;
NameLinkedList** neighborsWithColor = new(pool) NameLinkedList*[6]; // FIX
memset(neighborsWithColor, '\0', 6 * sizeof(NameLinkedList*));
InterferenceGraph<RegisterPressure>& iGraph = registerAllocator.iGraph;
for (InterferenceVector* vector = iGraph.getInterferenceVector(range); vector != NULL; vector = vector->next)
for (Int32 i = vector->count - 1; i >=0; --i) {
RegisterName neighbor = vector->neighbors[i];
RegisterName c = color[neighbor];
if (c < 6) { // FIX
NameLinkedList* node = new(pool) NameLinkedList();
node->name = neighbor;
node->next = neighborsWithColor[c];
neighborsWithColor[c] = node;
}
}
bool splitAroundName = true;
LiveRangeGraph<RegisterPressure>& lGraph = registerAllocator.lGraph;
RegisterName bestColor = RegisterName(6); // FIX
double bestCost = registerAllocator.spillCost[range].cost;
SplitCost* splitCost = registerAllocator.splitCost;
for (RegisterName i = RegisterName(0); i < 6; i = RegisterName(i + 1)) { // FIX
double splitAroundNameCost = 0.0;
bool canSplitAroundName = true;
SplitCost& sCost = splitCost[range];
double addedCost = 2.0 * (sCost.stores + sCost.loads);
for (NameLinkedList* node = neighborsWithColor[i]; node != NULL; node = node->next) {
RegisterName neighbor = node->name;
if (lGraph.haveEdge(neighbor, range)) {
canSplitAroundName = false;
break;
} else
splitAroundNameCost += addedCost;
}
if (canSplitAroundName && splitAroundNameCost < bestCost) {
bestCost = splitAroundNameCost;
bestColor = i;
splitAroundName = true;
}
double splitAroundColorCost = 0.0;
bool canSplitAroundColor = true;
for (NameLinkedList* node = neighborsWithColor[i]; node != NULL; node = node->next) {
RegisterName neighbor = node->name;
if (lGraph.haveEdge(range, neighbor)) {
canSplitAroundColor = false;
break;
} else {
SplitCost& sCost = splitCost[neighbor];
double addedCost = 2.0 * (sCost.stores + sCost.loads);
splitAroundColorCost += addedCost;
}
}
if (canSplitAroundColor && splitAroundColorCost < bestCost) {
bestCost = splitAroundColorCost;
bestColor = i;
splitAroundName = false;
}
}
if (bestColor < RegisterName(6)) {
color[range] = bestColor;
registerAllocator.splitFound = true;
NameLinkedList** splitAround = registerAllocator.splitAround;
if (splitAroundName)
for (NameLinkedList* node = neighborsWithColor[bestColor]; node != NULL; node = node->next) {
NameLinkedList* newNode = new(pool) NameLinkedList();
newNode->name = node->name;
newNode->next = splitAround[range];
splitAround[range] = newNode;
}
else
for (NameLinkedList* node = neighborsWithColor[bestColor]; node != NULL; node = node->next) {
NameLinkedList* newNode = new(pool) NameLinkedList();
RegisterName neighbor = node->name;
newNode->name = range;
newNode->next = splitAround[neighbor];
splitAround[neighbor] = newNode;
}
trespass("Found a split");
return true;
}
return false;
}
template <class RegisterPressure>
void Splits<RegisterPressure>::calculateSplitCosts(RegisterAllocator& registerAllocator)
{
Pool& pool = registerAllocator.pool;
Uint32 rangeCount = registerAllocator.rangeCount;
RegisterName* name2range = registerAllocator.name2range;
SplitCost* splitCost = new(pool) SplitCost[rangeCount];
memset(splitCost, '\0', rangeCount * sizeof(SplitCost));
SparseSet live(pool, rangeCount);
RegisterPressure::Set* liveIn = registerAllocator.liveness.liveIn;
RegisterPressure::Set* liveOut = registerAllocator.liveness.liveOut;
ControlGraph& controlGraph = registerAllocator.controlGraph;
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
for (Uint32 n = 0; n < nNodes; n++) {
ControlNode& node = *nodes[n];
double weight = doLog10(node.loopDepth);
live = liveOut[n];
ControlEdge* successorsEnd = node.getSuccessorsEnd();
for (ControlEdge* successorsPtr = node.getSuccessorsBegin(); successorsPtr < successorsEnd; successorsPtr++) {
ControlNode& successor = successorsPtr->getTarget();
if (successor.getControlKind() != ckEnd) {
RegisterPressure::Set& successorLiveIn = liveIn[successor.dfsNum];
for (SparseSet::iterator i = live.begin(); !live.done(i); i = live.advance(i)) {
RegisterName name = RegisterName(live.get(i));
if (!successorLiveIn.test(name))
splitCost[name].loads += doLog10(successor.loopDepth);
}
}
}
InstructionList& instructions = node.getInstructions();
for (InstructionList::iterator i = instructions.end(); !instructions.done(i); i = instructions.retreat(i)) {
Instruction& instruction = instructions.get(i);
InstructionUse* useBegin = instruction.getInstructionUseBegin();
InstructionUse* useEnd = instruction.getInstructionUseEnd();
InstructionUse* usePtr;
InstructionDefine* defineBegin = instruction.getInstructionDefineBegin();
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
InstructionDefine* definePtr;
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
if (definePtr->isRegister())
splitCost[name2range[definePtr->getRegisterName()]].stores += weight;
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
if (usePtr->isRegister()) {
RegisterName range = name2range[usePtr->getRegisterName()];
if (!live.test(range)) {
if (&instruction != &instructions.last())
splitCost[range].loads += weight;
else {
ControlEdge* successorsEnd = node.getSuccessorsEnd();
for (ControlEdge* successorsPtr = node.getSuccessorsBegin(); successorsPtr < successorsEnd; successorsPtr++)
splitCost[range].loads += doLog10(successorsPtr->getTarget().loopDepth);
}
}
}
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
if (definePtr->isRegister())
live.clear(name2range[definePtr->getRegisterName()]);
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
if (usePtr->isRegister())
live.set(name2range[usePtr->getRegisterName()]);
}
}
NameLinkedList** splitAround = new(pool) NameLinkedList*[rangeCount];
memset(splitAround, '\0', rangeCount * sizeof(NameLinkedList*));
registerAllocator.splitAround = splitAround;
registerAllocator.splitCost = splitCost;
registerAllocator.splitFound = false;
}
#endif // _SPLITS_H_

View File

@@ -0,0 +1,186 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "Fundamentals.h"
#include "HashTable.h"
#include "Timer.h"
#include "Pool.h"
static Pool pool; // Pool for the Timer class.
static HashTable<TimerEntry*> timerEntries(pool); // Timers hashtable.
const nTimersInABlock = 128; // Number of timers in a block.
static PRTime *timers = new(pool) PRTime[nTimersInABlock]; // A block of timers.
static Uint8 nextTimer = 0; // nextAvailableTimer.
//
// Calibrate the call to PR_Now().
//
static PRTime calibrate()
{
PRTime t = PR_Now();
PRTime& a = *new(pool) PRTime();
// Call 10 times the PR_Now() function.
a = PR_Now(); a = PR_Now(); a = PR_Now(); a = PR_Now(); a = PR_Now(); a = PR_Now();
a = PR_Now(); a = PR_Now(); a = PR_Now(); a = PR_Now(); a = PR_Now(); a = PR_Now();
t = (PR_Now() - t + 9) / 10;
return t;
}
static PRTime adjust = calibrate();
//
// Return the named timer..
//
TimerEntry& Timer::getTimerEntry(const char* name)
{
if (!timerEntries.exists(name)) {
TimerEntry* newEntry = new(pool) TimerEntry();
newEntry->accumulator = 0;
newEntry->running = false;
timerEntries.add(name, newEntry);
}
return *timerEntries[name];
}
//
// Return a reference to a new timer.
//
PRTime& Timer::getNewTimer()
{
if (nextTimer >= nTimersInABlock) {
timers = new(pool) PRTime[nTimersInABlock];
nextTimer = 0;
}
return timers[nextTimer++];
}
static Uint32 timersAreFrozen = 0;
//
// Start the named timer.
//
void Timer::start(const char* name)
{
if (timersAreFrozen)
return;
freezeTimers();
TimerEntry& timer = getTimerEntry(name);
PR_ASSERT(!timer.running);
timer.accumulator = 0;
timer.running = true;
timer.done = false;
unfreezeTimers();
}
//
// Stop the named timer.
//
void Timer::stop(const char* name)
{
if (timersAreFrozen)
return;
freezeTimers();
TimerEntry& timer = getTimerEntry(name);
PR_ASSERT(timer.running);
timer.running = false;
timer.done = true;
unfreezeTimers();
}
//
// Freeze all the running timers.
//
void Timer::freezeTimers()
{
PRTime when = PR_Now() - adjust;
if (timersAreFrozen == 0) {
Vector<TimerEntry*> entries = timerEntries;
Uint32 count = entries.size();
for (Uint32 i = 0; i < count; i++) {
TimerEntry& entry = *entries[i];
if (entry.running) {
entry.accumulator += (when - *entry.startTime);
}
}
}
timersAreFrozen++;
}
//
// Unfreeze all the running timers.
//
void Timer::unfreezeTimers()
{
PR_ASSERT(timersAreFrozen != 0);
timersAreFrozen--;
if (timersAreFrozen == 0) {
Vector<TimerEntry *> entries = timerEntries;
Uint32 count = entries.size();
PRTime& newStart = getNewTimer();
for (Uint32 i = 0; i < count; i++) {
TimerEntry& entry = *entries[i];
if (entry.running) {
entry.startTime = &newStart;
}
}
newStart = PR_Now();
}
}
//
// Print the named timer in the file f.
//
void Timer::print(FILE* f, const char *name)
{
if (timersAreFrozen)
return;
freezeTimers();
TimerEntry& timer = getTimerEntry(name);
PR_ASSERT(timer.done);
PRTime elapsed = timer.accumulator;
if (elapsed >> 32) {
fprintf(f, "[timer %s out of range]\n", name);
} else {
fprintf(f, "[%dus in %s]\n", Uint32(elapsed), name);
}
fflush(f);
unfreezeTimers();
}

View File

@@ -0,0 +1,80 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _TIMER_H_
#define _TIMER_H_
#include "Fundamentals.h"
#include "HashTable.h"
#include "prtime.h"
//
// Naming convention:
// As the class Timer contains only static methods, the timer's name should start with the
// module name. Otherwise starting 2 timers with the same name will assert.
//
#ifndef NO_TIMER
struct TimerEntry
{
PRTime *startTime; // Current time when we start the timer.
PRTime accumulator; // Time spent in this timer.
bool running; // True if the timer is running.
bool done; // True if the timer was running and was stopped.
};
class Timer
{
private:
// Return the named timer.
static TimerEntry& getTimerEntry(const char* name);
// Return a reference to a new Timer.
static PRTime& getNewTimer();
public:
// Start the timer.
static void start(const char* name);
// Stop the timer.
static void stop(const char* name);
// Freeze all the running timers.
static void freezeTimers();
// Unfreeze all the running timers.
static void unfreezeTimers();
// Print the timer.
static void print(FILE* f, const char *name);
};
inline void startTimer(const char* name) {Timer::start(name);}
inline void stopTimer(const char* name) {Timer::stop(name); Timer::print(stdout, name);}
#define START_TIMER_SAFE Timer::freezeTimers();
#define END_TIMER_SAFE Timer::unfreezeTimers();
#define TIMER_SAFE(x) START_TIMER_SAFE x; END_TIMER_SAFE
#else /* NO_TIMER */
inline void startTimer(const char* /*name*/) {}
inline void stopTimer(const char* /*name*/) {}
#define START_TIMER_SAFE
#define END_TIMER_SAFE
#define TIMER_SAFE(x) x;
#endif /* NO_TIMER */
#endif /* _TIMER_H_ */

View File

@@ -0,0 +1,40 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "Fundamentals.h"
#include "VirtualRegister.h"
#include "Instruction.h"
//------------------------------------------------------------------------------
// VirtualRegister -
#ifdef MANUAL_TEMPLATES
template class IndexedPool<VirtualRegister>;
#endif
// Set the defining instruction.
//
void VirtualRegister::setDefiningInstruction(Instruction& instruction)
{
if (definingInstruction != NULL) {
if ((instruction.getFlags() & ifCopy) && (definingInstruction->getFlags() & ifPhiNode))
return;
}
definingInstruction = &instruction;
}

View File

@@ -0,0 +1,116 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _VIRTUAL_REGISTER_H_
#define _VIRTUAL_REGISTER_H_
#include "Fundamentals.h"
#include "IndexedPool.h"
#include <string.h>
#include "RegisterTypes.h"
#include "RegisterClass.h"
//------------------------------------------------------------------------------
// VirtualRegister - 24b
class Instruction;
class VirtualRegister : public IndexedObject<VirtualRegister>
{
public:
Instruction* definingInstruction; // Instruction defining this VR.
// Initialize a VR of the given classKind.
VirtualRegister(RegisterClassKind /*classKind*/) : definingInstruction(NULL) {}
// Return the defining instruction for this VR.
Instruction* getDefiningInstruction() const {return definingInstruction;}
// Set the defining instruction.
void setDefiningInstruction(Instruction& insn);
};
// Return true if the VirtualRegisters are equals. The only way 2 VRs can be equal is if
// they have the same index. If they have the same index then they are at the same
// address in the indexed pool.
//
inline bool operator == (const VirtualRegister& regA, const VirtualRegister& regB) {return &regA == &regB;}
//------------------------------------------------------------------------------
// VirtualRegisterManager -
struct PreColoredRegister
{
RegisterID id;
RegisterName color;
};
class VirtualRegisterManager
{
private:
IndexedPool<VirtualRegister> registerPool;
PreColoredRegister machineRegister[6];
public:
VirtualRegisterManager()
{
for (Uint32 i = 0; i < 6; i++)
machineRegister[i].id = invalidID;
}
// Return the VirtualRegister at the given index.
VirtualRegister& getVirtualRegister(RegisterName name) const {return registerPool.get(name);}
// Return a new VirtualRegister.
RegisterID newVirtualRegister(RegisterClassKind classKind)
{
VirtualRegister& vReg = *new(registerPool) VirtualRegister(classKind);
RegisterID rid;
setName(rid, RegisterName(vReg.getIndex()));
setClass(rid, classKind);
return rid;
}
RegisterID newMachineRegister(RegisterName name, RegisterClassKind classKind)
{
RegisterID rid = machineRegister[name].id;
if (rid == invalidID) {
rid = newVirtualRegister(classKind);
DEBUG_ONLY(setMachineRegister(rid));
machineRegister[name].id = rid;
machineRegister[name].color = name;
}
return rid;
}
PreColoredRegister* getMachineRegistersBegin() const {return (PreColoredRegister*) machineRegister;} // FIX
PreColoredRegister* getMachineRegistersEnd() const {return (PreColoredRegister*) &machineRegister[6];} // FIX
// Return the VirtualRegister universe size.
Uint32 getSize() {return registerPool.getSize();}
void setSize(Uint32 size) {registerPool.setSize(size);}
};
#endif // _VIRTUAL_REGISTER_H_