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

%
% user can say cm3 -DM3CC_TARGET=FreeBSD4, for example.
%

include("platforms.quake")

%
% fs_exists is deliberately not used here, in order to build
% starting with versions of cm3 that do not have it.
%
proc FileExists (a) is
    return not stale (a, a)
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.
%  Configuration 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.
%
  "ALPHA_OSF"    : "-enable-obsolete",
  "I386_LINUX"   : "-with-gnu-as -with-gnu-ld",
  "AMD64_LINUX"  : "-with-gnu-as -with-gnu-ld",
  "PPC_LINUX"    : "-with-gnu-as -with-gnu-ld",
  "PPC32_LINUX"  : "-with-gnu-as -with-gnu-ld",
  "PPC64_LINUX"  : "-with-gnu-as -with-gnu-ld",
  "SPARC32_LINUX": "-with-gnu-as -with-gnu-ld",
  "SPARC64_LINUX": "-with-gnu-as -with-gnu-ld",
  "LINUXLIBC6"   : "-with-gnu-as -with-gnu-ld",
  "ARM_LINUX"    : "-with-gnu-as -with-gnu-ld -with-float=soft "
                 & "-enable-target-optspace -enable-threads -enable-shared",

  %
  % AIX usually 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" : "-without-gnu-as -without-gnu-ld",
  "PPC64_AIX" : "-without-gnu-as -without-gnu-ld",
  % If buiding native gcc driver, add:
  % -with-as=/usr/bin/as -with-ld=/us/bin/ld

  %
  % Irix requires GNU as and GNU ld should work but presently does not.
  % Irix native ld works.
  %

  "MIPS32_IRIX" : "-with-gnu-as -without-gnu-ld", 
  "MIPS64_IRIX" : "-with-gnu-as -without-gnu-ld",
  % If buiding native gcc driver, add:
  % -with-ld=/usr/bin/ld 

  %
  % I thought this was just about what assembler/linker the gcc driver runs,
  % but it also affect the contents of the assembly.
  % For example, SPARC64_SOLARIS output isn't being accepted by SUN as..
  % #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",
  %
  % I patched config.h manually, but this should be equivalent.
  % Native builds robably 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 many errors.
  %

  "SPARC64_SOLARIS" : "-without-gnu-as -without-gnu-ld",
  % If buiding native gcc driver, add:
  % -with-as=/usr/ccs/bin/as -with-ld=/usr/ccs/bin/ld 
  
  "I386_SOLARIS" :  "-without-gnu-as -without-gnu-ld",
  "AMD64_SOLARIS" : "-without-gnu-as -without-gnu-ld",
  % see: http://gcc.gnu.org/install/specific.html#ix86-x-solaris210
  %      http://gcc.gnu.org/ml/gcc/2010-05/msg00155.html
  % GNU assembler is ok with .stabd.
  % Sun assembler doesn't like .stabd.
  % Sun assembler doesn't like cross section subtraction, as occurs
  % with -fPIC -funwind-table -m64, but gcc 4.4.0 fix backported.
  % GNU assembler moves around: /usr/sfw/bin/gas vs. /opt/csw/gnu/as
  % If buiding native gcc driver, add:
  % -with-as=/usr/ccs/bin/as -with-ld=/usr/ccs/bin/ld 
  % or -with-as=/usr/sfw/bin/gas -with-ld=/usr/ccs/bin/ld
  % or /opt/csw/gnu/as, or /opt/csw/bin/gas, or gas

  "SOLgnu" : "-without-gnu-ld -without-gnu-as -with-cpu=v9", % v9 for atomics
  "SOLsun" : "-without-gnu-ld -without-gnu-as -with-cpu=v9", % v9 for atomics
  % If buiding native gcc driver, add:
  % -with-as=/usr/ccs/bin/as -with-ld=/usr/ccs/bin/ld

  %
  % 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",
  "PA64_HPUX"  : "-with-gnu-as",
  % If buiding native gcc driver, add:
  %    -with-as=/usr/local/32/bin/gas
  % or -with-as=/usr/local/64/bin/gas
  
  "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

sparc64_assembler_config = "gcc_cv_as_sparc_register_op=yes"
solaris_assembler_config = "gcc_cv_as_sparc_register_op=yes gcc_cv_as_weak=yes gcc_cv_as_hidden=yes gcc_cv_ld_hidden=yes"

readonly m3cc_env = {
  "SPARC64_FREEBSD" : sparc64_assembler_config,
  "SPARC64_LINUX"   : sparc64_assembler_config,
  "SPARC64_NETBSD"  : sparc64_assembler_config,
  "SPARC64_OPENBSD" : sparc64_assembler_config,
  "SPARC64_SOLARIS" : solaris_assembler_config,
  "SOLsun"          : solaris_assembler_config,
  "SOLgnu"          : solaris_assembler_config,
  "SPARC32_SOLARIS" : solaris_assembler_config,
  "I386_SOLARIS"    : solaris_assembler_config,
  % workaround http://gcc.gnu.org/bugzilla/show_bug.cgi?id=45927
  "AMD64_SOLARIS"   : solaris_assembler_config & " gcc_cv_as_ix86_quad=yes",
} % m3cc_env

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

