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

PortSystem              1.0
PortGroup active_variants 1.1
PortGroup cmake         1.0

set llvm_version        5.0
set clang_executable_version 5.0
set lldb_executable_version 5.0.2
name                    llvm-${llvm_version}
revision                5
subport                 clang-${llvm_version} { revision 8 }
subport                 lldb-${llvm_version} { revision 3 }
set suffix              mp-${llvm_version}
set sub_prefix          ${prefix}/libexec/llvm-${llvm_version}
dist_subdir             llvm
categories              lang
license                 NCSA
maintainers             {jeremyhu @jeremyhu}

if {${subport} eq "llvm-${llvm_version}"} {
    homepage            https://llvm.org/
    description         llvm is a next generation compiler infrastructure
    long_description    The LLVM Core libraries provide a modern source- and \
                        target-independent optimizer, along with code \
                        generation support for many popular CPUs (as well as \
                        some less common ones!) These libraries are built \
                        around a well specified code representation known as \
                        the LLVM intermediate representation ("LLVM IR").

    depends_lib         port:libedit port:libffi port:ncurses path:lib/libxar.dylib:xar port:zlib
    depends_run         bin:perl:perl5 port:llvm_select-${llvm_version}
} elseif {${subport} eq "clang-${llvm_version}"} {
    homepage            https://clang.llvm.org/
    description         C, C++, Objective C and Objective C++ compiler
    long_description    Clang is an "LLVM native" C/C++/Objective-C compiler, \
                        which aims to deliver amazingly fast compiles (e.g. \
                        about 3x faster than GCC when compiling Objective-C \
                        code in a debug configuration), extremely useful error \
                        and warning messages and to provide a platform for \
                        building great source level tools. The included Clang \
                        Static Analyzer is a tool that automatically finds bugs in \
                        your code, and is a great example of the sort of tool \
                        that can be built using the Clang frontend as a \
                        library to parse C/C++ code.

    depends_lib         port:libxml2 port:libomp port:llvm-${llvm_version}
    depends_run         port:clang_select-${llvm_version} port:ld64
    depends_skip_archcheck-append ld64 subversion

    # Older Xcode's cctools can't understand objects produced by newer clangs
    # (malformed object (unknown load command 2)) see #53159, #57412
    if {[vercmp $xcodeversion "6.0.0"] < 0} {
        depends_build-append port:cctools
        depends_run-append port:cctools
        depends_skip_archcheck-append cctools
    }

    # Avoid requiring a bootstrap version of perl5 on 10.6.
    if {${os.major} >= 11} {
        default_variants    +analyzer
    }

    # Not supported on macOS11 and newer
    platforms {darwin < 20}
} elseif {${subport} eq "lldb-${llvm_version}"} {
    homepage            https://lldb.llvm.org/
    description         the LLVM debugger
    long_description    Lldb is the "LLVM native" debugger.

    depends_lib         port:libxml2 port:libomp port:llvm-${llvm_version} port:ncurses
    depends_build-append port:swig-python path:bin/doxygen:doxygen
    depends_run         port:lldb_select-${llvm_version}

    # Clang doesn't actually use any of these, but the LLVM makefile
    # system overlinks its binaries. Remove (or convert to build deps?)
    # after #46040 is resolved.
    depends_lib-append  port:libedit port:libffi port:ncurses port:zlib
}

version                 ${llvm_version}.2
epoch                   2
master_sites            https://releases.llvm.org/${version}
use_xz                  yes
extract.suffix          .tar.xz
distfiles               llvm-${version}.src${extract.suffix}
worksrcdir              llvm-${version}.src

if {${distfiles} ne ""} {
    if {${subport} eq "llvm-${llvm_version}"} {
        if {[variant_isset polly]} {
            distfiles-append     polly-${version}.src${extract.suffix}
        }
    } elseif {${subport} eq "clang-${llvm_version}"} {
        distfiles-append     cfe-${version}.src${extract.suffix} compiler-rt-${version}.src${extract.suffix} libcxx-${version}.src${extract.suffix} clang-tools-extra-${version}.src${extract.suffix}
    } elseif {${subport} eq "lldb-${llvm_version}"} {
        distfiles-append     cfe-${version}.src${extract.suffix} lldb-${version}.src${extract.suffix}
    }
}

