%
% Copyright (C) 1994, Digital Equipment Corporation
% All rights reserved.
% See the file COPYRIGHT for a full description.
%

readonly Platform_info = {
  "AIX386"    : "i486-ibm-aix",
  "ALPHA_FREEBSD" : "alpha-freebsd6",
  "ALPHA_LINUX" : "alpha-linux",
  "ALPHA_NETBSD" : "alpha-netbsd",
  "ALPHA_OPENBSD" : "alpha-openbsd",
  "ALPHA_OSF" : "alpha-dec-osf1",
  "ALPHA_VMS" : "alpha-vms",
  "AMD64_DARWIN" : "i686-apple-darwin8.7.1",
  "AMD64_FREEBSD" : "amd64-freebsd7",
  "AMD64_LINUX" : "amd64-pc-linux-gnu",
  "AMD64_NETBSD" : "amd64-netbsd",
  "AMD64_NT"  : "amd64-pc-mingw32",
  "AMD64_OPENBSD" : "amd64-openbsd",
  "AMD64_SOLARIS" : "amd64-sun-solaris2",
  "AP3000"    : "apollo68-bsd",
  "ARM"       : "arm-riscos",
  "ARM_LINUX" : "arm-linux-uclibc",
  "BSDI4"     : "i386-unknown-freebsdelf",
  "DS3100"    : "decstation",
  "FBSD_ALPHA": "alpha-unknown-freebsd6",
  "FreeBSD"   : "i486-unknown-bsd",
  "FreeBSD2"  : "i486-unknown-freebsd",
  "FreeBSD3"  : "i386-unknown-freebsd3",
  "FreeBSD4"  : "i386-unknown-freebsd4",
  "HP300"     : "m68k-hp-hpux",
  "HPPA"      : "hppa1.1-hp-hpux",
  "I386_DARWIN" : "i686-apple-darwin8.7.1",
  "I386_MSDOS" : "i586-pc-msdosdjgpp",
  "I386_OPENBSD" : "i686-openbsd",
  "I386_SOLARIS" : "i686-sun-solaris2",
  "I386_NT"     : "i686-pc-mingw32",
  "I386_MINGW"	: "i686-pc-mingw32",
  "I386_CYGWIN" : "i686-pc-cygwin",
  "IA64_FREEBSD" : "ia64-freebsd7",
  "IA64_HPUX" : "ia64-hpux",
  "IA64_LINUX" : "ia64-linux",
  "IA64_NT" : "ia64-nt",
  "IA64_VMS" : "ia64-vms",
  "IBMR2"     : "rs6000-ibm-aix3.2",
  "IBMRT"     : "romp-ibm-aos",
  "IRIX5"     : "mips-sgi-irix5",
  "LINUX"     : "i686-pc-linux-gnuaout",
  "LINUXELF"  : "i686-pc-linux-gnu",
  "LINUXLIBC6": "i686-pc-linux-gnu",
  "MIPS32_IRIX" : "mips-irix",
  "MIPS32_LINUX" : "mips-linux",
  "MIPS64_IRIX" : "mips64-irix",
  "MIPS64_LINUX" : "mips64-linux",
  "MIPS64_OPENBSD" : "mips64-openbsd",
  "NEXT"      : "next-bsd",
  "NT386"     : "i686-pc-mingw32",
  "NT386GNU"     : "i686-pc-cygwin",
  "NT386MINGNU"     : "i686-pc-mingw32",
  "NetBSD2_i386" : "i386-unknown-netbsdelf",
  "OKI"       : "i860-sysv4.0",
  "PA32_HPUX"  : "hppa-hpux",
  "PA32_LINUX" : "hppa-linux",
  "PA64_HPUX"  : "hppa64-hpux",
  "PA64_LINUX" : "hppa64-linux",
  "PPC32_AIX" : "powerpc-aix",
  "PPC32_OPENBSD" : "powerpc-openbsd",
  "PPC64_AIX" : "powerpc64-aix",
  "PPC64_DARWIN" : "powerpc64-darwin",
  "PPC_DARWIN"  : "powerpc-apple-darwin6.3",
  "PPC_LINUX"   : "powerpc-apple-linuxelf",
  "SEQUENT"   : "i386-sequent-bsd",
  "SOLgnu"    : "sparc-sun-solaris2",
  "SOLsun"    : "sparc-sun-solaris2",
  "SPARC"     : "sparc-sun-sunos4.1",
  "SPARC32_LINUX" : "sparc-linux-gnu",
  "SPARC32_OPENBSD" : "sparc-openbsd",
  "SPARC64_LINUX" : "sparc64-linux-gnu",
  "SPARC64_OPENBSD" : "sparc64-openbsd",
  "SPARC64_SOLARIS" : "sparc64-sun-solaris2",
  "SUN3"      : "m68k-sun-sunos4.1",
  "SUN386"    : "i386-sun-sunos4.1",
  "Tru64v5"   : "alpha-dec-osf1",
  "UMAX"      : "encore-bsd",
  "VAX"       : "vax-dec-ultrix",
}

