From 68f281f25798294d262ac1c63d17b9a09f470c87 Mon Sep 17 00:00:00 2001 From: Finagolfin Date: Wed, 6 Mar 2024 06:27:00 +0530 Subject: [PATCH] bump(swift): 5.9.2 to 5.10 --- packages/libdispatch/build.sh | 5 +- packages/llbuild/build.sh | 5 +- packages/swift/build.sh | 55 +- packages/swift/swift-android-ndk26.patch | 90 - packages/swift/swift-cmake.patch | 165 +- .../swift/swift-driver-Package.swift.patch | 27 + packages/swift/swift-modify-astgen.patch | 740 -- packages/swift/swift-modify-bridging.patch | 2916 -------- .../swift/swift-move-regex-literals.patch | 1291 ---- packages/swift/swift-move-syntax-build.patch | 1571 ---- packages/swift/swift-pure-bridging.patch | 6451 +++++++++++++++++ .../swift/swift-remove-relative-rpaths.patch | 26 + ...public-runtime-CrashHandlerLinux.cpp.patch | 16 - .../swift-syntax-cross-compile-host.patch | 498 -- .../swift-syntax-regex-cross-compile.patch | 164 - ...swift-syntax-unimplementable-missing.patch | 32 - .../swift-tools-support-core-ndk26.patch | 105 + .../swift-utils-build-script-impl-flags.patch | 22 +- .../swift/swiftpm-disable-local-rpath.patch | 278 - scripts/build/setup/termux_setup_swift.sh | 2 +- 20 files changed, 6777 insertions(+), 7682 deletions(-) create mode 100644 packages/swift/swift-driver-Package.swift.patch delete mode 100644 packages/swift/swift-modify-astgen.patch delete mode 100644 packages/swift/swift-modify-bridging.patch delete mode 100644 packages/swift/swift-move-regex-literals.patch delete mode 100644 packages/swift/swift-move-syntax-build.patch create mode 100644 packages/swift/swift-pure-bridging.patch delete mode 100644 packages/swift/swift-stdlib-public-runtime-CrashHandlerLinux.cpp.patch delete mode 100644 packages/swift/swift-syntax-cross-compile-host.patch delete mode 100644 packages/swift/swift-syntax-regex-cross-compile.patch delete mode 100644 packages/swift/swift-syntax-unimplementable-missing.patch create mode 100644 packages/swift/swift-tools-support-core-ndk26.patch delete mode 100644 packages/swift/swiftpm-disable-local-rpath.patch diff --git a/packages/libdispatch/build.sh b/packages/libdispatch/build.sh index adffc0ec00..741c427f53 100644 --- a/packages/libdispatch/build.sh +++ b/packages/libdispatch/build.sh @@ -2,9 +2,8 @@ TERMUX_PKG_HOMEPAGE=https://github.com/apple/swift-corelibs-libdispatch TERMUX_PKG_DESCRIPTION="The libdispatch project, for concurrency on multicore hardware" TERMUX_PKG_LICENSE="Apache-2.0" TERMUX_PKG_MAINTAINER="@finagolfin" -TERMUX_PKG_VERSION="1:5.9" -TERMUX_PKG_REVISION=1 +TERMUX_PKG_VERSION="1:5.10" TERMUX_PKG_SRCURL=https://github.com/apple/swift-corelibs-libdispatch/archive/swift-${TERMUX_PKG_VERSION:2}-RELEASE.tar.gz -TERMUX_PKG_SHA256=db30ccf6b20963112ab3aad256c2e49a18041a9806cf2f05854fe63a90d688c2 +TERMUX_PKG_SHA256=16e088cf12654d22658879710b9694a6fad1c94d5e5d0c597741b71fbcb3e034 TERMUX_PKG_AUTO_UPDATE=false TERMUX_PKG_DEPENDS="libc++, libblocksruntime" diff --git a/packages/llbuild/build.sh b/packages/llbuild/build.sh index 13c288fef9..07dae2dfc8 100644 --- a/packages/llbuild/build.sh +++ b/packages/llbuild/build.sh @@ -2,9 +2,8 @@ TERMUX_PKG_HOMEPAGE=https://github.com/apple/swift-llbuild TERMUX_PKG_DESCRIPTION="A low-level build system, used by the Swift Package Manager" TERMUX_PKG_LICENSE="Apache-2.0, NCSA" TERMUX_PKG_MAINTAINER="@finagolfin" -TERMUX_PKG_VERSION=5.9 -TERMUX_PKG_REVISION=1 +TERMUX_PKG_VERSION=5.10 TERMUX_PKG_SRCURL=https://github.com/apple/swift-llbuild/archive/swift-${TERMUX_PKG_VERSION}-RELEASE.tar.gz -TERMUX_PKG_SHA256=cc8dfb098db4b0210ca5466f59d3e5fc55c4eedcd835263e6eae7dd719ba8203 +TERMUX_PKG_SHA256=ae8962d59244abac157c02813d05e1c077915bbd6022fe9fb62040806ac8dc55 TERMUX_PKG_DEPENDS="libc++, libandroid-spawn, libsqlite" TERMUX_PKG_NO_STATICSPLIT=true diff --git a/packages/swift/build.sh b/packages/swift/build.sh index 05a00c61ec..1c11e1a5da 100644 --- a/packages/swift/build.sh +++ b/packages/swift/build.sh @@ -2,10 +2,10 @@ TERMUX_PKG_HOMEPAGE=https://swift.org/ TERMUX_PKG_DESCRIPTION="Swift is a high-performance system programming language" TERMUX_PKG_LICENSE="Apache-2.0, NCSA" TERMUX_PKG_MAINTAINER="@finagolfin" -TERMUX_PKG_VERSION=5.9.2 +TERMUX_PKG_VERSION=5.10 SWIFT_RELEASE="RELEASE" TERMUX_PKG_SRCURL=https://github.com/apple/swift/archive/swift-$TERMUX_PKG_VERSION-$SWIFT_RELEASE.tar.gz -TERMUX_PKG_SHA256=5b93c737c24ba7d861e0777800740eaa9ccddfa2a6a4326bd47dbc5aa9ae8379 +TERMUX_PKG_SHA256=874c3b6668fb138db35c9f1c63570dafacac8476a6094b17764a51a45a1b69a2 TERMUX_PKG_AUTO_UPDATE=false TERMUX_PKG_HOSTBUILD=true TERMUX_PKG_DEPENDS="clang, libandroid-glob, libandroid-posix-semaphore, libandroid-spawn, libcurl, libicu, libicu-static, libsqlite, libuuid, libxml2, libdispatch, llbuild, pkg-config, swift-sdk-${TERMUX_ARCH/_/-}" @@ -35,43 +35,44 @@ termux_step_post_get_source() { mv .temp swift declare -A library_checksums - library_checksums[swift-cmark]=658f4eb94f271e68af4ae07f4214f58d36dfc8edd7fc17ac44e8c85bec984337 - library_checksums[llvm-project]=9df7cacc0107202dcdee8025d5cec9fe413f164e28921372acc61fddd78ed473 - library_checksums[swift-experimental-string-processing]=3abc4225789e19defae966f7d9a712c77a5c0366f1d44d37df671048fe62daf6 - library_checksums[swift-syntax]=b1918519f5bc6c7820f14242adfe26d9520a91896349a486359d9809b4e89351 - library_checksums[swift-corelibs-libdispatch]=b1f3e46ed248df6a3456d20bc23b2d8a12b740a40185d81b668b1d31735cadf2 - library_checksums[swift-corelibs-foundation]=e58c529ababd547cf0b205fc0820ccce38a033664625c271110b564f2554dd44 - library_checksums[swift-corelibs-xctest]=7f0d21ce0bb15ed5275b0d6e5ee1747344d9756c9f1913a644a0b2142ee1fb19 - library_checksums[swift-llbuild]=44bcb0f8c6fa6cccdc16b7e75c996987568d8fde3caf8bc83c24a2e10383406f - library_checksums[swift-argument-parser]=44782ba7180f924f72661b8f457c268929ccd20441eac17301f18eff3b91ce0c + library_checksums[swift-cmark]=6b7377e78b59410f8f3993cd6b83fe35fd097369a5cf89aa77c0e8b86d2218ee + library_checksums[llvm-project]=107e88150257e0c12333b4c43baa371a4252118e4977a69f5a16c566ee9f2cd3 + library_checksums[swift-experimental-string-processing]=542fa52af41287772ff36a18f4a8971e0aec07dbf4c59400e6d3422ab42d46df + library_checksums[swift-syntax]=bec161cf707758d34d208c8e00bc338603094b489a9388caff79db1af3af20c7 + library_checksums[swift-corelibs-libdispatch]=16e088cf12654d22658879710b9694a6fad1c94d5e5d0c597741b71fbcb3e034 + library_checksums[swift-corelibs-foundation]=e25700bffc439b36c5c9acf169332c0dd9805fcd91cd570b4ce96163b70bae5b + library_checksums[swift-corelibs-xctest]=b298316185270ac43ecdaf4c2fbd4329af51a18b174650510d7526238e9ca6fa + library_checksums[swift-llbuild]=ae8962d59244abac157c02813d05e1c077915bbd6022fe9fb62040806ac8dc55 + library_checksums[swift-argument-parser]=4a10bbef290a2167c5cc340b39f1f7ff6a8cf4e1b5433b68548bf5f1e542e908 library_checksums[Yams]=ec1ad699c30f0db45520006c63a88cc1c946a7d7b36dff32a96460388c0a4af2 - library_checksums[swift-collections]=575cf0f88d9068411f9acc6e3ca5d542bef1cc9e87dc5d69f7b5a1d5aec8c6b6 - library_checksums[swift-crypto]=a7b2f5c4887ccd728cdff5d1162b4d4d36bd6c2df9c0c31d5b9b73d341c5c1bb + library_checksums[swift-collections]=d0f584b197860db26fd939175c9d1a7badfe7b89949b4bd52d4f626089776e0a + library_checksums[swift-crypto]=5c860c0306d0393ff06268f361aaf958656e1288353a0e23c3ad20de04319154 library_checksums[swift-system]=865b8c380455eef27e73109835142920c60ae4c4f4178a3d12ad04acc83f1371 - library_checksums[swift-asn1]=d4470d61788194abbd60ed73965ee0722cc25037e83d41226a8a780088ba524e - library_checksums[swift-certificates]=d7699ce91d65a622c1b9aaa0235cbbbd1be4ddc42a90fce007ff74bef50e8985 - library_checksums[swift-driver]=e4db5194e99ebbd605a14b86965b301b5a060482ecd1c5c94a4a099de5754e35 - library_checksums[swift-tools-support-core]=e0ab6f07998865549ad4bff34c91a3947a50a0085890d2d32605dfff296980c8 - library_checksums[swift-package-manager]=132ae4908fa9c8f10265585f593dc748a021a18b11d6a1881e22d2db2dd1e162 - library_checksums[indexstore-db]=a907c8fce27e718c179f6a92b73df62675e44b86612116468ff6ebd3f2997b31 - library_checksums[sourcekit-lsp]=0db3e5c56f2889a3be2ff4e9b5a285085459dee6f821c0cdf513eb5c9cc94ae4 + library_checksums[swift-asn1]=e0da995ae53e6fcf8251887f44d4030f6600e2f8f8451d9c92fcaf52b41b6c35 + library_checksums[swift-certificates]=fcaca458aab45ee69b0f678b72c2194b15664cc5f6f5e48d0e3f62bc5d1202ca + library_checksums[swift-driver]=51a48f1f277f4c5f87b8e1f08668e99ecd74f9fbee359ccde502cbb839eb7128 + library_checksums[swift-tools-support-core]=36bb714e46966bdc48e9835e9440508f30f6c9d0b4479a1cebae0ab9f5952bb9 + library_checksums[swift-package-manager]=857391656ef94e7ef249b5d05d6a4226c2ec070ddbdd182d7dac92de748ff526 + library_checksums[indexstore-db]=b701755b9ecef2363b8f91ad3d1f8677d78f06e81857a10de9a835c72176c241 + library_checksums[sourcekit-lsp]=e69f11068546ba1ee0015c68d3dbde0d053f1574ca643dd8d43e1d9dbc4cb2d7 + for library in "${!library_checksums[@]}"; do \ GH_ORG="apple" if [ "$library" = "swift-argument-parser" ]; then - SRC_VERSION="1.2.2" + SRC_VERSION="1.2.3" TAR_NAME=$SRC_VERSION elif [ "$library" = "swift-asn1" ]; then - SRC_VERSION="0.7.0" + SRC_VERSION="1.0.0" TAR_NAME=$SRC_VERSION elif [ "$library" = "swift-certificates" ]; then - SRC_VERSION="0.4.1" - TAR_NAME=$SRC_VERSION - elif [ "$library" = "swift-collections" ]; then SRC_VERSION="1.0.1" TAR_NAME=$SRC_VERSION + elif [ "$library" = "swift-collections" ]; then + SRC_VERSION="1.0.5" + TAR_NAME=$SRC_VERSION elif [ "$library" = "swift-crypto" ]; then - SRC_VERSION="2.5.0" + SRC_VERSION="3.0.0" TAR_NAME=$SRC_VERSION elif [ "$library" = "swift-system" ]; then SRC_VERSION="1.1.1" @@ -133,7 +134,7 @@ termux_step_make() { SWIFT_BUILD_FLAGS="$SWIFT_BUILD_FLAGS --android --android-ndk $TERMUX_STANDALONE_TOOLCHAIN --android-arch $SWIFT_ARCH --build-toolchain-only --skip-local-build --skip-local-host-install - --cross-compile-hosts=android-$SWIFT_ARCH --bootstrapping=off + --cross-compile-hosts=android-$SWIFT_ARCH --cross-compile-deps-path=$(dirname $TERMUX_PREFIX) --native-swift-tools-path=$SWIFT_BINDIR --native-clang-tools-path=$SWIFT_BINDIR diff --git a/packages/swift/swift-android-ndk26.patch b/packages/swift/swift-android-ndk26.patch index 98375b9280..e8467103e8 100644 --- a/packages/swift/swift-android-ndk26.patch +++ b/packages/swift/swift-android-ndk26.patch @@ -205,93 +205,3 @@ index 4d6577d0..aa22dade 100644 messages = constructJobSignalledMessages(job: job, error: errorMessage, output: output, signal: signal, pid: pid).map { ParsableMessage(name: job.kind.rawValue, kind: .signalled($0)) -diff --git a/swift-tools-support-core/Sources/TSCBasic/FileSystem.swift b/swift-tools-support-core/Sources/TSCBasic/FileSystem.swift -index b33b1c6..cd2ce5b 100644 ---- a/swift-tools-support-core/Sources/TSCBasic/FileSystem.swift -+++ b/swift-tools-support-core/Sources/TSCBasic/FileSystem.swift -@@ -491,8 +491,8 @@ private struct LocalFileSystem: FileSystem { - - func readFileContents(_ path: AbsolutePath) throws -> ByteString { - // Open the file. -- let fp = fopen(path.pathString, "rb") -- if fp == nil { -+ let fpo = fopen(path.pathString, "rb") -+ guard let fp = fpo else { - throw FileSystemError(errno: errno, path) - } - defer { fclose(fp) } -@@ -521,8 +521,8 @@ private struct LocalFileSystem: FileSystem { - - func writeFileContents(_ path: AbsolutePath, bytes: ByteString) throws { - // Open the file. -- let fp = fopen(path.pathString, "wb") -- if fp == nil { -+ let fpo = fopen(path.pathString, "wb") -+ guard let fp = fpo else { - throw FileSystemError(errno: errno, path) - } - defer { fclose(fp) } -diff --git a/swift-tools-support-core/Sources/TSCBasic/Process.swift b/swift-tools-support-core/Sources/TSCBasic/Process.swift -index 6c8aa11..71d829c 100644 ---- a/swift-tools-support-core/Sources/TSCBasic/Process.swift -+++ b/swift-tools-support-core/Sources/TSCBasic/Process.swift -@@ -144,6 +144,9 @@ public final class Process { - - /// The current OS does not support the workingDirectory API. - case workingDirectoryNotSupported -+ -+ /// The stdin could not be opened. -+ case stdinNotOpening - } - - public enum OutputRedirection { -@@ -677,7 +680,10 @@ public final class Process { - var stdinPipe: [Int32] = [-1, -1] - try open(pipe: &stdinPipe) - -- let stdinStream = try LocalFileOutputByteStream(filePointer: fdopen(stdinPipe[1], "wb"), closeOnDeinit: true) -+ guard let fp = fdopen(stdinPipe[1], "wb") else { -+ throw Process.Error.stdinNotOpening -+ } -+ let stdinStream = try LocalFileOutputByteStream(filePointer: fp, closeOnDeinit: true) - - // Dupe the read portion of the remote to 0. - posix_spawn_file_actions_adddup2(&fileActions, stdinPipe[0], 0) -@@ -1258,6 +1264,8 @@ extension Process.Error: CustomStringConvertible { - return "could not find executable for '\(program)'" - case .workingDirectoryNotSupported: - return "workingDirectory is not supported in this platform" -+ case .stdinNotOpening: -+ return "could not open stdin on this platform" - } - } - } -diff --git a/swift-tools-support-core/Sources/TSCBasic/WritableByteStream.swift b/swift-tools-support-core/Sources/TSCBasic/WritableByteStream.swift -index aee907e..2047d22 100644 ---- a/swift-tools-support-core/Sources/TSCBasic/WritableByteStream.swift -+++ b/swift-tools-support-core/Sources/TSCBasic/WritableByteStream.swift -@@ -790,7 +790,11 @@ public final class LocalFileOutputByteStream: FileOutputByteStream { - override final func writeImpl(_ bytes: ArraySlice) { - bytes.withUnsafeBytes { bytesPtr in - while true { -+ #if os(Android) -+ let n = fwrite(bytesPtr.baseAddress!, 1, bytesPtr.count, filePointer) -+ #else - let n = fwrite(bytesPtr.baseAddress, 1, bytesPtr.count, filePointer) -+ #endif - if n < 0 { - if errno == EINTR { continue } - errorDetected(code: errno) -diff --git a/swift-tools-support-core/Sources/TSCTestSupport/PseudoTerminal.swift b/swift-tools-support-core/Sources/TSCTestSupport/PseudoTerminal.swift -index 59610b6..2797c71 100644 ---- a/swift-tools-support-core/Sources/TSCTestSupport/PseudoTerminal.swift -+++ b/swift-tools-support-core/Sources/TSCTestSupport/PseudoTerminal.swift -@@ -24,7 +24,7 @@ public final class PseudoTerminal { - if openpty(&primary, &secondary, nil, nil, nil) != 0 { - return nil - } -- guard let outStream = try? LocalFileOutputByteStream(filePointer: fdopen(secondary, "w"), closeOnDeinit: false) else { -+ guard let outStream = try? LocalFileOutputByteStream(filePointer: fdopen(secondary, "w")!, closeOnDeinit: false) else { - return nil - } - self.outStream = outStream diff --git a/packages/swift/swift-cmake.patch b/packages/swift/swift-cmake.patch index 3b141963d2..24edf14d4a 100644 --- a/packages/swift/swift-cmake.patch +++ b/packages/swift/swift-cmake.patch @@ -44,27 +44,6 @@ index ac9e0871489d..b495cbfb5c2e 100644 RESULT_VARIABLE had_error OUTPUT_VARIABLE library_file ) -diff --git a/llvm-project/llvm/cmake/modules/FindTerminfo.cmake b/llvm-project/llvm/cmake/modules/FindTerminfo.cmake -index 65edb80fa6..d02a445021 100644 ---- a/llvm-project/llvm/cmake/modules/FindTerminfo.cmake -+++ b/llvm-project/llvm/cmake/modules/FindTerminfo.cmake -@@ -14,15 +14,7 @@ - find_library(Terminfo_LIBRARIES NAMES terminfo tinfo curses ncurses ncursesw) - - if(Terminfo_LIBRARIES) -- include(CMakePushCheckState) -- include(CheckCSourceCompiles) -- cmake_push_check_state() -- list(APPEND CMAKE_REQUIRED_LIBRARIES ${Terminfo_LIBRARIES}) -- check_c_source_compiles(" -- int setupterm(char *term, int filedes, int *errret); -- int main() { return setupterm(0, 0, 0); }" -- Terminfo_LINKABLE) -- cmake_pop_check_state() -+ set(Terminfo_LINKABLE 1) - endif() - - include(FindPackageHandleStandardArgs) diff --git a/swift/CMakeLists.txt b/swift/CMakeLists.txt index b7503ecdd6..c643c2c9a5 100644 --- a/swift/CMakeLists.txt @@ -78,7 +57,24 @@ index b7503ecdd6..c643c2c9a5 100644 set(SWIFT_BUILD_HOST_DISPATCH TRUE) endif() -@@ -976,7 +976,8 @@ if (LLVM_ENABLE_DOXYGEN) +@@ -857,7 +857,7 @@ endif() + + if(SWIFT_BUILD_SWIFT_SYNTAX) + # Only "HOSTTOOLS" is supported in Linux when Swift parser integration is enabled. +- if(SWIFT_HOST_VARIANT_SDK MATCHES "LINUX|ANDROID|OPENBSD|FREEBSD" AND NOT BOOTSTRAPPING_MODE STREQUAL "HOSTTOOLS") ++ if(SWIFT_HOST_VARIANT_SDK MATCHES "LINUX|OPENBSD|FREEBSD" AND NOT BOOTSTRAPPING_MODE STREQUAL "HOSTTOOLS") + message(WARNING "Force setting BOOTSTRAPPING=HOSTTOOLS because Swift parser integration is enabled") + set(BOOTSTRAPPING_MODE "HOSTTOOLS") + endif() +@@ -1187,6 +1187,7 @@ if(SWIFT_INCLUDE_TOOLS) + message(STATUS " Assertions: ${LLVM_ENABLE_ASSERTIONS}") + message(STATUS " LTO: ${SWIFT_TOOLS_ENABLE_LTO}") + message(STATUS " Bootstrapping: ${BOOTSTRAPPING_MODE}") ++ message(STATUS " C++ Bridging: ${BRIDGING_MODE}") + message(STATUS " Swift parser: ${SWIFT_BUILD_SWIFT_SYNTAX}") + message(STATUS "") + else() +@@ -1279,7 +1280,8 @@ if (LLVM_ENABLE_DOXYGEN) message(STATUS "Doxygen: enabled") endif() @@ -88,6 +84,16 @@ index b7503ecdd6..c643c2c9a5 100644 include(Libdispatch) endif() +@@ -1345,6 +1345,9 @@ if(SWIFT_INCLUDE_TOOLS) + FetchContent_MakeAvailable(SwiftSyntax) + endfunction() + include_swift_syntax() ++ if (NOT "${SWIFT_ANDROID_NDK_PATH}" STREQUAL "") ++ add_dependencies(SwiftSyntax swift-stdlib-android-${SWIFT_HOST_VARIANT_ARCH}) ++ endif() + + add_subdirectory(lib) + diff --git a/swift/SwiftCompilerSources/CMakeLists.txt b/swift/SwiftCompilerSources/CMakeLists.txt index f4a2eb2dddc..61a2548cf77 100644 --- a/swift/SwiftCompilerSources/CMakeLists.txt @@ -111,19 +117,47 @@ index f4a2eb2dddc..61a2548cf77 100644 endforeach() # Create a static library containing all module object files. +diff --git a/swift/cmake/modules/AddPureSwift.cmake b/swift/cmake/modules/AddPureSwift.cmake +index dc58b8fa0f6..37e9f817471 100644 +--- a/swift/cmake/modules/AddPureSwift.cmake ++++ b/swift/cmake/modules/AddPureSwift.cmake +@@ -44,6 +44,13 @@ function(_add_host_swift_compile_options name) + $<$:none>) + + target_compile_options(${name} PRIVATE $<$:-target;${SWIFT_HOST_TRIPLE}>) ++ if (NOT "${SWIFT_ANDROID_NDK_PATH}" STREQUAL "") ++ swift_android_tools_path(${SWIFT_HOST_VARIANT_ARCH} tools_path) ++ target_compile_options(${name} PRIVATE $<$:-resource-dir;${SWIFTLIB_DIR};> ++ $<$:-sdk;${SWIFT_SDK_ANDROID_ARCH_${SWIFT_HOST_VARIANT_ARCH}_PATH};> ++ $<$:-tools-directory;${tools_path};>) ++ add_dependencies(${name} swift-stdlib-android-${SWIFT_HOST_VARIANT_ARCH}) ++ endif() + _add_host_variant_swift_sanitizer_flags(${name}) + endfunction() + diff --git a/swift/cmake/modules/AddSwift.cmake b/swift/cmake/modules/AddSwift.cmake index a448bcb23c4..0ddbac17a52 100644 --- a/swift/cmake/modules/AddSwift.cmake +++ b/swift/cmake/modules/AddSwift.cmake -@@ -526,7 +526,7 @@ function(_add_swift_runtime_link_flags target relpath_to_lib_dir bootstrapping) - # installed host toolchain. - get_filename_component(swift_bin_dir ${SWIFT_EXEC_FOR_SWIFT_MODULES} DIRECTORY) - get_filename_component(swift_dir ${swift_bin_dir} DIRECTORY) +@@ -548,7 +548,7 @@ + get_filename_component(swift_bin_dir ${SWIFT_EXEC_FOR_SWIFT_MODULES} DIRECTORY) + get_filename_component(swift_dir ${swift_bin_dir} DIRECTORY) + endif() - set(host_lib_dir "${swift_dir}/lib/swift/${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_LIB_SUBDIR}") + set(host_lib_dir "${SWIFT_BINARY_DIR}/lib/swift/${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_LIB_SUBDIR}") - set(swiftrt "${host_lib_dir}/${SWIFT_HOST_VARIANT_ARCH}/swiftrt.o") + set(host_lib_arch_dir "${host_lib_dir}/${SWIFT_HOST_VARIANT_ARCH}") - target_link_libraries(${target} PRIVATE ${swiftrt}) + set(swiftrt "${host_lib_arch_dir}/swiftrt${CMAKE_C_OUTPUT_EXTENSION}") +@@ -606,6 +606,9 @@ function(_add_swift_runtime_link_flags target relpath_to_lib_dir bootstrapping) + endif() + endif() + endif() ++ if(SWIFT_HOST_VARIANT_SDK STREQUAL "ANDROID") ++ target_link_options(${target} PRIVATE "SHELL:-Xlinker -z -Xlinker nostart-stop-gc") ++ endif() + endif() + + set_property(TARGET ${target} PROPERTY BUILD_WITH_INSTALL_RPATH YES) diff --git a/swift/localization/CMakeLists.txt b/swift/localization/CMakeLists.txt index 07a3585a66c..461a98b6856 100644 --- a/swift/localization/CMakeLists.txt @@ -138,18 +172,6 @@ index 07a3585a66c..461a98b6856 100644 PATTERN "*.strings" ) +endif() -diff --git a/swift/stdlib/cmake/modules/AddSwiftStdlib.cmake b/swift/stdlib/cmake/modules/AddSwiftStdlib.cmake -index 25a79d145fb..74a838e2075 100644 ---- a/swift/stdlib/cmake/modules/AddSwiftStdlib.cmake -+++ b/swift/stdlib/cmake/modules/AddSwiftStdlib.cmake -@@ -462,6 +462,7 @@ function(_add_target_variant_link_flags) - list(APPEND link_libraries "dl" "log") - # We need to add the math library, which is linked implicitly by libc++ - list(APPEND result "-lm") -+ list(APPEND result "-fno-openmp-implicit-rpath") - if(NOT "${SWIFT_ANDROID_NDK_PATH}" STREQUAL "") - file(GLOB RESOURCE_DIR ${SWIFT_SDK_ANDROID_ARCH_${LFLAGS_ARCH}_PATH}/../lib64/clang/*) - list(APPEND result "-resource-dir=${RESOURCE_DIR}") diff --git a/swift/stdlib/cmake/modules/SwiftSource.cmake b/swift/stdlib/cmake/modules/SwiftSource.cmake index 4bc312f7f89..d71f6408d9f 100644 --- a/swift/stdlib/cmake/modules/SwiftSource.cmake @@ -236,6 +258,46 @@ index 11cda641cc2..bd2cb152725 100644 compiler ) +endif() +diff --git a/swift/tools/swift-plugin-server/CMakeLists.txt b/swift/tools/swift-plugin-server/CMakeLists.txt +index a21b79ed260..5b591a30514 100644 +--- a/swift/tools/swift-plugin-server/CMakeLists.txt ++++ b/swift/tools/swift-plugin-server/CMakeLists.txt +@@ -1,28 +1,19 @@ + if (SWIFT_BUILD_SWIFT_SYNTAX) +- # _swiftCSwiftPluginServer is just a C support library for swift-plugin-server +- # Don't bother to create '.a' for that. +- add_swift_host_library(_swiftCSwiftPluginServer OBJECT +- Sources/CSwiftPluginServer/PluginServer.cpp +- ) +- target_link_libraries(_swiftCSwiftPluginServer PRIVATE +- swiftDemangling ++ add_swift_host_tool(swift-plugin-server SWIFT_COMPONENT compiler Sources/CSwiftPluginServer/PluginServer.cpp) ++ add_pure_swift_host_library(SwiftPluginServer STATIC ++ Sources/swift-plugin-server/swift-plugin-server.swift + ) +- target_include_directories(_swiftCSwiftPluginServer PUBLIC ++ target_include_directories(SwiftPluginServer PUBLIC + Sources/CSwiftPluginServer/include + ) +- +- add_pure_swift_host_tool(swift-plugin-server +- Sources/swift-plugin-server/swift-plugin-server.swift +- DEPENDENCIES ++ target_link_libraries(SwiftPluginServer PRIVATE SwiftCompilerPluginMessageHandling) ++ target_link_libraries(swift-plugin-server PRIVATE + swiftDemangling +- $ +- SWIFT_COMPONENT +- compiler +- SWIFT_DEPENDENCIES + SwiftSyntaxMacros + SwiftSyntaxMacroExpansion + SwiftCompilerPluginMessageHandling + swiftLLVMJSON ++ SwiftPluginServer + ) + target_include_directories(swift-plugin-server PRIVATE + Sources/CSwiftPluginServer/include diff --git a/swift-corelibs-xctest/CMakeLists.txt b/swift-corelibs-xctest/CMakeLists.txt index 531e7c0..589930f 100644 --- a/swift-corelibs-xctest/CMakeLists.txt @@ -248,11 +310,20 @@ index 531e7c0..589930f 100644 endif() endif() set_target_properties(XCTest PROPERTIES -@@ -69,7 +69,6 @@ set_target_properties(XCTest PROPERTIES - if(ENABLE_TESTING) - enable_testing() +diff --git a/swift-syntax/cmake/modules/AddSwiftHostLibrary.cmake b/swift-syntax/cmake/modules/AddSwiftHostLibrary.cmake +index 951c2d2e..1157ec66 100644 +--- a/swift-syntax/cmake/modules/AddSwiftHostLibrary.cmake ++++ b/swift-syntax/cmake/modules/AddSwiftHostLibrary.cmake +@@ -87,6 +87,12 @@ function(add_swift_syntax_library name) + target_compile_options(${name} PRIVATE + $<$:-wmo>) + endif() ++ if (NOT "${SWIFT_ANDROID_NDK_PATH}" STREQUAL "") ++ swift_android_tools_path(${SWIFT_HOST_VARIANT_ARCH} tools_path) ++ target_compile_options(${name} PRIVATE $<$:-resource-dir;${SWIFTLIB_DIR};> ++ $<$:-sdk;${SWIFT_SDK_ANDROID_ARCH_${SWIFT_HOST_VARIANT_ARCH}_PATH};> ++ $<$:-tools-directory;${tools_path};>) ++ endif() -- enable_language(C) - find_package(LLVM CONFIG) - if(LLVM_FOUND) - message(STATUS "Found LLVM ${LLVM_PACKAGE_VERSION}") + if(LLVM_USE_LINKER) + target_link_options(${name} PRIVATE diff --git a/packages/swift/swift-driver-Package.swift.patch b/packages/swift/swift-driver-Package.swift.patch new file mode 100644 index 0000000000..6279bffe3c --- /dev/null +++ b/packages/swift/swift-driver-Package.swift.patch @@ -0,0 +1,27 @@ +commit 8e11ec10b769ee4de04159a05d5e701a712694cc +Date: Fri Nov 10 15:56:03 2023 +0530 + + Revert 'Add missing dependency (#1414)' + + The llbuild executable is not a dependency of this library. + +diff --git a/swift-driver/Package.swift b/swift-driver/Package.swift +index f09f530d..0e1c989c 100644 +--- a/swift-driver/Package.swift ++++ b/swift-driver/Package.swift +@@ -145,7 +145,6 @@ if ProcessInfo.processInfo.environment["SWIFT_DRIVER_LLBUILD_FWK"] == nil { + ] + package.targets.first(where: { $0.name == "SwiftDriverExecution" })!.dependencies += [ + .product(name: "llbuildSwift", package: "swift-llbuild"), +- .product(name: "llbuild", package: "swift-llbuild"), + ] + } else { + // In Swift CI, use a local path to llbuild to interoperate with tools +@@ -155,7 +154,6 @@ if ProcessInfo.processInfo.environment["SWIFT_DRIVER_LLBUILD_FWK"] == nil { + ] + package.targets.first(where: { $0.name == "SwiftDriverExecution" })!.dependencies += [ + .product(name: "llbuildSwift", package: "llbuild"), +- .product(name: "llbuild", package: "llbuild"), + ] + } + } diff --git a/packages/swift/swift-modify-astgen.patch b/packages/swift/swift-modify-astgen.patch deleted file mode 100644 index 55f1761f14..0000000000 --- a/packages/swift/swift-modify-astgen.patch +++ /dev/null @@ -1,740 +0,0 @@ -From dba94bdbd4f4b1e9b3b271409cbc5d1bb49ddaf3 -From: Doug Gregor -Date: Fri, 19 May 2023 15:02:42 -0700 -Subject: [PATCH] [ASTGen] Add experimental feature to use ASTGen in lieu - of parsing types - -Introduce a new experimental feature `ASTGenTypes` that uses ASTGen to -translate the Swift syntax tree (produced by the new Swift parser) -into C++ `TypeRepr` nodes instead of having the C++ parser create the -nodes. - -The approach here is to intercept the C++ parser's `parseType` -operation to find the Swift syntax node at the given position (where -the lexer currently is) and have ASTGen translate that into the -corresponding C++ AST node. Then, we spin the lexer forward to the -token immediately following the end of the syntax node and continue -parsing. - -diff --git a/swift/include/swift/AST/CASTBridging.h b/swift/include/swift/AST/CASTBridging.h -index 4699a291a1f..dd24e573561 100644 ---- a/swift/include/swift/AST/CASTBridging.h -+++ b/swift/include/swift/AST/CASTBridging.h -@@ -112,6 +112,70 @@ typedef enum ENUM_EXTENSIBILITY_ATTR(open) BridgedMacroDefinitionKind : long { - BridgedBuiltinExternalMacro - } BridgedMacroDefinitionKind; - -+/// Bridged parameter specifiers -+typedef enum ENUM_EXTENSIBILITY_ATTR(open) BridgedAttributedTypeSpecifier : long { -+ BridgedAttributedTypeSpecifierInOut, -+ BridgedAttributedTypeSpecifierBorrowing, -+ BridgedAttributedTypeSpecifierConsuming, -+ BridgedAttributedTypeSpecifierLegacyShared, -+ BridgedAttributedTypeSpecifierLegacyOwned, -+ BridgedAttributedTypeSpecifierConst, -+ BridgedAttributedTypeSpecifierIsolated, -+} BridgedAttributedTypeSpecifier; -+ -+ -+// Bridged type attribute kinds, which mirror TypeAttrKind exactly. -+typedef enum ENUM_EXTENSIBILITY_ATTR(closed) BridgedTypeAttrKind : long { -+ BridgedTypeAttrKind_autoclosure, -+ BridgedTypeAttrKind_convention, -+ BridgedTypeAttrKind_noescape, -+ BridgedTypeAttrKind_escaping, -+ BridgedTypeAttrKind_differentiable, -+ BridgedTypeAttrKind_noDerivative, -+ BridgedTypeAttrKind_async, -+ BridgedTypeAttrKind_Sendable, -+ BridgedTypeAttrKind_unchecked, -+ BridgedTypeAttrKind__local, -+ BridgedTypeAttrKind__noMetadata, -+ BridgedTypeAttrKind__opaqueReturnTypeOf, -+ BridgedTypeAttrKind_block_storage, -+ BridgedTypeAttrKind_box, -+ BridgedTypeAttrKind_dynamic_self, -+ BridgedTypeAttrKind_sil_weak, -+ BridgedTypeAttrKind_sil_unowned, -+ BridgedTypeAttrKind_sil_unmanaged, -+ BridgedTypeAttrKind_error, -+ BridgedTypeAttrKind_out, -+ BridgedTypeAttrKind_direct, -+ BridgedTypeAttrKind_in, -+ BridgedTypeAttrKind_inout, -+ BridgedTypeAttrKind_inout_aliasable, -+ BridgedTypeAttrKind_in_guaranteed, -+ BridgedTypeAttrKind_in_constant, -+ BridgedTypeAttrKind_pack_owned, -+ BridgedTypeAttrKind_pack_guaranteed, -+ BridgedTypeAttrKind_pack_inout, -+ BridgedTypeAttrKind_pack_out, -+ BridgedTypeAttrKind_owned, -+ BridgedTypeAttrKind_unowned_inner_pointer, -+ BridgedTypeAttrKind_guaranteed, -+ BridgedTypeAttrKind_autoreleased, -+ BridgedTypeAttrKind_callee_owned, -+ BridgedTypeAttrKind_callee_guaranteed, -+ BridgedTypeAttrKind_objc_metatype, -+ BridgedTypeAttrKind_opened, -+ BridgedTypeAttrKind_pack_element, -+ BridgedTypeAttrKind_pseudogeneric, -+ BridgedTypeAttrKind_yields, -+ BridgedTypeAttrKind_yield_once, -+ BridgedTypeAttrKind_yield_many, -+ BridgedTypeAttrKind_captures_generics, -+ BridgedTypeAttrKind_moveOnly, -+ BridgedTypeAttrKind_thin, -+ BridgedTypeAttrKind_thick, -+ BridgedTypeAttrKind_Count -+} BridgedTypeAttrKind; -+ - #ifdef __cplusplus - extern "C" { - -@@ -261,6 +325,19 @@ void *ImplicitlyUnwrappedOptionalTypeRepr_create(void *ctx, void *base, - void *exclamationLoc); - void *MetatypeTypeRepr_create(void *ctx, void *baseType, void *typeLoc); - void *ProtocolTypeRepr_create(void *ctx, void *baseType, void *protoLoc); -+ -+BridgedTypeAttrKind getBridgedTypeAttrKindFromString( -+ const unsigned char * _Nullable str, long len); -+ -+typedef void *BridgedTypeAttributes; -+BridgedTypeAttributes BridgedTypeAttributes_create(void); -+void BridgedTypeAttributes_addSimpleAttr( -+ BridgedTypeAttributes typeAttributes, BridgedTypeAttrKind kind, void *atLoc, void *attrLoc); -+void *AttributedTypeRepr_create(void *ctx, void *base, BridgedTypeAttributes typeAttributes); -+ -+void *AttributedTypeSpecifierRepr_create( -+ void *ctx, void *base, BridgedAttributedTypeSpecifier specifier, void *specifierLoc); -+void *VarargTypeRepr_create(void *ctx, void *base, void *ellipsisLocPtr); - void *PackExpansionTypeRepr_create(void *ctx, void *base, void *repeatLoc); - void *TupleTypeRepr_create(void *ctx, BridgedArrayRef elements, void *lParenLoc, - void *rParenLoc); -@@ -269,8 +346,9 @@ void *MemberTypeRepr_create(void *ctx, void *baseComponent, - void *GenericIdentTypeRepr_create(void *ctx, BridgedIdentifier name, - void *nameLoc, BridgedArrayRef genericArgs, - void *lAngle, void *rAngle); -+void *EmptyCompositionTypeRepr_create(void *ctx, void *anyLoc); - void *CompositionTypeRepr_create(void *ctx, BridgedArrayRef types, -- void *firstTypeLoc); -+ void *firstTypeLoc, void *firstAmpLoc); - void *FunctionTypeRepr_create(void *ctx, void *argsTy, void *_Nullable asyncLoc, - void *_Nullable throwsLoc, void *arrowLoc, - void *returnType); -diff --git a/swift/include/swift/Basic/Features.def b/swift/include/swift/Basic/Features.def -index d3b6ed2519f..d0884deafe4 100644 ---- a/swift/include/swift/Basic/Features.def -+++ b/swift/include/swift/Basic/Features.def -@@ -184,6 +184,10 @@ EXPERIMENTAL_FEATURE(ImplicitSome, false) - /// corresponding syntax tree. - EXPERIMENTAL_FEATURE(ParserASTGen, false) - -+/// Use the syntax tree produced by the Swift (swift-syntax) parser for type -+/// parsing, using ASTGen to translate them into AST nodes. -+EXPERIMENTAL_FEATURE(ASTGenTypes, false) -+ - /// Parse using the Swift (swift-syntax) parser and use ASTGen to generate the - /// corresponding syntax tree. - EXPERIMENTAL_FEATURE(BuiltinMacros, false) -diff --git a/swift/include/swift/Parse/Parser.h b/swift/include/swift/Parse/Parser.h -index a1ac3666776..2ba8c645833 100644 ---- a/swift/include/swift/Parse/Parser.h -+++ b/swift/include/swift/Parse/Parser.h -@@ -24,6 +24,7 @@ - #include "swift/AST/LayoutConstraint.h" - #include "swift/AST/ParseRequests.h" - #include "swift/AST/Pattern.h" -+#include "swift/AST/SourceFile.h" - #include "swift/AST/Stmt.h" - #include "swift/Basic/OptionSet.h" - #include "swift/Config.h" -@@ -1343,6 +1344,50 @@ public: - /// Get the location for a type error. - SourceLoc getTypeErrorLoc() const; - -+ /// Callback function used for creating a C++ AST from the syntax node at the given source location. -+ /// -+ /// The arguments to this callback are the source file to pass into ASTGen (the exported source file) -+ /// and the source location pointer to pass into ASTGen (to find the syntax node). -+ /// -+ /// The callback returns the new AST node and the ending location of the syntax node. If the AST node -+ /// is NULL, something went wrong. -+ template -+ using ASTFromSyntaxTreeCallback = std::pair( -+ void *sourceFile, const void *sourceLoc -+ ); -+ -+ /// Parse by constructing a C++ AST node from the Swift syntax tree via ASTGen. -+ template -+ ParserResult parseASTFromSyntaxTree( -+ llvm::function_ref> body -+ ) { -+ if (!Context.LangOpts.hasFeature(Feature::ASTGenTypes)) -+ return nullptr; -+ -+ auto exportedSourceFile = SF.getExportedSourceFile(); -+ if (!exportedSourceFile) -+ return nullptr; -+ -+ // Perform the translation. -+ auto sourceLoc = Tok.getLoc().getOpaquePointerValue(); -+ T* astNode; -+ const void *endLocPtr; -+ std::tie(astNode, endLocPtr) = body(exportedSourceFile, sourceLoc); -+ -+ if (!astNode) { -+ assert(false && "Could not build AST node from syntax tree"); -+ return nullptr; -+ } -+ -+ // Reset the lexer to the ending location. -+ StringRef contents = -+ SourceMgr.extractText(SourceMgr.getRangeForBuffer(L->getBufferID())); -+ L->resetToOffset((const char *)endLocPtr - contents.data()); -+ L->lex(Tok); -+ -+ return makeParserResult(astNode); -+ } -+ - //===--------------------------------------------------------------------===// - // Type Parsing - -diff --git a/swift/lib/AST/ASTPrinter.cpp b/swift/lib/AST/ASTPrinter.cpp -index 7f24711916c..474e62aa8dc 100644 ---- a/swift/lib/AST/ASTPrinter.cpp -+++ b/swift/lib/AST/ASTPrinter.cpp -@@ -3364,6 +3364,10 @@ static bool usesFeatureParserASTGen(Decl *decl) { - return false; - } - -+static bool usesFeatureASTGenTypes(Decl *decl) { -+ return false; -+} -+ - static bool usesFeatureBuiltinMacros(Decl *decl) { - return false; - } -diff --git a/swift/lib/AST/CASTBridging.cpp b/swift/lib/AST/CASTBridging.cpp -index 5b935d4cebb..2f7c14fd1a2 100644 ---- a/swift/lib/AST/CASTBridging.cpp -+++ b/swift/lib/AST/CASTBridging.cpp -@@ -119,6 +119,15 @@ void SwiftDiagnostic_finish(BridgedDiagnostic diagPtr) { - BridgedIdentifier - SwiftASTContext_getIdentifier(void *ctx, const unsigned char *_Nullable str, - SwiftInt len) { -+ if (len == 1 && str[0] == '_') -+ return BridgedIdentifier(); -+ -+ // If this was a back-ticked identifier, drop the back-ticks. -+ if (len >= 2 && str[0] == '`' && str[len-1] == '`') { -+ ++str; -+ len -= 2; -+ } -+ - return const_cast( - static_cast(ctx) - ->getIdentifier( -@@ -484,6 +493,87 @@ void *PackExpansionTypeRepr_create(void *ctx, void *base, void *repeatLoc) { - getSourceLocFromPointer(repeatLoc), (TypeRepr *)base); - } - -+static BridgedTypeAttrKind bridgeTypeAttrKind(TypeAttrKind kind) { -+ switch (kind) { -+#define TYPE_ATTR(X) case TAK_##X: return BridgedTypeAttrKind_##X; -+#include "swift/AST/Attr.def" -+ case TAK_Count: return BridgedTypeAttrKind_Count; -+ } -+} -+ -+static TypeAttrKind bridgeTypeAttrKind(BridgedTypeAttrKind kind) { -+ switch (kind) { -+#define TYPE_ATTR(X) case BridgedTypeAttrKind_##X: return TAK_##X; -+#include "swift/AST/Attr.def" -+ case BridgedTypeAttrKind_Count: return TAK_Count; -+ } -+} -+ -+BridgedTypeAttrKind getBridgedTypeAttrKindFromString( -+ const unsigned char *str, intptr_t len) { -+ return bridgeTypeAttrKind( -+ TypeAttributes::getAttrKindFromString(StringRef((const char *)str, len))); -+} -+ -+BridgedTypeAttributes BridgedTypeAttributes_create() { -+ return new TypeAttributes(); -+} -+ -+void BridgedTypeAttributes_addSimpleAttr( -+ BridgedTypeAttributes typeAttributesPtr, BridgedTypeAttrKind kind, -+ void *atLoc, void *attrLoc -+) { -+ TypeAttributes *typeAttributes = (TypeAttributes *)typeAttributesPtr; -+ typeAttributes->setAttr( -+ bridgeTypeAttrKind(kind), getSourceLocFromPointer(attrLoc)); -+ if (typeAttributes->AtLoc.isInvalid()) -+ typeAttributes->AtLoc = getSourceLocFromPointer(atLoc); -+} -+ -+void *AttributedTypeRepr_create( -+ void *ctx, void *base, BridgedTypeAttributes typeAttributesPtr) { -+ TypeAttributes *typeAttributes = (TypeAttributes *)typeAttributesPtr; -+ if (typeAttributes->empty()) -+ return base; -+ -+ ASTContext &Context = *static_cast(ctx); -+ auto attributedType = -+ new (Context) AttributedTypeRepr(*typeAttributes, (TypeRepr *)base); -+ delete typeAttributes; -+ return attributedType; -+} -+ -+void *AttributedTypeSpecifierRepr_create( -+ void *ctx, void *base, BridgedAttributedTypeSpecifier specifier, void *specifierLoc -+) { -+ ASTContext &Context = *static_cast(ctx); -+ SourceLoc loc = getSourceLocFromPointer(specifierLoc); -+ TypeRepr *baseType = (TypeRepr *)base; -+ switch (specifier) { -+ case BridgedAttributedTypeSpecifierInOut: -+ return new (Context) OwnershipTypeRepr(baseType, ParamSpecifier::InOut, loc); -+ case BridgedAttributedTypeSpecifierBorrowing: -+ return new (Context) OwnershipTypeRepr(baseType, ParamSpecifier::Borrowing, loc); -+ case BridgedAttributedTypeSpecifierConsuming: -+ return new (Context) OwnershipTypeRepr(baseType, ParamSpecifier::Consuming, loc); -+ case BridgedAttributedTypeSpecifierLegacyShared: -+ return new (Context) OwnershipTypeRepr(baseType, ParamSpecifier::LegacyShared, loc); -+ case BridgedAttributedTypeSpecifierLegacyOwned: -+ return new (Context) OwnershipTypeRepr(baseType, ParamSpecifier::LegacyOwned, loc); -+ case BridgedAttributedTypeSpecifierConst: -+ return new (Context) CompileTimeConstTypeRepr(baseType, loc); -+ case BridgedAttributedTypeSpecifierIsolated: -+ return new (Context) IsolatedTypeRepr(baseType, loc); -+ } -+} -+ -+void *VarargTypeRepr_create(void *ctx, void *base, void *ellipsisLocPtr) { -+ ASTContext &Context = *static_cast(ctx); -+ SourceLoc ellipsisLoc = getSourceLocFromPointer(ellipsisLocPtr); -+ TypeRepr *baseType = (TypeRepr *)base; -+ return new (Context) VarargTypeRepr(baseType, ellipsisLoc); -+} -+ - void *TupleTypeRepr_create(void *ctx, BridgedArrayRef elements, void *lParenLoc, - void *rParenLoc) { - ASTContext &Context = *static_cast(ctx); -@@ -518,12 +608,21 @@ void *MemberTypeRepr_create(void *ctx, void *baseComponent, - memberComponents); - } - --void *CompositionTypeRepr_create(void *ctx, BridgedArrayRef types, -- void *firstTypeLoc) { -+void *EmptyCompositionTypeRepr_create(void *ctx, void *anyLocPtr) { -+ ASTContext &Context = *static_cast(ctx); -+ SourceLoc anyLoc = getSourceLocFromPointer(anyLocPtr); -+ return CompositionTypeRepr::createEmptyComposition(Context, anyLoc); -+} -+ -+void *CompositionTypeRepr_create(void *ctx, BridgedArrayRef typesPtr, -+ void *firstTypeLoc, void *firstAmpLocPtr) { - ASTContext &Context = *static_cast(ctx); - SourceLoc firstType = getSourceLocFromPointer(firstTypeLoc); -- return CompositionTypeRepr::create(Context, getArrayRef(types), -- firstType, SourceRange{}); -+ SourceLoc firstAmpLoc = getSourceLocFromPointer(firstAmpLocPtr); -+ auto types = getArrayRef(typesPtr); -+ return CompositionTypeRepr::create( -+ Context, types, firstType, -+ SourceRange{firstAmpLoc, types.back()->getEndLoc()}); - } - - void *FunctionTypeRepr_create(void *ctx, void *argsTy, void *_Nullable asyncLoc, -diff --git a/swift/lib/ASTGen/Sources/ASTGen/Macros.swift b/swift/lib/ASTGen/Sources/ASTGen/Macros.swift -index 4ee025884bd..81e355f475d 100644 ---- a/swift/lib/ASTGen/Sources/ASTGen/Macros.swift -+++ b/swift/lib/ASTGen/Sources/ASTGen/Macros.swift -@@ -627,10 +627,11 @@ func expandFreestandingMacroInProcess( - } - - /// Retrieve a syntax node in the given source file, with the given type. --private func findSyntaxNodeInSourceFile( -+func findSyntaxNodeInSourceFile( - sourceFilePtr: UnsafeRawPointer, - sourceLocationPtr: UnsafePointer?, -- type: Node.Type -+ type: Node.Type, -+ wantOutermost: Bool = false - ) -> Node? { - guard let sourceLocationPtr = sourceLocationPtr else { - return nil -@@ -656,16 +657,45 @@ private func findSyntaxNodeInSourceFile( - } - - var currentSyntax = Syntax(token) -+ var resultSyntax: Node? = nil - while let parentSyntax = currentSyntax.parent { - if let typedParent = parentSyntax.as(type) { -- return typedParent -+ resultSyntax = typedParent -+ break - } - - currentSyntax = parentSyntax - } - -- print("unable to find node: \(token.debugDescription)") -- return nil -+ // If we didn't find anything, complain and fail. -+ guard var resultSyntax else { -+ print("unable to find node: \(token.debugDescription)") -+ return nil -+ } -+ -+ // If we want the outermost node, keep looking. -+ // FIXME: This is VERY SPECIFIC to handling of types. We must be able to -+ // do better. -+ if wantOutermost { -+ while let parentSyntax = resultSyntax.parent { -+ // Look through type compositions. -+ if let compositionElement = parentSyntax.as(CompositionTypeElementSyntax.self), -+ let compositionList = compositionElement.parent?.as(CompositionTypeElementListSyntax.self), -+ let typedParent = compositionList.parent?.as(type) { -+ resultSyntax = typedParent -+ continue -+ } -+ -+ guard let typedParent = parentSyntax.as(type), -+ typedParent.position == resultSyntax.position else { -+ break -+ } -+ -+ resultSyntax = typedParent -+ } -+ } -+ -+ return resultSyntax - } - - @_cdecl("swift_ASTGen_expandAttachedMacro") -diff --git a/swift/lib/ASTGen/Sources/ASTGen/Types.swift b/swift/lib/ASTGen/Sources/ASTGen/Types.swift -index eb2be48a8a8..82bbca53bf4 100644 ---- a/swift/lib/ASTGen/Sources/ASTGen/Types.swift -+++ b/swift/lib/ASTGen/Sources/ASTGen/Types.swift -@@ -6,6 +6,11 @@ extension ASTGenVisitor { - public func visit(_ node: SimpleTypeIdentifierSyntax) -> ASTNode { - let loc = self.base.advanced(by: node.position.utf8Offset).raw - -+ // If this is the bare 'Any' keyword, produce an empty composition type. -+ if node.name.tokenKind == .keyword(.Any) && node.genericArgumentClause == nil { -+ return .type(EmptyCompositionTypeRepr_create(self.ctx, loc)) -+ } -+ - var text = node.name.text - let id = text.withUTF8 { buf in - return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, SwiftInt(buf.count)) -@@ -19,7 +24,7 @@ extension ASTGenVisitor { - let rAngle = self.base.advanced(by: generics.rightAngleBracket.position.utf8Offset).raw - return .type( - generics.arguments.map({ -- self.visit($0.argumentType) -+ self.visit($0.argumentType).rawValue - }).withBridgedArrayRef { - genericArgs in - GenericIdentTypeRepr_create( -@@ -46,7 +51,7 @@ extension ASTGenVisitor { - let lAngle = self.base.advanced(by: generics.leftAngleBracket.position.utf8Offset).raw - let rAngle = self.base.advanced(by: generics.rightAngleBracket.position.utf8Offset).raw - reverseMemberComponents.append( -- generics.arguments.map({ self.visit($0.argumentType) }).withBridgedArrayRef { -+ generics.arguments.map({ self.visit($0.argumentType).rawValue }).withBridgedArrayRef { - genericArgs in - GenericIdentTypeRepr_create(self.ctx, name, nameLoc, genericArgs, lAngle, rAngle) - }) -@@ -123,9 +128,11 @@ extension ASTGenVisitor { - assert(node.elements.count > 1) - let types = node.elements.map { visit($0.type) }.map { $0.rawValue } - let firstTypeLoc = self.base.advanced(by: node.elements.first!.type.position.utf8Offset).raw -+ let firstAmpOffset = node.elements.first?.ampersand.map { $0.position.utf8Offset } ?? 0 -+ let firstAmpLoc = self.base.advanced(by: firstAmpOffset).raw - return .type( - types.withBridgedArrayRef { types in -- return CompositionTypeRepr_create(self.ctx, types, firstTypeLoc) -+ return CompositionTypeRepr_create(self.ctx, types, firstTypeLoc, firstAmpLoc) - }) - } - -@@ -161,8 +168,77 @@ extension ASTGenVisitor { - } - - public func visit(_ node: AttributedTypeSyntax) -> ASTNode { -- // FIXME: Respect the attributes -- return visit(node.baseType) -+ var type = visit(node.baseType) -+ -+ // Handle specifiers. -+ if let specifier = node.specifier { -+ let specifierLoc = self.base.advanced(by: specifier.position.utf8Offset).raw -+ -+ let kind: BridgedAttributedTypeSpecifier -+ switch specifier.tokenKind { -+ case .keyword(.inout): kind = .inOut -+ case .keyword(.borrowing): kind = .borrowing -+ case .keyword(.consuming): kind = .consuming -+ case .keyword(.__shared): kind = .legacyShared -+ case .keyword(.__owned): kind = .legacyOwned -+ case .keyword(._const): kind = .const -+ case .keyword(.isolated): kind = .isolated -+ default: fatalError("unhandled specifier \(specifier.debugDescription)") -+ } -+ -+ type = .type(AttributedTypeSpecifierRepr_create(self.ctx, type.rawValue, kind, specifierLoc)) -+ } -+ -+ // Handle type attributes. -+ if let attributes = node.attributes { -+ let typeAttributes = BridgedTypeAttributes_create() -+ for attributeElt in attributes { -+ // FIXME: Ignoring #ifs entirely. We want to provide a filtered view, -+ // but we don't have that ability right now. -+ guard case let .attribute(attribute) = attributeElt else { -+ continue -+ } -+ -+ // Only handle simple attribute names right now. -+ guard let identType = attribute.attributeName.as(SimpleTypeIdentifierSyntax.self) else { -+ continue -+ } -+ -+ let nameSyntax = identType.name -+ var name = nameSyntax.text -+ let typeAttrKind = name.withUTF8 { buf in -+ getBridgedTypeAttrKindFromString(buf.baseAddress, buf.count) -+ } -+ let atLoc = self.base.advanced(by: attribute.atSignToken.position.utf8Offset).raw -+ let attrLoc = self.base.advanced(by: nameSyntax.position.utf8Offset).raw -+ switch typeAttrKind { -+ // SIL attributes -+ // FIXME: Diagnose if not in SIL mode? Or should that move to the -+ // type checker? -+ case .out, .in, .owned, .unowned_inner_pointer, .guaranteed, -+ .autoreleased, .callee_owned, .callee_guaranteed, .objc_metatype, -+ .sil_weak, .sil_unowned, .inout, .block_storage, .box, -+ .dynamic_self, .sil_unmanaged, .error, .direct, .inout_aliasable, -+ .in_guaranteed, .in_constant, .captures_generics, .moveOnly: -+ fallthrough -+ -+ case .autoclosure, .escaping, .noescape, .noDerivative, .async, -+ .sendable, .unchecked, ._local, ._noMetadata, .pack_owned, -+ .pack_guaranteed, .pack_inout, .pack_out, .pseudogeneric, -+ .yields, .yield_once, .yield_many, .thin, .thick, .count: -+ BridgedTypeAttributes_addSimpleAttr(typeAttributes, typeAttrKind, atLoc, attrLoc) -+ -+ case .opened, .pack_element, .differentiable, .convention, -+ ._opaqueReturnTypeOf: -+ // FIXME: These require more complicated checks -+ break -+ } -+ } -+ -+ type = .type(AttributedTypeRepr_create(self.ctx, type.rawValue, typeAttributes)) -+ } -+ -+ return type - } - } - -@@ -186,7 +262,13 @@ extension ASTGenVisitor { - self.base.advanced(by: $0.position.utf8Offset).raw - } - let colonLoc = element.colon.map { self.base.advanced(by: $0.position.utf8Offset).raw } -- let type = visit(element.type).rawValue -+ -+ var type = visit(element.type).rawValue -+ if let ellipsis = element.ellipsis { -+ let ellipsisLoc = self.base.advanced(by: ellipsis.positionAfterSkippingLeadingTrivia.utf8Offset).raw -+ type = VarargTypeRepr_create(self.ctx, type, ellipsisLoc) -+ } -+ - let trailingCommaLoc = element.trailingComma.map { - self.base.advanced(by: $0.position.utf8Offset).raw - } -@@ -207,3 +289,37 @@ extension ASTGenVisitor { - } - } - } -+ -+@_cdecl("swift_ASTGen_buildTypeRepr") -+@usableFromInline -+func buildTypeRepr( -+ sourceFilePtr: UnsafeRawPointer, -+ typeLocPtr: UnsafePointer, -+ dc: UnsafeMutableRawPointer, -+ ctx: UnsafeMutableRawPointer, -+ endTypeLocPtr: UnsafeMutablePointer?> -+) -> UnsafeMutableRawPointer? { -+ let sourceFile = sourceFilePtr.bindMemory( -+ to: ExportedSourceFile.self, capacity: 1 -+ ) -+ -+ // Find the type syntax node. -+ guard let typeSyntax = findSyntaxNodeInSourceFile( -+ sourceFilePtr: sourceFilePtr, -+ sourceLocationPtr: typeLocPtr, -+ type: TypeSyntax.self, -+ wantOutermost: true -+ ) else { -+ // FIXME: Produce an error -+ return nil -+ } -+ -+ // Fill in the end location. -+ endTypeLocPtr.pointee = sourceFile.pointee.buffer.baseAddress!.advanced(by: typeSyntax.endPosition.utf8Offset) -+ -+ // Convert the type syntax node. -+ let typeReprNode = ASTGenVisitor(ctx: ctx, base: sourceFile.pointee.buffer.baseAddress!, declContext: dc) -+ .visit(typeSyntax) -+ -+ return typeReprNode.rawValue -+} -diff --git a/swift/lib/Parse/ParseType.cpp b/swift/lib/Parse/ParseType.cpp -index 98a1cb0a4fc..97c88da9bbd 100644 ---- a/swift/lib/Parse/ParseType.cpp -+++ b/swift/lib/Parse/ParseType.cpp -@@ -582,6 +582,14 @@ ParserResult Parser::parseTypeScalar( - constLoc)); - } - -+/// Build a TypeRepr for AST node for the type at the given source location in the specified file. -+/// -+/// \param sourceLoc The source location at which to start processing a type. -+/// \param endSourceLoc Will receive the source location immediately following the type. -+extern "C" TypeRepr *swift_ASTGen_buildTypeRepr( -+ void *sourceFile, const void *_Nullable sourceLoc, -+ void *declContext, void *astContext, const void *_Nullable *endSourceLoc); -+ - /// parseType - /// type: - /// type-scalar -@@ -592,6 +600,32 @@ ParserResult Parser::parseTypeScalar( - /// - ParserResult Parser::parseType( - Diag<> MessageID, ParseTypeReason reason) { -+ #if SWIFT_SWIFT_PARSER -+ auto astGenResult = parseASTFromSyntaxTree( -+ [&](void *exportedSourceFile, const void *sourceLoc) { -+ const void *endLocPtr = nullptr; -+ TypeRepr *typeRepr = swift_ASTGen_buildTypeRepr( -+ exportedSourceFile, Tok.getLoc().getOpaquePointerValue(), -+ CurDeclContext, &Context, &endLocPtr); -+ return std::make_pair(typeRepr, endLocPtr); -+ }); -+ if (astGenResult.isNonNull()) { -+ // Note: there is a representational difference between the swift-syntax -+ // tree and the C++ parser tree regarding variadic parameters. In the -+ // swift-syntax tree, the ellipsis is part of the parameter declaration. -+ // In the C++ parser tree, the ellipsis is part of the type. Account for -+ // this difference by consuming the ellipsis here. -+ if (Tok.isEllipsis()) { -+ Tok.setKind(tok::ellipsis); -+ SourceLoc ellipsisLoc = consumeToken(); -+ return makeParserResult(astGenResult, -+ new (Context) VarargTypeRepr(astGenResult.get(), ellipsisLoc)); -+ } -+ -+ return astGenResult; -+ } -+ #endif -+ - // Parse pack expansion 'repeat T' - if (Tok.is(tok::kw_repeat)) { - SourceLoc repeatLoc = consumeToken(tok::kw_repeat); -diff --git a/swift/test/ASTGen/types.swift b/swift/test/ASTGen/types.swift -new file mode 100644 -index 00000000000..f6eddfe1ed6 ---- /dev/null -+++ b/swift/test/ASTGen/types.swift -@@ -0,0 +1,41 @@ -+// RUN: %target-typecheck-verify-swift -enable-experimental-feature ASTGenTypes -+ -+// -enable-experimental-feature requires an asserts build -+// REQUIRES: asserts -+ -+protocol P { } -+protocol Q { } -+typealias PQ = P & Q -+ -+func test7(_ b: inout Bool) { -+ b = true -+} -+ -+struct X { struct `Protocol` { } } -+ -+func test10(_: X.`Protocol`) { } -+ -+func test11(_: Int...) { } -+func test11a() { -+ test11(1, 2, 3, 4, 5) -+} -+ -+typealias VAFunc = (Int, Int...) -> Int -+func testVAFunc(a: Int, f: VAFunc) { -+ _ = f(a, a, a, a, a) -+} -+ -+func test12(_ producer: @escaping @autoclosure () -> Int) { -+ _ = producer() -+} -+func test12a(i: Int) { -+ test12(i) -+} -+ -+func test13(body: (_ value: Int) -> Void, i: Int) { -+ body(i) -+} -+ -+func test14() { -+ _ = Array>>().count -+} -diff --git a/swift/test/ASTGen/verify-parse.swift b/swift/test/ASTGen/verify-parse.swift -index ec5004eb129..9bdc36cb4f0 100644 ---- a/swift/test/ASTGen/verify-parse.swift -+++ b/swift/test/ASTGen/verify-parse.swift -@@ -1,8 +1,9 @@ - // RUN: %target-run-simple-swift(-enable-experimental-feature SwiftParser -enable-experimental-feature ParserASTGen) -+// RUN: %target-run-simple-swift(-enable-experimental-feature ASTGenTypes) - - // REQUIRES: executable_test - --// -enable-experimental-feature requires and asserts build -+// -enable-experimental-feature requires an asserts build - // REQUIRES: asserts - - func test1(x: Int, fn: (Int) -> Int) -> Int { -@@ -25,11 +26,11 @@ func test3(y: Int) -> Int { - return x - } - --func test4(_ b: Bool) -> Int { -- if b { 0 } else { 1 } -+func test4(_ b: [Bool]) -> Int { -+ if b.isEmpty { 0 } else { 1 } - } - --func test5(_ b: Bool) -> Int { -+func test5(_ b: Swift.Bool) -> Int { - return if b { 0 } else { 1 } - } - -@@ -37,3 +38,12 @@ func test6(_ b: Bool) -> Int { - let x = if b { 0 } else { 1 } - return x - } -+ -+func test7(_ b: inout Bool) { -+ // b = true -+} -+ -+func test8(_ i: _const Int) { -+} -+ -+func test9(_ value: Any) { } diff --git a/packages/swift/swift-modify-bridging.patch b/packages/swift/swift-modify-bridging.patch deleted file mode 100644 index 78bc3f2c1e..0000000000 --- a/packages/swift/swift-modify-bridging.patch +++ /dev/null @@ -1,2916 +0,0 @@ -From 18f56c9de54318fb0357c3ba4b3fba06e370bb85 -From: Ben Barham -Date: Sun, 21 May 2023 12:23:23 -0700 -Subject: [PATCH] [NFC][ASTGen] Add wrapping structs for commonly bridged types - -Adds wrapping structs for a bunch of commonly bridged types (but not all -the AST nodes yet). - -diff --git a/swift/include/swift/AST/CASTBridging.h b/swift/include/swift/AST/CASTBridging.h -index 9647ddf561f14..4f181c1d1f916 100644 ---- a/swift/include/swift/AST/CASTBridging.h -+++ b/swift/include/swift/AST/CASTBridging.h -@@ -42,27 +42,46 @@ SWIFT_BEGIN_NULLABILITY_ANNOTATIONS - - SWIFT_BEGIN_NULLABILITY_ANNOTATIONS - -+typedef struct { -+ const unsigned char *_Nullable data; -+ long length; -+} BridgedString; -+ - typedef struct { - const void *_Nullable data; - SwiftInt numElements; - } BridgedArrayRef; - -+typedef struct BridgedASTContext { -+ void *raw; -+} BridgedASTContext; -+ -+typedef struct BridgedDeclContext { -+ void *raw; -+} BridgedDeclContext; -+ -+typedef struct BridgedSourceLoc { -+ const void *_Nullable raw; -+} BridgedSourceLoc; -+ -+typedef struct BridgedIdentifier { -+ const void *_Nullable raw; -+} BridgedIdentifier; -+ - typedef struct { - void *start; - SwiftInt byteLength; - } BridgedCharSourceRange; - --typedef void *BridgedIdentifier; -- - typedef struct { -- BridgedIdentifier _Nullable Name; -- void *_Nullable NameLoc; -- BridgedIdentifier _Nullable SecondName; -- void *_Nullable SecondNameLoc; -- void *_Nullable UnderscoreLoc; -- void *_Nullable ColonLoc; -+ BridgedIdentifier Name; -+ BridgedSourceLoc NameLoc; -+ BridgedIdentifier SecondName; -+ BridgedSourceLoc SecondNameLoc; -+ BridgedSourceLoc UnderscoreLoc; -+ BridgedSourceLoc ColonLoc; - void *Type; -- void *_Nullable TrailingCommaLoc; -+ BridgedSourceLoc TrailingCommaLoc; - } BridgedTupleTypeElement; - - typedef enum ENUM_EXTENSIBILITY_ATTR(open) BridgedRequirementReprKind : SwiftInt { -@@ -84,7 +103,7 @@ typedef enum ENUM_EXTENSIBILITY_ATTR(open) BridgedRequirementReprKind : long { - } BridgedRequirementReprKind; - - typedef struct { -- void *_Nullable SeparatorLoc; -+ BridgedSourceLoc SeparatorLoc; - BridgedRequirementReprKind Kind; - void *FirstType; - void *SecondType; -@@ -100,7 +119,13 @@ typedef enum ENUM_EXTENSIBILITY_ATTR(open) BridgedDiagnosticSeverity : long { - BridgedNote, - } BridgedDiagnosticSeverity; - --typedef void* BridgedDiagnostic; -+typedef struct BridgedDiagnostic { -+ void *raw; -+} BridgedDiagnostic; -+ -+typedef struct BridgedDiagnosticEngine { -+ void *raw; -+} BridgedDiagnosticEngine; - - typedef enum ENUM_EXTENSIBILITY_ATTR(open) BridgedMacroDefinitionKind : SwiftInt { - /// An expanded macro. -@@ -176,11 +200,37 @@ typedef enum ENUM_EXTENSIBILITY_ATTR(closed) BridgedTypeAttrKind : long { - BridgedTypeAttrKind_Count - } BridgedTypeAttrKind; - -+typedef enum ENUM_EXTENSIBILITY_ATTR(open) ASTNodeKind : long { -+ ASTNodeKindExpr, -+ ASTNodeKindStmt, -+ ASTNodeKindDecl -+} ASTNodeKind; -+ -+typedef struct BridgedASTNode { -+ void *ptr; -+ ASTNodeKind kind; -+} BridgedASTNode; -+ -+typedef struct BridgedFuncDecl { -+ BridgedDeclContext declContext; -+ void *funcDecl; -+ void *decl; -+} BridgedFuncDecl; -+ -+typedef struct BridgedDeclContextAndDecl { -+ BridgedDeclContext declContext; -+ void *nominalDecl; -+ void *decl; -+} BridgedDeclContextAndDecl; -+ -+typedef struct BridgedTypeAttributes { -+ void *raw; -+} BridgedTypeAttributes; -+ - #ifdef __cplusplus - extern "C" { - - #define _Bool bool -- - #endif - - // Diagnostics -@@ -190,192 +240,212 @@ extern "C" { - /// - /// \returns a diagnostic instance that can be extended with additional - /// information and then must be finished via \c SwiftDiagnostic_finish. --BridgedDiagnostic SwiftDiagnostic_create(void *diagnosticEngine, -- BridgedDiagnosticSeverity severity, -- const void *_Nullable sourceLoc, -- const unsigned char *_Nullable text, -- SwiftInt textLen); -+BridgedDiagnostic Diagnostic_create(BridgedDiagnosticEngine cDiags, -+ BridgedDiagnosticSeverity severity, -+ BridgedSourceLoc cLoc, BridgedString cText); - - /// Highlight a source range as part of the diagnostic. --void SwiftDiagnostic_highlight( -- BridgedDiagnostic diag, const void *_Nullable startLoc, const void *_Nullable endLoc); -+void Diagnostic_highlight(BridgedDiagnostic cDiag, BridgedSourceLoc cStartLoc, -+ BridgedSourceLoc cEndLoc); - - /// Add a Fix-It to replace a source range as part of the diagnostic. --void SwiftDiagnostic_fixItReplace(BridgedDiagnostic diag, -- const void *_Nullable replaceStartLoc, -- const void *_Nullable replaceEndLoc, -- const unsigned char *_Nullable newText, -- SwiftInt newTextLen); -+void Diagnostic_fixItReplace(BridgedDiagnostic cDiag, -+ BridgedSourceLoc cStartLoc, -+ BridgedSourceLoc cEndLoc, -+ BridgedString cReplaceText); - - /// Finish the given diagnostic and emit it. --void SwiftDiagnostic_finish(BridgedDiagnostic diag); -+void Diagnostic_finish(BridgedDiagnostic cDiag); - --BridgedIdentifier --SwiftASTContext_getIdentifier(void *ctx, const unsigned char *_Nullable str, -- SwiftInt len); -+BridgedIdentifier ASTContext_getIdentifier(BridgedASTContext cContext, -+ BridgedString cStr); - --void *SwiftImportDecl_create(void *, void *, void *, char, void *, -- BridgedArrayRef, BridgedArrayRef); -+void *ImportDecl_create(BridgedASTContext cContext, -+ BridgedDeclContext cDeclContext, -+ BridgedSourceLoc cImportLoc, char kind, -+ BridgedSourceLoc cKindLoc, BridgedArrayRef path, -+ BridgedArrayRef cPathLocs); - --void *SwiftTopLevelCodeDecl_createStmt(void *ctx, void *DC, void *startLoc, -- void *element, void *endLoc); --void *SwiftTopLevelCodeDecl_createExpr(void *ctx, void *DC, void *startLoc, -- void *element, void *endLoc); -+void *TopLevelCodeDecl_createStmt(BridgedASTContext cContext, -+ BridgedDeclContext cDeclContext, -+ BridgedSourceLoc cStartLoc, void *element, -+ BridgedSourceLoc cEndLoc); -+void *TopLevelCodeDecl_createExpr(BridgedASTContext cContext, -+ BridgedDeclContext cDeclContext, -+ BridgedSourceLoc cStartLoc, void *element, -+ BridgedSourceLoc cEndLoc); - --void *ReturnStmt_create(void *ctx, void *loc, void *_Nullable expr); -+void *ReturnStmt_create(BridgedASTContext cContext, BridgedSourceLoc cLoc, -+ void *_Nullable expr); - --void *SwiftSequenceExpr_create(void *ctx, BridgedArrayRef exprs); -+void *SequenceExpr_create(BridgedASTContext cContext, BridgedArrayRef exprs); - --void *SwiftTupleExpr_create(void *ctx, void *lparen, BridgedArrayRef subs, -- BridgedArrayRef names, -- BridgedArrayRef nameLocs, -- void *rparen); -+void *TupleExpr_create(BridgedASTContext cContext, BridgedSourceLoc cLParen, -+ BridgedArrayRef subs, BridgedArrayRef names, -+ BridgedArrayRef cNameLocs, BridgedSourceLoc cRParen); - --void *SwiftFunctionCallExpr_create(void *ctx, void *fn, void *args); -+void *FunctionCallExpr_create(BridgedASTContext cContext, void *fn, void *args); - --void *SwiftIdentifierExpr_create(void *ctx, BridgedIdentifier base, void *loc); -+void *IdentifierExpr_create(BridgedASTContext cContext, BridgedIdentifier base, -+ BridgedSourceLoc cLoc); - --void *SwiftStringLiteralExpr_create(void *ctx, -- const unsigned char *_Nullable string, -- SwiftInt len, void *TokenLoc); -+void *StringLiteralExpr_create(BridgedASTContext cContext, BridgedString cStr, -+ BridgedSourceLoc cTokenLoc); - --void *SwiftIntegerLiteralExpr_create(void *ctx, -- const unsigned char *_Nullable string, -- SwiftInt len, void *TokenLoc); -+void *IntegerLiteralExpr_create(BridgedASTContext cContext, BridgedString cStr, -+ BridgedSourceLoc cTokenLoc); - --void *SwiftBooleanLiteralExpr_create(void *ctx, _Bool value, void *TokenLoc); -+void *BooleanLiteralExpr_create(BridgedASTContext cContext, _Bool value, -+ BridgedSourceLoc cTokenLoc); - --void *ArrayExpr_create(void *ctx, void *lLoc, BridgedArrayRef elements, -- BridgedArrayRef commas, void *rLoc); -+void *ArrayExpr_create(BridgedASTContext cContext, BridgedSourceLoc cLLoc, -+ BridgedArrayRef elements, BridgedArrayRef commas, -+ BridgedSourceLoc cRLoc); - --void *SwiftVarDecl_create(void *ctx, BridgedIdentifier _Nullable name, -- void *initExpr, void *loc, _Bool isStatic, -- _Bool isLet, void *dc); -+void *VarDecl_create(BridgedASTContext cContext, void *nameExpr, void *initExpr, -+ BridgedSourceLoc cLoc, _Bool isStatic, _Bool isLet, -+ BridgedDeclContext cDeclContext); - --void *SingleValueStmtExpr_createWithWrappedBranches(void *ctx, void *S, -- void *DC, _Bool mustBeExpr); -+void *SingleValueStmtExpr_createWithWrappedBranches( -+ BridgedASTContext cContext, void *S, BridgedDeclContext cDeclContext, -+ _Bool mustBeExpr); - --void *IfStmt_create(void *ctx, void *ifLoc, void *cond, void *_Nullable then, -- void *_Nullable elseLoc, void *_Nullable elseStmt); -- --typedef enum ENUM_EXTENSIBILITY_ATTR(open) ASTNodeKind : SwiftInt { -- ASTNodeKindExpr, -- ASTNodeKindStmt, -- ASTNodeKindDecl --} ASTNodeKind; -+void *IfStmt_create(BridgedASTContext cContext, BridgedSourceLoc cIfLoc, -+ void *cond, void *_Nullable then, BridgedSourceLoc cElseLoc, -+ void *_Nullable elseStmt); - --struct ASTNodeBridged { -- void *ptr; -- ASTNodeKind kind; --}; -+void *BraceStmt_create(BridgedASTContext cContext, BridgedSourceLoc cLBLoc, -+ BridgedArrayRef elements, BridgedSourceLoc cRBLoc); - --void *BraceStmt_create(void *ctx, void *lbloc, BridgedArrayRef elements, -- void *rbloc); -+BridgedSourceLoc SourceLoc_advanced(BridgedSourceLoc cLoc, long len); - --void *BridgedSourceLoc_advanced(void *loc, SwiftInt len); -+void *ParamDecl_create(BridgedASTContext cContext, BridgedSourceLoc cLoc, -+ BridgedSourceLoc cArgLoc, BridgedIdentifier argName, -+ BridgedSourceLoc cParamLoc, BridgedIdentifier paramName, -+ void *_Nullable type, BridgedDeclContext cDeclContext); - --void *ParamDecl_create(void *ctx, void *loc, void *_Nullable argLoc, -- void *_Nullable argName, void *_Nullable paramLoc, -- void *_Nullable paramName, void *_Nullable type, -- void *declContext); --struct FuncDeclBridged { -- void *declContext; -- void *funcDecl; -- void *decl; --}; -- --struct FuncDeclBridged --FuncDecl_create(void *ctx, void *staticLoc, _Bool isStatic, void *funcLoc, -- BridgedIdentifier name, void *nameLoc, _Bool isAsync, -- void *_Nullable asyncLoc, _Bool throws, -- void *_Nullable throwsLoc, void *paramLLoc, -- BridgedArrayRef params, void *paramRLoc, -- void *_Nullable returnType, void *declContext); -+struct BridgedFuncDecl -+FuncDecl_create(BridgedASTContext cContext, BridgedSourceLoc cStaticLoc, -+ _Bool isStatic, BridgedSourceLoc cFuncLoc, -+ BridgedIdentifier name, BridgedSourceLoc cNameLoc, -+ _Bool isAsync, BridgedSourceLoc cAsyncLoc, _Bool throws, -+ BridgedSourceLoc cThrowsLoc, BridgedSourceLoc cParamLLoc, -+ BridgedArrayRef params, BridgedSourceLoc cParamRLoc, -+ void *_Nullable returnType, BridgedDeclContext cDeclContext); - void FuncDecl_setBody(void *fn, void *body); - --void *SimpleIdentTypeRepr_create(void *ctx, void *loc, BridgedIdentifier id); -+void *SimpleIdentTypeRepr_create(BridgedASTContext cContext, -+ BridgedSourceLoc cLoc, BridgedIdentifier id); - --void *UnresolvedDotExpr_create(void *ctx, void *base, void *dotLoc, -- BridgedIdentifier name, void *nameLoc); -+void *UnresolvedDotExpr_create(BridgedASTContext cContext, void *base, -+ BridgedSourceLoc cDotLoc, BridgedIdentifier name, -+ BridgedSourceLoc cNameLoc); - --void *ClosureExpr_create(void *ctx, void *body, void *dc); -+void *ClosureExpr_create(BridgedASTContext cContext, void *body, -+ BridgedDeclContext cDeclContext); - - void NominalTypeDecl_setMembers(void *decl, BridgedArrayRef members); - --struct DeclContextAndDecl { -- void *declContext; -- void *nominalDecl; -- void *decl; --}; -- --struct DeclContextAndDecl --StructDecl_create(void *ctx, void *loc, BridgedIdentifier name, void *nameLoc, -- void *_Nullable genericParams, void *dc); --struct DeclContextAndDecl ClassDecl_create(void *ctx, void *loc, -+BridgedDeclContextAndDecl StructDecl_create(BridgedASTContext cContext, -+ BridgedSourceLoc cLoc, -+ BridgedIdentifier name, -+ BridgedSourceLoc cNameLoc, -+ void *_Nullable genericParams, -+ BridgedDeclContext cDeclContext); -+BridgedDeclContextAndDecl ClassDecl_create(BridgedASTContext cContext, -+ BridgedSourceLoc cLoc, - BridgedIdentifier name, -- void *nameLoc, void *dc); -- --void *ArrayTypeRepr_create(void *ctx, void *base, void *lsquareLoc, -- void *rsquareLoc); --void *DictionaryTypeRepr_create(void *ctx, void *keyType, void *valueType, -- void *lsquareLoc, void *colonloc, -- void *rsquareLoc); --void *OptionalTypeRepr_create(void *ctx, void *base, void *questionLoc); --void *ImplicitlyUnwrappedOptionalTypeRepr_create(void *ctx, void *base, -- void *exclamationLoc); --void *MetatypeTypeRepr_create(void *ctx, void *baseType, void *typeLoc); --void *ProtocolTypeRepr_create(void *ctx, void *baseType, void *protoLoc); -- --BridgedTypeAttrKind getBridgedTypeAttrKindFromString( -- const unsigned char * _Nullable str, long len); -- --typedef void *BridgedTypeAttributes; --BridgedTypeAttributes BridgedTypeAttributes_create(void); --void BridgedTypeAttributes_addSimpleAttr( -- BridgedTypeAttributes typeAttributes, BridgedTypeAttrKind kind, void *atLoc, void *attrLoc); --void *AttributedTypeRepr_create(void *ctx, void *base, BridgedTypeAttributes typeAttributes); -- --void *AttributedTypeSpecifierRepr_create( -- void *ctx, void *base, BridgedAttributedTypeSpecifier specifier, void *specifierLoc); --void *VarargTypeRepr_create(void *ctx, void *base, void *ellipsisLocPtr); --void *PackExpansionTypeRepr_create(void *ctx, void *base, void *repeatLoc); --void *TupleTypeRepr_create(void *ctx, BridgedArrayRef elements, void *lParenLoc, -- void *rParenLoc); --void *MemberTypeRepr_create(void *ctx, void *baseComponent, -- BridgedArrayRef bridgedMemberComponents); --void *GenericIdentTypeRepr_create(void *ctx, BridgedIdentifier name, -- void *nameLoc, BridgedArrayRef genericArgs, -- void *lAngle, void *rAngle); --void *EmptyCompositionTypeRepr_create(void *ctx, void *anyLoc); --void *CompositionTypeRepr_create(void *ctx, BridgedArrayRef types, -- void *firstTypeLoc, void *firstAmpLoc); --void *FunctionTypeRepr_create(void *ctx, void *argsTy, void *_Nullable asyncLoc, -- void *_Nullable throwsLoc, void *arrowLoc, -- void *returnType); --void *NamedOpaqueReturnTypeRepr_create(void *ctx, void *baseTy); --void *OpaqueReturnTypeRepr_create(void *ctx, void *opaqueLoc, void *baseTy); --void *ExistentialTypeRepr_create(void *ctx, void *anyLoc, void *baseTy); --void *GenericParamList_create(void *ctx, void *lAngleLoc, -- BridgedArrayRef params, void *_Nullable whereLoc, -- BridgedArrayRef reqs, void *rAngleLoc); --void *GenericTypeParamDecl_create(void *ctx, void *declContext, -- BridgedIdentifier name, void *nameLoc, -- void *_Nullable eachLoc, SwiftInt index, -+ BridgedSourceLoc cNameLoc, -+ BridgedDeclContext cDeclContext); -+ -+void *GenericParamList_create(BridgedASTContext cContext, -+ BridgedSourceLoc cLAngleLoc, -+ BridgedArrayRef params, -+ BridgedSourceLoc cWhereLoc, BridgedArrayRef reqs, -+ BridgedSourceLoc cRAngleLoc); -+void *GenericTypeParamDecl_create(BridgedASTContext cContext, -+ BridgedDeclContext cDeclContext, -+ BridgedIdentifier name, -+ BridgedSourceLoc cNameLoc, -+ BridgedSourceLoc cEachLoc, SwiftInt index, - _Bool isParameterPack); --void GenericTypeParamDecl_setInheritedType(void *ctx, void *Param, void *ty); -+void GenericTypeParamDecl_setInheritedType(BridgedASTContext cContext, -+ void *Param, void *ty); - --struct DeclContextAndDecl TypeAliasDecl_create(void *ctx, void *declContext, -- void *aliasLoc, void *equalLoc, -+BridgedDeclContextAndDecl TypeAliasDecl_create(BridgedASTContext cContext, -+ BridgedDeclContext cDeclContext, -+ BridgedSourceLoc cAliasLoc, -+ BridgedSourceLoc cEqualLoc, - BridgedIdentifier name, -- void *nameLoc, -+ BridgedSourceLoc cNameLoc, - void *_Nullable genericParams); - void TypeAliasDecl_setUnderlyingTypeRepr(void *decl, void *underlyingType); - --void TopLevelCodeDecl_dump(void *); --void Expr_dump(void *); --void Decl_dump(void *); --void Stmt_dump(void *); --void Type_dump(void *); -+BridgedTypeAttrKind TypeAttrKind_fromString(BridgedString cStr); -+BridgedTypeAttributes TypeAttributes_create(void); -+void TypeAttributes_addSimpleAttr(BridgedTypeAttributes cAttributes, -+ BridgedTypeAttrKind kind, -+ BridgedSourceLoc cAtLoc, -+ BridgedSourceLoc cAttrLoc); -+ -+void *ArrayTypeRepr_create(BridgedASTContext cContext, void *base, -+ BridgedSourceLoc cLSquareLoc, -+ BridgedSourceLoc cRSquareLoc); -+void *AttributedTypeRepr_create(BridgedASTContext cContext, void *base, -+ BridgedTypeAttributes cAttributes); -+void * -+AttributedTypeSpecifierRepr_create(BridgedASTContext cContext, void *base, -+ BridgedAttributedTypeSpecifier specifier, -+ BridgedSourceLoc cSpecifierLoc); -+void *CompositionTypeRepr_create(BridgedASTContext cContext, -+ BridgedArrayRef types, -+ BridgedSourceLoc cFirstTypeLoc, -+ BridgedSourceLoc cFirstAmpLoc); -+void *DictionaryTypeRepr_create(BridgedASTContext cContext, void *keyType, -+ void *valueType, BridgedSourceLoc cLSquareLoc, -+ BridgedSourceLoc cColonloc, -+ BridgedSourceLoc cRSquareLoc); -+void *EmptyCompositionTypeRepr_create(BridgedASTContext cContext, -+ BridgedSourceLoc cAnyLoc); -+void *FunctionTypeRepr_create(BridgedASTContext cContext, void *argsTy, -+ BridgedSourceLoc cAsyncLoc, -+ BridgedSourceLoc cThrowsLoc, -+ BridgedSourceLoc cArrowLoc, void *returnType); -+void *GenericIdentTypeRepr_create(BridgedASTContext cContext, -+ BridgedIdentifier name, -+ BridgedSourceLoc cNameLoc, -+ BridgedArrayRef genericArgs, -+ BridgedSourceLoc cLAngleLoc, -+ BridgedSourceLoc cRAngleLoc); -+void *OptionalTypeRepr_create(BridgedASTContext cContext, void *base, -+ BridgedSourceLoc cQuestionLoc); -+void *ImplicitlyUnwrappedOptionalTypeRepr_create( -+ BridgedASTContext cContext, void *base, BridgedSourceLoc cExclamationLoc); -+void *MemberTypeRepr_create(BridgedASTContext cContext, void *baseComponent, -+ BridgedArrayRef bridgedMemberComponents); -+void *MetatypeTypeRepr_create(BridgedASTContext cContext, void *baseType, -+ BridgedSourceLoc cTypeLoc); -+void *ProtocolTypeRepr_create(BridgedASTContext cContext, void *baseType, -+ BridgedSourceLoc cProtoLoc); -+void *PackExpansionTypeRepr_create(BridgedASTContext cContext, void *base, -+ BridgedSourceLoc cRepeatLoc); -+void *TupleTypeRepr_create(BridgedASTContext cContext, BridgedArrayRef elements, -+ BridgedSourceLoc cLParenLoc, -+ BridgedSourceLoc cRParenLoc); -+void *NamedOpaqueReturnTypeRepr_create(BridgedASTContext cContext, -+ void *baseTy); -+void *OpaqueReturnTypeRepr_create(BridgedASTContext cContext, -+ BridgedSourceLoc cOpaqueLoc, void *baseTy); -+void *ExistentialTypeRepr_create(BridgedASTContext cContext, -+ BridgedSourceLoc cAnyLoc, void *baseTy); -+void *VarargTypeRepr_create(BridgedASTContext cContext, void *base, -+ BridgedSourceLoc cEllipsisLoc); -+ -+void TopLevelCodeDecl_dump(void *decl); -+void Expr_dump(void *expr); -+void Decl_dump(void *decl); -+void Stmt_dump(void *statement); -+void Type_dump(void *type); - - //===----------------------------------------------------------------------===// - // Plugins -diff --git a/swift/lib/AST/CASTBridging.cpp b/swift/lib/AST/CASTBridging.cpp -index b76dcfa8e5cc8..76b9b484e8f80 100644 ---- a/swift/lib/AST/CASTBridging.cpp -+++ b/swift/lib/AST/CASTBridging.cpp -@@ -15,50 +15,91 @@ - - using namespace swift; - -+namespace { -+struct BridgedDiagnosticImpl { -+ InFlightDiagnostic inFlight; -+ std::vector textBlobs; -+ -+ BridgedDiagnosticImpl(const BridgedDiagnosticImpl &) = delete; -+ BridgedDiagnosticImpl(BridgedDiagnosticImpl &&) = delete; -+ BridgedDiagnosticImpl &operator=(const BridgedDiagnosticImpl &) = delete; -+ BridgedDiagnosticImpl &operator=(BridgedDiagnosticImpl &&) = delete; -+ -+ ~BridgedDiagnosticImpl() { -+ inFlight.flush(); -+ for (auto text : textBlobs) { -+ free((void *)text.data()); -+ } -+ } -+}; -+} // namespace -+ - template --inline llvm::ArrayRef getArrayRef(BridgedArrayRef bridged) { -+static inline llvm::ArrayRef convertArrayRef(const BridgedArrayRef bridged) { - return {static_cast(bridged.data), size_t(bridged.numElements)}; - } - --static SourceLoc getSourceLocFromPointer(const void *loc) { -- auto smLoc = llvm::SMLoc::getFromPointer((const char *)loc); -+static inline StringRef convertString(BridgedString cStr) { -+ return StringRef{reinterpret_cast(cStr.data), -+ size_t(cStr.length)}; -+} -+ -+static inline ASTContext &convertASTContext(BridgedASTContext cContext) { -+ return *static_cast(cContext.raw); -+} -+ -+static inline DeclContext *convertDeclContext(BridgedDeclContext cDeclContext) { -+ return static_cast(cDeclContext.raw); -+} -+ -+static inline BridgedDeclContext bridgeDeclContext(DeclContext *declContext) { -+ return BridgedDeclContext{declContext}; -+} -+ -+static inline SourceLoc convertSourceLoc(BridgedSourceLoc cLoc) { -+ auto smLoc = llvm::SMLoc::getFromPointer(static_cast(cLoc.raw)); - return SourceLoc(smLoc); - } - --namespace { -- struct BridgedDiagnosticImpl { -- typedef llvm::MallocAllocator Allocator; -- -- InFlightDiagnostic inFlight; -- std::vector textBlobs; -- -- BridgedDiagnosticImpl(const BridgedDiagnosticImpl&) = delete; -- BridgedDiagnosticImpl(BridgedDiagnosticImpl &&) = delete; -- BridgedDiagnosticImpl &operator=(const BridgedDiagnosticImpl&) = delete; -- BridgedDiagnosticImpl &operator=(BridgedDiagnosticImpl &&) = delete; -- -- ~BridgedDiagnosticImpl() { -- inFlight.flush(); -- -- Allocator allocator; -- for (auto text: textBlobs) { -- allocator.Deallocate(text.data(), text.size()); -- } -- } -- }; -+static inline Identifier convertIdentifier(BridgedIdentifier cIdentifier) { -+ return Identifier::getFromOpaquePointer(const_cast(cIdentifier.raw)); -+} -+ -+static inline BridgedDiagnosticImpl * -+convertDiagnostic(BridgedDiagnostic cDiag) { -+ return static_cast(cDiag.raw); -+} -+ -+static inline DiagnosticEngine & -+convertDiagnosticEngine(BridgedDiagnosticEngine cEngine) { -+ return *static_cast(cEngine.raw); -+} -+ -+static inline TypeAttributes * -+convertTypeAttributes(BridgedTypeAttributes cAttributes) { -+ return static_cast(cAttributes.raw); -+} -+ -+static TypeAttrKind convertTypeAttrKind(BridgedTypeAttrKind kind) { -+ switch (kind) { -+#define TYPE_ATTR(X) \ -+ case BridgedTypeAttrKind_##X: \ -+ return TAK_##X; -+#include "swift/AST/Attr.def" -+ case BridgedTypeAttrKind_Count: -+ return TAK_Count; -+ } - } - --BridgedDiagnostic SwiftDiagnostic_create(void *diagnosticEngine, -- BridgedDiagnosticSeverity severity, -- const void *sourceLocPtr, -- const unsigned char *textPtr, -- SwiftInt textLen) { -- StringRef origText{ -- reinterpret_cast(textPtr), size_t(textLen)}; -- BridgedDiagnosticImpl::Allocator alloc; -- StringRef text = origText.copy(alloc); -+BridgedDiagnostic Diagnostic_create(BridgedDiagnosticEngine cDiags, -+ BridgedDiagnosticSeverity severity, -+ BridgedSourceLoc cLoc, -+ BridgedString cText) { -+ StringRef origText = convertString(cText); -+ llvm::MallocAllocator mallocAlloc; -+ StringRef text = origText.copy(mallocAlloc); - -- SourceLoc loc = getSourceLocFromPointer(sourceLocPtr); -+ SourceLoc loc = convertSourceLoc(cLoc); - - Diag diagID; - switch (severity) { -@@ -75,230 +120,232 @@ BridgedDiagnostic SwiftDiagnostic_create(void *diagnosticEngine, - break; - } - -- DiagnosticEngine &diags = *static_cast(diagnosticEngine); -- return new BridgedDiagnosticImpl{diags.diagnose(loc, diagID, text), {text}}; -+ DiagnosticEngine &diags = convertDiagnosticEngine(cDiags); -+ return {new BridgedDiagnosticImpl{diags.diagnose(loc, diagID, text), {text}}}; - } - - /// Highlight a source range as part of the diagnostic. --void SwiftDiagnostic_highlight( -- BridgedDiagnostic diagPtr, const void *startLocPtr, const void *endLocPtr --) { -- SourceLoc startLoc = getSourceLocFromPointer(startLocPtr); -- SourceLoc endLoc = getSourceLocFromPointer(endLocPtr); -+void Diagnostic_highlight(BridgedDiagnostic cDiag, BridgedSourceLoc cStartLoc, -+ BridgedSourceLoc cEndLoc) { -+ SourceLoc startLoc = convertSourceLoc(cStartLoc); -+ SourceLoc endLoc = convertSourceLoc(cEndLoc); - -- BridgedDiagnosticImpl *impl = static_cast(diagPtr); -- impl->inFlight.highlightChars(startLoc, endLoc); -+ BridgedDiagnosticImpl *diag = convertDiagnostic(cDiag); -+ diag->inFlight.highlightChars(startLoc, endLoc); - } - - /// Add a Fix-It to replace a source range as part of the diagnostic. --void SwiftDiagnostic_fixItReplace(BridgedDiagnostic diagPtr, -- const void *replaceStartLocPtr, -- const void *replaceEndLocPtr, -- const unsigned char *newTextPtr, -- SwiftInt newTextLen) { -+void Diagnostic_fixItReplace(BridgedDiagnostic cDiag, -+ BridgedSourceLoc cStartLoc, -+ BridgedSourceLoc cEndLoc, -+ BridgedString cReplaceText) { - -- SourceLoc startLoc = getSourceLocFromPointer(replaceStartLocPtr); -- SourceLoc endLoc = getSourceLocFromPointer(replaceEndLocPtr); -+ SourceLoc startLoc = convertSourceLoc(cStartLoc); -+ SourceLoc endLoc = convertSourceLoc(cEndLoc); - -- StringRef origReplaceText{ -- reinterpret_cast(newTextPtr), size_t(newTextLen)}; -- BridgedDiagnosticImpl::Allocator alloc; -- StringRef replaceText = origReplaceText.copy(alloc); -+ StringRef origReplaceText = convertString(cReplaceText); -+ llvm::MallocAllocator mallocAlloc; -+ StringRef replaceText = origReplaceText.copy(mallocAlloc); - -- BridgedDiagnosticImpl *impl = static_cast(diagPtr); -- impl->textBlobs.push_back(replaceText); -- impl->inFlight.fixItReplaceChars(startLoc, endLoc, replaceText); -+ BridgedDiagnosticImpl *diag = convertDiagnostic(cDiag); -+ diag->textBlobs.push_back(replaceText); -+ diag->inFlight.fixItReplaceChars(startLoc, endLoc, replaceText); - } - - /// Finish the given diagnostic and emit it. --void SwiftDiagnostic_finish(BridgedDiagnostic diagPtr) { -- BridgedDiagnosticImpl *impl = static_cast(diagPtr); -- delete impl; -+void Diagnostic_finish(BridgedDiagnostic cDiag) { -+ BridgedDiagnosticImpl *diag = convertDiagnostic(cDiag); -+ delete diag; - } - --BridgedIdentifier --SwiftASTContext_getIdentifier(void *ctx, const unsigned char *_Nullable str, -- SwiftInt len) { -- if (len == 1 && str[0] == '_') -+BridgedIdentifier ASTContext_getIdentifier(BridgedASTContext cContext, -+ BridgedString cStr) { -+ StringRef str = convertString(cStr); -+ if (str.size() == 1 && str.front() == '_') - return BridgedIdentifier(); - - // If this was a back-ticked identifier, drop the back-ticks. -- if (len >= 2 && str[0] == '`' && str[len-1] == '`') { -- ++str; -- len -= 2; -+ if (str.size() >= 2 && str.front() == '`' && str.back() == '`') { -+ str = str.drop_front().drop_back(); - } - -- return const_cast( -- static_cast(ctx) -- ->getIdentifier( -- StringRef{reinterpret_cast(str), size_t(len)}) -- .getAsOpaquePointer()); -+ return {convertASTContext(cContext).getIdentifier(str).getAsOpaquePointer()}; - } - --void *SwiftImportDecl_create(void *ctx, void *dc, void *importLoc, char kind, -- void *kindLoc, BridgedArrayRef path, -- BridgedArrayRef pathLocs) { -- assert(path.numElements == pathLocs.numElements); -- ASTContext &Context = *static_cast(ctx); -+void *ImportDecl_create(BridgedASTContext cContext, -+ BridgedDeclContext cDeclContext, -+ BridgedSourceLoc cImportLoc, char kind, -+ BridgedSourceLoc cKindLoc, BridgedArrayRef path, -+ BridgedArrayRef cPathLocs) { -+ assert(path.numElements == cPathLocs.numElements); -+ ASTContext &context = convertASTContext(cContext); -+ DeclContext *declContext = convertDeclContext(cDeclContext); -+ - ImportPath::Builder importPath; -- for (auto p : llvm::zip(getArrayRef(path), -- getArrayRef(pathLocs))) { -+ for (auto p : llvm::zip(convertArrayRef(path), -+ convertArrayRef(cPathLocs))) { - Identifier ident; - SourceLoc loc; - std::tie(ident, loc) = p; - importPath.push_back(ident, loc); - } -- return ImportDecl::create( -- Context, static_cast(dc), -- getSourceLocFromPointer(importLoc), static_cast(kind), -- getSourceLocFromPointer(kindLoc), std::move(importPath).get()); -+ return ImportDecl::create(context, declContext, convertSourceLoc(cImportLoc), -+ static_cast(kind), -+ convertSourceLoc(cKindLoc), -+ std::move(importPath).get()); - } - --void *BridgedSourceLoc_advanced(void *loc, SwiftInt len) { -- SourceLoc l = getSourceLocFromPointer(loc).getAdvancedLoc(len); -- return const_cast(l.getOpaquePointerValue()); -+BridgedSourceLoc SourceLoc_advanced(BridgedSourceLoc cLoc, long len) { -+ SourceLoc loc = convertSourceLoc(cLoc).getAdvancedLoc(len); -+ return {loc.getOpaquePointerValue()}; - } - --void *SwiftTopLevelCodeDecl_createStmt(void *ctx, void *DC, void *startLoc, -- void *element, void *endLoc) { -- ASTContext &Context = *static_cast(ctx); -+void *TopLevelCodeDecl_createStmt(BridgedASTContext cContext, -+ BridgedDeclContext cDeclContext, -+ BridgedSourceLoc cStartLoc, void *element, -+ BridgedSourceLoc cEndLoc) { -+ ASTContext &context = convertASTContext(cContext); -+ DeclContext *declContext = convertDeclContext(cDeclContext); -+ - auto *S = static_cast(element); -- auto Brace = BraceStmt::create(Context, getSourceLocFromPointer(startLoc), -- {S}, getSourceLocFromPointer(endLoc), -+ auto Brace = BraceStmt::create(context, convertSourceLoc(cStartLoc), {S}, -+ convertSourceLoc(cEndLoc), - /*Implicit=*/true); -- auto *TLCD = -- new (Context) TopLevelCodeDecl(static_cast(DC), Brace); -+ auto *TLCD = new (context) TopLevelCodeDecl(declContext, Brace); - return (Decl *)TLCD; - } - --void *SwiftTopLevelCodeDecl_createExpr(void *ctx, void *DC, void *startLoc, -- void *element, void *endLoc) { -- ASTContext &Context = *static_cast(ctx); -+void *TopLevelCodeDecl_createExpr(BridgedASTContext cContext, -+ BridgedDeclContext cDeclContext, -+ BridgedSourceLoc cStartLoc, void *element, -+ BridgedSourceLoc cEndLoc) { -+ ASTContext &context = convertASTContext(cContext); -+ DeclContext *declContext = convertDeclContext(cDeclContext); -+ - auto *E = static_cast(element); -- auto Brace = BraceStmt::create(Context, getSourceLocFromPointer(startLoc), -- {E}, getSourceLocFromPointer(endLoc), -+ auto Brace = BraceStmt::create(context, convertSourceLoc(cStartLoc), {E}, -+ convertSourceLoc(cEndLoc), - /*Implicit=*/true); -- auto *TLCD = -- new (Context) TopLevelCodeDecl(static_cast(DC), Brace); -+ auto *TLCD = new (context) TopLevelCodeDecl(declContext, Brace); - return (Decl *)TLCD; - } - --void *SwiftSequenceExpr_create(void *ctx, BridgedArrayRef exprs) { -- return SequenceExpr::create(*static_cast(ctx), -- getArrayRef(exprs)); -+void *SequenceExpr_create(BridgedASTContext cContext, BridgedArrayRef exprs) { -+ return SequenceExpr::create(convertASTContext(cContext), -+ convertArrayRef(exprs)); - } - --void *SwiftTupleExpr_create(void *ctx, void *lparen, BridgedArrayRef subs, -- BridgedArrayRef names, -- BridgedArrayRef nameLocs, -- void *rparen) { -- auto &Context = *static_cast(ctx); -+void *TupleExpr_create(BridgedASTContext cContext, BridgedSourceLoc cLParen, -+ BridgedArrayRef subs, BridgedArrayRef names, -+ BridgedArrayRef cNameLocs, BridgedSourceLoc cRParen) { -+ ASTContext &context = convertASTContext(cContext); - return TupleExpr::create( -- Context, getSourceLocFromPointer(lparen), -- getArrayRef(subs), getArrayRef(names), -- getArrayRef(nameLocs), getSourceLocFromPointer(rparen), -+ context, convertSourceLoc(cLParen), convertArrayRef(subs), -+ convertArrayRef(names), convertArrayRef(cNameLocs), -+ convertSourceLoc(cRParen), - /*Implicit*/ false); - } - --void *SwiftFunctionCallExpr_create(void *ctx, void *fn, void *args) { -- ASTContext &Context = *static_cast(ctx); -+void *FunctionCallExpr_create(BridgedASTContext cContext, void *fn, -+ void *args) { -+ ASTContext &context = convertASTContext(cContext); - TupleExpr *TE = static_cast(args); - SmallVector arguments; - for (unsigned i = 0; i < TE->getNumElements(); ++i) { - arguments.emplace_back(TE->getElementNameLoc(i), TE->getElementName(i), - TE->getElement(i)); - } -- auto *argList = ArgumentList::create(Context, TE->getLParenLoc(), arguments, -+ auto *argList = ArgumentList::create(context, TE->getLParenLoc(), arguments, - TE->getRParenLoc(), llvm::None, - /*isImplicit*/ false); -- return CallExpr::create(Context, static_cast(fn), argList, -+ return CallExpr::create(context, static_cast(fn), argList, - /*implicit*/ false); - } - --void *SwiftIdentifierExpr_create(void *ctx, BridgedIdentifier base, void *loc) { -- ASTContext &Context = *static_cast(ctx); -- auto name = DeclNameRef{swift::Identifier::getFromOpaquePointer(base)}; -- Expr *E = new (Context) UnresolvedDeclRefExpr( -- name, DeclRefKind::Ordinary, DeclNameLoc{getSourceLocFromPointer(loc)}); -+void *IdentifierExpr_create(BridgedASTContext cContext, BridgedIdentifier base, -+ BridgedSourceLoc cLoc) { -+ ASTContext &context = convertASTContext(cContext); -+ auto name = DeclNameRef{convertIdentifier(base)}; -+ Expr *E = new (context) UnresolvedDeclRefExpr( -+ name, DeclRefKind::Ordinary, DeclNameLoc{convertSourceLoc(cLoc)}); - return E; - } - --void *SwiftStringLiteralExpr_create(void *ctx, -- const unsigned char *_Nullable string, -- SwiftInt len, void *TokenLoc) { -- ASTContext &Context = *static_cast(ctx); -- auto stringRef = Context.AllocateCopy( -- StringRef{reinterpret_cast(string), size_t(len)}); -- return new (Context) -- StringLiteralExpr(stringRef, getSourceLocFromPointer(TokenLoc)); -+void *StringLiteralExpr_create(BridgedASTContext cContext, BridgedString cStr, -+ BridgedSourceLoc cTokenLoc) { -+ ASTContext &context = convertASTContext(cContext); -+ auto str = context.AllocateCopy(convertString(cStr)); -+ return new (context) StringLiteralExpr(str, convertSourceLoc(cTokenLoc)); - } - --void *SwiftIntegerLiteralExpr_create(void *ctx, -- const unsigned char *_Nullable string, -- SwiftInt len, void *TokenLoc) { -- ASTContext &Context = *static_cast(ctx); -- auto stringRef = Context.AllocateCopy( -- StringRef{reinterpret_cast(string), size_t(len)}); -- return new (Context) -- IntegerLiteralExpr(stringRef, getSourceLocFromPointer(TokenLoc)); -+void *IntegerLiteralExpr_create(BridgedASTContext cContext, BridgedString cStr, -+ BridgedSourceLoc cTokenLoc) { -+ ASTContext &context = convertASTContext(cContext); -+ auto str = context.AllocateCopy(convertString(cStr)); -+ return new (context) IntegerLiteralExpr(str, convertSourceLoc(cTokenLoc)); - } - --void *ArrayExpr_create(void *ctx, void *lLoc, BridgedArrayRef elements, -- BridgedArrayRef commas, void *rLoc) { -- ASTContext &Context = *static_cast(ctx); -+void *ArrayExpr_create(BridgedASTContext cContext, BridgedSourceLoc cLLoc, -+ BridgedArrayRef elements, BridgedArrayRef commas, -+ BridgedSourceLoc cRLoc) { -+ ASTContext &context = convertASTContext(cContext); - return ArrayExpr::create( -- Context, getSourceLocFromPointer(lLoc), getArrayRef(elements), -- getArrayRef(commas), getSourceLocFromPointer(rLoc)); -+ context, convertSourceLoc(cLLoc), convertArrayRef(elements), -+ convertArrayRef(commas), convertSourceLoc(cRLoc)); - } - --void *SwiftBooleanLiteralExpr_create(void *ctx, bool value, void *TokenLoc) { -- ASTContext &Context = *static_cast(ctx); -- return new (Context) -- BooleanLiteralExpr(value, getSourceLocFromPointer(TokenLoc)); -+void *BooleanLiteralExpr_create(BridgedASTContext cContext, bool value, -+ BridgedSourceLoc cTokenLoc) { -+ ASTContext &context = convertASTContext(cContext); -+ return new (context) BooleanLiteralExpr(value, convertSourceLoc(cTokenLoc)); - } - --void *SwiftVarDecl_create(void *ctx, BridgedIdentifier _Nullable nameId, -- void *initExpr, void *loc, bool isStatic, bool isLet, -- void *dc) { -- ASTContext &Context = *static_cast(ctx); -- auto name = (UnresolvedDeclRefExpr *)nameId; -- auto sourceLoc = getSourceLocFromPointer(loc); -- auto varDecl = new (Context) VarDecl( -+void *VarDecl_create(BridgedASTContext cContext, void *nameExpr, void *initExpr, -+ BridgedSourceLoc cLoc, bool isStatic, bool isLet, -+ BridgedDeclContext cDeclContext) { -+ ASTContext &context = convertASTContext(cContext); -+ DeclContext *declContext = convertDeclContext(cDeclContext); -+ -+ auto name = (UnresolvedDeclRefExpr *)nameExpr; -+ auto sourceLoc = convertSourceLoc(cLoc); -+ auto varDecl = new (context) VarDecl( - isStatic, isLet ? VarDecl::Introducer::Let : VarDecl::Introducer::Var, -- sourceLoc, name->getName().getBaseIdentifier(), -- reinterpret_cast(dc)); -- auto pattern = NamedPattern::createImplicit(Context, varDecl); -+ sourceLoc, name->getName().getBaseIdentifier(), declContext); -+ auto pattern = NamedPattern::createImplicit(context, varDecl); - return PatternBindingDecl::create( -- Context, sourceLoc, -+ context, sourceLoc, - isStatic ? StaticSpellingKind::KeywordStatic : StaticSpellingKind::None, -- sourceLoc, pattern, sourceLoc, (Expr *)initExpr, -- reinterpret_cast(dc)); -+ sourceLoc, pattern, sourceLoc, (Expr *)initExpr, declContext); - } - --void *SingleValueStmtExpr_createWithWrappedBranches(void *_ctx, void *S, -- void *DC, bool mustBeExpr) { -- auto &ctx = *static_cast(_ctx); -+void *SingleValueStmtExpr_createWithWrappedBranches( -+ BridgedASTContext cContext, void *S, BridgedDeclContext cDeclContext, -+ bool mustBeExpr) { -+ ASTContext &context = convertASTContext(cContext); -+ DeclContext *declContext = convertDeclContext(cDeclContext); - return SingleValueStmtExpr::createWithWrappedBranches( -- ctx, (Stmt *)S, (DeclContext *)DC, mustBeExpr); -+ context, (Stmt *)S, declContext, mustBeExpr); - } - --void *IfStmt_create(void *ctx, void *ifLoc, void *cond, void *_Nullable then, -- void *_Nullable elseLoc, void *_Nullable elseStmt) { -- ASTContext &Context = *static_cast(ctx); -- return new (Context) IfStmt(getSourceLocFromPointer(ifLoc), (Expr *)cond, -- (Stmt *)then, getSourceLocFromPointer(elseLoc), -- (Stmt *)elseStmt, llvm::None, Context); -+void *IfStmt_create(BridgedASTContext cContext, BridgedSourceLoc cIfLoc, -+ void *cond, void *_Nullable then, BridgedSourceLoc cElseLoc, -+ void *_Nullable elseStmt) { -+ ASTContext &context = convertASTContext(cContext); -+ return new (context) -+ IfStmt(convertSourceLoc(cIfLoc), (Expr *)cond, (Stmt *)then, -+ convertSourceLoc(cElseLoc), (Stmt *)elseStmt, llvm::None, context); - } - --void *ReturnStmt_create(void *ctx, void *loc, void *_Nullable expr) { -- ASTContext &Context = *static_cast(ctx); -- return new (Context) ReturnStmt(getSourceLocFromPointer(loc), (Expr *)expr); -+void *ReturnStmt_create(BridgedASTContext cContext, BridgedSourceLoc cLoc, -+ void *_Nullable expr) { -+ ASTContext &context = convertASTContext(cContext); -+ return new (context) ReturnStmt(convertSourceLoc(cLoc), (Expr *)expr); - } - --void *BraceStmt_create(void *ctx, void *lbloc, BridgedArrayRef elements, -- void *rbloc) { -+void *BraceStmt_create(BridgedASTContext cContext, BridgedSourceLoc cLBLoc, -+ BridgedArrayRef elements, BridgedSourceLoc cRBLoc) { - llvm::SmallVector nodes; -- for (auto node : getArrayRef(elements)) { -+ for (auto node : convertArrayRef(elements)) { - if (node.kind == ASTNodeKindExpr) { - auto expr = (Expr *)node.ptr; - nodes.push_back(expr); -@@ -312,88 +359,94 @@ void *BraceStmt_create(void *ctx, void *lbloc, BridgedArrayRef elements, - } - } - -- ASTContext &Context = *static_cast(ctx); -- return BraceStmt::create(Context, getSourceLocFromPointer(lbloc), -- Context.AllocateCopy(nodes), -- getSourceLocFromPointer(rbloc)); -+ ASTContext &context = convertASTContext(cContext); -+ return BraceStmt::create(context, convertSourceLoc(cLBLoc), -+ context.AllocateCopy(nodes), -+ convertSourceLoc(cRBLoc)); - } - --void *ParamDecl_create(void *ctx, void *loc, void *_Nullable argLoc, -- BridgedIdentifier _Nullable argName, -- void *_Nullable paramLoc, -- BridgedIdentifier _Nullable paramName, -- void *_Nullable type, void *declContext) { -- ASTContext &Context = *static_cast(ctx); -- if (!paramName) -+void *ParamDecl_create(BridgedASTContext cContext, BridgedSourceLoc cLoc, -+ BridgedSourceLoc cArgLoc, BridgedIdentifier argName, -+ BridgedSourceLoc cParamLoc, BridgedIdentifier paramName, -+ void *_Nullable type, BridgedDeclContext cDeclContext) { -+ ASTContext &context = convertASTContext(cContext); -+ DeclContext *declContext = convertDeclContext(cDeclContext); -+ -+ if (!paramName.raw) - paramName = argName; -- auto paramDecl = new (Context) ParamDecl( -- getSourceLocFromPointer(loc), getSourceLocFromPointer(argLoc), -- Identifier::getFromOpaquePointer(argName), -- getSourceLocFromPointer(paramLoc), -- Identifier::getFromOpaquePointer(paramName), (DeclContext *)declContext); -+ auto paramDecl = new (context) -+ ParamDecl(convertSourceLoc(cLoc), convertSourceLoc(cArgLoc), -+ convertIdentifier(argName), convertSourceLoc(cParamLoc), -+ convertIdentifier(paramName), declContext); - paramDecl->setTypeRepr((TypeRepr *)type); - return paramDecl; - } - --struct FuncDeclBridged --FuncDecl_create(void *ctx, void *staticLoc, bool isStatic, void *funcLoc, -- BridgedIdentifier name, void *nameLoc, bool isAsync, -- void *_Nullable asyncLoc, bool throws, -- void *_Nullable throwsLoc, void *paramLLoc, -- BridgedArrayRef params, void *paramRLoc, -- void *_Nullable returnType, void *declContext) { -- auto *paramList = ParameterList::create( -- *static_cast(ctx), getSourceLocFromPointer(paramLLoc), -- getArrayRef(params), getSourceLocFromPointer(paramRLoc)); -- auto declName = DeclName(*static_cast(ctx), -- Identifier::getFromOpaquePointer(name), paramList); -+BridgedFuncDecl -+FuncDecl_create(BridgedASTContext cContext, BridgedSourceLoc cStaticLoc, -+ bool isStatic, BridgedSourceLoc cFuncLoc, -+ BridgedIdentifier name, BridgedSourceLoc cNameLoc, bool isAsync, -+ BridgedSourceLoc cAsyncLoc, bool throws, -+ BridgedSourceLoc cThrowsLoc, BridgedSourceLoc cParamLLoc, -+ BridgedArrayRef params, BridgedSourceLoc cParamRLoc, -+ void *_Nullable returnType, BridgedDeclContext cDeclContext) { -+ ASTContext &context = convertASTContext(cContext); -+ DeclContext *declContext = convertDeclContext(cDeclContext); -+ -+ auto *paramList = ParameterList::create(context, convertSourceLoc(cParamLLoc), -+ convertArrayRef(params), -+ convertSourceLoc(cParamRLoc)); -+ auto declName = -+ DeclName(convertASTContext(cContext), convertIdentifier(name), paramList); - auto *out = FuncDecl::create( -- *static_cast(ctx), getSourceLocFromPointer(staticLoc), -+ context, convertSourceLoc(cStaticLoc), - isStatic ? StaticSpellingKind::KeywordStatic : StaticSpellingKind::None, -- getSourceLocFromPointer(funcLoc), declName, -- getSourceLocFromPointer(nameLoc), isAsync, -- getSourceLocFromPointer(asyncLoc), throws, -- getSourceLocFromPointer(throwsLoc), nullptr, paramList, -- (TypeRepr *)returnType, (DeclContext *)declContext); -+ convertSourceLoc(cFuncLoc), declName, convertSourceLoc(cNameLoc), isAsync, -+ convertSourceLoc(cAsyncLoc), throws, convertSourceLoc(cThrowsLoc), -+ nullptr, paramList, (TypeRepr *)returnType, declContext); - -- return {static_cast(out), static_cast(out), -- static_cast(out)}; -+ return {bridgeDeclContext(out), cast(out), cast(out)}; - } - - void FuncDecl_setBody(void *fn, void *body) { - ((FuncDecl *)fn)->setBody((BraceStmt *)body, FuncDecl::BodyKind::Parsed); - } - --void *SimpleIdentTypeRepr_create(void *ctx, void *loc, BridgedIdentifier id) { -- ASTContext &Context = *static_cast(ctx); -- return new (Context) -- SimpleIdentTypeRepr(DeclNameLoc(getSourceLocFromPointer(loc)), -- DeclNameRef(Identifier::getFromOpaquePointer(id))); --} -- --void *GenericIdentTypeRepr_create(void *ctx, BridgedIdentifier name, -- void *nameLoc, BridgedArrayRef genericArgs, -- void *lAngle, void *rAngle) { -- ASTContext &Context = *static_cast(ctx); -- auto Loc = DeclNameLoc(getSourceLocFromPointer(nameLoc)); -- auto Name = DeclNameRef(Identifier::getFromOpaquePointer(name)); -- SourceLoc lAngleLoc = getSourceLocFromPointer(lAngle); -- SourceLoc rAngleLoc = getSourceLocFromPointer(rAngle); -- return GenericIdentTypeRepr::create(Context, Loc, Name, -- getArrayRef(genericArgs), -+void *SimpleIdentTypeRepr_create(BridgedASTContext cContext, -+ BridgedSourceLoc cLoc, BridgedIdentifier id) { -+ ASTContext &context = convertASTContext(cContext); -+ return new (context) SimpleIdentTypeRepr(DeclNameLoc(convertSourceLoc(cLoc)), -+ DeclNameRef(convertIdentifier(id))); -+} -+ -+void *GenericIdentTypeRepr_create(BridgedASTContext cContext, -+ BridgedIdentifier name, -+ BridgedSourceLoc cNameLoc, -+ BridgedArrayRef genericArgs, -+ BridgedSourceLoc cLAngleLoc, -+ BridgedSourceLoc cRAngleLoc) { -+ ASTContext &context = convertASTContext(cContext); -+ auto Loc = DeclNameLoc(convertSourceLoc(cNameLoc)); -+ auto Name = DeclNameRef(convertIdentifier(name)); -+ SourceLoc lAngleLoc = convertSourceLoc(cLAngleLoc); -+ SourceLoc rAngleLoc = convertSourceLoc(cRAngleLoc); -+ return GenericIdentTypeRepr::create(context, Loc, Name, -+ convertArrayRef(genericArgs), - SourceRange{lAngleLoc, rAngleLoc}); - } - --void *UnresolvedDotExpr_create(void *ctx, void *base, void *dotLoc, -- BridgedIdentifier name, void *nameLoc) { -- ASTContext &Context = *static_cast(ctx); -- return new (Context) -- UnresolvedDotExpr((Expr *)base, getSourceLocFromPointer(dotLoc), -- DeclNameRef(Identifier::getFromOpaquePointer(name)), -- DeclNameLoc(getSourceLocFromPointer(nameLoc)), false); -+void *UnresolvedDotExpr_create(BridgedASTContext cContext, void *base, -+ BridgedSourceLoc cDotLoc, BridgedIdentifier name, -+ BridgedSourceLoc cNameLoc) { -+ ASTContext &context = convertASTContext(cContext); -+ return new (context) -+ UnresolvedDotExpr((Expr *)base, convertSourceLoc(cDotLoc), -+ DeclNameRef(convertIdentifier(name)), -+ DeclNameLoc(convertSourceLoc(cNameLoc)), false); - } - --void *ClosureExpr_create(void *ctx, void *body, void *dc) { -+void *ClosureExpr_create(BridgedASTContext cContext, void *body, -+ BridgedDeclContext cDeclContext) { - DeclAttributes attributes; - SourceRange bracketRange; - SourceLoc asyncLoc; -@@ -401,99 +454,118 @@ void *ClosureExpr_create(void *ctx, void *body, void *dc) { - SourceLoc arrowLoc; - SourceLoc inLoc; - -- ASTContext &Context = *static_cast(ctx); -- auto params = ParameterList::create(Context, inLoc, {}, inLoc); -+ ASTContext &context = convertASTContext(cContext); -+ DeclContext *declContext = convertDeclContext(cDeclContext); - -- auto *out = new (Context) -+ auto params = ParameterList::create(context, inLoc, {}, inLoc); -+ -+ auto *out = new (context) - ClosureExpr(attributes, bracketRange, nullptr, nullptr, asyncLoc, -- throwsLoc, arrowLoc, inLoc, nullptr, (DeclContext *)dc); -+ throwsLoc, arrowLoc, inLoc, nullptr, declContext); - out->setBody((BraceStmt *)body, true); - out->setParameterList(params); - return (Expr *)out; - } - - void NominalTypeDecl_setMembers(void *decl, BridgedArrayRef members) { -- auto declMembers = getArrayRef(members); -+ auto declMembers = convertArrayRef(members); - for (auto m : declMembers) - ((NominalTypeDecl *)decl)->addMember(m); - } - --DeclContextAndDecl StructDecl_create(void *ctx, void *loc, -- BridgedIdentifier name, void *nameLoc, -- void *_Nullable genericParams, void *dc) { -- ASTContext &Context = *static_cast(ctx); -- auto *out = new (Context) StructDecl( -- getSourceLocFromPointer(loc), Identifier::getFromOpaquePointer(name), -- getSourceLocFromPointer(nameLoc), {}, (GenericParamList *)genericParams, -- (DeclContext *)dc); -+BridgedDeclContextAndDecl StructDecl_create(BridgedASTContext cContext, -+ BridgedSourceLoc cLoc, -+ BridgedIdentifier name, -+ BridgedSourceLoc cNameLoc, -+ void *_Nullable genericParams, -+ BridgedDeclContext cDeclContext) { -+ ASTContext &context = convertASTContext(cContext); -+ DeclContext *declContext = convertDeclContext(cDeclContext); -+ -+ auto *out = -+ new (context) StructDecl(convertSourceLoc(cLoc), convertIdentifier(name), -+ convertSourceLoc(cNameLoc), {}, -+ (GenericParamList *)genericParams, declContext); - out->setImplicit(); // TODO: remove this. -- return {(DeclContext *)out, (NominalTypeDecl *)out, (Decl *)out}; -+ return {bridgeDeclContext(out->getDeclContext()), cast(out), cast(out)}; - } - --DeclContextAndDecl ClassDecl_create(void *ctx, void *loc, -- BridgedIdentifier name, void *nameLoc, -- void *dc) { -- ASTContext &Context = *static_cast(ctx); -- auto *out = new (Context) ClassDecl( -- getSourceLocFromPointer(loc), Identifier::getFromOpaquePointer(name), -- getSourceLocFromPointer(nameLoc), {}, nullptr, (DeclContext *)dc, false); -+BridgedDeclContextAndDecl ClassDecl_create(BridgedASTContext cContext, -+ BridgedSourceLoc cLoc, -+ BridgedIdentifier name, -+ BridgedSourceLoc cNameLoc, -+ BridgedDeclContext cDeclContext) { -+ ASTContext &context = convertASTContext(cContext); -+ DeclContext *declContext = convertDeclContext(cDeclContext); -+ -+ auto *out = new (context) -+ ClassDecl(convertSourceLoc(cLoc), convertIdentifier(name), -+ convertSourceLoc(cNameLoc), {}, nullptr, declContext, false); - out->setImplicit(); // TODO: remove this. -- return {(DeclContext *)out, (NominalTypeDecl *)out, (Decl *)out}; -+ return {BridgedDeclContext{out}, (NominalTypeDecl *)out, (Decl *)out}; - } - --void *OptionalTypeRepr_create(void *ctx, void *base, void *questionLoc) { -- ASTContext &Context = *static_cast(ctx); -- return new (Context) -- OptionalTypeRepr((TypeRepr *)base, getSourceLocFromPointer(questionLoc)); -+void *OptionalTypeRepr_create(BridgedASTContext cContext, void *base, -+ BridgedSourceLoc cQuestionLoc) { -+ ASTContext &context = convertASTContext(cContext); -+ return new (context) -+ OptionalTypeRepr((TypeRepr *)base, convertSourceLoc(cQuestionLoc)); - } - --void *ImplicitlyUnwrappedOptionalTypeRepr_create(void *ctx, void *base, -- void *exclamationLoc) { -- ASTContext &Context = *static_cast(ctx); -- return new (Context) ImplicitlyUnwrappedOptionalTypeRepr( -- (TypeRepr *)base, getSourceLocFromPointer(exclamationLoc)); -+void *ImplicitlyUnwrappedOptionalTypeRepr_create( -+ BridgedASTContext cContext, void *base, BridgedSourceLoc cExclamationLoc) { -+ ASTContext &context = convertASTContext(cContext); -+ return new (context) ImplicitlyUnwrappedOptionalTypeRepr( -+ (TypeRepr *)base, convertSourceLoc(cExclamationLoc)); - } - --void *ArrayTypeRepr_create(void *ctx, void *base, void *lsquareLoc, -- void *rsquareLoc) { -- ASTContext &Context = *static_cast(ctx); -- SourceLoc lSquareLoc = getSourceLocFromPointer(lsquareLoc); -- SourceLoc rSquareLoc = getSourceLocFromPointer(rsquareLoc); -- return new (Context) -+void *ArrayTypeRepr_create(BridgedASTContext cContext, void *base, -+ BridgedSourceLoc cLSquareLoc, -+ BridgedSourceLoc cRSquareLoc) { -+ ASTContext &context = convertASTContext(cContext); -+ SourceLoc lSquareLoc = convertSourceLoc(cLSquareLoc); -+ SourceLoc rSquareLoc = convertSourceLoc(cRSquareLoc); -+ return new (context) - ArrayTypeRepr((TypeRepr *)base, SourceRange{lSquareLoc, rSquareLoc}); - } - --void *DictionaryTypeRepr_create(void *ctx, void *keyType, void *valueType, -- void *lsquareLoc, void *colonloc, -- void *rsquareLoc) { -- ASTContext &Context = *static_cast(ctx); -- SourceLoc lSquareLoc = getSourceLocFromPointer(lsquareLoc); -- SourceLoc colonLoc = getSourceLocFromPointer(colonloc); -- SourceLoc rSquareLoc = getSourceLocFromPointer(rsquareLoc); -- return new (Context) -+void *DictionaryTypeRepr_create(BridgedASTContext cContext, void *keyType, -+ void *valueType, BridgedSourceLoc cLSquareLoc, -+ BridgedSourceLoc cColonloc, -+ BridgedSourceLoc cRSquareLoc) { -+ ASTContext &context = convertASTContext(cContext); -+ SourceLoc lSquareLoc = convertSourceLoc(cLSquareLoc); -+ SourceLoc colonLoc = convertSourceLoc(cColonloc); -+ SourceLoc rSquareLoc = convertSourceLoc(cRSquareLoc); -+ return new (context) - DictionaryTypeRepr((TypeRepr *)keyType, (TypeRepr *)valueType, colonLoc, - SourceRange{lSquareLoc, rSquareLoc}); - } - --void *MetatypeTypeRepr_create(void *ctx, void *baseType, void *typeLoc) { -- ASTContext &Context = *static_cast(ctx); -- SourceLoc tyLoc = getSourceLocFromPointer(typeLoc); -- return new (Context) MetatypeTypeRepr((TypeRepr *)baseType, tyLoc); -+void *MetatypeTypeRepr_create(BridgedASTContext cContext, void *baseType, -+ BridgedSourceLoc cTypeLoc) { -+ ASTContext &context = convertASTContext(cContext); -+ SourceLoc tyLoc = convertSourceLoc(cTypeLoc); -+ return new (context) MetatypeTypeRepr((TypeRepr *)baseType, tyLoc); - } - --void *ProtocolTypeRepr_create(void *ctx, void *baseType, void *protoLoc) { -- ASTContext &Context = *static_cast(ctx); -- SourceLoc protocolLoc = getSourceLocFromPointer(protoLoc); -- return new (Context) ProtocolTypeRepr((TypeRepr *)baseType, protocolLoc); -+void *ProtocolTypeRepr_create(BridgedASTContext cContext, void *baseType, -+ BridgedSourceLoc cProtoLoc) { -+ ASTContext &context = convertASTContext(cContext); -+ SourceLoc protoLoc = convertSourceLoc(cProtoLoc); -+ return new (context) ProtocolTypeRepr((TypeRepr *)baseType, protoLoc); - } - --void *PackExpansionTypeRepr_create(void *ctx, void *base, void *repeatLoc) { -- ASTContext &Context = *static_cast(ctx); -- return new (Context) PackExpansionTypeRepr( -- getSourceLocFromPointer(repeatLoc), (TypeRepr *)base); -+void *PackExpansionTypeRepr_create(BridgedASTContext cContext, void *base, -+ BridgedSourceLoc cRepeatLoc) { -+ ASTContext &context = convertASTContext(cContext); -+ return new (context) -+ PackExpansionTypeRepr(convertSourceLoc(cRepeatLoc), (TypeRepr *)base); - } - --static BridgedTypeAttrKind bridgeTypeAttrKind(TypeAttrKind kind) { -+BridgedTypeAttrKind TypeAttrKind_fromString(BridgedString cStr) { -+ TypeAttrKind kind = -+ TypeAttributes::getAttrKindFromString(convertString(cStr)); - switch (kind) { - #define TYPE_ATTR(X) case TAK_##X: return BridgedTypeAttrKind_##X; - #include "swift/AST/Attr.def" -@@ -501,212 +573,217 @@ static BridgedTypeAttrKind bridgeTypeAttrKind(TypeAttrKind kind) { - } - } - --static TypeAttrKind bridgeTypeAttrKind(BridgedTypeAttrKind kind) { -- switch (kind) { --#define TYPE_ATTR(X) case BridgedTypeAttrKind_##X: return TAK_##X; --#include "swift/AST/Attr.def" -- case BridgedTypeAttrKind_Count: return TAK_Count; -- } --} -- --BridgedTypeAttrKind getBridgedTypeAttrKindFromString( -- const unsigned char *str, intptr_t len) { -- return bridgeTypeAttrKind( -- TypeAttributes::getAttrKindFromString(StringRef((const char *)str, len))); --} -+BridgedTypeAttributes TypeAttributes_create() { return {new TypeAttributes()}; } - --BridgedTypeAttributes BridgedTypeAttributes_create() { -- return new TypeAttributes(); --} -- --void BridgedTypeAttributes_addSimpleAttr( -- BridgedTypeAttributes typeAttributesPtr, BridgedTypeAttrKind kind, -- void *atLoc, void *attrLoc --) { -- TypeAttributes *typeAttributes = (TypeAttributes *)typeAttributesPtr; -- typeAttributes->setAttr( -- bridgeTypeAttrKind(kind), getSourceLocFromPointer(attrLoc)); -+void TypeAttributes_addSimpleAttr(BridgedTypeAttributes cAttributes, -+ BridgedTypeAttrKind cKind, -+ BridgedSourceLoc cAtLoc, -+ BridgedSourceLoc cAttrLoc) { -+ TypeAttributes *typeAttributes = convertTypeAttributes(cAttributes); -+ typeAttributes->setAttr(convertTypeAttrKind(cKind), -+ convertSourceLoc(cAttrLoc)); - if (typeAttributes->AtLoc.isInvalid()) -- typeAttributes->AtLoc = getSourceLocFromPointer(atLoc); -+ typeAttributes->AtLoc = convertSourceLoc(cAtLoc); - } - --void *AttributedTypeRepr_create( -- void *ctx, void *base, BridgedTypeAttributes typeAttributesPtr) { -- TypeAttributes *typeAttributes = (TypeAttributes *)typeAttributesPtr; -+void *AttributedTypeRepr_create(BridgedASTContext cContext, void *base, -+ BridgedTypeAttributes cAttributes) { -+ TypeAttributes *typeAttributes = convertTypeAttributes(cAttributes); - if (typeAttributes->empty()) - return base; - -- ASTContext &Context = *static_cast(ctx); -+ ASTContext &context = convertASTContext(cContext); - auto attributedType = -- new (Context) AttributedTypeRepr(*typeAttributes, (TypeRepr *)base); -+ new (context) AttributedTypeRepr(*typeAttributes, (TypeRepr *)base); - delete typeAttributes; - return attributedType; - } - --void *AttributedTypeSpecifierRepr_create( -- void *ctx, void *base, BridgedAttributedTypeSpecifier specifier, void *specifierLoc --) { -- ASTContext &Context = *static_cast(ctx); -- SourceLoc loc = getSourceLocFromPointer(specifierLoc); -+void * -+AttributedTypeSpecifierRepr_create(BridgedASTContext cContext, void *base, -+ BridgedAttributedTypeSpecifier specifier, -+ BridgedSourceLoc cSpecifierLoc) { -+ ASTContext &context = convertASTContext(cContext); -+ SourceLoc loc = convertSourceLoc(cSpecifierLoc); - TypeRepr *baseType = (TypeRepr *)base; - switch (specifier) { - case BridgedAttributedTypeSpecifierInOut: -- return new (Context) OwnershipTypeRepr(baseType, ParamSpecifier::InOut, loc); -+ return new (context) -+ OwnershipTypeRepr(baseType, ParamSpecifier::InOut, loc); - case BridgedAttributedTypeSpecifierBorrowing: -- return new (Context) OwnershipTypeRepr(baseType, ParamSpecifier::Borrowing, loc); -+ return new (context) -+ OwnershipTypeRepr(baseType, ParamSpecifier::Borrowing, loc); - case BridgedAttributedTypeSpecifierConsuming: -- return new (Context) OwnershipTypeRepr(baseType, ParamSpecifier::Consuming, loc); -+ return new (context) -+ OwnershipTypeRepr(baseType, ParamSpecifier::Consuming, loc); - case BridgedAttributedTypeSpecifierLegacyShared: -- return new (Context) OwnershipTypeRepr(baseType, ParamSpecifier::LegacyShared, loc); -+ return new (context) -+ OwnershipTypeRepr(baseType, ParamSpecifier::LegacyShared, loc); - case BridgedAttributedTypeSpecifierLegacyOwned: -- return new (Context) OwnershipTypeRepr(baseType, ParamSpecifier::LegacyOwned, loc); -+ return new (context) -+ OwnershipTypeRepr(baseType, ParamSpecifier::LegacyOwned, loc); - case BridgedAttributedTypeSpecifierConst: -- return new (Context) CompileTimeConstTypeRepr(baseType, loc); -+ return new (context) CompileTimeConstTypeRepr(baseType, loc); - case BridgedAttributedTypeSpecifierIsolated: -- return new (Context) IsolatedTypeRepr(baseType, loc); -+ return new (context) IsolatedTypeRepr(baseType, loc); - } - } - --void *VarargTypeRepr_create(void *ctx, void *base, void *ellipsisLocPtr) { -- ASTContext &Context = *static_cast(ctx); -- SourceLoc ellipsisLoc = getSourceLocFromPointer(ellipsisLocPtr); -+void *VarargTypeRepr_create(BridgedASTContext cContext, void *base, -+ BridgedSourceLoc cEllipsisLoc) { -+ ASTContext &context = convertASTContext(cContext); -+ SourceLoc ellipsisLoc = convertSourceLoc(cEllipsisLoc); - TypeRepr *baseType = (TypeRepr *)base; -- return new (Context) VarargTypeRepr(baseType, ellipsisLoc); -+ return new (context) VarargTypeRepr(baseType, ellipsisLoc); - } - --void *TupleTypeRepr_create(void *ctx, BridgedArrayRef elements, void *lParenLoc, -- void *rParenLoc) { -- ASTContext &Context = *static_cast(ctx); -- SourceLoc lParen = getSourceLocFromPointer(lParenLoc); -- SourceLoc rParen = getSourceLocFromPointer(rParenLoc); -+void *TupleTypeRepr_create(BridgedASTContext cContext, BridgedArrayRef elements, -+ BridgedSourceLoc cLParenLoc, -+ BridgedSourceLoc cRParenLoc) { -+ ASTContext &context = convertASTContext(cContext); -+ SourceLoc lParen = convertSourceLoc(cLParenLoc); -+ SourceLoc rParen = convertSourceLoc(cRParenLoc); -+ - SmallVector tupleElements; -- for (auto element : getArrayRef(elements)) { -+ for (auto element : convertArrayRef(elements)) { - TupleTypeReprElement elementRepr; -- elementRepr.Name = Identifier::getFromOpaquePointer(element.Name); -- elementRepr.NameLoc = getSourceLocFromPointer(element.NameLoc); -- elementRepr.SecondName = -- Identifier::getFromOpaquePointer(element.SecondName); -- elementRepr.SecondNameLoc = getSourceLocFromPointer(element.SecondNameLoc); -- elementRepr.UnderscoreLoc = getSourceLocFromPointer(element.UnderscoreLoc); -- elementRepr.ColonLoc = getSourceLocFromPointer(element.ColonLoc); -+ elementRepr.Name = convertIdentifier(element.Name); -+ elementRepr.NameLoc = convertSourceLoc(element.NameLoc); -+ elementRepr.SecondName = convertIdentifier(element.SecondName); -+ elementRepr.SecondNameLoc = convertSourceLoc(element.SecondNameLoc); -+ elementRepr.UnderscoreLoc = convertSourceLoc(element.UnderscoreLoc); -+ elementRepr.ColonLoc = convertSourceLoc(element.ColonLoc); - elementRepr.Type = (TypeRepr *)element.Type; -- elementRepr.TrailingCommaLoc = -- getSourceLocFromPointer(element.TrailingCommaLoc); -+ elementRepr.TrailingCommaLoc = convertSourceLoc(element.TrailingCommaLoc); - tupleElements.emplace_back(elementRepr); - } - -- return TupleTypeRepr::create(Context, tupleElements, -+ return TupleTypeRepr::create(context, tupleElements, - SourceRange{lParen, rParen}); - } - --void *MemberTypeRepr_create(void *ctx, void *baseComponent, -+void *MemberTypeRepr_create(BridgedASTContext cContext, void *baseComponent, - BridgedArrayRef bridgedMemberComponents) { -- ASTContext &Context = *static_cast(ctx); -- auto memberComponents = getArrayRef(bridgedMemberComponents); -+ ASTContext &context = convertASTContext(cContext); -+ auto memberComponents = -+ convertArrayRef(bridgedMemberComponents); - -- return MemberTypeRepr::create(Context, (TypeRepr *)baseComponent, -+ return MemberTypeRepr::create(context, (TypeRepr *)baseComponent, - memberComponents); - } - --void *EmptyCompositionTypeRepr_create(void *ctx, void *anyLocPtr) { -- ASTContext &Context = *static_cast(ctx); -- SourceLoc anyLoc = getSourceLocFromPointer(anyLocPtr); -- return CompositionTypeRepr::createEmptyComposition(Context, anyLoc); -+void *EmptyCompositionTypeRepr_create(BridgedASTContext cContext, -+ BridgedSourceLoc cAnyLoc) { -+ ASTContext &context = convertASTContext(cContext); -+ SourceLoc anyLoc = convertSourceLoc(cAnyLoc); -+ return CompositionTypeRepr::createEmptyComposition(context, anyLoc); - } - --void *CompositionTypeRepr_create(void *ctx, BridgedArrayRef typesPtr, -- void *firstTypeLoc, void *firstAmpLocPtr) { -- ASTContext &Context = *static_cast(ctx); -- SourceLoc firstType = getSourceLocFromPointer(firstTypeLoc); -- SourceLoc firstAmpLoc = getSourceLocFromPointer(firstAmpLocPtr); -- auto types = getArrayRef(typesPtr); -+void *CompositionTypeRepr_create(BridgedASTContext cContext, -+ BridgedArrayRef cTypes, -+ BridgedSourceLoc cFirstTypeLoc, -+ BridgedSourceLoc cFirstAmpLoc) { -+ ASTContext &context = convertASTContext(cContext); -+ SourceLoc firstTypeLoc = convertSourceLoc(cFirstTypeLoc); -+ SourceLoc firstAmpLoc = convertSourceLoc(cFirstAmpLoc); -+ auto types = convertArrayRef(cTypes); - return CompositionTypeRepr::create( -- Context, types, firstType, -+ context, types, firstTypeLoc, - SourceRange{firstAmpLoc, types.back()->getEndLoc()}); - } - --void *FunctionTypeRepr_create(void *ctx, void *argsTy, void *_Nullable asyncLoc, -- void *_Nullable throwsLoc, void *arrowLoc, -- void *returnType) { -- ASTContext &Context = *static_cast(ctx); -- return new (Context) FunctionTypeRepr( -- nullptr, (TupleTypeRepr *)argsTy, getSourceLocFromPointer(asyncLoc), -- getSourceLocFromPointer(throwsLoc), getSourceLocFromPointer(arrowLoc), -+void *FunctionTypeRepr_create(BridgedASTContext cContext, void *argsTy, -+ BridgedSourceLoc cAsyncLoc, -+ BridgedSourceLoc cThrowsLoc, -+ BridgedSourceLoc cArrowLoc, void *returnType) { -+ ASTContext &context = convertASTContext(cContext); -+ return new (context) FunctionTypeRepr( -+ nullptr, (TupleTypeRepr *)argsTy, convertSourceLoc(cAsyncLoc), -+ convertSourceLoc(cThrowsLoc), convertSourceLoc(cArrowLoc), - (TypeRepr *)returnType); - } - --void *NamedOpaqueReturnTypeRepr_create(void *ctx, void *baseTy) { -- ASTContext &Context = *static_cast(ctx); -- return new (Context) NamedOpaqueReturnTypeRepr((TypeRepr *)baseTy, nullptr); -+void *NamedOpaqueReturnTypeRepr_create(BridgedASTContext cContext, -+ void *baseTy) { -+ ASTContext &context = convertASTContext(cContext); -+ return new (context) NamedOpaqueReturnTypeRepr((TypeRepr *)baseTy, nullptr); - } - --void *OpaqueReturnTypeRepr_create(void *ctx, void *opaqueLoc, void *baseTy) { -- ASTContext &Context = *static_cast(ctx); -- return new (Context) OpaqueReturnTypeRepr(getSourceLocFromPointer(opaqueLoc), -- (TypeRepr *)baseTy); -+void *OpaqueReturnTypeRepr_create(BridgedASTContext cContext, -+ BridgedSourceLoc cOpaqueLoc, void *baseTy) { -+ ASTContext &context = convertASTContext(cContext); -+ return new (context) -+ OpaqueReturnTypeRepr(convertSourceLoc(cOpaqueLoc), (TypeRepr *)baseTy); - } --void *ExistentialTypeRepr_create(void *ctx, void *anyLoc, void *baseTy) { -- ASTContext &Context = *static_cast(ctx); -- return new (Context) -- ExistentialTypeRepr(getSourceLocFromPointer(anyLoc), (TypeRepr *)baseTy); -+void *ExistentialTypeRepr_create(BridgedASTContext cContext, -+ BridgedSourceLoc cAnyLoc, void *baseTy) { -+ ASTContext &context = convertASTContext(cContext); -+ return new (context) -+ ExistentialTypeRepr(convertSourceLoc(cAnyLoc), (TypeRepr *)baseTy); - } - --void *GenericParamList_create(void *ctx, void *lAngleLoc, -- BridgedArrayRef params, void *_Nullable whereLoc, -- BridgedArrayRef reqs, void *rAngleLoc) { -- ASTContext &Context = *static_cast(ctx); -+void *GenericParamList_create(BridgedASTContext cContext, -+ BridgedSourceLoc cLAngleLoc, -+ BridgedArrayRef params, -+ BridgedSourceLoc cWhereLoc, BridgedArrayRef reqs, -+ BridgedSourceLoc cRAngleLoc) { -+ ASTContext &context = convertASTContext(cContext); - SmallVector requirements; -- for (auto req : getArrayRef(reqs)) { -+ for (auto req : convertArrayRef(reqs)) { - switch (req.Kind) { - case BridgedRequirementReprKindTypeConstraint: - requirements.push_back(RequirementRepr::getTypeConstraint( -- (TypeRepr *)req.FirstType, getSourceLocFromPointer(req.SeparatorLoc), -- (TypeRepr *)req.SecondType, /*isExpansionPattern*/false)); -+ (TypeRepr *)req.FirstType, convertSourceLoc(req.SeparatorLoc), -+ (TypeRepr *)req.SecondType, /*isExpansionPattern*/ false)); - break; - case BridgedRequirementReprKindSameType: - requirements.push_back(RequirementRepr::getSameType( -- (TypeRepr *)req.FirstType, getSourceLocFromPointer(req.SeparatorLoc), -- (TypeRepr *)req.SecondType, /*isExpansionPattern*/false)); -+ (TypeRepr *)req.FirstType, convertSourceLoc(req.SeparatorLoc), -+ (TypeRepr *)req.SecondType, /*isExpansionPattern*/ false)); - break; - case BridgedRequirementReprKindLayoutConstraint: - llvm_unreachable("cannot handle layout constraints!"); - } - } -- return GenericParamList::create(Context, getSourceLocFromPointer(lAngleLoc), -- getArrayRef(params), -- getSourceLocFromPointer(whereLoc), -- requirements, -- getSourceLocFromPointer(rAngleLoc)); -+ return GenericParamList::create( -+ context, convertSourceLoc(cLAngleLoc), -+ convertArrayRef(params), -+ convertSourceLoc(cWhereLoc), requirements, convertSourceLoc(cRAngleLoc)); - } - --void *GenericTypeParamDecl_create(void *ctx, void *declContext, -- BridgedIdentifier name, void *nameLoc, -- void *_Nullable eachLoc, SwiftInt index, -+void *GenericTypeParamDecl_create(BridgedASTContext cContext, -+ BridgedDeclContext cDeclContext, -+ BridgedIdentifier name, -+ BridgedSourceLoc cNameLoc, -+ BridgedSourceLoc cEachLoc, SwiftInt index, - bool isParameterPack) { - return GenericTypeParamDecl::createParsed( -- static_cast(declContext), -- Identifier::getFromOpaquePointer(name), getSourceLocFromPointer(nameLoc), -- getSourceLocFromPointer(eachLoc), -+ convertDeclContext(cDeclContext), convertIdentifier(name), -+ convertSourceLoc(cNameLoc), convertSourceLoc(cEachLoc), - /*index*/ index, isParameterPack); - } - --void GenericTypeParamDecl_setInheritedType(void *ctx, void *Param, void *ty) { -- ASTContext &Context = *static_cast(ctx); -- auto entries = Context.AllocateCopy( -+void GenericTypeParamDecl_setInheritedType(BridgedASTContext cContext, -+ void *param, void *ty) { -+ ASTContext &context = convertASTContext(cContext); -+ auto entries = context.AllocateCopy( - ArrayRef{InheritedEntry{(TypeRepr *)ty}}); -- ((GenericTypeParamDecl *)Param)->setInherited(entries); -+ ((GenericTypeParamDecl *)param)->setInherited(entries); - } - --DeclContextAndDecl TypeAliasDecl_create(void *ctx, void *declContext, -- void *aliasLoc, void *equalLoc, -- BridgedIdentifier name, void *nameLoc, -- void *_Nullable genericParams) { -- ASTContext &Context = *static_cast(ctx); -- auto *out = new (Context) TypeAliasDecl( -- getSourceLocFromPointer(aliasLoc), getSourceLocFromPointer(equalLoc), -- Identifier::getFromOpaquePointer(name), getSourceLocFromPointer(nameLoc), -- (GenericParamList *)genericParams, (DeclContext *)declContext); -- return {(DeclContext *)out, (TypeAliasDecl *)out, (Decl *)out}; -+BridgedDeclContextAndDecl TypeAliasDecl_create(BridgedASTContext cContext, -+ BridgedDeclContext cDeclContext, -+ BridgedSourceLoc cAliasLoc, -+ BridgedSourceLoc cEqualLoc, -+ BridgedIdentifier name, -+ BridgedSourceLoc cNameLoc, -+ void *_Nullable genericParams) { -+ ASTContext &context = convertASTContext(cContext); -+ auto *out = new (context) TypeAliasDecl( -+ convertSourceLoc(cAliasLoc), convertSourceLoc(cEqualLoc), -+ convertIdentifier(name), convertSourceLoc(cNameLoc), -+ (GenericParamList *)genericParams, convertDeclContext(cDeclContext)); -+ return {BridgedDeclContext{out}, (TypeAliasDecl *)out, (Decl *)out}; - } - - void TypeAliasDecl_setUnderlyingTypeRepr(void *decl, void *underlyingType) { -@@ -717,13 +794,14 @@ void TypeAliasDecl_setUnderlyingTypeRepr(void *decl, void *underlyingType) { - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - - void TopLevelCodeDecl_dump(void *decl) { -- ((TopLevelCodeDecl *)decl)->dump(llvm::errs()); -+ static_cast(decl)->dump(llvm::errs()); - } -- --void Expr_dump(void *expr) { ((Expr *)expr)->dump(llvm::errs()); } --void Decl_dump(void *expr) { ((Decl *)expr)->dump(llvm::errs()); } --void Stmt_dump(void *expr) { ((Stmt *)expr)->dump(llvm::errs()); } --void Type_dump(void *expr) { ((TypeRepr *)expr)->dump(); } -+void Expr_dump(void *expr) { static_cast(expr)->dump(llvm::errs()); } -+void Decl_dump(void *decl) { static_cast(decl)->dump(llvm::errs()); } -+void Stmt_dump(void *statement) { -+ static_cast(statement)->dump(llvm::errs()); -+} -+void Type_dump(void *type) { static_cast(type)->dump(); } - - #pragma clang diagnostic pop - -diff --git a/swift/lib/ASTGen/Sources/ASTGen/ASTGen.swift b/swift/lib/ASTGen/Sources/ASTGen/ASTGen.swift -index 4aa3321190403..5cfedde85a4d6 100644 ---- a/swift/lib/ASTGen/Sources/ASTGen/ASTGen.swift -+++ b/swift/lib/ASTGen/Sources/ASTGen/ASTGen.swift -@@ -38,14 +38,14 @@ enum ASTNode { - } - } - -- func bridged() -> ASTNodeBridged { -+ var bridged: BridgedASTNode { - switch self { - case .expr(let e): -- return ASTNodeBridged(ptr: e, kind: .expr) -+ return BridgedASTNode(ptr: e, kind: .expr) - case .stmt(let s): -- return ASTNodeBridged(ptr: s, kind: .stmt) -+ return BridgedASTNode(ptr: s, kind: .stmt) - case .decl(let d): -- return ASTNodeBridged(ptr: d, kind: .decl) -+ return BridgedASTNode(ptr: d, kind: .decl) - default: - fatalError("Must be expr, stmt, or decl.") - } -@@ -66,10 +66,10 @@ class Boxed { - struct ASTGenVisitor: SyntaxTransformVisitor { - typealias ResultType = ASTNode - -- let ctx: UnsafeMutableRawPointer -- let base: UnsafePointer -+ let ctx: BridgedASTContext -+ let base: UnsafeBufferPointer - -- @Boxed var declContext: UnsafeMutableRawPointer -+ @Boxed var declContext: BridgedDeclContext - - // TODO: this some how messes up the witness table when I uncomment it locally :/ - // public func visit(_ node: T?) -> [UnsafeMutableRawPointer]? { -@@ -90,15 +90,15 @@ struct ASTGenVisitor: SyntaxTransformVisitor { - var out = [UnsafeMutableRawPointer]() - - for element in node.statements { -- let loc = self.base.advanced(by: element.position.utf8Offset).raw -+ let loc = bridgedSourceLoc(for: element) - let swiftASTNodes = visit(element) - switch swiftASTNodes { - case .decl(let d): - out.append(d) - case .stmt(let s): -- out.append(SwiftTopLevelCodeDecl_createStmt(ctx, declContext, loc, s, loc)) -+ out.append(TopLevelCodeDecl_createStmt(ctx, declContext, loc, s, loc)) - case .expr(let e): -- out.append(SwiftTopLevelCodeDecl_createExpr(ctx, declContext, loc, e, loc)) -+ out.append(TopLevelCodeDecl_createExpr(ctx, declContext, loc, e, loc)) - default: - fatalError("Top level nodes must be decls, stmts, or exprs.") - } -@@ -118,7 +118,7 @@ public func buildTopLevelASTNodes( - callback: @convention(c) (UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Void - ) { - sourceFilePtr.withMemoryRebound(to: ExportedSourceFile.self, capacity: 1) { sourceFile in -- ASTGenVisitor(ctx: ctx, base: sourceFile.pointee.buffer.baseAddress!, declContext: dc) -+ ASTGenVisitor(ctx: BridgedASTContext(raw: ctx), base: sourceFile.pointee.buffer, declContext: BridgedDeclContext(raw: dc)) - .visit(sourceFile.pointee.syntax) - .forEach { callback($0, outputContext) } - } -diff --git a/swift/lib/ASTGen/Sources/ASTGen/Decls.swift b/swift/lib/ASTGen/Sources/ASTGen/Decls.swift -index 815bb696b137b..d1f60d3a94df3 100644 ---- a/swift/lib/ASTGen/Sources/ASTGen/Decls.swift -+++ b/swift/lib/ASTGen/Sources/ASTGen/Decls.swift -@@ -4,13 +4,13 @@ import SwiftSyntax - - extension ASTGenVisitor { - public func visit(_ node: TypealiasDeclSyntax) -> ASTNode { -- let aliasLoc = self.base.advanced(by: node.typealiasKeyword.position.utf8Offset).raw -- let equalLoc = self.base.advanced(by: node.initializer.equal.position.utf8Offset).raw -+ let aliasLoc = bridgedSourceLoc(for: node.typealiasKeyword) -+ let equalLoc = bridgedSourceLoc(for: node.initializer.equal) - var nameText = node.identifier.text -- let name = nameText.withUTF8 { buf in -- return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, SwiftInt(buf.count)) -+ let name = nameText.withBridgedString { bridgedName in -+ return ASTContext_getIdentifier(ctx, bridgedName) - } -- let nameLoc = self.base.advanced(by: node.identifier.position.utf8Offset).raw -+ let nameLoc = bridgedSourceLoc(for: node.identifier) - let genericParams = node.genericParameterClause.map { self.visit($0).rawValue } - let out = TypeAliasDecl_create( - self.ctx, self.declContext, aliasLoc, equalLoc, name, nameLoc, genericParams) -@@ -26,10 +26,10 @@ extension ASTGenVisitor { - } - - public func visit(_ node: StructDeclSyntax) -> ASTNode { -- let loc = self.base.advanced(by: node.position.utf8Offset).raw -+ let loc = bridgedSourceLoc(for: node) - var nameText = node.identifier.text -- let name = nameText.withUTF8 { buf in -- return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, SwiftInt(buf.count)) -+ let name = nameText.withBridgedString { bridgedName in -+ return ASTContext_getIdentifier(ctx, bridgedName) - } - - let genericParams = node.genericParameterClause -@@ -49,10 +49,10 @@ extension ASTGenVisitor { - } - - public func visit(_ node: ClassDeclSyntax) -> ASTNode { -- let loc = self.base.advanced(by: node.position.utf8Offset).raw -+ let loc = bridgedSourceLoc(for: node) - var nameText = node.identifier.text -- let name = nameText.withUTF8 { buf in -- return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, SwiftInt(buf.count)) -+ let name = nameText.withBridgedString { bridgedName in -+ return ASTContext_getIdentifier(ctx, bridgedName) - } - - let out = ClassDecl_create(ctx, loc, name, loc, declContext) -@@ -73,29 +73,29 @@ extension ASTGenVisitor { - let pattern = visit(node.bindings.first!.pattern).rawValue - let initializer = visit(node.bindings.first!.initializer!).rawValue - -- let loc = self.base.advanced(by: node.position.utf8Offset).raw -+ let loc = bridgedSourceLoc(for: node) - let isStatic = false // TODO: compute this - let isLet = node.bindingKeyword.tokenKind == .keyword(.let) - - // TODO: don't drop "initializer" on the floor. - return .decl( -- SwiftVarDecl_create( -+ VarDecl_create( - ctx, pattern, initializer, loc, isStatic, - isLet, declContext)) - } - - public func visit(_ node: FunctionParameterSyntax) -> ASTNode { -- let loc = self.base.advanced(by: node.position.utf8Offset).raw -+ let loc = bridgedSourceLoc(for: node) -+ -+ let firstName: BridgedIdentifier -+ let secondName: BridgedIdentifier - -- let firstName: UnsafeMutableRawPointer? -- let secondName: UnsafeMutableRawPointer? -- - let nodeFirstName = node.firstName - if nodeFirstName.text != "_" { - // Swift AST represents "_" as nil. - var text = nodeFirstName.text -- firstName = text.withUTF8 { buf in -- SwiftASTContext_getIdentifier(ctx, buf.baseAddress, SwiftInt(buf.count)) -+ firstName = text.withBridgedString { bridgedName in -+ ASTContext_getIdentifier(ctx, bridgedName) - } - } else { - firstName = nil -@@ -103,8 +103,8 @@ extension ASTGenVisitor { - - if let nodeSecondName = node.secondName { - var text = nodeSecondName.text -- secondName = text.withUTF8 { buf in -- SwiftASTContext_getIdentifier(ctx, buf.baseAddress, SwiftInt(buf.count)) -+ secondName = text.withBridgedString { bridgedName in -+ ASTContext_getIdentifier(ctx, bridgedName) - } - } else { - secondName = nil -@@ -116,15 +116,15 @@ extension ASTGenVisitor { - } - - public func visit(_ node: FunctionDeclSyntax) -> ASTNode { -- let staticLoc = self.base.advanced(by: node.position.utf8Offset).raw -- let funcLoc = self.base.advanced(by: node.funcKeyword.position.utf8Offset).raw -- let nameLoc = self.base.advanced(by: node.identifier.position.utf8Offset).raw -- let rParamLoc = self.base.advanced(by: node.signature.input.leftParen.position.utf8Offset).raw -- let lParamLoc = self.base.advanced(by: node.signature.input.rightParen.position.utf8Offset).raw -+ let staticLoc = bridgedSourceLoc(for: node) -+ let funcLoc = bridgedSourceLoc(for: node.funcKeyword) -+ let nameLoc = bridgedSourceLoc(for: node.identifier) -+ let rParamLoc = bridgedSourceLoc(for: node.signature.input.leftParen) -+ let lParamLoc = bridgedSourceLoc(for: node.signature.input.rightParen) - - var nameText = node.identifier.text -- let name = nameText.withUTF8 { buf in -- return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, SwiftInt(buf.count)) -+ let name = nameText.withBridgedString { bridgedName in -+ return ASTContext_getIdentifier(ctx, bridgedName) - } - - let returnType: ASTNode? -diff --git a/swift/lib/ASTGen/Sources/ASTGen/Diagnostics.swift b/swift/lib/ASTGen/Sources/ASTGen/Diagnostics.swift -index 7071029c43983..4d299cc6f19eb 100644 ---- a/swift/lib/ASTGen/Sources/ASTGen/Diagnostics.swift -+++ b/swift/lib/ASTGen/Sources/ASTGen/Diagnostics.swift -@@ -4,13 +4,15 @@ import SwiftSyntax - - fileprivate func emitDiagnosticParts( - diagEnginePtr: UnsafeMutablePointer, -- sourceFileBuffer: UnsafeMutableBufferPointer, -+ sourceFileBuffer: UnsafeBufferPointer, - message: String, - severity: DiagnosticSeverity, - position: AbsolutePosition, - highlights: [Syntax] = [], - fixItChanges: [FixIt.Change] = [] - ) { -+ let bridgedDiagEngine = BridgedDiagnosticEngine(raw: diagEnginePtr) -+ - // Map severity - let bridgedSeverity: BridgedDiagnosticSeverity - switch severity { -@@ -19,75 +21,66 @@ fileprivate func emitDiagnosticParts( - case .warning: bridgedSeverity = .warning - } - -- // Form a source location for the given absolute position -- func sourceLoc( -- at position: AbsolutePosition -- ) -> UnsafeMutablePointer? { -- if let sourceFileBase = sourceFileBuffer.baseAddress, -- position.utf8Offset >= 0 && -- position.utf8Offset < sourceFileBuffer.count { -- return sourceFileBase + position.utf8Offset -- } -- -- return nil -+ func bridgedSourceLoc(at position: AbsolutePosition) -> BridgedSourceLoc { -+ return BridgedSourceLoc(at: position, in: sourceFileBuffer) - } - - // Emit the diagnostic - var mutableMessage = message -- let diag = mutableMessage.withUTF8 { messageBuffer in -- SwiftDiagnostic_create( -- diagEnginePtr, bridgedSeverity, sourceLoc(at: position), -- messageBuffer.baseAddress, SwiftInt(messageBuffer.count) -+ let diag = mutableMessage.withBridgedString { bridgedMessage in -+ Diagnostic_create( -+ bridgedDiagEngine, bridgedSeverity, bridgedSourceLoc(at: position), -+ bridgedMessage - ) - } - - // Emit highlights - for highlight in highlights { -- SwiftDiagnostic_highlight( -- diag, sourceLoc(at: highlight.positionAfterSkippingLeadingTrivia), -- sourceLoc(at: highlight.endPositionBeforeTrailingTrivia) -+ Diagnostic_highlight( -+ diag, bridgedSourceLoc(at: highlight.positionAfterSkippingLeadingTrivia), -+ bridgedSourceLoc(at: highlight.endPositionBeforeTrailingTrivia) - ) - } - - // Emit changes for a Fix-It. - for change in fixItChanges { -- let replaceStartLoc: UnsafeMutablePointer? -- let replaceEndLoc: UnsafeMutablePointer? -+ let replaceStartLoc: BridgedSourceLoc -+ let replaceEndLoc: BridgedSourceLoc - var newText: String - - switch change { - case .replace(let oldNode, let newNode): -- replaceStartLoc = sourceLoc(at: oldNode.position) -- replaceEndLoc = sourceLoc(at: oldNode.endPosition) -+ replaceStartLoc = bridgedSourceLoc(at: oldNode.position) -+ replaceEndLoc = bridgedSourceLoc(at: oldNode.endPosition) - newText = newNode.description - - case .replaceLeadingTrivia(let oldToken, let newTrivia): -- replaceStartLoc = sourceLoc(at: oldToken.position) -- replaceEndLoc = sourceLoc( -+ replaceStartLoc = bridgedSourceLoc(at: oldToken.position) -+ replaceEndLoc = bridgedSourceLoc( - at: oldToken.positionAfterSkippingLeadingTrivia) - newText = newTrivia.description - - case .replaceTrailingTrivia(let oldToken, let newTrivia): -- replaceStartLoc = sourceLoc(at: oldToken.endPositionBeforeTrailingTrivia) -- replaceEndLoc = sourceLoc(at: oldToken.endPosition) -+ replaceStartLoc = bridgedSourceLoc(at: oldToken.endPositionBeforeTrailingTrivia) -+ replaceEndLoc = bridgedSourceLoc(at: oldToken.endPosition) - newText = newTrivia.description - } - -- newText.withUTF8 { textBuffer in -- SwiftDiagnostic_fixItReplace( -+ newText.withBridgedString { bridgedMessage in -+ Diagnostic_fixItReplace( - diag, replaceStartLoc, replaceEndLoc, -- textBuffer.baseAddress, SwiftInt(textBuffer.count) -+ bridgedMessage - ) - } - } - -- SwiftDiagnostic_finish(diag); -+ Diagnostic_finish(diag); - } - - /// Emit the given diagnostic via the diagnostic engine. - func emitDiagnostic( - diagEnginePtr: UnsafeMutablePointer, -- sourceFileBuffer: UnsafeMutableBufferPointer, -+ sourceFileBuffer: UnsafeBufferPointer, - diagnostic: Diagnostic, - diagnosticSeverity: DiagnosticSeverity, - messageSuffix: String? = nil -@@ -145,69 +138,69 @@ extension SourceManager { - - // Emit the diagnostic - var mutableMessage = message -- let diag = mutableMessage.withUTF8 { messageBuffer in -- SwiftDiagnostic_create( -- cxxDiagnosticEngine, bridgedSeverity, -- cxxSourceLocation(for: node, at: position), -- messageBuffer.baseAddress, SwiftInt(messageBuffer.count) -+ let diag = mutableMessage.withBridgedString { bridgedMessage in -+ Diagnostic_create( -+ bridgedDiagEngine, bridgedSeverity, -+ bridgedSourceLoc(for: node, at: position), -+ bridgedMessage - ) - } - - // Emit highlights - for highlight in highlights { -- SwiftDiagnostic_highlight( -+ Diagnostic_highlight( - diag, -- cxxSourceLocation(for: highlight, at: highlight.positionAfterSkippingLeadingTrivia), -- cxxSourceLocation(for: highlight, at: highlight.endPositionBeforeTrailingTrivia) -+ bridgedSourceLoc(for: highlight, at: highlight.positionAfterSkippingLeadingTrivia), -+ bridgedSourceLoc(for: highlight, at: highlight.endPositionBeforeTrailingTrivia) - ) - } - - // Emit changes for a Fix-It. - for change in fixItChanges { -- let replaceStartLoc: CxxSourceLoc? -- let replaceEndLoc: CxxSourceLoc? -+ let replaceStartLoc: BridgedSourceLoc -+ let replaceEndLoc: BridgedSourceLoc - var newText: String - - switch change { - case .replace(let oldNode, let newNode): -- replaceStartLoc = cxxSourceLocation( -+ replaceStartLoc = bridgedSourceLoc( - for: oldNode, - at: oldNode.positionAfterSkippingLeadingTrivia - ) -- replaceEndLoc = cxxSourceLocation( -+ replaceEndLoc = bridgedSourceLoc( - for: oldNode, - at: oldNode.endPositionBeforeTrailingTrivia - ) - newText = newNode.description - - case .replaceLeadingTrivia(let oldToken, let newTrivia): -- replaceStartLoc = cxxSourceLocation(for: oldToken) -- replaceEndLoc = cxxSourceLocation( -+ replaceStartLoc = bridgedSourceLoc(for: oldToken) -+ replaceEndLoc = bridgedSourceLoc( - for: oldToken, - at: oldToken.positionAfterSkippingLeadingTrivia - ) - newText = newTrivia.description - - case .replaceTrailingTrivia(let oldToken, let newTrivia): -- replaceStartLoc = cxxSourceLocation( -+ replaceStartLoc = bridgedSourceLoc( - for: oldToken, - at: oldToken.endPositionBeforeTrailingTrivia) -- replaceEndLoc = cxxSourceLocation( -+ replaceEndLoc = bridgedSourceLoc( - for: oldToken, - at: oldToken.endPosition - ) - newText = newTrivia.description - } - -- newText.withUTF8 { textBuffer in -- SwiftDiagnostic_fixItReplace( -+ newText.withBridgedString { bridgedMessage in -+ Diagnostic_fixItReplace( - diag, replaceStartLoc, replaceEndLoc, -- textBuffer.baseAddress, SwiftInt(textBuffer.count) -+ bridgedMessage - ) - } - } - -- SwiftDiagnostic_finish(diag); -+ Diagnostic_finish(diag); - } - - /// Emit a diagnostic via the C++ diagnostic engine. -@@ -357,21 +350,25 @@ public func addQueuedDiagnostic( - text: UnsafePointer, - textLength: Int, - severity: BridgedDiagnosticSeverity, -- position: CxxSourceLoc, -- highlightRangesPtr: UnsafePointer?, -+ position: BridgedSourceLoc, -+ highlightRangesPtr: UnsafePointer?, - numHighlightRanges: Int - ) { - let queuedDiagnostics = queuedDiagnosticsPtr.assumingMemoryBound( - to: QueuedDiagnostics.self - ) - -+ guard let rawPosition = position.raw else { -+ return -+ } -+ - // Find the source file that contains this location. - let sourceFile = queuedDiagnostics.pointee.sourceFiles.first { sf in - guard let baseAddress = sf.buffer.baseAddress else { - return false - } - -- return position >= baseAddress && position < baseAddress + sf.buffer.count -+ return rawPosition >= baseAddress && rawPosition < baseAddress + sf.buffer.count - } - guard let sourceFile = sourceFile else { - // FIXME: Hard to report an error here... -@@ -379,22 +376,24 @@ public func addQueuedDiagnostic( - } - - // Find the token at that offset. -- let sourceFileBaseAddress = sourceFile.buffer.baseAddress! -+ let sourceFileBaseAddress = UnsafeRawPointer(sourceFile.buffer.baseAddress!) - let sourceFileEndAddress = sourceFileBaseAddress + sourceFile.buffer.count -- let offset = position - sourceFileBaseAddress -+ let offset = rawPosition - sourceFileBaseAddress - guard let token = sourceFile.syntax.token(at: AbsolutePosition(utf8Offset: offset)) else { - return - } - - // Map the highlights. - var highlights: [Syntax] = [] -- let highlightRanges = UnsafeBufferPointer( -+ let highlightRanges = UnsafeBufferPointer( - start: highlightRangesPtr, count: numHighlightRanges * 2 - ) - for index in 0..= sourceFileBaseAddress && start < sourceFileEndAddress, - end >= sourceFileBaseAddress && end <= sourceFileEndAddress else { -diff --git a/swift/lib/ASTGen/Sources/ASTGen/Exprs.swift b/swift/lib/ASTGen/Sources/ASTGen/Exprs.swift -index 38097c72cc218..432a1e77cbee2 100644 ---- a/swift/lib/ASTGen/Sources/ASTGen/Exprs.swift -+++ b/swift/lib/ASTGen/Sources/ASTGen/Exprs.swift -@@ -4,10 +4,10 @@ import SwiftSyntax - - extension ASTGenVisitor { - public func visit(_ node: ClosureExprSyntax) -> ASTNode { -- let statements = node.statements.map { self.visit($0).bridged() } -+ let statements = node.statements.map { self.visit($0).bridged } - let body: UnsafeMutableRawPointer = statements.withBridgedArrayRef { ref in -- let startLoc = self.base.advanced(by: node.leftBrace.position.utf8Offset).raw -- let endLoc = self.base.advanced(by: node.rightBrace.position.utf8Offset).raw -+ let startLoc = bridgedSourceLoc(for: node.leftBrace) -+ let endLoc = bridgedSourceLoc(for: node.rightBrace) - return BraceStmt_create(ctx, startLoc, ref, endLoc) - } - -@@ -26,37 +26,37 @@ extension ASTGenVisitor { - let args = visit(node.argumentList).rawValue - let callee = visit(node.calledExpression).rawValue - -- return .expr(SwiftFunctionCallExpr_create(self.ctx, callee, args)) -+ return .expr(FunctionCallExpr_create(self.ctx, callee, args)) - } - - public func visit(_ node: IdentifierExprSyntax) -> ASTNode { -- let loc = self.base.advanced(by: node.position.utf8Offset).raw -+ let loc = bridgedSourceLoc(for: node) - - var text = node.identifier.text -- let id = text.withUTF8 { buf in -- return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, SwiftInt(buf.count)) -+ let id = text.withBridgedString { bridgedText in -+ return ASTContext_getIdentifier(ctx, bridgedText) - } - -- return .expr(SwiftIdentifierExpr_create(ctx, id, loc)) -+ return .expr(IdentifierExpr_create(ctx, id, loc)) - } - - public func visit(_ node: IdentifierPatternSyntax) -> ASTNode { -- let loc = self.base.advanced(by: node.position.utf8Offset).raw -+ let loc = bridgedSourceLoc(for: node) - - var text = node.identifier.text -- let id = text.withUTF8 { buf in -- return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, SwiftInt(buf.count)) -+ let id = text.withBridgedString { bridgedText in -+ return ASTContext_getIdentifier(ctx, bridgedText) - } - -- return .expr(SwiftIdentifierExpr_create(ctx, id, loc)) -+ return .expr(IdentifierExpr_create(ctx, id, loc)) - } - - public func visit(_ node: MemberAccessExprSyntax) -> ASTNode { -- let loc = self.base.advanced(by: node.position.utf8Offset).raw -+ let loc = bridgedSourceLoc(for: node) - let base = visit(node.base!).rawValue - var nameText = node.name.text -- let name = nameText.withUTF8 { buf in -- return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, SwiftInt(buf.count)) -+ let name = nameText.withBridgedString { bridgedName in -+ return ASTContext_getIdentifier(ctx, bridgedName) - } - - return .expr(UnresolvedDotExpr_create(ctx, base, loc, name, loc)) -@@ -77,24 +77,24 @@ extension ASTGenVisitor { - guard var name = $0.label?.text else { - return nil - } -- return name.withUTF8 { buf in -- SwiftASTContext_getIdentifier(ctx, buf.baseAddress, SwiftInt(buf.count)) -+ return name.withBridgedString { bridgedName in -+ ASTContext_getIdentifier(ctx, bridgedName) - } - } -- let labelLocs: [UnsafeMutableRawPointer] = node.map { -+ let labelLocs: [BridgedSourceLoc] = node.map { - let pos = $0.label?.position ?? $0.position -- return base.advanced(by: pos.utf8Offset).raw -+ return bridgedSourceLoc(at: pos) - } - -- let lParenLoc = self.base.advanced(by: node.position.utf8Offset).raw -- let rParenLoc = self.base.advanced(by: node.endPosition.utf8Offset).raw -+ let lParenLoc = bridgedSourceLoc(for: node) -+ let rParenLoc = bridgedSourceLoc(at: node.endPosition) - - return .expr( - elements.withBridgedArrayRef { elementsRef in - labels.withBridgedArrayRef { labelsRef in - labelLocs.withBridgedArrayRef { labelLocRef in -- SwiftTupleExpr_create(self.ctx, lParenLoc, elementsRef, labelsRef, -- labelLocRef, rParenLoc) -+ TupleExpr_create(self.ctx, lParenLoc, elementsRef, labelsRef, -+ labelLocRef, rParenLoc) - } - } - }) -diff --git a/swift/lib/ASTGen/Sources/ASTGen/Generics.swift b/swift/lib/ASTGen/Sources/ASTGen/Generics.swift -index 22163381143b0..46b4b3bf90419 100644 ---- a/swift/lib/ASTGen/Sources/ASTGen/Generics.swift -+++ b/swift/lib/ASTGen/Sources/ASTGen/Generics.swift -@@ -4,11 +4,9 @@ import SwiftSyntax - - extension ASTGenVisitor { - func visit(_ node: GenericParameterClauseSyntax) -> ASTNode { -- let lAngleLoc = self.base.advanced(by: node.leftAngleBracket.position.utf8Offset).raw -- let whereLoc = node.genericWhereClause.map { -- self.base.advanced(by: $0.whereKeyword.position.utf8Offset).raw -- } -- let rAngleLoc = self.base.advanced(by: node.rightAngleBracket.position.utf8Offset).raw -+ let lAngleLoc = bridgedSourceLoc(for: node.leftAngleBracket) -+ let whereLoc = bridgedSourceLoc(for: node.genericWhereClause?.whereKeyword) -+ let rAngleLoc = bridgedSourceLoc(for: node.rightAngleBracket) - return .misc( - self.withBridgedParametersAndRequirements(node) { params, reqs in - return GenericParamList_create(self.ctx, lAngleLoc, params, whereLoc, reqs, rAngleLoc) -@@ -17,11 +15,11 @@ extension ASTGenVisitor { - - func visit(_ node: GenericParameterSyntax) -> ASTNode { - var nodeName = node.name.text -- let name = nodeName.withUTF8 { buf in -- return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, SwiftInt(buf.count)) -+ let name = nodeName.withBridgedString { bridgedName in -+ return ASTContext_getIdentifier(ctx, bridgedName) - } -- let nameLoc = self.base.advanced(by: node.name.position.utf8Offset).raw -- let eachLoc = node.each.map { self.base.advanced(by: $0.position.utf8Offset).raw } -+ let nameLoc = bridgedSourceLoc(for: node.name) -+ let eachLoc = bridgedSourceLoc(for: node.each) - - var genericParameterIndex: Int? - for (index, sibling) in (node.parent?.as(GenericParameterListSyntax.self) ?? []).enumerated() { -@@ -37,7 +35,7 @@ extension ASTGenVisitor { - return .decl( - GenericTypeParamDecl_create( - self.ctx, self.declContext, name, nameLoc, eachLoc, SwiftInt(genericParameterIndex), -- eachLoc != nil)) -+ eachLoc.raw != nil)) - } - } - -@@ -65,7 +63,7 @@ extension ASTGenVisitor { - switch requirement.body { - case .conformanceRequirement(let conformance): - let firstType = self.visit(conformance.leftTypeIdentifier).rawValue -- let separatorLoc = self.base.advanced(by: conformance.colon.position.utf8Offset).raw -+ let separatorLoc = bridgedSourceLoc(for: conformance.colon) - let secondType = self.visit(conformance.rightTypeIdentifier).rawValue - requirements.append( - BridgedRequirementRepr( -@@ -75,7 +73,7 @@ extension ASTGenVisitor { - SecondType: secondType)) - case .sameTypeRequirement(let sameType): - let firstType = self.visit(sameType.leftTypeIdentifier).rawValue -- let separatorLoc = self.base.advanced(by: sameType.equalityToken.position.utf8Offset).raw -+ let separatorLoc = bridgedSourceLoc(for: sameType.equalityToken) - let secondType = self.visit(sameType.rightTypeIdentifier).rawValue - requirements.append( - BridgedRequirementRepr( -diff --git a/swift/lib/ASTGen/Sources/ASTGen/Literals.swift b/swift/lib/ASTGen/Sources/ASTGen/Literals.swift -index 1653d09ac348d..21d538df2d939 100644 ---- a/swift/lib/ASTGen/Sources/ASTGen/Literals.swift -+++ b/swift/lib/ASTGen/Sources/ASTGen/Literals.swift -@@ -4,38 +4,38 @@ import SwiftSyntax - - extension ASTGenVisitor { - public func visit(_ node: StringLiteralExprSyntax) -> ASTNode { -- let loc = self.base.advanced(by: node.position.utf8Offset).raw -+ let loc = bridgedSourceLoc(for: node) - var segment = node.segments.first!.as(StringSegmentSyntax.self)!.content.text - return .expr( -- segment.withUTF8 { buf in -- return SwiftStringLiteralExpr_create(ctx, buf.baseAddress, SwiftInt(buf.count), loc) -+ segment.withBridgedString { bridgedSegment in -+ return StringLiteralExpr_create(ctx, bridgedSegment, loc) - }) - } - - public func visit(_ node: IntegerLiteralExprSyntax) -> ASTNode { -- let loc = self.base.advanced(by: node.position.utf8Offset).raw -+ let loc = bridgedSourceLoc(for: node) - var segment = node.digits.text - return .expr( -- segment.withUTF8 { buf in -- return SwiftIntegerLiteralExpr_create(ctx, buf.baseAddress, SwiftInt(buf.count), loc) -+ segment.withBridgedString { bridgedSegment in -+ return IntegerLiteralExpr_create(ctx, bridgedSegment, loc) - }) - } - - public func visit(_ node: BooleanLiteralExprSyntax) -> ASTNode { -- let loc = self.base.advanced(by: node.position.utf8Offset).raw -+ let loc = bridgedSourceLoc(for: node) - let value = node.booleanLiteral == .keyword(.true) -- return .expr(SwiftBooleanLiteralExpr_create(ctx, value, loc)) -+ return .expr(BooleanLiteralExpr_create(ctx, value, loc)) - } - - public func visit(_ node: ArrayExprSyntax) -> ASTNode { -- let lLoc = self.base.advanced(by: node.leftSquare.position.utf8Offset).raw -- let rLoc = self.base.advanced(by: node.rightSquare.position.utf8Offset).raw -+ let lLoc = bridgedSourceLoc(for: node.leftSquare) -+ let rLoc = bridgedSourceLoc(for: node.rightSquare) - - let elements = node.elements.map { self.visit($0).rawValue } - let commas = node.elements - .compactMap { $0.trailingComma } - .map { -- self.base.advanced(by: $0.position.utf8Offset).raw -+ bridgedSourceLoc(for: $0) - } - - return elements.withBridgedArrayRef { elementsRef in -diff --git a/swift/lib/ASTGen/Sources/ASTGen/Misc.swift b/swift/lib/ASTGen/Sources/ASTGen/Misc.swift -index bb63fd0b1b181..0cecfdbe7bb69 100644 ---- a/swift/lib/ASTGen/Sources/ASTGen/Misc.swift -+++ b/swift/lib/ASTGen/Sources/ASTGen/Misc.swift -@@ -26,4 +26,53 @@ extension ASTGenVisitor { - public func visit(_ node: ArrayElementSyntax) -> ASTNode { - visit(node.expression) - } -+ -+ /// Form a source location at the given absolute position in the current -+ /// file. -+ public func bridgedSourceLoc(at position: AbsolutePosition) -> BridgedSourceLoc { -+ return BridgedSourceLoc(at: position, in: base) -+ } -+ -+ /// Form a source location at the given node's position in the current file. -+ public func bridgedSourceLoc(for node: Node?) -> BridgedSourceLoc { -+ guard let node = node else { -+ return nil -+ } -+ return BridgedSourceLoc(at: node.position, in: base) -+ } -+} -+ -+extension BridgedSourceLoc: ExpressibleByNilLiteral { -+ public init(nilLiteral: ()) { -+ self.init(raw: nil) -+ } -+} -+ -+extension BridgedIdentifier: ExpressibleByNilLiteral { -+ public init(nilLiteral: ()) { -+ self.init(raw: nil) -+ } -+} -+ -+extension BridgedSourceLoc { -+ /// Form a source location at the given absolute position in `buffer`. -+ init( -+ at position: AbsolutePosition, -+ in buffer: UnsafeBufferPointer -+ ) { -+ if let start = buffer.baseAddress, -+ position.utf8Offset >= 0 && position.utf8Offset < buffer.count { -+ self = SourceLoc_advanced(BridgedSourceLoc(raw: start), position.utf8Offset) -+ } else { -+ self = nil -+ } -+ } -+} -+ -+extension String { -+ mutating func withBridgedString(_ body: (BridgedString) throws -> R) rethrows -> R { -+ try withUTF8 { buffer in -+ try body(BridgedString(data: buffer.baseAddress, length: buffer.count)) -+ } -+ } - } -diff --git a/swift/lib/ASTGen/Sources/ASTGen/PluginHost.swift b/swift/lib/ASTGen/Sources/ASTGen/PluginHost.swift -index ee90ad3990f2f..e14c14db41ded 100644 ---- a/swift/lib/ASTGen/Sources/ASTGen/PluginHost.swift -+++ b/swift/lib/ASTGen/Sources/ASTGen/PluginHost.swift -@@ -188,11 +188,11 @@ struct CompilerPlugin { - } - - class PluginDiagnosticsEngine { -- private let cxxDiagnosticEngine: UnsafeMutablePointer -+ private let bridgedDiagEngine: BridgedDiagnosticEngine - private var exportedSourceFileByName: [String: UnsafePointer] = [:] - - init(cxxDiagnosticEngine: UnsafeMutablePointer) { -- self.cxxDiagnosticEngine = cxxDiagnosticEngine -+ self.bridgedDiagEngine = BridgedDiagnosticEngine(raw: cxxDiagnosticEngine) - } - - /// Failable convenience initializer for optional cxx engine pointer. -@@ -258,34 +258,34 @@ class PluginDiagnosticsEngine { - - // Emit the diagnostic - var mutableMessage = message -- let diag = mutableMessage.withUTF8 { messageBuffer in -- SwiftDiagnostic_create( -- cxxDiagnosticEngine, bridgedSeverity, -- cxxSourceLocation(at: position), -- messageBuffer.baseAddress, SwiftInt(messageBuffer.count)) -+ let diag = mutableMessage.withBridgedString { bridgedMessage in -+ Diagnostic_create( -+ bridgedDiagEngine, bridgedSeverity, -+ bridgedSourceLoc(at: position), -+ bridgedMessage) - } - - // Emit highlights - for highlight in highlights { -- guard let (startLoc, endLoc) = cxxSourceRange(for: highlight) else { -+ guard let (startLoc, endLoc) = bridgedSourceRange(for: highlight) else { - continue - } -- SwiftDiagnostic_highlight(diag, startLoc, endLoc) -+ Diagnostic_highlight(diag, startLoc, endLoc) - } - - // Emit changes for a Fix-It. - for change in fixItChanges { -- guard let (startLoc, endLoc) = cxxSourceRange(for: change.range) else { -+ guard let (startLoc, endLoc) = bridgedSourceRange(for: change.range) else { - continue - } - var newText = change.newText -- newText.withUTF8 { textBuffer in -- SwiftDiagnostic_fixItReplace( -- diag, startLoc, endLoc, textBuffer.baseAddress, SwiftInt(textBuffer.count)) -+ newText.withBridgedString { bridgedFixItText in -+ Diagnostic_fixItReplace( -+ diag, startLoc, endLoc, bridgedFixItText) - } - } - -- SwiftDiagnostic_finish(diag) -+ Diagnostic_finish(diag) - } - - /// Emit diagnostics. -@@ -312,40 +312,36 @@ class PluginDiagnosticsEngine { - - /// Produce the C++ source location for a given position based on a - /// syntax node. -- private func cxxSourceLocation( -+ private func bridgedSourceLoc( - at offset: Int, in fileName: String -- ) -> CxxSourceLoc? { -+ ) -> BridgedSourceLoc { - // Find the corresponding exported source file. -- guard -- let exportedSourceFile = exportedSourceFileByName[fileName] -- else { -+ guard let exportedSourceFile = exportedSourceFileByName[fileName] else { - return nil - } - - // Compute the resulting address. -- guard -- let bufferBaseAddress = exportedSourceFile.pointee.buffer.baseAddress -- else { -+ guard let bufferBaseAddress = exportedSourceFile.pointee.buffer.baseAddress else { - return nil - } -- return bufferBaseAddress.advanced(by: offset) -+ return SourceLoc_advanced(BridgedSourceLoc(raw: bufferBaseAddress), offset) - } - - /// C++ source location from a position value from a plugin. -- private func cxxSourceLocation( -+ private func bridgedSourceLoc( - at position: PluginMessage.Diagnostic.Position -- ) -> CxxSourceLoc? { -- cxxSourceLocation(at: position.offset, in: position.fileName) -+ ) -> BridgedSourceLoc { -+ return bridgedSourceLoc(at: position.offset, in: position.fileName) - } - - /// C++ source range from a range value from a plugin. -- private func cxxSourceRange( -+ private func bridgedSourceRange( - for range: PluginMessage.Diagnostic.PositionRange -- ) -> (start: CxxSourceLoc, end: CxxSourceLoc)? { -- guard -- let start = cxxSourceLocation(at: range.startOffset, in: range.fileName), -- let end = cxxSourceLocation(at: range.endOffset, in: range.fileName) -- else { -+ ) -> (start: BridgedSourceLoc, end: BridgedSourceLoc)? { -+ let start = bridgedSourceLoc(at: range.startOffset, in: range.fileName) -+ let end = bridgedSourceLoc(at: range.endOffset, in: range.fileName) -+ -+ if start.raw == nil || end.raw == nil { - return nil - } - return (start: start, end: end ) -@@ -364,9 +360,8 @@ extension PluginMessage.Syntax { - case syntax.is(AttributeSyntax.self): kind = .attribute - default: return nil - } -- let source = syntax.description -- - -+ let source = syntax.description - let sourceStr = String(decoding: sourceFilePtr.pointee.buffer, as: UTF8.self) - let fileName = sourceFilePtr.pointee.fileName - let fileID = "\(sourceFilePtr.pointee.moduleName)/\(sourceFilePtr.pointee.fileName.basename)" -diff --git a/swift/lib/ASTGen/Sources/ASTGen/SourceFile.swift b/swift/lib/ASTGen/Sources/ASTGen/SourceFile.swift -index 5def6146f4a6a..227f00e83e75c 100644 ---- a/swift/lib/ASTGen/Sources/ASTGen/SourceFile.swift -+++ b/swift/lib/ASTGen/Sources/ASTGen/SourceFile.swift -@@ -110,8 +110,7 @@ public func emitParserDiagnostics( - - emitDiagnostic( - diagEnginePtr: diagEnginePtr, -- sourceFileBuffer: UnsafeMutableBufferPointer( -- mutating: sourceFile.pointee.buffer), -+ sourceFileBuffer: sourceFile.pointee.buffer, - diagnostic: diag, - diagnosticSeverity: diagnosticSeverity - ) -diff --git a/swift/lib/ASTGen/Sources/ASTGen/SourceManager.swift b/swift/lib/ASTGen/Sources/ASTGen/SourceManager.swift -index e7b410a2fa765..a3e2551e07dba 100644 ---- a/swift/lib/ASTGen/Sources/ASTGen/SourceManager.swift -+++ b/swift/lib/ASTGen/Sources/ASTGen/SourceManager.swift -@@ -1,18 +1,16 @@ -+import CASTBridging - import SwiftOperators - import SwiftSyntax - import SwiftSyntaxMacros - --/// A C++ source location. --public typealias CxxSourceLoc = UnsafePointer -- - /// A source manager that keeps track of the source files in the program. - class SourceManager { - init(cxxDiagnosticEngine: UnsafeMutablePointer) { -- self.cxxDiagnosticEngine = cxxDiagnosticEngine -+ self.bridgedDiagEngine = BridgedDiagnosticEngine(raw: cxxDiagnosticEngine) - } - -- /// A pointer to the C++ diagnostic engine. -- let cxxDiagnosticEngine: UnsafeMutablePointer -+ /// The bridged diagnostic engine (just the wrapped C++ `DiagnosticEngine`). -+ let bridgedDiagEngine: BridgedDiagnosticEngine - - /// The set of source files that have been exported to the C++ code of - /// the program. -@@ -100,10 +98,10 @@ extension SourceManager { - - /// Produce the C++ source location for a given position based on a - /// syntax node. -- func cxxSourceLocation( -+ func bridgedSourceLoc( - for node: Node, - at position: AbsolutePosition? = nil -- ) -> CxxSourceLoc? { -+ ) -> BridgedSourceLoc { - // Find the source file and this node's position within it. - guard let (sourceFile, rootPosition) = rootSourceFile(of: node) else { - return nil -@@ -118,16 +116,9 @@ extension SourceManager { - // Find the offset of the given position based on the root of the given - // node. - let position = position ?? node.position -- let offsetWithinSyntaxNode = -- position.utf8Offset - node.position.utf8Offset -- let offsetFromSourceFile = rootPosition.utf8Offset + offsetWithinSyntaxNode -+ let nodeOffset = SourceLength(utf8Length: position.utf8Offset - node.position.utf8Offset) -+ let realPosition = rootPosition + nodeOffset - -- // Compute the resulting address. -- guard let bufferBaseAddress = exportedSourceFile.pointee.buffer.baseAddress -- else { -- return nil -- } -- let address = bufferBaseAddress.advanced(by: offsetFromSourceFile) -- return address -+ return BridgedSourceLoc(at: realPosition, in: exportedSourceFile.pointee.buffer) - } - } -diff --git a/swift/lib/ASTGen/Sources/ASTGen/Stmts.swift b/swift/lib/ASTGen/Sources/ASTGen/Stmts.swift -index 9b8b625974520..5b32bd6611270 100644 ---- a/swift/lib/ASTGen/Sources/ASTGen/Stmts.swift -+++ b/swift/lib/ASTGen/Sources/ASTGen/Stmts.swift -@@ -4,9 +4,9 @@ import SwiftSyntax - - extension ASTGenVisitor { - public func visit(_ node: CodeBlockSyntax) -> ASTNode { -- let statements = node.statements.map { self.visit($0).bridged() } -- let startLoc = self.base.advanced(by: node.leftBrace.position.utf8Offset).raw -- let endLoc = self.base.advanced(by: node.rightBrace.position.utf8Offset).raw -+ let statements = node.statements.map { self.visit($0).bridged } -+ let startLoc = bridgedSourceLoc(for: node.leftBrace) -+ let endLoc = bridgedSourceLoc(for: node.rightBrace) - - return .stmt( - statements.withBridgedArrayRef { ref in -@@ -19,7 +19,7 @@ extension ASTGenVisitor { - assert(conditions.count == 1) // TODO: handle multiple conditions. - - let body = visit(node.body).rawValue -- let loc = self.base.advanced(by: node.position.utf8Offset).raw -+ let loc = bridgedSourceLoc(for: node) - - if let elseBody = node.elseBody, node.elseKeyword != nil { - return .stmt(IfStmt_create(ctx, loc, conditions.first!, body, loc, -@@ -39,7 +39,7 @@ extension ASTGenVisitor { - } - - public func visit(_ node: ReturnStmtSyntax) -> ASTNode { -- let loc = self.base.advanced(by: node.position.utf8Offset).raw -+ let loc = bridgedSourceLoc(for: node) - - let expr: ASTNode? - if let expression = node.expression { -diff --git a/swift/lib/ASTGen/Sources/ASTGen/Types.swift b/swift/lib/ASTGen/Sources/ASTGen/Types.swift -index 82bbca53bf4b2..34a185fe13fbf 100644 ---- a/swift/lib/ASTGen/Sources/ASTGen/Types.swift -+++ b/swift/lib/ASTGen/Sources/ASTGen/Types.swift -@@ -4,7 +4,7 @@ import SwiftSyntax - - extension ASTGenVisitor { - public func visit(_ node: SimpleTypeIdentifierSyntax) -> ASTNode { -- let loc = self.base.advanced(by: node.position.utf8Offset).raw -+ let loc = bridgedSourceLoc(for: node) - - // If this is the bare 'Any' keyword, produce an empty composition type. - if node.name.tokenKind == .keyword(.Any) && node.genericArgumentClause == nil { -@@ -12,16 +12,16 @@ extension ASTGenVisitor { - } - - var text = node.name.text -- let id = text.withUTF8 { buf in -- return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, SwiftInt(buf.count)) -+ let id = text.withBridgedString { bridgedText in -+ return ASTContext_getIdentifier(ctx, bridgedText) - } - - guard let generics = node.genericArgumentClause else { - return .type(SimpleIdentTypeRepr_create(ctx, loc, id)) - } - -- let lAngle = self.base.advanced(by: generics.leftAngleBracket.position.utf8Offset).raw -- let rAngle = self.base.advanced(by: generics.rightAngleBracket.position.utf8Offset).raw -+ let lAngle = bridgedSourceLoc(for: generics.leftAngleBracket) -+ let rAngle = bridgedSourceLoc(for: generics.rightAngleBracket) - return .type( - generics.arguments.map({ - self.visit($0.argumentType).rawValue -@@ -42,14 +42,14 @@ extension ASTGenVisitor { - let generics = memberType.genericArgumentClause - - var nameText = nameToken.text -- let name = nameText.withUTF8 { buf in -- return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, SwiftInt(buf.count)) -+ let name = nameText.withBridgedString { bridgedName in -+ return ASTContext_getIdentifier(ctx, bridgedName) - } -- let nameLoc = self.base.advanced(by: nameToken.position.utf8Offset).raw -+ let nameLoc = bridgedSourceLoc(for: nameToken) - - if let generics = generics { -- let lAngle = self.base.advanced(by: generics.leftAngleBracket.position.utf8Offset).raw -- let rAngle = self.base.advanced(by: generics.rightAngleBracket.position.utf8Offset).raw -+ let lAngle = bridgedSourceLoc(for: generics.leftAngleBracket) -+ let rAngle = bridgedSourceLoc(for: generics.rightAngleBracket) - reverseMemberComponents.append( - generics.arguments.map({ self.visit($0.argumentType).rawValue }).withBridgedArrayRef { - genericArgs in -@@ -72,24 +72,24 @@ extension ASTGenVisitor { - - public func visit(_ node: ArrayTypeSyntax) -> ASTNode { - let elementType = visit(node.elementType).rawValue -- let lSquareLoc = self.base.advanced(by: node.leftSquareBracket.position.utf8Offset).raw -- let rSquareLoc = self.base.advanced(by: node.rightSquareBracket.position.utf8Offset).raw -+ let lSquareLoc = bridgedSourceLoc(for: node.leftSquareBracket) -+ let rSquareLoc = bridgedSourceLoc(for: node.rightSquareBracket) - return .type(ArrayTypeRepr_create(self.ctx, elementType, lSquareLoc, rSquareLoc)) - } - - public func visit(_ node: DictionaryTypeSyntax) -> ASTNode { - let keyType = visit(node.keyType).rawValue - let valueType = visit(node.valueType).rawValue -- let colonLoc = self.base.advanced(by: node.colon.position.utf8Offset).raw -- let lSquareLoc = self.base.advanced(by: node.leftSquareBracket.position.utf8Offset).raw -- let rSquareLoc = self.base.advanced(by: node.rightSquareBracket.position.utf8Offset).raw -+ let colonLoc = bridgedSourceLoc(for: node.colon) -+ let lSquareLoc = bridgedSourceLoc(for: node.leftSquareBracket) -+ let rSquareLoc = bridgedSourceLoc(for: node.rightSquareBracket) - return .type( - DictionaryTypeRepr_create(self.ctx, keyType, valueType, colonLoc, lSquareLoc, rSquareLoc)) - } - - public func visit(_ node: MetatypeTypeSyntax) -> ASTNode { - let baseType = visit(node.baseType).rawValue -- let tyLoc = self.base.advanced(by: node.typeOrProtocol.position.utf8Offset).raw -+ let tyLoc = bridgedSourceLoc(for: node.typeOrProtocol) - if node.typeOrProtocol.text == "Type" { - return .type(MetatypeTypeRepr_create(self.ctx, baseType, tyLoc)) - } else { -@@ -100,26 +100,26 @@ extension ASTGenVisitor { - - public func visit(_ node: ImplicitlyUnwrappedOptionalTypeSyntax) -> ASTNode { - let base = visit(node.wrappedType).rawValue -- let exclaimLoc = self.base.advanced(by: node.exclamationMark.position.utf8Offset).raw -+ let exclaimLoc = bridgedSourceLoc(for: node.exclamationMark) - return .type(ImplicitlyUnwrappedOptionalTypeRepr_create(self.ctx, base, exclaimLoc)) - } - - public func visit(_ node: OptionalTypeSyntax) -> ASTNode { - let base = visit(node.wrappedType).rawValue -- let questionLoc = self.base.advanced(by: node.questionMark.position.utf8Offset).raw -+ let questionLoc = bridgedSourceLoc(for: node.questionMark) - return .type(OptionalTypeRepr_create(self.ctx, base, questionLoc)) - } - - public func visit(_ node: PackExpansionTypeSyntax) -> ASTNode { - let base = visit(node.patternType).rawValue -- let repeatLoc = self.base.advanced(by: node.repeatKeyword.position.utf8Offset).raw -+ let repeatLoc = bridgedSourceLoc(for: node.repeatKeyword) - return .type(PackExpansionTypeRepr_create(self.ctx, base, repeatLoc)) - } - - public func visit(_ node: TupleTypeSyntax) -> ASTNode { - return self.withBridgedTupleElements(node.elements) { elements in -- let lParenLoc = self.base.advanced(by: node.leftParen.position.utf8Offset).raw -- let rParenLoc = self.base.advanced(by: node.rightParen.position.utf8Offset).raw -+ let lParenLoc = bridgedSourceLoc(for: node.leftParen) -+ let rParenLoc = bridgedSourceLoc(for: node.rightParen) - return .type(TupleTypeRepr_create(self.ctx, elements, lParenLoc, rParenLoc)) - } - } -@@ -127,9 +127,8 @@ extension ASTGenVisitor { - public func visit(_ node: CompositionTypeSyntax) -> ASTNode { - assert(node.elements.count > 1) - let types = node.elements.map { visit($0.type) }.map { $0.rawValue } -- let firstTypeLoc = self.base.advanced(by: node.elements.first!.type.position.utf8Offset).raw -- let firstAmpOffset = node.elements.first?.ampersand.map { $0.position.utf8Offset } ?? 0 -- let firstAmpLoc = self.base.advanced(by: firstAmpOffset).raw -+ let firstTypeLoc = bridgedSourceLoc(for: node.elements.first?.type) -+ let firstAmpLoc = bridgedSourceLoc(for: node.elements.first?.ampersand) - return .type( - types.withBridgedArrayRef { types in - return CompositionTypeRepr_create(self.ctx, types, firstTypeLoc, firstAmpLoc) -@@ -138,14 +137,12 @@ extension ASTGenVisitor { - - public func visit(_ node: FunctionTypeSyntax) -> ASTNode { - return self.withBridgedTupleElements(node.arguments) { elements in -- let lParenLoc = self.base.advanced(by: node.leftParen.position.utf8Offset).raw -- let rParenLoc = self.base.advanced(by: node.rightParen.position.utf8Offset).raw -+ let lParenLoc = bridgedSourceLoc(for: node.leftParen) -+ let rParenLoc = bridgedSourceLoc(for: node.rightParen) - let args = TupleTypeRepr_create(self.ctx, elements, lParenLoc, rParenLoc) -- let asyncLoc = node.effectSpecifiers?.asyncSpecifier.map { self.base.advanced(by: $0.position.utf8Offset).raw } -- let throwsLoc = node.effectSpecifiers?.throwsSpecifier.map { -- self.base.advanced(by: $0.position.utf8Offset).raw -- } -- let arrowLoc = self.base.advanced(by: node.output.arrow.position.utf8Offset).raw -+ let asyncLoc = bridgedSourceLoc(for: node.effectSpecifiers?.asyncSpecifier) -+ let throwsLoc = bridgedSourceLoc(for: node.effectSpecifiers?.throwsSpecifier) -+ let arrowLoc = bridgedSourceLoc(for: node.output.arrow) - let retTy = visit(node.output.returnType).rawValue - return .type(FunctionTypeRepr_create(self.ctx, args, asyncLoc, throwsLoc, arrowLoc, retTy)) - } -@@ -157,7 +154,7 @@ extension ASTGenVisitor { - } - - public func visit(_ node: ConstrainedSugarTypeSyntax) -> ASTNode { -- let someOrAnyLoc = self.base.advanced(by: node.someOrAnySpecifier.position.utf8Offset).raw -+ let someOrAnyLoc = bridgedSourceLoc(for: node.someOrAnySpecifier) - let baseTy = visit(node.baseType).rawValue - if node.someOrAnySpecifier.text == "some" { - return .type(OpaqueReturnTypeRepr_create(self.ctx, someOrAnyLoc, baseTy)) -@@ -172,7 +169,7 @@ extension ASTGenVisitor { - - // Handle specifiers. - if let specifier = node.specifier { -- let specifierLoc = self.base.advanced(by: specifier.position.utf8Offset).raw -+ let specifierLoc = bridgedSourceLoc(for: specifier) - - let kind: BridgedAttributedTypeSpecifier - switch specifier.tokenKind { -@@ -191,7 +188,7 @@ extension ASTGenVisitor { - - // Handle type attributes. - if let attributes = node.attributes { -- let typeAttributes = BridgedTypeAttributes_create() -+ let typeAttributes = TypeAttributes_create() - for attributeElt in attributes { - // FIXME: Ignoring #ifs entirely. We want to provide a filtered view, - // but we don't have that ability right now. -@@ -206,11 +203,11 @@ extension ASTGenVisitor { - - let nameSyntax = identType.name - var name = nameSyntax.text -- let typeAttrKind = name.withUTF8 { buf in -- getBridgedTypeAttrKindFromString(buf.baseAddress, buf.count) -+ let typeAttrKind = name.withBridgedString { bridgedName in -+ TypeAttrKind_fromString(bridgedName) - } -- let atLoc = self.base.advanced(by: attribute.atSignToken.position.utf8Offset).raw -- let attrLoc = self.base.advanced(by: nameSyntax.position.utf8Offset).raw -+ let atLoc = bridgedSourceLoc(for: attribute.atSignToken) -+ let attrLoc = bridgedSourceLoc(for: nameSyntax) - switch typeAttrKind { - // SIL attributes - // FIXME: Diagnose if not in SIL mode? Or should that move to the -@@ -226,7 +223,7 @@ extension ASTGenVisitor { - .sendable, .unchecked, ._local, ._noMetadata, .pack_owned, - .pack_guaranteed, .pack_inout, .pack_out, .pseudogeneric, - .yields, .yield_once, .yield_many, .thin, .thick, .count: -- BridgedTypeAttributes_addSimpleAttr(typeAttributes, typeAttrKind, atLoc, attrLoc) -+ TypeAttributes_addSimpleAttr(typeAttributes, typeAttrKind, atLoc, attrLoc) - - case .opened, .pack_element, .differentiable, .convention, - ._opaqueReturnTypeOf: -@@ -250,28 +247,22 @@ extension ASTGenVisitor { - var elements = [BridgedTupleTypeElement]() - for element in elementList { - var nameText = element.name?.text -- let name = nameText?.withUTF8 { buf in -- return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, SwiftInt(buf.count)) -- } -- let nameLoc = element.name.map { self.base.advanced(by: $0.position.utf8Offset).raw } -+ let name = nameText?.withBridgedString { bridgedName in -+ return ASTContext_getIdentifier(ctx, bridgedName) -+ } ?? nil -+ let nameLoc = bridgedSourceLoc(for: element.name) - var secondNameText = element.secondName?.text -- let secondName = secondNameText?.withUTF8 { buf in -- return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, SwiftInt(buf.count)) -- } -- let secondNameLoc = element.secondName.map { -- self.base.advanced(by: $0.position.utf8Offset).raw -- } -- let colonLoc = element.colon.map { self.base.advanced(by: $0.position.utf8Offset).raw } -- -+ let secondName = secondNameText?.withBridgedString { bridgedName in -+ return ASTContext_getIdentifier(ctx, bridgedName) -+ } ?? nil -+ let secondNameLoc = bridgedSourceLoc(for: element.secondName) -+ let colonLoc = bridgedSourceLoc(for: element.colon) - var type = visit(element.type).rawValue - if let ellipsis = element.ellipsis { -- let ellipsisLoc = self.base.advanced(by: ellipsis.positionAfterSkippingLeadingTrivia.utf8Offset).raw -+ let ellipsisLoc = bridgedSourceLoc(at: ellipsis.positionAfterSkippingLeadingTrivia) - type = VarargTypeRepr_create(self.ctx, type, ellipsisLoc) - } -- -- let trailingCommaLoc = element.trailingComma.map { -- self.base.advanced(by: $0.position.utf8Offset).raw -- } -+ let trailingCommaLoc = bridgedSourceLoc(for: element.trailingComma) - - elements.append( - BridgedTupleTypeElement( -@@ -318,7 +309,7 @@ func buildTypeRepr( - endTypeLocPtr.pointee = sourceFile.pointee.buffer.baseAddress!.advanced(by: typeSyntax.endPosition.utf8Offset) - - // Convert the type syntax node. -- let typeReprNode = ASTGenVisitor(ctx: ctx, base: sourceFile.pointee.buffer.baseAddress!, declContext: dc) -+ let typeReprNode = ASTGenVisitor(ctx: BridgedASTContext(raw: ctx), base: sourceFile.pointee.buffer, declContext: BridgedDeclContext(raw: dc)) - .visit(typeSyntax) - - return typeReprNode.rawValue diff --git a/packages/swift/swift-move-regex-literals.patch b/packages/swift/swift-move-regex-literals.patch deleted file mode 100644 index 9875dc78df..0000000000 --- a/packages/swift/swift-move-regex-literals.patch +++ /dev/null @@ -1,1291 +0,0 @@ -From 7159e72f7babe3e74cc6839d62c8e07bcccbc1f6 -From: Doug Gregor -Date: Fri, 8 Sep 2023 10:43:45 -0700 -Subject: [PATCH] Move regex literal parsing logic from SwiftCompilerSources to - ASTGen - -ASTGen always builds with the host Swift compiler, without requiring -bootstrapping, and is enabled in more places. Move the regex literal -parsing logic there so it is enabled in more host environments, and -makes use of CMake's Swift support. Enable all of the regex literal -tests when ASTGen is built, to ensure everything is working. - -Remove the "AST" and "Parse" Swift modules from SwiftCompilerSources, -because they are no longer needed. - -diff --git a/swift/SwiftCompilerSources/CMakeLists.txt b/swift/SwiftCompilerSources/CMakeLists.txt -index 138d208d9a3a9..44ed3a90d0546 100644 ---- a/swift/SwiftCompilerSources/CMakeLists.txt -+++ b/swift/SwiftCompilerSources/CMakeLists.txt -@@ -241,15 +241,9 @@ else() - #include \"Basic/BasicBridging.h\" - #include \"Basic/SourceLoc.h\" - --#include \"AST/ASTBridging.h\" --#include \"AST/DiagnosticEngine.h\" --#include \"AST/DiagnosticConsumer.h\" -- - #include \"SIL/SILBridging.h\" - - #include \"SILOptimizer/OptimizerBridging.h\" -- --#include \"Parse/RegexParserBridging.h\" - ") - add_custom_command( - OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/HeaderDependencies.cpp" -diff --git a/swift/SwiftCompilerSources/Package.swift b/swift/SwiftCompilerSources/Package.swift -index 3b1a3817cb686..5785c411c1907 100644 ---- a/swift/SwiftCompilerSources/Package.swift -+++ b/swift/SwiftCompilerSources/Package.swift -@@ -48,38 +48,21 @@ let package = Package( - .library( - name: "swiftCompilerModules", - type: .static, -- targets: ["Basic", "AST", "Parse", "SIL", "Optimizer", "_CompilerRegexParser"]), -+ targets: ["Basic", "SIL", "Optimizer"]), - ], - dependencies: [ - ], - // Note that targets and their dependencies must align with - // 'SwiftCompilerSources/Sources/CMakeLists.txt' - targets: [ -- .compilerModuleTarget( -- name: "_CompilerRegexParser", -- dependencies: [], -- path: "_RegexParser_Sources", -- swiftSettings: [ -- // Workaround until `_CompilerRegexParser` is imported as implementation-only -- // by `_StringProcessing`. -- .unsafeFlags([ -- "-Xfrontend", -- "-disable-implicit-string-processing-module-import" -- ])]), - .compilerModuleTarget( - name: "Basic", - dependencies: []), -- .compilerModuleTarget( -- name: "AST", -- dependencies: ["Basic"]), -- .compilerModuleTarget( -- name: "Parse", -- dependencies: ["Basic", "AST", "_CompilerRegexParser"]), - .compilerModuleTarget( - name: "SIL", - dependencies: ["Basic"]), - .compilerModuleTarget( - name: "Optimizer", -- dependencies: ["Basic", "SIL", "Parse"]), -+ dependencies: ["Basic", "SIL"]), - ] - ) -diff --git a/swift/SwiftCompilerSources/Sources/AST/CMakeLists.txt b/swift/SwiftCompilerSources/Sources/AST/CMakeLists.txt -deleted file mode 100644 -index 3d814cad0a6c4..0000000000000 ---- a/swift/SwiftCompilerSources/Sources/AST/CMakeLists.txt -+++ /dev/null -@@ -1,14 +0,0 @@ --# This source file is part of the Swift.org open source project --# --# Copyright (c) 2022 Apple Inc. and the Swift project authors --# Licensed under Apache License v2.0 with Runtime Library Exception --# --# See http://swift.org/LICENSE.txt for license information --# See http://swift.org/CONTRIBUTORS.txt for Swift project authors -- --add_swift_compiler_module(AST -- DEPENDS -- Basic -- SOURCES -- DiagnosticEngine.swift) -- -diff --git a/swift/SwiftCompilerSources/Sources/AST/DiagnosticEngine.swift b/swift/SwiftCompilerSources/Sources/AST/DiagnosticEngine.swift -deleted file mode 100644 -index 69d4c8b77f8a7..0000000000000 ---- a/swift/SwiftCompilerSources/Sources/AST/DiagnosticEngine.swift -+++ /dev/null -@@ -1,122 +0,0 @@ --//===--- DiagnosticEngine.swift -------------------------------------------===// --// --// This source file is part of the Swift.org open source project --// --// Copyright (c) 2022 Apple Inc. and the Swift project authors --// Licensed under Apache License v2.0 with Runtime Library Exception --// --// See https://swift.org/LICENSE.txt for license information --// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors --// --//===----------------------------------------------------------------------===// -- --import ASTBridging -- --import Basic -- --public typealias DiagID = BridgedDiagID -- --public protocol DiagnosticArgument { -- func _withBridgedDiagnosticArgument(_ fn: (swift.DiagnosticArgument) -> Void) --} --extension String: DiagnosticArgument { -- public func _withBridgedDiagnosticArgument(_ fn: (swift.DiagnosticArgument) -> Void) { -- _withStringRef { fn(swift.DiagnosticArgument($0)) } -- } --} --extension Int: DiagnosticArgument { -- public func _withBridgedDiagnosticArgument(_ fn: (swift.DiagnosticArgument) -> Void) { -- fn(swift.DiagnosticArgument(Int32(self))) -- } --} -- --public struct DiagnosticFixIt { -- public let start: SourceLoc -- public let byteLength: Int -- public let text: String -- -- public init(start: SourceLoc, byteLength: Int, replacement text: String) { -- self.start = start -- self.byteLength = byteLength -- self.text = text -- } -- -- func withBridgedDiagnosticFixIt(_ fn: (swift.DiagnosticInfo.FixIt) -> Void) { -- text._withStringRef { bridgedTextRef in -- let bridgedDiagnosticFixIt = swift.DiagnosticInfo.FixIt( -- swift.CharSourceRange(start.bridged, UInt32(byteLength)), -- bridgedTextRef, -- ArrayRefOfDiagnosticArgument()) -- fn(bridgedDiagnosticFixIt) -- } -- } --} -- --public struct DiagnosticEngine { -- private let bridged: BridgedDiagnosticEngine -- -- public init(bridged: BridgedDiagnosticEngine) { -- self.bridged = bridged -- } -- public init?(bridged: BridgedOptionalDiagnosticEngine) { -- guard let object = bridged.object else { -- return nil -- } -- self.bridged = BridgedDiagnosticEngine(object: object) -- } -- -- public func diagnose(_ position: SourceLoc?, -- _ id: DiagID, -- _ args: [DiagnosticArgument], -- highlight: CharSourceRange? = nil, -- fixIts: [DiagnosticFixIt] = []) { -- -- let bridgedSourceLoc: swift.SourceLoc = position.bridged -- let bridgedHighlightRange: swift.CharSourceRange = highlight.bridged -- var bridgedArgs: [swift.DiagnosticArgument] = [] -- var bridgedFixIts: [swift.DiagnosticInfo.FixIt] = [] -- -- // Build a higher-order function to wrap every 'withBridgedXXX { ... }' -- // calls, so we don't escape anything from the closure. 'bridgedArgs' and -- // 'bridgedFixIts' are temporary storage to store bridged values. So they -- // should not be used after the closure is executed. -- -- var closure: () -> Void = { -- bridgedArgs.withBridgedArrayRef { bridgedArgsRef in -- bridgedFixIts.withBridgedArrayRef { bridgedFixItsRef in -- DiagnosticEngine_diagnose(bridged, bridgedSourceLoc, -- id, bridgedArgsRef, -- bridgedHighlightRange, bridgedFixItsRef) -- } -- } -- } -- // 'reversed()' because the closure should be wrapped in that order. -- for arg in args.reversed() { -- closure = { [closure, arg] in -- arg._withBridgedDiagnosticArgument { bridgedArg in -- bridgedArgs.append(bridgedArg) -- closure() -- } -- } -- } -- // 'reversed()' because the closure should be wrapped in that order. -- for fixIt in fixIts.reversed() { -- closure = { [closure, fixIt] in -- fixIt.withBridgedDiagnosticFixIt { bridgedFixIt in -- bridgedFixIts.append(bridgedFixIt) -- closure() -- } -- } -- } -- -- closure() -- } -- -- public func diagnose(_ position: SourceLoc?, -- _ id: DiagID, -- _ args: DiagnosticArgument..., -- highlight: CharSourceRange? = nil, -- fixIts: DiagnosticFixIt...) { -- diagnose(position, id, args, highlight: highlight, fixIts: fixIts) -- } --} -diff --git a/swift/SwiftCompilerSources/Sources/CMakeLists.txt b/swift/SwiftCompilerSources/Sources/CMakeLists.txt -index af6900ff8d0e9..622fa883889a9 100644 ---- a/swift/SwiftCompilerSources/Sources/CMakeLists.txt -+++ b/swift/SwiftCompilerSources/Sources/CMakeLists.txt -@@ -8,11 +8,6 @@ - - # NOTE: Subdirectories must be added in dependency order. - --if(SWIFT_BUILD_REGEX_PARSER_IN_COMPILER) -- add_subdirectory(_RegexParser) --endif() - add_subdirectory(Basic) --add_subdirectory(AST) --add_subdirectory(Parse) - add_subdirectory(SIL) - add_subdirectory(Optimizer) -diff --git a/swift/SwiftCompilerSources/Sources/Optimizer/CMakeLists.txt b/swift/SwiftCompilerSources/Sources/Optimizer/CMakeLists.txt -index acce165e1ee79..48b74e373e115 100644 ---- a/swift/SwiftCompilerSources/Sources/Optimizer/CMakeLists.txt -+++ b/swift/SwiftCompilerSources/Sources/Optimizer/CMakeLists.txt -@@ -7,7 +7,7 @@ - # See http://swift.org/CONTRIBUTORS.txt for Swift project authors - - set(dependencies) --list(APPEND dependencies Basic SIL Parse) -+list(APPEND dependencies Basic SIL) - - add_swift_compiler_module(Optimizer DEPENDS ${dependencies}) - -diff --git a/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/PassRegistration.swift b/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/PassRegistration.swift -index 060adf01abf53..13f1b7fe7d106 100644 ---- a/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/PassRegistration.swift -+++ b/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/PassRegistration.swift -@@ -12,14 +12,12 @@ - - import SIL - import OptimizerBridging --import Parse - - @_cdecl("initializeSwiftModules") - public func initializeSwiftModules() { - registerSILClasses() - registerSwiftAnalyses() - registerSwiftPasses() -- initializeSwiftParseModules() - } - - private func registerPass( -diff --git a/swift/SwiftCompilerSources/Sources/Parse/CMakeLists.txt b/swift/SwiftCompilerSources/Sources/Parse/CMakeLists.txt -deleted file mode 100644 -index 7e5c1c7d97717..0000000000000 ---- a/swift/SwiftCompilerSources/Sources/Parse/CMakeLists.txt -+++ /dev/null -@@ -1,19 +0,0 @@ --# This source file is part of the Swift.org open source project --# --# Copyright (c) 2022 Apple Inc. and the Swift project authors --# Licensed under Apache License v2.0 with Runtime Library Exception --# --# See http://swift.org/LICENSE.txt for license information --# See http://swift.org/CONTRIBUTORS.txt for Swift project authors -- --set(dependencies Basic AST) --if(SWIFT_BUILD_REGEX_PARSER_IN_COMPILER) -- list(APPEND dependencies _CompilerRegexParser) --endif() -- --add_swift_compiler_module(Parse -- DEPENDS -- ${dependencies} -- SOURCES -- Parse.swift -- Regex.swift) -diff --git a/swift/SwiftCompilerSources/Sources/Parse/Parse.swift b/swift/SwiftCompilerSources/Sources/Parse/Parse.swift -deleted file mode 100644 -index a8a79489fc5a8..0000000000000 ---- a/swift/SwiftCompilerSources/Sources/Parse/Parse.swift -+++ /dev/null -@@ -1,16 +0,0 @@ --//===--- Parse.swift - SourceLoc bridiging utilities ------------------===// --// --// This source file is part of the Swift.org open source project --// --// Copyright (c) 2022 Apple Inc. and the Swift project authors --// Licensed under Apache License v2.0 with Runtime Library Exception --// --// See https://swift.org/LICENSE.txt for license information --// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors --// --//===----------------------------------------------------------------------===// -- --@_cdecl("initializeSwiftParseModules") --public func initializeSwiftParseModules() { -- registerRegexParser() --} -diff --git a/swift/SwiftCompilerSources/Sources/_RegexParser/CMakeLists.txt b/swift/SwiftCompilerSources/Sources/_RegexParser/CMakeLists.txt -deleted file mode 100644 -index d202c421e84d1..0000000000000 ---- a/swift/SwiftCompilerSources/Sources/_RegexParser/CMakeLists.txt -+++ /dev/null -@@ -1,20 +0,0 @@ --# This source file is part of the Swift.org open source project --# --# Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors --# Licensed under Apache License v2.0 with Runtime Library Exception --# --# See http://swift.org/LICENSE.txt for license information --# See http://swift.org/CONTRIBUTORS.txt for Swift project authors -- --file(GLOB_RECURSE _LIBSWIFT_REGEX_PARSER_SOURCES -- "${SWIFT_PATH_TO_STRING_PROCESSING_SOURCE}/Sources/_RegexParser/*.swift") --set(LIBSWIFT_REGEX_PARSER_SOURCES) --foreach(source ${_LIBSWIFT_REGEX_PARSER_SOURCES}) -- file(TO_CMAKE_PATH "${source}" source) -- list(APPEND LIBSWIFT_REGEX_PARSER_SOURCES ${source}) --endforeach() --message(STATUS "Using Experimental String Processing library for libswift _RegexParser (${SWIFT_PATH_TO_STRING_PROCESSING_SOURCE}).") -- --add_swift_compiler_module(_CompilerRegexParser -- SOURCES -- "${LIBSWIFT_REGEX_PARSER_SOURCES}") -diff --git a/swift/SwiftCompilerSources/_RegexParser_Sources b/swift/SwiftCompilerSources/_RegexParser_Sources -deleted file mode 120000 -index 8c4799dab65a6..0000000000000 ---- a/swift/SwiftCompilerSources/_RegexParser_Sources -+++ /dev/null -@@ -1 +0,0 @@ --../../swift-experimental-string-processing/Sources/_RegexParser -\ No newline at end of file -diff --git a/swift/SwiftCompilerSources/stubs.cpp b/swift/SwiftCompilerSources/stubs.cpp -index 36df93a14d970..908eef9cad9ad 100644 ---- a/swift/SwiftCompilerSources/stubs.cpp -+++ b/swift/SwiftCompilerSources/stubs.cpp -@@ -13,9 +13,7 @@ - extern "C" { - - void initializeSwiftModules(); --void initializeSwiftParseModules(); - - } - - void initializeSwiftModules() {} --void initializeSwiftParseModules() {} -diff --git a/swift/include/swift/module.modulemap b/swift/include/swift/module.modulemap -index 2e421469dd1dd..4c8a45e88c69b 100644 ---- a/swift/include/swift/module.modulemap -+++ b/swift/include/swift/module.modulemap -@@ -12,10 +12,7 @@ module CBasicBridging { - - module ASTBridging { - header "AST/AnyFunctionRef.h" -- header "AST/ASTBridging.h" - header "AST/Builtins.h" -- header "AST/DiagnosticEngine.h" -- header "AST/DiagnosticConsumer.h" - header "AST/ForeignAsyncConvention.h" - header "AST/ForeignErrorConvention.h" - header "AST/SubstitutionMap.h" -@@ -41,8 +38,3 @@ module OptimizerBridging { - header "SILOptimizer/OptimizerBridging.h" - export * - } -- --module _RegexParserBridging { -- header "Parse/RegexParserBridging.h" -- export * --} -diff --git a/swift/include/swift/AST/ASTBridging.h b/swift/include/swift/AST/ASTBridging.h -deleted file mode 100644 -index d02968cf85c34..0000000000000 ---- a/swift/include/swift/AST/ASTBridging.h -+++ /dev/null -@@ -1,55 +0,0 @@ --//===--- ASTBridging.h - header for the swift SILBridging module ----------===// --// --// This source file is part of the Swift.org open source project --// --// Copyright (c) 2022 Apple Inc. and the Swift project authors --// Licensed under Apache License v2.0 with Runtime Library Exception --// --// See https://swift.org/LICENSE.txt for license information --// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors --// --//===----------------------------------------------------------------------===// -- --#ifndef SWIFT_AST_ASTBRIDGING_H --#define SWIFT_AST_ASTBRIDGING_H -- --#include "swift/Basic/BasicBridging.h" --#include "swift/Basic/Compiler.h" --#include "swift/AST/DiagnosticEngine.h" --#include --#include -- --SWIFT_BEGIN_NULLABILITY_ANNOTATIONS -- --//===----------------------------------------------------------------------===// --// Diagnostic Engine --//===----------------------------------------------------------------------===// -- --// NOTE: This must be the same underlying value as C++ 'swift::DiagID' defined --// in 'DiagnosticList.cpp'. --typedef enum ENUM_EXTENSIBILITY_ATTR(open) BridgedDiagID : uint32_t { --#define DIAG(KIND, ID, Options, Text, Signature) BridgedDiagID_##ID, --#include "swift/AST/DiagnosticsAll.def" --} BridgedDiagID; -- --typedef struct { -- void * _Nonnull object; --} BridgedDiagnosticEngine; -- --typedef struct { -- void *_Nullable object; --} BridgedOptionalDiagnosticEngine; -- --// FIXME: Can we bridge InFlightDiagnostic? --void DiagnosticEngine_diagnose(BridgedDiagnosticEngine, swift::SourceLoc loc, -- BridgedDiagID diagID, BridgedArrayRef arguments, -- swift::CharSourceRange highlight, -- BridgedArrayRef fixIts); -- --bool DiagnosticEngine_hadAnyError(BridgedDiagnosticEngine); -- --using ArrayRefOfDiagnosticArgument = llvm::ArrayRef; -- --SWIFT_END_NULLABILITY_ANNOTATIONS -- --#endif // SWIFT_AST_ASTBRIDGING_H -diff --git a/swift/include/swift/AST/BridgingUtils.h b/swift/include/swift/AST/BridgingUtils.h -deleted file mode 100644 -index 6f5a0dfbbbe90..0000000000000 ---- a/swift/include/swift/AST/BridgingUtils.h -+++ /dev/null -@@ -1,32 +0,0 @@ --//===--- BridgingUtils.h - utilities for swift bridging -------------------===// --// --// This source file is part of the Swift.org open source project --// --// Copyright (c) 2022 Apple Inc. and the Swift project authors --// Licensed under Apache License v2.0 with Runtime Library Exception --// --// See https://swift.org/LICENSE.txt for license information --// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors --// --//===----------------------------------------------------------------------===// -- --#ifndef SWIFT_AST_BRIDGINGUTILS_H --#define SWIFT_AST_BRIDGINGUTILS_H -- --#include "swift/AST/ASTBridging.h" --#include "swift/AST/DiagnosticEngine.h" -- --namespace swift { -- --inline BridgedDiagnosticEngine getBridgedDiagnosticEngine(DiagnosticEngine *D) { -- return {(void *)D}; --} --inline BridgedOptionalDiagnosticEngine --getBridgedOptionalDiagnosticEngine(DiagnosticEngine *D) { -- return {(void *)D}; --} -- --} // namespace swift -- --#endif -- -diff --git a/swift/include/swift/AST/CASTBridging.h b/swift/include/swift/AST/CASTBridging.h -index 0f798f961db94..fc2c07d5381f8 100644 ---- a/swift/include/swift/AST/CASTBridging.h -+++ b/swift/include/swift/AST/CASTBridging.h -@@ -107,7 +107,7 @@ typedef struct BridgedDiagnostic { - } BridgedDiagnostic; - - typedef struct BridgedDiagnosticEngine { -- void *raw; -+ void * _Nullable raw; - } BridgedDiagnosticEngine; - - typedef enum ENUM_EXTENSIBILITY_ATTR(open) BridgedMacroDefinitionKind : SwiftInt { -@@ -434,6 +434,53 @@ void Decl_dump(void *decl); - void Stmt_dump(void *statement); - void Type_dump(void *type); - -+//===----------------------------------------------------------------------===// -+// Regular expression literal parsing hooks -+//===----------------------------------------------------------------------===// -+ -+/// Attempt to lex a regex literal string. Takes the following arguments: -+/// -+/// - CurPtrPtr: A pointer to the current pointer of lexer, which should be the -+/// start of the literal. This will be advanced to the point at -+/// which the lexer should resume, or will remain the same if this -+/// is not a regex literal. -+/// - BufferEnd: A pointer to the end of the buffer, which should not be lexed -+/// past. -+/// - MustBeRegex: whether an error during lexing should be considered a regex -+/// literal, or some thing else. -+/// - BridgedDiagnosticEngine: RegexLiteralLexingFn should diagnose the -+/// token using this engine. -+/// -+/// Returns: A bool indicating whether lexing was completely erroneous, and -+/// cannot be recovered from, or false if there either was no error, -+/// or there was a recoverable error. -+typedef _Bool (*RegexLiteralLexingFn)( -+ /*CurPtrPtr*/ const char *_Nonnull *_Nonnull, -+ /*BufferEnd*/ const char *_Nonnull, -+ /*MustBeRegex*/ _Bool, BridgedDiagnosticEngine); -+void Parser_registerRegexLiteralLexingFn(RegexLiteralLexingFn _Nullable fn); -+ -+/// Parse a regex literal string. Takes the following arguments: -+/// -+/// - InputPtr: A null-terminated C string of the regex literal. -+/// - VersionOut: A buffer accepting a regex literal format version. -+/// - CaptureStructureOut: A buffer accepting a byte sequence representing the -+/// capture structure of the literal. -+/// - CaptureStructureSize: The size of the capture structure buffer. Must be -+/// greater than or equal to `strlen(InputPtr) + 3`. -+/// - DiagnosticBaseLoc: Start location of the regex literal. -+/// - BridgedDiagnosticEngine: RegexLiteralParsingFn should diagnose the -+/// parsing errors using this engine. -+/// -+/// Returns: A bool value indicating if there was an error while parsing. -+typedef _Bool (*RegexLiteralParsingFn)(/*InputPtr*/ const char *_Nonnull, -+ /*VersionOut*/ unsigned *_Nonnull, -+ /*CaptureStructureOut*/ void *_Nonnull, -+ /*CaptureStructureSize*/ unsigned, -+ /*DiagnosticBaseLoc*/ BridgedSourceLoc, -+ BridgedDiagnosticEngine); -+void Parser_registerRegexLiteralParsingFn(RegexLiteralParsingFn _Nullable fn); -+ - //===----------------------------------------------------------------------===// - // Plugins - //===----------------------------------------------------------------------===// -diff --git a/swift/include/swift/Parse/RegexParserBridging.h b/swift/include/swift/Parse/RegexParserBridging.h -deleted file mode 100644 -index 35ea10eeadbfc..0000000000000 ---- a/swift/include/swift/Parse/RegexParserBridging.h -+++ /dev/null -@@ -1,63 +0,0 @@ --//===-- RegexParserBridging.h --- Regex parser interface -*- C++ -*-===// --// --// This source file is part of the Swift.org open source project --// --// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors --// Licensed under Apache License v2.0 with Runtime Library Exception --// --// See https://swift.org/LICENSE.txt for license information --// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors --// --//===----------------------------------------------------------------------===// -- -- --#ifndef REGEX_PARSER_BRIDGING --#define REGEX_PARSER_BRIDGING -- --#include "swift/AST/ASTBridging.h" --#include -- --/// Attempt to lex a regex literal string. Takes the following arguments: --/// --/// - CurPtrPtr: A pointer to the current pointer of lexer, which should be the --/// start of the literal. This will be advanced to the point at --/// which the lexer should resume, or will remain the same if this --/// is not a regex literal. --/// - BufferEnd: A pointer to the end of the buffer, which should not be lexed --/// past. --/// - MustBeRegex: whether an error during lexing should be considered a regex --/// literal, or some thing else. --/// - BridgedOptionalDiagnosticEngine: RegexLiteralLexingFn should diagnose the --/// token using this engine. --/// --/// Returns: A bool indicating whether lexing was completely erroneous, and --/// cannot be recovered from, or false if there either was no error, --/// or there was a recoverable error. --typedef bool (*RegexLiteralLexingFn)( -- /*CurPtrPtr*/ const char *_Nonnull *_Nonnull, -- /*BufferEnd*/ const char *_Nonnull, -- /*MustBeRegex*/ bool, BridgedOptionalDiagnosticEngine); --void Parser_registerRegexLiteralLexingFn(RegexLiteralLexingFn _Nullable fn); -- --/// Parse a regex literal string. Takes the following arguments: --/// --/// - InputPtr: A null-terminated C string of the regex literal. --/// - VersionOut: A buffer accepting a regex literal format version. --/// - CaptureStructureOut: A buffer accepting a byte sequence representing the --/// capture structure of the literal. --/// - CaptureStructureSize: The size of the capture structure buffer. Must be --/// greater than or equal to `strlen(InputPtr) + 3`. --/// - DiagnosticBaseLoc: Start location of the regex literal. --/// - BridgedDiagnosticEngine: RegexLiteralParsingFn should diagnose the --/// parsing errors using this engine. --/// --/// Returns: A bool value indicating if there was an error while parsing. --typedef bool (*RegexLiteralParsingFn)(/*InputPtr*/ const char *_Nonnull, -- /*VersionOut*/ unsigned *_Nonnull, -- /*CaptureStructureOut*/ void *_Nonnull, -- /*CaptureStructureSize*/ unsigned, -- /*DiagnosticBaseLoc*/ swift::SourceLoc, -- BridgedDiagnosticEngine); --void Parser_registerRegexLiteralParsingFn(RegexLiteralParsingFn _Nullable fn); -- --#endif // REGEX_PARSER_BRIDGING -diff --git a/swift/lib/AST/ASTBridging.cpp b/swift/lib/AST/ASTBridging.cpp -deleted file mode 100644 -index 4b924f801637a..0000000000000 ---- a/swift/lib/AST/ASTBridging.cpp -+++ /dev/null -@@ -1,59 +0,0 @@ --//===--- ASTBridging.cpp - AST bridging functions -------------------------===// --// --// This source file is part of the Swift.org open source project --// --// Copyright (c) 2022 Apple Inc. and the Swift project authors --// Licensed under Apache License v2.0 with Runtime Library Exception --// --// See https://swift.org/LICENSE.txt for license information --// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors --// --//===----------------------------------------------------------------------===// -- --#include "swift/AST/ASTBridging.h" -- --#include "swift/AST/DiagnosticEngine.h" --#include "swift/Basic/BridgingUtils.h" -- --using namespace swift; -- --namespace { --/// BridgedDiagnosticEngine -> DiagnosticEngine *. --DiagnosticEngine *getDiagnosticEngine(const BridgedDiagnosticEngine &bridged) { -- return static_cast(bridged.object); --} -- --} // namespace -- --void DiagnosticEngine_diagnose( -- BridgedDiagnosticEngine bridgedEngine, SourceLoc loc, -- BridgedDiagID bridgedDiagID, -- BridgedArrayRef /*DiagnosticArgument*/ bridgedArguments, -- CharSourceRange highlight, -- BridgedArrayRef /*DiagnosticInfo::FixIt*/ bridgedFixIts) { -- auto *D = getDiagnosticEngine(bridgedEngine); -- -- auto diagID = static_cast(bridgedDiagID); -- SmallVector arguments; -- for (auto arg : getArrayRef(bridgedArguments)) { -- arguments.push_back(arg); -- } -- auto inflight = D->diagnose(loc, diagID, arguments); -- -- // Add highlight. -- if (highlight.isValid()) { -- inflight.highlightChars(highlight.getStart(), highlight.getEnd()); -- } -- -- // Add fix-its. -- for (auto fixIt : getArrayRef(bridgedFixIts)) { -- auto range = fixIt.getRange(); -- auto text = fixIt.getText(); -- inflight.fixItReplaceChars(range.getStart(), range.getEnd(), text); -- } --} -- --bool DiagnosticEngine_hadAnyError(BridgedDiagnosticEngine bridgedEngine) { -- auto *D = getDiagnosticEngine(bridgedEngine); -- return D->hadAnyError(); --} -diff --git a/swift/lib/AST/CMakeLists.txt b/swift/lib/AST/CMakeLists.txt -index 9e5590b7315db..7222554f3b0af 100644 ---- a/swift/lib/AST/CMakeLists.txt -+++ b/swift/lib/AST/CMakeLists.txt -@@ -10,7 +10,6 @@ add_swift_host_library(swiftAST STATIC - AccessNotes.cpp - AccessRequests.cpp - ArgumentList.cpp -- ASTBridging.cpp - ASTContext.cpp - ASTDemangler.cpp - ASTDumper.cpp -diff --git a/swift/lib/ASTGen/CMakeLists.txt b/swift/lib/ASTGen/CMakeLists.txt -index b80782f838e52..90367cf6caba1 100644 ---- a/swift/lib/ASTGen/CMakeLists.txt -+++ b/swift/lib/ASTGen/CMakeLists.txt -@@ -5,6 +5,26 @@ add_pure_swift_host_library(swiftLLVMJSON STATIC EMIT_MODULE - swiftBasic - ) - -+set(ASTGen_Swift_dependencies swiftLLVMJSON) -+ -+# If requested, build the regular expression parser into the compiler itself. -+if(SWIFT_BUILD_REGEX_PARSER_IN_COMPILER) -+ file(GLOB_RECURSE _LIBSWIFT_REGEX_PARSER_SOURCES -+ "${SWIFT_PATH_TO_STRING_PROCESSING_SOURCE}/Sources/_RegexParser/*.swift") -+ set(LIBSWIFT_REGEX_PARSER_SOURCES) -+ foreach(source ${_LIBSWIFT_REGEX_PARSER_SOURCES}) -+ file(TO_CMAKE_PATH "${source}" source) -+ list(APPEND LIBSWIFT_REGEX_PARSER_SOURCES ${source}) -+ endforeach() -+ message(STATUS "Using Experimental String Processing library for libswift _RegexParser (${SWIFT_PATH_TO_STRING_PROCESSING_SOURCE}).") -+ -+ add_pure_swift_host_library(_CompilerRegexParser STATIC EMIT_MODULE -+ "${LIBSWIFT_REGEX_PARSER_SOURCES}" -+ ) -+ -+ list(APPEND ASTGen_Swift_dependencies _CompilerRegexParser) -+endif() -+ - add_pure_swift_host_library(swiftASTGen STATIC - Sources/ASTGen/ASTGen.swift - Sources/ASTGen/Decls.swift -@@ -15,6 +35,7 @@ add_pure_swift_host_library(swiftASTGen STATIC - Sources/ASTGen/Macros.swift - Sources/ASTGen/Misc.swift - Sources/ASTGen/PluginHost.swift -+ Sources/ASTGen/Regex.swift - Sources/ASTGen/SourceFile.swift - Sources/ASTGen/SourceManager.swift - Sources/ASTGen/SourceManager+MacroExpansionContext.swift -@@ -34,5 +55,5 @@ add_pure_swift_host_library(swiftASTGen STATIC - SwiftSyntax::SwiftSyntaxBuilder - SwiftSyntax::SwiftSyntaxMacros - SwiftSyntax::SwiftSyntaxMacroExpansion -- swiftLLVMJSON -+ ${ASTGen_Swift_dependencies} - ) -diff --git a/swift/lib/ASTGen/Package.swift b/swift/lib/ASTGen/Package.swift -index 151ea07f960ba..4965d3be9b2ca 100644 ---- a/swift/lib/ASTGen/Package.swift -+++ b/swift/lib/ASTGen/Package.swift -@@ -24,6 +24,7 @@ let package = Package( - products: [ - .library(name: "swiftASTGen", targets: ["swiftASTGen"]), - .library(name: "swiftLLVMJSON", targets: ["swiftLLVMJSON"]), -+ .library(name: "_CompilerRegexParser", targets: ["_CompilerRegexParser"]), - ], - dependencies: [ - .package(path: "../../../swift-syntax") -@@ -42,7 +43,8 @@ let package = Package( - .product(name: "SwiftSyntaxBuilder", package: "swift-syntax"), - .product(name: "SwiftSyntaxMacros", package: "swift-syntax"), - .product(name: "SwiftSyntaxMacroExpansion", package: "swift-syntax"), -- "swiftLLVMJSON" -+ "swiftLLVMJSON", -+ "_CompilerRegexParser", - ], - path: "Sources/ASTGen", - swiftSettings: swiftSetttings -@@ -53,5 +55,11 @@ let package = Package( - path: "Sources/LLVMJSON", - swiftSettings: swiftSetttings - ), -+ .target( -+ name: "_CompilerRegexParser", -+ dependencies: [], -+ path: "_RegexParser_Sources", -+ swiftSettings: swiftSetttings -+ ), - ] - ) -diff --git a/swift/SwiftCompilerSources/Sources/Parse/Regex.swift b/swift/lib/ASTGen/Sources/ASTGen/Regex.swift -similarity index 80% -rename from swift/SwiftCompilerSources/Sources/Parse/Regex.swift -rename to swift/lib/ASTGen/Sources/ASTGen/Regex.swift -index a2229bc6fbc24..b8342fb909bc2 100644 ---- a/swift/SwiftCompilerSources/Sources/Parse/Regex.swift -+++ b/swift/lib/ASTGen/Sources/ASTGen/Regex.swift -@@ -10,14 +10,14 @@ - // - //===----------------------------------------------------------------------===// - --import _RegexParserBridging --import AST --import Basic -+import CBasicBridging -+import CASTBridging - - #if canImport(_CompilerRegexParser) - @_spi(CompilerInterface) import _CompilerRegexParser - --func registerRegexParser() { -+@_cdecl("initializeSwiftParseModules") -+public func initializeSwiftParseModules() { - Parser_registerRegexLiteralParsingFn(_RegexLiteralParsingFn) - Parser_registerRegexLiteralLexingFn(_RegexLiteralLexingFn) - } -@@ -46,8 +47,8 @@ private func _RegexLiteralLexingFn( - _ curPtrPtr: UnsafeMutablePointer>, - _ bufferEndPtr: UnsafePointer, - _ mustBeRegex: CBool, -- _ bridgedDiagnosticEngine: BridgedOptionalDiagnosticEngine --) -> /*CompletelyErroneous*/ CBool { -+ _ bridgedDiagnosticEngine: BridgedDiagnosticEngine -+) -> /*CompletelyErroneous*/ Bool { - let inputPtr = curPtrPtr.pointee - - guard let (resumePtr, error) = swiftCompilerLexRegexLiteral( -@@ -62,10 +63,16 @@ private func _RegexLiteralLexingFn( - - if let error = error { - // Emit diagnostic if diagnostics are enabled. -- if let diagEngine = DiagnosticEngine(bridged: bridgedDiagnosticEngine) { -- let startLoc = SourceLoc( -- locationInFile: error.location.assumingMemoryBound(to: UInt8.self))! -- diagEngine.diagnose(startLoc, .foreign_diagnostic, error.message) -+ if bridgedDiagnosticEngine.raw != nil { -+ let startLoc = BridgedSourceLoc(raw: error.location) -+ var message = error.message -+ let diag = message.withBridgedString { bridgedMessage in -+ Diagnostic_create( -+ bridgedDiagnosticEngine, .error, startLoc, -+ bridgedMessage -+ ) -+ } -+ Diagnostic_finish(diag) - } - return error.completelyErroneous - } -@@ -92,7 +99,7 @@ public func _RegexLiteralParsingFn( - _ versionOut: UnsafeMutablePointer, - _ captureStructureOut: UnsafeMutableRawPointer, - _ captureStructureSize: CUnsignedInt, -- _ bridgedDiagnosticBaseLoc: swift.SourceLoc, -+ _ bridgedDiagnosticBaseLoc: BridgedSourceLoc, - _ bridgedDiagnosticEngine: BridgedDiagnosticEngine - ) -> Bool { - let str = String(cString: inputPtr) -@@ -106,13 +113,20 @@ public func _RegexLiteralParsingFn( - versionOut.pointee = CUnsignedInt(version) - return false - } catch let error as CompilerParseError { -- var diagLoc = SourceLoc(bridged: bridgedDiagnosticBaseLoc) -- let diagEngine = DiagnosticEngine(bridged: bridgedDiagnosticEngine) -- if let _diagLoc = diagLoc, let errorLoc = error.location { -+ var diagLoc = bridgedDiagnosticBaseLoc -+ if diagLoc.raw != nil, let errorLoc = error.location { - let offset = str.utf8.distance(from: str.startIndex, to: errorLoc) -- diagLoc = _diagLoc.advanced(by: offset) -+ diagLoc = SourceLoc_advanced(diagLoc, offset) -+ } -+ -+ var message = error.message -+ let diag = message.withBridgedString { bridgedMessage in -+ Diagnostic_create( -+ bridgedDiagnosticEngine, .error, diagLoc, -+ bridgedMessage -+ ) - } -- diagEngine.diagnose(diagLoc, .foreign_diagnostic, error.message) -+ Diagnostic_finish(diag) - return true - } catch { - fatalError("Expected CompilerParseError") -diff --git a/swift/lib/ASTGen/_RegexParser_Sources b/swift/lib/ASTGen/_RegexParser_Sources -new file mode 120000 -index 0000000000000..b52a98d0897ed ---- /dev/null -+++ b/swift/lib/ASTGen/_RegexParser_Sources -@@ -0,0 +1 @@ -+../../../swift-experimental-string-processing/Sources/_RegexParser -\ No newline at end of file -diff --git a/swift/lib/DriverTool/driver.cpp b/swift/lib/DriverTool/driver.cpp -index af3b576aef2a2..a9666e628b95e 100644 ---- a/swift/lib/DriverTool/driver.cpp -+++ b/swift/lib/DriverTool/driver.cpp -@@ -220,6 +220,8 @@ static llvm::SmallVector eraseFirstArg(ArrayRef - static int run_driver(StringRef ExecName, - ArrayRef argv, - const ArrayRef originalArgv) { -+ initializeSwiftParseModules(); -+ - // This is done here and not done in FrontendTool.cpp, because - // FrontendTool.cpp is linked to tools, which don't use swift modules. - initializeSwiftModules(); -diff --git a/swift/tools/sil-opt/SILOpt.cpp b/swift/tools/sil-opt/SILOpt.cpp -index b1248d8994537..89d15bd58e234 100644 ---- a/swift/tools/sil-opt/SILOpt.cpp -+++ b/swift/tools/sil-opt/SILOpt.cpp -@@ -20,7 +20,6 @@ - #include "swift/AST/SILOptions.h" - #include "swift/Basic/FileTypes.h" - #include "swift/Basic/LLVMInitialize.h" --#include "swift/Basic/InitializeSwiftModules.h" - #include "swift/Basic/QuotedString.h" - #include "swift/Frontend/DiagnosticVerifier.h" - #include "swift/Frontend/Frontend.h" -diff --git a/swift/lib/Parse/Lexer.cpp b/swift/lib/Parse/Lexer.cpp -index 80e0a7182b711..b0c3dd032314f 100644 ---- a/swift/lib/Parse/Lexer.cpp -+++ b/swift/lib/Parse/Lexer.cpp -@@ -15,13 +15,12 @@ - //===----------------------------------------------------------------------===// - - #include "swift/Parse/Lexer.h" --#include "swift/AST/BridgingUtils.h" -+#include "swift/AST/CASTBridging.h" - #include "swift/AST/DiagnosticsParse.h" - #include "swift/AST/Identifier.h" - #include "swift/Basic/LangOptions.h" - #include "swift/Basic/SourceManager.h" - #include "swift/Parse/Confusables.h" --#include "swift/Parse/RegexParserBridging.h" - #include "llvm/ADT/SmallString.h" - #include "llvm/ADT/StringSwitch.h" - #include "llvm/ADT/Twine.h" -@@ -35,9 +34,12 @@ - - // Regex lexing delivered via libSwift. - static RegexLiteralLexingFn regexLiteralLexingFn = nullptr; -+ -+#if SWIFT_BUILD_SWIFT_SYNTAX - void Parser_registerRegexLiteralLexingFn(RegexLiteralLexingFn fn) { - regexLiteralLexingFn = fn; - } -+#endif - - using namespace swift; - -@@ -2090,7 +2092,7 @@ const char *Lexer::tryScanRegexLiteral(const char *TokStart, bool MustBeRegex, - // recovered from. - auto *Ptr = TokStart; - CompletelyErroneous = regexLiteralLexingFn( -- &Ptr, BufferEnd, MustBeRegex, getBridgedOptionalDiagnosticEngine(Diags)); -+ &Ptr, BufferEnd, MustBeRegex, BridgedDiagnosticEngine{Diags}); - - // If we didn't make any lexing progress, this isn't a regex literal and we - // should fallback to lexing as something else. -diff --git a/lib/Parse/ParseRegex.cpp b/swift/lib/Parse/ParseRegex.cpp -index 5ed804653d3e0..14d76e941cc27 100644 ---- a/swift/lib/Parse/ParseRegex.cpp -+++ b/swift/lib/Parse/ParseRegex.cpp -@@ -14,17 +14,20 @@ - // - //===----------------------------------------------------------------------===// - --#include "swift/AST/BridgingUtils.h" - #include "swift/AST/DiagnosticsParse.h" --#include "swift/Basic/BridgingUtils.h" - #include "swift/Parse/Parser.h" -+#include "swift/AST/CASTBridging.h" - - // Regex parser delivered via Swift modules. --#include "swift/Parse/RegexParserBridging.h" - static RegexLiteralParsingFn regexLiteralParsingFn = nullptr; -+ -+#if SWIFT_BUILD_SWIFT_SYNTAX - void Parser_registerRegexLiteralParsingFn(RegexLiteralParsingFn fn) { - regexLiteralParsingFn = fn; - } -+#else -+extern "C" void initializeSwiftParseModules() { } -+#endif - - using namespace swift; - -@@ -44,8 +47,8 @@ ParserResult Parser::parseExprRegexLiteral() { - regexLiteralParsingFn(regexText.str().c_str(), &version, - /*captureStructureOut*/ capturesBuf.data(), - /*captureStructureSize*/ capturesBuf.size(), -- /*diagBaseLoc*/ Tok.getLoc(), -- getBridgedDiagnosticEngine(&Diags)); -+ /*diagBaseLoc*/ BridgedSourceLoc{Tok.getLoc().getOpaquePointerValue()}, -+ BridgedDiagnosticEngine{&Diags}); - auto loc = consumeToken(); - SourceMgr.recordRegexLiteralStartLoc(loc); - -diff --git a/test/IDE/complete_regex.swift b/swift/test/IDE/complete_regex.swift -index 587c3b24324ca..c5da4e05e02f9 100644 ---- a/swift/test/IDE/complete_regex.swift -+++ b/swift/test/IDE/complete_regex.swift -@@ -1,4 +1,4 @@ --// REQUIRES: swift_in_compiler -+// REQUIRES: swift_swift_parser - - // RUN: %empty-directory(%t) - // RUN: %target-swift-ide-test -enable-bare-slash-regex -batch-code-completion -source-filename %s -filecheck %raw-FileCheck -completion-output-dir %t -diff --git a/test/SourceKit/CodeComplete/rdar95772803.swift b/swift/test/SourceKit/CodeComplete/rdar95772803.swift -index b68bca2571ad9..eec4f67e38ad2 100644 ---- a/swift/test/SourceKit/CodeComplete/rdar95772803.swift -+++ b/swift/test/SourceKit/CodeComplete/rdar95772803.swift -@@ -11,4 +11,4 @@ var qux: Regex { / x}/ } - // RUN: -req=complete -pos=4:28 %s -- -enable-bare-slash-regex %s == \ - // RUN: -req=complete -pos=5:28 %s -- -enable-bare-slash-regex %s - --// REQUIRES: swift_in_compiler -+// REQUIRES: swift_swift_parser -diff --git a/test/SourceKit/Sema/sema_regex.swift b/swift/test/SourceKit/Sema/sema_regex.swift -index 2c657b36d4b7b..8620b9f13cf95 100644 ---- a/swift/test/SourceKit/Sema/sema_regex.swift -+++ b/swift/test/SourceKit/Sema/sema_regex.swift -@@ -2,7 +2,7 @@ public func retRegex() -> Regex { - /foo/ - } - --// REQUIRES: swift_in_compiler -+// REQUIRES: swift_swift_parser - // RUN: %sourcekitd-test -req=sema %s -- %s -Xfrontend -enable-bare-slash-regex -Xfrontend -disable-availability-checking | %FileCheck %s - - // CHECK: [ -diff --git a/test/StringProcessing/Frontend/enable-flag.swift b/swift/test/StringProcessing/Frontend/enable-flag.swift -index 601cdb71e1a59..b1768a913dcc6 100644 ---- a/swift/test/StringProcessing/Frontend/enable-flag.swift -+++ b/swift/test/StringProcessing/Frontend/enable-flag.swift -@@ -2,7 +2,7 @@ - // RUN: %target-typecheck-verify-swift -disable-availability-checking -enable-experimental-string-processing -enable-bare-slash-regex - // RUN: %target-typecheck-verify-swift -disable-availability-checking -disable-experimental-string-processing -enable-experimental-string-processing -enable-bare-slash-regex - --// REQUIRES: swift_in_compiler -+// REQUIRES: swift_swift_parser - - prefix operator / - -diff --git a/test/StringProcessing/Parse/forward-slash-regex-disabled.swift b/swift/test/StringProcessing/Parse/forward-slash-regex-disabled.swift -index 4c491a4a863a0..db403c97dfea8 100644 ---- a/swift/test/StringProcessing/Parse/forward-slash-regex-disabled.swift -+++ b/swift/test/StringProcessing/Parse/forward-slash-regex-disabled.swift -@@ -1,6 +1,6 @@ - // RUN: %target-typecheck-verify-swift -disable-availability-checking - --// REQUIRES: swift_in_compiler -+// REQUIRES: swift_swift_parser - - prefix operator / - prefix operator ^/ -diff --git a/test/StringProcessing/Parse/forward-slash-regex-skipping-allowed.swift b/swift/test/StringProcessing/Parse/forward-slash-regex-skipping-allowed.swift -index e9b9c2b122c47..1974bd55c6044 100644 ---- a/swift/test/StringProcessing/Parse/forward-slash-regex-skipping-allowed.swift -+++ b/swift/test/StringProcessing/Parse/forward-slash-regex-skipping-allowed.swift -@@ -4,7 +4,7 @@ - // RUN: %{python} %utils/process-stats-dir.py --set-csv-baseline %t/stats.csv %t - // RUN: %FileCheck -input-file %t/stats.csv %s - --// REQUIRES: swift_in_compiler -+// REQUIRES: swift_swift_parser - - // Make sure we can skip in all of the below cases. - -diff --git a/test/StringProcessing/Parse/forward-slash-regex-skipping-invalid.swift b/swift/test/StringProcessing/Parse/forward-slash-regex-skipping-invalid.swift -index ccebc28bee855..23e3e8c16f9f0 100644 ---- a/swift/test/StringProcessing/Parse/forward-slash-regex-skipping-invalid.swift -+++ b/swift/test/StringProcessing/Parse/forward-slash-regex-skipping-invalid.swift -@@ -2,7 +2,7 @@ - // RUN: %target-typecheck-verify-swift -enable-bare-slash-regex -disable-availability-checking -experimental-skip-non-inlinable-function-bodies-without-types - // RUN: %target-typecheck-verify-swift -enable-bare-slash-regex -disable-availability-checking -experimental-skip-non-inlinable-function-bodies - --// REQUIRES: swift_in_compiler -+// REQUIRES: swift_swift_parser - - // We don't consider this a regex literal when skipping as it has an initial - // space. -diff --git a/test/StringProcessing/Parse/forward-slash-regex-skipping.swift b/swift/test/StringProcessing/Parse/forward-slash-regex-skipping.swift -index e3e9c9d07048b..031bef3a1ef20 100644 ---- a/swift/test/StringProcessing/Parse/forward-slash-regex-skipping.swift -+++ b/swift/test/StringProcessing/Parse/forward-slash-regex-skipping.swift -@@ -2,7 +2,7 @@ - // RUN: %target-typecheck-verify-swift -enable-bare-slash-regex -disable-availability-checking -experimental-skip-non-inlinable-function-bodies-without-types - // RUN: %target-typecheck-verify-swift -enable-bare-slash-regex -disable-availability-checking -experimental-skip-non-inlinable-function-bodies - --// REQUIRES: swift_in_compiler -+// REQUIRES: swift_swift_parser - - // Make sure we properly handle `/.../` regex literals in skipped function - // bodies. Currently we detect them and avoid skipping, but in the future we -diff --git a/test/StringProcessing/Parse/forward-slash-regex.swift b/swift/test/StringProcessing/Parse/forward-slash-regex.swift -index 22c6a654e6da0..f4990d4fcb4d4 100644 ---- a/swift/test/StringProcessing/Parse/forward-slash-regex.swift -+++ b/swift/test/StringProcessing/Parse/forward-slash-regex.swift -@@ -1,5 +1,5 @@ - // RUN: %target-typecheck-verify-swift -enable-bare-slash-regex -disable-availability-checking -typo-correction-limit 0 --// REQUIRES: swift_in_compiler -+// REQUIRES: swift_swift_parser - // REQUIRES: concurrency - - prefix operator / -diff --git a/test/StringProcessing/Parse/prefix-slash.swift b/swift/test/StringProcessing/Parse/prefix-slash.swift -index 4be97f55397e2..dbe33cac8d91c 100644 ---- a/swift/test/StringProcessing/Parse/prefix-slash.swift -+++ b/swift/test/StringProcessing/Parse/prefix-slash.swift -@@ -1,5 +1,5 @@ - // RUN: %target-typecheck-verify-swift -enable-bare-slash-regex -disable-availability-checking --// REQUIRES: swift_in_compiler -+// REQUIRES: swift_swift_parser - - // Test the behavior of prefix '/' with regex literals enabled. - -diff --git a/test/StringProcessing/Parse/regex.swift b/swift/test/StringProcessing/Parse/regex.swift -index 797fc2af85eec..a25db9de0019c 100644 ---- a/swift/test/StringProcessing/Parse/regex.swift -+++ b/swift/test/StringProcessing/Parse/regex.swift -@@ -1,5 +1,5 @@ - // RUN: %target-typecheck-verify-swift -enable-bare-slash-regex -disable-availability-checking --// REQUIRES: swift_in_compiler -+// REQUIRES: swift_swift_parser - - _ = /abc/ - _ = #/abc/# -diff --git a/test/StringProcessing/Parse/regex_parse_end_of_buffer.swift b/swift/test/StringProcessing/Parse/regex_parse_end_of_buffer.swift -index 5c62181c0c8c2..177dcd66bbf35 100644 ---- a/swift/test/StringProcessing/Parse/regex_parse_end_of_buffer.swift -+++ b/swift/test/StringProcessing/Parse/regex_parse_end_of_buffer.swift -@@ -1,7 +1,7 @@ - // RUN: %target-typecheck-verify-swift -enable-bare-slash-regex -disable-availability-checking --// REQUIRES: swift_in_compiler -+// REQUIRES: swift_swift_parser - - // Note there is purposefully no trailing newline here. - // expected-error@+2:20 {{unterminated regex literal}} - // expected-error@+1:25 {{cannot parse regular expression: expected ')'}} --var unterminated = #/(xy -\ No newline at end of file -+var unterminated = #/(xy -diff --git a/test/StringProcessing/Parse/regex_parse_error.swift b/swift/test/StringProcessing/Parse/regex_parse_error.swift -index c719e33ad9b80..ffa05d1ac9a8c 100644 ---- a/swift/test/StringProcessing/Parse/regex_parse_error.swift -+++ b/swift/test/StringProcessing/Parse/regex_parse_error.swift -@@ -1,5 +1,5 @@ - // RUN: %target-typecheck-verify-swift -enable-bare-slash-regex -disable-availability-checking --// REQUIRES: swift_in_compiler -+// REQUIRES: swift_swift_parser - - _ = /(/ // expected-error@:7 {{expected ')'}} - _ = #/(/# // expected-error@:8 {{expected ')'}} -diff --git a/test/StringProcessing/Runtime/regex_basic.swift b/swift/test/StringProcessing/Runtime/regex_basic.swift -index 9ad6c31d30662..498894cd1dff6 100644 ---- a/swift/test/StringProcessing/Runtime/regex_basic.swift -+++ b/swift/test/StringProcessing/Runtime/regex_basic.swift -@@ -1,6 +1,6 @@ - // RUN: %target-run-simple-swift(-Xfrontend -enable-bare-slash-regex) - --// REQUIRES: swift_in_compiler,string_processing,executable_test -+// REQUIRES: swift_swift_parser,string_processing,executable_test - - import StdlibUnittest - -diff --git a/test/StringProcessing/SILGen/regex_literal_silgen.swift b/swift/test/StringProcessing/SILGen/regex_literal_silgen.swift -index 7d16c82d81040..3cfa2bba161af 100644 ---- a/swift/test/StringProcessing/SILGen/regex_literal_silgen.swift -+++ b/swift/test/StringProcessing/SILGen/regex_literal_silgen.swift -@@ -1,5 +1,5 @@ - // RUN: %target-swift-frontend -emit-silgen -enable-bare-slash-regex -disable-availability-checking %s | %FileCheck %s --// REQUIRES: swift_in_compiler -+// REQUIRES: swift_swift_parser - - var s = #/abc/# - // CHECK: [[REGEX_STR_LITERAL:%[0-9]+]] = string_literal utf8 "#/abc/#" -diff --git a/test/StringProcessing/Sema/regex_builder_fix_import_after_imports.swift b/swift/test/StringProcessing/Sema/regex_builder_fix_import_after_imports.swift -index 29e7881822ac1..acaf229511b91 100644 ---- a/swift/test/StringProcessing/Sema/regex_builder_fix_import_after_imports.swift -+++ b/swift/test/StringProcessing/Sema/regex_builder_fix_import_after_imports.swift -@@ -7,7 +7,7 @@ - - // RUN: %target-typecheck-verify-swift -enable-bare-slash-regex -disable-availability-checking -I %t - --// REQUIRES: swift_in_compiler -+// REQUIRES: swift_swift_parser - - import A - -diff --git a/test/StringProcessing/Sema/regex_builder_fix_import_decl.swift b/swift/test/StringProcessing/Sema/regex_builder_fix_import_decl.swift -index 31feb6744497d..a0df60f6cdfd3 100644 ---- a/swift/test/StringProcessing/Sema/regex_builder_fix_import_decl.swift -+++ b/swift/test/StringProcessing/Sema/regex_builder_fix_import_decl.swift -@@ -1,6 +1,6 @@ - // RUN: %target-typecheck-verify-swift -enable-bare-slash-regex -disable-availability-checking - --// REQUIRES: swift_in_compiler -+// REQUIRES: swift_swift_parser - - struct S { - func foo() { -diff --git a/test/StringProcessing/Sema/regex_builder_fix_import_top_level.swift b/swift/test/StringProcessing/Sema/regex_builder_fix_import_top_level.swift -index eaae05546891c..155b43f50d71a 100644 ---- a/swift/test/StringProcessing/Sema/regex_builder_fix_import_top_level.swift -+++ b/swift/test/StringProcessing/Sema/regex_builder_fix_import_top_level.swift -@@ -1,6 +1,6 @@ - // RUN: %target-typecheck-verify-swift -enable-bare-slash-regex -disable-availability-checking - --// REQUIRES: swift_in_compiler -+// REQUIRES: swift_swift_parser - - Regex {} // expected-error {{regex builder requires the 'RegexBuilder' module be imported'}} {{5:1-1=import RegexBuilder\n\n}} - -diff --git a/test/StringProcessing/Sema/regex_builder_unavailable.swift b/swift/test/StringProcessing/Sema/regex_builder_unavailable.swift -index 38bf6049b31d3..7167315c87a34 100644 ---- a/swift/test/StringProcessing/Sema/regex_builder_unavailable.swift -+++ b/swift/test/StringProcessing/Sema/regex_builder_unavailable.swift -@@ -1,6 +1,6 @@ - // RUN: %target-typecheck-verify-swift -enable-bare-slash-regex -target %target-cpu-apple-macosx12.0 - --// REQUIRES: swift_in_compiler -+// REQUIRES: swift_swift_parser - // REQUIRES: OS=macosx - - import RegexBuilder -diff --git a/test/StringProcessing/Sema/regex_literal_availability.swift b/swift/test/StringProcessing/Sema/regex_literal_availability.swift -index ec68855876783..bcf8cdce2d0fb 100644 ---- a/swift/test/StringProcessing/Sema/regex_literal_availability.swift -+++ b/swift/test/StringProcessing/Sema/regex_literal_availability.swift -@@ -1,6 +1,6 @@ - // RUN: %target-typecheck-verify-swift -enable-bare-slash-regex -target %target-cpu-apple-macosx12.0 - --// REQUIRES: swift_in_compiler -+// REQUIRES: swift_swift_parser - // REQUIRES: OS=macosx - - _ = /x/ // expected-error {{'Regex' is only available in}} -diff --git a/test/StringProcessing/Sema/regex_literal_diagnostics.swift b/swift/test/StringProcessing/Sema/regex_literal_diagnostics.swift -index 0a0f0629669ba..e3ec4b77c70dd 100644 ---- a/swift/test/StringProcessing/Sema/regex_literal_diagnostics.swift -+++ b/swift/test/StringProcessing/Sema/regex_literal_diagnostics.swift -@@ -1,6 +1,6 @@ - // RUN: %target-typecheck-verify-swift -enable-bare-slash-regex -disable-availability-checking - --// REQUIRES: swift_in_compiler -+// REQUIRES: swift_swift_parser - - postfix operator ^^ - postfix func ^^ (_ x: T) -> T { x } -diff --git a/test/StringProcessing/Sema/regex_literal_type_inference.swift b/swift/test/StringProcessing/Sema/regex_literal_type_inference.swift -index 9cce7a1b0e76e..5ea94df139e08 100644 ---- a/swift/test/StringProcessing/Sema/regex_literal_type_inference.swift -+++ b/swift/test/StringProcessing/Sema/regex_literal_type_inference.swift -@@ -1,5 +1,5 @@ - // RUN: %target-typecheck-verify-swift -enable-bare-slash-regex -disable-availability-checking --// REQUIRES: swift_in_compiler -+// REQUIRES: swift_swift_parser - - let r0 = #/./# - let _: Regex = r0 -diff --git a/test/StringProcessing/Sema/string_processing_import.swift b/swift/test/StringProcessing/Sema/string_processing_import.swift -index 5a83931364d6b..200e0729f8b78 100644 ---- a/swift/test/StringProcessing/Sema/string_processing_import.swift -+++ b/swift/test/StringProcessing/Sema/string_processing_import.swift -@@ -1,5 +1,5 @@ - // RUN: %target-typecheck-verify-swift -disable-implicit-string-processing-module-import -disable-availability-checking --// REQUIRES: swift_in_compiler -+// REQUIRES: swift_swift_parser - - // expected-error @+1 {{missing 'Regex' declaration, probably because the '_StringProcessing' module was not imported properly}} - let r0 = #/./# -diff --git a/tools/SourceKit/tools/sourcekitd/lib/Service/Requests.cpp b/swift/tools/SourceKit/tools/sourcekitd/lib/Service/Requests.cpp -index dc9990e4ff141..54018ab10fca4 100644 ---- a/swift/tools/SourceKit/tools/sourcekitd/lib/Service/Requests.cpp -+++ b/swift/tools/SourceKit/tools/sourcekitd/lib/Service/Requests.cpp -@@ -111,6 +111,7 @@ void sourcekitd::initializeService( - StringRef diagnosticDocumentationPath, - std::function postNotification) { - INITIALIZE_LLVM(); -+ initializeSwiftParseModules(); - initializeSwiftModules(); - llvm::EnablePrettyStackTrace(); - GlobalCtx = new SourceKit::Context(swiftExecutablePath, runtimeLibPath, -diff --git a/tools/swift-ide-test/swift-ide-test.cpp b/swift/tools/swift-ide-test/swift-ide-test.cpp -index e676be519090f..f6e7a8ae6998b 100644 ---- a/swift/tools/swift-ide-test/swift-ide-test.cpp -+++ b/swift/tools/swift-ide-test/swift-ide-test.cpp -@@ -4240,6 +4240,7 @@ std::string getDriverPath(StringRef MainExecutablePath) { - int main(int argc, char *argv[]) { - PROGRAM_START(argc, argv); - INITIALIZE_LLVM(); -+ initializeSwiftParseModules(); - initializeSwiftModules(); - - std::string mainExecutablePath = llvm::sys::fs::getMainExecutable( diff --git a/packages/swift/swift-move-syntax-build.patch b/packages/swift/swift-move-syntax-build.patch deleted file mode 100644 index 69b5da1445..0000000000 --- a/packages/swift/swift-move-syntax-build.patch +++ /dev/null @@ -1,1571 +0,0 @@ -From 62b0c38c93e0feb589b1e9b915831f45118a3ace -From: Ben Barham -Date: Tue, 16 May 2023 16:25:12 -0700 -Subject: [PATCH 1/7] [CMake] Replace early swift-syntax with FetchContent - -Use FetchContent to include swift-syntax directly in swift. This can be -thought of as an `add_subdirectory` for a directory outside the root. - -The default build directory will be `_deps/swiftsyntax-subbuild/`, though -the modules and shared libraries will be built in `lib/swift/host` by -passing down `SWIFT_HOST_LIBRARIES_DEST_DIR` to avoid copying them as we -were doing previously. - -diff --git a/swift/CMakeLists.txt b/swift/CMakeLists.txt -index 2eeaf61e37423..e052c618fe5f8 100644 ---- a/swift/CMakeLists.txt -+++ b/swift/CMakeLists.txt -@@ -94,6 +94,7 @@ include(CMakeDependentOption) - include(CheckLanguage) - include(GNUInstallDirs) - include(SwiftImplicitImport) -+include(FetchContent) - - # Enable Swift for the host compiler build if we have the language. It is - # optional until we have a bootstrap story. -@@ -697,10 +698,9 @@ if(CMAKE_C_COMPILER_ID MATCHES Clang) - add_compile_options($<$:-Werror=c++98-compat-extra-semi>) - endif() - --# Make sure we know where swift-syntax is because we need it to build the parser. --if(NOT EXISTS "${SWIFT_PATH_TO_SWIFT_SYNTAX_SOURCE}") -- message(SEND_ERROR "swift-syntax is required to build the Swift compiler. Please run update-checkout or specify SWIFT_PATH_TO_SWIFT_SYNTAX_SOURCE") --endif() -+option(SWIFT_BUILD_SWIFT_SYNTAX -+ "Enable building swift syntax" -+ FALSE) - - set(SWIFT_BUILD_HOST_DISPATCH FALSE) - if(SWIFT_ENABLE_DISPATCH AND NOT CMAKE_SYSTEM_NAME STREQUAL "Darwin") -@@ -800,7 +800,6 @@ include(SwiftConfigureSDK) - include(SwiftComponents) - include(SwiftList) - include(AddPureSwift) --include(SetRPATH) - - # Configure swift include, install, build components. - swift_configure_components() -@@ -836,7 +835,7 @@ elseif(BOOTSTRAPPING_MODE MATCHES "BOOTSTRAPPING.*") - else() - set(BOOTSTRAPPING_MODE "HOSTTOOLS") - endif() --elseif(BOOTSTRAPPING_MODE STREQUAL "HOSTTOOLS" OR SWIFT_SWIFT_PARSER) -+elseif(BOOTSTRAPPING_MODE STREQUAL "HOSTTOOLS" OR SWIFT_BUILD_SWIFT_SYNTAX) - # We are building using a pre-installed host toolchain but not bootstrapping - # the Swift modules. This happens when building using 'build-tooling-libs' - # where we haven't built a new Swift compiler. Use the Swift compiler from the -@@ -844,6 +843,14 @@ elseif(BOOTSTRAPPING_MODE STREQUAL "HOSTTOOLS" OR SWIFT_SWIFT_PARSER) - set(SWIFT_EXEC_FOR_SWIFT_MODULES "${CMAKE_Swift_COMPILER}") - endif() - -+if(SWIFT_BUILD_SWIFT_SYNTAX) -+ # Only "HOSTTOOLS" is supported in Linux when Swift parser integration is enabled. -+ if(SWIFT_HOST_VARIANT_SDK MATCHES "LINUX|ANDROID|OPENBSD|FREEBSD" AND NOT BOOTSTRAPPING_MODE STREQUAL "HOSTTOOLS") -+ message(WARNING "Force setting BOOTSTRAPPING=HOSTTOOLS because Swift parser integration is enabled") -+ set(BOOTSTRAPPING_MODE "HOSTTOOLS") -+ endif() -+endif() -+ - if(BOOTSTRAPPING_MODE MATCHES "HOSTTOOLS|.*-WITH-HOSTLIBS") - if(SWIFT_ENABLE_ARRAY_COW_CHECKS) - message(STATUS "array COW checks disabled when building the swift modules with host libraries") -@@ -950,25 +957,6 @@ if(XCODE) - set(SWIFT_SDKS "OSX") - endif() - --# When we have the early SwiftSyntax build, we can include its parser. --if(SWIFT_PATH_TO_EARLYSWIFTSYNTAX_BUILD_DIR) -- set(SWIFT_PATH_TO_EARLYSWIFTSYNTAX_TARGETS -- ${SWIFT_PATH_TO_EARLYSWIFTSYNTAX_BUILD_DIR}/cmake/SwiftSyntaxTargets.cmake) -- if(NOT EXISTS "${SWIFT_PATH_TO_EARLYSWIFTSYNTAX_TARGETS}") -- message(STATUS "Skipping Swift Swift parser integration due to missing early SwiftSyntax") -- else() -- set(SWIFT_SWIFT_PARSER TRUE) -- include(${SWIFT_PATH_TO_EARLYSWIFTSYNTAX_TARGETS}) -- -- if(SWIFT_HOST_VARIANT_SDK MATCHES "LINUX|ANDROID|OPENBSD|FREEBSD" AND NOT BOOTSTRAPPING_MODE STREQUAL "HOSTTOOLS") -- # Only "HOSTTOOLS" is supported in Linux when Swift parser integration is enabled. -- message(WARNING "Force setting BOOTSTRAPPING=HOSTTOOLS because Swift parser integration is enabled") -- set(BOOTSTRAPPING_MODE "HOSTTOOLS") -- endif() -- endif() --endif() -- -- - # FIXME: the parameters we specify in SWIFT_SDKS are lacking architecture specifics, - # so we need to hard-code it. For example, the SDK for Android is just 'ANDROID', - # and we have to specify SWIFT_SDK_ANDROID_ARCHITECTURES separately. -@@ -1169,13 +1157,17 @@ if("${CMAKE_SYSTEM_NAME}" STREQUAL "Darwin" AND NOT CMAKE_CROSSCOMPILING) - set(CMAKE_OSX_DEPLOYMENT_TARGET "") - endif() - -+swift_get_host_triple(SWIFT_HOST_TRIPLE) -+set(SWIFT_HOST_MODULE_TRIPLE "${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_ARCH_${SWIFT_HOST_VARIANT_ARCH}_MODULE}") -+set(SWIFT_HOST_LIBRARIES_DEST_DIR "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/swift/host") -+ - if(SWIFT_INCLUDE_TOOLS) - message(STATUS "Building host Swift tools for ${SWIFT_HOST_VARIANT_SDK} ${SWIFT_HOST_VARIANT_ARCH}") - message(STATUS " Build type: ${CMAKE_BUILD_TYPE}") - message(STATUS " Assertions: ${LLVM_ENABLE_ASSERTIONS}") - message(STATUS " LTO: ${SWIFT_TOOLS_ENABLE_LTO}") - message(STATUS " Bootstrapping: ${BOOTSTRAPPING_MODE}") -- message(STATUS " Swift parser: ${SWIFT_SWIFT_PARSER}") -+ message(STATUS " Swift parser: ${SWIFT_BUILD_SWIFT_SYNTAX}") - message(STATUS "") - else() - message(STATUS "Not building host Swift tools") -@@ -1326,6 +1318,35 @@ endif() - add_subdirectory(include) - - if(SWIFT_INCLUDE_TOOLS) -+ # Include 'swift-syntax'. -+ # This is a function because we want to set some 'CMAKE_*' variables temporarily.' -+ # TODO: Replace this with 'block()' after CMake 3.25 -+ function(include_swift_syntax) -+ if(NOT SWIFT_BUILD_SWIFT_SYNTAX) -+ return() -+ endif() -+ if(NOT EXISTS "${SWIFT_PATH_TO_SWIFT_SYNTAX_SOURCE}") -+ message(SEND_ERROR "swift-syntax is required to build the Swift compiler. Please run update-checkout or specify SWIFT_PATH_TO_SWIFT_SYNTAX_SOURCE") -+ return() -+ endif() -+ -+ set(CMAKE_Swift_COMPILER_TARGET ${SWIFT_HOST_TRIPLE}) -+ set(BUILD_SHARED_LIBS ON) -+ # All libraries in 'swift-syntax' goes to 'lib/swift/host'. -+ set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${SWIFT_HOST_LIBRARIES_DEST_DIR}") -+ set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${SWIFT_HOST_LIBRARIES_DEST_DIR}") -+ if(SWIFT_HOST_VARIANT_SDK MATCHES "LINUX|ANDROID|OPENBSD|FREEBSD") -+ set(SWIFT_HOST_LIBRARIES_RPATH "$ORIGIN;$ORIGIN/../..") -+ endif() -+ -+ file(TO_CMAKE_PATH "${SWIFT_PATH_TO_SWIFT_SYNTAX_SOURCE}" swift_syntax_path) -+ FetchContent_Declare(SwiftSyntax -+ SOURCE_DIR "${swift_syntax_path}" -+ ) -+ FetchContent_MakeAvailable(SwiftSyntax) -+ endfunction() -+ include_swift_syntax() -+ - add_subdirectory(lib) - - # SwiftCompilerSources must come before "tools". -diff --git a/swift/cmake/modules/AddPureSwift.cmake b/swift/cmake/modules/AddPureSwift.cmake -index ad177634dbca9..2fed86ca12abf 100644 ---- a/swift/cmake/modules/AddPureSwift.cmake -+++ b/swift/cmake/modules/AddPureSwift.cmake -@@ -2,17 +2,15 @@ include(macCatalystUtils) - - # Workaround a cmake bug, see the corresponding function in swift-syntax - function(force_target_link_libraries TARGET) -- cmake_parse_arguments(ARGS "" "" "PUBLIC" ${ARGN}) -- -- foreach(DEPENDENCY ${ARGS_PUBLIC}) -- target_link_libraries(${TARGET} PRIVATE ${DEPENDENCY}) -- add_dependencies(${TARGET} ${DEPENDENCY}) -+ target_link_libraries(${TARGET} ${ARGN}) - -+ cmake_parse_arguments(ARGS "PUBLIC;PRIVATE;INTERFACE" "" "" ${ARGN}) -+ foreach(DEPENDENCY ${ARGS_UNPARSED_ARGUMENTS}) - string(REGEX REPLACE [<>:\"/\\|?*] _ sanitized ${DEPENDENCY}) - add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/forced-${sanitized}-dep.swift - COMMAND ${CMAKE_COMMAND} -E touch ${CMAKE_CURRENT_BINARY_DIR}/forced-${sanitized}-dep.swift - DEPENDS ${DEPENDENCY} -- ) -+ ) - target_sources(${TARGET} PRIVATE - ${CMAKE_CURRENT_BINARY_DIR}/forced-${sanitized}-dep.swift - ) -@@ -46,21 +44,7 @@ function(_add_host_swift_compile_options name) - $<$:-runtime-compatibility-version> - $<$:none>) - -- # Set the appropriate target triple. -- # FIXME: This should be set by CMake. -- if(SWIFT_HOST_VARIANT_SDK IN_LIST SWIFT_DARWIN_PLATFORMS) -- set(DEPLOYMENT_VERSION "${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_DEPLOYMENT_VERSION}") -- endif() -- -- if(SWIFT_HOST_VARIANT_SDK STREQUAL "ANDROID") -- set(DEPLOYMENT_VERSION ${SWIFT_ANDROID_API_LEVEL}) -- endif() -- -- get_target_triple(target target_variant "${SWIFT_HOST_VARIANT_SDK}" "${SWIFT_HOST_VARIANT_ARCH}" -- MACCATALYST_BUILD_FLAVOR "" -- DEPLOYMENT_VERSION "${DEPLOYMENT_VERSION}") -- -- target_compile_options(${name} PRIVATE $<$:-target;${target}>) -+ target_compile_options(${name} PRIVATE $<$:-target;${SWIFT_HOST_TRIPLE}>) - _add_host_variant_swift_sanitizer_flags(${name}) - endfunction() - -@@ -121,7 +105,7 @@ endfunction() - # source1 ... - # Sources to add into this library. - function(add_pure_swift_host_library name) -- if (NOT SWIFT_SWIFT_PARSER) -+ if (NOT SWIFT_BUILD_SWIFT_SYNTAX) - message(STATUS "Not building ${name} because swift-syntax is not available") - return() - endif() -@@ -196,13 +180,15 @@ function(add_pure_swift_host_library name) - - # Make sure we can use the host libraries. - target_include_directories(${name} PUBLIC -- ${SWIFT_HOST_LIBRARIES_DEST_DIR}) -+ "${SWIFT_HOST_LIBRARIES_DEST_DIR}") -+ target_link_directories(${name} PUBLIC -+ "${SWIFT_HOST_LIBRARIES_DEST_DIR}") - - if(APSHL_EMIT_MODULE) - # Determine where Swift modules will be built and installed. - -- set(module_triple ${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_ARCH_${SWIFT_HOST_VARIANT_ARCH}_MODULE}) -- set(module_dir ${SWIFT_HOST_LIBRARIES_DEST_DIR}) -+ set(module_triple "${SWIFT_HOST_MODULE_TRIPLE}") -+ set(module_dir "${SWIFT_HOST_LIBRARIES_DEST_DIR}") - set(module_base "${module_dir}/${name}.swiftmodule") - set(module_file "${module_base}/${module_triple}.swiftmodule") - set(module_interface_file "${module_base}/${module_triple}.swiftinterface") -@@ -234,6 +220,12 @@ function(add_pure_swift_host_library name) - >) - endif() - -+ if(LLVM_USE_LINKER) -+ target_link_options(${name} PRIVATE -+ "-use-ld=${LLVM_USE_LINKER}" -+ ) -+ endif() -+ - # Export this target. - set_property(GLOBAL APPEND PROPERTY SWIFT_EXPORTS ${name}) - endfunction() -@@ -241,7 +233,7 @@ endfunction() - # Add a new "pure" Swift host tool. - # - # "Pure" Swift host tools can only contain Swift code, and will be built --# with the host compiler. -+# with the host compiler. - # - # Usage: - # add_pure_swift_host_tool(name -@@ -262,7 +254,7 @@ endfunction() - # source1 ... - # Sources to add into this tool. - function(add_pure_swift_host_tool name) -- if (NOT SWIFT_SWIFT_PARSER) -+ if (NOT SWIFT_BUILD_SWIFT_SYNTAX) - message(STATUS "Not building ${name} because swift-syntax is not available") - return() - endif() -@@ -322,7 +314,15 @@ function(add_pure_swift_host_tool name) - - # Make sure we can use the host libraries. - target_include_directories(${name} PUBLIC -- ${SWIFT_HOST_LIBRARIES_DEST_DIR}) -+ "${SWIFT_HOST_LIBRARIES_DEST_DIR}") -+ target_link_directories(${name} PUBLIC -+ "${SWIFT_HOST_LIBRARIES_DEST_DIR}") -+ -+ if(LLVM_USE_LINKER) -+ target_link_options(${name} PRIVATE -+ "-use-ld=${LLVM_USE_LINKER}" -+ ) -+ endif() - - if(NOT APSHT_SWIFT_COMPONENT STREQUAL no_component) - add_dependencies(${APSHT_SWIFT_COMPONENT} ${name}) -diff --git a/swift/cmake/modules/AddSwift.cmake b/swift/cmake/modules/AddSwift.cmake -index e0fb5de09f257..58f94846fa699 100644 ---- a/swift/cmake/modules/AddSwift.cmake -+++ b/swift/cmake/modules/AddSwift.cmake -@@ -113,9 +113,7 @@ function(_add_host_variant_swift_sanitizer_flags target) - endif() - endfunction() - --# Usage: --# _add_host_variant_c_compile_link_flags(name) --function(_add_host_variant_c_compile_link_flags name) -+function(swift_get_host_triple out_var) - if(SWIFT_HOST_VARIANT_SDK IN_LIST SWIFT_DARWIN_PLATFORMS) - set(DEPLOYMENT_VERSION "${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_DEPLOYMENT_VERSION}") - endif() -@@ -124,26 +122,30 @@ function(_add_host_variant_c_compile_link_flags name) - set(DEPLOYMENT_VERSION ${SWIFT_ANDROID_API_LEVEL}) - endif() - -+ get_target_triple(target target_variant "${SWIFT_HOST_VARIANT_SDK}" "${SWIFT_HOST_VARIANT_ARCH}" -+ MACCATALYST_BUILD_FLAVOR "" -+ DEPLOYMENT_VERSION "${DEPLOYMENT_VERSION}") -+ -+ set(${out_var} "${target}" PARENT_SCOPE) -+endfunction() -+ -+# Usage: -+# _add_host_variant_c_compile_link_flags(name) -+function(_add_host_variant_c_compile_link_flags name) - # MSVC and gcc don't understand -target. - # clang-cl understands --target. - if(CMAKE_C_COMPILER_ID MATCHES "Clang") -- get_target_triple(target target_variant "${SWIFT_HOST_VARIANT_SDK}" "${SWIFT_HOST_VARIANT_ARCH}" -- MACCATALYST_BUILD_FLAVOR "" -- DEPLOYMENT_VERSION "${DEPLOYMENT_VERSION}") - if("${CMAKE_C_COMPILER_FRONTEND_VARIANT}" STREQUAL "MSVC") # clang-cl options -- target_compile_options(${name} PRIVATE $<$:--target=${target}>) -- target_link_options(${name} PRIVATE $<$:--target=${target}>) -+ target_compile_options(${name} PRIVATE $<$:--target=${SWIFT_HOST_TRIPLE}>) -+ target_link_options(${name} PRIVATE $<$:--target=${SWIFT_HOST_TRIPLE}>) - else() -- target_compile_options(${name} PRIVATE $<$:-target;${target}>) -- target_link_options(${name} PRIVATE $<$:-target;${target}>) -+ target_compile_options(${name} PRIVATE $<$:-target;${SWIFT_HOST_TRIPLE}>) -+ target_link_options(${name} PRIVATE $<$:-target;${SWIFT_HOST_TRIPLE}>) - endif() - endif() - - if (CMAKE_Swift_COMPILER) -- get_target_triple(target target_variant "${SWIFT_HOST_VARIANT_SDK}" "${SWIFT_HOST_VARIANT_ARCH}" -- MACCATALYST_BUILD_FLAVOR "" -- DEPLOYMENT_VERSION "${DEPLOYMENT_VERSION}") -- target_compile_options(${name} PRIVATE $<$:-target;${target}>) -+ target_compile_options(${name} PRIVATE $<$:-target;${SWIFT_HOST_TRIPLE}>) - - _add_host_variant_swift_sanitizer_flags(${name}) - endif() -@@ -439,7 +441,7 @@ endfunction() - - function(_add_swift_runtime_link_flags target relpath_to_lib_dir bootstrapping) - if(NOT BOOTSTRAPPING_MODE) -- if (SWIFT_SWIFT_PARSER) -+ if (SWIFT_BUILD_SWIFT_SYNTAX) - set(ASRLF_BOOTSTRAPPING_MODE "HOSTTOOLS") - else() - return() -@@ -576,7 +578,7 @@ function(_add_swift_runtime_link_flags target relpath_to_lib_dir bootstrapping) - ${SWIFT_PATH_TO_SWIFT_SDK}/usr/lib/swift/${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_LIB_SUBDIR}/${SWIFT_HOST_VARIANT_ARCH}) - endif() - -- if(SWIFT_SWIFT_PARSER) -+ if(SWIFT_BUILD_SWIFT_SYNTAX) - # For the "end step" of bootstrapping configurations, we need to be - # able to fall back to the SDK directory for libswiftCore et al. - if (BOOTSTRAPPING_MODE MATCHES "BOOTSTRAPPING.*") -@@ -654,7 +656,7 @@ function(add_swift_host_library name) - translate_flags(ASHL "${options}") - - # Once the new Swift parser is linked, everything has Swift modules. -- if (SWIFT_SWIFT_PARSER AND ASHL_SHARED) -+ if (SWIFT_BUILD_SWIFT_SYNTAX AND ASHL_SHARED) - set(ASHL_HAS_SWIFT_MODULES ON) - endif() - -@@ -700,7 +702,7 @@ function(add_swift_host_library name) - - add_library(${name} ${libkind} ${ASHL_SOURCES}) - -- target_link_directories(${name} PUBLIC ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) -+ target_link_directories(${name} PUBLIC "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}") - - # Respect LLVM_COMMON_DEPENDS if it is set. - # -@@ -922,7 +924,7 @@ function(add_swift_host_tool executable) - endif() - - # Once the new Swift parser is linked in, every host tool has Swift modules. -- if (SWIFT_SWIFT_PARSER AND NOT ASHT_DOES_NOT_USE_SWIFT) -+ if (SWIFT_BUILD_SWIFT_SYNTAX AND NOT ASHT_DOES_NOT_USE_SWIFT) - set(ASHT_HAS_SWIFT_MODULES ON) - endif() - -@@ -961,7 +963,7 @@ function(add_swift_host_tool executable) - endif() - endif() - -- if(SWIFT_SWIFT_PARSER) -+ if(SWIFT_BUILD_SWIFT_SYNTAX) - set(extra_relative_rpath "") - if(NOT "${ASHT_BOOTSTRAPPING}" STREQUAL "") - if(executable MATCHES "-bootstrapping") -diff --git a/swift/cmake/modules/AddSwiftUnittests.cmake b/swift/cmake/modules/AddSwiftUnittests.cmake -index 45acb9bf10698..78a84e6ec5821 100644 ---- a/swift/cmake/modules/AddSwiftUnittests.cmake -+++ b/swift/cmake/modules/AddSwiftUnittests.cmake -@@ -111,10 +111,31 @@ function(add_swift_unittest test_dirname) - endif() - endif() - -- if (SWIFT_SWIFT_PARSER AND NOT ASU_IS_TARGET_TEST) -+ file(RELATIVE_PATH relative_lib_path "${CMAKE_CURRENT_BINARY_DIR}" "${SWIFT_LIBRARY_OUTPUT_INTDIR}") -+ -+ if(SWIFT_HOST_VARIANT_SDK IN_LIST SWIFT_DARWIN_PLATFORMS) -+ set_property( -+ TARGET ${test_dirname} -+ APPEND PROPERTY INSTALL_RPATH "@executable_path/${relative_lib_path}") -+ elseif(SWIFT_HOST_VARIANT_SDK MATCHES "LINUX|ANDROID|OPENBSD|FREEBSD") -+ set_property( -+ TARGET ${test_dirname} -+ APPEND PROPERTY INSTALL_RPATH "$ORIGIN/${relative_lib_path}") -+ endif() -+ -+ if (SWIFT_BUILD_SWIFT_SYNTAX AND NOT ASU_IS_TARGET_TEST) - # Link to stdlib the compiler uses. -- _add_swift_runtime_link_flags(${test_dirname} "../../lib" "") -- set_property(TARGET ${test_dirname} PROPERTY BUILD_WITH_INSTALL_RPATH OFF) -+ _add_swift_runtime_link_flags(${test_dirname} "${relative_lib_path}" "") -+ -+ if(SWIFT_HOST_VARIANT_SDK IN_LIST SWIFT_DARWIN_PLATFORMS) -+ set_property( -+ TARGET ${test_dirname} -+ APPEND PROPERTY INSTALL_RPATH "@executable_path/${relative_lib_path}/swift/host") -+ elseif(SWIFT_HOST_VARIANT_SDK MATCHES "LINUX|ANDROID|OPENBSD|FREEBSD") -+ set_property( -+ TARGET ${test_dirname} -+ APPEND PROPERTY INSTALL_RPATH "$ORIGIN/${relative_lib_path}/swift/host") -+ endif() - endif() - endfunction() - -diff --git a/swift/cmake/modules/SetRPATH.cmake b/swift/cmake/modules/SetRPATH.cmake -deleted file mode 100644 -index 76b8b4644e59a..0000000000000 ---- a/swift/cmake/modules/SetRPATH.cmake -+++ /dev/null -@@ -1,24 +0,0 @@ --set(SWIFT_SET_RPATH_SCRIPT_FILE "${CMAKE_CURRENT_LIST_FILE}") -- --function(swift_get_set_rpath_script_file out_var) -- set(${out_var} "${SWIFT_SET_RPATH_SCRIPT_FILE}" PARENT_SCOPE) --endfunction() -- --# Actual RPATH_CHANGE operation to the file. --function(_swift_set_rpath_impl file new_rpath) -- # FIXME: Handle non-ELF files. We can't use RPATH_SET because it's only available CMake 3.21.0 -- execute_process( -- COMMAND readelf -Wd "${file}" -- COMMAND grep -Po "R(UN)?PATH.*\\[\\K[^\\]]*" -- OUTPUT_VARIABLE current_rpath -- ) -- string(STRIP "${current_rpath}" current_rpath) -- -- # NOTE: RPATH_CHANGE is not documented, and works only for ELF and XCOFF. -- file(RPATH_CHANGE FILE "${file}" OLD_RPATH "${current_rpath}" NEW_RPATH "${new_rpath}") --endfunction() -- --# For 'cmake -P '. --if (SWIFT_SET_RPATH_FILE AND SWIFT_SET_RPATH_NEW_RPATH) -- _swift_set_rpath_impl("${SWIFT_SET_RPATH_FILE}" "${SWIFT_SET_RPATH_NEW_RPATH}") --endif() -diff --git a/swift/cmake/modules/SwiftComponents.cmake b/swift/cmake/modules/SwiftComponents.cmake -index 5bfb3c7427693..c29f5286e1a28 100644 ---- a/swift/cmake/modules/SwiftComponents.cmake -+++ b/swift/cmake/modules/SwiftComponents.cmake -@@ -65,11 +65,12 @@ - # * toolchain-tools -- a subset of tools that we will install to the OSS toolchain. - # * testsuite-tools -- extra tools required to run the Swift testsuite. - # * static-mirror-lib -- Build the static mirror library used by SwiftStaticMirror. -+# * swift-syntax-lib -- install swift-syntax libraries - # * toolchain-dev-tools -- install development tools useful in a shared toolchain - # * llvm-toolchain-dev-tools -- install LLVM development tools useful in a shared toolchain - # * dev -- headers and libraries required to use Swift compiler as a library. - set(_SWIFT_DEFINED_COMPONENTS -- "autolink-driver;back-deployment;compiler;clang-builtin-headers;clang-resource-dir-symlink;clang-builtin-headers-in-clang-resource-dir;libexec;stdlib;stdlib-experimental;sdk-overlay;static-mirror-lib;editor-integration;tools;testsuite-tools;toolchain-tools;toolchain-dev-tools;llvm-toolchain-dev-tools;dev;license;sourcekit-xpc-service;sourcekit-inproc;swift-remote-mirror;swift-remote-mirror-headers") -+ "autolink-driver;back-deployment;compiler;clang-builtin-headers;clang-resource-dir-symlink;clang-builtin-headers-in-clang-resource-dir;libexec;stdlib;stdlib-experimental;sdk-overlay;static-mirror-lib;swift-syntax-lib;editor-integration;tools;testsuite-tools;toolchain-tools;toolchain-dev-tools;llvm-toolchain-dev-tools;dev;license;sourcekit-xpc-service;sourcekit-inproc;swift-remote-mirror;swift-remote-mirror-headers") - - # The default install components include all of the defined components, except - # for the following exceptions. -@@ -96,6 +97,12 @@ macro(swift_configure_components) - set(SWIFT_INSTALL_COMPONENTS "${_SWIFT_DEFAULT_COMPONENTS}" CACHE STRING - "A semicolon-separated list of components to install from the set ${_SWIFT_DEFINED_COMPONENTS}") - -+ # 'compiler' depends on 'swift-syntax-lib' component. -+ if ("compiler" IN_LIST SWIFT_INSTALL_COMPONENTS AND -+ NOT "swift-syntax-lib" IN_LIST SWIFT_INSTALL_COMPONENTS) -+ list(APPEND SWIFT_INSTALL_COMPONENTS "swift-syntax-lib") -+ endif() -+ - foreach(component ${_SWIFT_DEFINED_COMPONENTS}) - add_custom_target(${component}) - add_llvm_install_targets(install-${component} -diff --git a/swift/lib/AST/CMakeLists.txt b/swift/lib/AST/CMakeLists.txt -index c8793e6d10ecb..5c7af5d85ee12 100644 ---- a/swift/lib/AST/CMakeLists.txt -+++ b/swift/lib/AST/CMakeLists.txt -@@ -155,10 +155,10 @@ target_link_libraries(swiftAST INTERFACE - clangAPINotes - clangBasic) - --if(SWIFT_SWIFT_PARSER) -+if(SWIFT_BUILD_SWIFT_SYNTAX) - target_compile_definitions(swiftAST - PRIVATE -- SWIFT_SWIFT_PARSER -+ SWIFT_BUILD_SWIFT_SYNTAX - ) - endif() - -diff --git a/swift/lib/ASTGen/CMakeLists.txt b/swift/lib/ASTGen/CMakeLists.txt -index b80782f838e52..2628124156dfd 100644 ---- a/swift/lib/ASTGen/CMakeLists.txt -+++ b/swift/lib/ASTGen/CMakeLists.txt -@@ -24,15 +24,15 @@ add_pure_swift_host_library(swiftASTGen STATIC - DEPENDENCIES - swiftAST - SWIFT_DEPENDENCIES -- SwiftSyntax::SwiftBasicFormat -- SwiftSyntax::SwiftCompilerPluginMessageHandling -- SwiftSyntax::SwiftDiagnostics -- SwiftSyntax::SwiftOperators -- SwiftSyntax::SwiftParser -- SwiftSyntax::SwiftParserDiagnostics -- SwiftSyntax::SwiftSyntax -- SwiftSyntax::SwiftSyntaxBuilder -- SwiftSyntax::SwiftSyntaxMacros -- SwiftSyntax::SwiftSyntaxMacroExpansion -+ SwiftBasicFormat -+ SwiftCompilerPluginMessageHandling -+ SwiftDiagnostics -+ SwiftOperators -+ SwiftParser -+ SwiftParserDiagnostics -+ SwiftSyntax -+ SwiftSyntaxBuilder -+ SwiftSyntaxMacros -+ SwiftSyntaxMacroExpansion - ${ASTGen_Swift_dependencies} - ) -diff --git a/swift/lib/CMakeLists.txt b/swift/lib/CMakeLists.txt -index 7d61c18522a1c..8c59a9292688f 100644 ---- a/swift/lib/CMakeLists.txt -+++ b/swift/lib/CMakeLists.txt -@@ -16,9 +16,7 @@ list(APPEND LLVM_COMMON_DEPENDS intrinsics_gen clang-tablegen-targets) - list(APPEND LLVM_COMMON_DEPENDS swift-ast-generated-headers) - - # Set up for linking against swift-syntax. --if (SWIFT_SWIFT_PARSER) -- # Set up linking against the swift-syntax modules. -- # Link against the swift-syntax modules. -+if (SWIFT_BUILD_SWIFT_SYNTAX) - set(SWIFT_SYNTAX_MODULES - SwiftBasicFormat - SwiftParser -@@ -32,130 +30,43 @@ if (SWIFT_SWIFT_PARSER) - SwiftCompilerPluginMessageHandling - ) - -- # Compute the list of SwiftSyntax targets that we will link against. -- list(TRANSFORM SWIFT_SYNTAX_MODULES PREPEND "SwiftSyntax::" -- OUTPUT_VARIABLE SWIFT_SYNTAX_TARGETS) -- -- set(SWIFT_SYNTAX_LIBRARIES_BUILD_DIR -- "${SWIFT_PATH_TO_EARLYSWIFTSYNTAX_BUILD_DIR}/lib/swift/host") -- set(SWIFT_HOST_LIBRARIES_DEST_DIR -- "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/swift/host") -- -- # Determine the SwiftSyntax shared library files that were built as -- # part of earlyswiftsyntax. -- list(TRANSFORM SWIFT_SYNTAX_MODULES PREPEND "${CMAKE_SHARED_LIBRARY_PREFIX}" -- OUTPUT_VARIABLE SWIFT_SYNTAX_SHARED_LIBRARIES) -- list(TRANSFORM SWIFT_SYNTAX_SHARED_LIBRARIES APPEND -- "${CMAKE_SHARED_LIBRARY_SUFFIX}" -- OUTPUT_VARIABLE SWIFT_SYNTAX_SHARED_LIBRARIES) -- -- list(TRANSFORM SWIFT_SYNTAX_MODULES PREPEND "${CMAKE_IMPORT_LIBRARY_PREFIX}" -- OUTPUT_VARIABLE SWIFT_SYNTAX_IMPORT_LIBRARIES) -- list(TRANSFORM SWIFT_SYNTAX_IMPORT_LIBRARIES APPEND -- "${CMAKE_IMPORT_LIBRARY_SUFFIX}" OUTPUT_VARIABLE -- SWIFT_SYNTAX_IMPORT_LIBRARIES) -- -- # Interface library to collect swiftinterfaces and swiftmodules from -- # SwiftSyntax -- add_library(swiftSyntaxLibraries INTERFACE) -- -- # Copy over all of the shared libraries from earlyswiftsyntax so they can -- # be found via RPATH. -- foreach (sharedlib ${SWIFT_SYNTAX_SHARED_LIBRARIES}) -- set(add_origin_rpath) -- if(SWIFT_HOST_VARIANT_SDK MATCHES "LINUX|ANDROID|OPENBSD|FREEBSD") -- # At runtime, use swiftCore in the current toolchain. -- swift_get_set_rpath_script_file(setrpath_command) -- set(add_origin_rpath COMMAND ${CMAKE_COMMAND} -- "-DSWIFT_SET_RPATH_FILE=${SWIFT_HOST_LIBRARIES_DEST_DIR}/${sharedlib}" -- "-DSWIFT_SET_RPATH_NEW_RPATH='$$ORIGIN:$$ORIGIN/../${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_LIB_SUBDIR}'" -- -P "${setrpath_command}" -- ) -- endif() -- -- if(CMAKE_SYSTEM_NAME MATCHES Windows) -- add_custom_command(OUTPUT ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${sharedlib} -- DEPENDS "${SWIFT_PATH_TO_EARLYSWIFTSYNTAX_BUILD_DIR}/bin/${sharedlib}" -- COMMAND ${CMAKE_COMMAND} -E copy_if_different ${SWIFT_PATH_TO_EARLYSWIFTSYNTAX_BUILD_DIR}/bin/${sharedlib} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${sharedlib}) -- add_custom_target(copy_swiftSyntaxLibrary_${sharedlib} -- DEPENDS ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${sharedlib} -- COMMENT "copying ${sharedlib}") -- swift_install_in_component(PROGRAMS ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${sharedlib} -- DESTINATION bin -- COMPONENT compiler) -- else() -- add_custom_command(OUTPUT "${SWIFT_HOST_LIBRARIES_DEST_DIR}/${sharedlib}" -- DEPENDS "${SWIFT_SYNTAX_LIBRARIES_BUILD_DIR}/${sharedlib}" -- COMMAND ${CMAKE_COMMAND} -E copy_if_different ${SWIFT_SYNTAX_LIBRARIES_BUILD_DIR}/${sharedlib} ${SWIFT_HOST_LIBRARIES_DEST_DIR}/${sharedlib} -- ${add_origin_rpath}) -- add_custom_target(copy_swiftSyntaxLibrary_${sharedlib} -- DEPENDS "${SWIFT_HOST_LIBRARIES_DEST_DIR}/${sharedlib}" -- COMMENT "Copying ${sharedlib}") -- swift_install_in_component(PROGRAMS "${SWIFT_HOST_LIBRARIES_DEST_DIR}/${sharedlib}" -- DESTINATION "lib${LLVM_LIBDIR_SUFFIX}/swift/host" -- COMPONENT compiler) -- endif() -- -- add_dependencies(swiftSyntaxLibraries copy_swiftSyntaxLibrary_${sharedlib}) -- endforeach() -- -+ # Install shared runtime libraries - if(CMAKE_SYSTEM_NAME MATCHES Windows) -- foreach(implib ${SWIFT_SYNTAX_IMPORT_LIBRARIES}) -- add_custom_command(OUTPUT ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/swift/windows/${SWIFT_HOST_VARIANT_ARCH}/${implib} -- DEPENDS ${SWIFT_PATH_TO_EARLYSWIFTSYNTAX_BUILD_DIR}/lib/swift/host/${implib} -- COMMAND "${CMAKE_COMMAND}" -E copy_if_different ${SWIFT_PATH_TO_EARLYSWIFTSYNTAX_BUILD_DIR}/lib/swift/host/${implib} ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/swift/windows/${SWIFT_HOST_VARIANT_ARCH}/${implib}) -- add_custom_target(copy_swiftSyntaxLibrary_${implib} -- DEPENDS ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/swift/windows/${SWIFT_HOST_VARIANT_ARCH}/${implib} -- COMMENT "Copying ${implib}") -- swift_install_in_component(PROGRAMS ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/swift/windows/${SWIFT_HOST_VARIANT_ARCH}/${implib} -- DESTINATION lib -- COMPONENT compiler) -- add_dependencies(swiftSyntaxLibraries copy_swiftSyntaxLibrary_${implib}) -- endforeach() -+ swift_install_in_component(TARGETS ${SWIFT_SYNTAX_MODULES} -+ RUNTIME -+ DESTINATION "bin" -+ COMPONENT swift-syntax-lib) -+ else() -+ swift_install_in_component(TARGETS ${SWIFT_SYNTAX_MODULES} -+ LIBRARY -+ DESTINATION "lib${LLVM_LIBDIR_SUFFIX}/swift/host" -+ COMPONENT swift-syntax-lib) - endif() - -- # Copy all of the Swift modules from earlyswiftsyntax so they can be found -- # in the same relative place within the build directory as in the final -- # toolchain. -- list(TRANSFORM SWIFT_SYNTAX_MODULES APPEND ".swiftmodule" -- OUTPUT_VARIABLE SWIFT_SYNTAX_MODULE_DIRS) -- -- foreach(module_dir ${SWIFT_SYNTAX_MODULE_DIRS}) -- # Find all of the source module files. -- file(GLOB module_files -- "${SWIFT_SYNTAX_LIBRARIES_BUILD_DIR}/${module_dir}/*.swiftinterface") -- -- # Determine the destination module files. -- set(dest_module_files) -- foreach(full_module_file ${module_files}) -- get_filename_component(module_file ${full_module_file} NAME) -- list(APPEND dest_module_files -- "${SWIFT_HOST_LIBRARIES_DEST_DIR}/${module_dir}/${module_file}") -- endforeach() -- -- add_custom_command( -- OUTPUT ${dest_module_files} -- DEPENDS ${module_files} -- COMMAND ${CMAKE_COMMAND} -E make_directory ${SWIFT_HOST_LIBRARIES_DEST_DIR}/${module_dir} -- COMMAND ${CMAKE_COMMAND} -E copy_if_different ${module_files} ${SWIFT_HOST_LIBRARIES_DEST_DIR}/${module_dir}/ -- ) -- -- add_custom_target(copy_swiftSyntaxModule_${module_dir} -- DEPENDS ${dest_module_files} -- COMMENT "Copying ${module_dir}" -- ) -- -- swift_install_in_component( -- FILES ${dest_module_files} -- DESTINATION "lib${LLVM_LIBDIR_SUFFIX}/swift/host/${module_dir}" -- COMPONENT compiler -- ) -+ # Install import libraries in Windows. -+ if(CMAKE_SYSTEM_NAME MATCHES Windows) -+ list(TRANSFORM SWIFT_SYNTAX_MODULES -+ PREPEND "${CMAKE_IMPORT_LIBRARY_PREFIX}" -+ OUTPUT_VARIABLE SWIFT_SYNTAX_IMPORT_LIBRARIES) -+ list(TRANSFORM SWIFT_SYNTAX_IMPORT_LIBRARIES -+ APPEND "${CMAKE_IMPORT_LIBRARY_SUFFIX}" -+ OUTPUT_VARIABLE SWIFT_SYNTAX_IMPORT_LIBRARIES) -+ list(TRANSFORM SWIFT_SYNTAX_IMPORT_LIBRARIES -+ PREPEND "${SWIFT_HOST_LIBRARIES_DEST_DIR}/" -+ OUTPUT_VARIABLE SWIFT_SYNTAX_IMPORT_LIBRARIES) -+ swift_install_in_component(PROGRAMS "${SWIFT_SYNTAX_IMPORT_LIBRARIES}" -+ DESTINATION lib -+ COMPONENT swift-syntax-lib) -+ endif() - -- add_dependencies(swiftSyntaxLibraries copy_swiftSyntaxModule_${module_dir}) -+ # Install Swift module interface files. -+ foreach(module ${SWIFT_SYNTAX_MODULES}) -+ set(module_dir "${module}.swiftmodule") -+ set(module_file "${SWIFT_HOST_LIBRARIES_DEST_DIR}/${module_dir}/${SWIFT_HOST_MODULE_TRIPLE}.swiftinterface") -+ swift_install_in_component(FILES "${module_file}" -+ DESTINATION "lib${LLVM_LIBDIR_SUFFIX}/swift/host/${module_dir}" -+ COMPONENT swift-syntax-lib) - endforeach() -- -- # Add copied SwiftSyntax libraries to global dependencies. -- list(APPEND LLVM_COMMON_DEPENDS swiftSyntaxLibraries) - endif() - - add_subdirectory(APIDigester) -diff --git a/swift/lib/Frontend/CMakeLists.txt b/swift/lib/Frontend/CMakeLists.txt -index 21ef5231ce3ac..a75be05e4feef 100644 ---- a/swift/lib/Frontend/CMakeLists.txt -+++ b/swift/lib/Frontend/CMakeLists.txt -@@ -34,9 +34,9 @@ target_link_libraries(swiftFrontend PRIVATE - - set_swift_llvm_is_available(swiftFrontend) - --if (SWIFT_SWIFT_PARSER) -+if (SWIFT_BUILD_SWIFT_SYNTAX) - target_compile_definitions(swiftFrontend - PRIVATE -- SWIFT_SWIFT_PARSER -+ SWIFT_BUILD_SWIFT_SYNTAX - ) - endif() -diff --git a/swift/lib/Frontend/PrintingDiagnosticConsumer.cpp b/swift/lib/Frontend/PrintingDiagnosticConsumer.cpp -index eaa246940ccd0..f3e2e53834ce2 100644 ---- a/swift/lib/Frontend/PrintingDiagnosticConsumer.cpp -+++ b/swift/lib/Frontend/PrintingDiagnosticConsumer.cpp -@@ -964,7 +964,7 @@ static void annotateSnippetWithInfo(SourceManager &SM, - } - } - --#if SWIFT_SWIFT_PARSER -+#if SWIFT_BUILD_SWIFT_SYNTAX - /// Enqueue a diagnostic with ASTGen's diagnostic rendering. - static void enqueueDiagnostic( - void *queuedDiagnostics, const DiagnosticInfo &info, SourceManager &SM -@@ -1038,7 +1038,7 @@ static SmallVector getSourceBufferStack( - } - } - --#if SWIFT_SWIFT_PARSER -+#if SWIFT_BUILD_SWIFT_SYNTAX - void PrintingDiagnosticConsumer::queueBuffer( - SourceManager &sourceMgr, unsigned bufferID) { - QueuedBuffer knownSourceFile = queuedBuffers[bufferID]; -@@ -1103,7 +1103,7 @@ void PrintingDiagnosticConsumer::handleDiagnostic(SourceManager &SM, - - switch (FormattingStyle) { - case DiagnosticOptions::FormattingStyle::Swift: { --#if SWIFT_SWIFT_PARSER -+#if SWIFT_BUILD_SWIFT_SYNTAX - // Use the swift-syntax formatter. - auto bufferStack = getSourceBufferStack(SM, Info.Loc); - if (!bufferStack.empty()) { -@@ -1190,7 +1190,7 @@ void PrintingDiagnosticConsumer::flush(bool includeTrailingBreak) { - currentSnippet.reset(); - } - --#if SWIFT_SWIFT_PARSER -+#if SWIFT_BUILD_SWIFT_SYNTAX - if (queuedDiagnostics) { - char *renderedString = nullptr; - ptrdiff_t renderedStringLen = 0; -diff --git a/swift/lib/IDE/CodeCompletion.cpp b/swift/lib/IDE/CodeCompletion.cpp -index 2cc7a2477e979..e76e64b6af883 100644 ---- a/swift/lib/IDE/CodeCompletion.cpp -+++ b/swift/lib/IDE/CodeCompletion.cpp -@@ -1142,7 +1142,7 @@ static void addPoundDirectives(CodeCompletionResultSink &Sink) { - Builder.addRightParen(); - }); - --#ifndef SWIFT_SWIFT_PARSER -+#ifndef SWIFT_BUILD_SWIFT_SYNTAX - addWithName("warning", CodeCompletionKeywordKind::pound_warning, - [&] (CodeCompletionResultBuilder &Builder) { - Builder.addLeftParen(); -diff --git a/swift/lib/Macros/CMakeLists.txt b/swift/lib/Macros/CMakeLists.txt -index 3598a4e917557..23e7de788cd47 100644 ---- a/swift/lib/Macros/CMakeLists.txt -+++ b/swift/lib/Macros/CMakeLists.txt -@@ -33,7 +33,7 @@ function(add_swift_macro_library name) - - # If we don't have the Swift swift parser, bail out, because the above - # add_pure_swift_host_library did nothing. -- if (NOT SWIFT_SWIFT_PARSER) -+ if (NOT SWIFT_BUILD_SWIFT_SYNTAX) - return() - endif() - -diff --git a/swift/lib/Macros/Sources/ObservationMacros/CMakeLists.txt b/swift/lib/Macros/Sources/ObservationMacros/CMakeLists.txt -index 3afd3380125aa..c3deee2c4747a 100644 ---- a/swift/lib/Macros/Sources/ObservationMacros/CMakeLists.txt -+++ b/swift/lib/Macros/Sources/ObservationMacros/CMakeLists.txt -@@ -15,9 +15,9 @@ add_swift_macro_library(ObservationMacros - Extensions.swift - ObservableMacro.swift - SWIFT_DEPENDENCIES -- SwiftSyntax::SwiftDiagnostics -- SwiftSyntax::SwiftOperators -- SwiftSyntax::SwiftSyntaxBuilder -- SwiftSyntax::SwiftSyntax -- SwiftSyntax::SwiftSyntaxMacros -+ SwiftDiagnostics -+ SwiftOperators -+ SwiftSyntaxBuilder -+ SwiftSyntax -+ SwiftSyntaxMacros - ) -diff --git a/swift/lib/Macros/Sources/SwiftMacros/CMakeLists.txt b/swift/lib/Macros/Sources/SwiftMacros/CMakeLists.txt -index 32a798260afdb..9d83b612b4987 100644 ---- a/swift/lib/Macros/Sources/SwiftMacros/CMakeLists.txt -+++ b/swift/lib/Macros/Sources/SwiftMacros/CMakeLists.txt -@@ -13,8 +13,8 @@ - add_swift_macro_library(SwiftMacros - OptionSetMacro.swift - SWIFT_DEPENDENCIES -- SwiftSyntax::SwiftDiagnostics -- SwiftSyntax::SwiftSyntax -- SwiftSyntax::SwiftSyntaxBuilder -- SwiftSyntax::SwiftSyntaxMacros -+ SwiftDiagnostics -+ SwiftSyntax -+ SwiftSyntaxBuilder -+ SwiftSyntaxMacros - ) -diff --git a/swift/lib/Parse/CMakeLists.txt b/swift/lib/Parse/CMakeLists.txt -index 1b66331ad7e6d..8a01e55f893b0 100644 ---- a/swift/lib/Parse/CMakeLists.txt -+++ b/swift/lib/Parse/CMakeLists.txt -@@ -25,35 +25,35 @@ target_link_libraries(swiftParse PRIVATE - swiftAST - ) - --if (SWIFT_SWIFT_PARSER) -+if (SWIFT_BUILD_SWIFT_SYNTAX) - target_link_libraries(swiftParse - PRIVATE -- SwiftSyntax::SwiftBasicFormat -- SwiftSyntax::SwiftParser -- SwiftSyntax::SwiftParserDiagnostics -- SwiftSyntax::SwiftDiagnostics -- SwiftSyntax::SwiftSyntax -- SwiftSyntax::SwiftOperators -- SwiftSyntax::SwiftSyntaxBuilder -- SwiftSyntax::SwiftSyntaxMacros -+ SwiftBasicFormat -+ SwiftParser -+ SwiftParserDiagnostics -+ SwiftDiagnostics -+ SwiftSyntax -+ SwiftOperators -+ SwiftSyntaxBuilder -+ SwiftSyntaxMacros - swiftASTGen - ) - - add_dependencies(swiftParse -- SwiftSyntax::SwiftBasicFormat -- SwiftSyntax::SwiftParser -- SwiftSyntax::SwiftParserDiagnostics -- SwiftSyntax::SwiftDiagnostics -- SwiftSyntax::SwiftSyntax -- SwiftSyntax::SwiftOperators -- SwiftSyntax::SwiftSyntaxBuilder -- SwiftSyntax::SwiftSyntaxMacros -+ SwiftBasicFormat -+ SwiftParser -+ SwiftParserDiagnostics -+ SwiftDiagnostics -+ SwiftSyntax -+ SwiftOperators -+ SwiftSyntaxBuilder -+ SwiftSyntaxMacros - swiftASTGen - ) - - target_compile_definitions(swiftParse - PRIVATE -- SWIFT_SWIFT_PARSER -+ SWIFT_BUILD_SWIFT_SYNTAX - ) - endif() - -diff --git a/swift/lib/Parse/ParseDecl.cpp b/swift/lib/Parse/ParseDecl.cpp -index cdae5b4443322..98344c7c98582 100644 ---- a/swift/lib/Parse/ParseDecl.cpp -+++ b/swift/lib/Parse/ParseDecl.cpp -@@ -162,7 +162,7 @@ extern "C" void parseTopLevelSwift(const char *buffer, - void *outputContext, - void (*)(void *, void *)); - --#if SWIFT_SWIFT_PARSER -+#if SWIFT_BUILD_SWIFT_SYNTAX - static void appendToVector(void *declPtr, void *vecPtr) { - auto vec = static_cast *>(vecPtr); - auto decl = static_cast(declPtr); -@@ -207,7 +207,7 @@ extern "C" void swift_ASTGen_buildTopLevelASTNodes(void *sourceFile, - /// decl-sil-stage [[only in SIL mode] - /// \endverbatim - void Parser::parseTopLevelItems(SmallVectorImpl &items) { --#if SWIFT_SWIFT_PARSER -+#if SWIFT_BUILD_SWIFT_SYNTAX - llvm::Optional existingParsingTransaction; - parseSourceFileViaASTGen(items, existingParsingTransaction); - #endif -@@ -258,7 +258,7 @@ void Parser::parseTopLevelItems(SmallVectorImpl &items) { - } - } - --#if SWIFT_SWIFT_PARSER -+#if SWIFT_BUILD_SWIFT_SYNTAX - if (existingParsingTransaction) - existingParsingTransaction->abort(); - -@@ -310,7 +310,7 @@ void Parser::parseTopLevelItems(SmallVectorImpl &items) { - - void *ExportedSourceFileRequest::evaluate(Evaluator &evaluator, - const SourceFile *SF) const { --#if SWIFT_SWIFT_PARSER -+#if SWIFT_BUILD_SWIFT_SYNTAX - // The SwiftSyntax parser doesn't (yet?) handle SIL. - if (SF->Kind == SourceFileKind::SIL) - return nullptr; -@@ -343,7 +343,7 @@ void Parser::parseSourceFileViaASTGen( - SmallVectorImpl &items, - llvm::Optional &transaction, - bool suppressDiagnostics) { --#if SWIFT_SWIFT_PARSER -+#if SWIFT_BUILD_SWIFT_SYNTAX - const auto &langOpts = Context.LangOpts; - - // We only need to do parsing if we either have ASTGen enabled, or want the -diff --git a/swift/lib/Parse/ParseIfConfig.cpp b/swift/lib/Parse/ParseIfConfig.cpp -index ef10f8fdde5b8..58d991841cab3 100644 ---- a/swift/lib/Parse/ParseIfConfig.cpp -+++ b/swift/lib/Parse/ParseIfConfig.cpp -@@ -557,7 +557,7 @@ class EvaluateIfConfigCondition : - - // Check whether this is any one of the known compiler features. - const auto &langOpts = Ctx.LangOpts; --#if SWIFT_SWIFT_PARSER -+#if SWIFT_BUILD_SWIFT_SYNTAX - const bool hasSwiftSwiftParser = true; - #else - const bool hasSwiftSwiftParser = false; -diff --git a/swift/lib/Parse/ParseType.cpp b/swift/lib/Parse/ParseType.cpp -index 7d02b146bf2fd..54548243d43cf 100644 ---- a/swift/lib/Parse/ParseType.cpp -+++ b/swift/lib/Parse/ParseType.cpp -@@ -601,7 +601,7 @@ extern "C" TypeRepr *swift_ASTGen_buildTypeRepr( - /// - ParserResult Parser::parseType( - Diag<> MessageID, ParseTypeReason reason) { -- #if SWIFT_SWIFT_PARSER -+ #if SWIFT_BUILD_SWIFT_SYNTAX - auto astGenResult = parseASTFromSyntaxTree( - [&](void *exportedSourceFile, const void *sourceLoc) { - const void *endLocPtr = nullptr; -diff --git a/swift/lib/Sema/CMakeLists.txt b/swift/lib/Sema/CMakeLists.txt -index f3cdbffcbfc18..4f95db5553219 100644 ---- a/swift/lib/Sema/CMakeLists.txt -+++ b/swift/lib/Sema/CMakeLists.txt -@@ -87,10 +87,10 @@ target_link_libraries(swiftSema PRIVATE - swiftParse - swiftSerialization) - --if (SWIFT_SWIFT_PARSER) -+if (SWIFT_BUILD_SWIFT_SYNTAX) - target_compile_definitions(swiftSema - PRIVATE -- SWIFT_SWIFT_PARSER -+ SWIFT_BUILD_SWIFT_SYNTAX - ) - target_link_libraries(swiftSema PRIVATE - swiftASTGen) -diff --git a/swift/lib/Sema/CSApply.cpp b/swift/lib/Sema/CSApply.cpp -index 77b0d7e2cd3a9..8317b9027c832 100644 ---- a/swift/lib/Sema/CSApply.cpp -+++ b/swift/lib/Sema/CSApply.cpp -@@ -2934,7 +2934,7 @@ namespace { - } - - Expr *visitMagicIdentifierLiteralExpr(MagicIdentifierLiteralExpr *expr) { --#if SWIFT_SWIFT_PARSER -+#if SWIFT_BUILD_SWIFT_SYNTAX - auto &ctx = cs.getASTContext(); - if (ctx.LangOpts.hasFeature(Feature::BuiltinMacros)) { - auto expandedType = solution.simplifyType(solution.getType(expr)); -diff --git a/swift/lib/Sema/CSGen.cpp b/swift/lib/Sema/CSGen.cpp -index f50b7d8fee110..037ad6db8bdff 100644 ---- a/swift/lib/Sema/CSGen.cpp -+++ b/swift/lib/Sema/CSGen.cpp -@@ -1267,7 +1267,7 @@ namespace { - } - - Type visitMagicIdentifierLiteralExpr(MagicIdentifierLiteralExpr *expr) { --#ifdef SWIFT_SWIFT_PARSER -+#ifdef SWIFT_BUILD_SWIFT_SYNTAX - auto &ctx = CS.getASTContext(); - if (ctx.LangOpts.hasFeature(Feature::BuiltinMacros)) { - auto kind = MagicIdentifierLiteralExpr::getKindString(expr->getKind()) -diff --git a/swift/lib/Sema/TypeCheckMacros.cpp b/swift/lib/Sema/TypeCheckMacros.cpp -index 9d599b54c4b95..4861eb726b27e 100644 ---- a/swift/lib/Sema/TypeCheckMacros.cpp -+++ b/swift/lib/Sema/TypeCheckMacros.cpp -@@ -94,7 +94,7 @@ extern "C" bool swift_ASTGen_pluginServerLoadLibraryPlugin( - void *handle, const char *libraryPath, const char *moduleName, - void *diagEngine); - --#if SWIFT_SWIFT_PARSER -+#if SWIFT_BUILD_SWIFT_SYNTAX - /// Look for macro's type metadata given its external module and type name. - static void const * - lookupMacroTypeMetadataByExternalName(ASTContext &ctx, StringRef moduleName, -@@ -190,7 +190,7 @@ MacroDefinition MacroDefinitionRequest::evaluate( - - auto sourceFile = macro->getParentSourceFile(); - --#if SWIFT_SWIFT_PARSER -+#if SWIFT_BUILD_SWIFT_SYNTAX - char *externalMacroNamePtr; - ptrdiff_t externalMacroNameLength; - ptrdiff_t *replacements; -@@ -296,7 +296,7 @@ initializeExecutablePlugin(ASTContext &ctx, - // FIXME: Ideally this should be done right after invoking the plugin. - // But plugin loading is in libAST and it can't link ASTGen symbols. - if (!executablePlugin->isInitialized()) { --#if SWIFT_SWIFT_PARSER -+#if SWIFT_BUILD_SWIFT_SYNTAX - if (!swift_ASTGen_initializePlugin(executablePlugin, &ctx.Diags)) { - return nullptr; - } -@@ -317,7 +317,7 @@ initializeExecutablePlugin(ASTContext &ctx, - - // If this is a plugin server, load the library. - if (!libraryPath.empty()) { --#if SWIFT_SWIFT_PARSER -+#if SWIFT_BUILD_SWIFT_SYNTAX - llvm::SmallString<128> resolvedLibraryPath; - auto fs = ctx.SourceMgr.getFileSystem(); - if (auto err = fs->getRealPath(libraryPath, resolvedLibraryPath)) { -@@ -380,7 +380,7 @@ CompilerPluginLoadRequest::evaluate(Evaluator &evaluator, ASTContext *ctx, - static llvm::Optional - resolveInProcessMacro(ASTContext &ctx, Identifier moduleName, - Identifier typeName, LoadedLibraryPlugin *plugin) { --#if SWIFT_SWIFT_PARSER -+#if SWIFT_BUILD_SWIFT_SYNTAX - /// Look for the type metadata given the external module and type names. - auto macroMetatype = lookupMacroTypeMetadataByExternalName( - ctx, moduleName.str(), typeName.str(), plugin); -@@ -404,7 +404,7 @@ static llvm::Optional - resolveExecutableMacro(ASTContext &ctx, - LoadedExecutablePlugin *executablePlugin, - Identifier moduleName, Identifier typeName) { --#if SWIFT_SWIFT_PARSER -+#if SWIFT_BUILD_SWIFT_SYNTAX - if (auto *execMacro = swift_ASTGen_resolveExecutableMacro( - moduleName.str().data(), moduleName.str().size(), - typeName.str().data(), typeName.str().size(), executablePlugin)) { -@@ -975,7 +975,7 @@ evaluateFreestandingMacro(FreestandingMacroExpansion *expansion, - LazyValue discriminator([&]() -> std::string { - if (!discriminatorStr.empty()) - return discriminatorStr.str(); --#if SWIFT_SWIFT_PARSER -+#if SWIFT_BUILD_SWIFT_SYNTAX - Mangle::ASTMangler mangler; - return mangler.mangleMacroExpansion(expansion); - #else -@@ -1036,7 +1036,7 @@ evaluateFreestandingMacro(FreestandingMacroExpansion *expansion, - return nullptr; - } - --#if SWIFT_SWIFT_PARSER -+#if SWIFT_BUILD_SWIFT_SYNTAX - PrettyStackTraceFreestandingMacroExpansion debugStack( - "expanding freestanding macro", expansion); - -@@ -1215,7 +1215,7 @@ static SourceFile *evaluateAttachedMacro(MacroDecl *macro, Decl *attachedTo, - LazyValue discriminator([&]() -> std::string { - if (!discriminatorStr.empty()) - return discriminatorStr.str(); --#if SWIFT_SWIFT_PARSER -+#if SWIFT_BUILD_SWIFT_SYNTAX - Mangle::ASTMangler mangler; - return mangler.mangleAttachedMacroExpansion(attachedTo, attr, role); - #else -@@ -1294,7 +1294,7 @@ static SourceFile *evaluateAttachedMacro(MacroDecl *macro, Decl *attachedTo, - return nullptr; - } - --#if SWIFT_SWIFT_PARSER -+#if SWIFT_BUILD_SWIFT_SYNTAX - PrettyStackTraceDecl debugStack("expanding attached macro", attachedTo); - - auto *astGenAttrSourceFile = attrSourceFile->getExportedSourceFile(); -diff --git a/swift/test/CMakeLists.txt b/swift/test/CMakeLists.txt -index d2d5f71ded49a..52ea7dc00842a 100644 ---- a/swift/test/CMakeLists.txt -+++ b/swift/test/CMakeLists.txt -@@ -205,18 +205,10 @@ normalize_boolean_spelling(SWIFT_STDLIB_ENABLE_UNICODE_DATA) - normalize_boolean_spelling(SWIFT_ENABLE_DISPATCH) - normalize_boolean_spelling(SWIFT_STDLIB_ENABLE_OBJC_INTEROP) - normalize_boolean_spelling(SWIFT_ENABLE_BACKTRACING) -+normalize_boolean_spelling(SWIFT_BUILD_SWIFT_SYNTAX) - is_build_type_optimized("${SWIFT_STDLIB_BUILD_TYPE}" SWIFT_OPTIMIZED) - --# Get 'SWIFT_HOST_TRIPLE' and 'SWIFT_HOST_SDKROOT' for lit.site.cfg.in --if(SWIFT_HOST_VARIANT_SDK IN_LIST SWIFT_DARWIN_PLATFORMS) -- set(DEPLOYMENT_VERSION "${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_DEPLOYMENT_VERSION}") --endif() --if(SWIFT_HOST_VARIANT_SDK STREQUAL "ANDROID") -- set(DEPLOYMENT_VERSION ${SWIFT_ANDROID_API_LEVEL}) --endif() --get_target_triple(SWIFT_HOST_TRIPLE SWIFT_HOST_TRIPLE_VARIANT "${SWIFT_HOST_VARIANT_SDK}" "${SWIFT_HOST_VARIANT_ARCH}" -- MACCATALYST_BUILD_FLAVOR "" -- DEPLOYMENT_VERSION "${DEPLOYMENT_VERSION}") -+# Get 'SWIFT_HOST_SDKROOT' for lit.site.cfg.in - set(SWIFT_HOST_SDKROOT "${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_ARCH_${SWIFT_HOST_VARIANT_ARCH}_PATH}") - - set(profdata_merge_worker -diff --git a/swift/test/IDE/complete_pound_expr.swift b/swift/test/IDE/complete_pound_expr.swift -index bb074a1ab0d26..4bfd862f00d68 100644 ---- a/swift/test/IDE/complete_pound_expr.swift -+++ b/swift/test/IDE/complete_pound_expr.swift -@@ -1,7 +1,7 @@ - // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=POUND_EXPR_1 | %FileCheck %s -check-prefix=POUND_EXPR_INTCONTEXT - // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=POUND_EXPR_2 | %FileCheck %s -check-prefix=POUND_EXPR_STRINGCONTEXT - // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=POUND_EXPR_3 | %FileCheck %s -check-prefix=POUND_EXPR_SELECTORCONTEXT --// REQUIRES: objc_interop -+// REQUIRES: objc_interop, swift_swift_parser - - import ObjectiveC - -diff --git a/swift/test/Macros/extension_macro_plugin.swift b/swift/test/Macros/extension_macro_plugin.swift -index 5204d9c74fb4b..eaf90a366c231 100644 ---- a/swift/test/Macros/extension_macro_plugin.swift -+++ b/swift/test/Macros/extension_macro_plugin.swift -@@ -1,5 +1,4 @@ --// FIXME: Swift parser is not enabled on Linux CI yet. --// REQUIRES: OS=macosx -+// REQUIRES: swift_swift_parser - - // RUN: %empty-directory(%t) - // RUN: %empty-directory(%t/plugins) -@@ -13,7 +12,7 @@ - // RUN: %S/Inputs/syntax_macro_definitions.swift \ - // RUN: -g -no-toolchain-stdlib-rpath - --// RUN: SWIFT_DUMP_PLUGIN_MESSAGING=1 %swift-target-frontend \ -+// RUN: env SWIFT_DUMP_PLUGIN_MESSAGING=1 %swift-target-frontend \ - // RUN: -typecheck -verify \ - // RUN: -swift-version 5 -enable-experimental-feature ExtensionMacros \ - // RUN: -external-plugin-path %t/plugins#%swift-plugin-server \ -diff --git a/swift/test/Macros/macro_plugin_server.swift b/swift/test/Macros/macro_plugin_server.swift -index dfdd12874b30a..91d45c30e1c82 100644 ---- a/swift/test/Macros/macro_plugin_server.swift -+++ b/swift/test/Macros/macro_plugin_server.swift -@@ -1,5 +1,4 @@ --// FIXME: Swift parser is not enabled on Linux CI yet. --// REQUIRES: OS=macosx -+// REQUIRES: swift_swift_parser - - // RUN: %empty-directory(%t) - // RUN: %empty-directory(%t/plugins) -@@ -21,7 +20,7 @@ - // RUN: %S/Inputs/evil_macro_definitions.swift \ - // RUN: -g -no-toolchain-stdlib-rpath - --// RUN: SWIFT_DUMP_PLUGIN_MESSAGING=1 %swift-target-frontend \ -+// RUN: env SWIFT_DUMP_PLUGIN_MESSAGING=1 %swift-target-frontend \ - // RUN: -typecheck -verify \ - // RUN: -swift-version 5 -enable-experimental-feature Macros \ - // RUN: -external-plugin-path %t/plugins#%swift-plugin-server \ -@@ -33,9 +32,9 @@ - - // CHECK: ->(plugin:[[#PID1:]]) {"getCapability":{"capability":{"protocolVersion":[[#PROTOCOL_VERSION:]]}}} - // CHECK-NEXT: <-(plugin:[[#PID1]]) {"getCapabilityResult":{"capability":{"features":["load-plugin-library"],"protocolVersion":[[#PROTOCOL_VERSION]]}}} --// CHECK-NEXT: ->(plugin:[[#PID1]]) {"loadPluginLibrary":{"libraryPath":"BUILD_DIR{{.*}}plugins/libMacroDefinition.dylib","moduleName":"MacroDefinition"}} -+// CHECK-NEXT: ->(plugin:[[#PID1]]) {"loadPluginLibrary":{"libraryPath":"{{.*}}MacroDefinition.{{dylib|so|dll}}","moduleName":"MacroDefinition"}} - // CHECK-NEXT: <-(plugin:[[#PID1]]) {"loadPluginLibraryResult":{"diagnostics":[],"loaded":true}} --// CHECK-NEXT: ->(plugin:[[#PID1]]) {"loadPluginLibrary":{"libraryPath":"BUILD_DIR{{.*}}plugins/libEvilMacros.dylib","moduleName":"EvilMacros"}} -+// CHECK-NEXT: ->(plugin:[[#PID1]]) {"loadPluginLibrary":{"libraryPath":"{{.*}}EvilMacros.{{dylib|so|dll}}","moduleName":"EvilMacros"}} - // CHECK-NEXT: <-(plugin:[[#PID1]]) {"loadPluginLibraryResult":{"diagnostics":[],"loaded":true}} - // CHECK-NEXT: ->(plugin:[[#PID1]]) {"expandFreestandingMacro":{"discriminator":"${{.*}}","macro":{"moduleName":"MacroDefinition","name":"stringify","typeName":"StringifyMacro"},"macroRole":"expression","syntax":{"kind":"expression","location":{{{.+}}},"source":"#stringify(a + b)"}}} - // CHECK-NEXT: <-(plugin:[[#PID1]]) {"expandMacroResult":{"diagnostics":[],"expandedSource":"(a + b, \"a + b\")"}} -@@ -44,9 +43,9 @@ - - // CHECK: ->(plugin:[[#PID2:]]) {"getCapability":{"capability":{"protocolVersion":[[#PROTOCOL_VERSION]]}}} - // CHECK-NEXT: <-(plugin:[[#PID2]]) {"getCapabilityResult":{"capability":{"features":["load-plugin-library"],"protocolVersion":[[#PROTOCOL_VERSION]]}}} --// CHECK-NEXT: ->(plugin:[[#PID2]]) {"loadPluginLibrary":{"libraryPath":"BUILD_DIR{{.*}}plugins/libMacroDefinition.dylib","moduleName":"MacroDefinition"}} -+// CHECK-NEXT: ->(plugin:[[#PID2]]) {"loadPluginLibrary":{"libraryPath":"{{.*}}MacroDefinition.{{dylib|so|dll}}","moduleName":"MacroDefinition"}} - // CHECK-NEXT: <-(plugin:[[#PID2]]) {"loadPluginLibraryResult":{"diagnostics":[],"loaded":true}} --// CHECK-NEXT: ->(plugin:[[#PID2]]) {"loadPluginLibrary":{"libraryPath":"BUILD_DIR{{.*}}plugins/libEvilMacros.dylib","moduleName":"EvilMacros"}} -+// CHECK-NEXT: ->(plugin:[[#PID2]]) {"loadPluginLibrary":{"libraryPath":"{{.*}}EvilMacros.{{dylib|so|dll}}","moduleName":"EvilMacros"}} - // CHECK-NEXT: <-(plugin:[[#PID2]]) {"loadPluginLibraryResult":{"diagnostics":[],"loaded":true}} - // CHECK-NEXT: ->(plugin:[[#PID2]]) {"expandFreestandingMacro":{"discriminator":"${{.*}}","macro":{"moduleName":"MacroDefinition","name":"stringify","typeName":"StringifyMacro"},"macroRole":"expression","syntax":{"kind":"expression","location":{{{.+}}},"source":"#stringify(b + a)"}}} - // CHECK-NEXT: <-(plugin:[[#PID2]]) {"expandMacroResult":{"diagnostics":[],"expandedSource":"(b + a, \"b + a\")"}} -diff --git a/swift/test/lit.site.cfg.in b/swift/test/lit.site.cfg.in -index 06af9476c7f12..740a08c33bc7b 100644 ---- a/swift/test/lit.site.cfg.in -+++ b/swift/test/lit.site.cfg.in -@@ -166,7 +166,7 @@ elif "@BOOTSTRAPPING_MODE@" == 'BOOTSTRAPPING': - elif "@BOOTSTRAPPING_MODE@" == 'BOOTSTRAPPING-WITH-HOSTLIBS': - config.available_features.add('bootstrapping_with_hostlibs_mode') - --if '@SWIFT_SWIFT_PARSER@' == 'TRUE': -+if '@SWIFT_BUILD_SWIFT_SYNTAX@' == 'TRUE': - config.available_features.add('swift_swift_parser') - - # Let the main config do the real work. -diff --git a/swift/tools/SourceKit/cmake/modules/AddSwiftSourceKit.cmake b/swift/tools/SourceKit/cmake/modules/AddSwiftSourceKit.cmake -index 5514431eea9ce..4b5a63fef6046 100644 ---- a/swift/tools/SourceKit/cmake/modules/AddSwiftSourceKit.cmake -+++ b/swift/tools/SourceKit/cmake/modules/AddSwiftSourceKit.cmake -@@ -25,7 +25,7 @@ function(add_sourcekit_swift_runtime_link_flags target path HAS_SWIFT_MODULES) - # to do it. - set(ASKD_BOOTSTRAPPING_MODE ${BOOTSTRAPPING_MODE}) - if (NOT ASKD_BOOTSTRAPPING_MODE) -- if (SWIFT_SWIFT_PARSER) -+ if (SWIFT_BUILD_SWIFT_SYNTAX) - set(ASKD_BOOTSTRAPPING_MODE HOSTTOOLS) - endif() - endif() -@@ -115,12 +115,6 @@ function(add_sourcekit_swift_runtime_link_flags target path HAS_SWIFT_MODULES) - LINK_FLAGS " -lobjc ") - - endif() # HAS_SWIFT_MODULES AND ASKD_BOOTSTRAPPING_MODE -- -- if(SWIFT_SWIFT_PARSER) -- # Add rpath to the host Swift libraries. -- file(RELATIVE_PATH relative_hostlib_path "${path}" "${SWIFTLIB_DIR}/host") -- list(APPEND RPATH_LIST "@loader_path/${relative_hostlib_path}") -- endif() - elseif(SWIFT_HOST_VARIANT_SDK MATCHES "LINUX|ANDROID|OPENBSD" AND HAS_SWIFT_MODULES AND ASKD_BOOTSTRAPPING_MODE) - set(swiftrt "swiftImageRegistrationObject${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_OBJECT_FORMAT}-${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_LIB_SUBDIR}-${SWIFT_HOST_VARIANT_ARCH}") - if(ASKD_BOOTSTRAPPING_MODE MATCHES "HOSTTOOLS|CROSSCOMPILE") -@@ -156,18 +150,22 @@ function(add_sourcekit_swift_runtime_link_flags target path HAS_SWIFT_MODULES) - else() - message(FATAL_ERROR "Unknown ASKD_BOOTSTRAPPING_MODE '${ASKD_BOOTSTRAPPING_MODE}'") - endif() -+ endif() - -- if(SWIFT_SWIFT_PARSER) -+ if(SWIFT_BUILD_SWIFT_SYNTAX) -+ if(SWIFT_HOST_VARIANT_SDK IN_LIST SWIFT_DARWIN_PLATFORMS) -+ # Add rpath to the host Swift libraries. -+ file(RELATIVE_PATH relative_hostlib_path "${path}" "${SWIFTLIB_DIR}/host") -+ list(APPEND RPATH_LIST "@loader_path/${relative_hostlib_path}") -+ elseif(SWIFT_HOST_VARIANT_SDK MATCHES "LINUX|ANDROID|OPENBSD") - # Add rpath to the host Swift libraries. - file(RELATIVE_PATH relative_hostlib_path "${path}" "${SWIFTLIB_DIR}/host") - list(APPEND RPATH_LIST "$ORIGIN/${relative_hostlib_path}") -+ else() -+ target_link_directories(${target} PRIVATE -+ ${SWIFT_PATH_TO_SWIFT_SDK}/usr/lib/swift/${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_LIB_SUBDIR}/${SWIFT_HOST_VARIANT_ARCH}) - endif() -- else() -- target_link_directories(${target} PRIVATE -- ${SWIFT_PATH_TO_SWIFT_SDK}/usr/lib/swift/${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_LIB_SUBDIR}/${SWIFT_HOST_VARIANT_ARCH}) -- endif() - -- if(SWIFT_SWIFT_PARSER) - # For the "end step" of bootstrapping configurations on Darwin, need to be - # able to fall back to the SDK directory for libswiftCore et al. - if (BOOTSTRAPPING_MODE MATCHES "BOOTSTRAPPING.*") -@@ -263,7 +261,7 @@ macro(add_sourcekit_library name) - endif() - - # Once the new Swift parser is linked, everything has Swift modules. -- if (SWIFT_SWIFT_PARSER AND SOURCEKITLIB_SHARED) -+ if (SWIFT_BUILD_SWIFT_SYNTAX AND SOURCEKITLIB_SHARED) - set(SOURCEKITLIB_HAS_SWIFT_MODULES ON) - endif() - -@@ -367,7 +365,7 @@ macro(add_sourcekit_framework name) - set(framework_location "${lib_dir}/${name}.framework") - - # Once the new Swift parser is linked, everything has Swift modules. -- if (SWIFT_SWIFT_PARSER) -+ if (SWIFT_BUILD_SWIFT_SYNTAX) - set(SOURCEKITFW_HAS_SWIFT_MODULES ON) - endif() - -@@ -439,7 +437,6 @@ macro(add_sourcekit_framework name) - file(RELATIVE_PATH relative_lib_path - "${framework_location}/Versions/A" "${SOURCEKIT_LIBRARY_OUTPUT_INTDIR}") - list(APPEND RPATH_LIST "@loader_path/${relative_lib_path}") -- list(APPEND RPATH_LIST "@loader_path/${relative_lib_path}/swift/host") - - set_target_properties(${name} PROPERTIES - BUILD_WITH_INSTALL_RPATH TRUE -@@ -475,7 +472,6 @@ macro(add_sourcekit_framework name) - file(RELATIVE_PATH relative_lib_path - "${framework_location}" "${SOURCEKIT_LIBRARY_OUTPUT_INTDIR}") - list(APPEND RPATH_LIST "@loader_path/${relative_lib_path}") -- list(APPEND RPATH_LIST "@loader_path/${relative_lib_path}/swift/host") - - set_target_properties(${name} PROPERTIES - BUILD_WITH_INSTALL_RPATH TRUE -@@ -567,7 +563,6 @@ macro(add_sourcekit_xpc_service name framework_target) - - file(RELATIVE_PATH relative_lib_path "${xpc_bin_dir}" "${lib_dir}") - list(APPEND RPATH_LIST "@loader_path/${relative_lib_path}") -- list(APPEND RPATH_LIST "@loader_path/${relative_lib_path}/swift/host") - - # Add rpath for sourcekitdInProc - # lib/${framework_target}.framework/Versions/A/XPCServices/${name}.xpc/Contents/MacOS/${name} -diff --git a/swift/tools/driver/CMakeLists.txt b/swift/tools/driver/CMakeLists.txt -index 9c2e5ed6486a9..f6ceb3dae63d8 100644 ---- a/swift/tools/driver/CMakeLists.txt -+++ b/swift/tools/driver/CMakeLists.txt -@@ -4,9 +4,7 @@ - # Add additional libraries to which we need to link when the Swift Swift - # parser is built in. - function(add_swift_parser_link_libraries target) -- if(SWIFT_SWIFT_PARSER) -- target_link_directories(${target} PRIVATE -- ${SWIFT_PATH_TO_SWIFT_SDK}/usr/lib/swift/${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_LIB_SUBDIR}/${SWIFT_HOST_VARIANT_ARCH}) -+ if(SWIFT_BUILD_SWIFT_SYNTAX) - target_link_libraries(${target} - PRIVATE swiftCore) - -diff --git a/swift/tools/libSwiftScan/CMakeLists.txt b/swift/tools/libSwiftScan/CMakeLists.txt -index 1a99080337f84..ced11bf418416 100644 ---- a/swift/tools/libSwiftScan/CMakeLists.txt -+++ b/swift/tools/libSwiftScan/CMakeLists.txt -@@ -43,7 +43,7 @@ if(SWIFT_HOST_VARIANT_SDK MATCHES "LINUX|ANDROID|OPENBSD|FREEBSD" AND BOOTSTRAPP - ) - endif() - --if(SWIFT_SWIFT_PARSER) -+if(SWIFT_BUILD_SWIFT_SYNTAX) - if(SWIFT_HOST_VARIANT_SDK IN_LIST SWIFT_DARWIN_PLATFORMS) - # Ensure that we can find the host shared libraries. - set_property( -diff --git a/swift/tools/swift-plugin-server/CMakeLists.txt b/swift/tools/swift-plugin-server/CMakeLists.txt -index 1d1b88b22bd8a..34e8637089521 100644 ---- a/swift/tools/swift-plugin-server/CMakeLists.txt -+++ b/swift/tools/swift-plugin-server/CMakeLists.txt -@@ -1,4 +1,4 @@ --if (SWIFT_SWIFT_PARSER) -+if (SWIFT_BUILD_SWIFT_SYNTAX) - # _swiftCSwiftPluginServer is just a C support library for swift-plugin-server - # Don't bother to create '.a' for that. - add_swift_host_library(_swiftCSwiftPluginServer OBJECT -@@ -19,9 +19,9 @@ if (SWIFT_SWIFT_PARSER) - SWIFT_COMPONENT - compiler - SWIFT_DEPENDENCIES -- SwiftSyntax::SwiftSyntaxMacros -- SwiftSyntax::SwiftSyntaxMacroExpansion -- SwiftSyntax::SwiftCompilerPluginMessageHandling -+ SwiftSyntaxMacros -+ SwiftSyntaxMacroExpansion -+ SwiftCompilerPluginMessageHandling - swiftLLVMJSON - ) - target_include_directories(swift-plugin-server PRIVATE -diff --git a/swift/utils/build-script-impl b/swift/utils/build-script-impl -index 4a243bd7cab5e..4d388a96e3ed1 100755 ---- a/swift/utils/build-script-impl -+++ b/swift/utils/build-script-impl -@@ -836,16 +836,6 @@ function set_build_options_for_host() { - swift_cmake_options+=( - -DCOVERAGE_DB="${COVERAGE_DB}" - ) -- -- if [[ "$(true_false ${SWIFT_EARLYSWIFTSYNTAX})" == "TRUE" ]]; then -- early_swiftsyntax_build_dir="$(build_directory ${host} earlyswiftsyntax)" -- swift_cmake_options+=( -- -DSWIFT_PATH_TO_EARLYSWIFTSYNTAX_BUILD_DIR:PATH="${early_swiftsyntax_build_dir}" -- ) -- lldb_cmake_options+=( -- -DSWIFT_PATH_TO_EARLYSWIFTSYNTAX_BUILD_DIR:PATH="${early_swiftsyntax_build_dir}" -- ) -- fi - } - - function configure_default_options() { -diff --git a/swift/utils/swift_build_support/swift_build_support/build_script_invocation.py b/swift/utils/swift_build_support/swift_build_support/build_script_invocation.py -index 4d70897286f6a..166c5ea02cced 100644 ---- a/swift/utils/swift_build_support/swift_build_support/build_script_invocation.py -+++ b/swift/utils/swift_build_support/swift_build_support/build_script_invocation.py -@@ -251,13 +251,15 @@ def convert_to_impl_arguments(self): - args.extra_cmake_options.append( - '-DSWIFT_BACK_DEPLOY_CONCURRENCY:BOOL=TRUE') - -- swift_syntax_src = os.path.join(self.workspace.source_root, -- "swift-syntax") -- args.extra_cmake_options.append( -- '-DSWIFT_PATH_TO_SWIFT_SYNTAX_SOURCE:PATH={}'.format(swift_syntax_src)) -- - if args.build_early_swiftsyntax: -- impl_args += ["--swift-earlyswiftsyntax"] -+ swift_syntax_src = os.path.join(self.workspace.source_root, -+ "swift-syntax") -+ args.extra_cmake_options.append( -+ '-DSWIFT_PATH_TO_SWIFT_SYNTAX_SOURCE:PATH={}'.format(swift_syntax_src)) -+ args.extra_cmake_options.append('-DSWIFT_BUILD_SWIFT_SYNTAX:BOOL=TRUE') -+ if self.args.assertions: -+ args.extra_cmake_options.append( -+ '-DSWIFTSYNTAX_ENABLE_ASSERTIONS:BOOL=TRUE') - - # Then add subproject install flags that either skip building them /or/ - # if we are going to build them and install_all is set, we also install -@@ -446,6 +448,15 @@ def convert_to_impl_arguments(self): - os.path.abspath(args.coverage_db) - ] - -+ # '--install-swiftsyntax' is a legacy form of 'swift-syntax-lib' -+ # install component. -+ if (args.install_swiftsyntax and -+ '--install-swift' not in args.build_script_impl_args): -+ impl_args += [ -+ "--install-swift", -+ "--swift-install-components=swift-syntax-lib" -+ ] -+ - if args.llvm_install_components: - impl_args += [ - "--llvm-install-components=%s" % args.llvm_install_components -@@ -568,9 +579,6 @@ def compute_product_pipelines(self): - - builder.begin_pipeline() - -- builder.add_product(products.EarlySwiftSyntax, -- is_enabled=self.args.build_early_swiftsyntax) -- - # If --skip-early-swift-driver is passed in, swift will be built - # as usual, but relying on its own C++-based (Legacy) driver. - # Otherwise, we build an "early" swift-driver using the host -diff --git a/swift/utils/swift_build_support/swift_build_support/products/__init__.py b/swift/utils/swift_build_support/swift_build_support/products/__init__.py -index 40fd43960af40..3294929bd1585 100644 ---- a/swift/utils/swift_build_support/swift_build_support/products/__init__.py -+++ b/swift/utils/swift_build_support/swift_build_support/products/__init__.py -@@ -15,7 +15,6 @@ - from .cmark import CMark - from .curl import LibCurl - from .earlyswiftdriver import EarlySwiftDriver --from .earlyswiftsyntax import EarlySwiftSyntax - from .foundation import Foundation - from .indexstoredb import IndexStoreDB - from .libcxx import LibCXX -@@ -65,7 +64,6 @@ - 'SwiftPM', - 'SwiftDriver', - 'EarlySwiftDriver', -- 'EarlySwiftSyntax', - 'XCTest', - 'SwiftSyntax', - 'SKStressTester', -diff --git a/swift/utils/swift_build_support/swift_build_support/products/earlyswiftdriver.py b/swift/utils/swift_build_support/swift_build_support/products/earlyswiftdriver.py -index 48f4e59014f1a..62c5222a54bf3 100644 ---- a/swift/utils/swift_build_support/swift_build_support/products/earlyswiftdriver.py -+++ b/swift/utils/swift_build_support/swift_build_support/products/earlyswiftdriver.py -@@ -13,7 +13,6 @@ - import os - import sys - --from . import earlyswiftsyntax - from . import product - from .. import shell - from .. import toolchain -@@ -64,11 +63,7 @@ def should_build(self, host_target): - - @classmethod - def get_dependencies(cls): -- # FIXME: This isn't a real dependency, but is necessary to linearize the -- # dependency graph from Swift to EarlySwiftSyntax. If we properly -- # express the dependency from Swift -> EarlySwiftSyntax, build_graph.py -- # asserts that there are multiple roots to the graph. -- return [earlyswiftsyntax.EarlySwiftSyntax] -+ return [] - - def should_clean(self, host_target): - return self.args.clean_early_swift_driver -diff --git a/swift/utils/swift_build_support/swift_build_support/products/earlyswiftsyntax.py b/swift/utils/swift_build_support/swift_build_support/products/earlyswiftsyntax.py -deleted file mode 100644 -index 37c1bede9b0bd..0000000000000 ---- a/swift/utils/swift_build_support/swift_build_support/products/earlyswiftsyntax.py -+++ /dev/null -@@ -1,83 +0,0 @@ --# swift_build_support/products/earlyswiftsyntax.py --------------*- python -*- --# --# This source file is part of the Swift.org open source project --# --# Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors --# Licensed under Apache License v2.0 with Runtime Library Exception --# --# See https://swift.org/LICENSE.txt for license information --# See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors --# --# ---------------------------------------------------------------------------- -- --import sys -- --from . import cmake_product --from .. import toolchain -- -- --# SwiftSyntax is a Swift module used to parse and manipulate Swift syntax. This --# build product is a "Special" SwiftSyntax that gets built with the host --# toolchain that can be linked into the Swift compiler itself, hence it does not --# depend on any other build product of `build-script`. --class EarlySwiftSyntax(cmake_product.CMakeProduct): -- @classmethod -- def product_source_name(cls): -- return "swift-syntax" -- -- @classmethod -- def is_build_script_impl_product(cls): -- return False -- -- @classmethod -- def is_before_build_script_impl_product(cls): -- return True -- -- def should_build(self, host_target): -- # Temporarily disable for non-darwin since this build never works -- # outside of that case currently. -- if sys.platform != 'darwin' and sys.platform != 'linux': -- return False -- -- if self.args.build_early_swiftsyntax: -- if toolchain.host_toolchain().find_tool("swift") is None: -- warn_msg = 'Host toolchain could not locate a '\ -- 'compiler to build early swift-syntax.' -- print('-- Warning: {}', warn_msg) -- return False -- else: -- return True -- return False -- -- @classmethod -- def get_dependencies(cls): -- return [] -- -- def build(self, host_target): -- self.cmake_options.define('CMAKE_BUILD_TYPE:STRING', -- self.args.swift_build_variant) -- self.cmake_options.define('BUILD_SHARED_LIBS:STRING', 'YES') -- -- self.generate_toolchain_file_for_darwin_or_linux(host_target) -- -- self.cmake_options.define('CMAKE_INSTALL_PREFIX:PATH', self.args.install_prefix) -- self.cmake_options.define('SWIFTSYNTAX_ENABLE_ASSERTIONS:BOOL', -- self.args.assertions) -- self.cmake_options.define('SWIFT_MODULE_ABI_NAME_PREFIX:STRING', 'Compiler') -- self.build_with_cmake(["all"], self.args.swift_build_variant, []) -- -- def should_test(self, host_target): -- # The normal SwiftSyntax target runs tests through SwiftPM. -- return False -- -- def test(self, host_target): -- pass -- -- def should_install(self, host_target): -- # When '--install-swift' is enabled, earlyswiftsyntax libraries are installed -- # from 'swift' product. -- return (self.should_build(host_target) and self.args.install_swiftsyntax and -- "--install-swift" not in self.args.build_script_impl_args) -- -- def install(self, host_target): -- self.install_with_cmake(["install"], self.host_install_destdir(host_target)) diff --git a/packages/swift/swift-pure-bridging.patch b/packages/swift/swift-pure-bridging.patch new file mode 100644 index 0000000000..adef36d90d --- /dev/null +++ b/packages/swift/swift-pure-bridging.patch @@ -0,0 +1,6451 @@ +From 2dbd6cc56bb29db3d23dcd3c85d83f75ddc8bfab +From: Erik Eckstein +Date: Fri, 6 Oct 2023 20:19:24 +0200 +Subject: [PATCH] SwiftCompilerSources: rework bridging + +Introduce two modes of bridging: +* inline mode: this is basically how it worked so far. Using full C++ interop which allows bridging functions to be inlined. +* pure mode: bridging functions are not inlined but compiled in a cpp file. This allows to reduce the C++ interop requirements to a minimum. No std/llvm/swift headers are imported. + +This change requires a major refactoring of bridging sources. The implementation of bridging functions go to two separate files: SILBridgingImpl.h and OptimizerBridgingImpl.h. +Depending on the mode, those files are either included in the corresponding header files (inline mode), or included in the c++ file (pure mode). + +The mode can be selected with the BRIDGING_MODE cmake variable. By default it is set to the inline mode (= existing behavior). The pure mode is only selected in certain configurations to work around C++ interop issues: +* In debug builds, to workaround a problem with LLDB's `po` command (rdar://115770255). +* On windows to workaround a build problem. + +diff --git a/swift/CMakeLists.txt b/swift/CMakeLists.txt +index 294649a5ac0..027ca16521e 100644 +--- a/swift/CMakeLists.txt ++++ b/swift/CMakeLists.txt +@@ -346,6 +346,13 @@ How to build the swift compiler modules. Possible values are + compiler, provided in `SWIFT_NATIVE_SWIFT_TOOLS_PATH` + ]=] OFF) + ++option(BRIDGING_MODE [=[ ++How swift-C++ bridging code is compiled: ++ INLINE: uses full swift C++ interop and briding functions are inlined ++ PURE: uses limited C++ interp an bridging functions are not inlined ++ DEFAULT: based on the build configuration ++]=] DEFAULT) ++ + # The following only works with the Ninja generator in CMake >= 3.0. + set(SWIFT_PARALLEL_LINK_JOBS "" CACHE STRING + "Define the maximum number of linker jobs for swift.") +@@ -390,6 +397,17 @@ set(SWIFT_STDLIB_MSVC_RUNTIME_LIBRARY + ${SWIFT_STDLIB_MSVC_RUNTIME_LIBRARY_default} + CACHE STRING "MSVC Runtime Library for the standard library") + ++ ++if(BRIDGING_MODE STREQUAL "DEFAULT" OR NOT BRIDGING_MODE) ++ if(CMAKE_BUILD_TYPE STREQUAL "Debug" OR "${CMAKE_SYSTEM_NAME}" STREQUAL "Windows") ++ # In debug builds, to workaround a problem with LLDB's `po` command (rdar://115770255). ++ # On windows to workaround a build problem. ++ set(BRIDGING_MODE "PURE") ++ else() ++ set(BRIDGING_MODE "INLINE") ++ endif() ++endif() ++ + is_build_type_optimized("${SWIFT_STDLIB_BUILD_TYPE}" swift_optimized) + if(swift_optimized) + set(SWIFT_STDLIB_ASSERTIONS_default FALSE) +diff --git a/swift/SwiftCompilerSources/CMakeLists.txt b/swift/SwiftCompilerSources/CMakeLists.txt +index 138d208d9a3..e962132dec5 100644 +--- a/swift/SwiftCompilerSources/CMakeLists.txt ++++ b/swift/SwiftCompilerSources/CMakeLists.txt +@@ -76,6 +76,7 @@ function(add_swift_compiler_modules_library name) + "-Xfrontend" "-validate-tbd-against-ir=none" + "-Xfrontend" "-enable-experimental-cxx-interop" + "-Xcc" "-std=c++17" ++ "-Xcc" "-DCOMPILED_WITH_SWIFT" + "-Xcc" "-UIBOutlet" "-Xcc" "-UIBAction" "-Xcc" "-UIBInspectable") + if (NOT BOOTSTRAPPING_MODE STREQUAL "HOSTTOOLS") + list(APPEND swift_compile_options "-Xfrontend" "-disable-implicit-string-processing-module-import") +@@ -91,6 +92,10 @@ function(add_swift_compiler_modules_library name) + list(APPEND swift_compile_options "-Xcc" "-DNDEBUG") + endif() + ++ if("${BRIDGING_MODE}" STREQUAL "PURE") ++ list(APPEND swift_compile_options "-Xcc" "-DPURE_BRIDGING_MODE") ++ endif() ++ + if(NOT SWIFT_STDLIB_SUPPORT_BACK_DEPLOYMENT) + list(APPEND swift_compile_options "-Xfrontend" "-disable-legacy-type-info") + endif() +@@ -237,8 +242,8 @@ else() + # defined in include/swift/module.modulemap + file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/HeaderDependencies.cpp.tmp" + " +-#include \"Basic/BridgedSwiftObject.h\" +-#include \"Basic/BasicBridging.h\" ++#define COMPILED_WITH_SWIFT ++#include \"Basic/BasicBridging.h\" + #include \"SIL/SILBridging.h\" + + #include \"SILOptimizer/OptimizerBridging.h\" +diff --git a/swift/SwiftCompilerSources/Sources/Basic/SourceLoc.swift b/swift/SwiftCompilerSources/Sources/Basic/SourceLoc.swift +index aa1094dd786..a82baf8d2fc 100644 +--- a/swift/SwiftCompilerSources/Sources/Basic/SourceLoc.swift ++++ b/swift/SwiftCompilerSources/Sources/Basic/SourceLoc.swift +@@ -23,19 +23,15 @@ public struct SourceLoc { + self.locationInFile = locationInFile + } + +- public init?(bridged: swift.SourceLoc) { ++ public init?(bridged: BridgedSourceLoc) { + guard bridged.isValid() else { + return nil + } +-#if $NewCxxMethodSafetyHeuristics +- self.locationInFile = bridged.getOpaquePointerValue().assumingMemoryBound(to: UInt8.self) +-#else +- self.locationInFile = bridged.__getOpaquePointerValueUnsafe().assumingMemoryBound(to: UInt8.self) +-#endif ++ self.locationInFile = bridged.uint8Pointer()! + } + +- public var bridged: swift.SourceLoc { +- .init(llvm.SMLoc.getFromPointer(locationInFile)) ++ public var bridged: BridgedSourceLoc { ++ .init(locationInFile) + } + } + +@@ -46,40 +42,24 @@ extension SourceLoc { + } + + extension Optional where Wrapped == SourceLoc { +- public var bridged: swift.SourceLoc { ++ public var bridged: BridgedSourceLoc { + self?.bridged ?? .init() + } + } + + public struct CharSourceRange { +- private let start: SourceLoc +- private let byteLength: UInt32 ++ public let start: SourceLoc ++ public let byteLength: UInt32 + + public init(start: SourceLoc, byteLength: UInt32) { + self.start = start + self.byteLength = byteLength + } + +- public init?(bridged: swift.CharSourceRange) { +-#if $NewCxxMethodSafetyHeuristics +- guard let start = SourceLoc(bridged: bridged.getStart()) else { ++ public init?(bridgedStart: BridgedSourceLoc, byteLength: UInt32) { ++ guard let start = SourceLoc(bridged: bridgedStart) else { + return nil + } +-#else +- guard let start = SourceLoc(bridged: bridged.__getStartUnsafe()) else { +- return nil +- } +-#endif +- self.init(start: start, byteLength: bridged.getByteLength()) +- } +- +- public var bridged: swift.CharSourceRange { +- .init(start.bridged, byteLength) +- } +-} +- +-extension Optional where Wrapped == CharSourceRange { +- public var bridged: swift.CharSourceRange { +- self?.bridged ?? .init(.init(), 0) ++ self.init(start: start, byteLength: byteLength) + } + } +diff --git a/swift/SwiftCompilerSources/Sources/Basic/Utils.swift b/swift/SwiftCompilerSources/Sources/Basic/Utils.swift +index 853d3835faa..511fe58f00b 100644 +--- a/swift/SwiftCompilerSources/Sources/Basic/Utils.swift ++++ b/swift/SwiftCompilerSources/Sources/Basic/Utils.swift +@@ -58,42 +58,31 @@ public extension NoReflectionChildren { + //===----------------------------------------------------------------------===// + + public struct StringRef : CustomStringConvertible, NoReflectionChildren { +- let _bridged: llvm.StringRef ++ let _bridged: BridgedStringRef + +- public init(bridged: llvm.StringRef) { self._bridged = bridged } ++ public init(bridged: BridgedStringRef) { self._bridged = bridged } + +- public var string: String { _bridged.string } ++ public var string: String { String(_bridged) } + public var description: String { string } + + public var count: Int { +-#if $NewCxxMethodSafetyHeuristics +- Int(_bridged.bytes_end() - _bridged.bytes_begin()) +-#else +- Int(_bridged.__bytes_endUnsafe() - _bridged.__bytes_beginUnsafe()) +-#endif ++ Int(_bridged.size()) + } + + public subscript(index: Int) -> UInt8 { +-#if $NewCxxMethodSafetyHeuristics +- let buffer = UnsafeBufferPointer(start: _bridged.bytes_begin(), +- count: count) +-#else +- let buffer = UnsafeBufferPointer(start: _bridged.__bytes_beginUnsafe(), +- count: count) +-#endif ++ let buffer = UnsafeBufferPointer(start: _bridged.uintData(), count: count) + return buffer[index] + } + ++ public static func ==(lhs: StringRef, rhs: StringRef) -> Bool { ++ let lhsBuffer = UnsafeBufferPointer(start: lhs._bridged.uintData(), count: lhs.count) ++ let rhsBuffer = UnsafeBufferPointer(start: rhs._bridged.uintData(), count: rhs.count) ++ if lhsBuffer.count != rhsBuffer.count { return false } ++ return lhsBuffer.elementsEqual(rhsBuffer, by: ==) ++ } ++ + public static func ==(lhs: StringRef, rhs: StaticString) -> Bool { +-#if $NewCxxMethodSafetyHeuristics +- let lhsBuffer = UnsafeBufferPointer( +- start: lhs._bridged.bytes_begin(), +- count: lhs.count) +-#else +- let lhsBuffer = UnsafeBufferPointer( +- start: lhs._bridged.__bytes_beginUnsafe(), +- count: lhs.count) +-#endif ++ let lhsBuffer = UnsafeBufferPointer(start: lhs._bridged.uintData(), count: lhs.count) + return rhs.withUTF8Buffer { (rhsBuffer: UnsafeBufferPointer) in + if lhsBuffer.count != rhsBuffer.count { return false } + return lhsBuffer.elementsEqual(rhsBuffer, by: ==) +@@ -101,6 +90,7 @@ public struct StringRef : CustomStringConvertible, NoReflectionChildren { + } + + public static func !=(lhs: StringRef, rhs: StaticString) -> Bool { !(lhs == rhs) } ++ public static func !=(lhs: StringRef, rhs: StringRef) -> Bool { !(lhs == rhs) } + + public static func ~=(pattern: StaticString, value: StringRef) -> Bool { value == pattern } + } +@@ -109,27 +99,23 @@ public struct StringRef : CustomStringConvertible, NoReflectionChildren { + // Bridging Utilities + //===----------------------------------------------------------------------===// + +-extension llvm.StringRef { +- public var string: String { +- String(_cxxString: self.str()) +- } +-} +- + extension String { +- /// Underscored to avoid name collision with Swift LLVM Bindings. +- /// To be replaced with a bindings call once bindings are a dependency. +- public func _withStringRef(_ c: (llvm.StringRef) -> T) -> T { ++ public func _withBridgedStringRef(_ c: (BridgedStringRef) -> T) -> T { + var str = self + return str.withUTF8 { buffer in +- return c(llvm.StringRef(buffer.baseAddress, buffer.count)) ++ return c(BridgedStringRef(buffer.baseAddress, buffer.count)) + } + } + +- /// Underscored to avoid name collision with the std overlay. +- /// To be replaced with an overlay call once the CI uses SDKs built with Swift 5.8. +- public init(_cxxString s: std.string) { +- self.init(cString: s.__c_strUnsafe()) +- withExtendedLifetime(s) {} ++ public init(_ s: BridgedStringRef) { ++ let buffer = UnsafeBufferPointer(start: s.uintData(), count: Int(s.size())) ++ self.init(decoding: buffer, as: UTF8.self) ++ } ++ ++ public init(taking s: BridgedOwnedString) { ++ let buffer = UnsafeBufferPointer(start: s.uintData(), count: s.size()) ++ self.init(decoding: buffer, as: UTF8.self) ++ s.destroy() + } + } + +diff --git a/swift/SwiftCompilerSources/Sources/Optimizer/Analysis/AliasAnalysis.swift b/swift/SwiftCompilerSources/Sources/Optimizer/Analysis/AliasAnalysis.swift +index 21a0c2ce511..c2a880cd9b2 100644 +--- a/swift/SwiftCompilerSources/Sources/Optimizer/Analysis/AliasAnalysis.swift ++++ b/swift/SwiftCompilerSources/Sources/Optimizer/Analysis/AliasAnalysis.swift +@@ -36,7 +36,7 @@ struct AliasAnalysis { + static func register() { + BridgedAliasAnalysis.registerAnalysis( + // getMemEffectsFn +- { (bridgedCtxt: BridgedPassContext, bridgedVal: BridgedValue, bridgedInst: BridgedInstruction, complexityBudget: Int) -> swift.MemoryBehavior in ++ { (bridgedCtxt: BridgedPassContext, bridgedVal: BridgedValue, bridgedInst: BridgedInstruction, complexityBudget: Int) -> BridgedMemoryBehavior in + let context = FunctionPassContext(_bridged: bridgedCtxt) + let inst = bridgedInst.instruction + let val = bridgedVal.value +@@ -255,7 +255,7 @@ private struct IsIndirectResultWalker: AddressDefUseWalker { + } + + private extension SideEffects.Memory { +- var bridged: swift.MemoryBehavior { ++ var bridged: BridgedMemoryBehavior { + switch (read, write) { + case (false, false): return .None + case (true, false): return .MayRead +diff --git a/swift/SwiftCompilerSources/Sources/Optimizer/Analysis/CalleeAnalysis.swift b/swift/SwiftCompilerSources/Sources/Optimizer/Analysis/CalleeAnalysis.swift +index 18f0640d4a9..fc55ceb9393 100644 +--- a/swift/SwiftCompilerSources/Sources/Optimizer/Analysis/CalleeAnalysis.swift ++++ b/swift/SwiftCompilerSources/Sources/Optimizer/Analysis/CalleeAnalysis.swift +@@ -23,7 +23,7 @@ public struct CalleeAnalysis { + return inst.instruction.isDeinitBarrier(bca.analysis) + }, + // getMemBehaviorFn +- { (bridgedApply: BridgedInstruction, observeRetains: Bool, bca: BridgedCalleeAnalysis) -> swift.MemoryBehavior in ++ { (bridgedApply: BridgedInstruction, observeRetains: Bool, bca: BridgedCalleeAnalysis) -> BridgedMemoryBehavior in + let apply = bridgedApply.instruction as! ApplySite + let e = bca.analysis.getSideEffects(ofApply: apply) + return e.getMemBehavior(observeRetains: observeRetains) +@@ -126,13 +126,13 @@ extension Instruction { + } + + public struct FunctionArray : RandomAccessCollection, FormattedLikeArray { +- fileprivate let bridged: swift.CalleeList ++ fileprivate let bridged: BridgedCalleeAnalysis.CalleeList + + public var startIndex: Int { 0 } +- public var endIndex: Int { Int(bridged.getCount()) } ++ public var endIndex: Int { bridged.getCount() } + + public subscript(_ index: Int) -> Function { +- return BridgedCalleeAnalysis.getCallee(bridged, index).function ++ return bridged.getCallee(index).function + } + } + // Bridging utilities +diff --git a/swift/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/MergeCondFails.swift b/swift/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/MergeCondFails.swift +index 7338d8f8650..64b0bfe1e66 100644 +--- a/swift/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/MergeCondFails.swift ++++ b/swift/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/MergeCondFails.swift +@@ -86,7 +86,7 @@ private func mergeCondFails(_ condFailToMerge: inout Stack, + + // Create a new cond_fail using the merged condition. + _ = builder.createCondFail(condition: mergedCond!, +- message: lastCFI.message) ++ message: lastCFI.message.string) + + while let cfi = condFailToMerge.pop() { + context.erase(instruction: cfi) +diff --git a/swift/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/ObjectOutliner.swift b/swift/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/ObjectOutliner.swift +index 78f240c3e4a..0a97c61b24b 100644 +--- a/swift/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/ObjectOutliner.swift ++++ b/swift/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/ObjectOutliner.swift +@@ -161,10 +161,11 @@ private func findStores(toTailAddress tailAddr: Value, tailElementIndex: Int, st + for use in tailAddr.uses { + switch use.instruction { + case let indexAddr as IndexAddrInst: +- guard let indexLiteral = indexAddr.index as? IntegerLiteralInst else { ++ guard let indexLiteral = indexAddr.index as? IntegerLiteralInst, ++ let tailIdx = indexLiteral.value else ++ { + return false + } +- let tailIdx = Int(indexLiteral.value.getZExtValue()) + if !findStores(toTailAddress: indexAddr, tailElementIndex: tailElementIndex + tailIdx, stores: &stores) { + return false + } +@@ -381,11 +382,12 @@ private extension AllocRefInstBase { + } + + // The number of tail allocated elements must be constant. +- guard let tailCountLiteral = tailAllocatedCounts[0].value as? IntegerLiteralInst, +- tailCountLiteral.value.getActiveBits() <= 20 else { +- return nil ++ if let tailCountLiteral = tailAllocatedCounts[0].value as? IntegerLiteralInst, ++ let count = tailCountLiteral.value ++ { ++ return count + } +- return Int(tailCountLiteral.value.getZExtValue()); ++ return nil + } + + var numClassFields: Int { +diff --git a/swift/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyCondBranch.swift b/swift/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyCondBranch.swift +index 69a799e9087..8b71648f1e0 100644 +--- a/swift/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyCondBranch.swift ++++ b/swift/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyCondBranch.swift +@@ -20,11 +20,13 @@ extension CondBranchInst : OnoneSimplifyable { + + private extension CondBranchInst { + func tryConstantFold(_ context: SimplifyContext) { +- guard let literal = condition as? IntegerLiteralInst else { ++ guard let literal = condition as? IntegerLiteralInst, ++ let conditionValue = literal.value else ++ { + return + } + let builder = Builder(before: self, context) +- if literal.value.isZero() { ++ if conditionValue == 0 { + builder.createBranch(to: falseBlock, arguments: Array(falseOperands.map { $0.value })) + } else { + builder.createBranch(to: trueBlock, arguments: Array(trueOperands.map { $0.value })) +diff --git a/swift/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyCondFail.swift b/swift/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyCondFail.swift +index 9a423cae55b..b7ef2f29d30 100644 +--- a/swift/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyCondFail.swift ++++ b/swift/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyCondFail.swift +@@ -21,8 +21,9 @@ extension CondFailInst : OnoneSimplifyable { + /// cond_fail %0, "message" + /// ``` + if let literal = condition as? IntegerLiteralInst, +- literal.value.isZero() { +- ++ let value = literal.value, ++ value == 0 ++ { + context.erase(instruction: self) + } + } +diff --git a/swift/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyLoad.swift b/swift/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyLoad.swift +index 0596b9402a0..8d61c21544e 100644 +--- a/swift/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyLoad.swift ++++ b/swift/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyLoad.swift +@@ -284,10 +284,11 @@ private extension Value { + func getBaseAddressAndOffset() -> (baseAddress: Value, offset: Int)? { + if let indexAddr = self as? IndexAddrInst { + guard let indexLiteral = indexAddr.index as? IntegerLiteralInst, +- indexLiteral.value.getActiveBits() <= 32 else { ++ let indexValue = indexLiteral.value else ++ { + return nil + } +- return (baseAddress: indexAddr.base, offset: Int(indexLiteral.value.getZExtValue())) ++ return (baseAddress: indexAddr.base, offset: indexValue) + } + return (baseAddress: self, offset: 0) + } +@@ -297,9 +298,11 @@ private extension Instruction { + var isShiftRightByAtLeastOne: Bool { + guard let bi = self as? BuiltinInst, + bi.id == .LShr, +- let shiftLiteral = bi.operands[1].value as? IntegerLiteralInst else { ++ let shiftLiteral = bi.operands[1].value as? IntegerLiteralInst, ++ let shiftValue = shiftLiteral.value else ++ { + return false + } +- return shiftLiteral.value.isStrictlyPositive() ++ return shiftValue > 0 + } + } +diff --git a/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/Context.swift b/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/Context.swift +index 304fe88cacf..4ebec621530 100644 +--- a/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/Context.swift ++++ b/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/Context.swift +@@ -204,7 +204,7 @@ struct FunctionPassContext : MutatingContext { + + func loadFunction(name: StaticString, loadCalleesRecursively: Bool) -> Function? { + return name.withUTF8Buffer { (nameBuffer: UnsafeBufferPointer) in +- let nameStr = llvm.StringRef(nameBuffer.baseAddress, nameBuffer.count) ++ let nameStr = BridgedStringRef(nameBuffer.baseAddress, nameBuffer.count) + return _bridged.loadFunction(nameStr, loadCalleesRecursively).function + } + } +@@ -222,7 +222,7 @@ struct FunctionPassContext : MutatingContext { + /// Returns nil if no such function or multiple matching functions are found. + func lookupStdlibFunction(name: StaticString) -> Function? { + return name.withUTF8Buffer { (nameBuffer: UnsafeBufferPointer) in +- let nameStr = llvm.StringRef(nameBuffer.baseAddress, nameBuffer.count) ++ let nameStr = BridgedStringRef(nameBuffer.baseAddress, nameBuffer.count) + return _bridged.lookupStdlibFunction(nameStr).function + } + } +@@ -241,7 +241,7 @@ struct FunctionPassContext : MutatingContext { + } + + func optimizeMemoryAccesses(in function: Function) -> Bool { +- if swift.optimizeMemoryAccesses(function.bridged.getFunction()) { ++ if BridgedPassContext.optimizeMemoryAccesses(function.bridged) { + notifyInstructionsChanged() + return true + } +@@ -249,7 +249,7 @@ struct FunctionPassContext : MutatingContext { + } + + func eliminateDeadAllocations(in function: Function) -> Bool { +- if swift.eliminateDeadAllocations(function.bridged.getFunction()) { ++ if BridgedPassContext.eliminateDeadAllocations(function.bridged) { + notifyInstructionsChanged() + return true + } +@@ -266,12 +266,11 @@ struct FunctionPassContext : MutatingContext { + } + + func mangleOutlinedVariable(from function: Function) -> String { +- let stdString = _bridged.mangleOutlinedVariable(function.bridged) +- return String(_cxxString: stdString) ++ return String(taking: _bridged.mangleOutlinedVariable(function.bridged)) + } + + func createGlobalVariable(name: String, type: Type, isPrivate: Bool) -> GlobalVariable { +- let gv = name._withStringRef { ++ let gv = name._withBridgedStringRef { + _bridged.createGlobalVariable($0, type.bridged, isPrivate) + } + return gv.globalVar +diff --git a/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/ModulePassContext.swift b/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/ModulePassContext.swift +index 557ba9f8366..6ecd6dd740f 100644 +--- a/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/ModulePassContext.swift ++++ b/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/ModulePassContext.swift +@@ -22,8 +22,7 @@ struct ModulePassContext : Context, CustomStringConvertible { + let _bridged: BridgedPassContext + + public var description: String { +- let stdString = _bridged.getModuleDescription() +- return String(_cxxString: stdString) ++ return String(taking: _bridged.getModuleDescription()) + } + + struct FunctionList : CollectionLikeSequence, IteratorProtocol { +diff --git a/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/PassRegistration.swift b/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/PassRegistration.swift +index 060adf01abf..00db3b95ec4 100644 +--- a/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/PassRegistration.swift ++++ b/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/PassRegistration.swift +@@ -25,7 +25,7 @@ public func initializeSwiftModules() { + private func registerPass( + _ pass: ModulePass, + _ runFn: @escaping (@convention(c) (BridgedPassContext) -> ())) { +- pass.name._withStringRef { nameStr in ++ pass.name._withBridgedStringRef { nameStr in + SILPassManager_registerModulePass(nameStr, runFn) + } + } +@@ -33,7 +33,7 @@ private func registerPass( + private func registerPass( + _ pass: FunctionPass, + _ runFn: @escaping (@convention(c) (BridgedFunctionPassCtxt) -> ())) { +- pass.name._withStringRef { nameStr in ++ pass.name._withBridgedStringRef { nameStr in + SILPassManager_registerFunctionPass(nameStr, runFn) + } + } +@@ -54,7 +54,7 @@ private func run(_ instType: InstType.Type, + private func registerForSILCombine( + _ instType: InstType.Type, + _ runFn: @escaping (@convention(c) (BridgedInstructionPassCtxt) -> ())) { +- String(describing: instType)._withStringRef { instClassStr in ++ String(describing: instType)._withBridgedStringRef { instClassStr in + SILCombine_registerInstructionPass(instClassStr, runFn) + } + } +diff --git a/swift/SwiftCompilerSources/Sources/Optimizer/Utilities/WalkUtils.swift b/swift/SwiftCompilerSources/Sources/Optimizer/Utilities/WalkUtils.swift +index b2133ff9224..011e5c73530 100644 +--- a/swift/SwiftCompilerSources/Sources/Optimizer/Utilities/WalkUtils.swift ++++ b/swift/SwiftCompilerSources/Sources/Optimizer/Utilities/WalkUtils.swift +@@ -485,7 +485,7 @@ extension AddressDefUseWalker { + } + case let ia as IndexAddrInst: + if let (pathIdx, subPath) = path.pop(kind: .indexedElement) { +- if let idx = ia.constantSmallIndex, ++ if let idx = ia.constantIndex, + idx == pathIdx { + return walkDownUses(ofAddress: ia, path: subPath) + } +@@ -746,7 +746,7 @@ extension AddressUseDefWalker { + case is BeginAccessInst, is MarkUnresolvedNonCopyableValueInst: + return walkUp(address: (def as! Instruction).operands[0].value, path: path) + case let ia as IndexAddrInst: +- if let idx = ia.constantSmallIndex { ++ if let idx = ia.constantIndex { + return walkUp(address: ia.base, path: path.push(.indexedElement, index: idx)) + } else { + return walkUp(address: ia.base, path: path.push(.anyIndexedElement, index: 0)) +@@ -760,13 +760,11 @@ extension AddressUseDefWalker { + } + + private extension IndexAddrInst { +- var constantSmallIndex: Int? { +- guard let literal = index as? IntegerLiteralInst else { +- return nil +- } +- let index = literal.value +- if index.isIntN(16) { +- return Int(index.getSExtValue()) ++ var constantIndex: Int? { ++ if let literal = index as? IntegerLiteralInst, ++ let indexValue = literal.value ++ { ++ return indexValue + } + return nil + } +diff --git a/swift/SwiftCompilerSources/Sources/SIL/BasicBlock.swift b/swift/SwiftCompilerSources/Sources/SIL/BasicBlock.swift +index 6854ac57c72..a2abd532502 100644 +--- a/swift/SwiftCompilerSources/Sources/SIL/BasicBlock.swift ++++ b/swift/SwiftCompilerSources/Sources/SIL/BasicBlock.swift +@@ -21,8 +21,7 @@ final public class BasicBlock : CustomStringConvertible, HasShortDescription, Eq + public var parentFunction: Function { bridged.getFunction().function } + + public var description: String { +- let stdString = bridged.getDebugDescription() +- return String(_cxxString: stdString) ++ return String(taking: bridged.getDebugDescription()) + } + public var shortDescription: String { name } + +diff --git a/swift/SwiftCompilerSources/Sources/SIL/Builder.swift b/swift/SwiftCompilerSources/Sources/SIL/Builder.swift +index aa6f0893381..a24d36ff527 100644 +--- a/swift/SwiftCompilerSources/Sources/SIL/Builder.swift ++++ b/swift/SwiftCompilerSources/Sources/SIL/Builder.swift +@@ -65,7 +65,7 @@ public struct Builder { + public func createBuiltinBinaryFunction(name: String, + operandType: Type, resultType: Type, arguments: [Value]) -> BuiltinInst { + return arguments.withBridgedValues { valuesRef in +- return name._withStringRef { nameStr in ++ return name._withBridgedStringRef { nameStr in + let bi = bridged.createBuiltinBinaryFunction( + nameStr, operandType.bridged, resultType.bridged, valuesRef) + return notifyNew(bi.getAs(BuiltinInst.self)) +@@ -74,7 +74,7 @@ public struct Builder { + } + + public func createCondFail(condition: Value, message: String) -> CondFailInst { +- return message._withStringRef { messageStr in ++ return message._withBridgedStringRef { messageStr in + let cf = bridged.createCondFail(condition.bridged, messageStr) + return notifyNew(cf.getAs(CondFailInst.self)) + } +@@ -195,7 +195,7 @@ public struct Builder { + arguments: [Value], + isNonThrowing: Bool = false, + isNonAsync: Bool = false, +- specializationInfo: ApplyInst.SpecializationInfo = nil ++ specializationInfo: ApplyInst.SpecializationInfo = ApplyInst.SpecializationInfo() + ) -> ApplyInst { + let apply = arguments.withBridgedValues { valuesRef in + bridged.createApply(function.bridged, substitutionMap.bridged, valuesRef, +diff --git a/swift/SwiftCompilerSources/Sources/SIL/Function.swift b/swift/SwiftCompilerSources/Sources/SIL/Function.swift +index 77fde8318c8..8002a0a8779 100644 +--- a/swift/SwiftCompilerSources/Sources/SIL/Function.swift ++++ b/swift/SwiftCompilerSources/Sources/SIL/Function.swift +@@ -22,8 +22,7 @@ final public class Function : CustomStringConvertible, HasShortDescription, Hash + } + + final public var description: String { +- let stdString = bridged.getDebugDescription() +- return String(_cxxString: stdString) ++ return String(taking: bridged.getDebugDescription()) + } + + public var shortDescription: String { name.string } +@@ -113,7 +112,7 @@ final public class Function : CustomStringConvertible, HasShortDescription, Hash + + public func hasSemanticsAttribute(_ attr: StaticString) -> Bool { + attr.withUTF8Buffer { (buffer: UnsafeBufferPointer) in +- bridged.hasSemanticsAttr(llvm.StringRef(buffer.baseAddress!, buffer.count)) ++ bridged.hasSemanticsAttr(BridgedStringRef(buffer.baseAddress!, buffer.count)) + } + } + +@@ -284,19 +283,19 @@ final public class Function : CustomStringConvertible, HasShortDescription, Hash + } else { + s = effects.description + } +- s._withStringRef { OStream_write(os, $0) } ++ s._withBridgedStringRef { $0.write(os) } + }, + // parseFn: +- { (f: BridgedFunction, str: llvm.StringRef, mode: BridgedFunction.ParseEffectsMode, argumentIndex: Int, paramNames: BridgedArrayRef) -> BridgedFunction.ParsingError in ++ { (f: BridgedFunction, str: BridgedStringRef, mode: BridgedFunction.ParseEffectsMode, argumentIndex: Int, paramNames: BridgedArrayRef) -> BridgedFunction.ParsingError in + do { +- var parser = StringParser(str.string) ++ var parser = StringParser(String(str)) + let function = f.function + + switch mode { + case .argumentEffectsFromSource: +- let paramToIdx = paramNames.withElements(ofType: llvm.StringRef.self) { +- (buffer: UnsafeBufferPointer) -> Dictionary in +- let keyValPairs = buffer.enumerated().lazy.map { ($0.1.string, $0.0) } ++ let paramToIdx = paramNames.withElements(ofType: BridgedStringRef.self) { ++ (buffer: UnsafeBufferPointer) -> Dictionary in ++ let keyValPairs = buffer.enumerated().lazy.map { (String($0.1), $0.0) } + return Dictionary(uniqueKeysWithValues: keyValPairs) + } + let effect = try parser.parseEffectFromSource(for: function, params: paramToIdx) +@@ -358,7 +357,7 @@ final public class Function : CustomStringConvertible, HasShortDescription, Hash + return BridgedFunction.EffectInfo(argumentIndex: -1, isDerived: false, isEmpty: true, isValid: false) + }, + // getMemBehaviorFn +- { (f: BridgedFunction, observeRetains: Bool) -> swift.MemoryBehavior in ++ { (f: BridgedFunction, observeRetains: Bool) -> BridgedMemoryBehavior in + let e = f.function.getSideEffects() + return e.getMemBehavior(observeRetains: observeRetains) + } +@@ -393,7 +392,7 @@ extension OptionalBridgedFunction { + } + + public extension SideEffects.GlobalEffects { +- func getMemBehavior(observeRetains: Bool) -> swift.MemoryBehavior { ++ func getMemBehavior(observeRetains: Bool) -> BridgedMemoryBehavior { + if allocates || ownership.destroy || (ownership.copy && observeRetains) { + return .MayHaveSideEffects + } +diff --git a/swift/SwiftCompilerSources/Sources/SIL/GlobalVariable.swift b/swift/SwiftCompilerSources/Sources/SIL/GlobalVariable.swift +index e231757bdf3..e30843b7cd5 100644 +--- a/swift/SwiftCompilerSources/Sources/SIL/GlobalVariable.swift ++++ b/swift/SwiftCompilerSources/Sources/SIL/GlobalVariable.swift +@@ -19,8 +19,7 @@ final public class GlobalVariable : CustomStringConvertible, HasShortDescription + } + + public var description: String { +- let stdString = bridged.getDebugDescription() +- return String(_cxxString: stdString) ++ return String(taking: bridged.getDebugDescription()) + } + + public var shortDescription: String { name.string } +@@ -163,8 +162,10 @@ private extension TupleExtractInst { + let bi = tuple as? BuiltinInst, + bi.id == .USubOver, + bi.operands[1].value is IntegerLiteralInst, +- let overFlowFlag = bi.operands[2].value as? IntegerLiteralInst, +- overFlowFlag.value.isNullValue() { ++ let overflowLiteral = bi.operands[2].value as? IntegerLiteralInst, ++ let overflowValue = overflowLiteral.value, ++ overflowValue == 0 ++ { + return true + } + return false +diff --git a/swift/SwiftCompilerSources/Sources/SIL/Instruction.swift b/swift/SwiftCompilerSources/Sources/SIL/Instruction.swift +index 7c68b270147..9e26e780e8f 100644 +--- a/swift/SwiftCompilerSources/Sources/SIL/Instruction.swift ++++ b/swift/SwiftCompilerSources/Sources/SIL/Instruction.swift +@@ -34,8 +34,7 @@ public class Instruction : CustomStringConvertible, Hashable { + final public var parentFunction: Function { parentBlock.parentFunction } + + final public var description: String { +- let stdString = bridged.getDebugDescription() +- return String(_cxxString: stdString) ++ return String(taking: bridged.getDebugDescription()) + } + + final public var isDeleted: Bool { +@@ -288,7 +287,7 @@ final public class CondFailInst : Instruction, UnaryInstruction { + public var condition: Value { operand.value } + public override var mayTrap: Bool { true } + +- public var message: String { bridged.CondFailInst_getMessage().string } ++ public var message: StringRef { StringRef(bridged: bridged.CondFailInst_getMessage()) } + } + + final public class FixLifetimeInst : Instruction, UnaryInstruction {} +@@ -408,7 +407,7 @@ final public class LoadUnownedInst : SingleValueInstruction, UnaryInstruction {} + final public class LoadBorrowInst : SingleValueInstruction, UnaryInstruction {} + + final public class BuiltinInst : SingleValueInstruction { +- public typealias ID = swift.BuiltinValueKind ++ public typealias ID = BridgedInstruction.BuiltinValueKind + + public var id: ID { + return bridged.BuiltinInst_getID() +@@ -552,11 +551,16 @@ final public class AllocGlobalInst : Instruction { + } + + final public class IntegerLiteralInst : SingleValueInstruction { +- public var value: llvm.APInt { bridged.IntegerLiteralInst_getValue() } ++ public var value: Int? { ++ let optionalInt = bridged.IntegerLiteralInst_getValue() ++ if optionalInt.hasValue { ++ return optionalInt.value ++ } ++ return nil ++ } + } + + final public class FloatLiteralInst : SingleValueInstruction { +- public var value: llvm.APFloat { bridged.FloatLiteralInst_getValue() } + } + + final public class StringLiteralInst : SingleValueInstruction { +@@ -702,7 +706,7 @@ final public class BridgeObjectToRefInst : SingleValueInstruction, + final public class BridgeObjectToWordInst : SingleValueInstruction, + UnaryInstruction {} + +-public typealias AccessKind = swift.SILAccessKind ++public typealias AccessKind = BridgedInstruction.AccessKind + + + // TODO: add support for begin_unpaired_access +@@ -796,7 +800,7 @@ final public class ApplyInst : SingleValueInstruction, FullApplySite { + public var isNonThrowing: Bool { bridged.ApplyInst_getNonThrowing() } + public var isNonAsync: Bool { bridged.ApplyInst_getNonAsync() } + +- public typealias SpecializationInfo = UnsafePointer? ++ public typealias SpecializationInfo = BridgedGenericSpecializationInformation + + public var specializationInfo: SpecializationInfo { bridged.ApplyInst_getSpecializationInfo() } + } +diff --git a/swift/SwiftCompilerSources/Sources/SIL/Location.swift b/swift/SwiftCompilerSources/Sources/SIL/Location.swift +index 6940eb5b130..7b2553e053f 100644 +--- a/swift/SwiftCompilerSources/Sources/SIL/Location.swift ++++ b/swift/SwiftCompilerSources/Sources/SIL/Location.swift +@@ -13,11 +13,10 @@ + import SILBridging + + public struct Location: Equatable, CustomStringConvertible { +- let bridged: swift.SILDebugLocation ++ let bridged: BridgedLocation + + public var description: String { +- let stdString = bridged.getDebugDescription() +- return String(_cxxString: stdString) ++ return String(taking: bridged.getDebugDescription()) + } + + /// Keeps the debug scope but marks it as auto-generated. +@@ -39,6 +38,6 @@ public struct Location: Equatable, CustomStringConvertible { + } + + public static var artificialUnreachableLocation: Location { +- Location(bridged: swift.SILDebugLocation.getArtificialUnreachableLocation()) ++ Location(bridged: BridgedLocation.getArtificialUnreachableLocation()) + } + } +diff --git a/swift/SwiftCompilerSources/Sources/SIL/Registration.swift b/swift/SwiftCompilerSources/Sources/SIL/Registration.swift +index 2fa210ca99e..3d1fccd8c2f 100644 +--- a/swift/SwiftCompilerSources/Sources/SIL/Registration.swift ++++ b/swift/SwiftCompilerSources/Sources/SIL/Registration.swift +@@ -14,7 +14,7 @@ import Basic + import SILBridging + + private func register(_ cl: T.Type) { +- String(describing: cl)._withStringRef { nameStr in ++ String(describing: cl)._withBridgedStringRef { nameStr in + let metatype = unsafeBitCast(cl, to: SwiftMetatype.self) + registerBridgedClass(nameStr, metatype) + } +diff --git a/swift/SwiftCompilerSources/Sources/SIL/SubstitutionMap.swift b/swift/SwiftCompilerSources/Sources/SIL/SubstitutionMap.swift +index f618f31b8ff..4d62f6c081b 100644 +--- a/swift/SwiftCompilerSources/Sources/SIL/SubstitutionMap.swift ++++ b/swift/SwiftCompilerSources/Sources/SIL/SubstitutionMap.swift +@@ -13,17 +13,17 @@ + import SILBridging + + public struct SubstitutionMap { +- public let bridged: swift.SubstitutionMap ++ public let bridged: BridgedSubstitutionMap + +- public init(_ bridged: swift.SubstitutionMap) { ++ public init(_ bridged: BridgedSubstitutionMap) { + self.bridged = bridged + } + + public init() { +- self.bridged = swift.SubstitutionMap() ++ self.bridged = BridgedSubstitutionMap() + } + +- public var isEmpty: Bool { bridged.empty() } ++ public var isEmpty: Bool { bridged.isEmpty() } + + public var replacementTypes: OptionalTypeArray { + let types = BridgedTypeArray.fromReplacementTypes(bridged) +diff --git a/swift/SwiftCompilerSources/Sources/SIL/Type.swift b/swift/SwiftCompilerSources/Sources/SIL/Type.swift +index c7fdca56ee7..89bbad7cd30 100644 +--- a/swift/SwiftCompilerSources/Sources/SIL/Type.swift ++++ b/swift/SwiftCompilerSources/Sources/SIL/Type.swift +@@ -14,8 +14,8 @@ import Basic + import SILBridging + + public struct Type : CustomStringConvertible, NoReflectionChildren { +- public let bridged: swift.SILType +- ++ public let bridged: BridgedType ++ + public var isAddress: Bool { bridged.isAddress() } + public var isObject: Bool { !isAddress } + +@@ -23,12 +23,12 @@ public struct Type : CustomStringConvertible, NoReflectionChildren { + public var objectType: Type { bridged.getObjectType().type } + + public func isTrivial(in function: Function) -> Bool { +- return bridged.isTrivial(function.bridged.getFunction()) ++ return bridged.isTrivial(function.bridged) + } + + /// Returns true if the type is a trivial type and is and does not contain a Builtin.RawPointer. + public func isTrivialNonPointer(in function: Function) -> Bool { +- return !bridged.isNonTrivialOrContainsRawPointer(function.bridged.getFunction()) ++ return !bridged.isNonTrivialOrContainsRawPointer(function.bridged) + } + + /// True if this type is a value type (struct/enum) that requires deinitialization beyond +@@ -36,11 +36,11 @@ public struct Type : CustomStringConvertible, NoReflectionChildren { + public var isValueTypeWithDeinit: Bool { bridged.isValueTypeWithDeinit() } + + public func isLoadable(in function: Function) -> Bool { +- return bridged.isLoadable(function.bridged.getFunction()) ++ return bridged.isLoadable(function.bridged) + } + + public func isReferenceCounted(in function: Function) -> Bool { +- return bridged.isReferenceCounted(function.bridged.getFunction()) ++ return bridged.isReferenceCounted(function.bridged) + } + + public var isUnownedStorageType: Bool { +@@ -49,20 +49,20 @@ public struct Type : CustomStringConvertible, NoReflectionChildren { + + public var hasArchetype: Bool { bridged.hasArchetype() } + +- public var isNominal: Bool { bridged.getNominalOrBoundGenericNominal() != nil } +- public var isClass: Bool { bridged.getClassOrBoundGenericClass() != nil } +- public var isStruct: Bool { bridged.getStructOrBoundGenericStruct() != nil } ++ public var isNominal: Bool { bridged.isNominalOrBoundGenericNominal() } ++ public var isClass: Bool { bridged.isClassOrBoundGenericClass() } ++ public var isStruct: Bool { bridged.isStructOrBoundGenericStruct() } + public var isTuple: Bool { bridged.isTuple() } +- public var isEnum: Bool { bridged.getEnumOrBoundGenericEnum() != nil } ++ public var isEnum: Bool { bridged.isEnumOrBoundGenericEnum() } + public var isFunction: Bool { bridged.isFunction() } + public var isMetatype: Bool { bridged.isMetatype() } + public var isNoEscapeFunction: Bool { bridged.isNoEscapeFunction() } + +- public var canBeClass: swift.TypeTraitResult { bridged.canBeClass() } ++ public var canBeClass: BridgedType.TraitResult { bridged.canBeClass() } + + /// Can only be used if the type is in fact a nominal type (`isNominal` is true). + public var nominal: NominalTypeDecl { +- NominalTypeDecl(_bridged: BridgedNominalTypeDecl(decl: bridged.getNominalOrBoundGenericNominal())) ++ NominalTypeDecl(_bridged: bridged.getNominalOrBoundGenericNominal()) + } + + public var isOrContainsObjectiveCClass: Bool { bridged.isOrContainsObjectiveCClass() } +@@ -73,7 +73,7 @@ public struct Type : CustomStringConvertible, NoReflectionChildren { + public var builtinVectorElementType: Type { bridged.getBuiltinVectorElementType().type } + + public func isBuiltinInteger(withFixedWidth width: Int) -> Bool { +- bridged.isBuiltinFixedWidthInteger(UInt32(width)) ++ bridged.isBuiltinFixedWidthInteger(width) + } + + public func isExactSuperclass(of type: Type) -> Bool { +@@ -87,7 +87,7 @@ public struct Type : CustomStringConvertible, NoReflectionChildren { + } + + public func instanceTypeOfMetatype(in function: Function) -> Type { +- bridged.getInstanceTypeOfMetatype(function.bridged.getFunction()).type ++ bridged.getInstanceTypeOfMetatype(function.bridged).type + } + + public var isCalleeConsumedFunction: Bool { bridged.isCalleeConsumedFunction() } +@@ -95,20 +95,20 @@ public struct Type : CustomStringConvertible, NoReflectionChildren { + public var isMarkedAsImmortal: Bool { bridged.isMarkedAsImmortal() } + + public func getIndexOfEnumCase(withName name: String) -> Int? { +- let idx = name._withStringRef { ++ let idx = name._withBridgedStringRef { + bridged.getCaseIdxOfEnumType($0) + } + return idx >= 0 ? idx : nil + } + + public var description: String { +- String(_cxxString: bridged.getDebugDescription()) ++ String(taking: bridged.getDebugDescription()) + } + } + + extension Type: Equatable { + public static func ==(lhs: Type, rhs: Type) -> Bool { +- lhs.bridged == rhs.bridged ++ lhs.bridged.opaqueValue == rhs.bridged.opaqueValue + } + } + +@@ -160,11 +160,11 @@ public struct NominalFieldsArray : RandomAccessCollection, FormattedLikeArray { + public var endIndex: Int { Int(type.bridged.getNumNominalFields()) } + + public subscript(_ index: Int) -> Type { +- type.bridged.getFieldType(index, function.bridged.getFunction()).type ++ type.bridged.getFieldType(index, function.bridged).type + } + + public func getIndexOfField(withName name: String) -> Int? { +- let idx = name._withStringRef { ++ let idx = name._withBridgedStringRef { + type.bridged.getFieldIdxOfNominalType($0) + } + return idx >= 0 ? idx : nil +@@ -186,7 +186,7 @@ public struct TupleElementArray : RandomAccessCollection, FormattedLikeArray { + } + } + +-extension swift.SILType { ++extension BridgedType { + var type: Type { Type(bridged: self) } + var typeOrNil: Type? { isNull() ? nil : type } + } +diff --git a/swift/SwiftCompilerSources/Sources/SIL/VTable.swift b/swift/SwiftCompilerSources/Sources/SIL/VTable.swift +index 95a6da9d9d4..42e37b219d7 100644 +--- a/swift/SwiftCompilerSources/Sources/SIL/VTable.swift ++++ b/swift/SwiftCompilerSources/Sources/SIL/VTable.swift +@@ -23,8 +23,7 @@ public struct VTable : CustomStringConvertible, NoReflectionChildren { + public var function: Function { bridged.getImplementation().function } + + public var description: String { +- let stdString = bridged.getDebugDescription() +- return String(_cxxString: stdString) ++ return String(taking: bridged.getDebugDescription()) + } + } + +@@ -37,7 +36,7 @@ public struct VTable : CustomStringConvertible, NoReflectionChildren { + + public subscript(_ index: Int) -> Entry { + assert(index >= startIndex && index < endIndex) +- return Entry(bridged: BridgedVTableEntry(entry: base.entry + index)) ++ return Entry(bridged: base.advanceBy(index)) + } + } + +@@ -47,7 +46,6 @@ public struct VTable : CustomStringConvertible, NoReflectionChildren { + } + + public var description: String { +- let stdString = bridged.getDebugDescription() +- return String(_cxxString: stdString) ++ return String(taking: bridged.getDebugDescription()) + } + } +diff --git a/swift/SwiftCompilerSources/Sources/SIL/Value.swift b/swift/SwiftCompilerSources/Sources/SIL/Value.swift +index 320bfff10d3..f20c892fdfa 100644 +--- a/swift/SwiftCompilerSources/Sources/SIL/Value.swift ++++ b/swift/SwiftCompilerSources/Sources/SIL/Value.swift +@@ -88,8 +88,7 @@ public enum Ownership { + + extension Value { + public var description: String { +- let stdString = bridged.getDebugDescription() +- return String(_cxxString: stdString) ++ return String(taking: bridged.getDebugDescription()) + } + + public var uses: UseList { UseList(bridged.getFirstUse()) } +diff --git a/swift/SwiftCompilerSources/Sources/SIL/WitnessTable.swift b/swift/SwiftCompilerSources/Sources/SIL/WitnessTable.swift +index 4b4698f7618..f58277fb420 100644 +--- a/swift/SwiftCompilerSources/Sources/SIL/WitnessTable.swift ++++ b/swift/SwiftCompilerSources/Sources/SIL/WitnessTable.swift +@@ -20,8 +20,8 @@ public struct WitnessTable : CustomStringConvertible, NoReflectionChildren { + public struct Entry : CustomStringConvertible, NoReflectionChildren { + fileprivate let bridged: BridgedWitnessTableEntry + +- public typealias Kind = swift.SILWitnessTable.WitnessKind +- ++ public typealias Kind = BridgedWitnessTableEntry.Kind ++ + public var kind: Kind { + return bridged.getKind() + } +@@ -32,8 +32,7 @@ public struct WitnessTable : CustomStringConvertible, NoReflectionChildren { + } + + public var description: String { +- let stdString = bridged.getDebugDescription() +- return String(_cxxString: stdString) ++ return String(taking: bridged.getDebugDescription()) + } + } + +@@ -46,7 +45,7 @@ public struct WitnessTable : CustomStringConvertible, NoReflectionChildren { + + public subscript(_ index: Int) -> Entry { + assert(index >= startIndex && index < endIndex) +- return Entry(bridged: BridgedWitnessTableEntry(entry: base.entry + index)) ++ return Entry(bridged: base.advanceBy(index)) + } + } + +@@ -56,8 +55,7 @@ public struct WitnessTable : CustomStringConvertible, NoReflectionChildren { + } + + public var description: String { +- let stdString = bridged.getDebugDescription() +- return String(_cxxString: stdString) ++ return String(taking: bridged.getDebugDescription()) + } + } + +@@ -75,8 +73,7 @@ public struct DefaultWitnessTable : CustomStringConvertible, NoReflectionChildre + } + + public var description: String { +- let stdString = bridged.getDebugDescription() +- return String(_cxxString: stdString) ++ return String(taking: bridged.getDebugDescription()) + } + } + +diff --git a/swift/cmake/modules/SwiftSharedCMakeConfig.cmake b/swift/cmake/modules/SwiftSharedCMakeConfig.cmake +index 6679f404db2..4e7a033f40e 100644 +--- a/swift/cmake/modules/SwiftSharedCMakeConfig.cmake ++++ b/swift/cmake/modules/SwiftSharedCMakeConfig.cmake +@@ -351,6 +351,10 @@ macro(swift_common_cxx_warnings) + + # Disallow calls to objc_msgSend() with no function pointer cast. + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DOBJC_OLD_DISPATCH_PROTOTYPES=0") ++ ++ if(BRIDGING_MODE STREQUAL "PURE") ++ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DPURE_BRIDGING_MODE") ++ endif() + endmacro() + + # Like 'llvm_config()', but uses libraries from the selected build +diff --git a/swift/include/module.modulemap b/swift/include/module.modulemap +index 2e421469dd1..78fe887a51e 100644 +--- a/swift/include/module.modulemap ++++ b/swift/include/module.modulemap +@@ -1,7 +1,5 @@ + module BasicBridging { +- header "swift/Basic/BridgedSwiftObject.h" + header "swift/Basic/BasicBridging.h" +- header "swift/Basic/SourceLoc.h" + requires cplusplus + export * + } +@@ -11,17 +9,7 @@ module CBasicBridging { + } + + module ASTBridging { +- header "swift/AST/AnyFunctionRef.h" + header "swift/AST/ASTBridging.h" +- header "swift/AST/Builtins.h" +- header "swift/AST/DiagnosticEngine.h" +- header "swift/AST/DiagnosticConsumer.h" +- header "swift/AST/ForeignAsyncConvention.h" +- header "swift/AST/ForeignErrorConvention.h" +- header "swift/AST/SubstitutionMap.h" +- +- textual header "swift/AST/Builtins.def" +- + requires cplusplus + export * + } +@@ -32,7 +20,6 @@ module CASTBridging { + + module SILBridging { + header "swift/SIL/SILBridging.h" +- header "swift/SIL/SILLocation.h" + requires cplusplus + export * + } +diff --git a/swift/include/swift/AST/ASTBridging.h b/swift/include/swift/AST/ASTBridging.h +index d02968cf85c..3d26622667e 100644 +--- a/swift/include/swift/AST/ASTBridging.h ++++ b/swift/include/swift/AST/ASTBridging.h +@@ -13,15 +13,22 @@ + #ifndef SWIFT_AST_ASTBRIDGING_H + #define SWIFT_AST_ASTBRIDGING_H + +-#include "swift/AST/DiagnosticEngine.h" ++// Do not add other C++/llvm/swift header files here! ++// Function implementations should be placed into ASTBridging.cpp and required header files should be added there. ++// + #include "swift/Basic/BasicBridging.h" +-#include "swift/Basic/Compiler.h" +-#include "swift/Basic/Nullability.h" +-#include +-#include ++ ++#ifdef USED_IN_CPP_SOURCE ++#include "swift/AST/DiagnosticConsumer.h" ++#include "swift/AST/DiagnosticEngine.h" ++#endif + + SWIFT_BEGIN_NULLABILITY_ANNOTATIONS + ++namespace swift { ++ class DiagnosticArgument; ++} ++ + //===----------------------------------------------------------------------===// + // Diagnostic Engine + //===----------------------------------------------------------------------===// +@@ -33,24 +40,56 @@ typedef enum ENUM_EXTENSIBILITY_ATTR(open) BridgedDiagID : uint32_t { + #include "swift/AST/DiagnosticsAll.def" + } BridgedDiagID; + ++// Must match the definition of BridgedDiagnosticEngine in CASTBridging.h. + typedef struct { + void * _Nonnull object; + } BridgedDiagnosticEngine; + +-typedef struct { ++struct BridgedOptionalDiagnosticEngine { + void *_Nullable object; +-} BridgedOptionalDiagnosticEngine; ++}; ++ ++class BridgedDiagnosticArgument { ++ int64_t storage[3]; ++ ++public: ++#ifdef USED_IN_CPP_SOURCE ++ BridgedDiagnosticArgument(const swift::DiagnosticArgument &arg) { ++ *reinterpret_cast(&storage) = arg; ++ } ++ const swift::DiagnosticArgument &get() const { ++ return *reinterpret_cast(&storage); ++ } ++#endif ++ ++ BridgedDiagnosticArgument(SwiftInt i); ++ BridgedDiagnosticArgument(BridgedStringRef s); ++}; ++ ++class BridgedDiagnosticFixIt { ++ int64_t storage[7]; ++ ++public: ++#ifdef USED_IN_CPP_SOURCE ++ BridgedDiagnosticFixIt(const swift::DiagnosticInfo::FixIt &fixit){ ++ *reinterpret_cast(&storage) = fixit; ++ } ++ const swift::DiagnosticInfo::FixIt &get() const { ++ return *reinterpret_cast(&storage); ++ } ++#endif ++ ++ BridgedDiagnosticFixIt(BridgedSourceLoc start, uint32_t length, BridgedStringRef text); ++}; + + // FIXME: Can we bridge InFlightDiagnostic? +-void DiagnosticEngine_diagnose(BridgedDiagnosticEngine, swift::SourceLoc loc, ++void DiagnosticEngine_diagnose(BridgedDiagnosticEngine, BridgedSourceLoc loc, + BridgedDiagID diagID, BridgedArrayRef arguments, +- swift::CharSourceRange highlight, ++ BridgedSourceLoc highlightStart, uint32_t hightlightLength, + BridgedArrayRef fixIts); + + bool DiagnosticEngine_hadAnyError(BridgedDiagnosticEngine); + +-using ArrayRefOfDiagnosticArgument = llvm::ArrayRef; +- + SWIFT_END_NULLABILITY_ANNOTATIONS + + #endif // SWIFT_AST_ASTBRIDGING_H +diff --git a/swift/include/swift/AST/Decl.h b/swift/include/swift/AST/Decl.h +index 80330b15548..e6ba3651e6f 100644 +--- a/swift/include/swift/AST/Decl.h ++++ b/swift/include/swift/AST/Decl.h +@@ -26,6 +26,8 @@ + #include "swift/AST/DefaultArgumentKind.h" + #include "swift/AST/DiagnosticConsumer.h" + #include "swift/AST/DiagnosticEngine.h" ++#include "swift/AST/ForeignAsyncConvention.h" ++#include "swift/AST/ForeignErrorConvention.h" + #include "swift/AST/FreestandingMacroExpansion.h" + #include "swift/AST/GenericParamKey.h" + #include "swift/AST/IfConfigClause.h" +@@ -72,8 +74,6 @@ namespace swift { + struct ExternalSourceLocs; + class CaptureListExpr; + class DeclRefExpr; +- class ForeignAsyncConvention; +- class ForeignErrorConvention; + class LiteralExpr; + class BraceStmt; + class DeclAttributes; +diff --git a/swift/include/swift/Basic/BasicBridging.h b/swift/include/swift/Basic/BasicBridging.h +index f11083e83a0..8988bb75eb3 100644 +--- a/swift/include/swift/Basic/BasicBridging.h ++++ b/swift/include/swift/Basic/BasicBridging.h +@@ -13,31 +13,100 @@ + #ifndef SWIFT_BASIC_BASICBRIDGING_H + #define SWIFT_BASIC_BASICBRIDGING_H + ++#if !defined(COMPILED_WITH_SWIFT) || !defined(PURE_BRIDGING_MODE) ++#define USED_IN_CPP_SOURCE ++#endif ++ ++// Do not add other C++/llvm/swift header files here! ++// Function implementations should be placed into BasicBridging.cpp and required header files should be added there. ++// ++#include "swift/Basic/BridgedSwiftObject.h" ++#include "swift/Basic/Compiler.h" ++ ++#include ++#include ++#ifdef USED_IN_CPP_SOURCE + // Workaround to avoid a compiler error because `cas::ObjectRef` is not defined + // when including VirtualFileSystem.h + #include + #include "llvm/CAS/CASReference.h" + +-#include "swift/Basic/BridgedSwiftObject.h" +-#include "swift/Basic/Nullability.h" +-#include "swift/Basic/SourceLoc.h" +-#include ++#include "llvm/ADT/StringRef.h" ++#include ++#endif ++ ++#ifdef PURE_BRIDGING_MODE ++// In PURE_BRIDGING_MODE, briding functions are not inlined ++#define BRIDGED_INLINE ++#else ++#define BRIDGED_INLINE inline ++#endif + + SWIFT_BEGIN_NULLABILITY_ANNOTATIONS + + typedef intptr_t SwiftInt; + typedef uintptr_t SwiftUInt; + +-typedef struct { +- const void * _Nullable data; +- size_t numElements; +-} BridgedArrayRef; +- +-typedef struct { ++struct BridgedOStream { + void * _Nonnull streamAddr; +-} BridgedOStream; ++}; + +-void OStream_write(BridgedOStream os, llvm::StringRef str); ++class BridgedStringRef { ++ const char * _Nonnull data; ++ size_t length; ++ ++public: ++#ifdef USED_IN_CPP_SOURCE ++ BridgedStringRef(llvm::StringRef sref) : data(sref.data()), length(sref.size()) {} ++ ++ llvm::StringRef get() const { return llvm::StringRef(data, length); } ++#endif ++ ++ BridgedStringRef(const char * _Nullable data, size_t length) ++ : data(data), length(length) {} ++ ++ SWIFT_IMPORT_UNSAFE const uint8_t * _Nonnull uintData() const { ++ return (const uint8_t * _Nonnull)data; ++ } ++ SwiftInt size() const { return (SwiftInt)length; } ++ void write(BridgedOStream os) const; ++}; ++ ++class BridgedOwnedString { ++ char * _Nonnull data; ++ size_t length; ++ ++public: ++#ifdef USED_IN_CPP_SOURCE ++ BridgedOwnedString(const std::string &stringToCopy); ++#endif ++ ++ SWIFT_IMPORT_UNSAFE const uint8_t * _Nonnull uintData() const { ++ return (const uint8_t * _Nonnull)(data ? data : ""); ++ } ++ SwiftInt size() const { return (SwiftInt)length; } ++ void destroy() const; ++}; ++ ++class BridgedSourceLoc { ++ const void * _Nullable opaquePointer; ++public: ++ BridgedSourceLoc() : opaquePointer(nullptr) {} ++ BridgedSourceLoc(const void * _Nullable loc) : opaquePointer(loc) {} ++ ++ bool isValid() const { return opaquePointer != nullptr; } ++ SWIFT_IMPORT_UNSAFE const uint8_t * _Nullable uint8Pointer() const { ++ return (const uint8_t * _Nullable)opaquePointer; ++ } ++ const char * _Nullable getLoc() const { ++ return (const char * _Nullable)opaquePointer; ++ } ++}; ++ ++struct BridgedArrayRef { ++ const void * _Nullable data; ++ size_t numElements; ++}; + + SWIFT_END_NULLABILITY_ANNOTATIONS + +diff --git a/swift/include/swift/SIL/SILBridging.h b/swift/include/swift/SIL/SILBridging.h +index f7492f25592..1dd794aeacd 100644 +--- a/swift/include/swift/SIL/SILBridging.h ++++ b/swift/include/swift/SIL/SILBridging.h +@@ -13,24 +13,18 @@ + #ifndef SWIFT_SIL_SILBRIDGING_H + #define SWIFT_SIL_SILBRIDGING_H + +-#include "swift/AST/Builtins.h" +-#include "swift/AST/Decl.h" +-#include "swift/AST/SubstitutionMap.h" ++// Do not add other C++/llvm/swift header files here! ++// Function implementations should be placed into SILBridgingImpl.h or SILBridging.cpp and ++// required header files should be added there. ++// + #include "swift/Basic/BasicBridging.h" +-#include "swift/Basic/BridgedSwiftObject.h" +-#include "swift/Basic/Nullability.h" +-#include "swift/SIL/ApplySite.h" ++ ++#ifdef USED_IN_CPP_SOURCE ++#include "llvm/ADT/ArrayRef.h" + #include "swift/SIL/SILBuilder.h" +-#include "swift/SIL/SILDefaultWitnessTable.h" +-#include "swift/SIL/SILFunctionConventions.h" + #include "swift/SIL/SILInstruction.h" +-#include "swift/SIL/SILLocation.h" +-#include "swift/SIL/SILModule.h" +-#include "swift/SIL/SILVTable.h" + #include "swift/SIL/SILWitnessTable.h" +-#include +-#include +-#include ++#endif + + SWIFT_BEGIN_NULLABILITY_ANNOTATIONS + +@@ -38,11 +32,100 @@ struct BridgedInstruction; + struct OptionalBridgedInstruction; + struct OptionalBridgedOperand; + struct OptionalBridgedSuccessor; ++struct BridgedFunction; + struct BridgedBasicBlock; + struct BridgedSuccessorArray; + struct OptionalBridgedBasicBlock; ++struct BridgedNominalTypeDecl; ++ ++namespace swift { ++class ValueBase; ++class Operand; ++class SILFunction; ++class SILBasicBlock; ++class SILSuccessor; ++class SILGlobalVariable; ++class SILInstruction; ++class SILArgument; ++class MultipleValueInstructionResult; ++class SILVTableEntry; ++class SILVTable; ++class SILWitnessTable; ++class SILDefaultWitnessTable; ++class NominalTypeDecl; ++class SwiftPassInvocation; ++class GenericSpecializationInformation; ++} ++ ++void registerBridgedClass(BridgedStringRef className, SwiftMetatype metatype); ++ ++struct BridgedType { ++ void * _Nullable opaqueValue; ++ ++ enum class MetatypeRepresentation { ++ Thin, ++ Thick, ++ ObjC ++ }; ++ ++ enum class TraitResult { ++ IsNot, ++ CanBe, ++ Is ++ }; ++ ++#ifdef USED_IN_CPP_SOURCE ++ BridgedType(swift::SILType t) : opaqueValue(t.getOpaqueValue()) {} ++ ++ swift::SILType get() const { ++ return swift::SILType::getFromOpaqueValue(opaqueValue); ++ } ++#endif + +-void registerBridgedClass(llvm::StringRef className, SwiftMetatype metatype); ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedOwnedString getDebugDescription() const; ++ BRIDGED_INLINE bool isNull() const; ++ BRIDGED_INLINE bool isAddress() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getAddressType() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getObjectType() const; ++ BRIDGED_INLINE bool isTrivial(BridgedFunction f) const; ++ BRIDGED_INLINE bool isNonTrivialOrContainsRawPointer(BridgedFunction f) const; ++ BRIDGED_INLINE bool isValueTypeWithDeinit() const; ++ BRIDGED_INLINE bool isLoadable(BridgedFunction f) const; ++ BRIDGED_INLINE bool isReferenceCounted(BridgedFunction f) const; ++ BRIDGED_INLINE bool isUnownedStorageType() const; ++ BRIDGED_INLINE bool hasArchetype() const; ++ BRIDGED_INLINE bool isNominalOrBoundGenericNominal() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedNominalTypeDecl getNominalOrBoundGenericNominal() const; ++ BRIDGED_INLINE bool isClassOrBoundGenericClass() const; ++ BRIDGED_INLINE bool isStructOrBoundGenericStruct() const; ++ BRIDGED_INLINE bool isTuple() const; ++ BRIDGED_INLINE bool isEnumOrBoundGenericEnum() const; ++ BRIDGED_INLINE bool isFunction() const; ++ BRIDGED_INLINE bool isMetatype() const; ++ BRIDGED_INLINE bool isNoEscapeFunction() const; ++ // BRIDGED_INLINE bool isAsyncFunction() const; ++ BRIDGED_INLINE TraitResult canBeClass() const; ++ BRIDGED_INLINE bool isMoveOnly() const; ++ BRIDGED_INLINE bool isOrContainsObjectiveCClass() const; ++ BRIDGED_INLINE bool isBuiltinInteger() const; ++ BRIDGED_INLINE bool isBuiltinFloat() const; ++ BRIDGED_INLINE bool isBuiltinVector() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getBuiltinVectorElementType() const; ++ BRIDGED_INLINE bool isBuiltinFixedWidthInteger(SwiftInt width) const; ++ BRIDGED_INLINE bool isExactSuperclassOf(BridgedType t) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getInstanceTypeOfMetatype(BridgedFunction f) const; ++ BRIDGED_INLINE bool isDynamicSelfMetatype() const; ++ // BRIDGED_INLINE MetatypeRepresentation getRepresentationOfMetatype(BridgedFunction f) const; ++ BRIDGED_INLINE bool isCalleeConsumedFunction() const; ++ BRIDGED_INLINE bool isMarkedAsImmortal() const; ++ BRIDGED_INLINE SwiftInt getCaseIdxOfEnumType(BridgedStringRef name) const; ++ BRIDGED_INLINE SwiftInt getNumNominalFields() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getFieldType(SwiftInt idx, BridgedFunction f) const; ++ BRIDGED_INLINE SwiftInt getFieldIdxOfNominalType(BridgedStringRef name) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef getFieldName(SwiftInt idx) const; ++ BRIDGED_INLINE SwiftInt getNumTupleElements() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getTupleElementType(SwiftInt idx) const; ++}; + + struct BridgedValue { + SwiftObject obj; +@@ -63,49 +145,31 @@ struct BridgedValue { + None + }; + +- Kind getKind() const; +- +- swift::SILValue getSILValue() const { return static_cast(obj); } +- +- std::string getDebugDescription() const; +- +- SWIFT_IMPORT_UNSAFE +- inline OptionalBridgedOperand getFirstUse() const; +- +- SWIFT_IMPORT_UNSAFE +- swift::SILType getType() const { return getSILValue()->getType(); } +- +- Ownership getOwnership() const { +- switch (getSILValue()->getOwnershipKind()) { +- case swift::OwnershipKind::Any: +- llvm_unreachable("Invalid ownership for value"); +- case swift::OwnershipKind::Unowned: return Ownership::Unowned; +- case swift::OwnershipKind::Owned: return Ownership::Owned; +- case swift::OwnershipKind::Guaranteed: return Ownership::Guaranteed; +- case swift::OwnershipKind::None: return Ownership::None; ++#ifdef USED_IN_CPP_SOURCE ++ static swift::ValueOwnershipKind castToOwnership(BridgedValue::Ownership ownership) { ++ switch (ownership) { ++ case BridgedValue::Ownership::Unowned: return swift::OwnershipKind::Unowned; ++ case BridgedValue::Ownership::Owned: return swift::OwnershipKind::Owned; ++ case BridgedValue::Ownership::Guaranteed: return swift::OwnershipKind::Guaranteed; ++ case BridgedValue::Ownership::None: return swift::OwnershipKind::None; + } + } ++#endif ++ ++ Kind getKind() const; ++ BRIDGED_INLINE swift::ValueBase * _Nonnull getSILValue() const; ++ SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedOperand getFirstUse() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getType() const; ++ BRIDGED_INLINE Ownership getOwnership() const; + }; + + struct OptionalBridgedValue { + OptionalSwiftObject obj; + +- swift::SILValue getSILValue() const { +- if (obj) +- return static_cast(obj); +- return swift::SILValue(); +- } ++ BRIDGED_INLINE swift::ValueBase * _Nullable getSILValue() const; + }; + +-inline swift::ValueOwnershipKind castToOwnership(BridgedValue::Ownership ownership) { +- switch (ownership) { +- case BridgedValue::Ownership::Unowned: return swift::OwnershipKind::Unowned; +- case BridgedValue::Ownership::Owned: return swift::OwnershipKind::Owned; +- case BridgedValue::Ownership::Guaranteed: return swift::OwnershipKind::Guaranteed; +- case BridgedValue::Ownership::None: return swift::OwnershipKind::None; +- } +-} +- + // This is the layout of a class existential. + struct BridgeValueExistential { + BridgedValue value; +@@ -116,33 +179,31 @@ struct BridgedValueArray { + const BridgeValueExistential * _Nullable base; + size_t count; + ++#ifdef USED_IN_CPP_SOURCE + llvm::ArrayRef getValues(llvm::SmallVectorImpl &storage); ++#endif + }; + + struct BridgedOperand { + swift::Operand * _Nonnull op; + +- bool isTypeDependent() const { return op->isTypeDependent(); } +- +- SWIFT_IMPORT_UNSAFE +- inline OptionalBridgedOperand getNextUse() const; +- +- SWIFT_IMPORT_UNSAFE +- BridgedValue getValue() const { return {op->get()}; } +- +- SWIFT_IMPORT_UNSAFE +- inline BridgedInstruction getUser() const; ++ BRIDGED_INLINE bool isTypeDependent() const; ++ BRIDGED_INLINE bool isLifetimeEnding() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedOperand getNextUse() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedValue getValue() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction getUser() const; ++ //BRIDGED_INLINE OperandOwnership getOperandOwnership() const; + }; + + struct OptionalBridgedOperand { + swift::Operand * _Nullable op; + + // Assumes that `op` is not null. +- SWIFT_IMPORT_UNSAFE +- BridgedOperand advancedBy(SwiftInt index) const { return {op + index}; } ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE ++ BridgedOperand advancedBy(SwiftInt index) const; + + // Assumes that `op` is not null. +- SwiftInt distanceTo(BridgedOperand element) const { return element.op - op; } ++ BRIDGED_INLINE SwiftInt distanceTo(BridgedOperand element) const; + }; + + struct BridgedOperandArray { +@@ -154,153 +215,81 @@ struct BridgedOperandArray { + // Currently it's not possible to switch over `SILArgumentConvention::ConventionType`, + // because it's not a class enum. + enum class BridgedArgumentConvention { +- Indirect_In = swift::SILArgumentConvention::Indirect_In, +- Indirect_In_Guaranteed = swift::SILArgumentConvention::Indirect_In_Guaranteed, +- Indirect_Inout = swift::SILArgumentConvention::Indirect_Inout, +- Indirect_InoutAliasable = swift::SILArgumentConvention::Indirect_InoutAliasable, +- Indirect_Out = swift::SILArgumentConvention::Indirect_Out, +- Direct_Owned = swift::SILArgumentConvention::Direct_Owned, +- Direct_Unowned = swift::SILArgumentConvention::Direct_Unowned, +- Direct_Guaranteed = swift::SILArgumentConvention::Direct_Guaranteed, +- Pack_Owned = swift::SILArgumentConvention::Pack_Owned, +- Pack_Inout = swift::SILArgumentConvention::Pack_Inout, +- Pack_Guaranteed = swift::SILArgumentConvention::Pack_Guaranteed, +- Pack_Out = swift::SILArgumentConvention::Pack_Out ++ Indirect_In, ++ Indirect_In_Guaranteed, ++ Indirect_Inout, ++ Indirect_InoutAliasable, ++ Indirect_Out, ++ Direct_Owned, ++ Direct_Unowned, ++ Direct_Guaranteed, ++ Pack_Owned, ++ Pack_Inout, ++ Pack_Guaranteed, ++ Pack_Out ++}; ++ ++enum class BridgedMemoryBehavior { ++ None, ++ MayRead, ++ MayWrite, ++ MayReadWrite, ++ MayHaveSideEffects + }; + +-inline BridgedArgumentConvention castToArgumentConvention(swift::SILArgumentConvention convention) { +- return static_cast(convention.Value); +-} +- + struct BridgedFunction { + SwiftObject obj; + +- SWIFT_IMPORT_UNSAFE +- swift::SILFunction * _Nonnull getFunction() const { +- return static_cast(obj); +- } +- +- SWIFT_IMPORT_UNSAFE +- llvm::StringRef getName() const { return getFunction()->getName(); } +- +- std::string getDebugDescription() const; +- +- bool hasOwnership() const { return getFunction()->hasOwnership(); } +- +- SWIFT_IMPORT_UNSAFE +- inline OptionalBridgedBasicBlock getFirstBlock() const; +- +- SWIFT_IMPORT_UNSAFE +- inline OptionalBridgedBasicBlock getLastBlock() const; +- +- SwiftInt getNumIndirectFormalResults() const { +- return (SwiftInt)getFunction()->getLoweredFunctionType()->getNumIndirectFormalResults(); +- } +- +- SwiftInt getNumParameters() const { +- return (SwiftInt)getFunction()->getLoweredFunctionType()->getNumParameters(); +- } +- +- SwiftInt getSelfArgumentIndex() const { +- swift::SILFunctionConventions conv(getFunction()->getConventionsInContext()); +- swift::CanSILFunctionType fTy = getFunction()->getLoweredFunctionType(); +- if (!fTy->hasSelfParam()) +- return -1; +- return conv.getNumParameters() + conv.getNumIndirectSILResults() - 1; +- } +- +- SwiftInt getNumSILArguments() const { +- return swift::SILFunctionConventions(getFunction()->getConventionsInContext()).getNumSILArguments(); +- } +- +- swift::SILType getSILArgumentType(SwiftInt idx) const { +- swift::SILFunctionConventions conv(getFunction()->getConventionsInContext()); +- return conv.getSILArgumentType(idx, getFunction()->getTypeExpansionContext()); +- } +- +- BridgedArgumentConvention getSILArgumentConvention(SwiftInt idx) const { +- swift::SILFunctionConventions conv(getFunction()->getConventionsInContext()); +- return castToArgumentConvention(conv.getSILArgumentConvention(idx)); +- } +- +- swift::SILType getSILResultType() const { +- swift::SILFunctionConventions conv(getFunction()->getConventionsInContext()); +- return conv.getSILResultType(getFunction()->getTypeExpansionContext()); +- } +- +- bool isSwift51RuntimeAvailable() const { +- if (getFunction()->getResilienceExpansion() != swift::ResilienceExpansion::Maximal) +- return false; +- +- swift::ASTContext &ctxt = getFunction()->getModule().getASTContext(); +- return swift::AvailabilityContext::forDeploymentTarget(ctxt).isContainedIn(ctxt.getSwift51Availability()); +- } +- +- bool isPossiblyUsedExternally() const { +- return getFunction()->isPossiblyUsedExternally(); +- } +- +- bool isAvailableExternally() const { +- return getFunction()->isAvailableExternally(); +- } +- +- bool isTransparent() const { +- return getFunction()->isTransparent() == swift::IsTransparent; +- } +- +- bool isAsync() const { +- return getFunction()->isAsync(); +- } +- +- bool isGlobalInitFunction() const { +- return getFunction()->isGlobalInit(); +- } +- +- bool isGlobalInitOnceFunction() const { +- return getFunction()->isGlobalInitOnceFunction(); +- } +- +- bool isGenericFunction() const { +- return getFunction()->getGenericSignature().isNull(); +- } +- +- bool hasSemanticsAttr(llvm::StringRef attrName) const { +- return getFunction()->hasSemanticsAttr(attrName); +- } +- +- swift::EffectsKind getEffectAttribute() const { +- return getFunction()->getEffectsKind(); +- } ++ enum class EffectsKind { ++ ReadNone, ++ ReadOnly, ++ ReleaseNone, ++ ReadWrite, ++ Unspecified, ++ Custom ++ }; + +- swift::PerformanceConstraints getPerformanceConstraints() const { +- return getFunction()->getPerfConstraints(); +- } ++ enum class PerformanceConstraints { ++ None = 0, ++ NoAllocation = 1, ++ NoLocks = 2 ++ }; + + enum class InlineStrategy { +- InlineDefault = swift::InlineDefault, +- NoInline = swift::NoInline, +- AlwaysInline = swift::AlwaysInline ++ InlineDefault, ++ NoInline, ++ AlwaysInline + }; + +- InlineStrategy getInlineStrategy() const { +- return (InlineStrategy)getFunction()->getInlineStrategy(); +- } +- +- bool isSerialized() const { +- return getFunction()->isSerialized(); +- } +- +- bool hasValidLinkageForFragileRef() const { +- return getFunction()->hasValidLinkageForFragileRef(); +- } +- +- bool needsStackProtection() const { +- return getFunction()->needsStackProtection(); +- } +- +- void setNeedStackProtection(bool needSP) const { +- getFunction()->setNeedStackProtection(needSP); +- } ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE swift::SILFunction * _Nonnull getFunction() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef getName() const; ++ SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; ++ BRIDGED_INLINE bool hasOwnership() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedBasicBlock getFirstBlock() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedBasicBlock getLastBlock() const; ++ BRIDGED_INLINE SwiftInt getNumIndirectFormalResults() const; ++ BRIDGED_INLINE SwiftInt getNumParameters() const; ++ BRIDGED_INLINE SwiftInt getSelfArgumentIndex() const; ++ BRIDGED_INLINE SwiftInt getNumSILArguments() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getSILArgumentType(SwiftInt idx) const; ++ BRIDGED_INLINE BridgedArgumentConvention getSILArgumentConvention(SwiftInt idx) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getSILResultType() const; ++ BRIDGED_INLINE bool isSwift51RuntimeAvailable() const; ++ BRIDGED_INLINE bool isPossiblyUsedExternally() const; ++ BRIDGED_INLINE bool isAvailableExternally() const; ++ BRIDGED_INLINE bool isTransparent() const; ++ BRIDGED_INLINE bool isAsync() const; ++ BRIDGED_INLINE bool isGlobalInitFunction() const; ++ BRIDGED_INLINE bool isGlobalInitOnceFunction() const; ++ BRIDGED_INLINE bool isGenericFunction() const; ++ BRIDGED_INLINE bool hasSemanticsAttr(BridgedStringRef attrName) const; ++ BRIDGED_INLINE EffectsKind getEffectAttribute() const; ++ BRIDGED_INLINE PerformanceConstraints getPerformanceConstraints() const; ++ BRIDGED_INLINE InlineStrategy getInlineStrategy() const; ++ BRIDGED_INLINE bool isSerialized() const; ++ BRIDGED_INLINE bool hasValidLinkageForFragileRef() const; ++ BRIDGED_INLINE bool needsStackProtection() const; ++ BRIDGED_INLINE void setNeedStackProtection(bool needSP) const; + + enum class ParseEffectsMode { + argumentEffectsFromSource, +@@ -324,12 +313,12 @@ struct BridgedFunction { + typedef void (* _Nonnull RegisterFn)(BridgedFunction f, void * _Nonnull data, SwiftInt size); + typedef void (* _Nonnull WriteFn)(BridgedFunction, BridgedOStream, SwiftInt); + typedef ParsingError (*_Nonnull ParseFn)(BridgedFunction, +- llvm::StringRef, ++ BridgedStringRef, + ParseEffectsMode, SwiftInt, + BridgedArrayRef); + typedef SwiftInt (* _Nonnull CopyEffectsFn)(BridgedFunction, BridgedFunction); + typedef EffectInfo (* _Nonnull GetEffectInfoFn)(BridgedFunction, SwiftInt); +- typedef swift::MemoryBehavior (* _Nonnull GetMemBehaviorFn)(BridgedFunction, bool); ++ typedef BridgedMemoryBehavior (* _Nonnull GetMemBehaviorFn)(BridgedFunction, bool); + + static void registerBridging(SwiftMetatype metatype, + RegisterFn initFn, RegisterFn destroyFn, +@@ -347,34 +336,15 @@ struct BridgedGlobalVar { + SwiftObject obj; + + BridgedGlobalVar(SwiftObject obj) : obj(obj) {} +- +- SWIFT_IMPORT_UNSAFE +- swift::SILGlobalVariable * _Nonnull getGlobal() const { +- return static_cast(obj); +- } +- +- std::string getDebugDescription() const; +- +- SWIFT_IMPORT_UNSAFE +- llvm::StringRef getName() const { return getGlobal()->getName(); } +- +- bool isLet() const { return getGlobal()->isLet(); } +- +- void setLet(bool value) const { getGlobal()->setLet(value); } +- +- bool isPossiblyUsedExternally() const { +- return getGlobal()->isPossiblyUsedExternally(); +- } +- +- bool isAvailableExternally() const { +- return swift::isAvailableExternally(getGlobal()->getLinkage()); +- } +- +- SWIFT_IMPORT_UNSAFE +- inline OptionalBridgedInstruction getFirstStaticInitInst() const; +- ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE swift::SILGlobalVariable * _Nonnull getGlobal() const; ++ SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef getName() const; ++ BRIDGED_INLINE bool isLet() const; ++ BRIDGED_INLINE void setLet(bool value) const; ++ BRIDGED_INLINE bool isPossiblyUsedExternally() const; ++ BRIDGED_INLINE bool isAvailableExternally() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedInstruction getFirstStaticInitInst() const; + bool canBeInitializedStatically() const; +- + bool mustBeInitializedStatically() const; + }; + +@@ -385,410 +355,137 @@ struct OptionalBridgedGlobalVar { + struct BridgedMultiValueResult { + SwiftObject obj; + +- swift::MultipleValueInstructionResult * _Nonnull getMVResult() const { ++#ifdef USED_IN_CPP_SOURCE ++ swift::MultipleValueInstructionResult * _Nonnull get() const { + return static_cast(obj); + } ++#endif + +- SWIFT_IMPORT_UNSAFE +- inline BridgedInstruction getParent() const; +- +- SwiftInt getIndex() const { +- return (SwiftInt)getMVResult()->getIndex(); +- } ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction getParent() const; ++ BRIDGED_INLINE SwiftInt getIndex() const; + }; + +-struct OptionalBridgedInstruction { +- OptionalSwiftObject obj; +- +- OptionalBridgedInstruction() : obj(nullptr) {} ++struct BridgedSubstitutionMap { ++ uint64_t storage[1]; + +- OptionalBridgedInstruction(OptionalSwiftObject obj) : obj(obj) {} +- +- swift::SILInstruction * _Nullable getInst() const { +- if (!obj) +- return nullptr; +- return llvm::cast(static_cast(obj)->castToInstruction()); ++#ifdef USED_IN_CPP_SOURCE ++ BridgedSubstitutionMap(swift::SubstitutionMap map) { ++ *reinterpret_cast(&storage) = map; ++ } ++ swift::SubstitutionMap get() const { ++ return *reinterpret_cast(&storage); + } ++#endif ++ ++ BRIDGED_INLINE BridgedSubstitutionMap(); ++ BRIDGED_INLINE bool isEmpty() const; + }; + + struct BridgedTypeArray { +- llvm::ArrayRef typeArray; ++ BridgedArrayRef typeArray; + +- SWIFT_IMPORT_UNSAFE +- static BridgedTypeArray fromReplacementTypes(swift::SubstitutionMap substMap) { +- return {substMap.getReplacementTypes()}; +- } ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE ++ static BridgedTypeArray fromReplacementTypes(BridgedSubstitutionMap substMap); + +- SwiftInt getCount() const { return SwiftInt(typeArray.size()); } ++ SwiftInt getCount() const { return SwiftInt(typeArray.numElements); } + +- SWIFT_IMPORT_UNSAFE +- swift::SILType getAt(SwiftInt index) const { +- auto ty = typeArray[index]->getCanonicalType(); +- if (ty->isLegalSILType()) +- return swift::SILType::getPrimitiveObjectType(ty); +- return swift::SILType(); +- } ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE ++ BridgedType getAt(SwiftInt index) const; + }; + + struct BridgedSILTypeArray { +- llvm::ArrayRef typeArray; ++ BridgedArrayRef typeArray; + +- SwiftInt getCount() const { return SwiftInt(typeArray.size()); } ++ SwiftInt getCount() const { return SwiftInt(typeArray.numElements); } + +- SWIFT_IMPORT_UNSAFE +- swift::SILType getAt(SwiftInt index) const { return typeArray[index]; } ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE ++ BridgedType getAt(SwiftInt index) const; + }; + +-struct BridgedInstruction { +- SwiftObject obj; +- +- BridgedInstruction(SwiftObject obj) : obj(obj) {} +- +- template I *_Nonnull getAs() const { +- return llvm::cast(static_cast(obj)->castToInstruction()); +- } +- +- swift::SILInstruction * _Nonnull getInst() const { return getAs(); } +- +- std::string getDebugDescription() const; +- +- SWIFT_IMPORT_UNSAFE +- OptionalBridgedInstruction getNext() const { +- auto iter = std::next(getInst()->getIterator()); +- if (iter == getInst()->getParent()->end()) +- return {nullptr}; +- return {iter->asSILNode()}; +- } +- +- SWIFT_IMPORT_UNSAFE +- OptionalBridgedInstruction getPrevious() const { +- auto iter = std::next(getInst()->getReverseIterator()); +- if (iter == getInst()->getParent()->rend()) +- return {nullptr}; +- return {iter->asSILNode()}; +- } +- +- SWIFT_IMPORT_UNSAFE +- inline BridgedBasicBlock getParent() const; +- +- SWIFT_IMPORT_UNSAFE +- inline BridgedInstruction getLastInstOfParent() const; ++struct BridgedLocation { ++ uint64_t storage[3]; + +- bool isDeleted() const { +- return getInst()->isDeleted(); ++#ifdef USED_IN_CPP_SOURCE ++ BridgedLocation(const swift::SILDebugLocation &loc) { ++ *reinterpret_cast(&storage) = loc; + } + +- SWIFT_IMPORT_UNSAFE +- BridgedOperandArray getOperands() const { +- auto operands = getInst()->getAllOperands(); +- return {{operands.data()}, (SwiftInt)operands.size()}; ++ const swift::SILDebugLocation &getLoc() const { ++ return *reinterpret_cast(&storage); + } ++#endif + +- void setOperand(SwiftInt index, BridgedValue value) const { +- getInst()->setOperand((unsigned)index, value.getSILValue()); +- } ++ SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedLocation getAutogeneratedLocation() const; ++ BRIDGED_INLINE bool hasValidLineNumber() const; ++ BRIDGED_INLINE bool isAutoGenerated() const; ++ BRIDGED_INLINE bool isEqualTo(BridgedLocation rhs) const; ++ BRIDGED_INLINE bool hasSameSourceLocation(BridgedLocation rhs) const; ++ static BRIDGED_INLINE BridgedLocation getArtificialUnreachableLocation(); ++}; + +- SWIFT_IMPORT_UNSAFE +- swift::SILDebugLocation getLocation() const { +- return getInst()->getDebugLocation(); +- } ++struct BridgedGenericSpecializationInformation { ++ const swift::GenericSpecializationInformation * _Nullable data = nullptr; ++}; + +- swift::MemoryBehavior getMemBehavior() const { +- return getInst()->getMemoryBehavior(); +- } ++struct BridgedInstruction { ++ SwiftObject obj; + +- bool mayRelease() const { +- return getInst()->mayRelease(); ++#ifdef USED_IN_CPP_SOURCE ++ template I *_Nonnull getAs() const { ++ return llvm::cast(static_cast(obj)->castToInstruction()); + } +- +- bool mayHaveSideEffects() const { +- return getInst()->mayHaveSideEffects(); ++ swift::SILInstruction * _Nonnull get() const { ++ return getAs(); + } ++#endif + ++ BridgedInstruction(SwiftObject obj) : obj(obj) {} ++ SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedInstruction getNext() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedInstruction getPrevious() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlock getParent() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction getLastInstOfParent() const; ++ BRIDGED_INLINE bool isDeleted() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedOperandArray getOperands() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedOperandArray getTypeDependentOperands() const; ++ BRIDGED_INLINE void setOperand(SwiftInt index, BridgedValue value) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedLocation getLocation() const; ++ BRIDGED_INLINE BridgedMemoryBehavior getMemBehavior() const; ++ BRIDGED_INLINE bool mayRelease() const; ++ BRIDGED_INLINE bool mayHaveSideEffects() const; ++ BRIDGED_INLINE bool maySuspend() const; + bool mayAccessPointer() const; + bool mayLoadWeakOrUnowned() const; + bool maySynchronizeNotConsideringSideEffects() const; + bool mayBeDeinitBarrierNotConsideringSideEffects() const; + +- SwiftInt MultipleValueInstruction_getNumResults() const { +- return getAs()->getNumResults(); +- } ++ BRIDGED_INLINE SwiftInt MultipleValueInstruction_getNumResults() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedMultiValueResult MultipleValueInstruction_getResult(SwiftInt index) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedSuccessorArray TermInst_getSuccessors() const; + +- SWIFT_IMPORT_UNSAFE +- BridgedMultiValueResult MultipleValueInstruction_getResult(SwiftInt index) const { +- return {getAs()->getResult(index)}; +- } +- +- SWIFT_IMPORT_UNSAFE +- inline BridgedSuccessorArray TermInst_getSuccessors() const; +- +- SWIFT_IMPORT_UNSAFE +- llvm::StringRef CondFailInst_getMessage() const { +- return getAs()->getMessage(); +- } +- +- SwiftInt LoadInst_getLoadOwnership() const { +- return (SwiftInt)getAs()->getOwnershipQualifier(); +- } +- +- swift::BuiltinValueKind BuiltinInst_getID() const { +- return getAs()->getBuiltinInfo().ID; +- } ++ enum class BuiltinValueKind { ++ None = 0, ++#define BUILTIN(Id, Name, Attrs) Id, ++#include "swift/AST/Builtins.def" ++ }; + + enum class IntrinsicID { + memcpy, memmove, + unknown + }; + +- IntrinsicID BuiltinInst_getIntrinsicID() const { +- switch (getAs()->getIntrinsicInfo().ID) { +- case llvm::Intrinsic::memcpy: return IntrinsicID::memcpy; +- case llvm::Intrinsic::memmove: return IntrinsicID::memmove; +- default: return IntrinsicID::unknown; +- } +- } +- +- SWIFT_IMPORT_UNSAFE +- swift::SubstitutionMap BuiltinInst_getSubstitutionMap() const { +- return getAs()->getSubstitutions(); +- } +- +- bool PointerToAddressInst_isStrict() const { +- return getAs()->isStrict(); +- } +- +- bool AddressToPointerInst_needsStackProtection() const { +- return getAs()->needsStackProtection(); +- } +- +- bool IndexAddrInst_needsStackProtection() const { +- return getAs()->needsStackProtection(); +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedGlobalVar GlobalAccessInst_getGlobal() const { +- return {getAs()->getReferencedGlobal()}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedGlobalVar AllocGlobalInst_getGlobal() const { +- return {getAs()->getReferencedGlobal()}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedFunction FunctionRefBaseInst_getReferencedFunction() const { +- return {getAs()->getInitiallyReferencedFunction()}; +- } +- +- SWIFT_IMPORT_UNSAFE +- llvm::APInt IntegerLiteralInst_getValue() const { +- return getAs()->getValue(); +- } +- +- SWIFT_IMPORT_UNSAFE +- llvm::APFloat FloatLiteralInst_getValue() const { +- return getAs()->getValue(); +- } +- +- SWIFT_IMPORT_UNSAFE +- llvm::StringRef StringLiteralInst_getValue() const { +- return getAs()->getValue(); +- } +- +- int StringLiteralInst_getEncoding() const { +- return (int)getAs()->getEncoding(); +- } +- +- SwiftInt TupleExtractInst_fieldIndex() const { +- return getAs()->getFieldIndex(); +- } +- +- SwiftInt TupleElementAddrInst_fieldIndex() const { +- return getAs()->getFieldIndex(); +- } +- +- SwiftInt StructExtractInst_fieldIndex() const { +- return getAs()->getFieldIndex(); +- } +- +- OptionalBridgedValue StructInst_getUniqueNonTrivialFieldValue() const { +- return {getAs()->getUniqueNonTrivialFieldValue()}; +- } +- +- SwiftInt StructElementAddrInst_fieldIndex() const { +- return getAs()->getFieldIndex(); +- } +- +- SwiftInt ProjectBoxInst_fieldIndex() const { +- return getAs()->getFieldIndex(); +- } +- +- bool EndCOWMutationInst_doKeepUnique() const { +- return getAs()->doKeepUnique(); +- } +- +- SwiftInt EnumInst_caseIndex() const { +- return getAs()->getCaseIndex(); +- } +- +- SwiftInt UncheckedEnumDataInst_caseIndex() const { +- return getAs()->getCaseIndex(); +- } +- +- SwiftInt InitEnumDataAddrInst_caseIndex() const { +- return getAs()->getCaseIndex(); +- } +- +- SwiftInt UncheckedTakeEnumDataAddrInst_caseIndex() const { +- return getAs()->getCaseIndex(); +- } +- +- SwiftInt InjectEnumAddrInst_caseIndex() const { +- return getAs()->getCaseIndex(); +- } +- +- SwiftInt RefElementAddrInst_fieldIndex() const { +- return getAs()->getFieldIndex(); +- } +- +- bool RefElementAddrInst_fieldIsLet() const { +- return getAs()->getField()->isLet(); +- } +- +- SwiftInt PartialApplyInst_numArguments() const { +- return getAs()->getNumArguments(); +- } +- +- SwiftInt ApplyInst_numArguments() const { +- return getAs()->getNumArguments(); +- } +- +- bool ApplyInst_getNonThrowing() const { +- return getAs()->isNonThrowing(); +- } +- +- bool ApplyInst_getNonAsync() const { +- return getAs()->isNonAsync(); +- } +- +- const swift::GenericSpecializationInformation * _Nullable +- +- SWIFT_IMPORT_UNSAFE +- ApplyInst_getSpecializationInfo() const { +- return getAs()->getSpecializationInfo(); +- } +- +- SwiftInt ObjectInst_getNumBaseElements() const { +- return getAs()->getNumBaseElements(); +- } +- +- SwiftInt PartialApply_getCalleeArgIndexOfFirstAppliedArg() const { +- return swift::ApplySite(getInst()).getCalleeArgIndexOfFirstAppliedArg(); +- } +- +- bool PartialApplyInst_isOnStack() const { +- return getAs()->isOnStack(); +- } +- +- bool AllocStackInst_hasDynamicLifetime() const { +- return getAs()->hasDynamicLifetime(); +- } +- +- bool AllocRefInstBase_isObjc() const { +- return getAs()->isObjC(); +- } +- +- bool AllocRefInstBase_canAllocOnStack() const { +- return getAs()->canAllocOnStack(); +- } +- +- SwiftInt AllocRefInstBase_getNumTailTypes() const { +- return getAs()->getNumTailTypes(); +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedSILTypeArray AllocRefInstBase_getTailAllocatedTypes() const { +- return {getAs()->getTailAllocatedTypes()}; +- } +- +- bool AllocRefDynamicInst_isDynamicTypeDeinitAndSizeKnownEquivalentToBaseType() const { +- return getAs()->isDynamicTypeDeinitAndSizeKnownEquivalentToBaseType(); +- } +- +- SwiftInt BeginApplyInst_numArguments() const { +- return getAs()->getNumArguments(); +- } +- +- SwiftInt TryApplyInst_numArguments() const { +- return getAs()->getNumArguments(); +- } +- +- SWIFT_IMPORT_UNSAFE +- inline BridgedBasicBlock BranchInst_getTargetBlock() const; +- +- SwiftInt SwitchEnumInst_getNumCases() const { +- return getAs()->getNumCases(); +- } +- +- SwiftInt SwitchEnumInst_getCaseIndex(SwiftInt idx) const { +- auto *seInst = getAs(); +- return seInst->getModule().getCaseIndex(seInst->getCase(idx).first); +- } +- +- SwiftInt StoreInst_getStoreOwnership() const { +- return (SwiftInt)getAs()->getOwnershipQualifier(); +- } +- +- swift::SILAccessKind BeginAccessInst_getAccessKind() const { +- return getAs()->getAccessKind(); +- } +- +- bool BeginAccessInst_isStatic() const { +- return getAs()->getEnforcement() == swift::SILAccessEnforcement::Static; +- } +- +- bool CopyAddrInst_isTakeOfSrc() const { +- return getAs()->isTakeOfSrc(); +- } +- +- bool CopyAddrInst_isInitializationOfDest() const { +- return getAs()->isInitializationOfDest(); +- } +- +- void RefCountingInst_setIsAtomic(bool isAtomic) const { +- getAs()->setAtomicity( +- isAtomic ? swift::RefCountingInst::Atomicity::Atomic +- : swift::RefCountingInst::Atomicity::NonAtomic); +- } +- +- bool RefCountingInst_getIsAtomic() const { +- return getAs()->getAtomicity() == swift::RefCountingInst::Atomicity::Atomic; +- } +- +- SwiftInt CondBranchInst_getNumTrueArgs() const { +- return getAs()->getNumTrueArgs(); +- } +- +- void AllocRefInstBase_setIsStackAllocatable() const { +- getAs()->setStackAllocatable(); +- } +- +- bool AllocRefInst_isBare() const { +- return getAs()->isBare(); +- } +- +- void AllocRefInst_setIsBare() const { +- getAs()->setBare(true); +- } +- +- inline void TermInst_replaceBranchTarget(BridgedBasicBlock from, BridgedBasicBlock to) const; ++ struct OptionalInt { ++ SwiftInt value; ++ bool hasValue; ++ }; + +- SwiftInt KeyPathInst_getNumComponents() const { +- if (swift::KeyPathPattern *pattern = getAs()->getPattern()) { +- return (SwiftInt)pattern->getComponents().size(); +- } +- return 0; +- } ++ enum class AccessKind { ++ Init, ++ Read, ++ Modify, ++ Deinit ++ }; + + struct KeyPathFunctionResults { + enum { maxFunctions = 5 }; +@@ -796,71 +493,99 @@ struct BridgedInstruction { + SwiftInt numFunctions; + }; + +- void KeyPathInst_getReferencedFunctions(SwiftInt componentIdx, KeyPathFunctionResults * _Nonnull results) const { +- swift::KeyPathPattern *pattern = getAs()->getPattern(); +- const swift::KeyPathPatternComponent &comp = pattern->getComponents()[componentIdx]; +- results->numFunctions = 0; +- +- comp.visitReferencedFunctionsAndMethods([results](swift::SILFunction *func) { +- assert(results->numFunctions < KeyPathFunctionResults::maxFunctions); +- results->functions[results->numFunctions++] = {func}; +- }, [](swift::SILDeclRef) {}); +- } +- +- bool GlobalValueInst_isBare() const { +- return getAs()->isBare(); +- } +- +- void GlobalValueInst_setIsBare() const { +- getAs()->setBare(true); +- } +- +- void LoadInst_setOwnership(SwiftInt ownership) const { +- getAs()->setOwnershipQualifier((swift::LoadOwnershipQualifier)ownership); +- } +- +- SWIFT_IMPORT_UNSAFE +- inline BridgedBasicBlock CheckedCastBranch_getSuccessBlock() const; +- +- SWIFT_IMPORT_UNSAFE +- inline BridgedBasicBlock CheckedCastBranch_getFailureBlock() const; +- +- SWIFT_IMPORT_UNSAFE +- swift::SubstitutionMap ApplySite_getSubstitutionMap() const { +- auto as = swift::ApplySite(getInst()); +- return as.getSubstitutionMap(); +- } ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef CondFailInst_getMessage() const; ++ BRIDGED_INLINE SwiftInt LoadInst_getLoadOwnership() const ; ++ BRIDGED_INLINE BuiltinValueKind BuiltinInst_getID() const; ++ BRIDGED_INLINE IntrinsicID BuiltinInst_getIntrinsicID() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedSubstitutionMap BuiltinInst_getSubstitutionMap() const; ++ BRIDGED_INLINE bool PointerToAddressInst_isStrict() const; ++ BRIDGED_INLINE bool AddressToPointerInst_needsStackProtection() const; ++ BRIDGED_INLINE bool IndexAddrInst_needsStackProtection() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedGlobalVar GlobalAccessInst_getGlobal() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedGlobalVar AllocGlobalInst_getGlobal() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedFunction FunctionRefBaseInst_getReferencedFunction() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalInt IntegerLiteralInst_getValue() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef StringLiteralInst_getValue() const; ++ BRIDGED_INLINE int StringLiteralInst_getEncoding() const; ++ BRIDGED_INLINE SwiftInt TupleExtractInst_fieldIndex() const; ++ BRIDGED_INLINE SwiftInt TupleElementAddrInst_fieldIndex() const; ++ BRIDGED_INLINE SwiftInt StructExtractInst_fieldIndex() const; ++ BRIDGED_INLINE OptionalBridgedValue StructInst_getUniqueNonTrivialFieldValue() const; ++ BRIDGED_INLINE SwiftInt StructElementAddrInst_fieldIndex() const; ++ BRIDGED_INLINE SwiftInt ProjectBoxInst_fieldIndex() const; ++ BRIDGED_INLINE bool EndCOWMutationInst_doKeepUnique() const; ++ BRIDGED_INLINE SwiftInt EnumInst_caseIndex() const; ++ BRIDGED_INLINE SwiftInt UncheckedEnumDataInst_caseIndex() const; ++ BRIDGED_INLINE SwiftInt InitEnumDataAddrInst_caseIndex() const; ++ BRIDGED_INLINE SwiftInt UncheckedTakeEnumDataAddrInst_caseIndex() const; ++ BRIDGED_INLINE SwiftInt InjectEnumAddrInst_caseIndex() const; ++ BRIDGED_INLINE SwiftInt RefElementAddrInst_fieldIndex() const; ++ BRIDGED_INLINE bool RefElementAddrInst_fieldIsLet() const; ++ BRIDGED_INLINE SwiftInt PartialApplyInst_numArguments() const; ++ BRIDGED_INLINE SwiftInt ApplyInst_numArguments() const; ++ BRIDGED_INLINE bool ApplyInst_getNonThrowing() const; ++ BRIDGED_INLINE bool ApplyInst_getNonAsync() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedGenericSpecializationInformation ApplyInst_getSpecializationInfo() const; ++ BRIDGED_INLINE SwiftInt ObjectInst_getNumBaseElements() const; ++ BRIDGED_INLINE SwiftInt PartialApply_getCalleeArgIndexOfFirstAppliedArg() const; ++ BRIDGED_INLINE bool PartialApplyInst_isOnStack() const; ++ BRIDGED_INLINE bool AllocStackInst_hasDynamicLifetime() const; ++ BRIDGED_INLINE bool AllocRefInstBase_isObjc() const; ++ BRIDGED_INLINE bool AllocRefInstBase_canAllocOnStack() const; ++ BRIDGED_INLINE SwiftInt AllocRefInstBase_getNumTailTypes() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedSILTypeArray AllocRefInstBase_getTailAllocatedTypes() const; ++ BRIDGED_INLINE bool AllocRefDynamicInst_isDynamicTypeDeinitAndSizeKnownEquivalentToBaseType() const; ++ BRIDGED_INLINE SwiftInt BeginApplyInst_numArguments() const; ++ BRIDGED_INLINE SwiftInt TryApplyInst_numArguments() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlock BranchInst_getTargetBlock() const; ++ BRIDGED_INLINE SwiftInt SwitchEnumInst_getNumCases() const; ++ BRIDGED_INLINE SwiftInt SwitchEnumInst_getCaseIndex(SwiftInt idx) const; ++ BRIDGED_INLINE SwiftInt StoreInst_getStoreOwnership() const; ++ BRIDGED_INLINE AccessKind BeginAccessInst_getAccessKind() const; ++ BRIDGED_INLINE bool BeginAccessInst_isStatic() const; ++ BRIDGED_INLINE bool CopyAddrInst_isTakeOfSrc() const; ++ BRIDGED_INLINE bool CopyAddrInst_isInitializationOfDest() const; ++ BRIDGED_INLINE void RefCountingInst_setIsAtomic(bool isAtomic) const; ++ BRIDGED_INLINE bool RefCountingInst_getIsAtomic() const; ++ BRIDGED_INLINE SwiftInt CondBranchInst_getNumTrueArgs() const; ++ BRIDGED_INLINE void AllocRefInstBase_setIsStackAllocatable() const; ++ BRIDGED_INLINE bool AllocRefInst_isBare() const; ++ BRIDGED_INLINE void AllocRefInst_setIsBare() const; ++ BRIDGED_INLINE void TermInst_replaceBranchTarget(BridgedBasicBlock from, BridgedBasicBlock to) const; ++ BRIDGED_INLINE SwiftInt KeyPathInst_getNumComponents() const; ++ BRIDGED_INLINE void KeyPathInst_getReferencedFunctions(SwiftInt componentIdx, KeyPathFunctionResults * _Nonnull results) const; ++ BRIDGED_INLINE bool GlobalValueInst_isBare() const; ++ BRIDGED_INLINE void GlobalValueInst_setIsBare() const; ++ BRIDGED_INLINE void LoadInst_setOwnership(SwiftInt ownership) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlock CheckedCastBranch_getSuccessBlock() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlock CheckedCastBranch_getFailureBlock() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedSubstitutionMap ApplySite_getSubstitutionMap() const; ++ BRIDGED_INLINE BridgedArgumentConvention ApplySite_getArgumentConvention(SwiftInt calleeArgIdx) const; ++ BRIDGED_INLINE SwiftInt ApplySite_getNumArguments() const; ++ BRIDGED_INLINE SwiftInt FullApplySite_numIndirectResultArguments() const; ++}; + +- BridgedArgumentConvention ApplySite_getArgumentConvention(SwiftInt calleeArgIdx) const { +- auto as = swift::ApplySite(getInst()); +- auto conv = as.getSubstCalleeConv().getSILArgumentConvention(calleeArgIdx); +- return castToArgumentConvention(conv.Value); +- } ++struct OptionalBridgedInstruction { ++ OptionalSwiftObject obj; + +- SwiftInt ApplySite_getNumArguments() const { +- return swift::ApplySite(getInst()).getNumArguments(); ++#ifdef USED_IN_CPP_SOURCE ++ swift::SILInstruction * _Nullable get() const { ++ if (!obj) ++ return nullptr; ++ return llvm::cast(static_cast(obj)->castToInstruction()); + } ++#endif + +- SwiftInt FullApplySite_numIndirectResultArguments() const { +- auto fas = swift::FullApplySite(getInst()); +- return fas.getNumIndirectSILResults(); +- } ++ OptionalBridgedInstruction() : obj(nullptr) {} ++ OptionalBridgedInstruction(OptionalSwiftObject obj) : obj(obj) {} + }; + + struct BridgedArgument { + SwiftObject obj; + +- swift::SILArgument * _Nonnull getArgument() const { +- return static_cast(obj); +- } +- +- SWIFT_IMPORT_UNSAFE +- inline BridgedBasicBlock getParent() const; +- +- BridgedArgumentConvention getConvention() const { +- auto *fArg = llvm::cast(getArgument()); +- return castToArgumentConvention(fArg->getArgumentConvention()); +- } ++ BRIDGED_INLINE swift::SILArgument * _Nonnull getArgument() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlock getParent() const; ++ BRIDGED_INLINE BridgedArgumentConvention getConvention() const; + }; + + struct OptionalBridgedArgument { +@@ -870,112 +595,56 @@ struct OptionalBridgedArgument { + struct OptionalBridgedBasicBlock { + OptionalSwiftObject obj; + +- swift::SILBasicBlock * _Nullable getBlock() const { ++#ifdef USED_IN_CPP_SOURCE ++ swift::SILBasicBlock * _Nullable get() const { + return obj ? static_cast(obj) : nullptr; + } ++#endif + }; + + struct BridgedBasicBlock { + SwiftObject obj; + +- BridgedBasicBlock(SwiftObject obj) : obj(obj) {} +- +- swift::SILBasicBlock * _Nonnull getBlock() const { +- return static_cast(obj); +- } +- +- std::string getDebugDescription() const; +- +- SWIFT_IMPORT_UNSAFE +- OptionalBridgedBasicBlock getNext() const { +- auto iter = std::next(getBlock()->getIterator()); +- if (iter == getBlock()->getParent()->end()) +- return {nullptr}; +- return {&*iter}; +- } +- +- SWIFT_IMPORT_UNSAFE +- OptionalBridgedBasicBlock getPrevious() const { +- auto iter = std::next(getBlock()->getReverseIterator()); +- if (iter == getBlock()->getParent()->rend()) +- return {nullptr}; +- return {&*iter}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedFunction getFunction() const { +- return {getBlock()->getParent()}; ++ BridgedBasicBlock(SwiftObject obj) : obj(obj) { + } + +- SWIFT_IMPORT_UNSAFE +- OptionalBridgedInstruction getFirstInst() const { +- if (getBlock()->empty()) +- return {nullptr}; +- return {getBlock()->front().asSILNode()}; ++#ifdef USED_IN_CPP_SOURCE ++ BridgedBasicBlock(swift::SILBasicBlock * _Nonnull block) : obj(block) { + } +- +- SWIFT_IMPORT_UNSAFE +- OptionalBridgedInstruction getLastInst() const { +- if (getBlock()->empty()) +- return {nullptr}; +- return {getBlock()->back().asSILNode()}; +- } +- +- SwiftInt getNumArguments() const { +- return getBlock()->getNumArguments(); +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedArgument getArgument(SwiftInt index) const { +- return {getBlock()->getArgument(index)}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedArgument addBlockArgument(swift::SILType type, BridgedValue::Ownership ownership) const { +- return {getBlock()->createPhiArgument(type, castToOwnership(ownership))}; +- } +- +- void eraseArgument(SwiftInt index) const { +- getBlock()->eraseArgument(index); +- } +- +- void moveAllInstructionsToBegin(BridgedBasicBlock dest) const { +- dest.getBlock()->spliceAtBegin(getBlock()); +- } +- +- void moveAllInstructionsToEnd(BridgedBasicBlock dest) const { +- dest.getBlock()->spliceAtEnd(getBlock()); +- } +- +- void moveArgumentsTo(BridgedBasicBlock dest) const { +- dest.getBlock()->moveArgumentList(getBlock()); ++ swift::SILBasicBlock * _Nonnull get() const { ++ return static_cast(obj); + } ++#endif + +- SWIFT_IMPORT_UNSAFE +- inline OptionalBridgedSuccessor getFirstPred() const; ++ SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedBasicBlock getNext() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedBasicBlock getPrevious() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedFunction getFunction() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedInstruction getFirstInst() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedInstruction getLastInst() const; ++ BRIDGED_INLINE SwiftInt getNumArguments() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedArgument getArgument(SwiftInt index) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedArgument addBlockArgument(BridgedType type, BridgedValue::Ownership ownership) const; ++ BRIDGED_INLINE void eraseArgument(SwiftInt index) const; ++ BRIDGED_INLINE void moveAllInstructionsToBegin(BridgedBasicBlock dest) const; ++ BRIDGED_INLINE void moveAllInstructionsToEnd(BridgedBasicBlock dest) const; ++ BRIDGED_INLINE void moveArgumentsTo(BridgedBasicBlock dest) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedSuccessor getFirstPred() const; + }; + + struct BridgedSuccessor { + const swift::SILSuccessor * _Nonnull succ; + +- SWIFT_IMPORT_UNSAFE +- inline OptionalBridgedSuccessor getNext() const; +- +- SWIFT_IMPORT_UNSAFE +- BridgedBasicBlock getTargetBlock() const { +- return {succ->getBB()}; +- } +- +- SWIFT_IMPORT_UNSAFE +- inline BridgedInstruction getContainingInst() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedSuccessor getNext() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlock getTargetBlock() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction getContainingInst() const; + }; + + struct OptionalBridgedSuccessor { + const swift::SILSuccessor * _Nullable succ; + + // Assumes that `succ` is not null. +- SWIFT_IMPORT_UNSAFE +- BridgedSuccessor advancedBy(SwiftInt index) const { return {succ + index}; } ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedSuccessor advancedBy(SwiftInt index) const; + }; + + struct BridgedSuccessorArray { +@@ -986,12 +655,9 @@ struct BridgedSuccessorArray { + struct BridgedVTableEntry { + const swift::SILVTableEntry * _Nonnull entry; + +- std::string getDebugDescription() const; +- +- SWIFT_IMPORT_UNSAFE +- BridgedFunction getImplementation() const { +- return {entry->getImplementation()}; +- } ++ SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedFunction getImplementation() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedVTableEntry advanceBy(SwiftInt index) const; + }; + + struct BridgedVTableEntryArray { +@@ -1002,29 +668,31 @@ struct BridgedVTableEntryArray { + struct BridgedVTable { + const swift::SILVTable * _Nonnull vTable; + +- std::string getDebugDescription() const; +- +- SWIFT_IMPORT_UNSAFE +- BridgedVTableEntryArray getEntries() const { +- auto entries = vTable->getEntries(); +- return {{entries.data()}, (SwiftInt)entries.size()}; +- } ++ SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedVTableEntryArray getEntries() const; + }; + + struct BridgedWitnessTableEntry { +- const swift::SILWitnessTable::Entry * _Nonnull entry; ++ const void * _Nonnull entry; + +- SWIFT_IMPORT_UNSAFE +- std::string getDebugDescription() const; ++ enum class Kind { ++ Invalid, ++ Method, ++ AssociatedType, ++ AssociatedTypeProtocol, ++ BaseProtocol ++ }; + +- swift::SILWitnessTable::WitnessKind getKind() const { +- return entry->getKind(); ++#ifdef USED_IN_CPP_SOURCE ++ const swift::SILWitnessTable::Entry * _Nonnull getEntry() const { ++ return (const swift::SILWitnessTable::Entry * _Nonnull)entry; + } ++#endif + +- SWIFT_IMPORT_UNSAFE +- OptionalBridgedFunction getMethodFunction() const { +- return {entry->getMethodWitness().Witness}; +- } ++ SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; ++ BRIDGED_INLINE Kind getKind() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedFunction getMethodFunction() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedWitnessTableEntry advanceBy(SwiftInt index) const; + }; + + struct BridgedWitnessTableEntryArray { +@@ -1035,13 +703,8 @@ struct BridgedWitnessTableEntryArray { + struct BridgedWitnessTable { + const swift::SILWitnessTable * _Nonnull table; + +- std::string getDebugDescription() const; +- +- SWIFT_IMPORT_UNSAFE +- BridgedWitnessTableEntryArray getEntries() const { +- auto entries = table->getEntries(); +- return {{entries.data()}, (SwiftInt)entries.size()}; +- } ++ SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedWitnessTableEntryArray getEntries() const; + }; + + struct OptionalBridgedWitnessTable { +@@ -1051,13 +714,8 @@ struct OptionalBridgedWitnessTable { + struct BridgedDefaultWitnessTable { + const swift::SILDefaultWitnessTable * _Nonnull table; + +- std::string getDebugDescription() const; +- +- SWIFT_IMPORT_UNSAFE +- BridgedWitnessTableEntryArray getEntries() const { +- auto entries = table->getEntries(); +- return {{entries.data()}, (SwiftInt)entries.size()}; +- } ++ SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedWitnessTableEntryArray getEntries() const; + }; + + struct OptionalBridgedDefaultWitnessTable { +@@ -1071,292 +729,99 @@ struct BridgedBuilder{ + } insertAt; + + SwiftObject insertionObj; +- swift::SILDebugLocation loc; ++ BridgedLocation loc; + +- swift::SILBuilder builder() const { ++#ifdef USED_IN_CPP_SOURCE ++ swift::SILBuilder get() const { + switch (insertAt) { +- case InsertAt::beforeInst: +- return swift::SILBuilder(BridgedInstruction(insertionObj).getInst(), loc.getScope()); +- case InsertAt::endOfBlock: +- return swift::SILBuilder(BridgedBasicBlock(insertionObj).getBlock(), loc.getScope()); +- case InsertAt::intoGlobal: ++ case BridgedBuilder::InsertAt::beforeInst: ++ return swift::SILBuilder(BridgedInstruction(insertionObj).get(), loc.getLoc().getScope()); ++ case BridgedBuilder::InsertAt::endOfBlock: ++ return swift::SILBuilder(BridgedBasicBlock(insertionObj).get(), loc.getLoc().getScope()); ++ case BridgedBuilder::InsertAt::intoGlobal: + return swift::SILBuilder(BridgedGlobalVar(insertionObj).getGlobal()); + } + } +- +- swift::SILLocation regularLoc() const { return swift::RegularLocation(loc.getLocation()); } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createBuiltinBinaryFunction(llvm::StringRef name, +- swift::SILType operandType, swift::SILType resultType, +- BridgedValueArray arguments) const { +- llvm::SmallVector argValues; +- return {builder().createBuiltinBinaryFunction(regularLoc(), +- name, operandType, resultType, +- arguments.getValues(argValues))}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createCondFail(BridgedValue condition, llvm::StringRef message) const { +- return {builder().createCondFail(regularLoc(), condition.getSILValue(), message)}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createIntegerLiteral(swift::SILType type, SwiftInt value) const { +- return {builder().createIntegerLiteral(regularLoc(), type, value)}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createAllocStack(swift::SILType type, +- bool hasDynamicLifetime, bool isLexical, bool wasMoved) const { +- return {builder().createAllocStack(regularLoc(), type, llvm::None, hasDynamicLifetime, isLexical, wasMoved)}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createDeallocStack(BridgedValue operand) const { +- return {builder().createDeallocStack(regularLoc(), operand.getSILValue())}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createDeallocStackRef(BridgedValue operand) const { +- return {builder().createDeallocStackRef(regularLoc(), operand.getSILValue())}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createUncheckedRefCast(BridgedValue op, swift::SILType type) const { +- return {builder().createUncheckedRefCast(regularLoc(), op.getSILValue(), type)}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createUpcast(BridgedValue op, swift::SILType type) const { +- return {builder().createUpcast(regularLoc(), op.getSILValue(), type)}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createLoad(BridgedValue op, SwiftInt ownership) const { +- return {builder().createLoad(regularLoc(), op.getSILValue(), (swift::LoadOwnershipQualifier)ownership)}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createSetDeallocating(BridgedValue op, bool isAtomic) const { +- return {builder().createSetDeallocating(regularLoc(), +- op.getSILValue(), +- isAtomic ? swift::RefCountingInst::Atomicity::Atomic +- : swift::RefCountingInst::Atomicity::NonAtomic)}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createStrongRetain(BridgedValue op) const { +- auto b = builder(); +- return {b.createStrongRetain(regularLoc(), op.getSILValue(), b.getDefaultAtomicity())}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createStrongRelease(BridgedValue op) const { +- auto b = builder(); +- return {b.createStrongRelease(regularLoc(), op.getSILValue(), b.getDefaultAtomicity())}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createUnownedRetain(BridgedValue op) const { +- auto b = builder(); +- return {b.createUnownedRetain(regularLoc(), op.getSILValue(), b.getDefaultAtomicity())}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createUnownedRelease(BridgedValue op) const { +- auto b = builder(); +- return {b.createUnownedRelease(regularLoc(), op.getSILValue(), b.getDefaultAtomicity())}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createFunctionRef(BridgedFunction function) const { +- return {builder().createFunctionRef(regularLoc(), function.getFunction())}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createCopyValue(BridgedValue op) const { +- return {builder().createCopyValue(regularLoc(), op.getSILValue())}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createBeginBorrow(BridgedValue op) const { +- return {builder().createBeginBorrow(regularLoc(), op.getSILValue())}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createEndBorrow(BridgedValue op) const { +- return {builder().createEndBorrow(regularLoc(), op.getSILValue())}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createCopyAddr(BridgedValue from, BridgedValue to, +- bool takeSource, bool initializeDest) const { +- return {builder().createCopyAddr(regularLoc(), +- from.getSILValue(), to.getSILValue(), +- swift::IsTake_t(takeSource), +- swift::IsInitialization_t(initializeDest))}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createDestroyValue(BridgedValue op) const { +- return {builder().createDestroyValue(regularLoc(), op.getSILValue())}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createDestroyAddr(BridgedValue op) const { +- return {builder().createDestroyAddr(regularLoc(), op.getSILValue())}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createDebugStep() const { +- return {builder().createDebugStep(regularLoc())}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createApply(BridgedValue function, swift::SubstitutionMap subMap, +- BridgedValueArray arguments, bool isNonThrowing, bool isNonAsync, +- const swift::GenericSpecializationInformation * _Nullable specInfo) const { +- llvm::SmallVector argValues; +- swift::ApplyOptions applyOpts; +- if (isNonThrowing) { applyOpts |= swift::ApplyFlags::DoesNotThrow; } +- if (isNonAsync) { applyOpts |= swift::ApplyFlags::DoesNotAwait; } +- +- return {builder().createApply(regularLoc(), +- function.getSILValue(), subMap, +- arguments.getValues(argValues), +- applyOpts, specInfo)}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createSwitchEnumInst(BridgedValue enumVal, OptionalBridgedBasicBlock defaultBlock, +- const void * _Nullable enumCases, SwiftInt numEnumCases) const { +- using BridgedCase = const std::pair; +- llvm::ArrayRef cases(static_cast(enumCases), +- (unsigned)numEnumCases); +- llvm::SmallDenseMap mappedElements; +- swift::SILValue en = enumVal.getSILValue(); +- swift::EnumDecl *enumDecl = en->getType().getEnumOrBoundGenericEnum(); +- for (auto elemWithIndex : llvm::enumerate(enumDecl->getAllElements())) { +- mappedElements[elemWithIndex.index()] = elemWithIndex.value(); +- } +- llvm::SmallVector, 16> convertedCases; +- for (auto c : cases) { +- assert(mappedElements.count(c.first) && "wrong enum element index"); +- convertedCases.push_back({mappedElements[c.first], c.second.getBlock()}); +- } +- return {builder().createSwitchEnum(regularLoc(), +- enumVal.getSILValue(), +- defaultBlock.getBlock(), convertedCases)}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createUncheckedEnumData(BridgedValue enumVal, SwiftInt caseIdx, +- swift::SILType resultType) const { +- swift::SILValue en = enumVal.getSILValue(); +- return {builder().createUncheckedEnumData(regularLoc(), enumVal.getSILValue(), +- en->getType().getEnumElement(caseIdx), resultType)}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createEnum(SwiftInt caseIdx, OptionalBridgedValue payload, +- swift::SILType resultType) const { +- swift::EnumElementDecl *caseDecl = resultType.getEnumElement(caseIdx); +- swift::SILValue pl = payload.getSILValue(); +- return {builder().createEnum(regularLoc(), pl, caseDecl, resultType)}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createBranch(BridgedBasicBlock destBlock, BridgedValueArray arguments) const { +- llvm::SmallVector argValues; +- return {builder().createBranch(regularLoc(), destBlock.getBlock(), arguments.getValues(argValues))}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createUnreachable() const { +- return {builder().createUnreachable(regularLoc())}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createObject(swift::SILType type, BridgedValueArray arguments, SwiftInt numBaseElements) const { +- llvm::SmallVector argValues; +- return {builder().createObject(swift::ArtificialUnreachableLocation(), +- type, arguments.getValues(argValues), numBaseElements)}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createGlobalAddr(BridgedGlobalVar global) const { +- return {builder().createGlobalAddr(regularLoc(), global.getGlobal())}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createGlobalValue(BridgedGlobalVar global, bool isBare) const { +- return {builder().createGlobalValue(regularLoc(), global.getGlobal(), isBare)}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createStruct(swift::SILType type, BridgedValueArray elements) const { +- llvm::SmallVector elementValues; +- return {builder().createStruct(regularLoc(), type, elements.getValues(elementValues))}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createStructExtract(BridgedValue str, SwiftInt fieldIndex) const { +- swift::SILValue v = str.getSILValue(); +- return {builder().createStructExtract(regularLoc(), v, v->getType().getFieldDecl(fieldIndex))}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createStructElementAddr(BridgedValue addr, SwiftInt fieldIndex) const { +- swift::SILValue v = addr.getSILValue(); +- return {builder().createStructElementAddr(regularLoc(), v, v->getType().getFieldDecl(fieldIndex))}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createDestructureStruct(BridgedValue str) const { +- return {builder().createDestructureStruct(regularLoc(), str.getSILValue())}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createTuple(swift::SILType type, BridgedValueArray elements) const { +- llvm::SmallVector elementValues; +- return {builder().createTuple(regularLoc(), type, elements.getValues(elementValues))}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createTupleExtract(BridgedValue str, SwiftInt elementIndex) const { +- swift::SILValue v = str.getSILValue(); +- return {builder().createTupleExtract(regularLoc(), v, elementIndex)}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createTupleElementAddr(BridgedValue addr, SwiftInt elementIndex) const { +- swift::SILValue v = addr.getSILValue(); +- return {builder().createTupleElementAddr(regularLoc(), v, elementIndex)}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createDestructureTuple(BridgedValue str) const { +- return {builder().createDestructureTuple(regularLoc(), str.getSILValue())}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createStore(BridgedValue src, BridgedValue dst, +- SwiftInt ownership) const { +- return {builder().createStore(regularLoc(), src.getSILValue(), dst.getSILValue(), +- (swift::StoreOwnershipQualifier)ownership)}; ++ swift::SILLocation regularLoc() const { ++ return swift::RegularLocation(loc.getLoc().getLocation()); + } ++#endif + +- SWIFT_IMPORT_UNSAFE +- BridgedInstruction createInitExistentialRef(BridgedValue instance, +- swift::SILType type, +- BridgedInstruction useConformancesOf) const { +- auto *src = useConformancesOf.getAs(); +- return {builder().createInitExistentialRef(regularLoc(), type, +- src->getFormalConcreteType(), +- instance.getSILValue(), +- src->getConformances())}; +- } ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createBuiltinBinaryFunction(BridgedStringRef name, ++ BridgedType operandType, BridgedType resultType, ++ BridgedValueArray arguments) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createCondFail(BridgedValue condition, ++ BridgedStringRef message) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createIntegerLiteral(BridgedType type, SwiftInt value) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createAllocStack(BridgedType type, ++ bool hasDynamicLifetime, bool isLexical, bool wasMoved) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createDeallocStack(BridgedValue operand) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createDeallocStackRef(BridgedValue operand) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createUncheckedRefCast(BridgedValue op, ++ BridgedType type) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createUpcast(BridgedValue op, BridgedType type) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createLoad(BridgedValue op, SwiftInt ownership) const; ++ /*SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createBeginDeallocRef(BridgedValue reference, ++ BridgedValue allocation) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createEndInitLetRef(BridgedValue op) const;*/ ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createStrongRetain(BridgedValue op) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createStrongRelease(BridgedValue op) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createUnownedRetain(BridgedValue op) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createUnownedRelease(BridgedValue op) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createFunctionRef(BridgedFunction function) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createCopyValue(BridgedValue op) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createBeginBorrow(BridgedValue op) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createEndBorrow(BridgedValue op) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createCopyAddr(BridgedValue from, BridgedValue to, ++ bool takeSource, bool initializeDest) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createDestroyValue(BridgedValue op) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createDestroyAddr(BridgedValue op) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createDebugStep() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createApply(BridgedValue function, ++ BridgedSubstitutionMap subMap, ++ BridgedValueArray arguments, bool isNonThrowing, bool isNonAsync, ++ BridgedGenericSpecializationInformation specInfo) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createSwitchEnumInst(BridgedValue enumVal, ++ OptionalBridgedBasicBlock defaultBlock, ++ const void * _Nullable enumCases, SwiftInt numEnumCases) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createUncheckedEnumData(BridgedValue enumVal, ++ SwiftInt caseIdx, BridgedType resultType) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createEnum(SwiftInt caseIdx, OptionalBridgedValue payload, ++ BridgedType resultType) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createBranch(BridgedBasicBlock destBlock, ++ BridgedValueArray arguments) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createUnreachable() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createObject(BridgedType type, BridgedValueArray arguments, ++ SwiftInt numBaseElements) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createGlobalAddr(BridgedGlobalVar global) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createGlobalValue(BridgedGlobalVar global, ++ bool isBare) const; ++ ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createSetDeallocating(BridgedValue op, bool isAtomic) const; ++ ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createStruct(BridgedType type, ++ BridgedValueArray elements) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createStructExtract(BridgedValue str, ++ SwiftInt fieldIndex) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createStructElementAddr(BridgedValue addr, ++ SwiftInt fieldIndex) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createDestructureStruct(BridgedValue str) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createTuple(BridgedType type, ++ BridgedValueArray elements) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createTupleExtract(BridgedValue str, ++ SwiftInt elementIndex) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createTupleElementAddr(BridgedValue addr, ++ SwiftInt elementIndex) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createDestructureTuple(BridgedValue str) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createStore(BridgedValue src, BridgedValue dst, ++ SwiftInt ownership) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createInitExistentialRef(BridgedValue instance, ++ BridgedType type, ++ BridgedInstruction useConformancesOf) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createMetatype(BridgedType type, ++ BridgedType::MetatypeRepresentation representation) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createEndCOWMutation(BridgedValue instance, ++ bool keepUnique) const; + }; + + // AST bridging +@@ -1364,20 +826,11 @@ struct BridgedBuilder{ + struct BridgedNominalTypeDecl { + swift::NominalTypeDecl * _Nonnull decl; + +- SWIFT_IMPORT_UNSAFE +- llvm::StringRef getName() const { +- return decl->getName().str(); +- } +- ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef getName() const; + bool isStructWithUnreferenceableStorage() const; ++ BRIDGED_INLINE bool isGlobalActor() const; + }; + +-// Passmanager and Context +- +-namespace swift { +- class SwiftPassInvocation; +-} +- + struct BridgedChangeNotificationHandler { + swift::SwiftPassInvocation * _Nonnull invocation; + +@@ -1391,89 +844,7 @@ struct BridgedChangeNotificationHandler { + void notifyChanges(Kind changeKind) const; + }; + +-//===----------------------------------------------------------------------===// +-// Inline functions +-//===----------------------------------------------------------------------===// +- +-OptionalBridgedOperand BridgedOperand::getNextUse() const { +- return {op->getNextUse()}; +-} +- +-BridgedInstruction BridgedOperand::getUser() const { +- return {op->getUser()->asSILNode()}; +-} +- +-OptionalBridgedOperand BridgedValue::getFirstUse() const { +- return {*getSILValue()->use_begin()}; +-} +- +-OptionalBridgedSuccessor BridgedSuccessor::getNext() const { +- return {succ->getNext()}; +-} +- +-BridgedInstruction BridgedSuccessor::getContainingInst() const { +- return {succ->getContainingInst()}; +-} +- +-OptionalBridgedBasicBlock BridgedFunction::getFirstBlock() const { +- return {getFunction()->empty() ? nullptr : getFunction()->getEntryBlock()}; +-} +- +-OptionalBridgedBasicBlock BridgedFunction::getLastBlock() const { +- return {getFunction()->empty() ? nullptr : &*getFunction()->rbegin()}; +-} +- +-OptionalBridgedInstruction BridgedGlobalVar::getFirstStaticInitInst() const { +- if (getGlobal()->begin() == getGlobal()->end()) { +- return {nullptr}; +- } +- swift::SILInstruction *firstInst = &*getGlobal()->begin(); +- return {firstInst->asSILNode()}; +-} +- +-BridgedInstruction BridgedMultiValueResult::getParent() const { +- return {getMVResult()->getParent()}; +-} +- +-BridgedBasicBlock BridgedInstruction::getParent() const { +- assert(!getInst()->isStaticInitializerInst() && +- "cannot get the parent of a static initializer instruction"); +- return {getInst()->getParent()}; +-} +- +-inline BridgedInstruction BridgedInstruction::getLastInstOfParent() const { +- return {getInst()->getParent()->back().asSILNode()}; +-} +- +-BridgedSuccessorArray BridgedInstruction::TermInst_getSuccessors() const { +- auto successors = getAs()->getSuccessors(); +- return {{successors.data()}, (SwiftInt)successors.size()}; +-} +- +-BridgedBasicBlock BridgedInstruction::BranchInst_getTargetBlock() const { +- return {getAs()->getDestBB()}; +-} +- +-void BridgedInstruction::TermInst_replaceBranchTarget(BridgedBasicBlock from, BridgedBasicBlock to) const { +- getAs()->replaceBranchTarget(from.getBlock(), to.getBlock()); +-} +- +-BridgedBasicBlock BridgedInstruction::CheckedCastBranch_getSuccessBlock() const { +- return {getAs()->getSuccessBB()}; +-} +- +-inline BridgedBasicBlock BridgedInstruction::CheckedCastBranch_getFailureBlock() const { +- return {getAs()->getFailureBB()}; +-} +- +-OptionalBridgedSuccessor BridgedBasicBlock::getFirstPred() const { +- return {getBlock()->pred_begin().getSuccessorRef()}; +-} +- +-BridgedBasicBlock BridgedArgument::getParent() const { +- return {getArgument()->getParent()}; +-} +- ++void writeCharToStderr(int c); + + SWIFT_END_NULLABILITY_ANNOTATIONS + +diff --git a/swift/include/swift/SIL/SILBridgingImpl.h b/swift/include/swift/SIL/SILBridgingImpl.h +new file mode 100644 +index 00000000000..d195ffb9bf1 +--- /dev/null ++++ b/swift/include/swift/SIL/SILBridgingImpl.h +@@ -0,0 +1,1353 @@ ++//===--- SILBridgingImpl.h ------------------------------------------------===// ++// ++// This source file is part of the Swift.org open source project ++// ++// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors ++// Licensed under Apache License v2.0 with Runtime Library Exception ++// ++// See https://swift.org/LICENSE.txt for license information ++// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors ++// ++//===----------------------------------------------------------------------===// ++// ++// This file contains the implementation of bridging functions, which are either ++// - depending on if PURE_BRIDGING_MODE is set - included in the cpp file or ++// in the header file. ++// ++//===----------------------------------------------------------------------===// ++ ++#ifndef SWIFT_SIL_SILBRIDGING_IMPL_H ++#define SWIFT_SIL_SILBRIDGING_IMPL_H ++ ++#include "swift/AST/Builtins.h" ++#include "swift/AST/Decl.h" ++#include "swift/AST/SubstitutionMap.h" ++#include "swift/Basic/BasicBridging.h" ++#include "swift/Basic/Nullability.h" ++#include "swift/SIL/ApplySite.h" ++#include "swift/SIL/InstWrappers.h" ++#include "swift/SIL/SILBuilder.h" ++#include "swift/SIL/SILDefaultWitnessTable.h" ++#include "swift/SIL/SILFunctionConventions.h" ++#include "swift/SIL/SILInstruction.h" ++#include "swift/SIL/SILLocation.h" ++#include "swift/SIL/SILModule.h" ++#include "swift/SIL/SILVTable.h" ++#include "swift/SIL/SILWitnessTable.h" ++#include ++#include ++#include ++ ++SWIFT_BEGIN_NULLABILITY_ANNOTATIONS ++ ++//===----------------------------------------------------------------------===// ++// BridgedType ++//===----------------------------------------------------------------------===// ++ ++BridgedOwnedString BridgedType::getDebugDescription() const { ++ return BridgedOwnedString(get().getDebugDescription()); ++} ++ ++bool BridgedType::isNull() const { ++ return get().isNull(); ++} ++ ++bool BridgedType::isAddress() const { ++ return get().isAddress(); ++} ++ ++BridgedType BridgedType::getAddressType() const { ++ return get().getAddressType(); ++} ++ ++BridgedType BridgedType::getObjectType() const { ++ return get().getObjectType(); ++} ++ ++bool BridgedType::isTrivial(BridgedFunction f) const { ++ return get().isTrivial(f.getFunction()); ++} ++ ++bool BridgedType::isNonTrivialOrContainsRawPointer(BridgedFunction f) const { ++ return get().isNonTrivialOrContainsRawPointer(f.getFunction()); ++} ++ ++bool BridgedType::isValueTypeWithDeinit() const { ++ return get().isValueTypeWithDeinit(); ++} ++ ++bool BridgedType::isLoadable(BridgedFunction f) const { ++ return get().isLoadable(f.getFunction()); ++} ++ ++bool BridgedType::isReferenceCounted(BridgedFunction f) const { ++ return get().isReferenceCounted(f.getFunction()); ++} ++ ++bool BridgedType::isUnownedStorageType() const { ++ return get().isUnownedStorageType(); ++} ++ ++bool BridgedType::hasArchetype() const { ++ return get().hasArchetype(); ++} ++ ++bool BridgedType::isNominalOrBoundGenericNominal() const { ++ return get().getNominalOrBoundGenericNominal() != nullptr; ++} ++ ++BridgedNominalTypeDecl BridgedType::getNominalOrBoundGenericNominal() const { ++ return {get().getNominalOrBoundGenericNominal()}; ++} ++ ++bool BridgedType::isClassOrBoundGenericClass() const { ++ return get().getClassOrBoundGenericClass() != 0; ++} ++ ++bool BridgedType::isStructOrBoundGenericStruct() const { ++ return get().getStructOrBoundGenericStruct() != nullptr; ++} ++ ++bool BridgedType::isTuple() const { ++ return get().isTuple(); ++} ++ ++bool BridgedType::isEnumOrBoundGenericEnum() const { ++ return get().getEnumOrBoundGenericEnum() != nullptr; ++} ++ ++bool BridgedType::isFunction() const { ++ return get().isFunction(); ++} ++ ++bool BridgedType::isMetatype() const { ++ return get().isMetatype(); ++} ++ ++bool BridgedType::isNoEscapeFunction() const { ++ return get().isNoEscapeFunction(); ++} ++ ++/*bool BridgedType::isAsyncFunction() const { ++ return get().isAsyncFunction(); ++}*/ ++ ++BridgedType::TraitResult BridgedType::canBeClass() const { ++ return (TraitResult)get().canBeClass(); ++} ++ ++bool BridgedType::isMoveOnly() const { ++ return get().isMoveOnly(); ++} ++ ++bool BridgedType::isOrContainsObjectiveCClass() const { ++ return get().isOrContainsObjectiveCClass(); ++} ++ ++bool BridgedType::isBuiltinInteger() const { ++ return get().isBuiltinInteger(); ++} ++ ++bool BridgedType::isBuiltinFloat() const { ++ return get().isBuiltinFloat(); ++} ++ ++bool BridgedType::isBuiltinVector() const { ++ return get().isBuiltinVector(); ++} ++ ++BridgedType BridgedType::getBuiltinVectorElementType() const { ++ return get().getBuiltinVectorElementType(); ++} ++ ++bool BridgedType::isBuiltinFixedWidthInteger(SwiftInt width) const { ++ return get().isBuiltinFixedWidthInteger((unsigned)width); ++} ++ ++bool BridgedType::isExactSuperclassOf(BridgedType t) const { ++ return get().isExactSuperclassOf(t.get()); ++} ++ ++BridgedType BridgedType::getInstanceTypeOfMetatype(BridgedFunction f) const { ++ return get().getInstanceTypeOfMetatype(f.getFunction()); ++} ++ ++bool BridgedType::isDynamicSelfMetatype() const { ++ auto metaType = get().castTo(); ++ swift::Type instTy = metaType->getInstanceType(); ++ return instTy->is(); ++} ++ ++/*BridgedType::MetatypeRepresentation BridgedType::getRepresentationOfMetatype(BridgedFunction f) const { ++ return BridgedType::MetatypeRepresentation(get().getRepresentationOfMetatype(f.getFunction())); ++}*/ ++ ++bool BridgedType::isCalleeConsumedFunction() const { ++ return get().isCalleeConsumedFunction(); ++} ++ ++bool BridgedType::isMarkedAsImmortal() const { ++ return get().isMarkedAsImmortal(); ++} ++ ++SwiftInt BridgedType::getCaseIdxOfEnumType(BridgedStringRef name) const { ++ return get().getCaseIdxOfEnumType(name.get()); ++} ++ ++SwiftInt BridgedType::getNumNominalFields() const { ++ return get().getNumNominalFields(); ++} ++ ++ ++BridgedType BridgedType::getFieldType(SwiftInt idx, BridgedFunction f) const { ++ return get().getFieldType(idx, f.getFunction()); ++} ++ ++SwiftInt BridgedType::getFieldIdxOfNominalType(BridgedStringRef name) const { ++ return get().getFieldIdxOfNominalType(name.get()); ++} ++ ++BridgedStringRef BridgedType::getFieldName(SwiftInt idx) const { ++ return get().getFieldName(idx); ++} ++ ++SwiftInt BridgedType::getNumTupleElements() const { ++ return get().getNumTupleElements(); ++} ++ ++BridgedType BridgedType::getTupleElementType(SwiftInt idx) const { ++ return get().getTupleElementType(idx); ++} ++ ++//===----------------------------------------------------------------------===// ++// BridgedValue ++//===----------------------------------------------------------------------===// ++ ++inline BridgedValue::Ownership castOwnership(swift::OwnershipKind ownership) { ++ switch (ownership) { ++ case swift::OwnershipKind::Any: ++ llvm_unreachable("Invalid ownership for value"); ++ case swift::OwnershipKind::Unowned: return BridgedValue::Ownership::Unowned; ++ case swift::OwnershipKind::Owned: return BridgedValue::Ownership::Owned; ++ case swift::OwnershipKind::Guaranteed: return BridgedValue::Ownership::Guaranteed; ++ case swift::OwnershipKind::None: return BridgedValue::Ownership::None; ++ } ++} ++ ++swift::ValueBase * _Nonnull BridgedValue::getSILValue() const { ++ return static_cast(obj); ++} ++ ++swift::ValueBase * _Nullable OptionalBridgedValue::getSILValue() const { ++ if (obj) ++ return static_cast(obj); ++ return nullptr; ++} ++ ++OptionalBridgedOperand BridgedValue::getFirstUse() const { ++ return {*getSILValue()->use_begin()}; ++} ++ ++BridgedType BridgedValue::getType() const { ++ return getSILValue()->getType(); ++} ++ ++BridgedValue::Ownership BridgedValue::getOwnership() const { ++ return castOwnership(getSILValue()->getOwnershipKind()); ++} ++ ++//===----------------------------------------------------------------------===// ++// BridgedOperand ++//===----------------------------------------------------------------------===// ++ ++bool BridgedOperand::isTypeDependent() const { return op->isTypeDependent(); } ++ ++bool BridgedOperand::isLifetimeEnding() const { return op->isLifetimeEnding(); } ++ ++OptionalBridgedOperand BridgedOperand::getNextUse() const { ++ return {op->getNextUse()}; ++} ++ ++BridgedValue BridgedOperand::getValue() const { return {op->get()}; } ++ ++BridgedInstruction BridgedOperand::getUser() const { ++ return {op->getUser()->asSILNode()}; ++} ++ ++/*BridgedOperand::OperandOwnership BridgedOperand::getOperandOwnership() const { ++ switch (op->getOperandOwnership()) { ++ case swift::OperandOwnership::NonUse: ++ return OperandOwnership::NonUse; ++ case swift::OperandOwnership::TrivialUse: ++ return OperandOwnership::TrivialUse; ++ case swift::OperandOwnership::InstantaneousUse: ++ return OperandOwnership::InstantaneousUse; ++ case swift::OperandOwnership::UnownedInstantaneousUse: ++ return OperandOwnership::UnownedInstantaneousUse; ++ case swift::OperandOwnership::ForwardingUnowned: ++ return OperandOwnership::ForwardingUnowned; ++ case swift::OperandOwnership::PointerEscape: ++ return OperandOwnership::PointerEscape; ++ case swift::OperandOwnership::BitwiseEscape: ++ return OperandOwnership::BitwiseEscape; ++ case swift::OperandOwnership::Borrow: ++ return OperandOwnership::Borrow; ++ case swift::OperandOwnership::DestroyingConsume: ++ return OperandOwnership::DestroyingConsume; ++ case swift::OperandOwnership::ForwardingConsume: ++ return OperandOwnership::ForwardingConsume; ++ case swift::OperandOwnership::InteriorPointer: ++ return OperandOwnership::InteriorPointer; ++ case swift::OperandOwnership::GuaranteedForwarding: ++ return OperandOwnership::GuaranteedForwarding; ++ case swift::OperandOwnership::EndBorrow: ++ return OperandOwnership::EndBorrow; ++ case swift::OperandOwnership::Reborrow: ++ return OperandOwnership::Reborrow; ++ } ++}*/ ++ ++BridgedOperand OptionalBridgedOperand::advancedBy(SwiftInt index) const { return {op + index}; } ++ ++// Assumes that `op` is not null. ++SwiftInt OptionalBridgedOperand::distanceTo(BridgedOperand element) const { return element.op - op; } ++ ++//===----------------------------------------------------------------------===// ++// BridgedArgument ++//===----------------------------------------------------------------------===// ++ ++inline BridgedArgumentConvention castToArgumentConvention(swift::SILArgumentConvention convention) { ++ return static_cast(convention.Value); ++} ++ ++swift::SILArgument * _Nonnull BridgedArgument::getArgument() const { ++ return static_cast(obj); ++} ++ ++BridgedBasicBlock BridgedArgument::getParent() const { ++ return {getArgument()->getParent()}; ++} ++ ++BridgedArgumentConvention BridgedArgument::getConvention() const { ++ auto *fArg = llvm::cast(getArgument()); ++ return castToArgumentConvention(fArg->getArgumentConvention()); ++} ++ ++//===----------------------------------------------------------------------===// ++// BridgedSubstitutionMap ++//===----------------------------------------------------------------------===// ++ ++BridgedSubstitutionMap::BridgedSubstitutionMap() : BridgedSubstitutionMap(swift::SubstitutionMap()) { ++} ++ ++bool BridgedSubstitutionMap::isEmpty() const { ++ return get().empty(); ++} ++ ++//===----------------------------------------------------------------------===// ++// BridgedLocation ++//===----------------------------------------------------------------------===// ++ ++BridgedLocation BridgedLocation::getAutogeneratedLocation() const { ++ return getLoc().getAutogeneratedLocation(); ++} ++bool BridgedLocation::hasValidLineNumber() const { ++ return getLoc().hasValidLineNumber(); ++} ++bool BridgedLocation::isAutoGenerated() const { ++ return getLoc().isAutoGenerated(); ++} ++bool BridgedLocation::isEqualTo(BridgedLocation rhs) const { ++ return getLoc().isEqualTo(rhs.getLoc()); ++} ++bool BridgedLocation::hasSameSourceLocation(BridgedLocation rhs) const { ++ return getLoc().hasSameSourceLocation(rhs.getLoc()); ++} ++BridgedLocation BridgedLocation::getArtificialUnreachableLocation() { ++ return swift::SILDebugLocation::getArtificialUnreachableLocation(); ++} ++ ++//===----------------------------------------------------------------------===// ++// BridgedFunction ++//===----------------------------------------------------------------------===// ++ ++swift::SILFunction * _Nonnull BridgedFunction::getFunction() const { ++ return static_cast(obj); ++} ++ ++BridgedStringRef BridgedFunction::getName() const { ++ return getFunction()->getName(); ++} ++ ++bool BridgedFunction::hasOwnership() const { return getFunction()->hasOwnership(); } ++ ++OptionalBridgedBasicBlock BridgedFunction::getFirstBlock() const { ++ return {getFunction()->empty() ? nullptr : getFunction()->getEntryBlock()}; ++} ++ ++OptionalBridgedBasicBlock BridgedFunction::getLastBlock() const { ++ return {getFunction()->empty() ? nullptr : &*getFunction()->rbegin()}; ++} ++ ++SwiftInt BridgedFunction::getNumIndirectFormalResults() const { ++ return (SwiftInt)getFunction()->getLoweredFunctionType()->getNumIndirectFormalResults(); ++} ++ ++SwiftInt BridgedFunction::getNumParameters() const { ++ return (SwiftInt)getFunction()->getLoweredFunctionType()->getNumParameters(); ++} ++ ++SwiftInt BridgedFunction::getSelfArgumentIndex() const { ++ swift::SILFunctionConventions conv(getFunction()->getConventionsInContext()); ++ swift::CanSILFunctionType fTy = getFunction()->getLoweredFunctionType(); ++ if (!fTy->hasSelfParam()) ++ return -1; ++ return conv.getNumParameters() + conv.getNumIndirectSILResults() - 1; ++} ++ ++SwiftInt BridgedFunction::getNumSILArguments() const { ++ return swift::SILFunctionConventions(getFunction()->getConventionsInContext()).getNumSILArguments(); ++} ++ ++BridgedType BridgedFunction::getSILArgumentType(SwiftInt idx) const { ++ swift::SILFunctionConventions conv(getFunction()->getConventionsInContext()); ++ return conv.getSILArgumentType(idx, getFunction()->getTypeExpansionContext()); ++} ++ ++BridgedArgumentConvention BridgedFunction::getSILArgumentConvention(SwiftInt idx) const { ++ swift::SILFunctionConventions conv(getFunction()->getConventionsInContext()); ++ return castToArgumentConvention(conv.getSILArgumentConvention(idx)); ++} ++ ++BridgedType BridgedFunction::getSILResultType() const { ++ swift::SILFunctionConventions conv(getFunction()->getConventionsInContext()); ++ return conv.getSILResultType(getFunction()->getTypeExpansionContext()); ++} ++ ++bool BridgedFunction::isSwift51RuntimeAvailable() const { ++ if (getFunction()->getResilienceExpansion() != swift::ResilienceExpansion::Maximal) ++ return false; ++ ++ swift::ASTContext &ctxt = getFunction()->getModule().getASTContext(); ++ return swift::AvailabilityContext::forDeploymentTarget(ctxt).isContainedIn(ctxt.getSwift51Availability()); ++} ++ ++bool BridgedFunction::isPossiblyUsedExternally() const { ++ return getFunction()->isPossiblyUsedExternally(); ++} ++ ++bool BridgedFunction::isAvailableExternally() const { ++ return getFunction()->isAvailableExternally(); ++} ++ ++bool BridgedFunction::isTransparent() const { ++ return getFunction()->isTransparent() == swift::IsTransparent; ++} ++ ++bool BridgedFunction::isAsync() const { ++ return getFunction()->isAsync(); ++} ++ ++bool BridgedFunction::isGlobalInitFunction() const { ++ return getFunction()->isGlobalInit(); ++} ++ ++bool BridgedFunction::isGlobalInitOnceFunction() const { ++ return getFunction()->isGlobalInitOnceFunction(); ++} ++ ++bool BridgedFunction::isGenericFunction() const { ++ return !getFunction()->getGenericSignature().isNull(); ++} ++ ++bool BridgedFunction::hasSemanticsAttr(BridgedStringRef attrName) const { ++ return getFunction()->hasSemanticsAttr(attrName.get()); ++} ++ ++BridgedFunction::EffectsKind BridgedFunction::getEffectAttribute() const { ++ return (EffectsKind)getFunction()->getEffectsKind(); ++} ++ ++BridgedFunction::PerformanceConstraints BridgedFunction::getPerformanceConstraints() const { ++ return (PerformanceConstraints)getFunction()->getPerfConstraints(); ++} ++ ++BridgedFunction::InlineStrategy BridgedFunction::getInlineStrategy() const { ++ return (InlineStrategy)getFunction()->getInlineStrategy(); ++} ++ ++bool BridgedFunction::isSerialized() const { ++ return getFunction()->isSerialized(); ++} ++ ++bool BridgedFunction::hasValidLinkageForFragileRef() const { ++ return getFunction()->hasValidLinkageForFragileRef(); ++} ++ ++bool BridgedFunction::needsStackProtection() const { ++ return getFunction()->needsStackProtection(); ++} ++ ++void BridgedFunction::setNeedStackProtection(bool needSP) const { ++ getFunction()->setNeedStackProtection(needSP); ++} ++ ++ ++//===----------------------------------------------------------------------===// ++// BridgedGlobalVar ++//===----------------------------------------------------------------------===// ++ ++swift::SILGlobalVariable * _Nonnull BridgedGlobalVar::getGlobal() const { ++ return static_cast(obj); ++} ++ ++BridgedStringRef BridgedGlobalVar::getName() const { ++ return getGlobal()->getName(); ++} ++ ++bool BridgedGlobalVar::isLet() const { return getGlobal()->isLet(); } ++ ++void BridgedGlobalVar::setLet(bool value) const { getGlobal()->setLet(value); } ++ ++bool BridgedGlobalVar::isPossiblyUsedExternally() const { ++ return getGlobal()->isPossiblyUsedExternally(); ++} ++ ++bool BridgedGlobalVar::isAvailableExternally() const { ++ return swift::isAvailableExternally(getGlobal()->getLinkage()); ++} ++ ++OptionalBridgedInstruction BridgedGlobalVar::getFirstStaticInitInst() const { ++ if (getGlobal()->begin() == getGlobal()->end()) { ++ return {nullptr}; ++ } ++ swift::SILInstruction *firstInst = &*getGlobal()->begin(); ++ return {firstInst->asSILNode()}; ++} ++ ++//===----------------------------------------------------------------------===// ++// BridgedMultiValueResult ++//===----------------------------------------------------------------------===// ++ ++BridgedInstruction BridgedMultiValueResult::getParent() const { ++ return {get()->getParent()}; ++} ++ ++SwiftInt BridgedMultiValueResult::getIndex() const { ++ return (SwiftInt)get()->getIndex(); ++} ++ ++//===----------------------------------------------------------------------===// ++// BridgedTypeArray ++//===----------------------------------------------------------------------===// ++ ++BridgedTypeArray BridgedTypeArray::fromReplacementTypes(BridgedSubstitutionMap substMap) { ++ swift::ArrayRef replTypes = substMap.get().getReplacementTypes(); ++ return {replTypes.data(), replTypes.size()}; ++} ++ ++BridgedType BridgedTypeArray::getAt(SwiftInt index) const { ++ assert((size_t)index < typeArray.numElements); ++ swift::Type origTy = ((const swift::Type *)typeArray.data)[index]; ++ auto ty = origTy->getCanonicalType(); ++ if (ty->isLegalSILType()) ++ return swift::SILType::getPrimitiveObjectType(ty); ++ return swift::SILType(); ++} ++ ++//===----------------------------------------------------------------------===// ++// BridgedTypeArray ++//===----------------------------------------------------------------------===// ++ ++BridgedType BridgedSILTypeArray::getAt(SwiftInt index) const { ++ assert((size_t)index < typeArray.numElements); ++ return ((const swift::SILType *)typeArray.data)[index]; ++} ++ ++//===----------------------------------------------------------------------===// ++// BridgedInstruction ++//===----------------------------------------------------------------------===// ++ ++OptionalBridgedInstruction BridgedInstruction::getNext() const { ++ auto iter = std::next(get()->getIterator()); ++ if (iter == get()->getParent()->end()) ++ return {nullptr}; ++ return {iter->asSILNode()}; ++} ++ ++OptionalBridgedInstruction BridgedInstruction::getPrevious() const { ++ auto iter = std::next(get()->getReverseIterator()); ++ if (iter == get()->getParent()->rend()) ++ return {nullptr}; ++ return {iter->asSILNode()}; ++} ++ ++BridgedBasicBlock BridgedInstruction::getParent() const { ++ assert(!get()->isStaticInitializerInst() && ++ "cannot get the parent of a static initializer instruction"); ++ return {get()->getParent()}; ++} ++ ++BridgedInstruction BridgedInstruction::getLastInstOfParent() const { ++ return {get()->getParent()->back().asSILNode()}; ++} ++ ++bool BridgedInstruction::isDeleted() const { ++ return get()->isDeleted(); ++} ++ ++BridgedOperandArray BridgedInstruction::getOperands() const { ++ auto operands = get()->getAllOperands(); ++ return {{operands.data()}, (SwiftInt)operands.size()}; ++} ++ ++BridgedOperandArray BridgedInstruction::getTypeDependentOperands() const { ++ auto typeOperands = get()->getTypeDependentOperands(); ++ return {{typeOperands.data()}, (SwiftInt)typeOperands.size()}; ++} ++ ++void BridgedInstruction::setOperand(SwiftInt index, BridgedValue value) const { ++ get()->setOperand((unsigned)index, value.getSILValue()); ++} ++ ++BridgedLocation BridgedInstruction::getLocation() const { ++ return get()->getDebugLocation(); ++} ++ ++BridgedMemoryBehavior BridgedInstruction::getMemBehavior() const { ++ return (BridgedMemoryBehavior)get()->getMemoryBehavior(); ++} ++ ++bool BridgedInstruction::mayRelease() const { ++ return get()->mayRelease(); ++} ++ ++bool BridgedInstruction::mayHaveSideEffects() const { ++ return get()->mayHaveSideEffects(); ++} ++ ++bool BridgedInstruction::maySuspend() const { ++ return get()->maySuspend(); ++} ++ ++SwiftInt BridgedInstruction::MultipleValueInstruction_getNumResults() const { ++ return getAs()->getNumResults(); ++} ++ ++BridgedMultiValueResult BridgedInstruction::MultipleValueInstruction_getResult(SwiftInt index) const { ++ return {getAs()->getResult(index)}; ++} ++ ++BridgedSuccessorArray BridgedInstruction::TermInst_getSuccessors() const { ++ auto successors = getAs()->getSuccessors(); ++ return {{successors.data()}, (SwiftInt)successors.size()}; ++} ++ ++BridgedStringRef BridgedInstruction::CondFailInst_getMessage() const { ++ return getAs()->getMessage(); ++} ++ ++SwiftInt BridgedInstruction::LoadInst_getLoadOwnership() const { ++ return (SwiftInt)getAs()->getOwnershipQualifier(); ++} ++ ++BridgedInstruction::BuiltinValueKind BridgedInstruction::BuiltinInst_getID() const { ++ return (BuiltinValueKind)getAs()->getBuiltinInfo().ID; ++} ++ ++BridgedInstruction::IntrinsicID BridgedInstruction::BuiltinInst_getIntrinsicID() const { ++ switch (getAs()->getIntrinsicInfo().ID) { ++ case llvm::Intrinsic::memcpy: return IntrinsicID::memcpy; ++ case llvm::Intrinsic::memmove: return IntrinsicID::memmove; ++ default: return IntrinsicID::unknown; ++ } ++} ++ ++BridgedSubstitutionMap BridgedInstruction::BuiltinInst_getSubstitutionMap() const { ++ return getAs()->getSubstitutions(); ++} ++ ++bool BridgedInstruction::PointerToAddressInst_isStrict() const { ++ return getAs()->isStrict(); ++} ++ ++bool BridgedInstruction::AddressToPointerInst_needsStackProtection() const { ++ return getAs()->needsStackProtection(); ++} ++ ++bool BridgedInstruction::IndexAddrInst_needsStackProtection() const { ++ return getAs()->needsStackProtection(); ++} ++ ++BridgedGlobalVar BridgedInstruction::GlobalAccessInst_getGlobal() const { ++ return {getAs()->getReferencedGlobal()}; ++} ++ ++BridgedGlobalVar BridgedInstruction::AllocGlobalInst_getGlobal() const { ++ return {getAs()->getReferencedGlobal()}; ++} ++ ++BridgedFunction BridgedInstruction::FunctionRefBaseInst_getReferencedFunction() const { ++ return {getAs()->getInitiallyReferencedFunction()}; ++} ++ ++BridgedInstruction::OptionalInt BridgedInstruction::IntegerLiteralInst_getValue() const { ++ llvm::APInt result = getAs()->getValue(); ++ if (result.getSignificantBits() <= std::min(std::numeric_limits::digits, 64)) { ++ return {(SwiftInt)result.getSExtValue(), true}; ++ } ++ return {0, false}; ++} ++ ++BridgedStringRef BridgedInstruction::StringLiteralInst_getValue() const { ++ return getAs()->getValue(); ++} ++ ++int BridgedInstruction::StringLiteralInst_getEncoding() const { ++ return (int)getAs()->getEncoding(); ++} ++ ++SwiftInt BridgedInstruction::TupleExtractInst_fieldIndex() const { ++ return getAs()->getFieldIndex(); ++} ++ ++SwiftInt BridgedInstruction::TupleElementAddrInst_fieldIndex() const { ++ return getAs()->getFieldIndex(); ++} ++ ++SwiftInt BridgedInstruction::StructExtractInst_fieldIndex() const { ++ return getAs()->getFieldIndex(); ++} ++ ++OptionalBridgedValue BridgedInstruction::StructInst_getUniqueNonTrivialFieldValue() const { ++ return {getAs()->getUniqueNonTrivialFieldValue()}; ++} ++ ++SwiftInt BridgedInstruction::StructElementAddrInst_fieldIndex() const { ++ return getAs()->getFieldIndex(); ++} ++ ++SwiftInt BridgedInstruction::ProjectBoxInst_fieldIndex() const { ++ return getAs()->getFieldIndex(); ++} ++ ++bool BridgedInstruction::EndCOWMutationInst_doKeepUnique() const { ++ return getAs()->doKeepUnique(); ++} ++ ++SwiftInt BridgedInstruction::EnumInst_caseIndex() const { ++ return getAs()->getCaseIndex(); ++} ++ ++SwiftInt BridgedInstruction::UncheckedEnumDataInst_caseIndex() const { ++ return getAs()->getCaseIndex(); ++} ++ ++SwiftInt BridgedInstruction::InitEnumDataAddrInst_caseIndex() const { ++ return getAs()->getCaseIndex(); ++} ++ ++SwiftInt BridgedInstruction::UncheckedTakeEnumDataAddrInst_caseIndex() const { ++ return getAs()->getCaseIndex(); ++} ++ ++SwiftInt BridgedInstruction::InjectEnumAddrInst_caseIndex() const { ++ return getAs()->getCaseIndex(); ++} ++ ++SwiftInt BridgedInstruction::RefElementAddrInst_fieldIndex() const { ++ return getAs()->getFieldIndex(); ++} ++ ++bool BridgedInstruction::RefElementAddrInst_fieldIsLet() const { ++ return getAs()->getField()->isLet(); ++} ++ ++SwiftInt BridgedInstruction::PartialApplyInst_numArguments() const { ++ return getAs()->getNumArguments(); ++} ++ ++SwiftInt BridgedInstruction::ApplyInst_numArguments() const { ++ return getAs()->getNumArguments(); ++} ++ ++bool BridgedInstruction::ApplyInst_getNonThrowing() const { ++ return getAs()->isNonThrowing(); ++} ++ ++bool BridgedInstruction::ApplyInst_getNonAsync() const { ++ return getAs()->isNonAsync(); ++} ++ ++BridgedGenericSpecializationInformation BridgedInstruction::ApplyInst_getSpecializationInfo() const { ++ return {getAs()->getSpecializationInfo()}; ++} ++ ++SwiftInt BridgedInstruction::ObjectInst_getNumBaseElements() const { ++ return getAs()->getNumBaseElements(); ++} ++ ++SwiftInt BridgedInstruction::PartialApply_getCalleeArgIndexOfFirstAppliedArg() const { ++ return swift::ApplySite(get()).getCalleeArgIndexOfFirstAppliedArg(); ++} ++ ++bool BridgedInstruction::PartialApplyInst_isOnStack() const { ++ return getAs()->isOnStack(); ++} ++ ++bool BridgedInstruction::AllocStackInst_hasDynamicLifetime() const { ++ return getAs()->hasDynamicLifetime(); ++} ++ ++bool BridgedInstruction::AllocRefInstBase_isObjc() const { ++ return getAs()->isObjC(); ++} ++ ++bool BridgedInstruction::AllocRefInstBase_canAllocOnStack() const { ++ return getAs()->canAllocOnStack(); ++} ++ ++SwiftInt BridgedInstruction::AllocRefInstBase_getNumTailTypes() const { ++ return getAs()->getNumTailTypes(); ++} ++ ++BridgedSILTypeArray BridgedInstruction::AllocRefInstBase_getTailAllocatedTypes() const { ++ llvm::ArrayRef types = getAs()->getTailAllocatedTypes(); ++ return {types.data(), types.size()}; ++} ++ ++bool BridgedInstruction::AllocRefDynamicInst_isDynamicTypeDeinitAndSizeKnownEquivalentToBaseType() const { ++ return getAs()->isDynamicTypeDeinitAndSizeKnownEquivalentToBaseType(); ++} ++ ++SwiftInt BridgedInstruction::BeginApplyInst_numArguments() const { ++ return getAs()->getNumArguments(); ++} ++ ++SwiftInt BridgedInstruction::TryApplyInst_numArguments() const { ++ return getAs()->getNumArguments(); ++} ++ ++BridgedBasicBlock BridgedInstruction::BranchInst_getTargetBlock() const { ++ return {getAs()->getDestBB()}; ++} ++ ++SwiftInt BridgedInstruction::SwitchEnumInst_getNumCases() const { ++ return getAs()->getNumCases(); ++} ++ ++SwiftInt BridgedInstruction::SwitchEnumInst_getCaseIndex(SwiftInt idx) const { ++ auto *seInst = getAs(); ++ return seInst->getModule().getCaseIndex(seInst->getCase(idx).first); ++} ++ ++SwiftInt BridgedInstruction::StoreInst_getStoreOwnership() const { ++ return (SwiftInt)getAs()->getOwnershipQualifier(); ++} ++ ++BridgedInstruction::AccessKind BridgedInstruction::BeginAccessInst_getAccessKind() const { ++ return (AccessKind)getAs()->getAccessKind(); ++} ++ ++bool BridgedInstruction::BeginAccessInst_isStatic() const { ++ return getAs()->getEnforcement() == swift::SILAccessEnforcement::Static; ++} ++ ++bool BridgedInstruction::CopyAddrInst_isTakeOfSrc() const { ++ return getAs()->isTakeOfSrc(); ++} ++ ++bool BridgedInstruction::CopyAddrInst_isInitializationOfDest() const { ++ return getAs()->isInitializationOfDest(); ++} ++ ++void BridgedInstruction::RefCountingInst_setIsAtomic(bool isAtomic) const { ++ getAs()->setAtomicity( ++ isAtomic ? swift::RefCountingInst::Atomicity::Atomic ++ : swift::RefCountingInst::Atomicity::NonAtomic); ++} ++ ++bool BridgedInstruction::RefCountingInst_getIsAtomic() const { ++ return getAs()->getAtomicity() == swift::RefCountingInst::Atomicity::Atomic; ++} ++ ++SwiftInt BridgedInstruction::CondBranchInst_getNumTrueArgs() const { ++ return getAs()->getNumTrueArgs(); ++} ++ ++void BridgedInstruction::AllocRefInstBase_setIsStackAllocatable() const { ++ getAs()->setStackAllocatable(); ++} ++ ++bool BridgedInstruction::AllocRefInst_isBare() const { ++ return getAs()->isBare(); ++} ++ ++void BridgedInstruction::AllocRefInst_setIsBare() const { ++ getAs()->setBare(true); ++} ++ ++void BridgedInstruction::TermInst_replaceBranchTarget(BridgedBasicBlock from, BridgedBasicBlock to) const { ++ getAs()->replaceBranchTarget(from.get(), to.get()); ++} ++ ++SwiftInt BridgedInstruction::KeyPathInst_getNumComponents() const { ++ if (swift::KeyPathPattern *pattern = getAs()->getPattern()) { ++ return (SwiftInt)pattern->getComponents().size(); ++ } ++ return 0; ++} ++ ++void BridgedInstruction::KeyPathInst_getReferencedFunctions(SwiftInt componentIdx, ++ KeyPathFunctionResults * _Nonnull results) const { ++ swift::KeyPathPattern *pattern = getAs()->getPattern(); ++ const swift::KeyPathPatternComponent &comp = pattern->getComponents()[componentIdx]; ++ results->numFunctions = 0; ++ ++ comp.visitReferencedFunctionsAndMethods([results](swift::SILFunction *func) { ++ assert(results->numFunctions < KeyPathFunctionResults::maxFunctions); ++ results->functions[results->numFunctions++] = {func}; ++ }, [](swift::SILDeclRef) {}); ++} ++ ++bool BridgedInstruction::GlobalValueInst_isBare() const { ++ return getAs()->isBare(); ++} ++ ++void BridgedInstruction::GlobalValueInst_setIsBare() const { ++ getAs()->setBare(true); ++} ++ ++void BridgedInstruction::LoadInst_setOwnership(SwiftInt ownership) const { ++ getAs()->setOwnershipQualifier((swift::LoadOwnershipQualifier)ownership); ++} ++ ++BridgedBasicBlock BridgedInstruction::CheckedCastBranch_getSuccessBlock() const { ++ return {getAs()->getSuccessBB()}; ++} ++ ++BridgedBasicBlock BridgedInstruction::CheckedCastBranch_getFailureBlock() const { ++ return {getAs()->getFailureBB()}; ++} ++ ++BridgedSubstitutionMap BridgedInstruction::ApplySite_getSubstitutionMap() const { ++ auto as = swift::ApplySite(get()); ++ return as.getSubstitutionMap(); ++} ++ ++BridgedArgumentConvention BridgedInstruction::ApplySite_getArgumentConvention(SwiftInt calleeArgIdx) const { ++ auto as = swift::ApplySite(get()); ++ auto conv = as.getSubstCalleeConv().getSILArgumentConvention(calleeArgIdx); ++ return castToArgumentConvention(conv.Value); ++} ++ ++SwiftInt BridgedInstruction::ApplySite_getNumArguments() const { ++ return swift::ApplySite(get()).getNumArguments(); ++} ++ ++SwiftInt BridgedInstruction::FullApplySite_numIndirectResultArguments() const { ++ auto fas = swift::FullApplySite(get()); ++ return fas.getNumIndirectSILResults(); ++} ++ ++//===----------------------------------------------------------------------===// ++// BridgedBasicBlock ++//===----------------------------------------------------------------------===// ++ ++OptionalBridgedBasicBlock BridgedBasicBlock::getNext() const { ++ auto iter = std::next(get()->getIterator()); ++ if (iter == get()->getParent()->end()) ++ return {nullptr}; ++ return {&*iter}; ++} ++ ++OptionalBridgedBasicBlock BridgedBasicBlock::getPrevious() const { ++ auto iter = std::next(get()->getReverseIterator()); ++ if (iter == get()->getParent()->rend()) ++ return {nullptr}; ++ return {&*iter}; ++} ++ ++BridgedFunction BridgedBasicBlock::getFunction() const { ++ return {get()->getParent()}; ++} ++ ++OptionalBridgedInstruction BridgedBasicBlock::getFirstInst() const { ++ if (get()->empty()) ++ return {nullptr}; ++ return {get()->front().asSILNode()}; ++} ++ ++OptionalBridgedInstruction BridgedBasicBlock::getLastInst() const { ++ if (get()->empty()) ++ return {nullptr}; ++ return {get()->back().asSILNode()}; ++} ++ ++SwiftInt BridgedBasicBlock::getNumArguments() const { ++ return get()->getNumArguments(); ++} ++ ++BridgedArgument BridgedBasicBlock::getArgument(SwiftInt index) const { ++ return {get()->getArgument(index)}; ++} ++ ++BridgedArgument BridgedBasicBlock::addBlockArgument(BridgedType type, BridgedValue::Ownership ownership) const { ++ return {get()->createPhiArgument(type.get(), BridgedValue::castToOwnership(ownership))}; ++} ++ ++void BridgedBasicBlock::eraseArgument(SwiftInt index) const { ++ get()->eraseArgument(index); ++} ++ ++void BridgedBasicBlock::moveAllInstructionsToBegin(BridgedBasicBlock dest) const { ++ dest.get()->spliceAtBegin(get()); ++} ++ ++void BridgedBasicBlock::moveAllInstructionsToEnd(BridgedBasicBlock dest) const { ++ dest.get()->spliceAtEnd(get()); ++} ++ ++void BridgedBasicBlock::moveArgumentsTo(BridgedBasicBlock dest) const { ++ dest.get()->moveArgumentList(get()); ++} ++ ++OptionalBridgedSuccessor BridgedBasicBlock::getFirstPred() const { ++ return {get()->pred_begin().getSuccessorRef()}; ++} ++ ++//===----------------------------------------------------------------------===// ++// BridgedSuccessor ++//===----------------------------------------------------------------------===// ++ ++OptionalBridgedSuccessor BridgedSuccessor::getNext() const { ++ return {succ->getNext()}; ++} ++ ++BridgedBasicBlock BridgedSuccessor::getTargetBlock() const { ++ return succ->getBB(); ++} ++ ++BridgedInstruction BridgedSuccessor::getContainingInst() const { ++ return {succ->getContainingInst()}; ++} ++ ++BridgedSuccessor OptionalBridgedSuccessor::advancedBy(SwiftInt index) const { ++ return {succ + index}; ++} ++ ++//===----------------------------------------------------------------------===// ++// BridgedVTable ++//===----------------------------------------------------------------------===// ++ ++BridgedFunction BridgedVTableEntry::getImplementation() const { ++ return {entry->getImplementation()}; ++} ++ ++BridgedVTableEntry BridgedVTableEntry::advanceBy(SwiftInt index) const { ++ return {entry + index}; ++} ++ ++BridgedVTableEntryArray BridgedVTable::getEntries() const { ++ auto entries = vTable->getEntries(); ++ return {{entries.data()}, (SwiftInt)entries.size()}; ++} ++ ++//===----------------------------------------------------------------------===// ++// BridgedWitnessTable, BridgedDefaultWitnessTable ++//===----------------------------------------------------------------------===// ++ ++BridgedWitnessTableEntry::Kind BridgedWitnessTableEntry::getKind() const { ++ return (Kind)getEntry()->getKind(); ++} ++ ++OptionalBridgedFunction BridgedWitnessTableEntry::getMethodFunction() const { ++ return {getEntry()->getMethodWitness().Witness}; ++} ++ ++BridgedWitnessTableEntry BridgedWitnessTableEntry::advanceBy(SwiftInt index) const { ++ return {getEntry() + index}; ++} ++ ++BridgedWitnessTableEntryArray BridgedWitnessTable::getEntries() const { ++ auto entries = table->getEntries(); ++ return {{entries.data()}, (SwiftInt)entries.size()}; ++} ++ ++BridgedWitnessTableEntryArray BridgedDefaultWitnessTable::getEntries() const { ++ auto entries = table->getEntries(); ++ return {{entries.data()}, (SwiftInt)entries.size()}; ++} ++ ++//===----------------------------------------------------------------------===// ++// BridgedBuilder ++//===----------------------------------------------------------------------===// ++ ++BridgedInstruction BridgedBuilder::createBuiltinBinaryFunction(BridgedStringRef name, ++ BridgedType operandType, BridgedType resultType, ++ BridgedValueArray arguments) const { ++ llvm::SmallVector argValues; ++ return {get().createBuiltinBinaryFunction(regularLoc(), ++ name.get(), ++ operandType.get(), resultType.get(), ++ arguments.getValues(argValues))}; ++} ++ ++BridgedInstruction BridgedBuilder::createCondFail(BridgedValue condition, BridgedStringRef message) const { ++ return {get().createCondFail(regularLoc(), condition.getSILValue(), message.get())}; ++} ++ ++BridgedInstruction BridgedBuilder::createIntegerLiteral(BridgedType type, SwiftInt value) const { ++ return {get().createIntegerLiteral(regularLoc(), type.get(), value)}; ++} ++ ++BridgedInstruction BridgedBuilder::createAllocStack(BridgedType type, ++ bool hasDynamicLifetime, bool isLexical, bool wasMoved) const { ++ return {get().createAllocStack(regularLoc(), type.get(), llvm::None, ++ hasDynamicLifetime, isLexical, wasMoved)}; ++} ++ ++BridgedInstruction BridgedBuilder::createDeallocStack(BridgedValue operand) const { ++ return {get().createDeallocStack(regularLoc(), operand.getSILValue())}; ++} ++ ++BridgedInstruction BridgedBuilder::createDeallocStackRef(BridgedValue operand) const { ++ return {get().createDeallocStackRef(regularLoc(), operand.getSILValue())}; ++} ++ ++BridgedInstruction BridgedBuilder::createUncheckedRefCast(BridgedValue op, BridgedType type) const { ++ return {get().createUncheckedRefCast(regularLoc(), op.getSILValue(), type.get())}; ++} ++ ++BridgedInstruction BridgedBuilder::createUpcast(BridgedValue op, BridgedType type) const { ++ return {get().createUpcast(regularLoc(), op.getSILValue(), type.get())}; ++} ++ ++BridgedInstruction BridgedBuilder::createLoad(BridgedValue op, SwiftInt ownership) const { ++ return {get().createLoad(regularLoc(), op.getSILValue(), (swift::LoadOwnershipQualifier)ownership)}; ++} ++ ++/*BridgedInstruction BridgedBuilder::createBeginDeallocRef(BridgedValue reference, BridgedValue allocation) const { ++ return {get().createBeginDeallocRef(regularLoc(), reference.getSILValue(), allocation.getSILValue())}; ++} ++ ++BridgedInstruction BridgedBuilder::createEndInitLetRef(BridgedValue op) const { ++ return {get().createEndInitLetRef(regularLoc(), op.getSILValue())}; ++}*/ ++ ++BridgedInstruction BridgedBuilder::createStrongRetain(BridgedValue op) const { ++ auto b = get(); ++ return {b.createStrongRetain(regularLoc(), op.getSILValue(), b.getDefaultAtomicity())}; ++} ++ ++BridgedInstruction BridgedBuilder::createStrongRelease(BridgedValue op) const { ++ auto b = get(); ++ return {b.createStrongRelease(regularLoc(), op.getSILValue(), b.getDefaultAtomicity())}; ++} ++ ++BridgedInstruction BridgedBuilder::createUnownedRetain(BridgedValue op) const { ++ auto b = get(); ++ return {b.createUnownedRetain(regularLoc(), op.getSILValue(), b.getDefaultAtomicity())}; ++} ++ ++BridgedInstruction BridgedBuilder::createUnownedRelease(BridgedValue op) const { ++ auto b = get(); ++ return {b.createUnownedRelease(regularLoc(), op.getSILValue(), b.getDefaultAtomicity())}; ++} ++ ++BridgedInstruction BridgedBuilder::createFunctionRef(BridgedFunction function) const { ++ return {get().createFunctionRef(regularLoc(), function.getFunction())}; ++} ++ ++BridgedInstruction BridgedBuilder::createCopyValue(BridgedValue op) const { ++ return {get().createCopyValue(regularLoc(), op.getSILValue())}; ++} ++ ++BridgedInstruction BridgedBuilder::createBeginBorrow(BridgedValue op) const { ++ return {get().createBeginBorrow(regularLoc(), op.getSILValue())}; ++} ++ ++BridgedInstruction BridgedBuilder::createEndBorrow(BridgedValue op) const { ++ return {get().createEndBorrow(regularLoc(), op.getSILValue())}; ++} ++ ++BridgedInstruction BridgedBuilder::createCopyAddr(BridgedValue from, BridgedValue to, ++ bool takeSource, bool initializeDest) const { ++ return {get().createCopyAddr(regularLoc(), ++ from.getSILValue(), to.getSILValue(), ++ swift::IsTake_t(takeSource), ++ swift::IsInitialization_t(initializeDest))}; ++} ++ ++BridgedInstruction BridgedBuilder::createDestroyValue(BridgedValue op) const { ++ return {get().createDestroyValue(regularLoc(), op.getSILValue())}; ++} ++ ++BridgedInstruction BridgedBuilder::createDestroyAddr(BridgedValue op) const { ++ return {get().createDestroyAddr(regularLoc(), op.getSILValue())}; ++} ++ ++BridgedInstruction BridgedBuilder::createDebugStep() const { ++ return {get().createDebugStep(regularLoc())}; ++} ++ ++BridgedInstruction BridgedBuilder::createApply(BridgedValue function, BridgedSubstitutionMap subMap, ++ BridgedValueArray arguments, bool isNonThrowing, bool isNonAsync, ++ BridgedGenericSpecializationInformation specInfo) const { ++ llvm::SmallVector argValues; ++ swift::ApplyOptions applyOpts; ++ if (isNonThrowing) { applyOpts |= swift::ApplyFlags::DoesNotThrow; } ++ if (isNonAsync) { applyOpts |= swift::ApplyFlags::DoesNotAwait; } ++ ++ return {get().createApply(regularLoc(), ++ function.getSILValue(), subMap.get(), ++ arguments.getValues(argValues), ++ applyOpts, specInfo.data)}; ++} ++ ++BridgedInstruction BridgedBuilder::createSwitchEnumInst(BridgedValue enumVal, OptionalBridgedBasicBlock defaultBlock, ++ const void * _Nullable enumCases, SwiftInt numEnumCases) const { ++ using BridgedCase = const std::pair; ++ llvm::ArrayRef cases(static_cast(enumCases), ++ (unsigned)numEnumCases); ++ llvm::SmallDenseMap mappedElements; ++ swift::SILValue en = enumVal.getSILValue(); ++ swift::EnumDecl *enumDecl = en->getType().getEnumOrBoundGenericEnum(); ++ for (auto elemWithIndex : llvm::enumerate(enumDecl->getAllElements())) { ++ mappedElements[elemWithIndex.index()] = elemWithIndex.value(); ++ } ++ llvm::SmallVector, 16> convertedCases; ++ for (auto c : cases) { ++ assert(mappedElements.count(c.first) && "wrong enum element index"); ++ convertedCases.push_back({mappedElements[c.first], c.second.get()}); ++ } ++ return {get().createSwitchEnum(regularLoc(), ++ enumVal.getSILValue(), ++ defaultBlock.get(), convertedCases)}; ++} ++ ++BridgedInstruction BridgedBuilder::createUncheckedEnumData(BridgedValue enumVal, SwiftInt caseIdx, ++ BridgedType resultType) const { ++ swift::SILValue en = enumVal.getSILValue(); ++ return {get().createUncheckedEnumData(regularLoc(), enumVal.getSILValue(), ++ en->getType().getEnumElement(caseIdx), resultType.get())}; ++} ++ ++BridgedInstruction BridgedBuilder::createEnum(SwiftInt caseIdx, OptionalBridgedValue payload, ++ BridgedType resultType) const { ++ swift::EnumElementDecl *caseDecl = resultType.get().getEnumElement(caseIdx); ++ swift::SILValue pl = payload.getSILValue(); ++ return {get().createEnum(regularLoc(), pl, caseDecl, resultType.get())}; ++} ++ ++BridgedInstruction BridgedBuilder::createBranch(BridgedBasicBlock destBlock, BridgedValueArray arguments) const { ++ llvm::SmallVector argValues; ++ return {get().createBranch(regularLoc(), destBlock.get(), arguments.getValues(argValues))}; ++} ++ ++BridgedInstruction BridgedBuilder::createUnreachable() const { ++ return {get().createUnreachable(regularLoc())}; ++} ++ ++BridgedInstruction BridgedBuilder::createObject(BridgedType type, ++ BridgedValueArray arguments, ++ SwiftInt numBaseElements) const { ++ llvm::SmallVector argValues; ++ return {get().createObject(swift::ArtificialUnreachableLocation(), ++ type.get(), arguments.getValues(argValues), numBaseElements)}; ++} ++ ++BridgedInstruction BridgedBuilder::createGlobalAddr(BridgedGlobalVar global) const { ++ return {get().createGlobalAddr(regularLoc(), global.getGlobal())}; ++} ++ ++BridgedInstruction BridgedBuilder::createGlobalValue(BridgedGlobalVar global, bool isBare) const { ++ return {get().createGlobalValue(regularLoc(), global.getGlobal(), isBare)}; ++} ++ ++BridgedInstruction BridgedBuilder::createSetDeallocating(BridgedValue op, bool isAtomic) const { ++ return {get().createSetDeallocating(regularLoc(), ++ op.getSILValue(), ++ isAtomic ? swift::RefCountingInst::Atomicity::Atomic ++ : swift::RefCountingInst::Atomicity::NonAtomic)}; ++} ++ ++BridgedInstruction BridgedBuilder::createStruct(BridgedType type, BridgedValueArray elements) const { ++ llvm::SmallVector elementValues; ++ return {get().createStruct(regularLoc(), type.get(), elements.getValues(elementValues))}; ++} ++ ++BridgedInstruction BridgedBuilder::createStructExtract(BridgedValue str, SwiftInt fieldIndex) const { ++ swift::SILValue v = str.getSILValue(); ++ return {get().createStructExtract(regularLoc(), v, v->getType().getFieldDecl(fieldIndex))}; ++} ++ ++BridgedInstruction BridgedBuilder::createStructElementAddr(BridgedValue addr, SwiftInt fieldIndex) const { ++ swift::SILValue v = addr.getSILValue(); ++ return {get().createStructElementAddr(regularLoc(), v, v->getType().getFieldDecl(fieldIndex))}; ++} ++ ++BridgedInstruction BridgedBuilder::createDestructureStruct(BridgedValue str) const { ++ return {get().createDestructureStruct(regularLoc(), str.getSILValue())}; ++} ++ ++BridgedInstruction BridgedBuilder::createTuple(BridgedType type, BridgedValueArray elements) const { ++ llvm::SmallVector elementValues; ++ return {get().createTuple(regularLoc(), type.get(), elements.getValues(elementValues))}; ++} ++ ++BridgedInstruction BridgedBuilder::createTupleExtract(BridgedValue str, SwiftInt elementIndex) const { ++ swift::SILValue v = str.getSILValue(); ++ return {get().createTupleExtract(regularLoc(), v, elementIndex)}; ++} ++ ++BridgedInstruction BridgedBuilder::createTupleElementAddr(BridgedValue addr, SwiftInt elementIndex) const { ++ swift::SILValue v = addr.getSILValue(); ++ return {get().createTupleElementAddr(regularLoc(), v, elementIndex)}; ++} ++ ++BridgedInstruction BridgedBuilder::createDestructureTuple(BridgedValue str) const { ++ return {get().createDestructureTuple(regularLoc(), str.getSILValue())}; ++} ++ ++BridgedInstruction BridgedBuilder::createStore(BridgedValue src, BridgedValue dst, ++ SwiftInt ownership) const { ++ return {get().createStore(regularLoc(), src.getSILValue(), dst.getSILValue(), ++ (swift::StoreOwnershipQualifier)ownership)}; ++} ++ ++BridgedInstruction BridgedBuilder::createInitExistentialRef(BridgedValue instance, ++ BridgedType type, ++ BridgedInstruction useConformancesOf) const { ++ auto *src = useConformancesOf.getAs(); ++ return {get().createInitExistentialRef(regularLoc(), type.get(), ++ src->getFormalConcreteType(), ++ instance.getSILValue(), ++ src->getConformances())}; ++} ++ ++BridgedInstruction BridgedBuilder::createMetatype(BridgedType type, ++ BridgedType::MetatypeRepresentation representation) const { ++ auto *mt = swift::MetatypeType::get(type.get().getASTType(), (swift::MetatypeRepresentation)representation); ++ auto t = swift::SILType::getPrimitiveObjectType(swift::CanType(mt)); ++ return {get().createMetatype(regularLoc(), t)}; ++} ++ ++BridgedInstruction BridgedBuilder::createEndCOWMutation(BridgedValue instance, bool keepUnique) const { ++ return {get().createEndCOWMutation(regularLoc(), instance.getSILValue(), keepUnique)}; ++} ++ ++//===----------------------------------------------------------------------===// ++// BridgedNominalTypeDecl ++//===----------------------------------------------------------------------===// ++ ++BridgedStringRef BridgedNominalTypeDecl::getName() const { ++ return decl->getName().str(); ++} ++ ++bool BridgedNominalTypeDecl::isGlobalActor() const { return decl->isGlobalActor(); } ++ ++ ++SWIFT_END_NULLABILITY_ANNOTATIONS ++ ++#endif +diff --git a/swift/include/swift/SIL/SILLocation.h b/swift/include/swift/SIL/SILLocation.h +index 671eb25443d..1e18af386ed 100644 +--- a/swift/include/swift/SIL/SILLocation.h ++++ b/swift/include/swift/SIL/SILLocation.h +@@ -730,8 +730,6 @@ public: + bool isAutoGenerated() const { return location.isAutoGenerated(); } + operator bool() const { return bool(location) && debugScope; } + +- std::string getDebugDescription() const; +- + SWIFT_IMPORT_UNSAFE + SILDebugLocation getAutogeneratedLocation() const { + SILDebugLocation autoGenLoc(RegularLocation::getAutoGeneratedLocation(), getScope()); +diff --git a/swift/include/swift/SILOptimizer/OptimizerBridging.h b/swift/include/swift/SILOptimizer/OptimizerBridging.h +index 54312f2b204..ecb7b846263 100644 +--- a/swift/include/swift/SILOptimizer/OptimizerBridging.h ++++ b/swift/include/swift/SILOptimizer/OptimizerBridging.h +@@ -13,27 +13,52 @@ + #ifndef SWIFT_SILOPTIMIZER_OPTIMIZERBRIDGING_H + #define SWIFT_SILOPTIMIZER_OPTIMIZERBRIDGING_H + +-#include "swift/Basic/Nullability.h" ++// Do not add other C++/llvm/swift header files here! ++// Function implementations should be placed into OptimizerBridgingImpl.h or PassManager.cpp ++// (under OptimizerBridging) andrequired header files should be added there. ++// + #include "swift/SIL/SILBridging.h" +-#include "swift/SILOptimizer/Analysis/AliasAnalysis.h" ++ ++#ifdef USED_IN_CPP_SOURCE ++ + #include "swift/SILOptimizer/Analysis/BasicCalleeAnalysis.h" +-#include "swift/SILOptimizer/Analysis/DeadEndBlocksAnalysis.h" +-#include "swift/SILOptimizer/Analysis/DominanceAnalysis.h" +-#include "swift/SILOptimizer/PassManager/PassManager.h" +-#include "swift/SILOptimizer/Utils/InstOptUtils.h" ++ ++#else // USED_IN_CPP_SOURCE ++ ++#ifdef SWIFT_SIL_SILVALUE_H ++#error "should not include swift headers into bridging header" ++#endif ++#ifdef LLVM_SUPPORT_COMPILER_H ++#error "should not include llvm headers into bridging header" ++#endif ++ ++#endif // USED_IN_CPP_SOURCE + + SWIFT_BEGIN_NULLABILITY_ANNOTATIONS + ++namespace swift { ++class AliasAnalysis; ++class BasicCalleeAnalysis; ++class DeadEndBlocks; ++class DominanceInfo; ++class PostDominanceInfo; ++class BasicBlockSet; ++class NodeSet; ++class ClonerWithFixedLocation; ++class SwiftPassInvocation; ++class FixedSizeSlabPayload; ++class FixedSizeSlab; ++class SILVTable; ++} ++ + struct BridgedPassContext; + + struct BridgedAliasAnalysis { + swift::AliasAnalysis * _Nonnull aa; + +- swift::MemoryBehavior getMemBehavior(BridgedInstruction inst, BridgedValue addr) const { +- return aa->computeMemoryBehavior(inst.getInst(), addr.getSILValue()); +- } ++ BRIDGED_INLINE BridgedMemoryBehavior getMemBehavior(BridgedInstruction inst, BridgedValue addr) const; + +- typedef swift::MemoryBehavior (* _Nonnull GetMemEffectFn)( ++ typedef BridgedMemoryBehavior (* _Nonnull GetMemEffectFn)( + BridgedPassContext context, BridgedValue, BridgedInstruction, SwiftInt); + typedef bool (* _Nonnull Escaping2InstFn)( + BridgedPassContext context, BridgedValue, BridgedInstruction, SwiftInt); +@@ -51,19 +76,28 @@ struct BridgedAliasAnalysis { + struct BridgedCalleeAnalysis { + swift::BasicCalleeAnalysis * _Nonnull ca; + +- SWIFT_IMPORT_UNSAFE +- swift::CalleeList getCallees(BridgedValue callee) const; ++ struct CalleeList { ++ uint64_t storage[3]; + +- SWIFT_IMPORT_UNSAFE +- swift::CalleeList getDestructors(swift::SILType type, bool isExactType) const; ++#ifdef USED_IN_CPP_SOURCE ++ CalleeList(swift::CalleeList list) { ++ *reinterpret_cast(&storage) = list; ++ } ++ swift::CalleeList get() const { ++ return *reinterpret_cast(&storage); ++ } ++#endif + +- SWIFT_IMPORT_UNSAFE +- static BridgedFunction getCallee(swift::CalleeList cl, SwiftInt index) { +- return {cl.get(index)}; +- } ++ BRIDGED_INLINE bool isIncomplete() const; ++ BRIDGED_INLINE SwiftInt getCount() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedFunction getCallee(SwiftInt index) const; ++ }; ++ ++ SWIFT_IMPORT_UNSAFE CalleeList getCallees(BridgedValue callee) const; ++ SWIFT_IMPORT_UNSAFE CalleeList getDestructors(BridgedType type, bool isExactType) const; + + typedef bool (* _Nonnull IsDeinitBarrierFn)(BridgedInstruction, BridgedCalleeAnalysis bca); +- typedef swift::MemoryBehavior (* _Nonnull GetMemBehvaiorFn)( ++ typedef BridgedMemoryBehavior (* _Nonnull GetMemBehvaiorFn)( + BridgedInstruction apply, bool observeRetains, BridgedCalleeAnalysis bca); + + static void registerAnalysis(IsDeinitBarrierFn isDeinitBarrierFn, +@@ -73,231 +107,114 @@ struct BridgedCalleeAnalysis { + struct BridgedDeadEndBlocksAnalysis { + swift::DeadEndBlocks * _Nonnull deb; + +- bool isDeadEnd(BridgedBasicBlock block) const { +- return deb->isDeadEnd(block.getBlock()); +- } ++ BRIDGED_INLINE bool isDeadEnd(BridgedBasicBlock block) const; + }; + + struct BridgedDomTree { + swift::DominanceInfo * _Nonnull di; + +- bool dominates(BridgedBasicBlock dominating, BridgedBasicBlock dominated) const { +- return di->dominates(dominating.getBlock(), dominated.getBlock()); +- } ++ BRIDGED_INLINE bool dominates(BridgedBasicBlock dominating, BridgedBasicBlock dominated) const; + }; + +-struct BridgedBasicBlockSet { +- swift::BasicBlockSet * _Nonnull set; +- +- bool contains(BridgedBasicBlock block) const { +- return set->contains(block.getBlock()); +- } ++struct BridgedPostDomTree { ++ swift::PostDominanceInfo * _Nonnull pdi; + +- bool insert(BridgedBasicBlock block) const { +- return set->insert(block.getBlock()); +- } ++ BRIDGED_INLINE bool postDominates(BridgedBasicBlock dominating, BridgedBasicBlock dominated) const; ++}; + +- void erase(BridgedBasicBlock block) const { +- set->erase(block.getBlock()); +- } ++struct BridgedBasicBlockSet { ++ swift::BasicBlockSet * _Nonnull set; + +- SWIFT_IMPORT_UNSAFE +- BridgedFunction getFunction() const { +- return {set->getFunction()}; +- } ++ BRIDGED_INLINE bool contains(BridgedBasicBlock block) const; ++ BRIDGED_INLINE bool insert(BridgedBasicBlock block) const; ++ BRIDGED_INLINE void erase(BridgedBasicBlock block) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedFunction getFunction() const; + }; + + struct BridgedNodeSet { + swift::NodeSet * _Nonnull set; + +- bool containsValue(BridgedValue value) const { +- return set->contains(value.getSILValue()); +- } +- +- bool insertValue(BridgedValue value) const { +- return set->insert(value.getSILValue()); +- } +- +- void eraseValue(BridgedValue value) const { +- set->erase(value.getSILValue()); +- } +- +- bool containsInstruction(BridgedInstruction inst) const { +- return set->contains(inst.getInst()->asSILNode()); +- } +- +- bool insertInstruction(BridgedInstruction inst) const { +- return set->insert(inst.getInst()->asSILNode()); +- } +- +- void eraseInstruction(BridgedInstruction inst) const { +- set->erase(inst.getInst()->asSILNode()); +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedFunction getFunction() const { +- return {set->getFunction()}; +- } ++ BRIDGED_INLINE bool containsValue(BridgedValue value) const; ++ BRIDGED_INLINE bool insertValue(BridgedValue value) const; ++ BRIDGED_INLINE void eraseValue(BridgedValue value) const; ++ BRIDGED_INLINE bool containsInstruction(BridgedInstruction inst) const; ++ BRIDGED_INLINE bool insertInstruction(BridgedInstruction inst) const; ++ BRIDGED_INLINE void eraseInstruction(BridgedInstruction inst) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedFunction getFunction() const; + }; + +-namespace swift { +-class ClonerWithFixedLocation; +-} +- + struct BridgedCloner { + swift::ClonerWithFixedLocation * _Nonnull cloner; + + BridgedCloner(BridgedGlobalVar var, BridgedPassContext context); +- + BridgedCloner(BridgedInstruction inst, BridgedPassContext context); +- + void destroy(BridgedPassContext context); +- +- SWIFT_IMPORT_UNSAFE +- BridgedValue getClonedValue(BridgedValue v); +- ++ SWIFT_IMPORT_UNSAFE BridgedValue getClonedValue(BridgedValue v); + bool isValueCloned(BridgedValue v) const; +- + void clone(BridgedInstruction inst); + }; + +-struct BridgedPostDomTree { +- swift::PostDominanceInfo * _Nonnull pdi; +- +- bool postDominates(BridgedBasicBlock dominating, BridgedBasicBlock dominated) const { +- return pdi->dominates(dominating.getBlock(), dominated.getBlock()); +- } +-}; +- + struct BridgedPassContext { + swift::SwiftPassInvocation * _Nonnull invocation; + +- std::string getModuleDescription() const; ++ enum class SILStage { ++ Raw, ++ Canonical, ++ Lowered ++ }; ++ ++ SWIFT_IMPORT_UNSAFE BridgedOwnedString getModuleDescription() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedChangeNotificationHandler asNotificationHandler() const; + +- SWIFT_IMPORT_UNSAFE +- BridgedChangeNotificationHandler asNotificationHandler() const { +- return {invocation}; +- } + // Analysis + +- SWIFT_IMPORT_UNSAFE +- BridgedAliasAnalysis getAliasAnalysis() const { +- return {invocation->getPassManager()->getAnalysis(invocation->getFunction())}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedCalleeAnalysis getCalleeAnalysis() const { +- return {invocation->getPassManager()->getAnalysis()}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedDeadEndBlocksAnalysis getDeadEndBlocksAnalysis() const { +- auto *dba = invocation->getPassManager()->getAnalysis(); +- return {dba->get(invocation->getFunction())}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedDomTree getDomTree() const { +- auto *da = invocation->getPassManager()->getAnalysis(); +- return {da->get(invocation->getFunction())}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedPostDomTree getPostDomTree() const { +- auto *pda = invocation->getPassManager()->getAnalysis(); +- return {pda->get(invocation->getFunction())}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedNominalTypeDecl getSwiftArrayDecl() const { +- swift::SILModule *mod = invocation->getPassManager()->getModule(); +- return {mod->getASTContext().getArrayDecl()}; +- } ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedAliasAnalysis getAliasAnalysis() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedCalleeAnalysis getCalleeAnalysis() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedDeadEndBlocksAnalysis getDeadEndBlocksAnalysis() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedDomTree getDomTree() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedPostDomTree getPostDomTree() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedNominalTypeDecl getSwiftArrayDecl() const; + + // SIL modifications + +- SWIFT_IMPORT_UNSAFE +- BridgedBasicBlock splitBlock(BridgedInstruction bridgedInst) const { +- auto *inst = bridgedInst.getInst(); +- auto *block = inst->getParent(); +- return {block->split(inst->getIterator())}; +- } +- +- void eraseInstruction(BridgedInstruction inst) const { +- invocation->eraseInstruction(inst.getInst()); +- } +- +- void eraseBlock(BridgedBasicBlock block) const { +- block.getBlock()->eraseFromParent(); +- } +- +- bool tryOptimizeApplyOfPartialApply(BridgedInstruction closure) const; +- +- bool tryDeleteDeadClosure(BridgedInstruction closure, bool needKeepArgsAlive) const; +- + struct DevirtResult { + OptionalBridgedInstruction newApply; + bool cfgChanged; + }; + +- SWIFT_IMPORT_UNSAFE +- DevirtResult tryDevirtualizeApply(BridgedInstruction apply, bool isMandatory) const; +- +- SWIFT_IMPORT_UNSAFE +- OptionalBridgedValue constantFoldBuiltin(BridgedInstruction builtin) const; +- ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlock splitBlock(BridgedInstruction bridgedInst) const; ++ BRIDGED_INLINE void eraseInstruction(BridgedInstruction inst) const; ++ BRIDGED_INLINE void eraseBlock(BridgedBasicBlock block) const; ++ bool tryOptimizeApplyOfPartialApply(BridgedInstruction closure) const; ++ bool tryDeleteDeadClosure(BridgedInstruction closure, bool needKeepArgsAlive) const; ++ SWIFT_IMPORT_UNSAFE DevirtResult tryDevirtualizeApply(BridgedInstruction apply, bool isMandatory) const; ++ SWIFT_IMPORT_UNSAFE OptionalBridgedValue constantFoldBuiltin(BridgedInstruction builtin) const; + bool specializeAppliesInFunction(BridgedFunction function, bool isMandatory) const; +- +- std::string mangleOutlinedVariable(BridgedFunction function) const; +- +- SWIFT_IMPORT_UNSAFE +- BridgedGlobalVar createGlobalVariable(llvm::StringRef name, swift::SILType type, bool isPrivate) const; +- ++ SWIFT_IMPORT_UNSAFE BridgedOwnedString mangleOutlinedVariable(BridgedFunction function) const; ++ SWIFT_IMPORT_UNSAFE BridgedGlobalVar createGlobalVariable(BridgedStringRef name, BridgedType type, ++ bool isPrivate) const; + void inlineFunction(BridgedInstruction apply, bool mandatoryInline) const; +- +- SWIFT_IMPORT_UNSAFE +- BridgedValue getSILUndef(swift::SILType type) const { +- return {swift::SILUndef::get(type, *invocation->getFunction())}; +- } ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedValue getSILUndef(BridgedType type) const; ++ BRIDGED_INLINE static bool optimizeMemoryAccesses(BridgedFunction f); ++ BRIDGED_INLINE static bool eliminateDeadAllocations(BridgedFunction f); + + // IRGen + +- SwiftInt getStaticSize(swift::SILType type) const; +- +- SwiftInt getStaticAlignment(swift::SILType type) const; +- +- SwiftInt getStaticStride(swift::SILType type) const; ++ SwiftInt getStaticSize(BridgedType type) const; ++ SwiftInt getStaticAlignment(BridgedType type) const; ++ SwiftInt getStaticStride(BridgedType type) const; + + // Sets + +- SWIFT_IMPORT_UNSAFE +- BridgedBasicBlockSet allocBasicBlockSet() const { +- return {invocation->allocBlockSet()}; +- } +- +- void freeBasicBlockSet(BridgedBasicBlockSet set) const { +- invocation->freeBlockSet(set.set); +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedNodeSet allocNodeSet() const { +- return {invocation->allocNodeSet()}; +- } +- +- void freeNodeSet(BridgedNodeSet set) const { +- invocation->freeNodeSet(set.set); +- } ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlockSet allocBasicBlockSet() const; ++ BRIDGED_INLINE void freeBasicBlockSet(BridgedBasicBlockSet set) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedNodeSet allocNodeSet() const; ++ BRIDGED_INLINE void freeNodeSet(BridgedNodeSet set) const; + + // Stack nesting + +- void notifyInvalidatedStackNesting() const { +- invocation->setNeedFixStackNesting(true); +- } +- +- bool getNeedFixStackNesting() const { +- return invocation->getNeedFixStackNesting(); +- } +- ++ BRIDGED_INLINE void notifyInvalidatedStackNesting() const; ++ BRIDGED_INLINE bool getNeedFixStackNesting() const; + void fixStackNesting(BridgedFunction function) const; + + // Slabs +@@ -305,216 +222,65 @@ struct BridgedPassContext { + struct Slab { + swift::FixedSizeSlabPayload * _Nullable data = nullptr; + +- static SwiftInt getCapacity() { +- return (SwiftInt)swift::FixedSizeSlabPayload::capacity; +- } +- +- Slab(swift::FixedSizeSlab * _Nullable slab) { +- if (slab) { +- data = slab; +- assert((void *)data == slab->dataFor()); +- } +- } +- +- swift::FixedSizeSlab * _Nullable getSlab() const { +- if (data) +- return static_cast(data); +- return nullptr; +- } +- +- SWIFT_IMPORT_UNSAFE +- Slab getNext() const { +- return &*std::next(getSlab()->getIterator()); +- } +- +- SWIFT_IMPORT_UNSAFE +- Slab getPrevious() const { +- return &*std::prev(getSlab()->getIterator()); +- } ++ BRIDGED_INLINE static SwiftInt getCapacity(); ++ BRIDGED_INLINE Slab(swift::FixedSizeSlab * _Nullable slab); ++ BRIDGED_INLINE swift::FixedSizeSlab * _Nullable getSlab() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE Slab getNext() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE Slab getPrevious() const; + }; + +- SWIFT_IMPORT_UNSAFE +- Slab allocSlab(Slab afterSlab) const { +- return invocation->allocSlab(afterSlab.getSlab()); +- } +- +- SWIFT_IMPORT_UNSAFE +- Slab freeSlab(Slab slab) const { +- return invocation->freeSlab(slab.getSlab()); +- } ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE Slab allocSlab(Slab afterSlab) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE Slab freeSlab(Slab slab) const; + + // Access SIL module data structures + +- SWIFT_IMPORT_UNSAFE +- OptionalBridgedFunction getFirstFunctionInModule() const { +- swift::SILModule *mod = invocation->getPassManager()->getModule(); +- if (mod->getFunctions().empty()) +- return {nullptr}; +- return {&*mod->getFunctions().begin()}; +- } +- +- SWIFT_IMPORT_UNSAFE +- static OptionalBridgedFunction getNextFunctionInModule(BridgedFunction function) { +- auto *f = function.getFunction(); +- auto nextIter = std::next(f->getIterator()); +- if (nextIter == f->getModule().getFunctions().end()) +- return {nullptr}; +- return {&*nextIter}; +- } +- +- SWIFT_IMPORT_UNSAFE +- OptionalBridgedGlobalVar getFirstGlobalInModule() const { +- swift::SILModule *mod = invocation->getPassManager()->getModule(); +- if (mod->getSILGlobals().empty()) +- return {nullptr}; +- return {&*mod->getSILGlobals().begin()}; +- } +- +- SWIFT_IMPORT_UNSAFE +- static OptionalBridgedGlobalVar getNextGlobalInModule(BridgedGlobalVar global) { +- auto *g = global.getGlobal(); +- auto nextIter = std::next(g->getIterator()); +- if (nextIter == g->getModule().getSILGlobals().end()) +- return {nullptr}; +- return {&*nextIter}; +- } +- + struct VTableArray { + swift::SILVTable * const _Nonnull * _Nullable base; + SwiftInt count; + }; + +- SWIFT_IMPORT_UNSAFE +- VTableArray getVTables() const { +- swift::SILModule *mod = invocation->getPassManager()->getModule(); +- auto vTables = mod->getVTables(); +- return {vTables.data(), (SwiftInt)vTables.size()}; +- } +- +- SWIFT_IMPORT_UNSAFE +- OptionalBridgedWitnessTable getFirstWitnessTableInModule() const { +- swift::SILModule *mod = invocation->getPassManager()->getModule(); +- if (mod->getWitnessTables().empty()) +- return {nullptr}; +- return {&*mod->getWitnessTables().begin()}; +- } +- +- SWIFT_IMPORT_UNSAFE +- static OptionalBridgedWitnessTable getNextWitnessTableInModule(BridgedWitnessTable table) { +- auto *t = table.table; +- auto nextIter = std::next(t->getIterator()); +- if (nextIter == t->getModule().getWitnessTables().end()) +- return {nullptr}; +- return {&*nextIter}; +- } +- +- SWIFT_IMPORT_UNSAFE +- OptionalBridgedDefaultWitnessTable getFirstDefaultWitnessTableInModule() const { +- swift::SILModule *mod = invocation->getPassManager()->getModule(); +- if (mod->getDefaultWitnessTables().empty()) +- return {nullptr}; +- return {&*mod->getDefaultWitnessTables().begin()}; +- } +- +- SWIFT_IMPORT_UNSAFE +- static OptionalBridgedDefaultWitnessTable getNextDefaultWitnessTableInModule(BridgedDefaultWitnessTable table) { +- auto *t = table.table; +- auto nextIter = std::next(t->getIterator()); +- if (nextIter == t->getModule().getDefaultWitnessTables().end()) +- return {nullptr}; +- return {&*nextIter}; +- } +- +- SWIFT_IMPORT_UNSAFE +- OptionalBridgedFunction loadFunction(llvm::StringRef name, bool loadCalleesRecursively) const { +- swift::SILModule *mod = invocation->getPassManager()->getModule(); +- return {mod->loadFunction(name, loadCalleesRecursively ? swift::SILModule::LinkingMode::LinkAll +- : swift::SILModule::LinkingMode::LinkNormal)}; +- } +- +- SWIFT_IMPORT_UNSAFE +- void loadFunction(BridgedFunction function, bool loadCalleesRecursively) const { +- swift::SILModule *mod = invocation->getPassManager()->getModule(); +- mod->loadFunction(function.getFunction(), +- loadCalleesRecursively ? swift::SILModule::LinkingMode::LinkAll +- : swift::SILModule::LinkingMode::LinkNormal); +- } +- +- SWIFT_IMPORT_UNSAFE +- OptionalBridgedFunction lookupStdlibFunction(llvm::StringRef name) const; +- +- SWIFT_IMPORT_UNSAFE +- swift::SubstitutionMap getContextSubstitutionMap(swift::SILType type) const { +- auto *ntd = type.getASTType()->getAnyNominal(); +- auto *mod = invocation->getPassManager()->getModule()->getSwiftModule(); +- return type.getASTType()->getContextSubstitutionMap(mod, ntd); +- } ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedFunction getFirstFunctionInModule() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE static OptionalBridgedFunction getNextFunctionInModule(BridgedFunction function); ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedGlobalVar getFirstGlobalInModule() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE static OptionalBridgedGlobalVar getNextGlobalInModule(BridgedGlobalVar global); ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE VTableArray getVTables() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedWitnessTable getFirstWitnessTableInModule() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE static OptionalBridgedWitnessTable getNextWitnessTableInModule( ++ BridgedWitnessTable table); ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedDefaultWitnessTable getFirstDefaultWitnessTableInModule() const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE static OptionalBridgedDefaultWitnessTable getNextDefaultWitnessTableInModule( ++ BridgedDefaultWitnessTable table); ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedFunction loadFunction(BridgedStringRef name, ++ bool loadCalleesRecursively) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE void loadFunction(BridgedFunction function, bool loadCalleesRecursively) const; ++ SWIFT_IMPORT_UNSAFE OptionalBridgedFunction lookupStdlibFunction(BridgedStringRef name) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedSubstitutionMap getContextSubstitutionMap(BridgedType type) const; + + // Passmanager housekeeping + +- void beginTransformFunction(BridgedFunction function) const { +- invocation->beginTransformFunction(function.getFunction()); +- } +- +- void endTransformFunction() const { +- invocation->endTransformFunction(); +- } +- +- bool continueWithNextSubpassRun(OptionalBridgedInstruction inst) const { +- swift::SILPassManager *pm = invocation->getPassManager(); +- return pm->continueWithNextSubpassRun(inst.getInst(), +- invocation->getFunction(), +- invocation->getTransform()); +- } ++ BRIDGED_INLINE void beginTransformFunction(BridgedFunction function) const; ++ BRIDGED_INLINE void endTransformFunction() const; ++ BRIDGED_INLINE bool continueWithNextSubpassRun(OptionalBridgedInstruction inst) const; + + // SSAUpdater + +- void SSAUpdater_initialize(swift::SILType type, BridgedValue::Ownership ownership) const { +- invocation->initializeSSAUpdater(type, castToOwnership(ownership)); +- } +- +- void SSAUpdater_addAvailableValue(BridgedBasicBlock block, BridgedValue value) const { +- invocation->getSSAUpdater()->addAvailableValue(block.getBlock(), value.getSILValue()); +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedValue SSAUpdater_getValueAtEndOfBlock(BridgedBasicBlock block) const { +- return {invocation->getSSAUpdater()->getValueAtEndOfBlock(block.getBlock())}; +- } +- +- SWIFT_IMPORT_UNSAFE +- BridgedValue SSAUpdater_getValueInMiddleOfBlock(BridgedBasicBlock block) const { +- return {invocation->getSSAUpdater()->getValueInMiddleOfBlock(block.getBlock())}; +- } ++ BRIDGED_INLINE void SSAUpdater_initialize(BridgedType type, BridgedValue::Ownership ownership) const; ++ BRIDGED_INLINE void SSAUpdater_addAvailableValue(BridgedBasicBlock block, BridgedValue value) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedValue SSAUpdater_getValueAtEndOfBlock(BridgedBasicBlock block) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedValue SSAUpdater_getValueInMiddleOfBlock(BridgedBasicBlock block) const; + + // Options + +- bool enableStackProtection() const { +- swift::SILModule *mod = invocation->getPassManager()->getModule(); +- return mod->getOptions().EnableStackProtection; +- } +- +- bool enableEmbeddedSwift() const { +- swift::SILModule *mod = invocation->getPassManager()->getModule(); +- return mod->getASTContext().LangOpts.hasFeature(swift::Feature::Embedded); +- } +- +- bool enableMoveInoutStackProtection() const { +- swift::SILModule *mod = invocation->getPassManager()->getModule(); +- return mod->getOptions().EnableMoveInoutStackProtection; +- } +- + enum class AssertConfiguration { +- Debug = swift::SILOptions::Debug, +- Release = swift::SILOptions::Release, +- Unchecked = swift::SILOptions::Unchecked ++ Debug = 0, ++ Release = 1, ++ Unchecked = 2 + }; + +- AssertConfiguration getAssertConfiguration() const { +- swift::SILModule *mod = invocation->getPassManager()->getModule(); +- return (AssertConfiguration)mod->getOptions().AssertConfig; +- } +- ++ BRIDGED_INLINE bool enableStackProtection() const; ++ BRIDGED_INLINE bool enableEmbeddedSwift() const; ++ BRIDGED_INLINE bool enableMoveInoutStackProtection() const; ++ BRIDGED_INLINE AssertConfiguration getAssertConfiguration() const; + bool enableSimplificationFor(BridgedInstruction inst) const; + }; + +@@ -538,13 +304,18 @@ typedef void (* _Nonnull BridgedModulePassRunFn)(BridgedPassContext); + typedef void (* _Nonnull BridgedFunctionPassRunFn)(BridgedFunctionPassCtxt); + typedef void (* _Nonnull BridgedInstructionPassRunFn)(BridgedInstructionPassCtxt); + +-void SILPassManager_registerModulePass(llvm::StringRef name, ++void SILPassManager_registerModulePass(BridgedStringRef name, + BridgedModulePassRunFn runFn); +-void SILPassManager_registerFunctionPass(llvm::StringRef name, ++void SILPassManager_registerFunctionPass(BridgedStringRef name, + BridgedFunctionPassRunFn runFn); +-void SILCombine_registerInstructionPass(llvm::StringRef instClassName, ++void SILCombine_registerInstructionPass(BridgedStringRef instClassName, + BridgedInstructionPassRunFn runFn); + ++#ifndef PURE_BRIDGING_MODE ++// In _not_ PURE_BRIDGING_MODE, briding functions are inlined and therefore inluded in the header file. ++#include "OptimizerBridgingImpl.h" ++#endif ++ + SWIFT_END_NULLABILITY_ANNOTATIONS + + #endif +diff --git a/swift/include/swift/SILOptimizer/OptimizerBridgingImpl.h b/swift/include/swift/SILOptimizer/OptimizerBridgingImpl.h +new file mode 100644 +index 00000000000..798efc6ec57 +--- /dev/null ++++ b/swift/include/swift/SILOptimizer/OptimizerBridgingImpl.h +@@ -0,0 +1,397 @@ ++//===--- OptimizerBridgingImpl.h ------------------------------------------===// ++// ++// This source file is part of the Swift.org open source project ++// ++// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors ++// Licensed under Apache License v2.0 with Runtime Library Exception ++// ++// See https://swift.org/LICENSE.txt for license information ++// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors ++// ++//===----------------------------------------------------------------------===// ++// ++// This file contains the implementation of bridging functions, which are either ++// - depending on if PURE_BRIDGING_MODE is set - included in the cpp file or ++// in the header file. ++// ++//===----------------------------------------------------------------------===// ++ ++#ifndef SWIFT_SILOPTIMIZER_OPTIMIZERBRIDGING_IMPL_H ++#define SWIFT_SILOPTIMIZER_OPTIMIZERBRIDGING_IMPL_H ++ ++#include "swift/SILOptimizer/OptimizerBridging.h" ++#include "swift/SILOptimizer/Analysis/AliasAnalysis.h" ++#include "swift/SILOptimizer/Analysis/BasicCalleeAnalysis.h" ++#include "swift/SILOptimizer/Analysis/DeadEndBlocksAnalysis.h" ++#include "swift/SILOptimizer/Analysis/DominanceAnalysis.h" ++#include "swift/SILOptimizer/PassManager/PassManager.h" ++#include "swift/SILOptimizer/Utils/InstOptUtils.h" ++ ++SWIFT_BEGIN_NULLABILITY_ANNOTATIONS ++ ++//===----------------------------------------------------------------------===// ++// BridgedAliasAnalysis ++//===----------------------------------------------------------------------===// ++ ++BridgedMemoryBehavior BridgedAliasAnalysis::getMemBehavior(BridgedInstruction inst, BridgedValue addr) const { ++ return (BridgedMemoryBehavior)aa->computeMemoryBehavior(inst.get(), addr.getSILValue()); ++} ++ ++//===----------------------------------------------------------------------===// ++// BridgedCalleeAnalysis ++//===----------------------------------------------------------------------===// ++ ++static_assert(sizeof(BridgedCalleeAnalysis::CalleeList) >= sizeof(swift::CalleeList), ++ "BridgedCalleeAnalysis::CalleeList has wrong size"); ++ ++bool BridgedCalleeAnalysis::CalleeList::isIncomplete() const { ++ return get().isIncomplete(); ++} ++ ++SwiftInt BridgedCalleeAnalysis::CalleeList::getCount() const { ++ return get().getCount(); ++} ++ ++BridgedFunction BridgedCalleeAnalysis::CalleeList::getCallee(SwiftInt index) const { ++ return {get().get((unsigned)index)}; ++} ++ ++//===----------------------------------------------------------------------===// ++// BridgedDeadEndBlocksAnalysis ++//===----------------------------------------------------------------------===// ++ ++bool BridgedDeadEndBlocksAnalysis::isDeadEnd(BridgedBasicBlock block) const { ++ return deb->isDeadEnd(block.get()); ++} ++ ++//===----------------------------------------------------------------------===// ++// BridgedDomTree, BridgedPostDomTree ++//===----------------------------------------------------------------------===// ++ ++bool BridgedDomTree::dominates(BridgedBasicBlock dominating, BridgedBasicBlock dominated) const { ++ return di->dominates(dominating.get(), dominated.get()); ++} ++ ++bool BridgedPostDomTree::postDominates(BridgedBasicBlock dominating, BridgedBasicBlock dominated) const { ++ return pdi->dominates(dominating.get(), dominated.get()); ++} ++ ++//===----------------------------------------------------------------------===// ++// BridgedBasicBlockSet ++//===----------------------------------------------------------------------===// ++ ++bool BridgedBasicBlockSet::contains(BridgedBasicBlock block) const { ++ return set->contains(block.get()); ++} ++ ++bool BridgedBasicBlockSet::insert(BridgedBasicBlock block) const { ++ return set->insert(block.get()); ++} ++ ++void BridgedBasicBlockSet::erase(BridgedBasicBlock block) const { ++ set->erase(block.get()); ++} ++ ++BridgedFunction BridgedBasicBlockSet::getFunction() const { ++ return {set->getFunction()}; ++} ++ ++//===----------------------------------------------------------------------===// ++// BridgedNodeSet ++//===----------------------------------------------------------------------===// ++ ++bool BridgedNodeSet::containsValue(BridgedValue value) const { ++ return set->contains(value.getSILValue()); ++} ++ ++bool BridgedNodeSet::insertValue(BridgedValue value) const { ++ return set->insert(value.getSILValue()); ++} ++ ++void BridgedNodeSet::eraseValue(BridgedValue value) const { ++ set->erase(value.getSILValue()); ++} ++ ++bool BridgedNodeSet::containsInstruction(BridgedInstruction inst) const { ++ return set->contains(inst.get()->asSILNode()); ++} ++ ++bool BridgedNodeSet::insertInstruction(BridgedInstruction inst) const { ++ return set->insert(inst.get()->asSILNode()); ++} ++ ++void BridgedNodeSet::eraseInstruction(BridgedInstruction inst) const { ++ set->erase(inst.get()->asSILNode()); ++} ++ ++BridgedFunction BridgedNodeSet::getFunction() const { ++ return {set->getFunction()}; ++} ++ ++//===----------------------------------------------------------------------===// ++// BridgedPassContext ++//===----------------------------------------------------------------------===// ++ ++BridgedChangeNotificationHandler BridgedPassContext::asNotificationHandler() const { ++ return {invocation}; ++} ++ ++BridgedAliasAnalysis BridgedPassContext::getAliasAnalysis() const { ++ return {invocation->getPassManager()->getAnalysis(invocation->getFunction())}; ++} ++ ++BridgedCalleeAnalysis BridgedPassContext::getCalleeAnalysis() const { ++ return {invocation->getPassManager()->getAnalysis()}; ++} ++ ++BridgedDeadEndBlocksAnalysis BridgedPassContext::getDeadEndBlocksAnalysis() const { ++ auto *dba = invocation->getPassManager()->getAnalysis(); ++ return {dba->get(invocation->getFunction())}; ++} ++ ++BridgedDomTree BridgedPassContext::getDomTree() const { ++ auto *da = invocation->getPassManager()->getAnalysis(); ++ return {da->get(invocation->getFunction())}; ++} ++ ++BridgedPostDomTree BridgedPassContext::getPostDomTree() const { ++ auto *pda = invocation->getPassManager()->getAnalysis(); ++ return {pda->get(invocation->getFunction())}; ++} ++ ++BridgedNominalTypeDecl BridgedPassContext::getSwiftArrayDecl() const { ++ swift::SILModule *mod = invocation->getPassManager()->getModule(); ++ return {mod->getASTContext().getArrayDecl()}; ++} ++ ++// SIL modifications ++ ++BridgedBasicBlock BridgedPassContext::splitBlock(BridgedInstruction bridgedInst) const { ++ auto *block = bridgedInst.get()->getParent(); ++ return {block->split(bridgedInst.get()->getIterator())}; ++} ++ ++void BridgedPassContext::eraseInstruction(BridgedInstruction inst) const { ++ invocation->eraseInstruction(inst.get()); ++} ++ ++void BridgedPassContext::eraseBlock(BridgedBasicBlock block) const { ++ block.get()->eraseFromParent(); ++} ++ ++BridgedValue BridgedPassContext::getSILUndef(BridgedType type) const { ++ return {swift::SILUndef::get(type.get(), *invocation->getFunction())}; ++} ++ ++bool BridgedPassContext::optimizeMemoryAccesses(BridgedFunction f) { ++ return swift::optimizeMemoryAccesses(f.getFunction()); ++} ++bool BridgedPassContext::eliminateDeadAllocations(BridgedFunction f) { ++ return swift::eliminateDeadAllocations(f.getFunction()); ++} ++ ++BridgedBasicBlockSet BridgedPassContext::allocBasicBlockSet() const { ++ return {invocation->allocBlockSet()}; ++} ++ ++void BridgedPassContext::freeBasicBlockSet(BridgedBasicBlockSet set) const { ++ invocation->freeBlockSet(set.set); ++} ++ ++BridgedNodeSet BridgedPassContext::allocNodeSet() const { ++ return {invocation->allocNodeSet()}; ++} ++ ++void BridgedPassContext::freeNodeSet(BridgedNodeSet set) const { ++ invocation->freeNodeSet(set.set); ++} ++ ++void BridgedPassContext::notifyInvalidatedStackNesting() const { ++ invocation->setNeedFixStackNesting(true); ++} ++ ++bool BridgedPassContext::getNeedFixStackNesting() const { ++ return invocation->getNeedFixStackNesting(); ++} ++ ++SwiftInt BridgedPassContext::Slab::getCapacity() { ++ return (SwiftInt)swift::FixedSizeSlabPayload::capacity; ++} ++ ++BridgedPassContext::Slab::Slab(swift::FixedSizeSlab * _Nullable slab) { ++ if (slab) { ++ data = slab; ++ assert((void *)data == slab->dataFor()); ++ } ++} ++ ++swift::FixedSizeSlab * _Nullable BridgedPassContext::Slab::getSlab() const { ++ if (data) ++ return static_cast(data); ++ return nullptr; ++} ++ ++BridgedPassContext::Slab BridgedPassContext::Slab::getNext() const { ++ return &*std::next(getSlab()->getIterator()); ++} ++ ++BridgedPassContext::Slab BridgedPassContext::Slab::getPrevious() const { ++ return &*std::prev(getSlab()->getIterator()); ++} ++ ++BridgedPassContext::Slab BridgedPassContext::allocSlab(Slab afterSlab) const { ++ return invocation->allocSlab(afterSlab.getSlab()); ++} ++ ++BridgedPassContext::Slab BridgedPassContext::freeSlab(Slab slab) const { ++ return invocation->freeSlab(slab.getSlab()); ++} ++ ++OptionalBridgedFunction BridgedPassContext::getFirstFunctionInModule() const { ++ swift::SILModule *mod = invocation->getPassManager()->getModule(); ++ if (mod->getFunctions().empty()) ++ return {nullptr}; ++ return {&*mod->getFunctions().begin()}; ++} ++ ++OptionalBridgedFunction BridgedPassContext::getNextFunctionInModule(BridgedFunction function) { ++ auto *f = function.getFunction(); ++ auto nextIter = std::next(f->getIterator()); ++ if (nextIter == f->getModule().getFunctions().end()) ++ return {nullptr}; ++ return {&*nextIter}; ++} ++ ++OptionalBridgedGlobalVar BridgedPassContext::getFirstGlobalInModule() const { ++ swift::SILModule *mod = invocation->getPassManager()->getModule(); ++ if (mod->getSILGlobals().empty()) ++ return {nullptr}; ++ return {&*mod->getSILGlobals().begin()}; ++} ++ ++OptionalBridgedGlobalVar BridgedPassContext::getNextGlobalInModule(BridgedGlobalVar global) { ++ auto *g = global.getGlobal(); ++ auto nextIter = std::next(g->getIterator()); ++ if (nextIter == g->getModule().getSILGlobals().end()) ++ return {nullptr}; ++ return {&*nextIter}; ++} ++ ++BridgedPassContext::VTableArray BridgedPassContext::getVTables() const { ++ swift::SILModule *mod = invocation->getPassManager()->getModule(); ++ auto vTables = mod->getVTables(); ++ return {vTables.data(), (SwiftInt)vTables.size()}; ++} ++ ++OptionalBridgedWitnessTable BridgedPassContext::getFirstWitnessTableInModule() const { ++ swift::SILModule *mod = invocation->getPassManager()->getModule(); ++ if (mod->getWitnessTables().empty()) ++ return {nullptr}; ++ return {&*mod->getWitnessTables().begin()}; ++} ++ ++OptionalBridgedWitnessTable BridgedPassContext::getNextWitnessTableInModule(BridgedWitnessTable table) { ++ auto *t = table.table; ++ auto nextIter = std::next(t->getIterator()); ++ if (nextIter == t->getModule().getWitnessTables().end()) ++ return {nullptr}; ++ return {&*nextIter}; ++} ++ ++OptionalBridgedDefaultWitnessTable BridgedPassContext::getFirstDefaultWitnessTableInModule() const { ++ swift::SILModule *mod = invocation->getPassManager()->getModule(); ++ if (mod->getDefaultWitnessTables().empty()) ++ return {nullptr}; ++ return {&*mod->getDefaultWitnessTables().begin()}; ++} ++ ++OptionalBridgedDefaultWitnessTable BridgedPassContext:: ++getNextDefaultWitnessTableInModule(BridgedDefaultWitnessTable table) { ++ auto *t = table.table; ++ auto nextIter = std::next(t->getIterator()); ++ if (nextIter == t->getModule().getDefaultWitnessTables().end()) ++ return {nullptr}; ++ return {&*nextIter}; ++} ++ ++OptionalBridgedFunction BridgedPassContext::loadFunction(BridgedStringRef name, bool loadCalleesRecursively) const { ++ swift::SILModule *mod = invocation->getPassManager()->getModule(); ++ return {mod->loadFunction(name.get(), ++ loadCalleesRecursively ? swift::SILModule::LinkingMode::LinkAll ++ : swift::SILModule::LinkingMode::LinkNormal)}; ++} ++ ++void BridgedPassContext::loadFunction(BridgedFunction function, bool loadCalleesRecursively) const { ++ swift::SILModule *mod = invocation->getPassManager()->getModule(); ++ mod->loadFunction(function.getFunction(), ++ loadCalleesRecursively ? swift::SILModule::LinkingMode::LinkAll ++ : swift::SILModule::LinkingMode::LinkNormal); ++} ++ ++BridgedSubstitutionMap BridgedPassContext::getContextSubstitutionMap(BridgedType type) const { ++ swift::SILType ty = type.get(); ++ auto *ntd = ty.getASTType()->getAnyNominal(); ++ auto *mod = invocation->getPassManager()->getModule()->getSwiftModule(); ++ return ty.getASTType()->getContextSubstitutionMap(mod, ntd); ++} ++ ++void BridgedPassContext::beginTransformFunction(BridgedFunction function) const { ++ invocation->beginTransformFunction(function.getFunction()); ++} ++ ++void BridgedPassContext::endTransformFunction() const { ++ invocation->endTransformFunction(); ++} ++ ++bool BridgedPassContext::continueWithNextSubpassRun(OptionalBridgedInstruction inst) const { ++ swift::SILPassManager *pm = invocation->getPassManager(); ++ return pm->continueWithNextSubpassRun(inst.get(), invocation->getFunction(), invocation->getTransform()); ++} ++ ++void BridgedPassContext::SSAUpdater_initialize(BridgedType type, BridgedValue::Ownership ownership) const { ++ invocation->initializeSSAUpdater(type.get(), BridgedValue::castToOwnership(ownership)); ++} ++ ++void BridgedPassContext::SSAUpdater_addAvailableValue(BridgedBasicBlock block, BridgedValue value) const { ++ invocation->getSSAUpdater()->addAvailableValue(block.get(), value.getSILValue()); ++} ++ ++BridgedValue BridgedPassContext::SSAUpdater_getValueAtEndOfBlock(BridgedBasicBlock block) const { ++ return {invocation->getSSAUpdater()->getValueAtEndOfBlock(block.get())}; ++} ++ ++BridgedValue BridgedPassContext::SSAUpdater_getValueInMiddleOfBlock(BridgedBasicBlock block) const { ++ return {invocation->getSSAUpdater()->getValueInMiddleOfBlock(block.get())}; ++} ++ ++bool BridgedPassContext::enableStackProtection() const { ++ swift::SILModule *mod = invocation->getPassManager()->getModule(); ++ return mod->getOptions().EnableStackProtection; ++} ++ ++bool BridgedPassContext::enableEmbeddedSwift() const { ++ swift::SILModule *mod = invocation->getPassManager()->getModule(); ++ return mod->getASTContext().LangOpts.hasFeature(swift::Feature::Embedded); ++} ++ ++bool BridgedPassContext::enableMoveInoutStackProtection() const { ++ swift::SILModule *mod = invocation->getPassManager()->getModule(); ++ return mod->getOptions().EnableMoveInoutStackProtection; ++} ++ ++BridgedPassContext::AssertConfiguration BridgedPassContext::getAssertConfiguration() const { ++ swift::SILModule *mod = invocation->getPassManager()->getModule(); ++ return (AssertConfiguration)mod->getOptions().AssertConfig; ++} ++ ++static_assert((int)BridgedPassContext::SILStage::Raw == (int)swift::SILStage::Raw); ++static_assert((int)BridgedPassContext::SILStage::Canonical == (int)swift::SILStage::Canonical); ++static_assert((int)BridgedPassContext::SILStage::Lowered == (int)swift::SILStage::Lowered); ++ ++static_assert((int)BridgedPassContext::AssertConfiguration::Debug == (int)swift::SILOptions::Debug); ++static_assert((int)BridgedPassContext::AssertConfiguration::Release == (int)swift::SILOptions::Release); ++static_assert((int)BridgedPassContext::AssertConfiguration::Unchecked == (int)swift::SILOptions::Unchecked); ++ ++SWIFT_END_NULLABILITY_ANNOTATIONS ++ ++#endif +diff --git a/swift/lib/AST/ASTBridging.cpp b/swift/lib/AST/ASTBridging.cpp +index 4b924f80163..db58aaa98fe 100644 +--- a/swift/lib/AST/ASTBridging.cpp ++++ b/swift/lib/AST/ASTBridging.cpp +@@ -25,30 +25,53 @@ DiagnosticEngine *getDiagnosticEngine(const BridgedDiagnosticEngine &bridged) { + + } // namespace + ++static_assert(sizeof(BridgedDiagnosticArgument) >= sizeof(DiagnosticArgument), ++ "BridgedDiagnosticArgument has wrong size"); ++ ++BridgedDiagnosticArgument::BridgedDiagnosticArgument(SwiftInt i) ++ : BridgedDiagnosticArgument(DiagnosticArgument((int)i)) {} ++ ++BridgedDiagnosticArgument::BridgedDiagnosticArgument(BridgedStringRef s) ++ : BridgedDiagnosticArgument(DiagnosticArgument(s.get())) {} ++ ++static_assert(sizeof(BridgedDiagnosticFixIt) >= sizeof(DiagnosticInfo::FixIt), ++ "BridgedDiagnosticFixIt has wrong size"); ++ ++static SourceLoc getSourceLoc(BridgedSourceLoc bridgedLoc) { ++ return SourceLoc(llvm::SMLoc::getFromPointer(bridgedLoc.getLoc())); ++} ++ ++BridgedDiagnosticFixIt::BridgedDiagnosticFixIt(BridgedSourceLoc start, uint32_t length, BridgedStringRef text) ++ : BridgedDiagnosticFixIt(DiagnosticInfo::FixIt( ++ CharSourceRange(getSourceLoc(start), length), ++ text.get(), ++ llvm::ArrayRef())) {} ++ + void DiagnosticEngine_diagnose( +- BridgedDiagnosticEngine bridgedEngine, SourceLoc loc, ++ BridgedDiagnosticEngine bridgedEngine, BridgedSourceLoc loc, + BridgedDiagID bridgedDiagID, +- BridgedArrayRef /*DiagnosticArgument*/ bridgedArguments, +- CharSourceRange highlight, +- BridgedArrayRef /*DiagnosticInfo::FixIt*/ bridgedFixIts) { ++ BridgedArrayRef /*BridgedDiagnosticArgument*/ bridgedArguments, ++ BridgedSourceLoc highlightStart, uint32_t hightlightLength, ++ BridgedArrayRef /*BridgedDiagnosticFixIt*/ bridgedFixIts) { + auto *D = getDiagnosticEngine(bridgedEngine); + + auto diagID = static_cast(bridgedDiagID); + SmallVector arguments; +- for (auto arg : getArrayRef(bridgedArguments)) { +- arguments.push_back(arg); ++ for (auto arg : getArrayRef(bridgedArguments)) { ++ arguments.push_back(arg.get()); + } +- auto inflight = D->diagnose(loc, diagID, arguments); ++ auto inflight = D->diagnose(SourceLoc(llvm::SMLoc::getFromPointer(loc.getLoc())), diagID, arguments); + + // Add highlight. +- if (highlight.isValid()) { ++ if (highlightStart.isValid()) { ++ CharSourceRange highlight(getSourceLoc(highlightStart), (unsigned)hightlightLength); + inflight.highlightChars(highlight.getStart(), highlight.getEnd()); + } + + // Add fix-its. +- for (auto fixIt : getArrayRef(bridgedFixIts)) { +- auto range = fixIt.getRange(); +- auto text = fixIt.getText(); ++ for (const BridgedDiagnosticFixIt &fixIt : getArrayRef(bridgedFixIts)) { ++ auto range = fixIt.get().getRange(); ++ auto text = fixIt.get().getText(); + inflight.fixItReplaceChars(range.getStart(), range.getEnd(), text); + } + } +diff --git a/swift/lib/AST/Decl.cpp b/swift/lib/AST/Decl.cpp +index 8fd0134e9dc..f68e0ebf885 100644 +--- a/swift/lib/AST/Decl.cpp ++++ b/swift/lib/AST/Decl.cpp +@@ -27,8 +27,6 @@ + #include "swift/AST/DiagnosticsSema.h" + #include "swift/AST/ExistentialLayout.h" + #include "swift/AST/Expr.h" +-#include "swift/AST/ForeignAsyncConvention.h" +-#include "swift/AST/ForeignErrorConvention.h" + #include "swift/AST/GenericEnvironment.h" + #include "swift/AST/GenericSignature.h" + #include "swift/AST/Initializer.h" +diff --git a/swift/lib/Basic/BasicBridging.cpp b/swift/lib/Basic/BasicBridging.cpp +index 9f9e9e03e13..b9b9fe76717 100644 +--- a/swift/lib/Basic/BasicBridging.cpp ++++ b/swift/lib/Basic/BasicBridging.cpp +@@ -16,10 +16,27 @@ + using namespace swift; + + //===----------------------------------------------------------------------===// +-// Bridging C functions ++// BridgedStringRef + //===----------------------------------------------------------------------===// + +-void OStream_write(BridgedOStream os, StringRef str) { +- static_cast(os.streamAddr) +- ->write(str.data(), str.size()); ++void BridgedStringRef::write(BridgedOStream os) const { ++ static_cast(os.streamAddr)->write(data, length); + } ++ ++//===----------------------------------------------------------------------===// ++// BridgedOwnedString ++//===----------------------------------------------------------------------===// ++ ++BridgedOwnedString::BridgedOwnedString(const std::string &stringToCopy) ++ : data(nullptr), length(stringToCopy.size()) { ++ if (length != 0) { ++ data = new char[length]; ++ std::memcpy(data, stringToCopy.data(), length); ++ } ++} ++ ++void BridgedOwnedString::destroy() const { ++ if (data) ++ delete [] data; ++} ++ +diff --git a/swift/lib/Parse/ParseRegex.cpp b/swift/lib/Parse/ParseRegex.cpp +index 5ed804653d3..2b680142487 100644 +--- a/swift/lib/Parse/ParseRegex.cpp ++++ b/swift/lib/Parse/ParseRegex.cpp +@@ -44,7 +44,7 @@ ParserResult Parser::parseExprRegexLiteral() { + /*versionOut=*/&version, + /*captureStructureOut=*/capturesBuf.data(), + /*captureStructureSize=*/capturesBuf.size(), +- /*diagBaseLoc=*/{Tok.getLoc().getOpaquePointerValue()}, &Diags); ++ /*diagBaseLoc=*/{(const uint8_t *)(Tok.getLoc().getOpaquePointerValue())}, &Diags); + auto loc = consumeToken(); + SourceMgr.recordRegexLiteralStartLoc(loc); + +diff --git a/swift/lib/SIL/IR/SILBasicBlock.cpp b/swift/lib/SIL/IR/SILBasicBlock.cpp +index b94fcc7f376..2810e8331b4 100644 +--- a/swift/lib/SIL/IR/SILBasicBlock.cpp ++++ b/swift/lib/SIL/IR/SILBasicBlock.cpp +@@ -19,7 +19,6 @@ + #include "swift/SIL/DebugUtils.h" + #include "swift/SIL/SILBasicBlock.h" + #include "swift/SIL/SILBuilder.h" +-#include "swift/SIL/SILBridging.h" + #include "swift/SIL/SILArgument.h" + #include "swift/SIL/SILDebugScope.h" + #include "swift/SIL/SILFunction.h" +diff --git a/swift/lib/SIL/IR/SILFunction.cpp b/swift/lib/SIL/IR/SILFunction.cpp +index 5c97ac25581..201b27edf7f 100644 +--- a/swift/lib/SIL/IR/SILFunction.cpp ++++ b/swift/lib/SIL/IR/SILFunction.cpp +@@ -985,9 +985,14 @@ void BridgedFunction::registerBridging(SwiftMetatype metatype, + std::pair SILFunction:: + parseArgumentEffectsFromSource(StringRef effectStr, ArrayRef paramNames) { + if (parseFunction) { ++ llvm::SmallVector bridgedParamNames; ++ for (StringRef paramName : paramNames) { ++ bridgedParamNames.push_back(paramName); ++ } ++ ArrayRef bridgedParamNameArray = bridgedParamNames; + auto error = parseFunction( + {this}, effectStr, BridgedFunction::ParseEffectsMode::argumentEffectsFromSource, -1, +- {(const unsigned char *)paramNames.data(), paramNames.size()}); ++ {(const unsigned char *)bridgedParamNameArray.data(), bridgedParamNameArray.size()}); + return {(const char *)error.message, (int)error.position}; + } + return {nullptr, 0}; +diff --git a/swift/lib/SIL/IR/SILLocation.cpp b/swift/lib/SIL/IR/SILLocation.cpp +index ad6feba56f5..cfaa9880382 100644 +--- a/swift/lib/SIL/IR/SILLocation.cpp ++++ b/swift/lib/SIL/IR/SILLocation.cpp +@@ -337,21 +337,3 @@ ImplicitReturnLocation::ImplicitReturnLocation(SILLocation L) + L.isASTNode() || + L.isNull()); + } +- +-std::string SILDebugLocation::getDebugDescription() const { +- std::string str; +- llvm::raw_string_ostream os(str); +- SILLocation loc = getLocation(); +- loc.print(os); +-#ifndef NDEBUG +- if (const SILDebugScope *scope = getScope()) { +- if (DeclContext *dc = loc.getAsDeclContext()) { +- os << ", scope="; +- scope->print(dc->getASTContext().SourceMgr, os, /*indent*/ 2); +- } else { +- os << ", scope=?"; +- } +- } +-#endif +- return str; +-} +diff --git a/swift/lib/SIL/Utils/SILBridging.cpp b/swift/lib/SIL/Utils/SILBridging.cpp +index 0aa1baaa36e..2c1c1e0179a 100644 +--- a/swift/lib/SIL/Utils/SILBridging.cpp ++++ b/swift/lib/SIL/Utils/SILBridging.cpp +@@ -1,8 +1,8 @@ +-//===--- SILBridgingUtils.cpp - Utilities for swift bridging --------------===// ++//===--- SILBridging.cpp --------------------------------------------------===// + // + // This source file is part of the Swift.org open source project + // +-// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors ++// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors + // Licensed under Apache License v2.0 with Runtime Library Exception + // + // See https://swift.org/LICENSE.txt for license information +@@ -10,16 +10,22 @@ + // + //===----------------------------------------------------------------------===// + ++#include "swift/SIL/SILBridging.h" ++#ifdef PURE_BRIDGING_MODE ++// In PURE_BRIDGING_MODE, briding functions are not inlined and therefore inluded in the cpp file. ++#include "swift/SIL/SILBridgingImpl.h" ++#endif ++ + #include "swift/Basic/BridgingUtils.h" + #include "swift/AST/Attr.h" + #include "swift/AST/SemanticAttrs.h" + #include "swift/SIL/SILNode.h" +-#include "swift/SIL/ApplySite.h" +-#include "swift/SIL/SILBridging.h" + #include "swift/SIL/SILGlobalVariable.h" + #include "swift/SIL/SILBuilder.h" + #include "swift/SIL/MemAccessUtils.h" + #include ++#include ++#include + + using namespace swift; + +@@ -61,7 +67,8 @@ static void setUnimplementedRange(SwiftMetatype metatype, + + /// Registers the metatype of a swift SIL class. + /// Called by initializeSwiftModules(). +-void registerBridgedClass(StringRef className, SwiftMetatype metatype) { ++void registerBridgedClass(BridgedStringRef bridgedClassName, SwiftMetatype metatype) { ++ StringRef className = bridgedClassName.get(); + nodeMetatypesInitialized = true; + + // Handle the important non Node classes. +@@ -127,11 +134,39 @@ void registerBridgedClass(StringRef className, SwiftMetatype metatype) { + nodeMetatypes[(unsigned)kind] = metatype; + } + ++//===----------------------------------------------------------------------===// ++// SILType ++//===----------------------------------------------------------------------===// ++ ++static_assert((int)BridgedType::MetatypeRepresentation::Thin == (int)swift::MetatypeRepresentation::Thin); ++static_assert((int)BridgedType::MetatypeRepresentation::Thick == (int)swift::MetatypeRepresentation::Thick); ++static_assert((int)BridgedType::MetatypeRepresentation::ObjC == (int)swift::MetatypeRepresentation::ObjC); ++ ++static_assert((int)BridgedType::TraitResult::IsNot == (int)swift::TypeTraitResult::IsNot); ++static_assert((int)BridgedType::TraitResult::CanBe == (int)swift::TypeTraitResult::CanBe); ++static_assert((int)BridgedType::TraitResult::Is == (int)swift::TypeTraitResult::Is); ++ ++ + //===----------------------------------------------------------------------===// + // SILFunction + //===----------------------------------------------------------------------===// + +-std::string BridgedFunction::getDebugDescription() const { ++static_assert((int)BridgedFunction::EffectsKind::ReadNone == (int)swift::EffectsKind::ReadNone); ++static_assert((int)BridgedFunction::EffectsKind::ReadOnly == (int)swift::EffectsKind::ReadOnly); ++static_assert((int)BridgedFunction::EffectsKind::ReleaseNone == (int)swift::EffectsKind::ReleaseNone); ++static_assert((int)BridgedFunction::EffectsKind::ReadWrite == (int)swift::EffectsKind::ReadWrite); ++static_assert((int)BridgedFunction::EffectsKind::Unspecified == (int)swift::EffectsKind::Unspecified); ++static_assert((int)BridgedFunction::EffectsKind::Custom == (int)swift::EffectsKind::Custom); ++ ++static_assert((int)BridgedFunction::PerformanceConstraints::None == (int)swift::PerformanceConstraints::None); ++static_assert((int)BridgedFunction::PerformanceConstraints::NoAllocation == (int)swift::PerformanceConstraints::NoAllocation); ++static_assert((int)BridgedFunction::PerformanceConstraints::NoLocks == (int)swift::PerformanceConstraints::NoLocks); ++ ++static_assert((int)BridgedFunction::InlineStrategy::InlineDefault == (int)swift::InlineDefault); ++static_assert((int)BridgedFunction::InlineStrategy::NoInline == (int)swift::NoInline); ++static_assert((int)BridgedFunction::InlineStrategy::AlwaysInline == (int)swift::AlwaysInline); ++ ++BridgedOwnedString BridgedFunction::getDebugDescription() const { + std::string str; + llvm::raw_string_ostream os(str); + getFunction()->print(os); +@@ -143,10 +178,10 @@ std::string BridgedFunction::getDebugDescription() const { + // SILBasicBlock + //===----------------------------------------------------------------------===// + +-std::string BridgedBasicBlock::getDebugDescription() const { ++BridgedOwnedString BridgedBasicBlock::getDebugDescription() const { + std::string str; + llvm::raw_string_ostream os(str); +- getBlock()->print(os); ++ get()->print(os); + str.pop_back(); // Remove trailing newline. + return str; + } +@@ -155,7 +190,7 @@ std::string BridgedBasicBlock::getDebugDescription() const { + // SILValue + //===----------------------------------------------------------------------===// + +-std::string BridgedValue::getDebugDescription() const { ++BridgedOwnedString BridgedValue::getDebugDescription() const { + std::string str; + llvm::raw_string_ostream os(str); + getSILValue()->print(os); +@@ -184,11 +219,30 @@ ArrayRef BridgedValueArray::getValues(SmallVectorImpl &stora + return storage; + } + ++ ++//===----------------------------------------------------------------------===// ++// SILArgument ++//===----------------------------------------------------------------------===// ++ ++static_assert((int)BridgedArgumentConvention::Indirect_In == (int)swift::SILArgumentConvention::Indirect_In); ++static_assert((int)BridgedArgumentConvention::Indirect_In_Guaranteed == (int)swift::SILArgumentConvention::Indirect_In_Guaranteed); ++static_assert((int)BridgedArgumentConvention::Indirect_Inout == (int)swift::SILArgumentConvention::Indirect_Inout); ++static_assert((int)BridgedArgumentConvention::Indirect_InoutAliasable == (int)swift::SILArgumentConvention::Indirect_InoutAliasable); ++static_assert((int)BridgedArgumentConvention::Indirect_Out == (int)swift::SILArgumentConvention::Indirect_Out); ++static_assert((int)BridgedArgumentConvention::Direct_Owned == (int)swift::SILArgumentConvention::Direct_Owned); ++static_assert((int)BridgedArgumentConvention::Direct_Unowned == (int)swift::SILArgumentConvention::Direct_Unowned); ++static_assert((int)BridgedArgumentConvention::Direct_Guaranteed == (int)swift::SILArgumentConvention::Direct_Guaranteed); ++static_assert((int)BridgedArgumentConvention::Pack_Owned == (int)swift::SILArgumentConvention::Pack_Owned); ++static_assert((int)BridgedArgumentConvention::Pack_Inout == (int)swift::SILArgumentConvention::Pack_Inout); ++static_assert((int)BridgedArgumentConvention::Pack_Guaranteed == (int)swift::SILArgumentConvention::Pack_Guaranteed); ++static_assert((int)BridgedArgumentConvention::Pack_Out == (int)swift::SILArgumentConvention::Pack_Out); ++ ++ + //===----------------------------------------------------------------------===// + // SILGlobalVariable + //===----------------------------------------------------------------------===// + +-std::string BridgedGlobalVar::getDebugDescription() const { ++BridgedOwnedString BridgedGlobalVar::getDebugDescription() const { + std::string str; + llvm::raw_string_ostream os(str); + getGlobal()->print(os); +@@ -217,7 +271,7 @@ bool BridgedGlobalVar::mustBeInitializedStatically() const { + // SILVTable + //===----------------------------------------------------------------------===// + +-std::string BridgedVTable::getDebugDescription() const { ++BridgedOwnedString BridgedVTable::getDebugDescription() const { + std::string str; + llvm::raw_string_ostream os(str); + vTable->print(os); +@@ -225,7 +279,7 @@ std::string BridgedVTable::getDebugDescription() const { + return str; + } + +-std::string BridgedVTableEntry::getDebugDescription() const { ++BridgedOwnedString BridgedVTableEntry::getDebugDescription() const { + std::string str; + llvm::raw_string_ostream os(str); + entry->print(os); +@@ -237,15 +291,21 @@ std::string BridgedVTableEntry::getDebugDescription() const { + // SILVWitnessTable, SILDefaultWitnessTable + //===----------------------------------------------------------------------===// + +-std::string BridgedWitnessTableEntry::getDebugDescription() const { ++static_assert((int)BridgedWitnessTableEntry::Kind::Invalid == (int)swift::SILWitnessTable::WitnessKind::Invalid); ++static_assert((int)BridgedWitnessTableEntry::Kind::Method == (int)swift::SILWitnessTable::WitnessKind::Method); ++static_assert((int)BridgedWitnessTableEntry::Kind::AssociatedType == (int)swift::SILWitnessTable::WitnessKind::AssociatedType); ++static_assert((int)BridgedWitnessTableEntry::Kind::AssociatedTypeProtocol == (int)swift::SILWitnessTable::WitnessKind::AssociatedTypeProtocol); ++static_assert((int)BridgedWitnessTableEntry::Kind::BaseProtocol == (int)swift::SILWitnessTable::WitnessKind::BaseProtocol); ++ ++BridgedOwnedString BridgedWitnessTableEntry::getDebugDescription() const { + std::string str; + llvm::raw_string_ostream os(str); +- entry->print(os, /*verbose=*/ false, PrintOptions::printSIL()); ++ getEntry()->print(os, /*verbose=*/ false, PrintOptions::printSIL()); + str.pop_back(); // Remove trailing newline. + return str; + } + +-std::string BridgedWitnessTable::getDebugDescription() const { ++BridgedOwnedString BridgedWitnessTable::getDebugDescription() const { + std::string str; + llvm::raw_string_ostream os(str); + table->print(os); +@@ -253,7 +313,7 @@ std::string BridgedWitnessTable::getDebugDescription() const { + return str; + } + +-std::string BridgedDefaultWitnessTable::getDebugDescription() const { ++BridgedOwnedString BridgedDefaultWitnessTable::getDebugDescription() const { + std::string str; + llvm::raw_string_ostream os(str); + table->print(os); +@@ -261,32 +321,76 @@ std::string BridgedDefaultWitnessTable::getDebugDescription() const { + return str; + } + ++//===----------------------------------------------------------------------===// ++// SubstitutionMap ++//===----------------------------------------------------------------------===// ++ ++static_assert(sizeof(BridgedSubstitutionMap) >= sizeof(swift::SubstitutionMap), ++ "BridgedSubstitutionMap has wrong size"); ++ ++ ++//===----------------------------------------------------------------------===// ++// SILDebugLocation ++//===----------------------------------------------------------------------===// ++ ++static_assert(sizeof(BridgedLocation) >= sizeof(swift::SILDebugLocation), ++ "BridgedLocation has wrong size"); ++ ++BridgedOwnedString BridgedLocation::getDebugDescription() const { ++ std::string str; ++ llvm::raw_string_ostream os(str); ++ SILLocation loc = getLoc().getLocation(); ++ loc.print(os); ++#ifndef NDEBUG ++ if (const SILDebugScope *scope = getLoc().getScope()) { ++ if (DeclContext *dc = loc.getAsDeclContext()) { ++ os << ", scope="; ++ scope->print(dc->getASTContext().SourceMgr, os, /*indent*/ 2); ++ } else { ++ os << ", scope=?"; ++ } ++ } ++#endif ++ return str; ++} ++ + //===----------------------------------------------------------------------===// + // SILInstruction + //===----------------------------------------------------------------------===// + +-std::string BridgedInstruction::getDebugDescription() const { ++static_assert((int)BridgedMemoryBehavior::None == (int)swift::MemoryBehavior::None); ++static_assert((int)BridgedMemoryBehavior::MayRead == (int)swift::MemoryBehavior::MayRead); ++static_assert((int)BridgedMemoryBehavior::MayWrite == (int)swift::MemoryBehavior::MayWrite); ++static_assert((int)BridgedMemoryBehavior::MayReadWrite == (int)swift::MemoryBehavior::MayReadWrite); ++static_assert((int)BridgedMemoryBehavior::MayHaveSideEffects == (int)swift::MemoryBehavior::MayHaveSideEffects); ++ ++static_assert((int)BridgedInstruction::AccessKind::Init == (int)swift::SILAccessKind::Init); ++static_assert((int)BridgedInstruction::AccessKind::Read == (int)swift::SILAccessKind::Read); ++static_assert((int)BridgedInstruction::AccessKind::Modify == (int)swift::SILAccessKind::Modify); ++static_assert((int)BridgedInstruction::AccessKind::Deinit == (int)swift::SILAccessKind::Deinit); ++ ++BridgedOwnedString BridgedInstruction::getDebugDescription() const { + std::string str; + llvm::raw_string_ostream os(str); +- getInst()->print(os); ++ get()->print(os); + str.pop_back(); // Remove trailing newline. + return str; + } + + bool BridgedInstruction::mayAccessPointer() const { +- return ::mayAccessPointer(getInst()); ++ return ::mayAccessPointer(get()); + } + + bool BridgedInstruction::mayLoadWeakOrUnowned() const { +- return ::mayLoadWeakOrUnowned(getInst()); ++ return ::mayLoadWeakOrUnowned(get()); + } + + bool BridgedInstruction::maySynchronizeNotConsideringSideEffects() const { +- return ::maySynchronizeNotConsideringSideEffects(getInst()); ++ return ::maySynchronizeNotConsideringSideEffects(get()); + } + + bool BridgedInstruction::mayBeDeinitBarrierNotConsideringSideEffects() const { +- return ::mayBeDeinitBarrierNotConsideringSideEffects(getInst()); ++ return ::mayBeDeinitBarrierNotConsideringSideEffects(get()); + } + + //===----------------------------------------------------------------------===// +@@ -299,3 +403,7 @@ bool BridgedNominalTypeDecl::isStructWithUnreferenceableStorage() const { + } + return false; + } ++ ++void writeCharToStderr(int c) { ++ putc(c, stderr); ++} +diff --git a/swift/lib/SILOptimizer/PassManager/PassManager.cpp b/swift/lib/SILOptimizer/PassManager/PassManager.cpp +index a130147a445..cfa1a3abb39 100644 +--- a/swift/lib/SILOptimizer/PassManager/PassManager.cpp ++++ b/swift/lib/SILOptimizer/PassManager/PassManager.cpp +@@ -22,23 +22,17 @@ + #include "swift/SIL/SILCloner.h" + #include "swift/SIL/SILFunction.h" + #include "swift/SIL/SILModule.h" +-#include "swift/SILOptimizer/Analysis/AliasAnalysis.h" + #include "swift/SILOptimizer/Analysis/BasicCalleeAnalysis.h" +-#include "swift/SILOptimizer/Analysis/DeadEndBlocksAnalysis.h" + #include "swift/SILOptimizer/Analysis/FunctionOrder.h" +-#include "swift/SILOptimizer/Analysis/DominanceAnalysis.h" + #include "swift/SILOptimizer/OptimizerBridging.h" + #include "swift/SILOptimizer/PassManager/PrettyStackTrace.h" + #include "swift/SILOptimizer/PassManager/Transforms.h" +-#include "swift/SILOptimizer/Utils/BasicBlockOptUtils.h" +-#include "swift/SILOptimizer/Utils/ConstantFolding.h" +-#include "swift/SILOptimizer/Utils/CFGOptUtils.h" + #include "swift/SILOptimizer/Utils/Devirtualize.h" ++#include "swift/SILOptimizer/Utils/ConstantFolding.h" + #include "swift/SILOptimizer/Utils/OptimizerStatsUtils.h" + #include "swift/SILOptimizer/Utils/SILInliner.h" + #include "swift/SILOptimizer/Utils/SILOptFunctionBuilder.h" + #include "swift/SILOptimizer/Utils/StackNesting.h" +-#include "swift/SILOptimizer/Utils/InstOptUtils.h" + #include "llvm/ADT/DenseMap.h" + #include "llvm/ADT/Statistic.h" + #include "llvm/ADT/StringSwitch.h" +@@ -151,10 +145,6 @@ llvm::cl::opt SILForceVerifyAll( + llvm::cl::desc("For all passes, precompute analyses before the pass and " + "verify analyses after the pass")); + +-llvm::cl::list +- SimplifyInstructionTest("simplify-instruction", llvm::cl::CommaSeparated, +- llvm::cl::desc("Simplify instruction of specified kind(s)")); +- + static llvm::ManagedStatic> DebugPassNumbers; + + namespace { +@@ -1440,9 +1430,18 @@ SwiftPassInvocation::~SwiftPassInvocation() { + } + + //===----------------------------------------------------------------------===// +-// Swift Bridging ++// OptimizerBridging + //===----------------------------------------------------------------------===// + ++llvm::cl::list ++ SimplifyInstructionTest("simplify-instruction", llvm::cl::CommaSeparated, ++ llvm::cl::desc("Simplify instruction of specified kind(s)")); ++ ++#ifdef PURE_BRIDGING_MODE ++// In PURE_BRIDGING_MODE, briding functions are not inlined and therefore inluded in the cpp file. ++#include "swift/SILOptimizer/OptimizerBridgingImpl.h" ++#endif ++ + void BridgedChangeNotificationHandler::notifyChanges(Kind changeKind) const { + switch (changeKind) { + case Kind::instructionsChanged: +@@ -1460,7 +1459,7 @@ void BridgedChangeNotificationHandler::notifyChanges(Kind changeKind) const { + } + } + +-std::string BridgedPassContext::getModuleDescription() const { ++BridgedOwnedString BridgedPassContext::getModuleDescription() const { + std::string str; + llvm::raw_string_ostream os(str); + invocation->getPassManager()->getModule()->print(os); +@@ -1481,7 +1480,7 @@ bool BridgedPassContext::tryDeleteDeadClosure(BridgedInstruction closure, bool n + BridgedPassContext::DevirtResult BridgedPassContext::tryDevirtualizeApply(BridgedInstruction apply, + bool isMandatory) const { + auto cha = invocation->getPassManager()->getAnalysis(); +- auto result = ::tryDevirtualizeApply(ApplySite(apply.getInst()), cha, nullptr, isMandatory); ++ auto result = ::tryDevirtualizeApply(ApplySite(apply.get()), cha, nullptr, isMandatory); + if (result.first) { + OptionalBridgedInstruction newApply(result.first.getInstruction()->asSILNode()); + return {newApply, result.second}; +@@ -1498,7 +1497,7 @@ OptionalBridgedValue BridgedPassContext::constantFoldBuiltin(BridgedInstruction + void BridgedPassContext::inlineFunction(BridgedInstruction apply, bool mandatoryInline) const { + SILOptFunctionBuilder funcBuilder(*invocation->getTransform()); + InstructionDeleter deleter; +- SILInliner::inlineFullApply(FullApplySite(apply.getInst()), ++ SILInliner::inlineFullApply(FullApplySite(apply.get()), + mandatoryInline ? SILInliner::InlineKind::MandatoryInline + : SILInliner::InlineKind::PerformanceInline, + funcBuilder, +@@ -1518,29 +1517,29 @@ static SwiftInt integerValueFromConstant(llvm::Constant *c, SwiftInt add = 0) { + return value.getLimitedValue() + add; + } + +-SwiftInt BridgedPassContext::getStaticSize(swift::SILType type) const { ++SwiftInt BridgedPassContext::getStaticSize(BridgedType type) const { + irgen::IRGenModule *IGM = invocation->getIRGenModule(); + if (!IGM) + return -1; +- auto &ti = getTypeInfoOfBuiltin(type, *IGM); ++ auto &ti = getTypeInfoOfBuiltin(type.get(), *IGM); + llvm::Constant *c = ti.getStaticSize(*IGM); + return integerValueFromConstant(c); + } + +-SwiftInt BridgedPassContext::getStaticAlignment(swift::SILType type) const { ++SwiftInt BridgedPassContext::getStaticAlignment(BridgedType type) const { + irgen::IRGenModule *IGM = invocation->getIRGenModule(); + if (!IGM) + return -1; +- auto &ti = getTypeInfoOfBuiltin(type, *IGM); ++ auto &ti = getTypeInfoOfBuiltin(type.get(), *IGM); + llvm::Constant *c = ti.getStaticAlignmentMask(*IGM); + return integerValueFromConstant(c, 1); + } + +-SwiftInt BridgedPassContext::getStaticStride(swift::SILType type) const { ++SwiftInt BridgedPassContext::getStaticStride(BridgedType type) const { + irgen::IRGenModule *IGM = invocation->getIRGenModule(); + if (!IGM) + return -1; +- auto &ti = getTypeInfoOfBuiltin(type, *IGM); ++ auto &ti = getTypeInfoOfBuiltin(type.get(), *IGM); + llvm::Constant *c = ti.getStaticStride(*IGM); + return integerValueFromConstant(c); + } +@@ -1566,7 +1565,7 @@ public: + }; + } // namespace + +-std::string BridgedPassContext::mangleOutlinedVariable(BridgedFunction function) const { ++BridgedOwnedString BridgedPassContext::mangleOutlinedVariable(BridgedFunction function) const { + int idx = 0; + SILFunction *f = function.getFunction(); + SILModule &mod = f->getModule(); +@@ -1579,11 +1578,11 @@ std::string BridgedPassContext::mangleOutlinedVariable(BridgedFunction function) + } + } + +-BridgedGlobalVar BridgedPassContext::createGlobalVariable(StringRef name, SILType type, bool isPrivate) const { ++BridgedGlobalVar BridgedPassContext::createGlobalVariable(BridgedStringRef name, BridgedType type, bool isPrivate) const { + return {SILGlobalVariable::create(*invocation->getPassManager()->getModule(), + isPrivate ? SILLinkage::Private : SILLinkage::Public, + IsNotSerialized, +- name, type)}; ++ name.get(), type.get())}; + } + + void BridgedPassContext::fixStackNesting(BridgedFunction function) const { +@@ -1600,10 +1599,10 @@ void BridgedPassContext::fixStackNesting(BridgedFunction function) const { + invocation->setNeedFixStackNesting(false); + } + +-OptionalBridgedFunction BridgedPassContext::lookupStdlibFunction(llvm::StringRef name) const { ++OptionalBridgedFunction BridgedPassContext::lookupStdlibFunction(BridgedStringRef name) const { + swift::SILModule *mod = invocation->getPassManager()->getModule(); + SmallVector results; +- mod->getASTContext().lookupInSwiftModule(name, results); ++ mod->getASTContext().lookupInSwiftModule(name.get(), results); + if (results.size() != 1) + return {nullptr}; + +@@ -1621,7 +1620,7 @@ bool BridgedPassContext::enableSimplificationFor(BridgedInstruction inst) const + if (SimplifyInstructionTest.empty() && SILDisablePass.empty()) + return true; + +- StringRef instName = getSILInstructionName(inst.getInst()->getKind()); ++ StringRef instName = getSILInstructionName(inst.get()->getKind()); + + if (SILPassManager::isInstructionPassDisabled(instName)) + return false; +@@ -1637,17 +1636,17 @@ bool BridgedPassContext::enableSimplificationFor(BridgedInstruction inst) const + } + + bool FullApplySite_canInline(BridgedInstruction apply) { +- return swift::SILInliner::canInlineApplySite(swift::FullApplySite(apply.getInst())); ++ return swift::SILInliner::canInlineApplySite(swift::FullApplySite(apply.get())); + } + + // TODO: can't be inlined to work around https://github.com/apple/swift/issues/64502 +-CalleeList BridgedCalleeAnalysis::getCallees(BridgedValue callee) const { ++BridgedCalleeAnalysis::CalleeList BridgedCalleeAnalysis::getCallees(BridgedValue callee) const { + return ca->getCalleeListOfValue(callee.getSILValue()); + } + + // TODO: can't be inlined to work around https://github.com/apple/swift/issues/64502 +-CalleeList BridgedCalleeAnalysis::getDestructors(SILType type, bool isExactType) const { +- return ca->getDestructors(type, isExactType); ++BridgedCalleeAnalysis::CalleeList BridgedCalleeAnalysis::getDestructors(BridgedType type, bool isExactType) const { ++ return ca->getDestructors(type.get(), isExactType); + } + + // Need to put ClonerWithFixedLocation into namespace swift to forward reference +@@ -1698,7 +1697,7 @@ BridgedCloner::BridgedCloner(BridgedGlobalVar var, BridgedPassContext context) + } + + BridgedCloner::BridgedCloner(BridgedInstruction inst, BridgedPassContext context) +- : cloner(new ClonerWithFixedLocation(inst.getInst())) { ++ : cloner(new ClonerWithFixedLocation(inst.get())) { + context.invocation->notifyNewCloner(); + } + +@@ -1717,5 +1716,6 @@ bool BridgedCloner::isValueCloned(BridgedValue v) const { + } + + void BridgedCloner::clone(BridgedInstruction inst) { +- cloner->cloneInst(inst.getInst()); ++ cloner->cloneInst(inst.get()); + } ++ +diff --git a/swift/lib/SILOptimizer/PassManager/Passes.cpp b/swift/lib/SILOptimizer/PassManager/Passes.cpp +index 7f04f625a47..e28b6bbb6d8 100644 +--- a/swift/lib/SILOptimizer/PassManager/Passes.cpp ++++ b/swift/lib/SILOptimizer/PassManager/Passes.cpp +@@ -274,15 +274,15 @@ static void runBridgedFunctionPass(BridgedFunctionPassRunFn &runFunction, + } + + // Called from initializeSwiftModules(). +-void SILPassManager_registerModulePass(llvm::StringRef name, ++void SILPassManager_registerModulePass(BridgedStringRef name, + BridgedModulePassRunFn runFn) { +- bridgedModulePassRunFunctions[name] = runFn; ++ bridgedModulePassRunFunctions[name.get()] = runFn; + passesRegistered = true; + } + +-void SILPassManager_registerFunctionPass(llvm::StringRef name, ++void SILPassManager_registerFunctionPass(BridgedStringRef name, + BridgedFunctionPassRunFn runFn) { +- bridgedFunctionPassRunFunctions[name] = runFn; ++ bridgedFunctionPassRunFunctions[name.get()] = runFn; + passesRegistered = true; + } + +diff --git a/swift/lib/SILOptimizer/SILCombiner/SILCombine.cpp b/swift/lib/SILOptimizer/SILCombiner/SILCombine.cpp +index 599855125c9..0959b8733a9 100644 +--- a/swift/lib/SILOptimizer/SILCombiner/SILCombine.cpp ++++ b/swift/lib/SILOptimizer/SILCombiner/SILCombine.cpp +@@ -540,9 +540,9 @@ static llvm::StringMap swiftInstPasses; + static bool passesRegistered = false; + + // Called from initializeSwiftModules(). +-void SILCombine_registerInstructionPass(llvm::StringRef instClassName, ++void SILCombine_registerInstructionPass(BridgedStringRef instClassName, + BridgedInstructionPassRunFn runFn) { +- swiftInstPasses[instClassName] = runFn; ++ swiftInstPasses[instClassName.get()] = runFn; + passesRegistered = true; + } + diff --git a/packages/swift/swift-remove-relative-rpaths.patch b/packages/swift/swift-remove-relative-rpaths.patch index 694e07f521..f363ceddcb 100644 --- a/packages/swift/swift-remove-relative-rpaths.patch +++ b/packages/swift/swift-remove-relative-rpaths.patch @@ -26,6 +26,32 @@ index bd31bec..737c8c3 100755 # SwiftPM will otherwise try to compile against GNU strerror_r on # Android and fail. '-Xswiftc', '-Xcc', '-Xswiftc', '-U_GNU_SOURCE', +diff --git a/swift/CMakeLists.txt b/swift/CMakeLists.txt +index 93096ad07b9..27b7fe4b98d 100644 +--- a/swift/CMakeLists.txt ++++ b/swift/CMakeLists.txt +@@ -1366,7 +1368,7 @@ if(SWIFT_INCLUDE_TOOLS) + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${SWIFT_HOST_LIBRARIES_DEST_DIR}") + set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${SWIFT_HOST_LIBRARIES_DEST_DIR}") + if(SWIFT_HOST_VARIANT_SDK MATCHES "LINUX|ANDROID|OPENBSD|FREEBSD") +- set(SWIFT_HOST_LIBRARIES_RPATH "$ORIGIN;$ORIGIN/../${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_LIB_SUBDIR}") ++ set(SWIFT_HOST_LIBRARIES_RPATH "$ORIGIN;$ORIGIN/../..") + endif() + # Add unique ABI prefix to swift-syntax libraries so that compiler libraries (e.g. sourcekitdInProc) + # can be used from tools that has its own swift-syntax libraries as SwiftPM dependencies. +diff --git a/swift/cmake/modules/AddPureSwift.cmake b/swift/cmake/modules/AddPureSwift.cmake +index ee668f96903..61397d3910e 100644 +--- a/swift/cmake/modules/AddPureSwift.cmake ++++ b/swift/cmake/modules/AddPureSwift.cmake +@@ -65,7 +71,7 @@ function(_set_pure_swift_link_flags name relpath_to_lib_dir) + APPEND PROPERTY INSTALL_RPATH + # At runtime, use swiftCore in the current just-built toolchain. + # NOTE: This relies on the ABI being the same as the builder. +- "$ORIGIN/${relpath_to_lib_dir}swift/${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_LIB_SUBDIR}" ++ "$ORIGIN/${relpath_to_lib_dir}" + ) + # NOTE: At this point we don't have any pure swift executables/shared + # libraries required for building runtime/stdlib. So we don't need to add diff --git a/swift-corelibs-foundation/Sources/Tools/plutil/CMakeLists.txt b/swift-corelibs-foundation/Sources/Tools/plutil/CMakeLists.txt index b1c84350..35413f0b 100644 --- a/swift-corelibs-foundation/Sources/Tools/plutil/CMakeLists.txt diff --git a/packages/swift/swift-stdlib-public-runtime-CrashHandlerLinux.cpp.patch b/packages/swift/swift-stdlib-public-runtime-CrashHandlerLinux.cpp.patch deleted file mode 100644 index 8a3411a8c4..0000000000 --- a/packages/swift/swift-stdlib-public-runtime-CrashHandlerLinux.cpp.patch +++ /dev/null @@ -1,16 +0,0 @@ -diff --git a/swift/stdlib/public/runtime/CrashHandlerLinux.cpp b/swift/stdlib/public/runtime/CrashHandlerLinux.cpp -index ff44dbe7541..2f386278975 100644 ---- a/swift/stdlib/public/runtime/CrashHandlerLinux.cpp -+++ b/swift/stdlib/public/runtime/CrashHandlerLinux.cpp -@@ -243,7 +243,11 @@ handle_fatal_signal(int signum, - #elif defined(__arm64__) || defined(__aarch64__) - pc = (void *)(ctx->uc_mcontext.pc); - #elif defined(__arm__) -+#if defined(__ANDROID__) -+ pc = (void *)(ctx->uc_mcontext.arm_pc); -+#else - pc = (void *)(ctx->uc_mcontext.gprs[15]); -+#endif - #endif - - _swift_displayCrashMessage(signum, pc); diff --git a/packages/swift/swift-syntax-cross-compile-host.patch b/packages/swift/swift-syntax-cross-compile-host.patch deleted file mode 100644 index f87e695536..0000000000 --- a/packages/swift/swift-syntax-cross-compile-host.patch +++ /dev/null @@ -1,498 +0,0 @@ -From 9ee52eea768af39f4ccbc1939d1385d70bb0ef37 -From: Ben Barham -Date: Tue, 16 May 2023 16:25:36 -0700 -Subject: [PATCH 1/4] [CMake] Updates to allow inclusion using FetchContent - -Various updates that allow swift-syntax to be included using -FetchContent. - -Mostly this is just not replacing `target_link_libraries` since that is -a global replacement, but we also now use a couple of variables from the -swift if they're set (eg. `SWIFT_HOST_LIBRARIES_DEST_DIR` and -`SWIFT_HOST_MODULE_TRIPLE`). - -diff --git a/swift-syntax/CMakeLists.txt b/swift-syntax/CMakeLists.txt -index aadf062ae5..c5a697ccc0 100644 ---- a/swift-syntax/CMakeLists.txt -+++ b/swift-syntax/CMakeLists.txt -@@ -15,12 +15,25 @@ project(SwiftSyntax LANGUAGES C Swift) - set(SWIFT_VERSION 5) - set(CMAKE_Swift_LANGUAGE_VERSION ${SWIFT_VERSION}) - -+if(CMAKE_VERSION VERSION_LESS 3.21) -+ get_property(parent_dir DIRECTORY PROPERTY PARENT_DIRECTORY) -+ if(NOT parent_dir) -+ set(PROJECT_IS_TOP_LEVEL TRUE) -+ endif() -+endif() -+ - # The subdirectory into which host libraries will be installed. - set(SWIFT_HOST_LIBRARIES_SUBDIRECTORY "swift/host") - --set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib/${SWIFT_HOST_LIBRARIES_SUBDIRECTORY}") --set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib/${SWIFT_HOST_LIBRARIES_SUBDIRECTORY}") --set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin") -+if(NOT CMAKE_ARCHIVE_OUTPUT_DIRECTORY) -+ set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib/${SWIFT_HOST_LIBRARIES_SUBDIRECTORY}") -+endif() -+if(NOT CMAKE_LIBRARY_OUTPUT_DIRECTORY) -+ set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib/${SWIFT_HOST_LIBRARIES_SUBDIRECTORY}") -+endif() -+if(NOT CMAKE_RUNTIME_OUTPUT_DIRECTORY) -+ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin") -+endif() - - set(CMAKE_MACOSX_RPATH YES) - -@@ -49,22 +65,25 @@ if (NOT SWIFT_SUPPORTS_DISABLE_IMPLICIT_STRING_PROCESSING_MODULE_IMPORT) - endif() - - # Determine the module triple. --# FIXME: This is a hack. It's all a hack. Windows isn't setting --# CMAKE_Swift_COMPILER_TARGET. --if(CMAKE_Swift_COMPILER_TARGET) -- string(REGEX REPLACE "macosx[0-9]+([.][0-9]+)?" "macos" SWIFT_MODULE_TRIPLE -- ${CMAKE_Swift_COMPILER_TARGET}) --elseif("${CMAKE_SYSTEM_NAME}" STREQUAL "Windows") -- if(CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|AMD64") -- set(SWIFT_MODULE_TRIPLE "x86_64-unknown-windows-msvc") -- elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "aarch64|ARM64|arm64") -- set(SWIFT_MODULE_TRIPLE "aarch64-unknown-windows-msvc") -+if("${SWIFT_HOST_MODULE_TRIPLE}" STREQUAL "") -+ # FIXME: This is a hack. It's all a hack. Windows isn't setting -+ # CMAKE_Swift_COMPILER_TARGET. -+ if(CMAKE_Swift_COMPILER_TARGET) -+ string(REGEX REPLACE "macosx[0-9]+([.][0-9]+)?" "macos" SWIFT_HOST_MODULE_TRIPLE -+ ${CMAKE_Swift_COMPILER_TARGET}) -+ elseif("${CMAKE_SYSTEM_NAME}" STREQUAL "Windows") -+ if(CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|AMD64") -+ set(SWIFT_HOST_MODULE_TRIPLE "x86_64-unknown-windows-msvc") -+ elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "aarch64|ARM64|arm64") -+ set(SWIFT_HOST_MODULE_TRIPLE "aarch64-unknown-windows-msvc") -+ else() -+ message(FATAL_ERROR "Unrecognized architecture for Windows host") -+ endif() - else() -- message(FATAL_ERROR "Unrecognized architecture for Windows host") -+ message(FATAL_ERROR "Host module triple required") - endif() - endif() -- --message(STATUS "Module triple: ${SWIFT_MODULE_TRIPLE}") -+message(STATUS "Module triple: ${SWIFT_HOST_MODULE_TRIPLE}") - - # Force single-threaded-only syntax trees to eliminate the Darwin - # dependency in the compiler. -@@ -79,9 +98,9 @@ endif() - - add_subdirectory(Sources) - --export(EXPORT SwiftSyntaxTargets -- FILE "${CMAKE_CURRENT_BINARY_DIR}/cmake/SwiftSyntaxTargets.cmake" -- NAMESPACE SwiftSyntax:: --) -- --add_subdirectory(cmake/modules) -+if(PROJECT_IS_TOP_LEVEL) -+ export(EXPORT SwiftSyntaxTargets -+ FILE "${CMAKE_CURRENT_BINARY_DIR}/cmake/SwiftSyntaxTargets.cmake" -+ NAMESPACE SwiftSyntax:: -+ ) -+endif() -diff --git a/swift-syntax/Sources/CMakeLists.txt b/swift-syntax/Sources/CMakeLists.txt -index 3b317b0891..a6f6c9f5bc 100644 ---- a/swift-syntax/Sources/CMakeLists.txt -+++ b/swift-syntax/Sources/CMakeLists.txt -@@ -6,31 +6,6 @@ - # See http://swift.org/LICENSE.txt for license information - # See http://swift.org/CONTRIBUTORS.txt for Swift project authors - --# cmake generation for Swift adds an order only dependency, which matches how C-family languages --# works. In that case, however, ninja (and presumably other generators) will rebuild on header --# changes. That's not the case for Swift, and thus if A -> B, A is not being rebuilt when the --# ABI/API of B changes. --# --# For now workaround this by touching a file whenever B is rebuilt and then compiling that file as --# part of A. Ideally this file would be generated by each of the targets, but that dependency didn't --# seem to be being tracked. --# --# Remove once rdar://102202478 is fixed. --function(target_link_libraries TARGET) -- cmake_parse_arguments(ARGS "" "" "PUBLIC" ${ARGN}) -- -- _target_link_libraries(${TARGET} PUBLIC ${ARGS_PUBLIC}) -- foreach(DEPENDENCY ${ARGS_PUBLIC}) -- add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/forced-${DEPENDENCY}-dep.swift -- COMMAND ${CMAKE_COMMAND} -E touch ${CMAKE_CURRENT_BINARY_DIR}/forced-${DEPENDENCY}-dep.swift -- DEPENDS ${DEPENDENCY} -- ) -- target_sources(${TARGET} PRIVATE -- ${CMAKE_CURRENT_BINARY_DIR}/forced-${DEPENDENCY}-dep.swift -- ) -- endforeach() --endfunction() -- - add_subdirectory(SwiftBasicFormat) - add_subdirectory(SwiftSyntax) - add_subdirectory(SwiftDiagnostics) -diff --git a/swift-syntax/Sources/SwiftBasicFormat/CMakeLists.txt b/swift-syntax/Sources/SwiftBasicFormat/CMakeLists.txt - index 4c6c2dcb82..05859828e7 100644 ---- a/swift-syntax/Sources/SwiftBasicFormat/CMakeLists.txt -+++ b/swift-syntax/Sources/SwiftBasicFormat/CMakeLists.txt -@@ -6,12 +6,12 @@ - # See http://swift.org/LICENSE.txt for license information - # See http://swift.org/CONTRIBUTORS.txt for Swift project authors - --add_swift_host_library(SwiftBasicFormat -+add_swift_syntax_library(SwiftBasicFormat - BasicFormat.swift - generated/BasicFormat+Extensions.swift - SyntaxProtocol+Formatted.swift - Trivia+FormatExtensions.swift - ) - --target_link_libraries(SwiftBasicFormat PUBLIC -+target_link_swift_syntax_libraries(SwiftBasicFormat PUBLIC - SwiftSyntax) -diff --git a/swift-syntax/Sources/SwiftCompilerPluginMessageHandling/CMakeLists.txt b/swift-syntax/Sources/SwiftCompilerPluginMessageHandling/CMakeLists.txt -index c6e7c42432..f01fc1f2f1 100644 ---- a/swift-syntax/Sources/SwiftCompilerPluginMessageHandling/CMakeLists.txt -+++ b/swift-syntax/Sources/SwiftCompilerPluginMessageHandling/CMakeLists.txt -@@ -6,7 +6,7 @@ - # See http://swift.org/LICENSE.txt for license information - # See http://swift.org/CONTRIBUTORS.txt for Swift project authors - --add_swift_host_library(SwiftCompilerPluginMessageHandling -+add_swift_syntax_library(SwiftCompilerPluginMessageHandling - CompilerPluginMessageHandler.swift - Diagnostics.swift - Macros.swift -@@ -15,7 +15,7 @@ add_swift_host_library(SwiftCompilerPluginMessageHandling - PluginMessages.swift - ) - --target_link_libraries(SwiftCompilerPluginMessageHandling PUBLIC -+target_link_swift_syntax_libraries(SwiftCompilerPluginMessageHandling PUBLIC - SwiftSyntax - SwiftBasicFormat - SwiftDiagnostics -diff --git a/swift-syntax/Sources/SwiftDiagnostics/CMakeLists.txt b/swift-syntax/Sources/SwiftDiagnostics/CMakeLists.txt -index 05281ea0bf..9807022350 100644 ---- a/swift-syntax/Sources/SwiftDiagnostics/CMakeLists.txt -+++ b/swift-syntax/Sources/SwiftDiagnostics/CMakeLists.txt -@@ -6,7 +6,7 @@ - # See http://swift.org/LICENSE.txt for license information - # See http://swift.org/CONTRIBUTORS.txt for Swift project authors - --add_swift_host_library(SwiftDiagnostics -+add_swift_syntax_library(SwiftDiagnostics - Diagnostic.swift - DiagnosticsFormatter.swift - FixIt.swift -@@ -16,5 +16,5 @@ add_swift_host_library(SwiftDiagnostics - Note.swift - ) - --target_link_libraries(SwiftDiagnostics PUBLIC -+target_link_swift_syntax_libraries(SwiftDiagnostics PUBLIC - SwiftSyntax) -diff --git a/swift-syntax/Sources/SwiftIDEUtils/CMakeLists.txt b/swift-syntax/Sources/SwiftIDEUtils/CMakeLists.txt -index 309fd3efa3..3909d29315 100644 ---- a/swift-syntax/Sources/SwiftIDEUtils/CMakeLists.txt -+++ b/swift-syntax/Sources/SwiftIDEUtils/CMakeLists.txt -@@ -6,11 +6,11 @@ - # See http://swift.org/LICENSE.txt for license information - # See http://swift.org/CONTRIBUTORS.txt for Swift project authors - --add_swift_host_library(SwiftIDEUtils -+add_swift_syntax_library(SwiftIDEUtils - generated/SyntaxClassification.swift - Syntax+Classifications.swift - SyntaxClassifier.swift - ) - --target_link_libraries(SwiftIDEUtils PUBLIC -+target_link_swift_syntax_libraries(SwiftIDEUtils PUBLIC - SwiftSyntax) -diff --git a/swift-syntax/Sources/SwiftOperators/CMakeLists.txt b/swift-syntax/Sources/SwiftOperators/CMakeLists.txt -index 886590411b..998b51abb6 100644 ---- a/swift-syntax/Sources/SwiftOperators/CMakeLists.txt -+++ b/swift-syntax/Sources/SwiftOperators/CMakeLists.txt -@@ -6,7 +6,7 @@ - # See http://swift.org/LICENSE.txt for license information - # See http://swift.org/CONTRIBUTORS.txt for Swift project authors - --add_swift_host_library(SwiftOperators -+add_swift_syntax_library(SwiftOperators - Operator.swift - OperatorError+Diagnostics.swift - OperatorError.swift -@@ -19,7 +19,7 @@ add_swift_host_library(SwiftOperators - SyntaxSynthesis.swift - ) - --target_link_libraries(SwiftOperators PUBLIC -+target_link_swift_syntax_libraries(SwiftOperators PUBLIC - SwiftSyntax - SwiftDiagnostics - SwiftParser) -diff --git a/swift-syntax/Sources/SwiftParser/CMakeLists.txt b/swift-syntax/Sources/SwiftParser/CMakeLists.txt -index ae849ac9de..c5cce15b45 100644 ---- a/swift-syntax/Sources/SwiftParser/CMakeLists.txt -+++ b/swift-syntax/Sources/SwiftParser/CMakeLists.txt -@@ -6,7 +6,7 @@ - # See http://swift.org/LICENSE.txt for license information - # See http://swift.org/CONTRIBUTORS.txt for Swift project authors - --add_swift_host_library(SwiftParser -+add_swift_syntax_library(SwiftParser - Attributes.swift - Availability.swift - CharacterInfo.swift -@@ -52,6 +52,6 @@ add_swift_host_library(SwiftParser - Lexer/UnicodeScalarExtensions.swift - ) - --target_link_libraries(SwiftParser PUBLIC -+target_link_swift_syntax_libraries(SwiftParser PUBLIC - SwiftSyntax - SwiftDiagnostics) -diff --git a/swift-syntax/Sources/SwiftParserDiagnostics/CMakeLists.txt b/swift-syntax/Sources/SwiftParserDiagnostics/CMakeLists.txt -index 91be323333..d73590bb0f 100644 ---- a/swift-syntax/Sources/SwiftParserDiagnostics/CMakeLists.txt -+++ b/swift-syntax/Sources/SwiftParserDiagnostics/CMakeLists.txt -@@ -6,7 +6,7 @@ - # See http://swift.org/LICENSE.txt for license information - # See http://swift.org/CONTRIBUTORS.txt for Swift project authors - --add_swift_host_library(SwiftParserDiagnostics -+add_swift_syntax_library(SwiftParserDiagnostics - DiagnosticExtensions.swift - LexerDiagnosticMessages.swift - MissingNodesError.swift -@@ -23,7 +23,7 @@ add_swift_host_library(SwiftParserDiagnostics - generated/TokenNameForDiagnostics.swift - ) - --target_link_libraries(SwiftParserDiagnostics PUBLIC -+target_link_swift_syntax_libraries(SwiftParserDiagnostics PUBLIC - SwiftBasicFormat - SwiftDiagnostics - SwiftParser -diff --git a/swift-syntax/Sources/SwiftSyntax/CMakeLists.txt b/swift-syntax/Sources/SwiftSyntax/CMakeLists.txt -index 90c10e098b..5e59ce0e23 100644 ---- a/swift-syntax/Sources/SwiftSyntax/CMakeLists.txt -+++ b/swift-syntax/Sources/SwiftSyntax/CMakeLists.txt -@@ -6,7 +6,7 @@ - # See http://swift.org/LICENSE.txt for license information - # See http://swift.org/CONTRIBUTORS.txt for Swift project authors - --add_swift_host_library(SwiftSyntax -+add_swift_syntax_library(SwiftSyntax - AbsolutePosition.swift - Assert.swift - BumpPtrAllocator.swift -diff --git a/swift-syntax/Sources/SwiftSyntaxBuilder/CMakeLists.txt b/swift-syntax/Sources/SwiftSyntaxBuilder/CMakeLists.txt -index 36f5f1c900..38858cee6f 100644 ---- a/swift-syntax/Sources/SwiftSyntaxBuilder/CMakeLists.txt -+++ b/swift-syntax/Sources/SwiftSyntaxBuilder/CMakeLists.txt -@@ -6,7 +6,7 @@ - # See http://swift.org/LICENSE.txt for license information - # See http://swift.org/CONTRIBUTORS.txt for Swift project authors - --add_swift_host_library(SwiftSyntaxBuilder -+add_swift_syntax_library(SwiftSyntaxBuilder - ConvenienceInitializers.swift - Indenter.swift - ResultBuilderExtensions.swift -@@ -30,7 +30,7 @@ add_swift_host_library(SwiftSyntaxBuilder - target_compile_options(SwiftSyntaxBuilder PRIVATE - $<$:-D;SWIFTSYNTAX_NO_OSLOG_DEPENDENCY>) - --target_link_libraries(SwiftSyntaxBuilder PUBLIC -+target_link_swift_syntax_libraries(SwiftSyntaxBuilder PUBLIC - SwiftBasicFormat - SwiftParser - SwiftParserDiagnostics -diff --git a/swift-syntax/Sources/SwiftSyntaxMacroExpansion/CMakeLists.txt b/swift-syntax/Sources/SwiftSyntaxMacroExpansion/CMakeLists.txt -index ad311fa5ee..d1a635f337 100644 ---- a/swift-syntax/Sources/SwiftSyntaxMacroExpansion/CMakeLists.txt -+++ b/swift-syntax/Sources/SwiftSyntaxMacroExpansion/CMakeLists.txt -@@ -1,4 +1,4 @@ --add_swift_host_library(SwiftSyntaxMacroExpansion -+add_swift_syntax_library(SwiftSyntaxMacroExpansion - BasicMacroExpansionContext.swift - FunctionParameterUtils.swift - MacroExpansion.swift -@@ -8,7 +8,7 @@ add_swift_host_library(SwiftSyntaxMacroExpansion - Syntax+MacroEvaluation.swift - ) - --target_link_libraries(SwiftSyntaxMacroExpansion PUBLIC -+target_link_swift_syntax_libraries(SwiftSyntaxMacroExpansion PUBLIC - SwiftSyntax - SwiftSyntaxMacros - ) -diff --git a/swift-syntax/Sources/SwiftSyntaxMacros/CMakeLists.txt b/swift-syntax/Sources/SwiftSyntaxMacros/CMakeLists.txt -index 757b5eba93..d4dd2270d2 100644 ---- a/swift-syntax/Sources/SwiftSyntaxMacros/CMakeLists.txt -+++ b/swift-syntax/Sources/SwiftSyntaxMacros/CMakeLists.txt -@@ -6,7 +6,7 @@ - # See http://swift.org/LICENSE.txt for license information - # See http://swift.org/CONTRIBUTORS.txt for Swift project authors - --add_swift_host_library(SwiftSyntaxMacros -+add_swift_syntax_library(SwiftSyntaxMacros - MacroProtocols/AccessorMacro.swift - MacroProtocols/AttachedMacro.swift - MacroProtocols/CodeItemMacro.swift -@@ -24,6 +24,6 @@ add_swift_host_library(SwiftSyntaxMacros - MacroExpansionContext.swift - ) - --target_link_libraries(SwiftSyntaxMacros PUBLIC -+target_link_swift_syntax_libraries(SwiftSyntaxMacros PUBLIC - SwiftSyntaxBuilder - ) -diff --git a/swift-syntax/cmake/modules/AddSwiftHostLibrary.cmake b/swift-syntax/cmake/modules/AddSwiftHostLibrary.cmake -index 6428f80638..951c2d2e05 100644 ---- a/swift-syntax/cmake/modules/AddSwiftHostLibrary.cmake -+++ b/swift-syntax/cmake/modules/AddSwiftHostLibrary.cmake -@@ -6,22 +6,44 @@ - # See http://swift.org/LICENSE.txt for license information - # See http://swift.org/CONTRIBUTORS.txt for Swift project authors - -+# cmake generation for Swift adds an order only dependency, which matches how C-family languages -+# works. In that case, however, ninja (and presumably other generators) will rebuild on header -+# changes. That's not the case for Swift, and thus if A -> B, A is not being rebuilt when the -+# ABI/API of B changes. -+# -+# For now workaround this by touching a file whenever B is rebuilt and then compiling that file as -+# part of A. Ideally this file would be generated by each of the targets, but that dependency didn't -+# seem to be being tracked. -+# -+# Remove once rdar://102202478 is fixed. -+function(target_link_swift_syntax_libraries TARGET) -+ cmake_parse_arguments(ARGS "" "" "PUBLIC" ${ARGN}) -+ -+ target_link_libraries(${TARGET} PUBLIC ${ARGS_PUBLIC}) -+ foreach(DEPENDENCY ${ARGS_PUBLIC}) -+ add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/forced-${DEPENDENCY}-dep.swift -+ COMMAND ${CMAKE_COMMAND} -E touch ${CMAKE_CURRENT_BINARY_DIR}/forced-${DEPENDENCY}-dep.swift -+ DEPENDS ${DEPENDENCY} -+ ) -+ target_sources(${TARGET} PRIVATE -+ ${CMAKE_CURRENT_BINARY_DIR}/forced-${DEPENDENCY}-dep.swift -+ ) -+ endforeach() -+endfunction() -+ - # Add a new host library with the given name. --function(add_swift_host_library name) -+function(add_swift_syntax_library name) - set(ASHL_SOURCES ${ARGN}) - - # Create the library target. - add_library(${name} ${ASHL_SOURCES}) - -- # Add this to the list of exported targets. -- set_property(GLOBAL APPEND PROPERTY SWIFTSYNTAX_EXPORTS ${name}) -- - # Determine where Swift modules will be built and installed. - set(module_dir ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) - set(module_base "${module_dir}/${name}.swiftmodule") -- set(module_file "${module_base}/${SWIFT_MODULE_TRIPLE}.swiftmodule") -- set(module_interface_file "${module_base}/${SWIFT_MODULE_TRIPLE}.swiftinterface") -- set(module_sourceinfo_file "${module_base}/${SWIFT_MODULE_TRIPLE}.swiftsourceinfo") -+ set(module_file "${module_base}/${SWIFT_HOST_MODULE_TRIPLE}.swiftmodule") -+ set(module_interface_file "${module_base}/${SWIFT_HOST_MODULE_TRIPLE}.swiftinterface") -+ set(module_sourceinfo_file "${module_base}/${SWIFT_HOST_MODULE_TRIPLE}.swiftsourceinfo") - - # Add a custom target to create the module directory. - add_custom_command( -@@ -61,6 +83,18 @@ function(add_swift_host_library name) - -emit-module-interface-path;${module_interface_file} - >) - -+ if(SWIFT_HOST_TRIPLE) -+ target_compile_options("${name}" PRIVATE -+ $<$:-target;${SWIFT_HOST_TRIPLE};> -+ ) -+ endif() -+ -+ if(LLVM_USE_LINKER) -+ target_link_options(${name} PRIVATE -+ "-use-ld=${LLVM_USE_LINKER}" -+ ) -+ endif() -+ - # NOTE: workaround for CMake not setting up include flags yet - set_target_properties(${name} PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${module_dir} -@@ -70,31 +104,39 @@ function(add_swift_host_library name) - BUILD_WITH_INSTALL_RPATH YES - ) - -+ if(SWIFT_HOST_LIBRARIES_RPATH) -+ # Don't add builder's stdlib RPATH automatically. -+ target_compile_options(${name} PRIVATE -no-toolchain-stdlib-rpath) -+ set_property(TARGET ${name} -+ PROPERTY INSTALL_RPATH "${SWIFT_HOST_LIBRARIES_RPATH}" -+ ) -+ endif() -+ - get_target_property(lib_type ${name} TYPE) - if(lib_type STREQUAL SHARED_LIBRARY) - if (CMAKE_SYSTEM_NAME STREQUAL Darwin) - # Allow install_name_tool to update paths (for rdar://109473564) - set_property(TARGET ${name} APPEND_STRING PROPERTY - LINK_FLAGS " -Xlinker -headerpad_max_install_names") -- elseif (CMAKE_SYSTEM_NAME STREQUAL Linux) -- # Make some room to update paths. -- set_property(TARGET ${name} APPEND PROPERTY -- INSTALL_RPATH ":::::::::::::::::::::::::::::::::::::::::::::::::::::::") - endif() - endif() - -- # Install this target -- install(TARGETS ${name} -- EXPORT SwiftSyntaxTargets -- ARCHIVE DESTINATION lib/${SWIFT_HOST_LIBRARIES_SUBDIRECTORY} -- LIBRARY DESTINATION lib/${SWIFT_HOST_LIBRARIES_SUBDIRECTORY} -- RUNTIME DESTINATION bin -- ) -+ if(PROJECT_IS_TOP_LEVEL) -+ # Install this target -+ install(TARGETS ${name} -+ EXPORT SwiftSyntaxTargets -+ ARCHIVE DESTINATION lib/${SWIFT_HOST_LIBRARIES_SUBDIRECTORY} -+ LIBRARY DESTINATION lib/${SWIFT_HOST_LIBRARIES_SUBDIRECTORY} -+ RUNTIME DESTINATION bin -+ ) - -- # Install the module files. -- install( -- DIRECTORY ${module_base} -- DESTINATION lib/${SWIFT_HOST_LIBRARIES_SUBDIRECTORY} -- FILES_MATCHING PATTERN "*.swiftinterface" -- ) -+ # Install the module files. -+ install( -+ DIRECTORY ${module_base} -+ DESTINATION lib/${SWIFT_HOST_LIBRARIES_SUBDIRECTORY} -+ FILES_MATCHING PATTERN "*.swiftinterface" -+ ) -+ else() -+ set_property(GLOBAL APPEND PROPERTY SWIFT_EXPORTS ${name}) -+ endif() - endfunction() -diff --git a/swift-syntax/cmake/modules/CMakeLists.txt b/swift-syntax/cmake/modules/CMakeLists.txt -deleted file mode 100644 -index 069c64c0af..0000000000 ---- a/swift-syntax/cmake/modules/CMakeLists.txt -+++ /dev/null -@@ -1,4 +0,0 @@ --get_property(SWIFTSYNTAX_EXPORTS GLOBAL PROPERTY SWIFTSYNTAX_EXPORTS) --export(TARGETS ${SWIFTSYNTAX_EXPORTS} -- FILE ${CMAKE_CURRENT_BINARY_DIR}/SwiftSyntaxConfig.cmake -- NAMESPACE SwiftSyntax::) diff --git a/packages/swift/swift-syntax-regex-cross-compile.patch b/packages/swift/swift-syntax-regex-cross-compile.patch deleted file mode 100644 index 42a1107de2..0000000000 --- a/packages/swift/swift-syntax-regex-cross-compile.patch +++ /dev/null @@ -1,164 +0,0 @@ -diff --git a/swift/CMakeLists.txt b/swift/CMakeLists.txt -index 28dfded4ecc..45c68998bec 100644 ---- a/swift/CMakeLists.txt -+++ b/swift/CMakeLists.txt -@@ -950,7 +950,7 @@ endif() - - if(SWIFT_BUILD_SWIFT_SYNTAX) - # Only "HOSTTOOLS" is supported in Linux when Swift parser integration is enabled. -- if(SWIFT_HOST_VARIANT_SDK MATCHES "LINUX|ANDROID|OPENBSD|FREEBSD" AND NOT BOOTSTRAPPING_MODE STREQUAL "HOSTTOOLS") -+ if(SWIFT_HOST_VARIANT_SDK MATCHES "LINUX|ANDROID|OPENBSD|FREEBSD" AND NOT BOOTSTRAPPING_MODE MATCHES "HOSTTOOLS|OFF") - message(WARNING "Force setting BOOTSTRAPPING=HOSTTOOLS because Swift parser integration is enabled") - set(BOOTSTRAPPING_MODE "HOSTTOOLS") - endif() -@@ -1345,6 +1345,9 @@ if(SWIFT_INCLUDE_TOOLS) - FetchContent_MakeAvailable(SwiftSyntax) - endfunction() - include_swift_syntax() -+ if (NOT "${SWIFT_ANDROID_NDK_PATH}" STREQUAL "") -+ add_dependencies(SwiftSyntax swift-stdlib-android-${SWIFT_HOST_VARIANT_ARCH}) -+ endif() - - add_subdirectory(lib) - -diff --git a/swift/cmake/modules/AddPureSwift.cmake b/swift/cmake/modules/AddPureSwift.cmake -index dc58b8fa0f6..37e9f817471 100644 ---- a/swift/cmake/modules/AddPureSwift.cmake -+++ b/swift/cmake/modules/AddPureSwift.cmake -@@ -44,6 +44,13 @@ function(_add_host_swift_compile_options name) - $<$:none>) - - target_compile_options(${name} PRIVATE $<$:-target;${SWIFT_HOST_TRIPLE}>) -+ if (NOT "${SWIFT_ANDROID_NDK_PATH}" STREQUAL "") -+ swift_android_tools_path(${SWIFT_HOST_VARIANT_ARCH} tools_path) -+ target_compile_options(${name} PRIVATE $<$:-resource-dir;${SWIFTLIB_DIR};> -+ $<$:-sdk;${SWIFT_SDK_ANDROID_ARCH_${SWIFT_HOST_VARIANT_ARCH}_PATH};> -+ $<$:-tools-directory;${tools_path};>) -+ add_dependencies(${name} swift-stdlib-android-${SWIFT_HOST_VARIANT_ARCH}) -+ endif() - _add_host_variant_swift_sanitizer_flags(${name}) - endfunction() - -@@ -76,7 +76,7 @@ function(_set_pure_swift_link_flags name relpath_to_lib_dir) - APPEND PROPERTY INSTALL_RPATH - # At runtime, use swiftCore in the current just-built toolchain. - # NOTE: This relies on the ABI being the same as the builder. -- "$ORIGIN/${relpath_to_lib_dir}/swift/${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_LIB_SUBDIR}" -+ "$ORIGIN/${relpath_to_lib_dir}" - ) - # NOTE: At this point we don't have any pure swift executables/shared - # libraries required for building runtime/stdlib. So we don't need to add -diff --git a/swift/cmake/modules/AddSwift.cmake b/swift/cmake/modules/AddSwift.cmake -index ecdea6de266..777ea384050 100644 ---- a/swift/cmake/modules/AddSwift.cmake -+++ b/swift/cmake/modules/AddSwift.cmake -@@ -442,7 +442,11 @@ endfunction() - function(_add_swift_runtime_link_flags target relpath_to_lib_dir bootstrapping) - if(NOT BOOTSTRAPPING_MODE) - if (SWIFT_BUILD_SWIFT_SYNTAX) -- set(ASRLF_BOOTSTRAPPING_MODE "HOSTTOOLS") -+ if (NOT "${SWIFT_ANDROID_NDK_PATH}" STREQUAL "") -+ set(ASRLF_BOOTSTRAPPING_MODE "CROSSCOMPILE") -+ else() -+ set(ASRLF_BOOTSTRAPPING_MODE "HOSTTOOLS") -+ endif() - else() - return() - endif() -diff --git a/swift/stdlib/cmake/modules/SwiftSource.cmake b/swift/stdlib/cmake/modules/SwiftSource.cmake ---- a/swift/stdlib/cmake/modules/SwiftSource.cmake -+++ b/swift/stdlib/cmake/modules/SwiftSource.cmake -@@ -777,7 +777,7 @@ - endif() - - set(swift_compiler_tool_dep) -- if(SWIFT_INCLUDE_TOOLS AND NOT ${BOOTSTRAPPING_MODE} STREQUAL "CROSSCOMPILE") -+ if(SWIFT_INCLUDE_TOOLS AND NOT ${BOOTSTRAPPING_MODE} STREQUAL "CROSSCOMPILE" AND "${SWIFT_ANDROID_NDK_PATH}" STREQUAL "") - # Depend on the binary itself, in addition to the symlink. - set(swift_compiler_tool_dep "swift-frontend${target_suffix}") - endif() -diff --git a/swift/tools/libStaticMirror/CMakeLists.txt b/swift/tools/libStaticMirror/CMakeLists.txt -index 1b8c563b05a..463faab64de 100644 ---- a/swift/tools/libStaticMirror/CMakeLists.txt -+++ b/swift/tools/libStaticMirror/CMakeLists.txt -@@ -28,6 +28,9 @@ add_llvm_symbol_exports(libStaticMirror ${LLVM_EXPORTED_SYMBOL_FILE}) - - # Adds -dead_strip option - add_link_opts(libStaticMirror) -+if(SWIFT_HOST_VARIANT_SDK STREQUAL "ANDROID") -+ target_link_options(libStaticMirror PRIVATE "SHELL:-Xlinker -z -Xlinker nostart-stop-gc") -+endif() - - add_dependencies(static-mirror-lib libStaticMirror) - swift_install_in_component(TARGETS libStaticMirror -diff --git a/swift/tools/libSwiftScan/CMakeLists.txt b/swift/tools/libSwiftScan/CMakeLists.txt -index 1a99080337f..163a8d45690 100644 ---- a/swift/tools/libSwiftScan/CMakeLists.txt -+++ b/swift/tools/libSwiftScan/CMakeLists.txt -@@ -66,6 +66,9 @@ add_llvm_symbol_exports(libSwiftScan ${LLVM_EXPORTED_SYMBOL_FILE}) - - # Adds -dead_strip option - add_link_opts(libSwiftScan) -+if(SWIFT_HOST_VARIANT_SDK STREQUAL "ANDROID") -+ target_link_options(libSwiftScan PRIVATE "SHELL:-Xlinker -z -Xlinker nostart-stop-gc") -+endif() - - add_dependencies(compiler libSwiftScan) - -diff --git a/swift/tools/swift-plugin-server/CMakeLists.txt b/swift/tools/swift-plugin-server/CMakeLists.txt -index a21b79ed260..5b591a30514 100644 ---- a/swift/tools/swift-plugin-server/CMakeLists.txt -+++ b/swift/tools/swift-plugin-server/CMakeLists.txt -@@ -1,28 +1,19 @@ - if (SWIFT_BUILD_SWIFT_SYNTAX) -- # _swiftCSwiftPluginServer is just a C support library for swift-plugin-server -- # Don't bother to create '.a' for that. -- add_swift_host_library(_swiftCSwiftPluginServer OBJECT -- Sources/CSwiftPluginServer/PluginServer.cpp -- ) -- target_link_libraries(_swiftCSwiftPluginServer PRIVATE -- swiftDemangling -+ add_swift_host_tool(swift-plugin-server SWIFT_COMPONENT compiler Sources/CSwiftPluginServer/PluginServer.cpp) -+ add_pure_swift_host_library(SwiftPluginServer STATIC -+ Sources/swift-plugin-server/swift-plugin-server.swift - ) -- target_include_directories(_swiftCSwiftPluginServer PUBLIC -+ target_include_directories(SwiftPluginServer PUBLIC - Sources/CSwiftPluginServer/include - ) -- -- add_pure_swift_host_tool(swift-plugin-server -- Sources/swift-plugin-server/swift-plugin-server.swift -- DEPENDENCIES -+ target_link_libraries(SwiftPluginServer PRIVATE SwiftCompilerPluginMessageHandling) -+ target_link_libraries(swift-plugin-server PRIVATE - swiftDemangling -- $ -- SWIFT_COMPONENT -- compiler -- SWIFT_DEPENDENCIES - SwiftSyntaxMacros - SwiftSyntaxMacroExpansion - SwiftCompilerPluginMessageHandling - swiftLLVMJSON -+ SwiftPluginServer - ) - target_include_directories(swift-plugin-server PRIVATE - Sources/CSwiftPluginServer/include -diff --git a/swift-syntax/cmake/modules/AddSwiftHostLibrary.cmake b/swift-syntax/cmake/modules/AddSwiftHostLibrary.cmake -index 951c2d2e..1157ec66 100644 ---- a/swift-syntax/cmake/modules/AddSwiftHostLibrary.cmake -+++ b/swift-syntax/cmake/modules/AddSwiftHostLibrary.cmake -@@ -87,6 +87,12 @@ function(add_swift_syntax_library name) - target_compile_options("${name}" PRIVATE - $<$:-target;${SWIFT_HOST_TRIPLE};> - ) -+ if (NOT "${SWIFT_ANDROID_NDK_PATH}" STREQUAL "") -+ swift_android_tools_path(${SWIFT_HOST_VARIANT_ARCH} tools_path) -+ target_compile_options(${name} PRIVATE $<$:-resource-dir;${SWIFTLIB_DIR};> -+ $<$:-sdk;${SWIFT_SDK_ANDROID_ARCH_${SWIFT_HOST_VARIANT_ARCH}_PATH};> -+ $<$:-tools-directory;${tools_path};>) -+ endif() - endif() - - if(LLVM_USE_LINKER) diff --git a/packages/swift/swift-syntax-unimplementable-missing.patch b/packages/swift/swift-syntax-unimplementable-missing.patch deleted file mode 100644 index a5ef7a59ae..0000000000 --- a/packages/swift/swift-syntax-unimplementable-missing.patch +++ /dev/null @@ -1,32 +0,0 @@ -commit 1a7d44a11d4f06882c4a563b67e1f1b864c4c794 -Author: John McCall -Date: Tue Jul 18 13:21:12 2023 -0400 - - Diagnose attempts to reabstract variadic function types in unimplementable ways. - -diff --git a/swift/include/swift/AST/CASTBridging.h b/swift/include/swift/AST/CASTBridging.h -index 69f017855d7..6cb23ad4c85 100644 ---- a/swift/include/swift/AST/CASTBridging.h -+++ b/swift/include/swift/AST/CASTBridging.h -@@ -190,6 +190,7 @@ typedef enum ENUM_EXTENSIBILITY_ATTR(closed) BridgedTypeAttrKind : long { - BridgedTypeAttrKind_opened, - BridgedTypeAttrKind_pack_element, - BridgedTypeAttrKind_pseudogeneric, -+ BridgedTypeAttrKind_unimplementable, - BridgedTypeAttrKind_yields, - BridgedTypeAttrKind_yield_once, - BridgedTypeAttrKind_yield_many, -diff --git a/swift/lib/ASTGen/Sources/ASTGen/Types.swift b/swift/lib/ASTGen/Sources/ASTGen/Types.swift -index 34a185fe13f..89eec154f03 100644 ---- a/swift/lib/ASTGen/Sources/ASTGen/Types.swift -+++ b/swift/lib/ASTGen/Sources/ASTGen/Types.swift -@@ -222,7 +222,8 @@ extension ASTGenVisitor { - case .autoclosure, .escaping, .noescape, .noDerivative, .async, - .sendable, .unchecked, ._local, ._noMetadata, .pack_owned, - .pack_guaranteed, .pack_inout, .pack_out, .pseudogeneric, -- .yields, .yield_once, .yield_many, .thin, .thick, .count: -+ .yields, .yield_once, .yield_many, .thin, .thick, .count, -+ .unimplementable: - TypeAttributes_addSimpleAttr(typeAttributes, typeAttrKind, atLoc, attrLoc) - - case .opened, .pack_element, .differentiable, .convention, diff --git a/packages/swift/swift-tools-support-core-ndk26.patch b/packages/swift/swift-tools-support-core-ndk26.patch new file mode 100644 index 0000000000..1e2f718588 --- /dev/null +++ b/packages/swift/swift-tools-support-core-ndk26.patch @@ -0,0 +1,105 @@ +From 19546b1f4439659fe256fa62c74ecbfc3fb527ee +Date: Wed, 3 Jan 2024 22:32:35 +0530 +Subject: [PATCH] Android: add better nullability checks for nullability + annotations added in NDK 26 (#444) + +Also fix one test. + +diff --git a/swift-tools-support-core/Sources/TSCBasic/FileSystem.swift b/swift-tools-support-core/Sources/TSCBasic/FileSystem.swift +index b33b1c61..1d260331 100644 +--- a/swift-tools-support-core/Sources/TSCBasic/FileSystem.swift ++++ b/swift-tools-support-core/Sources/TSCBasic/FileSystem.swift +@@ -491,8 +491,7 @@ private struct LocalFileSystem: FileSystem { + + func readFileContents(_ path: AbsolutePath) throws -> ByteString { + // Open the file. +- let fp = fopen(path.pathString, "rb") +- if fp == nil { ++ guard let fp = fopen(path.pathString, "rb") else { + throw FileSystemError(errno: errno, path) + } + defer { fclose(fp) } +@@ -521,8 +520,7 @@ private struct LocalFileSystem: FileSystem { + + func writeFileContents(_ path: AbsolutePath, bytes: ByteString) throws { + // Open the file. +- let fp = fopen(path.pathString, "wb") +- if fp == nil { ++ guard let fp = fopen(path.pathString, "wb") else { + throw FileSystemError(errno: errno, path) + } + defer { fclose(fp) } +diff --git a/swift-tools-support-core/Sources/TSCBasic/Process.swift b/swift-tools-support-core/Sources/TSCBasic/Process.swift +index 6c8aa117..89d3a5be 100644 +--- a/swift-tools-support-core/Sources/TSCBasic/Process.swift ++++ b/swift-tools-support-core/Sources/TSCBasic/Process.swift +@@ -144,6 +144,9 @@ public final class Process { + + /// The current OS does not support the workingDirectory API. + case workingDirectoryNotSupported ++ ++ /// The stdin could not be opened. ++ case stdinUnavailable + } + + public enum OutputRedirection { +@@ -677,7 +680,10 @@ public final class Process { + var stdinPipe: [Int32] = [-1, -1] + try open(pipe: &stdinPipe) + +- let stdinStream = try LocalFileOutputByteStream(filePointer: fdopen(stdinPipe[1], "wb"), closeOnDeinit: true) ++ guard let fp = fdopen(stdinPipe[1], "wb") else { ++ throw Process.Error.stdinUnavailable ++ } ++ let stdinStream = try LocalFileOutputByteStream(filePointer: fp, closeOnDeinit: true) + + // Dupe the read portion of the remote to 0. + posix_spawn_file_actions_adddup2(&fileActions, stdinPipe[0], 0) +@@ -1258,6 +1264,8 @@ extension Process.Error: CustomStringConvertible { + return "could not find executable for '\(program)'" + case .workingDirectoryNotSupported: + return "workingDirectory is not supported in this platform" ++ case .stdinUnavailable: ++ return "could not open stdin on this platform" + } + } + } +diff --git a/swift-tools-support-core/Sources/TSCBasic/WritableByteStream.swift b/swift-tools-support-core/Sources/TSCBasic/WritableByteStream.swift +index aee907e3..5b6e4c2c 100644 +--- a/swift-tools-support-core/Sources/TSCBasic/WritableByteStream.swift ++++ b/swift-tools-support-core/Sources/TSCBasic/WritableByteStream.swift +@@ -790,7 +790,7 @@ public final class LocalFileOutputByteStream: FileOutputByteStream { + override final func writeImpl(_ bytes: ArraySlice) { + bytes.withUnsafeBytes { bytesPtr in + while true { +- let n = fwrite(bytesPtr.baseAddress, 1, bytesPtr.count, filePointer) ++ let n = fwrite(bytesPtr.baseAddress!, 1, bytesPtr.count, filePointer) + if n < 0 { + if errno == EINTR { continue } + errorDetected(code: errno) +diff --git a/swift-tools-support-core/Sources/TSCTestSupport/PseudoTerminal.swift b/swift-tools-support-core/Sources/TSCTestSupport/PseudoTerminal.swift +index 59610b61..2797c719 100644 +--- a/swift-tools-support-core/Sources/TSCTestSupport/PseudoTerminal.swift ++++ b/swift-tools-support-core/Sources/TSCTestSupport/PseudoTerminal.swift +@@ -24,7 +24,7 @@ public final class PseudoTerminal { + if openpty(&primary, &secondary, nil, nil, nil) != 0 { + return nil + } +- guard let outStream = try? LocalFileOutputByteStream(filePointer: fdopen(secondary, "w"), closeOnDeinit: false) else { ++ guard let outStream = try? LocalFileOutputByteStream(filePointer: fdopen(secondary, "w")!, closeOnDeinit: false) else { + return nil + } + self.outStream = outStream +diff --git a/swift-tools-support-core/Tests/TSCBasicTests/PathShimTests.swift b/swift-tools-support-core/Tests/TSCBasicTests/PathShimTests.swift +index 1af04a37..76fd6324 100644 +--- a/swift-tools-support-core/Tests/TSCBasicTests/PathShimTests.swift ++++ b/swift-tools-support-core/Tests/TSCBasicTests/PathShimTests.swift +@@ -39,7 +39,7 @@ class WalkTests : XCTestCase { + var expected: [AbsolutePath] = [ + "\(root)/usr", + "\(root)/bin", +- "\(root)/xbin" ++ "\(root)/etc" + ] + #else + let root = "" diff --git a/packages/swift/swift-utils-build-script-impl-flags.patch b/packages/swift/swift-utils-build-script-impl-flags.patch index 3a80dfddef..f465218246 100644 --- a/packages/swift/swift-utils-build-script-impl-flags.patch +++ b/packages/swift/swift-utils-build-script-impl-flags.patch @@ -10,11 +10,13 @@ index b1d060328bc..218c9215260 100755 if [[ ! "${SKIP_BUILD_ANDROID}" ]] || [[ $(is_cross_tools_host ${host}) && "${host}" == "android-"* ]]; then cmake_options=( -@@ -1733,6 +1734,7 @@ +@@ -1733,7 +1734,9 @@ + -DSWIFT_ANDROID_NDK_PATH:STRING="${ANDROID_NDK}" -DSWIFT_ANDROID_DEPLOY_DEVICE_PATH:STRING="${ANDROID_DEPLOY_DEVICE_PATH}" -DSWIFT_SDK_ANDROID_ARCHITECTURES:STRING="${ANDROID_ARCH}" ++ -DBRIDGING_MODE:STRING="PURE" ) -+ cross_c_flags="--target=$CCTERMUX_HOST_PLATFORM" ++ cross_c_flags="$CFLAGS --target=$CCTERMUX_HOST_PLATFORM" fi if [[ ! "${SKIP_BUILD_WASM}" ]]; then @@ -54,9 +56,9 @@ index b1d060328bc..218c9215260 100755 -DCMAKE_CXX_FLAGS_RELWITHDEBINFO="-O2 -DNDEBUG" -DCMAKE_BUILD_TYPE:STRING="${SWIFT_BUILD_TYPE}" @@ -1878,6 +1891,7 @@ - -DLIBDISPATCH_CMAKE_BUILD_TYPE:STRING="${LIBDISPATCH_BUILD_TYPE}" -DSWIFT_PATH_TO_SWIFT_SYNTAX_SOURCE:PATH="${SWIFT_SYNTAX_SOURCE_DIR}" -DSWIFT_ENABLE_BACKTRACING:BOOL=$(true_false "${SWIFT_ENABLE_BACKTRACING}") + -DSWIFT_STDLIB_OVERRIDABLE_RETAIN_RELEASE:BOOL=$(true_false "${SWIFT_STDLIB_OVERRIDABLE_RETAIN_RELEASE}") + -DSWIFT_CLANG_RESOURCE_DIR_SYMLINK_INSTALL_TARGET:STRING="../clang/${TERMUX_CLANG_VERSION}" "${swift_cmake_options[@]}" ) @@ -70,7 +72,17 @@ index b1d060328bc..218c9215260 100755 ) fi -@@ -2199,6 +2201,9 @@ for host in "${ALL_HOSTS[@]}"; do +@@ -2388,7 +2404,8 @@ + -DENABLE_TESTING=YES + ) + if [[ $(is_cross_tools_host ${host}) ]] ; then +- cmake_options+=("${SWIFT_TARGET_CMAKE_OPTIONS[@]}") ++ cmake_options+=("${SWIFT_TARGET_CMAKE_OPTIONS[@]}" ++ -DCMAKE_C_FLAGS="$CFLAGS --target=$CCTERMUX_HOST_PLATFORM $CPPFLAGS") + fi + ;; + esac +@@ -2537,6 +2554,9 @@ # https://cmake.org/cmake/help/latest/command/find_package.html cmake_options+=( -DCMAKE_FIND_ROOT_PATH:PATH="${CROSS_COMPILE_DEPS_PATH}" @@ -80,7 +92,7 @@ index b1d060328bc..218c9215260 100755 ) fi if [[ "${host}" == "android-"* ]]; then -@@ -2239,6 +2243,11 @@ for host in "${ALL_HOSTS[@]}"; do +@@ -2583,6 +2603,11 @@ ) if [[ $(is_cross_tools_host ${host}) ]] ; then cmake_options+=("${SWIFT_TARGET_CMAKE_OPTIONS[@]}") diff --git a/packages/swift/swiftpm-disable-local-rpath.patch b/packages/swift/swiftpm-disable-local-rpath.patch deleted file mode 100644 index a3d75f94ea..0000000000 --- a/packages/swift/swiftpm-disable-local-rpath.patch +++ /dev/null @@ -1,278 +0,0 @@ -commit 78b88bb6bc428f651ae615a944d985858e0a60f0 -Date: Mon Sep 25 02:19:40 2023 +0530 - - Add an rpath flag to disable the default of looking in the local directory for shared libraries - - This is useful when deploying build products, as most executables are not installed - in the same directory as libraries and system libraries do not need it for - system paths. Use the new flag when installing SwiftPM itself and the {Manifest,Plugin}API - libraries on ELF platforms. - -diff --git a/swiftpm/Sources/Build/BuildDescription/ProductBuildDescription.swift b/swiftpm/Sources/Build/BuildDescription/ProductBuildDescription.swift -index 7aed35e48..5fdb9b4e5 100644 ---- a/swiftpm/Sources/Build/BuildDescription/ProductBuildDescription.swift -+++ b/swiftpm/Sources/Build/BuildDescription/ProductBuildDescription.swift -@@ -257,12 +257,14 @@ public final class ProductBuildDescription: SPMBuildCore.ProductBuildDescription - } - - // Set rpath such that dynamic libraries are looked up -- // adjacent to the product. -- if self.buildParameters.triple.isLinux() { -- args += ["-Xlinker", "-rpath=$ORIGIN"] -- } else if self.buildParameters.triple.isDarwin() { -- let rpath = self.product.type == .test ? "@loader_path/../../../" : "@loader_path" -- args += ["-Xlinker", "-rpath", "-Xlinker", rpath] -+ // adjacent to the product, unless overridden. -+ if !self.buildParameters.shouldDisableLocalRpath { -+ if self.buildParameters.triple.isLinux() { -+ args += ["-Xlinker", "-rpath=$ORIGIN"] -+ } else if self.buildParameters.triple.isDarwin() { -+ let rpath = self.product.type == .test ? "@loader_path/../../../" : "@loader_path" -+ args += ["-Xlinker", "-rpath", "-Xlinker", rpath] -+ } - } - args += ["@\(self.linkFileListPath.pathString)"] - -diff --git a/swiftpm/Sources/CoreCommands/Options.swift b/swiftpm/Sources/CoreCommands/Options.swift -index d09b28d6a..739db470e 100644 ---- a/swiftpm/Sources/CoreCommands/Options.swift -+++ b/swiftpm/Sources/CoreCommands/Options.swift -@@ -524,6 +524,10 @@ public struct LinkerOptions: ParsableArguments { - /// If should link the Swift stdlib statically. - @Flag(name: .customLong("static-swift-stdlib"), inversion: .prefixedNo, help: "Link Swift stdlib statically") - public var shouldLinkStaticSwiftStdlib: Bool = false -+ -+ /// Disables adding $ORIGIN/@loader_path to the rpath, useful when deploying -+ @Flag(name: .customLong("disable-local-rpath"), help: "Disable adding $ORIGIN/@loader_path to the rpath by default") -+ public var shouldDisableLocalRpath: Bool = false - } - - // MARK: - Extensions -diff --git a/swiftpm/Sources/CoreCommands/SwiftTool.swift b/swiftpm/Sources/CoreCommands/SwiftTool.swift -index 72e8be958..b99b80770 100644 ---- a/swiftpm/Sources/CoreCommands/SwiftTool.swift -+++ b/swiftpm/Sources/CoreCommands/SwiftTool.swift -@@ -683,6 +683,7 @@ public final class SwiftTool { - architectures: options.build.architectures, - workers: options.build.jobs ?? UInt32(ProcessInfo.processInfo.activeProcessorCount), - shouldLinkStaticSwiftStdlib: options.linker.shouldLinkStaticSwiftStdlib, -+ shouldDisableLocalRpath: options.linker.shouldDisableLocalRpath, - canRenameEntrypointFunctionName: driverSupport.checkSupportedFrontendFlags( - flags: ["entry-point-function-name"], - toolchain: toolchain, -diff --git a/swiftpm/Sources/SPMBuildCore/BuildParameters.swift b/swiftpm/Sources/SPMBuildCore/BuildParameters.swift -index 57825c6e4..bbb3c2cc3 100644 ---- a/swiftpm/Sources/SPMBuildCore/BuildParameters.swift -+++ b/swiftpm/Sources/SPMBuildCore/BuildParameters.swift -@@ -190,6 +190,9 @@ public struct BuildParameters: Encodable { - /// If should link the Swift stdlib statically. - public var shouldLinkStaticSwiftStdlib: Bool - -+ /// Disables adding $ORIGIN/@loader_path to the rpath, useful when deploying -+ public var shouldDisableLocalRpath: Bool -+ - /// Which compiler sanitizers should be enabled - public var sanitizers: EnabledSanitizers - -@@ -362,6 +365,7 @@ public struct BuildParameters: Encodable { - architectures: [String]? = nil, - workers: UInt32 = UInt32(ProcessInfo.processInfo.activeProcessorCount), - shouldLinkStaticSwiftStdlib: Bool = false, -+ shouldDisableLocalRpath: Bool = false, - shouldEnableManifestCaching: Bool = false, - canRenameEntrypointFunctionName: Bool = false, - shouldCreateDylibForDynamicProducts: Bool = true, -@@ -424,6 +428,7 @@ public struct BuildParameters: Encodable { - self.architectures = architectures - self.workers = workers - self.shouldLinkStaticSwiftStdlib = shouldLinkStaticSwiftStdlib -+ self.shouldDisableLocalRpath = shouldDisableLocalRpath - self.shouldEnableManifestCaching = shouldEnableManifestCaching - self.shouldCreateDylibForDynamicProducts = shouldCreateDylibForDynamicProducts - self.canRenameEntrypointFunctionName = canRenameEntrypointFunctionName -@@ -487,6 +492,7 @@ public struct BuildParameters: Encodable { - architectures: nil, - workers: self.workers, - shouldLinkStaticSwiftStdlib: self.shouldLinkStaticSwiftStdlib, -+ shouldDisableLocalRpath: self.shouldDisableLocalRpath, - shouldEnableManifestCaching: self.shouldEnableManifestCaching, - canRenameEntrypointFunctionName: self.canRenameEntrypointFunctionName, - shouldCreateDylibForDynamicProducts: self.shouldCreateDylibForDynamicProducts, -diff --git a/swiftpm/Sources/swift-bootstrap/main.swift b/swiftpm/Sources/swift-bootstrap/main.swift -index 9f45edf51..5c80a5249 100644 ---- a/swiftpm/Sources/swift-bootstrap/main.swift -+++ b/swiftpm/Sources/swift-bootstrap/main.swift -@@ -118,6 +118,10 @@ struct SwiftBootstrapBuildTool: ParsableCommand { - @Flag() - public var useIntegratedSwiftDriver: Bool = false - -+ /// Disables adding $ORIGIN/@loader_path to the rpath, useful when deploying -+ @Flag(name: .customLong("disable-local-rpath"), help: "Disable adding $ORIGIN/@loader_path to the rpath by default") -+ public var shouldDisableLocalRpath: Bool = false -+ - private var buildSystem: BuildSystemProvider.Kind { - #if os(macOS) - // Force the Xcode build system if we want to build more than one arch. -@@ -188,7 +192,8 @@ struct SwiftBootstrapBuildTool: ParsableCommand { - architectures: self.architectures, - buildFlags: self.buildFlags, - manifestBuildFlags: self.manifestFlags, -- useIntegratedSwiftDriver: self.useIntegratedSwiftDriver -+ useIntegratedSwiftDriver: self.useIntegratedSwiftDriver, -+ shouldDisableLocalRpath: self.shouldDisableLocalRpath - ) - } catch _ as Diagnostics { - throw ExitCode.failure -@@ -232,7 +237,8 @@ struct SwiftBootstrapBuildTool: ParsableCommand { - architectures: [String], - buildFlags: BuildFlags, - manifestBuildFlags: [String], -- useIntegratedSwiftDriver: Bool -+ useIntegratedSwiftDriver: Bool, -+ shouldDisableLocalRpath: Bool - ) throws { - let buildSystem = try createBuildSystem( - packagePath: packagePath, -@@ -244,6 +250,7 @@ struct SwiftBootstrapBuildTool: ParsableCommand { - buildFlags: buildFlags, - manifestBuildFlags: manifestBuildFlags, - useIntegratedSwiftDriver: useIntegratedSwiftDriver, -+ shouldDisableLocalRpath: shouldDisableLocalRpath, - logLevel: logLevel - ) - try buildSystem.build(subset: .allExcludingTests) -@@ -259,6 +266,7 @@ struct SwiftBootstrapBuildTool: ParsableCommand { - buildFlags: BuildFlags, - manifestBuildFlags: [String], - useIntegratedSwiftDriver: Bool, -+ shouldDisableLocalRpath: Bool, - logLevel: Basics.Diagnostic.Severity - ) throws -> BuildSystem { - -@@ -277,6 +285,7 @@ struct SwiftBootstrapBuildTool: ParsableCommand { - destinationTriple: self.destinationToolchain.triple, - flags: buildFlags, - architectures: architectures, -+ shouldDisableLocalRpath: shouldDisableLocalRpath, - useIntegratedSwiftDriver: useIntegratedSwiftDriver, - isXcodeBuildSystemEnabled: buildSystem == .xcode, - verboseOutput: logLevel <= .info -diff --git a/swiftpm/Tests/BuildTests/BuildPlanTests.swift b/swiftpm/Tests/BuildTests/BuildPlanTests.swift -index 768952986..c847afd52 100644 ---- a/swiftpm/Tests/BuildTests/BuildPlanTests.swift -+++ b/swiftpm/Tests/BuildTests/BuildPlanTests.swift -@@ -5021,4 +5021,80 @@ final class BuildPlanTests: XCTestCase { - - XCTAssertMatch(try result.buildProduct(for: "exe").linkArguments(), ["-sanitize=\(expectedName)"]) - } -+ -+ func testBasicSwiftPackageWithoutLocalRpath() throws { -+ let fs = InMemoryFileSystem(emptyFiles: -+ "/Pkg/Sources/exe/main.swift", -+ "/Pkg/Sources/lib/lib.swift" -+ ) -+ -+ let observability = ObservabilitySystem.makeForTesting() -+ let graph = try loadPackageGraph( -+ fileSystem: fs, -+ manifests: [ -+ Manifest.createRootManifest( -+ displayName: "Pkg", -+ path: "/Pkg", -+ targets: [ -+ TargetDescription(name: "exe", dependencies: ["lib"]), -+ TargetDescription(name: "lib", dependencies: []), -+ ]), -+ ], -+ observabilityScope: observability.topScope -+ ) -+ XCTAssertNoDiagnostics(observability.diagnostics) -+ -+ let result = try BuildPlanResult(plan: BuildPlan( -+ buildParameters: mockBuildParameters(shouldDisableLocalRpath: true), -+ graph: graph, -+ fileSystem: fs, -+ observabilityScope: observability.topScope -+ )) -+ -+ result.checkProductsCount(1) -+ result.checkTargetsCount(2) -+ -+ let buildPath = result.plan.buildParameters.dataPath.appending(components: "debug") -+ -+ #if os(macOS) -+ let linkArguments = [ -+ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, -+ "-L", buildPath.pathString, -+ "-o", buildPath.appending(components: "exe").pathString, -+ "-module-name", "exe", -+ "-emit-executable", -+ "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", -+ "-Xlinker", "-rpath", "-Xlinker", "/fake/path/lib/swift-5.5/macosx", -+ "-target", defaultTargetTriple, -+ "-Xlinker", "-add_ast_path", "-Xlinker", buildPath.appending(components: "exe.build", "exe.swiftmodule").pathString, -+ "-Xlinker", "-add_ast_path", "-Xlinker", buildPath.appending(components: "lib.swiftmodule").pathString, -+ "-g", -+ ] -+ #elseif os(Windows) -+ let linkArguments = [ -+ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, -+ "-L", buildPath.pathString, -+ "-o", buildPath.appending(components: "exe.exe").pathString, -+ "-module-name", "exe", -+ "-emit-executable", -+ "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", -+ "-target", defaultTargetTriple, -+ "-g", "-use-ld=lld", "-Xlinker", "-debug:dwarf", -+ ] -+ #else -+ let linkArguments = [ -+ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, -+ "-L", buildPath.pathString, -+ "-o", buildPath.appending(components: "exe").pathString, -+ "-module-name", "exe", -+ "-emit-executable", -+ "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", -+ "-target", defaultTargetTriple, -+ "-g" -+ ] -+ #endif -+ -+ XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), linkArguments) -+ XCTAssertNoDiagnostics(observability.diagnostics) -+ } - } -diff --git a/swiftpm/Tests/BuildTests/MockBuildTestHelper.swift b/swiftpm/Tests/BuildTests/MockBuildTestHelper.swift -index 243f68a58..b4dd25595 100644 ---- a/swiftpm/Tests/BuildTests/MockBuildTestHelper.swift -+++ b/swiftpm/Tests/BuildTests/MockBuildTestHelper.swift -@@ -71,6 +71,7 @@ func mockBuildParameters( - toolchain: PackageModel.Toolchain = MockToolchain(), - flags: PackageModel.BuildFlags = PackageModel.BuildFlags(), - shouldLinkStaticSwiftStdlib: Bool = false, -+ shouldDisableLocalRpath: Bool = false, - canRenameEntrypointFunctionName: Bool = false, - destinationTriple: Basics.Triple = hostTriple, - indexStoreMode: BuildParameters.IndexStoreMode = .off, -@@ -88,6 +89,7 @@ func mockBuildParameters( - pkgConfigDirectories: [], - workers: 3, - shouldLinkStaticSwiftStdlib: shouldLinkStaticSwiftStdlib, -+ shouldDisableLocalRpath: shouldDisableLocalRpath, - canRenameEntrypointFunctionName: canRenameEntrypointFunctionName, - indexStoreMode: indexStoreMode, - useExplicitModuleBuild: useExplicitModuleBuild, -diff --git a/swiftpm/Utilities/bootstrap b/swiftpm/Utilities/bootstrap -index 33aacd0b7..5d8ab14b8 100755 ---- a/swiftpm/Utilities/bootstrap -+++ b/swiftpm/Utilities/bootstrap -@@ -769,6 +769,9 @@ def get_swiftpm_flags(args): - "--configuration", "release", - ]) - -+ if os.environ.get('ANDROID_DATA') and not '-macosx' in args.build_target and args.command == 'install': -+ build_flags.append("--disable-local-rpath") -+ - if args.verbose: - build_flags.append("--verbose") - diff --git a/scripts/build/setup/termux_setup_swift.sh b/scripts/build/setup/termux_setup_swift.sh index 44bd5a6309..0775e5ee45 100644 --- a/scripts/build/setup/termux_setup_swift.sh +++ b/scripts/build/setup/termux_setup_swift.sh @@ -19,7 +19,7 @@ termux_setup_swift() { termux_download \ https://download.swift.org/swift-$TERMUX_SWIFT_VERSION-release/ubuntu2204/swift-$TERMUX_SWIFT_VERSION-$SWIFT_RELEASE/$SWIFT_BIN.tar.gz \ $SWIFT_TAR \ - 6407e39eed7eaefcf7837d192d71765fb0f7cf8bf282c35b021171e8b15617c1 + ded6983736ab5e15862e5a924ebd5c4f9459802317eff719936442c832698d06 (cd $TERMUX_PKG_TMPDIR ; tar xf $SWIFT_TAR ; mv $SWIFT_BIN $SWIFT_FOLDER; rm $SWIFT_TAR) fi