checksums           llvm-5.0.2.src.tar.xz \
                    rmd160  b2083bf510d806fd2d7601905f2bf5c03f4de2b8 \
                    sha256  d522eda97835a9c75f0b88ddc81437e5edbb87dc2740686cb8647763855c2b3c \
                    size    23451868 \
                    cfe-5.0.2.src.tar.xz \
                    rmd160  e4aa04b8aaa39d7c222d33b0e95b8d06c423d229 \
                    sha256  fa9ce9724abdb68f166deea0af1f71ca0dfa9af8f7e1261f2cae63c280282800 \
                    size    11459216 \
                    compiler-rt-5.0.2.src.tar.xz \
                    rmd160  428960088def1d16a76ba9a679addf866249436a \
                    sha256  3efe9ddf3f69e0c0a45cde57ee93911f36f3ab5f2a7f6ab8c8efb3db9b24ed46 \
                    size    1543256 \
                    libcxx-5.0.2.src.tar.xz \
                    rmd160  3a751ac733fbb0d43bce63bf50ff5b0be0b71f56 \
                    sha256  6edf88e913175536e1182058753fff2365e388e017a9ec7427feb9929c52e298 \
                    size    1530908 \
                    clang-tools-extra-5.0.2.src.tar.xz \
                    rmd160  1165231393b5754a8fda51ddaf93a3faa36509c8 \
                    sha256  a3362a854ba4a60336b21a95612f647f4b6de0afd88858f2420e41c5a31b0b05 \
                    size    646272 \
                    lldb-5.0.2.src.tar.xz \
                    rmd160  805f97c1315c7bf391a3ddc7ca78e5403a336f54 \
                    sha256  78ba05326249b4d7577db56d16b2a7ffea43fc51e8592b0a1ac4d2ef87514216 \
                    size    19220632 \
                    polly-5.0.2.src.tar.xz \
                    rmd160  2e806d5eb56539473c5c7016ff36a9d7019609fe \
                    sha256  dda84e48b2195768c4ef25893edd5eeca731bed7e80a2376119dfbc3350e91b8 \
                    size    8513656

patch.pre_args-replace  -p0 -p1

patchfiles \
    0001-Set-the-Mach-O-CPU-Subtype-to-ppc7400-when-targeting.patch \
    0002-Define-EXC_MASK_CRASH-and-MACH_EXCEPTION_CODES-if-th.patch \
    0003-MacPorts-Only-Don-t-embed-the-deployment-target-in-t.patch \
    0004-Fix-build-issues-pre-Lion-due-to-missing-a-strnlen-d.patch \
    0005-Dont-build-LibFuzzer-pre-Lion-due-to-missing-__threa.patch \
    0005-Threading-Only-call-pthread_setname_np-on-SnowLeopar.patch

if {${subport} eq "clang-${llvm_version}"} {
    patchfiles-append \
        1001-MacPorts-Only-Prepare-clang-format-for-replacement-w.patch \
        1002-MacPorts-Only-Fix-name-of-scan-view-executable-insid.patch \
        1003-Default-to-ppc7400-for-OSX-10.5.patch \
        1004-Only-call-setpriority-PRIO_DARWIN_THREAD-0-PRIO_DARW.patch \
        1005-Default-to-fragile-ObjC-runtime-when-targeting-darwi.patch \
        1006-Fixup-libstdc-header-search-paths-for-older-versions.patch \
        1007-Fix-build-issues-pre-Lion-due-to-missing-a-strnlen-d.patch \
        1008-Fix-float.h-to-work-on-Snow-Leopard-and-earlier.patch \
        1234-clang-stop-on-linker-error.patch \
        2001-tsan-Annotate-function-parameters-with-attribute-noe.patch \
        2002-Ignore-the-DISPATCH_NOESCAPE-if-not-defined.patch \
        3001-Fix-local-and-iterator-when-building-with-Lion-and-n.patch \
        3002-Fix-missing-long-long-math-prototypes-when-using-the.patch \
        3003-implement-atomic-using-mutex-lock_guard-for-64b-ops-.patch \
        3004-compiler-rt-leopard-no-libdispatch.patch \
        openmp-locations.patch
}
if {${subport} eq "lldb-${llvm_version}"} {
    # lldb needs the clang sources present, so we apply the applicable patches.
    patchfiles-append \
        1001-MacPorts-Only-Prepare-clang-format-for-replacement-w.patch \
        1002-MacPorts-Only-Fix-name-of-scan-view-executable-insid.patch \
        1003-Default-to-ppc7400-for-OSX-10.5.patch \
        1004-Only-call-setpriority-PRIO_DARWIN_THREAD-0-PRIO_DARW.patch \
        1005-Default-to-fragile-ObjC-runtime-when-targeting-darwi.patch \
        1006-Fixup-libstdc-header-search-paths-for-older-versions.patch \
        1007-Fix-build-issues-pre-Lion-due-to-missing-a-strnlen-d.patch \
        1008-Fix-float.h-to-work-on-Snow-Leopard-and-earlier.patch \
        4001-https-llvm.org-bugs-show_bug.cgi-id-31433.patch \
        4002-Fix-build-on-Mountain-Lion.patch \
        openmp-locations.patch
}