readonly proc get_env (target) is
  if m3cc_env contains target
    return m3cc_env {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

env = ""

include ("../../m3cc/src/gnumake.common")
include ("../../m3cc/src/gnucc.common")

% check for overrides, otherwise use the defaults from the configuration file
if not defined ("M3CC_MAKE")    M3CC_MAKE   = GNU_MAKE   end
if not defined ("M3CC_CONFIG")  M3CC_CONFIG = get_config (M3CC_TARGET) end

% current default is gcc 4.5
% Also available: 4.2 (apple), 4.3, 4.6
SourceDir = "../gcc" % The plain "gcc" directory is 4.3.
if not defined("GCC46")
  GCC46 = FALSE
end
GCC42 = equal(M3CC_TARGET, "ARM_DARWIN") % iPhone
GCC45 = (not GCC42 and not GCC46)
GCC43 = not (GCC42 or GCC45 or GCC46)
local Defines = ""
local m3gty = "m3gty43.h"
if GCC42
  SourceDir = "../gcc-apple"
  Defines = "#define GCC_APPLE 1\n#define GCC42 1\n"
end
if GCC45
  Defines = "#define GCC45 1\n"
  SourceDir = "../gcc-4.5"
  m3gty = "m3gty45.h"
end
if GCC46
  Defines = "#define GCC45 1\n#define GCC46 1\n"
  SourceDir = "../gcc-4.6"
  m3gty = "m3gty45.h"
end
if GCC42 or GCC45 or GCC46
  fs_mkdir(SourceDir & "/gcc/m3cg")
  foreach a in ["config-lang.in", "m3-def.h", "m3-parse.h", "lang-options.h",
                "lang-specs.h", "lang.opt", "m3cg.h", "Make-lang.in"]
    cp_if("../gcc/gcc/m3cg/" & a, SourceDir & "/gcc/m3cg/" & a)
  end
  cp_if("../gcc/gcc/m3cg/" & m3gty, SourceDir & "/gcc/m3cg/m3gty43.h")
  local a = Defines & fs_contents("../gcc/gcc/m3cg/parse.c")
  local b = SourceDir & "/gcc/m3cg/parse.c"
  > b & ".temp" in
    write(a)
  end
  cp_if(b & ".temp", b)
end

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

Log = ""
if not Native
  build_dir = "../" & HOST & "-" & M3CC_TARGET
  Log = path() & "/" & build_dir & "/_m3.log"
else
  Log = path() & "/../" & BUILD_DIR & "/_m3.log"
end

Log = subst_chars(Log, "\\", "/")

fs_mkdir (build_dir)

m3cc_ResponseFileCounter = 0
include("Math.quake")

readonly proc m3cc_Run (x) is
    if not FileExists(Log) > Log in write("") end end
    >> Log in write(x & "\n") end
    if not HostIsNT()
        write(x & "\n")
        exec(x)
        return
    end
    InitMath()
    m3cc_ResponseFileCounter = Add(m3cc_ResponseFileCounter, 1)
    local ShLeaf = "_m3" & m3cc_ResponseFileCounter & ".sh"
    local Sh = build_dir & "/" & ShLeaf
    write(ShLeaf & ":" & x & "\n")
    > Sh in
        write(x & "\n")
    end
    local a = try_exec("@chmod +x " & Sh)
    exec("@sh -exc " & Sh)
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

DoMipsTfile = Native and (equal (M3CC_TARGET, "DS3100") or equal (M3CC_TARGET, "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
  if Native
    BindExport (AppendExeExtension ("cm3cg"))
    if DoMipsTfile
      BindExport ("mips-tfile")
    end
  end
end

deriveds("", ["cm3cg", "cm3cg.exe"])

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

% Omit unnecessary builds during regression testing.

PREBUILT_CM3CG = $PREBUILT_CM3CG
if ($WORKSPACE or equal($USER, "jay")) and PREBUILT_CM3CG
  CM3CG = AppendExeExtension (build_dir & "/cm3cg")
  if equal(M3_MODE, "build")
    write( "copying pre-built backend ", PREBUILT_CM3CG, " => ", CM3CG, CR )
    cp_if( PREBUILT_CM3CG, CM3CG )
  end
else

%
% configure
%

done0 = build_dir & "/.configure-done" % old version
done = build_dir & "/Makefile"

if (stale(build_dir & "/clean_marker.txt", "../src/clean_marker.txt") or defined ("FORCE"))
  foreach a in fs_lsfiles (build_dir, FALSE)
    write("rm ", a, CR)
    delete_file(a)
  end
  foreach a in fs_lsdirs (build_dir, FALSE)
    write("rm -rf ", a, CR)
    fs_rmrec(a)
  end
  cp_if("../src/clean_marker.txt", build_dir & "/clean_marker.txt")
end

% configure the sources
% check for non-default flags

Configure = " -enable-build-with-cxx "

if not equal (HOST, M3CC_TARGET)
  Configure = Configure & " -with-sysroot" % shouldn't matter
    
  %
  % This is the essential cross build step.
  %
  Configure = Configure & " -target=" & GNU_platform (M3CC_TARGET)
end

if Native % host == target == build

  %
  % Config.guess on SPARC32_LINUX yields sparc64 and m3cg
  % then just always fails with internal errors, so be explicit.
  % This is reasonable in all builds, but let's not upset that apple cart.
  % We still let host and build be guessed, leading to a typically
  % sparc64 hosted cm3cg. Actual sparc32 systems (vs. sparc64) are rare
  % (Linux kernel no longer supports such hardware) 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 {"SPARC32_LINUX","SPARC64_SOLARIS"} contains HOST
    Configure = Configure & " -target=" & GNU_platform (M3CC_TARGET)
    %Configure = Configure & " -host=" & GNU_platform (M3CC_TARGET)
    %Configure = Configure & " -build=" & GNU_platform (M3CC_TARGET)
  end
end

Configure = Configure & " -srcdir=" & SourceDir
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"
% less memory, old compiler
%if not {"FreeBSD4","I386_FREEBSD","PPC_DARWIN"} contains HOST
%  Configure = Configure & " -enable-checking=assert,df,fold,misc,rtl,rtlflag,runtime,tree"
%end
if {"I386_DARWIN","AMD64_DARWIN","AMD64_LINUX","LINUXLIBC6","I386_LINUX","I386_OPENBSD"} contains HOST
  Configure = Configure & " -enable-checking=assert,df,fold,misc,rtl,rtlflag,runtime,tree,types"
end
% 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"

%
% host=NT386GNU target=SPARC64_OPENBSD works.
% Native SPARC64_OPENBSD does not. -disable-tls reduces noise in comparing
% them, and we never use TLS anyway, so just disable it across the board.
%
Configure = Configure & " -disable-tls"

%
% Configure does not ferry environment variables from itself to make,
% so these must be specified on both the configure command and the make command.
%
if not Native
  env = env & " " & get_env(M3CC_TARGET)
end


ConfigureGNUMake()
write("GNU_MAKE is " & GNU_MAKE & CR)


env = env & " MAKE=" & GNU_MAKE & " "

%
% Problems building gmp/mpfr:
%   Documentation is built into the source tree, leading cvs diff
%   to slowly 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 & " AUTOCONF=:"
env = env & " AUTOMAKE=:"
env = env & " LEX='touch lex.yy.c'"
env = env & " MAKEINFO=:"
% so depcomp can detect Sun cc -xM as working
% seems dangerous? so we set am_cv_CC_dependencies_compiler_type instead
% env = env & " MAKE=" & M3CC_MAKE
M3CC_MAKE = M3CC_MAKE & " " & env

if not defined ("no_config")
  if not FileExists (done)
    m3cc_Run (["cd", build_dir, "&&", env, SourceDir & "/configure", M3CC_CONFIG, Configure
    % , " | tee -a " & Log
    ])
  end
end

m3cc_Run (["cd " & build_dir & " && " & M3CC_MAKE & " configure-host"
  % & " | tee -a " & 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

%
% Configure is for some reason unable to find Cygwin /usr/bin/libtool?
%

if HostIsNT()
  foreach dir in ["gcc", "libcpp"]
    local file = build_dir & "/" & dir & "/Makefile"
    if FileExists(file)
      Sed(file, "@LIBTOOL@", "libtool")
    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.
%
if GCC45 or GCC46
    m3cc_Run (["cd " & build_dir & " && " & M3CC_MAKE & " all-build-libiberty"
              & " all-libiberty"
              % & " | tee -a " & Log
              ])
else
if GCC42
    m3cc_Run (["cd " & build_dir & " && " & M3CC_MAKE & " all-build-libiberty"
              & " all-libiberty"
              % & " | tee -a " & Log
              ])
else
    m3cc_Run (["cd " & build_dir & " && " & M3CC_MAKE
              & " all-build-libiberty all-libiberty"
              % & " | tee -a " & Log
              ])
end
end

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

if DoMipsTfile
  m3cc_Run (["cd " & build_dir & " && cd gcc && " & M3CC_MAKE & " mips-tfile"
            % & " | tee -a " & Log
            ])
end

postcp ()

end % prebuild
