# -*- coding: utf-8; mode: tcl; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:fenc=utf-8:filetype=tcl:et:sw=4:ts=4:sts=4

PortSystem          1.0
PortGroup           active_variants 1.1
PortGroup           bootstrap 1.0
PortGroup           conflicts_build 1.0
PortGroup           select 1.0

# TODO: MacPorts has moved to gcc15 as the default runtime provider now:
# https://github.com/macports/macports-ports/commit/23a41014e1289ea2c3aed24cca93ec57b6caf433
# Since our toolchain is detached, thankfully, there is no need to mimic MacPorts anymore.
# As of now, gcc15 has not been tested much, so we remain with 14.3.0 for awhile.
# Then the plan is to use gcc-powerpc for the releases of gcc15 and subsequent versions,
# thus dropping all redundant zoo of gcc versions. gcc14 may stay for R ports
# a bit longer, just to avoid on-going recompilations of 5k R packages.
# In principle, we need a single [non-bootstrap] gcc version, tracking the latest release.

# TODO: when updating this port, make sure to review MacPorts upstream changes
# and pick the latest update from Iaian. (Ideally also see how to fix this for Linux
# and RISCV64, based on what macstrop has for gcc13.)

# TODO: before updating, see if libc++ 11.x can be fixed, to use for gcc-libcxx subport.

name                gcc-powerpc

categories          lang
maintainers         {@barracuda156 macos-powerpc.org:barracuda}
# an exception in the license allows dependents to not be GPL
license             {GPL-3+ Permissive}

# TODO: fix building universal.
universal_variant   no

homepage            https://gcc.gnu.org

description         The GNU compiler collection
long_description    {*}${description}, including front-ends \
                    for C, C++, Objective-C, Objective-C++ and Fortran. \
                    This is an !experimental! version for Darwin PowerPC.

version             15-20250323
revision            0

set libgccname      lib${name}
set libcxxname      ${name}-libcxx

subport             ${libgccname} { revision [ expr ${revision} + 0 ] }

checksums           rmd160  02f555536643fbe75155afb8876dcd6e1a485665 \
                    sha256  68bd1c2ad24202f669b257df0842a32c44279263ad6f51be954d4899243a8c5a \
                    size    91685912

# Primary releases
master_sites        https://ftpmirror.gnu.org/gcc/gcc-${version}/ \
                    https://mirror.its.dal.ca/gnu/gcc/gcc-${version}/ \
                    https://mirrors.kernel.org/gnu/gcc/gcc-${version}/ \
                    https://www.mirrorservice.org/sites/ftp.gnu.org/gnu/gcc/gcc-${version}/ \
                    https://ftp-stud.hs-esslingen.de/pub/Mirrors/ftp.gnu.org/gcc/gcc-${version}/ \
                    https://mirror.yongbok.net/gnu/gcc/gcc-${version}/ \
                    http://mirror.koddos.net/gcc/releases/gcc-${version}/ \
                    ftp://ftp.gwdg.de/pub/linux/gcc/releases/gcc-${version}/ \
                    ftp://gcc.ftp.nluug.nl/mirror/languages/gcc/releases/gcc-${version}/ \
                    ftp://gcc.gnu.org/pub/gcc/releases/gcc-${version}/ \
                    gnu:gcc/gcc-${version}
# Snapshots and RC candidates
master_sites-append https://mirror.koddos.net/gcc/snapshots/${version}/ \
                    https://bigsearcher.com/mirrors/gcc/snapshots/${version}/ \
                    ftp://ftp.funet.fi/pub/mirrors/sources.redhat.com/pub/gcc/snapshots/${version}/ \
                    ftp://gcc.gnu.org/pub/gcc/snapshots/${version}/

distname            gcc-${version}
use_xz              yes

bootstrap.force_gcc10   yes

# flex needed due to:
# g++: error: gengtype-lex.cc: No such file or directory
# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=84715
depends_build-append \
                    port:flex \
                    port:texinfo
depends_lib-append  port:cctools \
                    port:gmp \
                    port:isl-devel \
                    port:ld64 \
                    port:libiconv \
                    port:libmpc \
                    port:mpfr \
                    port:zlib \
                    port:zstd
depends_run-append  port:gcc_select \
                    port:libgcc-powerpc

# require_active_variants cctools llas
# require_active_variants ld64 ld64_97

depends_skip_archcheck-append gcc_select ld64 cctools
license_noconflict  gmp mpfr ppl libmpc zlib

set major           powerpc