configure.post_args         ../${worksrcdir}
default configure.dir       {${workpath}/build}
default build.dir           {${workpath}/build}

cmake.install_prefix ${sub_prefix}

# clang shared libraries are not installed in ${cmake.install_prefix}/lib
# so we have to let the llvm/clang cmake scripts handle the @rpath setting
# See:
#     https://llvm.org/bugs/show_bug.cgi?id=31425
#     https://trac.macports.org/ticket/53299
configure.args-delete \
    -DCMAKE_INSTALL_NAME_DIR=${cmake.install_prefix}/lib \
    -DCMAKE_INSTALL_RPATH=${cmake.install_prefix}/lib \
    -DCMAKE_SYSTEM_PREFIX_PATH="${prefix}\;/usr"
configure.args-append \
    -DCMAKE_SYSTEM_PREFIX_PATH="${cmake.install_prefix}\;${prefix}\;/usr"

configure.args-append \
    -DLLVM_LINK_LLVM_DYLIB=ON \
    -DLLVM_ENABLE_ASSERTIONS=OFF \
    -DLLVM_ENABLE_RTTI=ON \
    -DLLVM_INCLUDE_TESTS=OFF \
    -DLLVM_INCLUDE_EXAMPLES=OFF \
    -DLLVM_ENABLE_FFI=ON \
    -DLLVM_BINDINGS_LIST=none \
    -DFFI_INCLUDE_DIR=${prefix}/include \
    -DFFI_LIBRARY_DIR=${prefix}/lib

if {${os.major} < 11} {
    # See https://trac.macports.org/ticket/54996
    configure.args-append \
        -DLLVM_USE_SANITIZE_COVERAGE=OFF
}

if {${subport} eq "clang-${llvm_version}"} {
    # CMAKE_LINKER is used to determine the value for HOST_LINK_VERSION
    configure.args-append \
        -DCMAKE_LINKER=${prefix}/bin/ld \
        -DCLANG_INCLUDE_TESTS=OFF \
        -DCLANG_ENABLE_STATIC_ANALYZER=OFF \
        -DCLANG_ENABLE_ARCMT=OFF \
        -DDARWIN_PREFER_PUBLIC_SDK=ON \
        -DLLVM_BUILD_RUNTIME=ON \
        -DLIBCXX_ENABLE_SHARED=OFF \
        -DLIBCXX_INSTALL_LIBRARY=OFF

    if {${os.major} <= 13} {
        # We unfortunately don't have an option to just turn off tsan
        # https://llvm.org/bugs/show_bug.cgi?id=27715
        configure.args-append \
            -DCOMPILER_RT_BUILD_SANITIZERS=OFF
    }
    if {${os.major} <= 11} {
        # libfuzzer uses TLS, so disable it on Snow Leopard and earlier
       configure.args-append \
           -DCOMPILER_RT_BUILD_LIBFUZZER=OFF
    }
    if {${os.major} <= 9} {
        # xray calls in sanitizer_common, which presently
        # does not build on < SnowLeopard
       configure.args-append \
           -DCOMPILER_RT_BUILD_XRAY=OFF
    }
} elseif {${subport} eq "lldb-${llvm_version}"} {
    configure.args-append \
        -DLLDB_CODESIGN_IDENTITY=- \
        -DCLANG_ENABLE_ARCMT=OFF \
        -DCLANG_INCLUDE_TESTS=OFF \
        -DCLANG_ENABLE_STATIC_ANALYZER=OFF \
        -DLLVM_BUILD_RUNTIME=ON \
        -DLIBCXX_ENABLE_SHARED=OFF \
        -DLIBCXX_INSTALL_LIBRARY=OFF
}