%
% not currently used
%
readonly proc Platform_WordSize (Platform) is
  if {"ALPHA_OSF":1,"AMD64_DARWIN":1,"AMD64_LINUX":1,"AMD64_NT":1,
      "AMD64_FREEBSD":1,"AMD64_NETBSD":1,"AMD64_OPENBSD":1,"AMD64_SOLARIS":1,
      "IA64_NT":1,"FBSD_ALPHA":1,"Tru64v5":1,"SPARC64_LINUX":1,
      "SPARC64_OPENBSD":1,"SPARC64_SOLARIS":1,"MIPS64_IRIX":1,"MIPS64_OPENBSD":1} contains Platform
    return "64"
  end
  return "32"
end

readonly proc Platform_IsOpenBSD (Platform) is
  return {"I386_OPENBSD":1,"PPC32_OPENBSD":1,"SPARC64_OPENBSD":1,"MIPS64_OPENBSD":1} contains Platform
end

%
% fs_exists is deliberately not used here, in order to build
% starting with versions of cm3 that do not have it.
%
readonly proc FileExists (a) is
    return not stale (a, a)
end

readonly proc ApplyPatches (Platform) is
  if not Platform_IsOpenBSD (Platform)
    return
  end
  pushd ("../gcc")
  foreach a in fs_lsfiles ("../src/patches/openbsd", FALSE)
    if not tcontains(a, ".done")
      if not FileExists (a & ".done")
        if not tcontains(a, "readme.txt")
          exec("patch -z .orig -p0 < " & a)
          > a & ".done" in
            write("")
          end
        end
      end
    end
  end
  popd ()
end

readonly proc HostIsNT () is
  return equal ($OS, "Windows_NT")
end

local DevNull1 = "1>/dev/null"
local DevNull2 = "2>/dev/null"
if HostIsNT ()
  DevNull1 = "1>nul:"
  DevNull2 = "2>nul:"
end

readonly proc GNU_platform (x) is
  if Platform_info contains x
    return Platform_info{x}
  else
    error ("GNU platform is not known for \"" & x & "\"")
    return "unknown-unknown-unknown"
  end
end