proc gcc_arch {arch} {
    switch ${arch} {
        arm64       {return aarch64}
        ppc64       {return powerpc64}
        ppc         {return powerpc}
        default     {return ${arch}}
    }
}

platform darwin {
    set gcc_triple [gcc_arch ${build_arch}]-apple-darwin${os.major}
    configure.pre_args-append   --build=${gcc_triple} \
                                --host=${gcc_triple} \
                                --target=${gcc_triple}
}

# TODO: support gccrs, modula2, gcj.
set gcc_configure_langs {c c++ objc obj-c++ lto fortran jit}

proc get_clean_sysroot {} {
    global configure.sdkroot
    # if the sdkroot is one of the current, rapidly changing SDKS, use the generic one
    return [regsub {MacOSX1[1-9]\.[0-9]+\.sdk} ${configure.sdkroot} {MacOSX.sdk}]
}

# TODO: perhaps switch to a new version of configure.
# See: https://github.com/iains/gcc-13-branch/issues/20

set mp_extra_rpath  ${prefix}/lib/libgcc

configure.dir       ${workpath}/build
configure.cmd       ${worksrcpath}/configure
configure.args      --enable-languages=[join ${gcc_configure_langs} ","] \
                    --libdir=${prefix}/lib/${name} \
                    --includedir=${prefix}/include/${name} \
                    --infodir=${prefix}/share/info \
                    --mandir=${prefix}/share/man \
                    --datarootdir=${prefix}/share/gcc-${major} \
                    --with-local-prefix=${prefix} \
                    --with-system-zlib \
                    --program-suffix=-mp-${major} \
                    --with-gxx-include-dir=${prefix}/include/${name}/c++/ \
                    --with-gmp=${prefix} \
                    --with-isl=${prefix} \
                    --with-mpc=${prefix} \
                    --with-mpfr=${prefix} \
                    --with-zstd=${prefix} \
                    --enable-checking=release \
                    --disable-multiarch \
                    --disable-multilib \
                    --disable-nls \
                    --enable-lto \
                    --enable-libstdcxx-time \
                    --with-build-config=bootstrap-debug \
                    --with-ar=${prefix}/bin/ar \
                    --with-as=${prefix}/bin/as \
                    --with-ld=${prefix}/bin/ld \
                    --with-bugurl=https://github.com/macos-powerpc/powerpc-ports/issues/new \
                    --enable-host-shared \
                    --with-darwin-extra-rpath=${mp_extra_rpath} \
                    --with-libiconv-prefix=${prefix}

# configure.args-append \
                    --enable-gm2tools \
                    --enable-libgm2

# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105710
configure.args-append \
                    --disable-tls

if { ${subport} ne ${libcxxname} } {
    variant G4 conflicts G5 description "Optimize for G4" {
        configure.args-append \
                    --with-tune-cpu=G4
    }

    variant G5 conflicts G4 description "Optimize for G5" {
        configure.args-append \
                    --with-tune-cpu=G5
    }

#     configure.env-append \
#                     STAGE1_CFLAGS="-O1 -pipe -mdynamic-no-pic" \
#                     STAGE1_CXXFLAGS="-O1 -pipe -mdynamic-no-pic"
}

# Disable ccache
configure.ccache    no

if { ${subport} ne ${libcxxname} } {
    # gcc has build issues on macOS 11.3 with the use of Xcode 12.5 clang via cctools for ld
    # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=100340
    # https://trac.macports.org/ticket/62775
    # Update for gcc13 - Similar issues on macOS 10.6, 10.13 ...
    # Skip bootstrap comparison entirely
    configure.args-replace --with-build-config=bootstrap-debug --without-build-config
    post-patch {
        reinplace {s|^do-compare =|do-compare = /usr/bin/true|g} \
            ${worksrcpath}/Makefile.in \
            ${worksrcpath}/config/bootstrap-debug.mk \
            ${worksrcpath}/config/bootstrap-debug-lean.mk \
            ${worksrcpath}/config/bootstrap-debug-lib.mk
    }
}

# Do not abort if 'system' headers in /opt/local/include/gcc are missing
patchfiles-append   patch-disable-sys-header-missing-abort.diff