# llvm-3.5 and later requires a C++11 runtime
# Xcode 4.3's clang (318.x) fails per https://trac.macports.org/ticket/44161
# Xcode 4.5's clang (421.11.66) fails due to http://llvm.org/bugs/show_bug.cgi?id=20184
# Xcode 4.6.3's clang (425.0.28) fails due to http://trac.macports.org/ticket/46897
# Xcode 4.6.3's clang (425.0.28) fails due to https://llvm.org/bugs/show_bug.cgi?id=30384
# Xcode 5.1's clang (clang-503.0.40) has codegen issues (resulting compiler crashes)
# Xcode 6.2's clang (600.0.57) fails due to https://llvm.org/bugs/show_bug.cgi?id=25753
compiler.blacklist *gcc* {clang < 602}

# clang older than 3.5 fail due to https://llvm.org/bugs/show_bug.cgi?id=25753
# llvm-5.0 builds with clang-3.4 but has codegen issues resulting compiler crashes
compiler.blacklist-append macports-clang-3.3 macports-clang-3.4

# Override the normal compiler fallback list entirely since we have
# such specific requirements.
compiler.fallback   clang

# 3.7 is already needed to bootstrap cmake, so is a good last resort
# when the system clang is too old.
if {${os.platform} eq "darwin" && ${os.major} < 18} {
    compiler.fallback-append macports-clang-3.7
}

if {${subport} eq "lldb-${llvm_version}"} {
    # Xcode 6.4's clang (602.0.53) fails to build lldb with 'thread-local storage is not supported for the current target'
    compiler.blacklist-append {clang < 702}
}

# I'm not sure the exact version of Xcode that has a good enough libtool, but 3.2.6 seems to get past this when 3.1.4 doesn't:
#     /Developer/usr/bin/libtool: for architecture x86_64 object: CMakeFiles/LLVMSupport.dir/PluginLoader.cpp.o malformed object (unknown load command 1)
#     /Developer/usr/bin/libtool: for architecture: (null) file: CMakeFiles/LLVMSupport.dir/PluginLoader.cpp.o is not an object file (not allowed in a library)
#     /Developer/usr/bin/libtool: for architecture i386 object: CMakeFiles/LLVMSupport.dir/PluginLoader.cpp.o malformed object (unknown load command 1)
if {[string match macports-clang-* ${configure.compiler}]} {
    depends_build-append port:cctools
    depends_skip_archcheck-append cctools
}

# Set CMAKE_LIBTOOL if we're using MacPorts-provided cctools
if {[lsearch -exact $PortInfo(depends_build) port:cctools] != -1} {
    configure.args-append \
        -DCMAKE_LIBTOOL=${prefix}/bin/libtool
}

# use the system python27 if present
if {${os.platform} eq "darwin" && ${os.major} >= 11 && ${os.major} < 21} {
    set pythonfullpath   /usr/bin/python2.7
} else {
    set pythonfullpath   ${prefix}/bin/python2.7
    depends_lib-append   port:python27
}
configure.args-append   -DPYTHON_EXECUTABLE=${pythonfullpath}

platform darwin {
    # libcxx is untested on PPC
    if {${build_arch} ni [list ppc ppc64]} {
        configure.cxx_stdlib libc++
        depends_lib-append port:libcxx

        pre-fetch {
            if {${os.major} < 11} {
                if {![file exists /usr/lib/libc++.dylib]} {
                    ui_error "$name requires a C++11 runtime, which your configuration does not allow"
                    error "unsupported configuration"
                }
            }
        }
    }
}