readonly m3cc_config = {
%
% Note about configuring which assembler to use:
%  When building m3cg and not gcc driver, the configured assembler is never going
%  to be run (by m3cg) but it does matter.
%  Cconfiguration in the "gcc/gcc" directory, which is done as part of
%  building m3cg, does locate and test an assembler. Building on HP-UX will
%  fail and say the GNU assembler is required, if it is not the one found.
%

  %
  % The NT386GNU hosted tools work.
  % The native ones do not.
  % -disable-tls consistently to reduce noise
  % when comparing them, since we don't use this feature anyway.
  %
  "SPARC64_OPENBSD" : "-disable-tls",

  "ARM_LINUX": "-with-float=soft -enable-target-optspace -enable-threads -enable-shared",

  %
  % Irix requires GNU as and GNU ld should work but presently does not.
  % Irix native ld works.
  % AIX almost always requires native as and ld -- cross builds are not possible.
  % Not all of this is relevant to m3cg, but user can build gcc/cc1 here.
  %
  "PPC32_AIX" : "-with-ld=/us/bin/ld -with-as=/usr/bin/as",
  "PPC64_AIX" : "-with-ld=/us/bin/ld -with-as=/usr/bin/as",
  "MIPS32_IRIX" : "-with-ld=/us/bin/ld -with-gnu-as",
  "MIPS64_IRIX" : "-with-ld=/us/bin/ld -with-gnu-as",

  %
  % Hm -- I thought this was just about what assembler/linker the gcc driver runs,
  % but it might also affect the contents of the assembly.
  % For example, SPARC64_SOLARIS output isn't being accepted by SUN as, let's see..
  % #ifdef HAVE_AS_REGISTER_PSEUDO_OP
  % D:\dev2\cm3.2\m3-sys\m3cc\gcc\gcc\config\sparc\sparc.c(3842):	  fprintf (file, "\t.register\t%%g%d, #%s\n", i,
  %
  % "SPARC64_SOLARIS" : "-without-gnu-ld -without-gnu-as",
  %
  % Note for my initial build I patched config.h manually, but this should the same thing.
  % Also, native builds will probably just figure it out. This is needed for cross builds,
  % unless perhaps building binutils along with m3cg.
  % If m3cg omits the .register psuedo ops, assembly completely fails, with lots of errors.
  %
  "SPARC64_SOLARIS" : "gcc_cv_as_sparc_register_op=yes",

  %
  % Bootstrap procedure for gcc on HPPA{64}-HPUX:
  % See http://gcc.gnu.org/install/specific.html.
  % Lots of caveats for GNU ld, so use vendor ld.
  %  Build gcc 3.3.6 with bundled cc.
  %    32bit: CC="cc       -Wp,-H16376 -D_CLASSIC_TYPES -D_HPUX_SOURCE"
  %    64bit: CC="cc +DD64 -Wp,-H16376 -D_CLASSIC_TYPES -D_HPUX_SOURCE"
  %  Getting patches for ld can help, esp. if building libstdc++.
  %  This gcc won't support -g.
  %  Build current binutils with gcc -- just gas.
  %     http://gcc.gnu.org/install/specific.html offers building
  %     binutils first but current binutils doesn't work that way.
  %  Rebuild gcc 3.3.6 with -with-as=path -with-gnu-as.
  %  Build current gcc also with -with-as=path -with-gnu-as.
  %  32bit and 64bit HPPA-HPUX require separate -prefix.
  %    -program-suffix=32 does not suffice.
  %  I use /usr/local/32 and /usr/local/64.
  %  Also, vendor tar often can't extract all of gcc, e.g. libstdc++,
  %  so use GNU tar. And vendor make often can't build gcc, get GNU make.
  %
  % m3cg is not actually ever going to run as, only the gcc driver does,
  % but build/configure is still picky about it -- it affects
  % the generated assembly for SPARC64, whether or not some versions
  % of gcc will support -g on HP-UX, and I think whether or not
  % configure will even succeed on HP-UX (with newer gcc).
  %
  "PA32_HPUX"  : "-with-gnu-as -with-as=/usr/local/32/bin/gas",
  "PA64_HPUX"  : "-with-gnu-as -with-as=/usr/local/64/bin/gas",
  % If this suffices, good, otherwise specify the full path to the GNU assembler.
  %"PA32_HPUX"  : "-with-gnu-as",
  %"PA64_HPUX"  : "-with-gnu-as",

  "HPPA"  : "-with-gnu-as",
  % The HP assembler doesn't understand inline debugger info.

  "IRIX5" : "-with-stabs -with-gnu-as"
  % mips-sgi-irix5 does not support debugging using the native
  % assembler.  If you don't have gas, delete the config options above.
  % You will need the latest version of gas (binutils-2.5 or better).
  % -with-stabs is necessary because Modula-3 v3.3 generates funny
  % symbol names that can't be parsed by the ECOFF debugging
  % directives.  [Modula-3 v3.4 and later don't generate funny
  % symbol names. -- Bill Kalsow 1/13/94]

} % m3cc_config

readonly proc get_config (target) is
  if m3cc_config contains target
    return m3cc_config {target}
  else
    return ""
  end
end

readonly proc get_overrides (nm, ov) is
  if equal (ov, "*")
    return ""
  else
    return format ("%s=\"%s\" ", nm, ov)
  end
end

%
% star means default
% These are meant to come from the config file, but it can omit them
%
if not defined("GNU_CC")     GNU_CC     = "*"    end
if not defined("GNU_CFLAGS") GNU_CFLAGS = "*"    end
if not defined("GNU_MAKE")   GNU_MAKE   = "make" end

if defined("HOST_GNU_MAKE")
  GNU_MAKE = HOST_GNU_MAKE
end

% See gcc configure documentation.
% "Build" is the present machine we are running on, the machine that is building the compiler.
% "Host" is the machine the compiler will run on.
% "Target" is the machine the compiler's output will run on.
% Typically, in a "native" build, all three are the same.
% There are five variations.
% BHT - Build Host Target
%  HT -       Host Target
% AAA - native building a native compiler
%       This requires having an HT=AA compiler, and produces another AA compiler.
% AAB - building a cross compiler that will run on current machine
%       This requires HT=AA to build fixincludes and gcc, AB to build libgcc, producing a AB compiler (which is used to build libgcc)
% ABA - building a cross compiler that runs on another machine, targeting current machine ("cross back"?)
%       This requires HT=AA to build fixincludes, AB to build gcc, AA to build libgcc, producing a BA compiler.
% ABB - cross building a native compiler
%       This requires HT=AA to build fixincludes, AB to build gcc and libgcc, producing a BB compiler.
% ABC - cross building a cross compiler
%       This requires HT=AA to build fixincludes, AB to build gcc, AC to build libgcc, producing a BC compiler.
%
% check for overrides, otherwise use the defaults from the configuration file
if not defined ("M3CC_BUILD")   M3CC_BUILD  = TARGET     end
if not defined ("M3CC_HOST")    M3CC_HOST   = TARGET     end
if not defined ("M3CC_TARGET")  M3CC_TARGET = TARGET     end
if not defined ("M3CC_CC")      M3CC_CC     = GNU_CC     end
if not defined ("M3CC_CFLAGS")  M3CC_CFLAGS = GNU_CFLAGS end
if not defined ("M3CC_MAKE")    M3CC_MAKE   = GNU_MAKE   end
if not defined ("M3CC_CONFIG")  M3CC_CONFIG = get_config (M3CC_TARGET) end

% figure out where we're going to build gcc
local build_dir = "."  % let m3build set the build directory

local Native = equal (M3CC_HOST, M3CC_TARGET) and equal (M3CC_HOST, M3CC_BUILD)

if not Native
  build_dir = "../" & M3CC_HOST & "-" & M3CC_TARGET
  % make sure the derived directory exists
  fs_mkdir (build_dir)
end

m3cc_ResponseFileCounter = "0"

readonly proc m3cc_Run (x) is
  if HostIsNT ()
    x = "sh -c \"" & x & "\""
  end
  write(x & CR)
  %>> build_dir & SL & "_m3.log" in
  %  write(x & CR)
  %end
  exec(x)
end

done = build_dir & "/.configure-done"

if defined ("FORCE")
  %
  % Note: this block is hard to maintain correctly and I personally
  % just rmdir /q/s <target> or rm -rf <target>.
  %
  % Why not just rm -rf build_dir/*?
  % Scared of getting it wrong?
  %
  if FileExists (build_dir & "/Makefile")
    exec("-cd " & build_dir & " && " & M3CC_MAKE & " distclean")
  end
  foreach a in ["cm3cg", "cm3cg.exe", "confdefs.h", "config.log", "cm3cg", ".M3SHIP", done, "_m3.log", "_m3sh0.sh"]
    delete_file(build_dir & "/" & a)
  end
  %
  % Now delete directories.
  %
  foreach a in ["gcc", "gmp", "libcpp", "libdecnumber", "mpfr", "libiberty"]
    fs_rmrec(build_dir & "/" & a)
  end
end

%
% Configure does not seem to ferry environment variables from itself to make,
% so these must be specified on both the configure command and the make command.
%
local env = get_overrides ("CC", M3CC_CC) & get_overrides ("CFLAGS", M3CC_CFLAGS)
%
% Problems building gmp/mpfr:
%   Documentation is built into the source tree, leading cvs diff
%   to output a LOT of extra content, not good, avoid that.
%   Automake and autoconf are causing problems building on NT, even when they are installed.
%   We don't need their results usually. Libtool is also a problem, possibly a cascade.
%
% env = env & " CC='gcc -g'"
% env = env & " CFLAGS="
env = env & " AUTOCONF=:"
env = env & " AUTOMAKE=:"
env = env & " LEX='touch lex.yy.c'"
env = env & " MAKEINFO=:"
M3CC_MAKE = M3CC_MAKE & " " & env
M3CC_CONFIG = M3CC_CONFIG & " " & env

ApplyPatches (M3CC_TARGET)

% check for non-default flags

if not defined ("no_config")
  % configure the sources
  if not FileExists (done)
    local Configure = " "

    %
    % Workaround Canadian fixincludes not understanding sysroot of the cross compiler used to build it.
    % http://gcc.gnu.org/bugzilla/show_bug.cgi?id=37036
    % This does not affect m3cg.
    %
    if equal (M3CC_HOST, M3CC_TARGET) and not equal (M3CC_HOST, M3CC_BUILD)
        Configure = Configure & " -with-sysroot=/"
        local Prefix = "/usr/local"
        local DefaultSysroot = Prefix & "/" & GNU_platform (M3CC_TARGET) & "/sys-root"
        Configure = Configure & " -with-build-sysroot=" & DefaultSysroot
        Configure = Configure & " -host=" & GNU_platform (M3CC_HOST)
        Configure = Configure & " -target=" & GNU_platform (M3CC_TARGET)
    else
        if not equal (M3CC_HOST, M3CC_TARGET)
          Configure = Configure & " -with-sysroot"
          Configure = Configure & " -target=" & GNU_platform (M3CC_TARGET)
        end
    end

    %
    % Config.guess on SPARC32_LINUX yields sparc64 so be explicit.
    % This is reasonable in all builds, but let's not upset that apple cart.
    % We still let host and build be sniffed, leading to a typically sparc64 hosted cm3cg.
    % Actual sparc32 systems (vs. sparc64) are rare so this should be ok.
    % If we really wanted sparc32 cm3 to produce a sparc32 hosted cm3cg, we could
    % be explicit about host and/or build.
    %
    if equal (M3CC_HOST, M3CC_TARGET) and equal (M3CC_HOST, M3CC_BUILD) and equal (M3CC_BUILD, "SPARC32_LINUX")
          Configure = Configure & " -target=" & GNU_platform (M3CC_TARGET)
          %Configure = Configure & " -host=" & GNU_platform (M3CC_TARGET)
          %Configure = Configure & " -build=" & GNU_platform (M3CC_TARGET)
    end
    Configure = Configure & " -srcdir=../gcc"
    Configure = Configure & " -disable-bootstrap"
    Configure = Configure & " -disable-intl"
    Configure = Configure & " -disable-libgomp"
    Configure = Configure & " -disable-libmudflap"
    Configure = Configure & " -disable-libssp"
    Configure = Configure & " -disable-nls"
    Configure = Configure & " -enable-languages=m3cg"
    Configure = Configure & " -enable-targets=all"

    % Save some libtool wrapping layers to speed up esp. on NT?
    Configure = Configure & " -disable-dependency-tracking"

    % These are compatible with just building m3cg, but user might
    % build gcc/cc1/libgcc here.
    Configure = Configure & " -disable-fixincludes"
    Configure = Configure & " -disable-libgcc"
    Configure = Configure & " -disable-decimal-float"
    Configure = Configure & " -disable-fixed-point"

    %m3cc_Run (["cd", build_dir, "&&", "../gcc/configure", M3CC_CONFIG, Configure, " | tee -a _m3.log"])
    m3cc_Run (["cd", build_dir, "&&", "../gcc/configure", M3CC_CONFIG, Configure])
    > done in
      write("done")
    end
  end
end

readonly proc ProbeExeExtension (a) is
  return equal (TARGET, "NT386") or FileExists (a & ".exe")
end

readonly proc AppendExeExtension (a) is
  if ProbeExeExtension (a)
    return a & ".exe"
  end
  return a
end

local DoMipsTfile = (equal (M3CC_HOST, "DS3100") or equal (M3CC_HOST, "ALPHA_OSF"))

readonly proc postcp() is
  pSrc  = build_dir & "/gcc/m3cgc1"
  pDest = build_dir & "/cm3cg"
  if ProbeExeExtension (pSrc)
    pSrc = pSrc & ".exe"
	pDest = pDest & ".exe"
  end
  if stale(pDest, pSrc)
    cp_if(pSrc, pDest)
  end
  if DoMipsTfile
    pSrc = build_dir & "/gcc/mips-tfile"
    pDest = build_dir & "/mips-tfile"
    if stale(pDest, pSrc)
      cp_if(pSrc, pDest)
    end
  end
end

if Native
  BindExport (AppendExeExtension ("cm3cg"))
  if DoMipsTfile
    BindExport ("mips-tfile")
  end
end

%
% configure
%

m3cc_Run (["cd " & build_dir & " && " & M3CC_MAKE & " configure-host | tee -a _m3.log"])

proc Sed (file0, find, replace) is
  if FileExists (file0)
    local file1 = file0 & ".1"
    m3cc_Run (["sed", "-e", "'s/" & find & "/" & replace & "/'", "<", file0, ">", file1])
    m3cc_Run (["../gcc/move-if-change", file1, file0])
  end
end

foreach dir in ["gcc", "libcpp", "mpfr", "mpfr/tests"]
  foreach file in ["Makefile", "auto-host.h", "config.h"]
    local file = build_dir & "/" & dir & "/" & file
    if FileExists (file)
      %
      % remove libiconv dependency
      % It isn't needed, and stock Solaris install lacks it.
      %
      Sed (file, "^LIBICONV =.+$", "LIBICONV =")
      Sed (file, "^LIBICONV_DEP =.+$", "LIBICONV_DEP =")
      Sed (file, "^#define HAVE_ICONV 1$", "")
      Sed (file, "^#define HAVE_ICONV_H 1$", "")
      %
      % Configure is for some reason unable to find Cygwin /usr/bin/libtool.
      %
      if HostIsNT ()
        Sed (file, "@LIBTOOL@", "libtool")
      end
    end
  end
end

%
% Build only what is needed to build m3 backend, e.g. not the C frontend.
% User can still cd into build directory and run make to get gcc/cc1/libgcc.
%
m3cc_Run (["cd " & build_dir & " && " & M3CC_MAKE & " all-gmp all-mpfr all-build-libiberty all-libiberty all-libdecnumber | tee -a _m3.log"])

%
% make just libcpp.a, don't bother with makedepend.exe
%
m3cc_Run (["cd " & build_dir & " && cd libcpp && " & M3CC_MAKE & " libcpp.a | tee -a _m3.log"])
m3cc_Run (["cd " & build_dir & " && cd gcc && " & M3CC_MAKE & " s-modes insn-config.h m3cg | tee -a _m3.log"])

postcp ()