# Since GCC 7.4.0, during configure, it detects features supported by target-as.
# On the other hand, MacPorts cctools contain a proxy for 'as' that runs system
# 'as' or one of the supported MacPorts clang's 'as' if it is installed. Here,
# we may encounter a misconfiguration when GCC builds on a system with some
# MacPorts clang, and 'as' is using it. However, on a clean system, it uses
# system 'as' if no MacPorts clang is installed, which may behave differently.
# This can make GCC broken until MacPorts clang is installed. To avoid a stealth
# dependency on the used clang, I enforce building with system 'as'.
# See:
#  - https://trac.macports.org/ticket/68683
#  - https://github.com/gcc-mirror/gcc/commit/b410cf1dc056aab195c5408871ffca932df8a78a
patchfiles-append   patch-gcc10-disable-macports-cctools-as-changes.diff

# https://github.com/iains/darwin-toolchains-start-here/discussions/13
patchfiles-append   patch-contrib-fat-gcc.sh.diff

# Restore ppc intrinsics: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=93177
patchfiles-append   patch-restore-ppc_intrinsics.h.diff

configure.env-append \
                    DISABLE_MACPORTS_AS_CLANG_SEARCH=1 \
                    DISABLE_XCODE_AS_CLANG_SEARCH=1

build.env-append    DISABLE_MACPORTS_AS_CLANG_SEARCH=1 \
                    DISABLE_XCODE_AS_CLANG_SEARCH=1

configure.env-append \
                    AR_FOR_TARGET=${prefix}/bin/ar \
                    AS_FOR_TARGET=${prefix}/bin/as \
                    LD_FOR_TARGET=${prefix}/bin/ld \
                    NM_FOR_TARGET=${prefix}/bin/nm \
                    OBJDUMP_FOR_TARGET=${prefix}/bin/objdump \
                    RANLIB_FOR_TARGET=${prefix}/bin/ranlib \
                    STRIP_FOR_TARGET=${prefix}/bin/strip \
                    OTOOL=${prefix}/bin/otool \
                    OTOOL64=${prefix}/bin/otool

pre-configure {
    # Set package info
    configure.args-append --with-pkgversion="macOS PowerPC ${name} ${version}_${revision}${portvariants}"

    if {${configure.sdkroot} ne ""} {
        # We should be using --with-build-sysroot here.  Using --with-sysroot
        # changes the behavior of the installed gcc to look in that sysroot
        # by default instead of /.  Using --with-build-sysroot is supposed
        # to be used during the build but not impact the installed product.
        # Unfortunately, the build fails because the value doesn't get
        # plumbed everywhere it is supposed to.
        #
        # https://trac.macports.org/ticket/53726
        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=79885
        configure.args-append --with-sysroot="[get_clean_sysroot]"
    }
}

# Re libc++ support, see:
# https://github.com/iains/darwin-toolchains-start-here/discussions/31

set libcxx_incpath          ${prefix}/libexec/${name}/libc++/include/c++/v1

subport ${libcxxname} {
    revision                [ expr ${revision} + 0 ]
    description             libc++ header implementation to be used by ${name}
    long_description        {*}${description}
    homepage                https://llvm.org
    license                 NCSA
    # This assumes a default variant of libcxx-powerpc.
    depends_build           port:libcxx-powerpc
    depends_extract
    depends_run
    depends_lib
    distfiles
    patchfiles
    use_configure           no
    supported_archs         noarch
    platforms               any

    # Version used in libcxx-powerpc port:
    set llvm_ver            7.1.1

    build {
        # Copy headers from libcxx during build:
        file mkdir ${worksrcpath}/headers
        file copy ${prefix}/libexec/llvm-${llvm_ver}/include/c++/v1 ${worksrcpath}/headers/
    }
    destroot {
        set base_dir [file dirname ${libcxx_incpath}]
        file mkdir ${destroot}${base_dir}
        file copy ${worksrcpath}/headers/v1 ${destroot}${base_dir}
    }
}

if { ${subport} ne ${libcxxname} } {

    variant stdlib_flag description {Enable stdlib command line flag to select C++ runtime} {
        # Enables support for specifying the c++ runtime via `-stdlib=` in a similar
        # way to clang. For more details see the later comments in
        #   https://www.mail-archive.com/gcc-patches@gcc.gnu.org/msg257385.html
        # Note : This 'bakes' the libc++ include directory into gcc,
        # which is then used as the default search location when `-stdlib=libc++`
        # is given. Therefore to have consistency across various OS versions, and to enable
        # modern c++ standards, use a recent macports clang port to provide this.
        if {${subport} eq ${name}} {
            depends_run-append  port:${libcxxname}
        }
        configure.args-append   --with-gxx-libcxx-include-dir="${libcxx_incpath}"
    }

    # Notice that while this is enabled in the build, it is largely untested
    # and should not be used by default.
    default_variants-append +stdlib_flag

}