variant assertions description "Enable assertions for error detection (has performance impacts, especially on JIT)" {
    configure.args-delete -DLLVM_ENABLE_ASSERTIONS=OFF
    configure.args-append -DLLVM_ENABLE_ASSERTIONS=ON
}

platform darwin {

    if {${os.major} < 14} {
        # use cmake-bootstrap to minimize dependencies.
        depends_build-replace  path:bin/cmake:cmake port:cmake-bootstrap
        configure.cmd          ${prefix}/libexec/cmake-bootstrap/bin/cmake

        # remove need for port:libxml2 dependency
        depends_lib-delete     port:libxml2
        configure.args-append  -DLIBXML2_INCLUDE_DIR=/usr/include/libxml2
        configure.args-append  -DLIBXML2_LIBRARIES=/usr/lib/libxml2.dylib
        configure.args-append  -DLIBXML2_XMLLINT_EXECUTABLE=/usr/bin/xmllint
    }

    if {[string match "*ppc*" [get_canonical_archs]]} {
        # http://trac.macports.org/ticket/33987
        configure.optflags    -Os
    }

    if {${subport} eq "clang-${llvm_version}" && [vercmp $xcodeversion 5.0] < 0} {
        # https://llvm.org/bugs/show_bug.cgi?id=13671
        patchfiles-append leopard-no-asan.patch
        configure.args-append -DCOMPILER_RT_BUILD_SANITIZERS=OFF
    }

    if {${subport} eq "clang-${llvm_version}" && ${os.major} <= 9} {
        patchfiles-append leopard-no-blocks.patch
    }

    if {${os.major} < 11} {
        # Proxy for eliminating the dependency on native TLS
        # http://trac.macports.org/ticket/46887
        configure.args-append -DLLVM_ENABLE_BACKTRACES=OFF

        # https://llvm.org/bugs/show_bug.cgi?id=25680
        configure.cxxflags-append -U__STRICT_ANSI__

        # Wrong type in OrcRemoteTargetClient.h
        # error: could not convert 'Src->((llvm::orc::remote::OrcRemoteTargetClient<ChannelT>*)this)->callB<llvm::orc::remote::OrcRemoteTargetRPCAPI::ReadMem>(Size)'
        # from 'Expected<vector<unsigned char,allocator<unsigned char>>>' to 'Expected<vector<char,allocator<char>>>'
        # Patch borrows from llvm-7.1: https://github.com/iains/LLVM-7-branch/blob/7.1.1-Darwin-WIP/llvm/include/llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h
        patchfiles-append patch-include-orc.diff
    }

    # https://llvm.org/bugs/show_bug.cgi?id=25674
    configure.cxxflags-append -std=c++11
}

if {${subport} eq "lldb-${llvm_version}"} {
    platforms {darwin >= 13} {darwin < 21}
}

post-extract {
    if {${subport} eq "llvm-${llvm_version}"} {
        if {[variant_isset polly]} {
            file rename ${workpath}/polly-${version}.src ${worksrcpath}/tools/polly
        }
    } elseif {${subport} eq "clang-${llvm_version}"} {
        file rename ${workpath}/cfe-${version}.src ${worksrcpath}/tools/clang
        file rename ${workpath}/compiler-rt-${version}.src ${worksrcpath}/projects/compiler-rt
        file rename ${workpath}/libcxx-${version}.src ${worksrcpath}/projects/libcxx
        file rename ${workpath}/clang-tools-extra-${version}.src ${worksrcpath}/tools/clang/tools/extra
    } elseif {${subport} eq "lldb-${llvm_version}"} {
        file rename ${workpath}/cfe-${version}.src ${worksrcpath}/tools/clang
        file rename ${workpath}/lldb-${version}.src ${worksrcpath}/tools/lldb
    }
}

if {${subport} eq "clang-${llvm_version}"} {
    destroot {
        system "cd ${destroot.dir}/tools/clang && ${destroot.cmd} ${destroot.pre_args} ${destroot.target} ${destroot.post_args}"
        system "cd ${destroot.dir}/projects/compiler-rt && ${destroot.cmd} ${destroot.pre_args} ${destroot.target} ${destroot.post_args}"
        system "cd ${destroot.dir}/projects/libcxx && ${destroot.cmd} ${destroot.pre_args} ${destroot.target} ${destroot.post_args}"

        delete ${destroot}${sub_prefix}/bin/clang
        file rename ${destroot}${sub_prefix}/bin/clang-${clang_executable_version} ${destroot}${sub_prefix}/bin/clang
        reinplace "s|/bin/clang-${clang_executable_version}|/bin/clang|g" \
            "${destroot}${sub_prefix}/lib/cmake/clang/ClangTargets-release.cmake"
    }
}

if {${subport} eq "lldb-${llvm_version}"} {
    post-patch {
        reinplace "s|@@PREFIX@@|${prefix}|" \
            ${worksrcpath}/tools/clang/lib/Driver/ToolChains/Clang.cpp \
            ${worksrcpath}/tools/clang/lib/Driver/ToolChains/CommonArgs.cpp

        reinplace "s|@CLANG_FORMAT_PATH@|${prefix}/bin/clang-format-${suffix}|g" \
            ${worksrcpath}/tools/clang/tools/clang-format/clang-format-bbedit.applescript \
            ${worksrcpath}/tools/clang/tools/clang-format/clang-format-diff.py            \
            ${worksrcpath}/tools/clang/tools/clang-format/clang-format-sublime.py         \
            ${worksrcpath}/tools/clang/tools/clang-format/clang-format.el                 \
            ${worksrcpath}/tools/clang/tools/clang-format/clang-format.py
    }

    build.dir   ${build.dir}/tools/lldb

    post-destroot {
        xinstall -m 755 -d ${destroot}${prefix}/share/doc/lldb-${llvm_version}
        xinstall -m 644 ${worksrcpath}/tools/lldb/docs/code-signing.txt ${destroot}${prefix}/share/doc/lldb-${llvm_version}/
    }

    notes "Please follow the instructions in ${prefix}/share/doc/lldb-${llvm_version}/code-signing.txt and then codesign the debugserver with:\n--------------------\n"
    if {${os.major} >= 13} {
        notes-append "sudo codesign --force --deep --preserve-metadata=identifier,entitlements,resource-rules,requirements,flags,team-identifier --sign <identity> ${sub_prefix}/bin/debugserver"
    } else {
        notes-append "sudo codesign --force --deep --preserve-metadata=identifier,entitlements,resource-rules,requirements --sign <identity> ${sub_prefix}/bin/debugserver"
    }
}