compiler.blacklist-append   *gcc-4.0 *clang*

# "-stdlib" would be passed on to the bootstrap compiler if present
configure.cxx_stdlib

build.dir           ${configure.dir}
build.target        bootstrap-lean

destroot.target     install install-info-host

# gcc cannot build if these are active
conflicts_build-append  libunwind-headers binutils gdb

# Find dylibs at a given location
proc dylib_list {location} {
    # Note *.*.dylib is to only match versioned dylibs, not the versionless sym links
    set dylibs [glob -directory ${location} -tails *.*.dylib]
    ui_debug "Found at ${location} dylibs : ${dylibs}"
    return ${dylibs}
}

if {${subport} eq ${libgccname}} {

    # Always provides primary runtime so always in conflict
    conflicts libgcc libgcc-devel libgcc16

    # http://trac.macports.org/ticket/35770
    # http://trac.macports.org/ticket/38814
    # While there can be multiple versions of these runtimes in a single
    # process, it is not possible to pass objects between different versions,
    # so we simplify this by having the libgcc port provide the newest version
    # of these runtimes for all versions of gcc to use.
    #
    # If there is a binary incompatible change to the runtime in a future
    # version of gcc, then the latest version of gcc to provide a given ABI
    # version should continue to provide a subport for that and older gcc
    # versions.

    depends_run
    depends_lib-delete   port:zlib port:libiconv
    depends_build-append {*}${depends_lib}
    depends_lib          port:zlib port:libiconv

    configure.args-replace \
        --libdir=${prefix}/lib/${name} \
        --libdir=${prefix}/lib/libgcc

    # see https://trac.macports.org/ticket/54766
    configure.args-replace \
        --includedir=${prefix}/include/${name} \
        --includedir=${prefix}/include/gcc

    configure.args-replace \
        --with-gxx-include-dir=${prefix}/include/${name}/c++/ \
        --with-gxx-include-dir=${prefix}/include/gcc/c++/

    post-destroot {

        # Temporary working dir for dylibs
        file mkdir ${destroot}${prefix}/lib/libgcc.merged

        # loop over libs to install
        set dylibs [dylib_list ${destroot}${prefix}/lib/libgcc]
        foreach dylib ${dylibs} {

            # Different OS versions (e.g. Leopard) or architectures (e.g. PPC) don't produce all the dylibs
            # https://trac.macports.org/ticket/40098
            # https://trac.macports.org/ticket/40100
            if { ![file exists ${destroot}${prefix}/lib/libgcc/${dylib}] } {
                continue
            }

            # Move dylib to temp area
            move ${destroot}${prefix}/lib/libgcc/${dylib} ${destroot}${prefix}/lib/libgcc.merged

            # If needed create versionless sym link to dylib
            set dylib_split [split ${dylib} "."]
            set dylib_nover ${destroot}${prefix}/lib/libgcc.merged/[lindex ${dylib_split} 0].[lindex ${dylib_split} end]
            if { ![file exists ${dylib_nover}]  } {
                ln -s ${dylib} ${dylib_nover}
            }

            # Universal support
            if {[variant_exists universal] && [variant_isset universal]} {
                foreach archdir [glob ${destroot}${prefix}/lib/libgcc/*/] {
                    set archdir_nodestroot [string map "${destroot}/ /" ${archdir}]
                    if {[file exists ${archdir}/${dylib}]} {
                        system "install_name_tool -id ${prefix}/lib/libgcc/${dylib} ${archdir}/${dylib}"
                        foreach link [glob -tails -directory ${archdir} *.dylib] {
                            system "install_name_tool -change ${archdir_nodestroot}${link} ${prefix}/lib/libgcc/${link} ${archdir}/${dylib}"
                        }
                        system "lipo -create -output ${destroot}${prefix}/lib/libgcc.merged/${dylib}~ ${destroot}${prefix}/lib/libgcc.merged/${dylib} ${archdir}/${dylib} && mv ${destroot}${prefix}/lib/libgcc.merged/${dylib}~ ${destroot}${prefix}/lib/libgcc.merged/${dylib}"
                    }
                }
            }

            # strip debug symbols to supress debugger warnings:
            # http://trac.macports.org/attachment/ticket/34831
            if {! [string match *libgcc_ext* ${dylib}]} {
                system "strip -x ${destroot}${prefix}/lib/libgcc.merged/${dylib}"
            }
        }

        file delete -force ${destroot}${prefix}/bin
        file delete -force ${destroot}${prefix}/share
        file delete -force ${destroot}${prefix}/lib/libgcc
        file delete -force ${destroot}${prefix}/libexec

        move ${destroot}${prefix}/lib/libgcc.merged ${destroot}${prefix}/lib/libgcc

        # For binary compatibility with binaries that linked against the old libstdcxx port
        ln -s libgcc/libstdc++.6.dylib ${destroot}${prefix}/lib/libstdc++.6.dylib

        # Create README detailing runtime installed.
        # Also used as file checked for path-like port dependency for libgcc/libgcc-devel deps.
        xinstall -d ${destroot}${prefix}/share/doc/libgcc
        system "echo 'libgcc runtime is provided by ${subport}' > ${destroot}${prefix}/share/doc/libgcc/README"

    }

}

if {${subport} eq ${name}} {

    post-destroot {

        file delete ${destroot}${prefix}/share/info/dir

        foreach file [glob ${destroot}${prefix}/share/{info,man/man7}/*] {
            set extension [file extension ${file}]
            set newfile [regsub "${extension}$" ${file} "-mp-${major}${extension}"]
            file rename ${file} ${newfile}
        }

        # loop over libs to install
        set dylibs [dylib_list ${destroot}${prefix}/lib/${name}]
        foreach dylib ${dylibs} {
            if { [file exists ${prefix}/lib/libgcc/${dylib}] } {
                # Different OS versions (e.g. Leopard) or architectures (e.g. PPC) don't produce all the dylibs
                # https://trac.macports.org/ticket/40098
                # https://trac.macports.org/ticket/40100
                if {[file exists ${destroot}${prefix}/lib/${name}/${dylib}]} {
                    delete ${destroot}${prefix}/lib/${name}/${dylib}
                    ln -s ${prefix}/lib/libgcc/${dylib} ${destroot}${prefix}/lib/${name}/${dylib}
                }
                if {[variant_exists universal] && [variant_isset universal]} {
                    foreach archdir [glob ${destroot}${prefix}/lib/${name}/*/] {
                        if {[file exists ${archdir}/${dylib}]} {
                            delete ${archdir}/${dylib}
                            ln -s ${prefix}/lib/libgcc/${dylib} ${archdir}/${dylib}
                        }
                    }
                }
            }
        }

        # Place FAT gcc script into contrib folder:
        xinstall -d ${destroot}${prefix}/share/${name}/contrib
        file copy ${worksrcpath}/contrib/fat-gcc.sh ${destroot}${prefix}/share/${name}/contrib/

    }

    select.group        gcc
    select.file         ${filespath}/mp-${name}

}