post-destroot {
    foreach bin [glob ${destroot}${sub_prefix}/bin/*] {
        set bin_filename [string map "${sub_prefix} ${prefix}" ${bin}]-${suffix}
        set exec_path [string map "${destroot}${sub_prefix} ${sub_prefix}" ${bin}]

        # see https://trac.macports.org/ticket/54985
        if {${os.platform} eq "darwin" && [vercmp ${xcodeversion} 4.6] < 0} {
             xinstall -m 755 "${filespath}/llvm-bin-compat" "${bin_filename}"
        } else {
             xinstall -m 755 "${filespath}/llvm-bin" "${bin_filename}"
        }

        reinplace "s:EXEC_PATH:${exec_path}:" "${bin_filename}"
    }

    if {${subport} eq "llvm-${llvm_version}"} {
        # r156389 (a5d2435409858728970202226d0bbbee508fe408) temporarilary removed llvm man pages
        #foreach man [glob ${destroot}${sub_prefix}/share/man/man1/*.1] {
        #    set basename [string map "${destroot}${sub_prefix}/share/man/man1/ {}" ${man}]
        #    file rename ${man} ${destroot}${prefix}/share/man/man1/[string map ".1 -${suffix}.1" ${basename}]
        #}

        # https://trac.macports.org/ticket/53673
        ln -s llvm-dsymutil ${destroot}${sub_prefix}/bin/dsymutil

        # https://llvm.org/bugs/show_bug.cgi?id=19465
        if {[variant_isset polly]} {
            ln -s LLVMPolly.so ${destroot}${sub_prefix}/lib/LLVMPolly.dylib
        }
    } elseif {${subport} eq "clang-${llvm_version}"} {
        system "ditto ${worksrcpath}/projects/libcxx/include ${destroot}${sub_prefix}/lib/c++/v1"

        # http://trac.macports.org/ticket/33207
        ln -s ${prefix}/libexec/ld64/ld ${destroot}${sub_prefix}/bin/ld
    } elseif {${subport} eq "lldb-${llvm_version}"} {
        delete ${destroot}${prefix}/bin/debugserver-${suffix}
    }
}

if {${subport} eq "llvm-${llvm_version}"} {
    variant polly description {Provide the polly polyhedral optimizer} {}

    # Unless upstream reverts to their old OCaml detection mechanism,
    # this variant will be broken until #46161 is resolved.
    variant ocaml description {Enable generation of OCaml binding} {
        depends_lib-append   port:ocaml

        configure.args-delete -DLLVM_BINDINGS_LIST=none
        configure.args-append -DLLVM_BINDINGS_LIST=ocaml

        destroot.args-append  OVERRIDE_libdir=${sub_prefix}/lib
    }
} elseif {${subport} eq "clang-${llvm_version}"} {
    if {[variant_isset assertions]} {
        # Need to match llvm +-assertions
        require_active_variants port:llvm-${llvm_version} assertions
    } else {
        # Need to match llvm +-assertions
        require_active_variants port:llvm-${llvm_version} {} assertions
    }

    variant analyzer description {Install clang static analyzer} {
        # these have to be switched on or off together
        configure.args-replace -DCLANG_ENABLE_STATIC_ANALYZER=OFF \
                               -DCLANG_ENABLE_STATIC_ANALYZER=ON
        configure.args-replace -DCLANG_ENABLE_ARCMT=OFF \
                               -DCLANG_ENABLE_ARCMT=ON

        depends_run-append port:perl5

        post-patch {
            reinplace "s|/usr/bin/env perl|${prefix}/bin/perl5|g" \
                ${worksrcpath}/tools/clang/tools/scan-build/libexec/ccc-analyzer \
                ${worksrcpath}/tools/clang/tools/scan-build/libexec/c++-analyzer \
                ${worksrcpath}/tools/clang/tools/scan-build/bin/scan-build
            reinplace "s|/usr/bin/env python|${pythonfullpath}|g" \
                ${worksrcpath}/tools/clang/tools/scan-build/bin/set-xcode-analyzer \
                ${worksrcpath}/tools/clang/tools/scan-view/bin/scan-view
        }
    }

    variant emulated_tls description { enable c11/c++11 thread support on older systems using emulated-tls } {
        # allow clang to use emulated-tls to support thread_local on systems prior to 10.7
        # emulated TLS works when linking against macports-libstdc++ or against
        # libc++ / libc++abi with cxa_thread_atexit and emutls.c objects included
        patchfiles-append \
            9000-patch-clang-support-emulated-tls.diff
    }
    default_variants-append +emulated_tls

    variant defaultlibcxx description {default to -stdlib=libc++ on all systems}  {
        #patch clang to always default to -stdlib=libc++ if not otherwise specified
        patchfiles-append 9003-patch-clang-5.0-Toolchains-default-to-libcxx-on-all-systems.diff
    }

    # if macports.conf is configured to stdlib=libc++ then make that the default if not otherwise specified
    # exactly matches the behaviour of newer systems
    if { ${cxx_stdlib} eq "libc++" } {
        default_variants-append +defaultlibcxx
    }

    variant libstdcxx description {-stdlib=libstdc++_macports searches for MacPorts libstdc++} {

        patchfiles-append 9001-macports-libstdcxx.diff
        if {${os.major} < 11} {
            # see https://trac.macports.org/ticket/61778
            depends_run-append  port:libstdcxx_clang_fix
        }

        post-patch {
            reinplace "s|@@MACPORTS_GCC_INCLUDE_DIR@@|${prefix}/include/gcc/c++|g" \
                ${worksrcpath}/tools/clang/lib/Frontend/InitHeaderSearch.cpp
            reinplace "s|@@MACPORTS_HOST_NAME@@|${configure.build_arch}-apple-darwin${os.major}|g" \
                ${worksrcpath}/tools/clang/lib/Frontend/InitHeaderSearch.cpp
            reinplace "s|@@MACPORTS_libstdc++@@|${prefix}/lib/libgcc/libstdc++.6.dylib|g" \
                ${worksrcpath}/tools/clang/lib/Driver/ToolChains/Darwin.cpp

            # GCC was built for ${configure.build_arch}-apple-darwin${os.major}
            # if GCC was also built universal, it has an extra include directory
            # if ${configure.build_arch} is 32-bit, there is an extra 64-bit subdirectory
            # if ${configure.build_arch} is 64-bit, there is an extra 32-bit subdirectory
            # MacPorts GCC cannot compile across platforms
            switch ${configure.build_arch} {
                x86_64 {
                    reinplace {s|@@MACPORTS_32bit_DIR@@|i386|g} \
                        ${worksrcpath}/tools/clang/lib/Frontend/InitHeaderSearch.cpp
                    reinplace {s|@@MACPORTS_64bit_DIR@@||g} \
                        ${worksrcpath}/tools/clang/lib/Frontend/InitHeaderSearch.cpp
                }
                i386 {
                    reinplace {s|@@MACPORTS_32bit_DIR@@||g} \
                        ${worksrcpath}/tools/clang/lib/Frontend/InitHeaderSearch.cpp
                    reinplace {s|@@MACPORTS_64bit_DIR@@|x86_64|g} \
                        ${worksrcpath}/tools/clang/lib/Frontend/InitHeaderSearch.cpp
                }
                ppc64 {
                    reinplace {s|@@MACPORTS_32bit_DIR@@|ppc|g} \
                        ${worksrcpath}/tools/clang/lib/Frontend/InitHeaderSearch.cpp
                    reinplace {s|@@MACPORTS_64bit_DIR@@||g} \
                        ${worksrcpath}/tools/clang/lib/Frontend/InitHeaderSearch.cpp
                }
                ppc {
                    reinplace {s|@@MACPORTS_32bit_DIR@@||g} \
                        ${worksrcpath}/tools/clang/lib/Frontend/InitHeaderSearch.cpp
                    reinplace {s|@@MACPORTS_64bit_DIR@@|ppc64|g} \
                        ${worksrcpath}/tools/clang/lib/Frontend/InitHeaderSearch.cpp
                }
                arm64 {
                    reinplace {s|@@MACPORTS_32bit_DIR@@||g} \
                        ${worksrcpath}/tools/clang/lib/Frontend/InitHeaderSearch.cpp
                    reinplace {s|@@MACPORTS_64bit_DIR@@||g} \
                        ${worksrcpath}/tools/clang/lib/Frontend/InitHeaderSearch.cpp
                }
            }
        }
    }
    if { ${cxx_stdlib} eq "libstdc++" } {
        default_variants-append +libstdcxx
    }

    post-patch {
        reinplace "s|@@PREFIX@@|${prefix}|" \
            ${worksrcpath}/tools/clang/lib/Driver/ToolChains/Clang.cpp \
            ${worksrcpath}/tools/clang/lib/Driver/ToolChains/CommonArgs.cpp

        reinplace "s|@CLANG_FORMAT_PATH@|${prefix}/bin/clang-format-${suffix}|g" \
            ${worksrcpath}/tools/clang/tools/clang-format/clang-format-bbedit.applescript \
            ${worksrcpath}/tools/clang/tools/clang-format/clang-format-diff.py            \
            ${worksrcpath}/tools/clang/tools/clang-format/clang-format-sublime.py         \
            ${worksrcpath}/tools/clang/tools/clang-format/clang-format.el                 \
            ${worksrcpath}/tools/clang/tools/clang-format/clang-format.py
    }

    post-destroot {
        file mkdir ${destroot}${sub_prefix}/libexec
        file copy ${worksrcpath}/tools/clang/tools/clang-format ${destroot}${sub_prefix}/libexec/clang-format

        file delete -force ${destroot}${sub_prefix}/libexec/clang-format/.svn
        file delete -force ${destroot}${sub_prefix}/libexec/clang-format/Makefile
        file delete -force ${destroot}${sub_prefix}/libexec/clang-format/Release+Debug+Asserts
        file delete -force ${destroot}${sub_prefix}/libexec/clang-format/CMakeLists.txt
        file delete -force ${destroot}${sub_prefix}/libexec/clang-format/ClangFormat.cpp
    }
}

livecheck.type          none