if { ${subport} ne ${libcxxname} } {

    post-destroot {
        # Ensure all dylibs in destroot have our extra rpath added ..
        # https://trac.macports.org/ticket/65503
        foreach dlib [ exec find ${destroot}${prefix} -type f -and -name "*.dylib" ] {
            ui_debug "Ensuring DYLIB '${dlib}' has RPATH '${mp_extra_rpath}'"
            # Note install_name_tool returns a failure if the dylib already has the entry
            # We don't want that here so force final status to be true...
            system "install_name_tool -add_rpath ${mp_extra_rpath} ${dlib} > /dev/null 2>&1 ; true"
        }
    }

    # We keep the code, but it is not yet implemented properly.
    configure.universal_archs ppc ppc64

    variant universal {
        configure.args-delete --disable-multilib
    }
    # the generated compiler doesn't accept -arch
    configure.env-append \
        "CPP=${configure.cc} -E" \
        "CPP_FOR_BUILD=${configure.cc} -E" \
        "CXXCPP=${configure.cxx} -E"
    build.env-append \
        "CPP=${configure.cc} -E" \
        "CPP_FOR_BUILD=${configure.cc} -E" \
        "CXXCPP=${configure.cxx} -E"
    configure.cc-append [get_canonical_archflags]
    configure.cc_archflags
    configure.cxx-append ${configure.cxx_archflags}
    configure.cxx_archflags
    configure.objc_archflags
    configure.ld_archflags
    configure.universal_cflags
    configure.universal_cxxflags
    configure.universal_ldflags
    configure.universal_args

}

livecheck.type      regex
livecheck.url       http://mirror.koddos.net/gcc/releases/
livecheck.regex     gcc-(${major}\\.\[0-9.\]+)/
