diff --git a/Runtimes/Core/CMakeLists.txt b/Runtimes/Core/CMakeLists.txt index 5b090940e6de2..10ea0ed721613 100644 --- a/Runtimes/Core/CMakeLists.txt +++ b/Runtimes/Core/CMakeLists.txt @@ -82,6 +82,7 @@ include(AvailabilityMacros) include(CompilerSettings) include(DefaultSettings) include(EmitSwiftInterface) +include(InstallSwiftInterface) include(PlatformInfo) include(gyb) include(ResourceEmbedding) @@ -103,7 +104,6 @@ defaulted_option(SwiftCore_ENABLE_OBJC_INTEROP "Enable runtime ObjC interop") defaulted_option(SwiftCore_ENABLE_TYPE_PRINTING "Enable printing type names") defaulted_option(SwiftCore_ENABLE_VECTOR_TYPES "Enable vector support") defaulted_option(SwiftCore_ENABLE_REFLECTION "Enable runtime support for mirrors and reflection support") -defaulted_option(SwiftCore_ENABLE_COMMANDLINE_SUPPORT "Enable command line argument support") defaulted_option(SwiftCore_ENABLE_RUNTIME_FUNCTION_COUNTERS "Enable runtime function counter support") defaulted_option(SwiftCore_ENABLE_STDIN "Enable functions that use stdin support") defaulted_option(SwiftCore_ENABLE_ENVIRONMENT "Enable environment variable support") @@ -115,6 +115,7 @@ defaulted_option(SwiftCore_ENABLE_BACKDEPLOYMENT_SUPPORT "Add symbols for runtim defaulted_option(SwiftCore_ENABLE_STDLIB_TRACING "Enable tracing in the runtime. Assumes the presence of os_log(3) and the os_signpost(3) API.") defaulted_option(SwiftCore_ENABLE_CONCURRENCY "Enable Concurrency runtime support") defaulted_set(SwiftCore_CONCURRENCY_GLOBAL_EXECUTOR STRING "Default Concurrency global executor implementation") +option(SwiftCore_ENABLE_COMMANDLINE_SUPPORT "Enable command line argument support" ON) option(SwiftCore_ENABLE_UNICODE_DATA "Include unicode data in Swift runtimes" ON) option(SwiftCore_ENABLE_SHORT_MANGLING_LOOKUPS "Build with fast-path context descriptor lookups based on well-known short manglings." ON) option(SwiftCore_ENABLE_FILESYSTEM_SUPPORT "Build for systems that have a filesystem" ON) diff --git a/Runtimes/Core/CommandLineSupport/CMakeLists.txt b/Runtimes/Core/CommandLineSupport/CMakeLists.txt index fa53462384b44..3eeb52114899b 100644 --- a/Runtimes/Core/CommandLineSupport/CMakeLists.txt +++ b/Runtimes/Core/CommandLineSupport/CMakeLists.txt @@ -5,6 +5,8 @@ if(SwiftCore_ENABLE_COMMANDLINE_SUPPORT) "${PROJECT_BINARY_DIR}/include") target_compile_definitions(swiftCommandLineSupport PUBLIC -DSWIFT_STDLIB_HAS_COMMANDLINE) + target_compile_definitions(swiftCommandLineSupport PRIVATE + $<$:-DswiftCore_EXPORTS>) target_link_libraries(swiftCommandLineSupport PRIVATE swiftShims) diff --git a/Runtimes/Core/cmake/modules/DefaultSettings.cmake b/Runtimes/Core/cmake/modules/DefaultSettings.cmake index e6fc1f5820ef0..9cc2301048cd1 100644 --- a/Runtimes/Core/cmake/modules/DefaultSettings.cmake +++ b/Runtimes/Core/cmake/modules/DefaultSettings.cmake @@ -6,7 +6,6 @@ # the variable with `-DSwiftCore_*` on the commandline. set(SwiftCore_ENABLE_BACKTRACING_default OFF) # TODO: enable this by default -set(SwiftCore_ENABLE_COMMANDLINE_SUPPORT_default OFF) # TODO: enable this by default set(SwiftCore_ENABLE_STDIN_default ON) set(SwiftCore_ENABLE_TYPE_PRINTING_default ON) @@ -62,12 +61,19 @@ elseif(LINUX OR ANDROID OR BSD) set(SwiftCore_CONCURRENCY_GLOBAL_EXECUTOR_default "dispatch") elseif(WIN32) set(SwiftCore_OBJECT_FORMAT_default "coff") + + set(SwiftCore_ENABLE_LIBRARY_EVOLUTION_default ${BUILD_SHARED_LIBS}) set(SwiftCore_ENABLE_REFLECTION_default ON) set(SwiftCore_ENABLE_FATALERROR_BACKTRACE_default ON) + set(SwiftCore_ENABLE_OVERRIDABLE_RETAIN_RELEASE_default ON) set(SwiftCore_ENABLE_CONCURRENCY_default NO) set(SwiftCore_THREADING_PACKAGE_default "WIN32") set(SwiftCore_ENABLE_PRESPECIALIZATION_default ON) set(SwiftCore_CONCURRENCY_GLOBAL_EXECUTOR_default "dispatch") + + set(SwiftCore_ENABLE_VECTOR_TYPES_default ON) + set(SwiftCore_ENABLE_FILESYSTEM_SUPPORT_default ON) + set(SwiftCore_INSTALL_NESTED_SUBDIR_default ON) endif() include("${SwiftCore_VENDOR_MODULE_DIR}/DefaultSettings.cmake" OPTIONAL) diff --git a/Runtimes/Core/cmake/modules/EmitSwiftInterface.cmake b/Runtimes/Core/cmake/modules/EmitSwiftInterface.cmake index 88cf2427a68f5..d4e78c8341cec 100644 --- a/Runtimes/Core/cmake/modules/EmitSwiftInterface.cmake +++ b/Runtimes/Core/cmake/modules/EmitSwiftInterface.cmake @@ -31,43 +31,3 @@ function(emit_swift_interface target) endif() endif() endfunction() - -# Install the generated swift interface file for the target if library evolution -# is enabled. -function(install_swift_interface target) - # Install binary swift modules - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/$.swiftmodule" - RENAME "${SwiftCore_MODULE_TRIPLE}.swiftmodule" - DESTINATION "${SwiftCore_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" - COMPONENT SwiftCore_development) - if(SwiftCore_VARIANT_MODULE_TRIPLE) - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${target}-${SwiftCore_VARIANT_MODULE_TRIPLE}/${target}.swiftmodule" - RENAME "${SwiftCore_VARIANT_MODULE_TRIPLE}.swiftmodule" - DESTINATION "${SwiftCore_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" - COMPONENT SwiftCore_development) - endif() - - # Install Swift interfaces if library-evolution is enabled - if(SwiftCore_ENABLE_LIBRARY_EVOLUTION) - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/$.swiftinterface" - RENAME "${SwiftCore_MODULE_TRIPLE}.swiftinterface" - DESTINATION "${SwiftCore_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" - COMPONENT SwiftCore_development) - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/$.private.swiftinterface" - RENAME "${SwiftCore_MODULE_TRIPLE}.private.swiftinterface" - DESTINATION "${SwiftCore_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" - COMPONENT SwiftCore_development) - - # Install catalyst interface files - if(SwiftCore_VARIANT_MODULE_TRIPLE) - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${target}-${SwiftCore_VARIANT_MODULE_TRIPLE}/${target}.swiftinterface" - RENAME "${SwiftCore_VARIANT_MODULE_TRIPLE}.swiftinterface" - DESTINATION "${SwiftCore_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" - COMPONENT SwiftCore_development) - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${target}-${SwiftCore_VARIANT_MODULE_TRIPLE}/${target}.private.swiftinterface" - RENAME "${SwiftCore_VARIANT_MODULE_TRIPLE}.private.swiftinterface" - DESTINATION "${SwiftCore_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" - COMPONENT SwiftCore_development) - endif() - endif() -endfunction() diff --git a/Runtimes/Core/cmake/modules/ExperimentalFeatures.cmake b/Runtimes/Core/cmake/modules/ExperimentalFeatures.cmake index 21c675982392b..674951b286c86 100644 --- a/Runtimes/Core/cmake/modules/ExperimentalFeatures.cmake +++ b/Runtimes/Core/cmake/modules/ExperimentalFeatures.cmake @@ -4,6 +4,7 @@ add_compile_options( "$<$:SHELL:-enable-experimental-feature SE427NoInferenceOnExtension>" "$<$:SHELL:-enable-experimental-feature NonescapableTypes>" "$<$:SHELL:-enable-experimental-feature LifetimeDependence>" + "$<$:SHELL:-enable-experimental-feature LifetimeDependenceMutableAccessors>" "$<$:SHELL:-enable-experimental-feature MemberImportVisibility>" "$<$:SHELL:-enable-experimental-feature TypedThrows>" "$<$:SHELL:-enable-experimental-feature Macros>" diff --git a/Runtimes/Core/cmake/modules/InstallSwiftInterface.cmake b/Runtimes/Core/cmake/modules/InstallSwiftInterface.cmake new file mode 100644 index 0000000000000..2f435711705e3 --- /dev/null +++ b/Runtimes/Core/cmake/modules/InstallSwiftInterface.cmake @@ -0,0 +1,51 @@ + +# Install the generated swift interface files for the target. +function(install_swift_interface target) + # Install binary swift modules + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/$.swiftmodule" + RENAME "${SwiftCore_MODULE_TRIPLE}.swiftmodule" + DESTINATION "${SwiftCore_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" + COMPONENT SwiftCore_development) + if(SwiftCore_VARIANT_MODULE_TRIPLE) + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${target}-${SwiftCore_VARIANT_MODULE_TRIPLE}/${target}.swiftmodule" + RENAME "${SwiftCore_VARIANT_MODULE_TRIPLE}.swiftmodule" + DESTINATION "${SwiftCore_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" + COMPONENT SwiftCore_development) + endif() + + # Install Swift interfaces if library-evolution is enabled + if(SwiftCore_ENABLE_LIBRARY_EVOLUTION) + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/$.swiftinterface" + RENAME "${SwiftCore_MODULE_TRIPLE}.swiftinterface" + DESTINATION "${SwiftCore_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" + COMPONENT SwiftCore_development) + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/$.private.swiftinterface" + RENAME "${SwiftCore_MODULE_TRIPLE}.private.swiftinterface" + DESTINATION "${SwiftCore_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" + COMPONENT SwiftCore_development) + + # Install catalyst interface files + if(SwiftCore_VARIANT_MODULE_TRIPLE) + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${target}-${SwiftCore_VARIANT_MODULE_TRIPLE}/${target}.swiftinterface" + RENAME "${SwiftCore_VARIANT_MODULE_TRIPLE}.swiftinterface" + DESTINATION "${SwiftCore_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" + COMPONENT SwiftCore_development) + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${target}-${SwiftCore_VARIANT_MODULE_TRIPLE}/${target}.private.swiftinterface" + RENAME "${SwiftCore_VARIANT_MODULE_TRIPLE}.private.swiftinterface" + DESTINATION "${SwiftCore_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" + COMPONENT SwiftCore_development) + endif() + endif() + + # Install Swift documentation interface files. + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/$.swiftdoc" + RENAME "${SwiftCore_MODULE_TRIPLE}.swiftdoc" + DESTINATION "${SwiftCore_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" + COMPONENT SwiftCore_development) + if(SwiftCore_VARIANT_MODULE_TRIPLE) + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${target}-${SwiftCore_VARIANT_MODULE_TRIPLE}/${target}.swiftdoc" + RENAME "${SwiftCore_VARIANT_MODULE_TRIPLE}.swiftdoc" + DESTINATION "${SwiftCore_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" + COMPONENT SwiftCore_development) + endif() +endfunction() diff --git a/Runtimes/Overlay/CMakeLists.txt b/Runtimes/Overlay/CMakeLists.txt index a2d5fa2743bf3..436f3a98a830b 100644 --- a/Runtimes/Overlay/CMakeLists.txt +++ b/Runtimes/Overlay/CMakeLists.txt @@ -40,6 +40,7 @@ include(gyb) include(AvailabilityMacros) include(DefaultSettings) include(EmitSwiftInterface) +include(InstallSwiftInterface) include(PlatformInfo) include(ResourceEmbedding) diff --git a/Runtimes/Overlay/cmake/modules/EmitSwiftInterface.cmake b/Runtimes/Overlay/cmake/modules/EmitSwiftInterface.cmake index 95aa11017794a..45f40fe121d61 100644 --- a/Runtimes/Overlay/cmake/modules/EmitSwiftInterface.cmake +++ b/Runtimes/Overlay/cmake/modules/EmitSwiftInterface.cmake @@ -31,38 +31,3 @@ function(emit_swift_interface target) endif() endif() endfunction() - -# Install the generated swift interface file for the target if library evolution -# is enabled. -function(install_swift_interface target) - # Install binary swift modules - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/$.swiftmodule" - RENAME "${SwiftOverlay_MODULE_TRIPLE}.swiftmodule" - DESTINATION "${SwiftOverlay_INSTALL_SWIFTMODULEDIR}/$.swiftmodule") - if(SwiftOverlay_VARIANT_MODULE_TRIPLE) - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${target}-${SwiftOverlay_VARIANT_MODULE_TRIPLE}/${target}.swiftmodule" - RENAME "${SwiftOverlay_VARIANT_MODULE_TRIPLE}.swiftmodule" - DESTINATION "${SwiftOverlay_INSTALL_SWIFTMODULEDIR}/$.swiftmodule") - endif() - - # Install Swift interfaces if library-evolution is enabled - if(SwiftOverlay_ENABLE_LIBRARY_EVOLUTION) - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/$.swiftinterface" - RENAME "${SwiftOverlay_MODULE_TRIPLE}.swiftinterface" - DESTINATION "${SwiftOverlay_INSTALL_SWIFTMODULEDIR}/$.swiftmodule") - - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/$.private.swiftinterface" - RENAME "${SwiftOverlay_MODULE_TRIPLE}.private.swiftinterface" - DESTINATION "${SwiftOverlay_INSTALL_SWIFTMODULEDIR}/$.swiftmodule") - - # Install catalyst interface files - if(SwiftOverlay_VARIANT_MODULE_TRIPLE) - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${target}-${SwiftOverlay_VARIANT_MODULE_TRIPLE}/${target}.swiftinterface" - RENAME "${SwiftOverlay_VARIANT_MODULE_TRIPLE}.swiftinterface" - DESTINATION "${SwiftOverlay_INSTALL_SWIFTMODULEDIR}/$.swiftmodule") - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${target}-${SwiftOverlay_VARIANT_MODULE_TRIPLE}/${target}.private.swiftinterface" - RENAME "${SwiftOverlay_VARIANT_MODULE_TRIPLE}.private.swiftinterface" - DESTINATION "${SwiftOverlay_INSTALL_SWIFTMODULEDIR}/$.swiftmodule") - endif() - endif() -endfunction() diff --git a/Runtimes/Overlay/cmake/modules/InstallSwiftInterface.cmake b/Runtimes/Overlay/cmake/modules/InstallSwiftInterface.cmake new file mode 100644 index 0000000000000..50688926e3964 --- /dev/null +++ b/Runtimes/Overlay/cmake/modules/InstallSwiftInterface.cmake @@ -0,0 +1,46 @@ + +# Install the generated swift interface files for the target. +function(install_swift_interface target) + # Install binary swift modules + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/$.swiftmodule" + RENAME "${SwiftOverlay_MODULE_TRIPLE}.swiftmodule" + DESTINATION "${SwiftOverlay_INSTALL_SWIFTMODULEDIR}/$.swiftmodule") + if(SwiftOverlay_VARIANT_MODULE_TRIPLE) + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${target}-${SwiftOverlay_VARIANT_MODULE_TRIPLE}/${target}.swiftmodule" + RENAME "${SwiftOverlay_VARIANT_MODULE_TRIPLE}.swiftmodule" + DESTINATION "${SwiftOverlay_INSTALL_SWIFTMODULEDIR}/$.swiftmodule") + endif() + + # Install Swift interfaces if library-evolution is enabled + if(SwiftOverlay_ENABLE_LIBRARY_EVOLUTION) + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/$.swiftinterface" + RENAME "${SwiftOverlay_MODULE_TRIPLE}.swiftinterface" + DESTINATION "${SwiftOverlay_INSTALL_SWIFTMODULEDIR}/$.swiftmodule") + + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/$.private.swiftinterface" + RENAME "${SwiftOverlay_MODULE_TRIPLE}.private.swiftinterface" + DESTINATION "${SwiftOverlay_INSTALL_SWIFTMODULEDIR}/$.swiftmodule") + + # Install catalyst interface files + if(SwiftOverlay_VARIANT_MODULE_TRIPLE) + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${target}-${SwiftOverlay_VARIANT_MODULE_TRIPLE}/${target}.swiftinterface" + RENAME "${SwiftOverlay_VARIANT_MODULE_TRIPLE}.swiftinterface" + DESTINATION "${SwiftOverlay_INSTALL_SWIFTMODULEDIR}/$.swiftmodule") + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${target}-${SwiftOverlay_VARIANT_MODULE_TRIPLE}/${target}.private.swiftinterface" + RENAME "${SwiftOverlay_VARIANT_MODULE_TRIPLE}.private.swiftinterface" + DESTINATION "${SwiftOverlay_INSTALL_SWIFTMODULEDIR}/$.swiftmodule") + endif() + endif() + + # Install Swift documentation interface files. + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/$.swiftdoc" + RENAME "${SwiftOverlay_MODULE_TRIPLE}.swiftdoc" + DESTINATION "${SwiftOverlay_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" + COMPONENT SwiftOverlay_development) + if(SwiftOverlay_VARIANT_MODULE_TRIPLE) + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${target}-${SwiftOverlay_VARIANT_MODULE_TRIPLE}/${target}.swiftdoc" + RENAME "${SwiftOverlay_VARIANT_MODULE_TRIPLE}.swiftdoc" + DESTINATION "${SwiftOverlay_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" + COMPONENT SwiftOverlay_development) + endif() +endfunction() diff --git a/Runtimes/Resync.cmake b/Runtimes/Resync.cmake index 1af913cba5899..d0319c131ff79 100644 --- a/Runtimes/Resync.cmake +++ b/Runtimes/Resync.cmake @@ -96,6 +96,9 @@ endforeach() message(STATUS "plist[${StdlibSources}/Info.plist.in] -> Core/Info.plist.in") copy_files("" "Core" FILES "Info.plist.in") +message(STATUS "plist[${StdlibSources}/Info.plist.in] -> Supplemental/Synchronization/Info.plist.in") +copy_files("" "Supplemental/Synchronization" FILES "Info.plist.in") + # Platform Overlays # Copy magic linker symbols @@ -153,6 +156,8 @@ copy_files(public/Platform Overlay/Windows/CRT # libraries, and test support libraries. # Supplemental Libraries +copy_library_sources("Synchronization" "public" "Supplemental") + # Copy StringProcessing, RegexParser, RegexBuilder if(NOT DEFINED StringProcessing_ROOT_DIR) diff --git a/Runtimes/Supplemental/CMakeLists.txt b/Runtimes/Supplemental/CMakeLists.txt index 4c63086feb976..3be3b70f0f448 100644 --- a/Runtimes/Supplemental/CMakeLists.txt +++ b/Runtimes/Supplemental/CMakeLists.txt @@ -22,6 +22,7 @@ endif() set(COMMON_OPTIONS -DBUILD_SHARED_LIBS=${BUILD_SHARED_LIBS} + -DSwift_SDKROOT=${Swift_SDKROOT} -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} -DCMAKE_INSTALL_LIBDIR=${CMAKE_INSTALL_LIBDIR} -DCMAKE_INSTALL_NAME_DIR=${CMAKE_INSTALL_NAME_DIR} @@ -47,3 +48,14 @@ if(SwiftRuntime_ENABLE_stringprocessing) CMAKE_ARGS ${COMMON_OPTIONS}) endif() + +# Synchronization +if(SwiftRuntime_ENABLE_synchronization) + ExternalProject_Add(Synchronization + PREFIX "Synchronization" + SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/Synchronization" + INSTALL_DIR "${CMAKE_INSTALL_PREFIX}" + INSTALL_COMMAND "" + CMAKE_ARGS + ${COMMON_OPTIONS}) +endif() diff --git a/Runtimes/Supplemental/StringProcessing/CMakeLists.txt b/Runtimes/Supplemental/StringProcessing/CMakeLists.txt index a4b18fe8f5e52..45289796c0d34 100644 --- a/Runtimes/Supplemental/StringProcessing/CMakeLists.txt +++ b/Runtimes/Supplemental/StringProcessing/CMakeLists.txt @@ -1,9 +1,5 @@ cmake_minimum_required(VERSION 3.29) -set(CMAKE_POSITION_INDEPENDENT_CODE YES) - -list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/../cmake/modules") - if(POLICY CMP0157 AND CMAKE_Swift_COMPILER_USE_OLD_DRIVER) cmake_policy(SET CMP0157 OLD) endif() @@ -20,16 +16,21 @@ if(NOT PROJECT_IS_TOP_LEVEL) message(FATAL_ERROR "Swift StringProcessing must build as a standalone project") endif() +set(CMAKE_POSITION_INDEPENDENT_CODE YES) + +list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/../cmake/modules") + set(${PROJECT_NAME}_SWIFTC_SOURCE_DIR "${PROJECT_SOURCE_DIR}/../../../" CACHE FILEPATH "Path to the root source directory of the Swift compiler") -find_package(SwiftCore) +find_package(SwiftCore REQUIRED) include(GNUInstallDirs) include(AvailabilityMacros) include(EmitSwiftInterface) +include(InstallSwiftInterface) include(PlatformInfo) include(ResourceEmbedding) diff --git a/Runtimes/Supplemental/Synchronization/CMakeLists.txt b/Runtimes/Supplemental/Synchronization/CMakeLists.txt new file mode 100644 index 0000000000000..6d7eb4aa16ffd --- /dev/null +++ b/Runtimes/Supplemental/Synchronization/CMakeLists.txt @@ -0,0 +1,107 @@ +cmake_minimum_required(VERSION 3.29) + +if($ENV{BUILD_NUMBER}) + math(EXPR BUILD_NUMBER "$ENV{BUILD_NUMBER} % 65535") + set(BUILD_NUMBER ".${BUILD_NUMBER}") +endif() + +project(SwiftSynchronization + LANGUAGES Swift + VERSION 6.1.0${BUILD_NUMBER}) + +if(NOT PROJECT_IS_TOP_LEVEL) + message(SEND_ERROR "Swift Synchronization must build as a standalone project") +endif() + +set(CMAKE_POSITION_INDEPENDENT_CODE YES) + +list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/../cmake/modules") + +set(CMAKE_Swift_LANGUAGE_VERSION 5) + +include(GNUInstallDirs) + +set(${PROJECT_NAME}_SWIFTC_SOURCE_DIR + "${PROJECT_SOURCE_DIR}/../../../" + CACHE FILEPATH "Path to the root source directory of the Swift compiler") + +set(${PROJECT_NAME}_VENDOR_MODULE_DIR "${CMAKE_SOURCE_DIR}/../cmake/modules/vendor" + CACHE FILEPATH "Location for private build system extension") + +find_package(SwiftCore QUIET REQUIRED) + +include(gyb) +include(ResourceEmbedding) +include(AvailabilityMacros) +include(PlatformInfo) + +include("${${PROJECT_NAME}_VENDOR_MODULE_DIR}/Settings.cmake" OPTIONAL) + +option(${PROJECT_NAME}_ENABLE_LIBRARY_EVOLUTION "Generate ABI resilient runtime libraries" + ${SwiftCore_ENABLE_LIBRARY_EVOLUTION}) + +option(${PROJECT_NAME}_ENABLE_PRESPECIALIZATION "Enable generic metadata prespecialization" + ${SwiftCore_ENABLE_PRESPECIALIZATION}) + +include(CatalystSupport) +include(EmitSwiftInterface) +include(InstallSwiftInterface) + +add_compile_options( + "$<$:-nostdlibimport>" + "$<$,$>:-enable-library-evolution>" + "$<$,$>:SHELL:-Xfrontend -prespecialize-generic-metadata>" + $<$:-explicit-module-build> + $<$:-enable-builtin-module> + $<$:-strict-memory-safety> + "$<$:SHELL:-enable-experimental-feature RawLayout>" + "$<$:SHELL:-enable-experimental-feature StaticExclusiveOnly>" + "$<$:SHELL:-enable-experimental-feature Extern>") + +gyb_expand(Atomics/AtomicIntegers.swift.gyb Atomics/AtomicIntegers.swift) +gyb_expand(Atomics/AtomicStorage.swift.gyb Atomics/AtomicStorage.swift) + +add_library(swiftSynchronization + Atomics/Atomic.swift + Atomics/AtomicBool.swift + Atomics/AtomicFloats.swift + Atomics/AtomicLazyReference.swift + Atomics/AtomicMemoryOrderings.swift + Atomics/AtomicOptional.swift + Atomics/AtomicPointers.swift + Atomics/AtomicRepresentable.swift + Atomics/WordPair.swift + Atomics/AtomicStorage.swift + Atomics/AtomicIntegers.swift + Cell.swift + Mutex/Mutex.swift + $<$:Mutex/DarwinImpl.swift> + $<$:Mutex/LinuxImpl.swift> + $<$:Mutex/SpinLoopHint.swift> + $<$:Mutex/WindowsImpl.swift>) + +set_target_properties(swiftSynchronization PROPERTIES + Swift_MODULE_NAME Synchronization) + +target_link_libraries(swiftSynchronization + PRIVATE + swiftCore + $<$:swiftDarwin>) + +set(${PROJECT_NAME}_INSTALL_LIBDIR "${CMAKE_INSTALL_LIBDIR}/swift$<$>:_static>$<$:/${Supplemental_PLATFORM_SUBDIR}/${Supplemental_ARCH_SUBDIR}>" CACHE STRING "") +set(${PROJECT_NAME}_INSTALL_SWIFTMODULEDIR "${CMAKE_INSTALL_LIBDIR}/swift$<$>:_static>$<$:/${Supplemental_PLATFORM_SUBDIR}>" CACHE STRING "") + +install(TARGETS swiftSynchronization + EXPORT SwiftSynchronizationTargets + COMPONENT ${PROJECT_NAME}_runtime + ARCHIVE DESTINATION "${${PROJECT_NAME}_INSTALL_LIBDIR}" + LIBRARY DESTINATION "${${PROJECT_NAME}_INSTALL_LIBDIR}" + RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") +emit_swift_interface(swiftSynchronization) +install_swift_interface(swiftSynchronization) + +# Configure plist creation for Darwin platforms. +generate_plist("${CMAKE_PROJECT_NAME}" "${CMAKE_PROJECT_VERSION}" swiftSynchronization) +embed_manifest(swiftSynchronization) + +include("${${PROJECT_NAME}_VENDOR_MODULE_DIR}/swiftSynchronization.cmake" OPTIONAL) diff --git a/Runtimes/Supplemental/cmake/modules/EmitSwiftInterface.cmake b/Runtimes/Supplemental/cmake/modules/EmitSwiftInterface.cmake index 843772b323767..23b6303e653a2 100644 --- a/Runtimes/Supplemental/cmake/modules/EmitSwiftInterface.cmake +++ b/Runtimes/Supplemental/cmake/modules/EmitSwiftInterface.cmake @@ -31,43 +31,3 @@ function(emit_swift_interface target) endif() endif() endfunction() - -# Install the generated swift interface file for the target if library evolution -# is enabled. -function(install_swift_interface target) - # Install binary swift modules - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/$.swiftmodule" - RENAME "${${PROJECT_NAME}_MODULE_TRIPLE}.swiftmodule" - DESTINATION "${${PROJECT_NAME}_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" - COMPONENT ${PROJECT_NAME}_development) - if(${PROJECT_NAME}_VARIANT_MODULE_TRIPLE) - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${target}-${${PROJECT_NAME}_VARIANT_MODULE_TRIPLE}/${target}.swiftmodule" - RENAME "${${PROJECT_NAME}_VARIANT_MODULE_TRIPLE}.swiftmodule" - DESTINATION "${${PROJECT_NAME}_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" - COMPONENT ${PROJECT_NAME}_development) - endif() - - # Install Swift interfaces if library-evolution is enabled - if(${PROJECT_NAME}_ENABLE_LIBRARY_EVOLUTION) - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/$.swiftinterface" - RENAME "${${PROJECT_NAME}_MODULE_TRIPLE}.swiftinterface" - DESTINATION "${${PROJECT_NAME}_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" - COMPONENT ${PROJECT_NAME}_development) - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/$.private.swiftinterface" - RENAME "${${PROJECT_NAME}_MODULE_TRIPLE}.private.swiftinterface" - DESTINATION "${${PROJECT_NAME}_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" - COMPONENT ${PROJECT_NAME}_development) - - # Install catalyst interface files - if(${PROJECT_NAME}_VARIANT_MODULE_TRIPLE) - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${target}-${${PROJECT_NAME}_VARIANT_MODULE_TRIPLE}/${target}.swiftinterface" - RENAME "${${PROJECT_NAME}_VARIANT_MODULE_TRIPLE}.swiftinterface" - DESTINATION "${${PROJECT_NAME}_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" - COMPONENT ${PROJECT_NAME}_development) - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${target}-${${PROJECT_NAME}_VARIANT_MODULE_TRIPLE}/${target}.private.swiftinterface" - RENAME "${${PROJECT_NAME}_VARIANT_MODULE_TRIPLE}.private.swiftinterface" - DESTINATION "${${PROJECT_NAME}_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" - COMPONENT ${PROJECT_NAME}_development) - endif() - endif() -endfunction() diff --git a/Runtimes/Supplemental/cmake/modules/FindSwiftCore.cmake b/Runtimes/Supplemental/cmake/modules/FindSwiftCore.cmake new file mode 100644 index 0000000000000..a78fc40eac94f --- /dev/null +++ b/Runtimes/Supplemental/cmake/modules/FindSwiftCore.cmake @@ -0,0 +1,121 @@ +#[=======================================================================[.rst: +FindSwiftCore +------------ + +Find SwiftCore, deferring to SwiftCoreConfig.cmake when requested. +This is meant to find the core library to be linked by the Supplemental libraries. + +Imported Targets +^^^^^^^^^^^^^^^^ + +The following :prop_tgt:`IMPORTED` TARGETS may be defined: + + ``SwiftCore`` + +Hint Variables +^^^^^^^^^^^^^^ + + ``SDKROOT`` (environment variable) + Set the path to the Swift SDK Root. + This only affects Windows builds. + + ``Swift_SDKROOT`` + Set the path to the Swift SDK installation. + This only affects Linux and Windows builds. + Apple builds always use the library provided by the SDK. + +Result Variables +^^^^^^^^^^^^^^^^ + +The module may set the following variables if `SwiftCore_DIR` is not set. + + ``SwiftCore_FOUND`` + true if core was found + + ``SwiftCore_INCLUDE_DIR`` + the directory containing the Swift.swiftmodule folder + +#]=======================================================================] + +# If the SwiftCore_DIR_FLAG is specified, look there instead. The cmake-generated +# config file is more accurate, but requires that the SDK has one available. +if(SwiftCore_DIR) + if(SwiftCore_FIND_REQUIRED) + list(APPEND args REQUIRED) + endif() + if(SwiftCore_FIND_QUIETLY) + list(APPEND args QUIET) + endif() + find_package(SwiftCore NO_MODULE ${args}) + return() +endif() + +include(FindPackageHandleStandardArgs) + +if(APPLE) + # When building for Apple platforms, SwiftCore always comes from within the + # SDK as a tbd for a shared library in the shared cache. + find_path(SwiftCore_INCLUDE_DIR + "Swift.swiftmodule" + HINTS + "${CMAKE_OSX_SYSROOT}/usr/lib/swift") + find_library(SwiftCore_IMPLIB + NAMES "libswiftCore.tbd" + HINTS + "${CMAKE_OSX_SYSROOT}/usr/lib/swift") + add_library(SwiftCore SHARED IMPORTED GLOBAL) + set_target_properties(SwiftCore PROPERTIES + IMPORTED_IMPLIB "${SwiftCore_IMPLIB}" + INTERFACE_INCLUDE_DIRECTORIES "${SwiftCore_INCLUDE_DIR}") + find_package_handle_standard_args(SwiftCore DEFAULT_MSG + SwiftCore_IMPLIB SwiftCore_INCLUDE_DIR) +elseif(LINUX) + if (NOT BUILD_SHARED_LIBS) + find_path(SwiftCore_INCLUDE_DIR + "Swift.swiftmodule" + HINTS + "${Swift_SDKROOT}/usr/lib/swift_static/linux-static") + find_library(SwiftCore_LIBRARY + NAMES "libswiftCore.a" + HINTS "${Swift_SDKROOT}/usr/lib/swift_static/linux-static") + add_library(SwiftCore STATIC IMPORTED GLOBAL) + else() + find_path(SwiftCore_INCLUDE_DIR + "Swift.swiftmodule" + HINTS + "${Swift_SDKROOT}/usr/lib/swift/linux") + find_library(SwiftCore_LIBRARY + NAMES "libswiftCore.so" + HINTS "${Swift_SDKROOT}/usr/lib/swift/linux") + add_library(SwiftCore SHARED IMPORTED GLOBAL) + endif() + set_target_properties(SwiftCore PROPERTIES + IMPORTED_LOCATION "${SwiftCore_LIBRARY}" + INTERFACE_INCLUDE_DIRECTORIES "${SwiftCore_INCLUDE_DIR}") + find_package_handle_standard_args(SwiftCore DEFAULT_MSG + SwiftCore_LIBRARY SwiftCore_INCLUDE_DIR) +elseif(WIN32) + find_path(SwiftCore_INCLUDE_DIR + "Swift.swiftmodule" + HINTS + "${Swift_SDKROOT}/usr/lib/swift/windows" + "$ENV{SDKROOT}/usr/lib/swift/windows") + find_library(SwiftCore_LIBRARY + NAMES "libswiftCore.lib" + HINTS + "${Swift_SDKROOT}/usr/lib/swift/${SwiftCore_PLATFORM_SUBDIR}/${SwiftCore_ARCH_SUBDIR}" + "${Swift_SDKROOT}/usr/lib/swift" + "$ENV{SDKROOT}/usr/lib/swift/${SwiftCore_PLATFORM_SUBDIR}/${SwiftCore_ARCH_SUBDIR}" + "$ENV{SDKROOT}/usr/lib/swift") + + add_library(SwiftCore SHARED IMPORTED GLOBAL) + set_target_properties(SwiftCore PROPERTIES + IMPORTED_IMPLIB "${SwiftCore_LIBRARY}" + INTERFACE_INCLUDE_DIRECTORIES "${SwiftCore_INCLUDE_DIR}") + find_package_handle_standard_args(SwiftCore DEFAULT_MSG + SwiftCore_LIBRARY SwiftCore_INCLUDE_DIR) +else() + message(FATAL_ERROR "FindSwiftCore.cmake module search not implemented for targeted platform\n" + " Build Core for your platform and set `SwiftCore_DIR` to" + " the directory containing SwiftCoreConfig.cmake\n") +endif() diff --git a/Runtimes/Supplemental/cmake/modules/InstallSwiftInterface.cmake b/Runtimes/Supplemental/cmake/modules/InstallSwiftInterface.cmake new file mode 100644 index 0000000000000..b78a280074e4d --- /dev/null +++ b/Runtimes/Supplemental/cmake/modules/InstallSwiftInterface.cmake @@ -0,0 +1,51 @@ + +# Install the generated swift interface files for the target. +function(install_swift_interface target) + # Install binary swift modules + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/$.swiftmodule" + RENAME "${${PROJECT_NAME}_MODULE_TRIPLE}.swiftmodule" + DESTINATION "${${PROJECT_NAME}_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" + COMPONENT ${PROJECT_NAME}_development) + if(${PROJECT_NAME}_VARIANT_MODULE_TRIPLE) + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${target}-${${PROJECT_NAME}_VARIANT_MODULE_TRIPLE}/${target}.swiftmodule" + RENAME "${${PROJECT_NAME}_VARIANT_MODULE_TRIPLE}.swiftmodule" + DESTINATION "${${PROJECT_NAME}_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" + COMPONENT ${PROJECT_NAME}_development) + endif() + + # Install Swift interfaces if library-evolution is enabled + if(${PROJECT_NAME}_ENABLE_LIBRARY_EVOLUTION) + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/$.swiftinterface" + RENAME "${${PROJECT_NAME}_MODULE_TRIPLE}.swiftinterface" + DESTINATION "${${PROJECT_NAME}_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" + COMPONENT ${PROJECT_NAME}_development) + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/$.private.swiftinterface" + RENAME "${${PROJECT_NAME}_MODULE_TRIPLE}.private.swiftinterface" + DESTINATION "${${PROJECT_NAME}_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" + COMPONENT ${PROJECT_NAME}_development) + + # Install catalyst interface files + if(${PROJECT_NAME}_VARIANT_MODULE_TRIPLE) + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${target}-${${PROJECT_NAME}_VARIANT_MODULE_TRIPLE}/${target}.swiftinterface" + RENAME "${${PROJECT_NAME}_VARIANT_MODULE_TRIPLE}.swiftinterface" + DESTINATION "${${PROJECT_NAME}_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" + COMPONENT ${PROJECT_NAME}_development) + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${target}-${${PROJECT_NAME}_VARIANT_MODULE_TRIPLE}/${target}.private.swiftinterface" + RENAME "${${PROJECT_NAME}_VARIANT_MODULE_TRIPLE}.private.swiftinterface" + DESTINATION "${${PROJECT_NAME}_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" + COMPONENT ${PROJECT_NAME}_development) + endif() + endif() + + # Install Swift documentation interface files. + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/$.swiftdoc" + RENAME "${${PROJECT_NAME}_MODULE_TRIPLE}.swiftdoc" + DESTINATION "${${PROJECT_NAME}_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" + COMPONENT ${PROJECT_NAME}_development) + if(SwiftCore_VARIANT_MODULE_TRIPLE) + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${target}-${${PROJECT_NAME}_VARIANT_MODULE_TRIPLE}/${target}.swiftdoc" + RENAME "${${PROJECT_NAME}_VARIANT_MODULE_TRIPLE}.swiftdoc" + DESTINATION "${${PROJECT_NAME}_INSTALL_SWIFTMODULEDIR}/$.swiftmodule" + COMPONENT ${PROJECT_NAME}_development) + endif() +endfunction() diff --git a/SwiftCompilerSources/CMakeLists.txt b/SwiftCompilerSources/CMakeLists.txt index f38418922440c..9feda46fe1719 100644 --- a/SwiftCompilerSources/CMakeLists.txt +++ b/SwiftCompilerSources/CMakeLists.txt @@ -101,19 +101,12 @@ function(add_swift_compiler_modules_library name) set(swift_compile_options "-color-diagnostics" "-Xfrontend" "-validate-tbd-against-ir=none" - "${cxx_interop_flag}" + "-cxx-interoperability-mode=default" "-Xfrontend" "-disable-target-os-checking" "-Xcc" "-std=c++17" "-Xcc" "-DCOMPILED_WITH_SWIFT" "-Xcc" "-DSWIFT_TARGET" "-Xcc" "-UIBOutlet" "-Xcc" "-UIBAction" "-Xcc" "-UIBInspectable") - # Prior to 5.9, we have to use the experimental flag for C++ interop. - if (CMAKE_Swift_COMPILER_VERSION VERSION_LESS 5.9) - list(APPEND swift_compile_options "-Xfrontend" "-enable-experimental-cxx-interop") - else() - list(APPEND swift_compile_options "-cxx-interoperability-mode=default") - endif() - if (NOT BOOTSTRAPPING_MODE STREQUAL "HOSTTOOLS") if(SWIFT_MIN_RUNTIME_VERSION) list(APPEND swift_compile_options @@ -341,7 +334,7 @@ else() message(FATAL_ERROR "The Swift compiler (${CMAKE_Swift_COMPILER}) differs from the Swift compiler in SWIFT_NATIVE_SWIFT_TOOLS_PATH (${SWIFT_NATIVE_SWIFT_TOOLS_PATH}/swiftc).") endif() - set(min_supported_swift_version 5.8) + set(min_supported_swift_version 5.9) if(CMAKE_Swift_COMPILER_VERSION VERSION_LESS "${min_supported_swift_version}") message(FATAL_ERROR "Outdated Swift compiler: building with host tools requires Swift ${min_supported_swift_version} or newer. " diff --git a/SwiftCompilerSources/Sources/AST/DiagnosticEngine.swift b/SwiftCompilerSources/Sources/AST/DiagnosticEngine.swift index 51a19ebb50f91..9b056bb91d9c9 100644 --- a/SwiftCompilerSources/Sources/AST/DiagnosticEngine.swift +++ b/SwiftCompilerSources/Sources/AST/DiagnosticEngine.swift @@ -138,24 +138,40 @@ public struct DiagnosticEngine { diagnose(id, args, at: position, highlight: highlight, fixIts: fixIts) } - public func diagnose(_ diagnostic: Diagnostic) { - diagnose(diagnostic.id, diagnostic.arguments, at: diagnostic.position) + public func diagnose(_ diagnostic: Diagnostic) { + let loc = diagnostic.location.getSourceLocation(diagnosticEngine: self) + diagnose(diagnostic.id, diagnostic.arguments, at: loc) } + + /// Loads the file at `path` and returns a `SourceLoc` pointing to `line` and `column` in the file. + /// Returns nil if the file cannot be loaded. + public func getLocationFromExternalSource(path: StringRef, line: Int, column: Int) -> SourceLoc? { + return SourceLoc(bridged: bridged.getLocationFromExternalSource(path: path._bridged, line: line, column: column)) + } +} + +/// Something which can provide a `SourceLoc` for diagnostics. +public protocol ProvidingSourceLocation { + func getSourceLocation(diagnosticEngine: DiagnosticEngine) -> SourceLoc? +} + +extension SourceLoc: ProvidingSourceLocation { + public func getSourceLocation(diagnosticEngine: DiagnosticEngine) -> SourceLoc? { self } } /// A utility struct which allows throwing a Diagnostic. -public struct Diagnostic : Error { +public struct Diagnostic : Error { public let id: DiagID public let arguments: [DiagnosticArgument] - public let position: SourceLoc? + public let location: SourceLocation - public init(_ id: DiagID, _ arguments: DiagnosticArgument..., at position: SourceLoc?) { - self.init(id, arguments, at: position) + public init(_ id: DiagID, _ arguments: DiagnosticArgument..., at location: SourceLocation) { + self.init(id, arguments, at: location) } - public init(_ id: DiagID, _ arguments: [DiagnosticArgument], at position: SourceLoc?) { + public init(_ id: DiagID, _ arguments: [DiagnosticArgument], at location: SourceLocation) { self.id = id self.arguments = arguments - self.position = position + self.location = location } } diff --git a/SwiftCompilerSources/Sources/AST/Type.swift b/SwiftCompilerSources/Sources/AST/Type.swift index d7ae1d3c7f5de..68ff6b2b1ac5d 100644 --- a/SwiftCompilerSources/Sources/AST/Type.swift +++ b/SwiftCompilerSources/Sources/AST/Type.swift @@ -14,7 +14,7 @@ import Basic import ASTBridging /// A Swift type. -/// It is not necessarily canoncial, e.g. typealiases are not resolved. +/// It is not necessarily canonical, e.g. typealiases are not resolved. public struct Type: TypeProperties, CustomStringConvertible, NoReflectionChildren { public enum TraitResult { case isNot @@ -106,6 +106,7 @@ extension TypeProperties { public var isBuiltinFloat: Bool { rawType.bridged.isBuiltinFloat() } public var isBuiltinVector: Bool { rawType.bridged.isBuiltinVector() } + public var isBuiltinFixedArray: Bool { rawType.bridged.isBuiltinFixedArray() } public var isClass: Bool { if let nominal = nominal, nominal is ClassDecl { @@ -190,6 +191,23 @@ extension TypeProperties { rawType.bridged.getRepresentationOfMetatype().representation } + public var builtinFixedArrayElementType: CanonicalType { + CanonicalType(bridged: rawType.bridged.getBuiltinFixedArrayElementType()) + } + public var builtinFixedArraySizeType: CanonicalType { + CanonicalType(bridged: rawType.bridged.getBuiltinFixedArraySizeType()) + } + + /// Returns the value of an integer value type (see `isInteger`). + /// Returns nil if the value is not representable in an `Int`. + public var valueOfInteger: Int? { + let optionalInt = rawType.bridged.getValueOfIntegerType() + if optionalInt.hasValue { + return optionalInt.value + } + return nil + } + /// Assumes this is a nominal type. Returns a substitution map that sends each /// generic parameter of the declaration's generic signature to the corresponding /// generic argument of this nominal type. @@ -206,7 +224,7 @@ extension TypeProperties { rawType.bridged.getNominalOrBoundGenericNominal().getAs(NominalTypeDecl.self) } - /// Performas a global conformance lookup for this type for `protocol`. + /// Performs a global conformance lookup for this type for `protocol`. /// It checks conditional requirements. /// /// This type must be a contextualized type. It must not contain type parameters. diff --git a/SwiftCompilerSources/Sources/Basic/SourceLoc.swift b/SwiftCompilerSources/Sources/Basic/SourceLoc.swift index 7a631452b98a6..67e146482c90c 100644 --- a/SwiftCompilerSources/Sources/Basic/SourceLoc.swift +++ b/SwiftCompilerSources/Sources/Basic/SourceLoc.swift @@ -12,8 +12,11 @@ import BasicBridging +/// Represents a location in source code. +/// It is basically a pointer into a buffer of the loaded source file (managed by `DiagnosticEngine`). +/// In contrast to just having a filename+line+column, this allows displaying the context around +/// the location when printing diagnostics. public struct SourceLoc { - /// Points into a source file. public let bridged: BridgedSourceLoc public init?(bridged: BridgedSourceLoc) { diff --git a/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/InitializeStaticGlobals.swift b/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/InitializeStaticGlobals.swift index 7dd89bffac9c1..46ab48e99f922 100644 --- a/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/InitializeStaticGlobals.swift +++ b/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/InitializeStaticGlobals.swift @@ -175,7 +175,7 @@ private func lowerInlineArray(array: InlineArray, _ context: FunctionPassContext /// private func getInlineArrayInfo(of allocStack: AllocStackInst) -> InlineArray? { var arrayLoad: LoadInst? = nil - var elementStorage: UncheckedAddrCastInst? = nil + var elementStorage: VectorBaseAddrInst? = nil for use in allocStack.uses { switch use.instruction { @@ -188,11 +188,11 @@ private func getInlineArrayInfo(of allocStack: AllocStackInst) -> InlineArray? { arrayLoad = load case is DeallocStackInst: break - case let addrCastToElement as UncheckedAddrCastInst: + case let baseAddr as VectorBaseAddrInst: if elementStorage != nil { return nil } - elementStorage = addrCastToElement + elementStorage = baseAddr default: return nil } diff --git a/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/TempRValueElimination.swift b/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/TempRValueElimination.swift index 130cbce430912..791437230139c 100644 --- a/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/TempRValueElimination.swift +++ b/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/TempRValueElimination.swift @@ -38,18 +38,51 @@ let tempRValueElimination = FunctionPass(name: "temp-rvalue-elimination") { (function: Function, context: FunctionPassContext) in for inst in function.instructions { - if let copyAddr = inst as? CopyAddrInst { - tryEliminate(copy: copyAddr, context) + switch inst { + case let copy as CopyAddrInst: + if copy.source == copy.destination { + // Remove identity copies which may have been created by an earlier iteration, where another `copy_addr` + // copied the `alloc_stack` back to the source location. + context.erase(instruction: copy) + } else { + tryEliminate(copy: copy, context) + } + case let store as StoreInst: + // Also handle `load`-`store` pairs which are basically the same thing as a `copy_addr`. + if let load = store.source as? LoadInst, load.uses.isSingleUse, load.parentBlock == store.parentBlock { + tryEliminate(copy: store, context) + } + default: + break } } } -private func tryEliminate(copy: CopyAddrInst, _ context: FunctionPassContext) { - // Remove identity copies which may have been created by an earlier iteration, where another `copy_addr` - // copied the `alloc_stack` back to the source location. - if copy.source == copy.destination { - context.erase(instruction: copy) - } +private protocol CopyLikeInstruction: Instruction { + var sourceAddress: Value { get } + var destinationAddress: Value { get } + var isTakeOfSource: Bool { get } + var isInitializationOfDestination: Bool { get } + var loadingInstruction: Instruction { get } +} + +extension CopyAddrInst: CopyLikeInstruction { + var sourceAddress: Value { source } + var destinationAddress: Value { destination } + var loadingInstruction: Instruction { self } +} + +// A `store` which has a `load` as source operand. This is basically the same as a `copy_addr`. +extension StoreInst: CopyLikeInstruction { + var sourceAddress: Value { load.address } + var destinationAddress: Value { destination } + var isTakeOfSource: Bool { load.loadOwnership == .take } + var isInitializationOfDestination: Bool { storeOwnership != .assign } + var loadingInstruction: Instruction { load } + private var load: LoadInst { source as! LoadInst } +} + +private func tryEliminate(copy: CopyLikeInstruction, _ context: FunctionPassContext) { guard let (allocStack, lastUseOfAllocStack) = getRemovableAllocStackDestination(of: copy, context) else { return @@ -61,7 +94,7 @@ private func tryEliminate(copy: CopyAddrInst, _ context: FunctionPassContext) { if needToInsertDestroy(copy: copy, lastUseOfAllocStack: lastUseOfAllocStack) { Builder.insert(after: lastUseOfAllocStack, context) { builder in - builder.createDestroyAddr(address: copy.source) + builder.createDestroyAddr(address: copy.sourceAddress) } } @@ -76,7 +109,7 @@ private func tryEliminate(copy: CopyAddrInst, _ context: FunctionPassContext) { assert(cai == lastUseOfAllocStack && cai.source == allocStack) cai.set(isTakeOfSource: false, context) } - use.set(to: copy.source, context) + use.set(to: copy.sourceAddress, context) case let load as LoadInst: if load.loadOwnership == .take, !copy.isTakeOfSource { // If the original copy is not taking its source, a `load` from the `allocStack` must @@ -84,17 +117,17 @@ private func tryEliminate(copy: CopyAddrInst, _ context: FunctionPassContext) { assert(load == lastUseOfAllocStack) load.set(ownership: .copy, context) } - use.set(to: copy.source, context); + use.set(to: copy.sourceAddress, context); default: // Note that no operations that may be handled by this default clause can destroy the `allocStack`. // This includes operations that load the value from memory and release it or cast the address // before destroying it. - use.set(to: copy.source, context); + use.set(to: copy.sourceAddress, context); } } context.erase(instruction: allocStack) - context.erase(instruction: copy) + context.erase(instructionIncludingAllUsers: copy.loadingInstruction) } /// Checks if the `copy` is copying into an `alloc_stack` which is removable: @@ -105,17 +138,17 @@ private func tryEliminate(copy: CopyAddrInst, _ context: FunctionPassContext) { /// %lastUseOfAllocStack = load %allocStack /// ``` private func getRemovableAllocStackDestination( - of copy: CopyAddrInst, _ context: FunctionPassContext + of copy: CopyLikeInstruction, _ context: FunctionPassContext ) -> (allocStack: AllocStackInst, lastUseOfAllocStack: Instruction)? { guard copy.isInitializationOfDestination, - let allocStack = copy.destination as? AllocStackInst + let allocStack = copy.destinationAddress as? AllocStackInst else { return nil } // If the `allocStack` is lexical we can eliminate it if the source of the copy is lexical and // it is live for longer than the `allocStack`. - if allocStack.isLexical && !copy.source.accessBase.storageIsLexical { + if allocStack.isLexical && !copy.sourceAddress.accessBase.storageIsLexical { return nil } @@ -149,7 +182,7 @@ private func getRemovableAllocStackDestination( if copy.isTakeOfSource, lastUseOfAllocStack != copy, !(lastUseOfAllocStack is DestroyAddrInst), - lastUseOfAllocStack.mayWrite(toAddress: copy.source, context.aliasAnalysis) + lastUseOfAllocStack.mayWrite(toAddress: copy.sourceAddress, context.aliasAnalysis) { return nil } @@ -168,7 +201,7 @@ private func getRemovableAllocStackDestination( /// We need to insert a final destroy if the original `copy` is taking the source but the /// `lastUseOfAllocStack` is not taking the `alloc_stack`. -private func needToInsertDestroy(copy: CopyAddrInst, lastUseOfAllocStack: Instruction) -> Bool { +private func needToInsertDestroy(copy: CopyLikeInstruction, lastUseOfAllocStack: Instruction) -> Bool { if !copy.isTakeOfSource { return false } @@ -177,13 +210,13 @@ private func needToInsertDestroy(copy: CopyAddrInst, lastUseOfAllocStack: Instru return true case let cai as CopyAddrInst: if cai.isTakeOfSource { - assert(cai.source == copy.destination, "copy_addr must be not take a projected address") + assert(cai.source == copy.destinationAddress, "copy_addr must be not take a projected address") return false } return true case let li as LoadInst: if li.loadOwnership == .take { - assert(li.address == copy.destination, "load must be not take a projected address") + assert(li.address == copy.destinationAddress, "load must be not take a projected address") return false } return true @@ -247,7 +280,9 @@ private extension AllocStackInst { /// ``` /// We must not replace %temp with %a after the `end_access`. Instead we try to move the `end_access` /// after the last use. -private func extendAccessScopes(beyond lastUse: Instruction, copy: CopyAddrInst, _ context: FunctionPassContext) -> Bool { +private func extendAccessScopes(beyond lastUse: Instruction, copy: CopyLikeInstruction, + _ context: FunctionPassContext) -> Bool +{ var endAccessToMove: EndAccessInst? = nil for inst in InstructionList(first: copy.next) { @@ -257,7 +292,7 @@ private func extendAccessScopes(beyond lastUse: Instruction, copy: CopyAddrInst, if endAccessToMove != nil { return false } - if context.aliasAnalysis.mayAlias(copy.source, endAccess.beginAccess.address), + if context.aliasAnalysis.mayAlias(copy.sourceAddress, endAccess.beginAccess.address), // There cannot be any aliasing modifying accesses within the liverange of the `alloc_stack`, // because we would have cought this in `getLastUseWhileSourceIsNotModified`. // But there are cases where `aliasAnalysis.mayAlias` is less precise than `Instruction.mayWrite`. @@ -301,7 +336,7 @@ private func extendAccessScopes(beyond lastUse: Instruction, copy: CopyAddrInst, /// /// Unfortunately, we cannot simply use the destroy points as the lifetime end, because they can be in a /// different basic block. Instead we look for the last non-destroy, non-dealloc use. -private func getLastUseWhileSourceIsNotModified(of copy: CopyAddrInst, +private func getLastUseWhileSourceIsNotModified(of copy: CopyLikeInstruction, uses: InstructionSetWithCount, _ context: FunctionPassContext) -> Instruction? { @@ -313,7 +348,7 @@ private func getLastUseWhileSourceIsNotModified(of copy: CopyAddrInst, // We already checked that the useful lifetime of the `alloc_stack` ends in the same block as the `copy`. // Therefore we can limit our search to the instructions of this block. - for inst in InstructionList(first: copy.next) { + for inst in InstructionList(first: copy.loadingInstruction.next) { if uses.contains(inst) { numUsesFound += 1 } @@ -327,7 +362,7 @@ private func getLastUseWhileSourceIsNotModified(of copy: CopyAddrInst, // could occur _before_ the read of the `alloc_stack`. switch inst { case is FullApplySite, is YieldInst: - if inst.mayWrite(toAddress: copy.source, aliasAnalysis) { + if inst.mayWrite(toAddress: copy.sourceAddress, aliasAnalysis) { return nil } return inst @@ -336,7 +371,7 @@ private func getLastUseWhileSourceIsNotModified(of copy: CopyAddrInst, } } - if inst.mayWrite(toAddress: copy.source, aliasAnalysis) { + if inst.mayWrite(toAddress: copy.sourceAddress, aliasAnalysis) { return nil } } @@ -348,9 +383,9 @@ private func getLastUseWhileSourceIsNotModified(of copy: CopyAddrInst, /// Collects all uses of the `alloc_stack`. private struct UseCollector : AddressDefUseWalker { private(set) var uses: InstructionSetWithCount - private let copy: CopyAddrInst + private let copy: CopyLikeInstruction - init(copy: CopyAddrInst, _ context: FunctionPassContext) { + init(copy: CopyLikeInstruction, _ context: FunctionPassContext) { self.uses = InstructionSetWithCount(context) self.copy = copy } @@ -467,7 +502,7 @@ private struct UseCollector : AddressDefUseWalker { if load.loadOwnership == .take, // Only accept `load [take]` if it takes the whole `alloc_stack`. A `load [take]` from // a projection would destroy only a part of the `alloc_stack` and we don't handle this. - load.address != copy.destination + load.address != copy.destinationAddress { return .abortWalk } @@ -494,7 +529,7 @@ private struct UseCollector : AddressDefUseWalker { return .abortWalk } // As with `load [take]`, only accept `copy_addr [take]` if it takes the whole `alloc_stack`. - if copyFromStack.isTakeOfSource && copyFromStack.source != copy.destination { + if copyFromStack.isTakeOfSource && copyFromStack.source != copy.destinationAddress { return .abortWalk } uses.insert(copyFromStack) diff --git a/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/CMakeLists.txt b/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/CMakeLists.txt index 043a62589f37c..eb7a3d22d051e 100644 --- a/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/CMakeLists.txt +++ b/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/CMakeLists.txt @@ -39,6 +39,7 @@ swift_compiler_sources(Optimizer SimplifySwitchEnum.swift SimplifyTuple.swift SimplifyTupleExtract.swift + SimplifyUncheckedAddrCast.swift SimplifyUncheckedEnumData.swift SimplifyValueToBridgeObject.swift SimplifyWitnessMethod.swift) diff --git a/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyMisc.swift b/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyMisc.swift index 2aaaaeb80435d..2ad1e3c0e7636 100644 --- a/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyMisc.swift +++ b/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyMisc.swift @@ -15,7 +15,7 @@ import SIL extension TypeValueInst: OnoneSimplifiable, SILCombineSimplifiable { func simplify(_ context: SimplifyContext) { // If our parameter is not known statically, then bail. - guard paramType.isInteger else { + guard let value = value else { return } diff --git a/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyUncheckedAddrCast.swift b/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyUncheckedAddrCast.swift new file mode 100644 index 0000000000000..d8455d555aef8 --- /dev/null +++ b/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyUncheckedAddrCast.swift @@ -0,0 +1,81 @@ +//===--- SimplifyUncheckedAddrCast.swift ----------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2025 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 SIL + +extension UncheckedAddrCastInst : OnoneSimplifiable, SILCombineSimplifiable { + + func simplify(_ context: SimplifyContext) { + // ``` + // %1 = unchecked_addr_cast %0 : $*T to $*T + // ``` + // -> + // replace %1 with %0 + // + if optimizeSameTypeCast(context) { + return + } + + // ``` + // %1 = unchecked_addr_cast %0 : $*U to $*V + // %2 = unchecked_addr_cast %1 : $*V to $*T + // ``` + // -> + // ``` + // %2 = unchecked_addr_cast %0: $*U to $*T + // ``` + if optimizeDoubleCast(context) { + return + } + + // ``` + // %1 = unchecked_addr_cast %0 : $*Builtin.FixedArray to $*Element + // ``` + // -> + // ``` + // %1 = vector_base_addr %0 : $*Builtin.FixedArray + // ``` + _ = optimizeVectorBaseCast(context) + } +} + +private extension UncheckedAddrCastInst { + func optimizeSameTypeCast(_ context: SimplifyContext) -> Bool { + if fromAddress.type == type { + self.replace(with: fromAddress, context) + return true + } + return false + } + + func optimizeDoubleCast(_ context: SimplifyContext) -> Bool { + if let firstCast = fromAddress as? UncheckedAddrCastInst { + let builder = Builder(before: self, context) + let newCast = builder.createUncheckedAddrCast(from: firstCast.fromAddress, to: type) + self.replace(with: newCast, context) + return true + } + return false + } + + func optimizeVectorBaseCast(_ context: SimplifyContext) -> Bool { + if fromAddress.type.isBuiltinFixedArray, + fromAddress.type.builtinFixedArrayElementType(in: parentFunction, maximallyAbstracted: true).addressType == type + { + let builder = Builder(before: self, context) + let vectorBase = builder.createVectorBaseAddr(vector: fromAddress) + self.replace(with: vectorBase, context) + return true + } + return false + } +} diff --git a/SwiftCompilerSources/Sources/Optimizer/ModulePasses/EmbeddedSwiftDiagnostics.swift b/SwiftCompilerSources/Sources/Optimizer/ModulePasses/EmbeddedSwiftDiagnostics.swift index 803498f0f687c..4d99ca22ac7ba 100644 --- a/SwiftCompilerSources/Sources/Optimizer/ModulePasses/EmbeddedSwiftDiagnostics.swift +++ b/SwiftCompilerSources/Sources/Optimizer/ModulePasses/EmbeddedSwiftDiagnostics.swift @@ -37,7 +37,7 @@ let embeddedSwiftDiagnostics = ModulePass(name: "embedded-swift-diagnostics") { do { assert(checker.callStack.isEmpty) try checker.checkFunction(function) - } catch let error as Diagnostic { + } catch let error as Diagnostic { checker.diagnose(error) } catch { fatalError("unknown error thrown") @@ -248,9 +248,9 @@ private struct FunctionChecker { } } - mutating func diagnose(_ error: Diagnostic) { + mutating func diagnose(_ error: Diagnostic) { var diagPrinted = false - if error.position != nil { + if error.location.hasValidLineNumber { context.diagnosticEngine.diagnose(error) diagPrinted = true } diff --git a/SwiftCompilerSources/Sources/Optimizer/PassManager/Context.swift b/SwiftCompilerSources/Sources/Optimizer/PassManager/Context.swift index d667123c43aa8..54323de328f71 100644 --- a/SwiftCompilerSources/Sources/Optimizer/PassManager/Context.swift +++ b/SwiftCompilerSources/Sources/Optimizer/PassManager/Context.swift @@ -140,7 +140,10 @@ extension MutatingContext { return _bridged.createBlockAfter(block.bridged).block } - func erase(instruction: Instruction) { + /// Removes and deletes `instruction`. + /// If `salvageDebugInfo` is true, compensating `debug_value` instructions are inserted for certain + /// kind of instructions. + func erase(instruction: Instruction, salvageDebugInfo: Bool = true) { if !instruction.isInStaticInitializer { verifyIsTransforming(function: instruction.parentFunction) } @@ -152,7 +155,7 @@ extension MutatingContext { } notifyInstructionsChanged() - _bridged.eraseInstruction(instruction.bridged) + _bridged.eraseInstruction(instruction.bridged, salvageDebugInfo) } func erase(instructionIncludingAllUsers inst: Instruction) { @@ -164,7 +167,9 @@ extension MutatingContext { erase(instructionIncludingAllUsers: use.instruction) } } - erase(instruction: inst) + // We rely that after deleting the instruction its operands have no users. + // Therefore `salvageDebugInfo` must be turned off because we cannot insert debug_value instructions. + erase(instruction: inst, salvageDebugInfo: false) } func erase(instructions: S) where S.Element: Instruction { diff --git a/SwiftCompilerSources/Sources/Optimizer/PassManager/PassRegistration.swift b/SwiftCompilerSources/Sources/Optimizer/PassManager/PassRegistration.swift index b5a70e1a30cdb..e6ff780a93321 100644 --- a/SwiftCompilerSources/Sources/Optimizer/PassManager/PassRegistration.swift +++ b/SwiftCompilerSources/Sources/Optimizer/PassManager/PassRegistration.swift @@ -125,6 +125,7 @@ private func registerSwiftPasses() { registerForSILCombine(PointerToAddressInst.self, { run(PointerToAddressInst.self, $0) }) registerForSILCombine(UncheckedEnumDataInst.self, { run(UncheckedEnumDataInst.self, $0) }) registerForSILCombine(WitnessMethodInst.self, { run(WitnessMethodInst.self, $0) }) + registerForSILCombine(UncheckedAddrCastInst.self, { run(UncheckedAddrCastInst.self, $0) }) registerForSILCombine(UnconditionalCheckedCastInst.self, { run(UnconditionalCheckedCastInst.self, $0) }) registerForSILCombine(AllocStackInst.self, { run(AllocStackInst.self, $0) }) registerForSILCombine(ApplyInst.self, { run(ApplyInst.self, $0) }) diff --git a/SwiftCompilerSources/Sources/Optimizer/Utilities/OptUtils.swift b/SwiftCompilerSources/Sources/Optimizer/Utilities/OptUtils.swift index c8a4ef4e2ccc4..9000af0d317bd 100644 --- a/SwiftCompilerSources/Sources/Optimizer/Utilities/OptUtils.swift +++ b/SwiftCompilerSources/Sources/Optimizer/Utilities/OptUtils.swift @@ -387,7 +387,7 @@ extension Instruction { case let bi as BuiltinInst: switch bi.id { case .ZeroInitializer: - let type = bi.type.isBuiltinVector ? bi.type.builtinVectorElementType : bi.type + let type = bi.type.isBuiltinVector ? bi.type.builtinVectorElementType(in: parentFunction) : bi.type return type.isBuiltinInteger || type.isBuiltinFloat case .PtrToInt: return bi.operands[0].value is StringLiteralInst diff --git a/SwiftCompilerSources/Sources/Optimizer/Utilities/Verifier.swift b/SwiftCompilerSources/Sources/Optimizer/Utilities/Verifier.swift index d54ded9805934..7bb7e42a6c0ed 100644 --- a/SwiftCompilerSources/Sources/Optimizer/Utilities/Verifier.swift +++ b/SwiftCompilerSources/Sources/Optimizer/Utilities/Verifier.swift @@ -148,6 +148,16 @@ extension LoadBorrowInst : VerifiableInstruction { } } +extension VectorBaseAddrInst : VerifiableInstruction { + func verify(_ context: FunctionPassContext) { + require(vector.type.isBuiltinFixedArray, + "vector operand of vector_element_addr must be a Builtin.FixedArray") + require(type == vector.type.builtinFixedArrayElementType(in: parentFunction, + maximallyAbstracted: true).addressType, + "result of vector_element_addr has wrong type") + } +} + // Used to check if any instruction is mutating the memory location within the liverange of a `load_borrow`. // Note that it is not checking if an instruction _may_ mutate the memory, but it's checking if any instruction // _definitely_ will mutate the memory. diff --git a/SwiftCompilerSources/Sources/SIL/ASTExtensions.swift b/SwiftCompilerSources/Sources/SIL/ASTExtensions.swift index 56bb6c443be33..2aa6a9b957f5c 100644 --- a/SwiftCompilerSources/Sources/SIL/ASTExtensions.swift +++ b/SwiftCompilerSources/Sources/SIL/ASTExtensions.swift @@ -76,16 +76,16 @@ extension Conformance { extension DiagnosticEngine { public func diagnose(_ id: DiagID, _ args: DiagnosticArgument..., at location: Location) { - diagnose(id, args, at: location.sourceLoc) + diagnose(id, args, at: location.getSourceLocation(diagnosticEngine: self)) } public func diagnose(_ id: DiagID, _ args: [DiagnosticArgument], at location: Location) { - diagnose(id, args, at: location.sourceLoc) + diagnose(id, args, at: location.getSourceLocation(diagnosticEngine: self)) } } -extension Diagnostic { +extension Diagnostic where SourceLocation == Location { public init(_ id: DiagID, _ arguments: DiagnosticArgument..., at location: Location) { - self.init(id, arguments, at: location.sourceLoc) + self.init(id, arguments, at: location) } } diff --git a/SwiftCompilerSources/Sources/SIL/Builder.swift b/SwiftCompilerSources/Sources/SIL/Builder.swift index 235a5dcc411eb..a5ce4b04b2eab 100644 --- a/SwiftCompilerSources/Sources/SIL/Builder.swift +++ b/SwiftCompilerSources/Sources/SIL/Builder.swift @@ -487,6 +487,10 @@ public struct Builder { return notifyNew(vectorInst.getAs(VectorInst.self)) } + public func createVectorBaseAddr(vector: Value) -> VectorBaseAddrInst { + return notifyNew(bridged.createVectorBaseAddr(vector.bridged).getAs(VectorBaseAddrInst.self)) + } + public func createGlobalAddr(global: GlobalVariable, dependencyToken: Value?) -> GlobalAddrInst { return notifyNew(bridged.createGlobalAddr(global.bridged, dependencyToken.bridged).getAs(GlobalAddrInst.self)) } diff --git a/SwiftCompilerSources/Sources/SIL/Instruction.swift b/SwiftCompilerSources/Sources/SIL/Instruction.swift index 2eea59c78e607..e1106f19f699e 100644 --- a/SwiftCompilerSources/Sources/SIL/Instruction.swift +++ b/SwiftCompilerSources/Sources/SIL/Instruction.swift @@ -862,8 +862,12 @@ final public class TypeValueInst: SingleValueInstruction, UnaryInstruction { CanonicalType(bridged: bridged.TypeValueInst_getParamType()) } - public var value: Int { - bridged.TypeValueInst_getValue() + /// Returns the value of the Integer type is known and fits into an `Int`. + public var value: Int? { + if paramType.isInteger { + return paramType.valueOfInteger + } + return nil } } @@ -1350,6 +1354,10 @@ final public class ObjectInst : SingleValueInstruction { final public class VectorInst : SingleValueInstruction { } +final public class VectorBaseAddrInst : SingleValueInstruction, UnaryInstruction { + public var vector: Value { operand.value } +} + final public class DifferentiableFunctionInst: SingleValueInstruction {} final public class LinearFunctionInst: SingleValueInstruction {} diff --git a/SwiftCompilerSources/Sources/SIL/Location.swift b/SwiftCompilerSources/Sources/SIL/Location.swift index 59ec2859fffbd..771a8091a5dbc 100644 --- a/SwiftCompilerSources/Sources/SIL/Location.swift +++ b/SwiftCompilerSources/Sources/SIL/Location.swift @@ -13,7 +13,19 @@ import SILBridging import AST -public struct Location: Equatable, CustomStringConvertible { +/// Represents a location in source code. +/// `Location` is used in SIL and by the Optimizer. +/// +/// When compiling a Swift file, `Location` is basically a `SourceLoc` + information about the +/// containing debug scope. In this case the `SourceLoc` is directly retrieved from the AST nodes. +/// +/// However, for debug info which is de-serialized from a swiftmodule file, the location consists of +/// a filename + line and column indices. From such a location, a `SourceLoc` can only be created by +/// loading the file with `DiagnosticEngine.getLocationFromExternalSource`. +/// +/// In case of parsing textual SIL (e.g. with `sil-opt`), which does _not_ contain debug line +/// information, the location is also a `SourceLoc` which points to the textual SIL. +public struct Location: ProvidingSourceLocation, Equatable, CustomStringConvertible { let bridged: BridgedLocation public var description: String { @@ -27,6 +39,24 @@ public struct Location: Equatable, CustomStringConvertible { return nil } + public var fileNameAndPosition: (path: StringRef, line: Int, column: Int)? { + if bridged.isFilenameAndLocation() { + let loc = bridged.getFilenameAndLocation() + return (StringRef(bridged: loc.path), loc.line, loc.column) + } + return nil + } + + public func getSourceLocation(diagnosticEngine: DiagnosticEngine) -> SourceLoc? { + if let sourceLoc = sourceLoc { + return sourceLoc + } + if let (path, line, column) = fileNameAndPosition { + return diagnosticEngine.getLocationFromExternalSource(path: path, line: line, column: column) + } + return nil + } + /// Keeps the debug scope but marks it as auto-generated. public var autoGenerated: Location { Location(bridged: bridged.getAutogeneratedLocation()) diff --git a/SwiftCompilerSources/Sources/SIL/Registration.swift b/SwiftCompilerSources/Sources/SIL/Registration.swift index 15b83dc9002dd..d8f352762e129 100644 --- a/SwiftCompilerSources/Sources/SIL/Registration.swift +++ b/SwiftCompilerSources/Sources/SIL/Registration.swift @@ -118,6 +118,7 @@ public func registerSILClasses() { register(MoveOnlyWrapperToCopyableAddrInst.self) register(ObjectInst.self) register(VectorInst.self) + register(VectorBaseAddrInst.self) register(TuplePackExtractInst.self) register(TuplePackElementAddrInst.self) register(PackElementGetInst.self) diff --git a/SwiftCompilerSources/Sources/SIL/Type.swift b/SwiftCompilerSources/Sources/SIL/Type.swift index 3e49c0766409a..d88e0b3483dc0 100644 --- a/SwiftCompilerSources/Sources/SIL/Type.swift +++ b/SwiftCompilerSources/Sources/SIL/Type.swift @@ -80,7 +80,13 @@ public struct Type : TypeProperties, CustomStringConvertible, NoReflectionChildr !isNoEscapeFunction && isEscapable(in: function) } - public var builtinVectorElementType: Type { canonicalType.builtinVectorElementType.silType! } + public func builtinVectorElementType(in function: Function) -> Type { + canonicalType.builtinVectorElementType.loweredType(in: function) + } + + public func builtinFixedArrayElementType(in function: Function, maximallyAbstracted: Bool = false) -> Type { + canonicalType.builtinFixedArrayElementType.loweredType(in: function, maximallyAbstracted: maximallyAbstracted) + } public var superClassType: Type? { canonicalType.superClassType?.silType } diff --git a/SwiftCompilerSources/Sources/SIL/Utilities/AccessUtils.swift b/SwiftCompilerSources/Sources/SIL/Utilities/AccessUtils.swift index 26fb99731356b..2fbcf88d9e7f7 100644 --- a/SwiftCompilerSources/Sources/SIL/Utilities/AccessUtils.swift +++ b/SwiftCompilerSources/Sources/SIL/Utilities/AccessUtils.swift @@ -431,7 +431,7 @@ public struct AccessPath : CustomStringConvertible, Hashable { private func canBeOperandOfIndexAddr(_ value: Value) -> Bool { switch value { - case is IndexAddrInst, is RefTailAddrInst, is PointerToAddressInst: + case is IndexAddrInst, is RefTailAddrInst, is PointerToAddressInst, is VectorBaseAddrInst: return true default: return false diff --git a/SwiftCompilerSources/Sources/SIL/Utilities/SmallProjectionPath.swift b/SwiftCompilerSources/Sources/SIL/Utilities/SmallProjectionPath.swift index 188fd38fa1b51..ea94f2771e83f 100644 --- a/SwiftCompilerSources/Sources/SIL/Utilities/SmallProjectionPath.swift +++ b/SwiftCompilerSources/Sources/SIL/Utilities/SmallProjectionPath.swift @@ -83,15 +83,17 @@ public struct SmallProjectionPath : Hashable, CustomStringConvertible, NoReflect // This and all following kinds (we'll add in the future) cannot have a field index. case tailElements = 0x07 // (0 << 3) | 0x7 A tail allocated element of a class: syntax `ct` case existential = 0x0f // (1 << 3) | 0x7 A concrete value projected out of an existential: synatx 'x' - case anyClassField = 0x17 // (2 << 3) | 0x7 Any class field, including tail elements: syntax `c*` - case anyIndexedElement = 0x1f // (3 << 3) | 0x7 An unknown offset into an array of elements. + case vectorBase = 0x17 // (2 << 3) | 0x7 The base element of a vector: synatx 'b' + case anyClassField = 0x1f // (3 << 3) | 0x7 Any class field, including tail elements: syntax `c*` + case anyIndexedElement = 0x27 // (4 << 3) | 0x7 An unknown offset into an array of elements. // There must not be two successive element indices in the path. - case anyValueFields = 0x27 // (4 << 3) | 0x7 Any number of any value fields (struct, tuple, enum): syntax `v**` - case anything = 0x2f // (5 << 3) | 0x7 Any number of any fields: syntax `**` + case anyValueFields = 0x2f // (5 << 3) | 0x7 Any number of any value fields (struct, tuple, enum): syntax `v**` + case anything = 0x37 // (6 << 3) | 0x7 Any number of any fields: syntax `**` public var isValueField: Bool { switch self { - case .anyValueFields, .structField, .tupleField, .enumCase, .indexedElement, .anyIndexedElement, .existential: + case .structField, .tupleField, .enumCase, .indexedElement, .existential, .vectorBase, + .anyValueFields, .anyIndexedElement: return true case .root, .anything, .anyClassField, .classField, .tailElements: return false @@ -102,7 +104,8 @@ public struct SmallProjectionPath : Hashable, CustomStringConvertible, NoReflect switch self { case .anyClassField, .classField, .tailElements: return true - case .root, .anything, .anyValueFields, .structField, .tupleField, .enumCase, .indexedElement, .anyIndexedElement, .existential: + case .root, .anything, .anyValueFields, .structField, .tupleField, .enumCase, .indexedElement, + .anyIndexedElement, .existential, .vectorBase: return false } } @@ -140,6 +143,7 @@ public struct SmallProjectionPath : Hashable, CustomStringConvertible, NoReflect case .classField: s = "c\(idx)" case .tailElements: s = "ct" case .existential: s = "x" + case .vectorBase: s = "b" case .indexedElement: s = "i\(idx)" case .anyIndexedElement: s = "i*" case .anything: s = "**" @@ -398,7 +402,7 @@ public struct SmallProjectionPath : Hashable, CustomStringConvertible, NoReflect return subPath.matches(pattern: subPattern) case .anyIndexedElement: return popIndexedElements().matches(pattern: subPattern) - case .structField, .tupleField, .enumCase, .classField, .tailElements, .indexedElement, .existential: + case .structField, .tupleField, .enumCase, .classField, .tailElements, .indexedElement, .existential, .vectorBase: let (kind, index, subPath) = pop() if kind != patternKind || index != patternIdx { return false } return subPath.matches(pattern: subPattern) @@ -478,8 +482,18 @@ public struct SmallProjectionPath : Hashable, CustomStringConvertible, NoReflect } if (lhsKind == rhsKind && lhsIdx == rhsIdx) || (lhsKind == .anyClassField && rhsKind.isClassField) || - (lhsKind.isClassField && rhsKind == .anyClassField) { - return pop(numBits: lhsBits).mayOverlap(with: rhs.pop(numBits: rhsBits)) + (lhsKind.isClassField && rhsKind == .anyClassField) + { + let poppedPath = pop(numBits: lhsBits) + let rhsPoppedPath = rhs.pop(numBits: rhsBits) + // Check for the case of overlapping the first element of a vector with another element. + // Note that the index of `.indexedElement` cannot be 0. + if (poppedPath.isEmpty && rhsPoppedPath.pop().kind == .indexedElement) || + (rhsPoppedPath.isEmpty && poppedPath.pop().kind == .indexedElement) + { + return false + } + return poppedPath.mayOverlap(with: rhsPoppedPath) } return false } @@ -496,7 +510,7 @@ public struct SmallProjectionPath : Hashable, CustomStringConvertible, NoReflect switch lhsKind { case .root: return rhs - case .classField, .tailElements, .structField, .tupleField, .enumCase, .existential, .indexedElement: + case .classField, .tailElements, .structField, .tupleField, .enumCase, .existential, .indexedElement, .vectorBase: let (rhsKind, rhsIdx, rhsBits) = rhs.top if lhsKind == rhsKind && lhsIdx == rhsIdx { return pop(numBits: lhsBits).subtract(from: rhs.pop(numBits: rhsBits)) @@ -601,6 +615,8 @@ extension StringParser { entries.append((.tailElements, 0)) } else if consume("x") { entries.append((.existential, 0)) + } else if consume("b") { + entries.append((.vectorBase, 0)) } else if consume("c") { guard let idx = consumeInt(withWhiteSpace: false) else { try throwError("expected class field index") @@ -701,7 +717,8 @@ extension SmallProjectionPath { .push(.enumCase, index: 6) .push(.anyClassField) .push(.tupleField, index: 2)) - testParse("i3.x.i*", expect: SmallProjectionPath(.anyIndexedElement) + testParse("i3.x.b.i*", expect: SmallProjectionPath(.anyIndexedElement) + .push(.vectorBase) .push(.existential) .push(.indexedElement, index: 3)) @@ -739,6 +756,8 @@ extension SmallProjectionPath { testMerge("i*", "i2", expect: "i*") testMerge("s0.i*.e3", "s0.e3", expect: "s0.i*.e3") testMerge("i*", "v**", expect: "v**") + testMerge("s0.b.i1", "s0.b.i0", expect: "s0.b.i*") + testMerge("s0.b", "s0.1", expect: "s0.v**") testMerge("ct.s0.e0.v**.c0", "ct.s0.e0.v**.c0", expect: "ct.s0.e0.v**.c0") testMerge("ct.s0.s0.c0", "ct.s0.e0.s0.c0", expect: "ct.s0.v**.c0") @@ -813,6 +832,7 @@ extension SmallProjectionPath { testMatch("s1.v**", "s0.**", expect: false) testMatch("s0.**", "s0.v**", expect: false) testMatch("s0.s1", "s0.i*.s1", expect: true) + testMatch("s0.b.s1", "s0.b.i*.s1", expect: true) } func testMatch(_ lhsStr: String, _ rhsStr: String, expect: Bool) { @@ -847,6 +867,13 @@ extension SmallProjectionPath { testOverlap("i1", "i*", expect: true) testOverlap("i1", "v**", expect: true) testOverlap("s0.i*.s1", "s0.s1", expect: true) + testOverlap("s0.b.s1", "s0.b.i*.s1", expect: true) + testOverlap("s0.b.i0.s1", "s0.b.i1.s1", expect: false) + testOverlap("s0.b.i2.s1", "s0.b.i1.s1", expect: false) + testOverlap("s0.b.s1", "s0.b.i0.s1", expect: true) + testOverlap("s0.b", "s0.b.i1", expect: false) + testOverlap("s0.b.i1", "s0.b", expect: false) + testOverlap("s0.b.i1", "s0", expect: true) } func testOverlap(_ lhsStr: String, _ rhsStr: String, expect: Bool) { @@ -889,7 +916,7 @@ extension SmallProjectionPath { } func path2path() { - testPath2Path("s0.e2.3.c4.s1", { $0.popAllValueFields() }, expect: "c4.s1") + testPath2Path("s0.b.e2.3.c4.s1", { $0.popAllValueFields() }, expect: "c4.s1") testPath2Path("v**.c4.s1", { $0.popAllValueFields() }, expect: "c4.s1") testPath2Path("**", { $0.popAllValueFields() }, expect: "**") diff --git a/SwiftCompilerSources/Sources/SIL/Utilities/WalkUtils.swift b/SwiftCompilerSources/Sources/SIL/Utilities/WalkUtils.swift index 6ab15c5de5a1f..7c626a6923e59 100644 --- a/SwiftCompilerSources/Sources/SIL/Utilities/WalkUtils.swift +++ b/SwiftCompilerSources/Sources/SIL/Utilities/WalkUtils.swift @@ -509,6 +509,12 @@ extension AddressDefUseWalker { } else { return unmatchedPath(address: operand, path: path) } + case let vba as VectorBaseAddrInst: + if let path = path.popIfMatches(.vectorBase, index: 0) { + return walkDownUses(ofAddress: vba, path: path) + } else { + return unmatchedPath(address: operand, path: path) + } case is InitEnumDataAddrInst, is UncheckedTakeEnumDataAddrInst: let ei = instruction as! SingleValueInstruction if let path = path.popIfMatches(.enumCase, index: (instruction as! EnumInstruction).caseIndex) { @@ -814,6 +820,8 @@ extension AddressUseDefWalker { return walkUp(address: sea.struct, path: path.push(.structField, index: sea.fieldIndex)) case let tea as TupleElementAddrInst: return walkUp(address: tea.tuple, path: path.push(.tupleField, index: tea.fieldIndex)) + case let vba as VectorBaseAddrInst: + return walkUp(address: vba.vector, path: path.push(.vectorBase, index: 0)) case let ida as InitEnumDataAddrInst: return walkUp(address: ida.operand.value, path: path.push(.enumCase, index: ida.caseIndex)) case let uteda as UncheckedTakeEnumDataAddrInst: diff --git a/benchmark/single-source/ObjectiveCBridging.swift b/benchmark/single-source/ObjectiveCBridging.swift index c0e9d1a083292..1b9c04e980e27 100644 --- a/benchmark/single-source/ObjectiveCBridging.swift +++ b/benchmark/single-source/ObjectiveCBridging.swift @@ -97,6 +97,9 @@ public let benchmarks = [ BenchmarkInfo(name: "NSArray.bridged.repeatedBufferAccess", runFunction: run_BridgedNSArrayRepeatedBufferAccess, tags: t, setUpFunction: setup_bridgedArrays), + BenchmarkInfo(name: "NSDictionary.bridged.enumerate", + runFunction: run_BridgedNSDictionaryEnumerate, tags: t, + setUpFunction: setup_bridgedDictionaries), ] #if _runtime(_ObjC) @@ -794,6 +797,7 @@ public func run_UnicodeStringFromCodable(_ n: Int) { #if _runtime(_ObjC) var bridgedArray:NSArray! = nil +var bridgedDictionaryOfNumbersToNumbers:NSDictionary! = nil var bridgedArrayMutableCopy:NSMutableArray! = nil var nsArray:NSArray! = nil var nsArrayMutableCopy:NSMutableArray! = nil @@ -804,11 +808,21 @@ public func setup_bridgedArrays() { var arr = Array(repeating: NSObject(), count: 100) as [AnyObject] bridgedArray = arr as NSArray bridgedArrayMutableCopy = (bridgedArray.mutableCopy() as! NSMutableArray) + nsArray = NSArray(objects: &arr, count: 100) nsArrayMutableCopy = (nsArray.mutableCopy() as! NSMutableArray) #endif } +public func setup_bridgedDictionaries() { + var numDict = Dictionary() + for i in 0 ..< 100 { + numDict[i] = i + } + bridgedDictionaryOfNumbersToNumbers = numDict as NSDictionary +} + + @inline(never) public func run_BridgedNSArrayObjectAtIndex(_ n: Int) { #if _runtime(_ObjC) @@ -820,6 +834,23 @@ public func run_BridgedNSArrayObjectAtIndex(_ n: Int) { #endif } +private func dictionaryApplier( + _ keyPtr: UnsafeRawPointer?, + _ valuePtr :UnsafeRawPointer?, + _ contextPtr: UnsafeMutableRawPointer? +) -> Void {} + +@inline(never) +public func run_BridgedNSDictionaryEnumerate(_ n: Int) { + #if _runtime(_ObjC) + let cf = bridgedDictionaryOfNumbersToNumbers as CFDictionary + for _ in 0 ..< n * 50 { + // Use CF to prevent Swift from providing an override, forcing going through ObjC bridging + CFDictionaryApplyFunction(cf, dictionaryApplier, nil) + } + #endif +} + @inline(never) public func run_BridgedNSArrayBufferAccess(_ n: Int) { #if _runtime(_ObjC) diff --git a/docs/ReferenceGuides/UnderscoredAttributes.md b/docs/ReferenceGuides/UnderscoredAttributes.md index 07d66bc5013b9..a9db7c7ea998e 100644 --- a/docs/ReferenceGuides/UnderscoredAttributes.md +++ b/docs/ReferenceGuides/UnderscoredAttributes.md @@ -600,6 +600,43 @@ inherit the actor context (i.e. what actor it should be run on) based on the declaration site of the closure rather than be non-Sendable. This does not do anything if the closure is synchronous. +This works with global actors as expected: + +```swift +@MainActor +func test() { + Task { /* main actor isolated */ } +} +``` + +However, for the inference to work with instance actors (i.e. `isolated` parameters), +the closure must capture the isolated parameter explicitly: + +```swift +func test(actor: isolated (any Actor)) { + Task { /* non isolated */ } // !!! +} + +func test(actor: isolated (any Actor)) { + Task { // @_inheritActorContext + _ = actor // 'actor'-isolated + } +} +``` + +The attribute takes an optional modifier '`always`', which changes this behavior +and *always* captures the enclosing isolated context, rather than forcing developers +to perform the explicit capture themselfes: + +```swift +func test(actor: isolated (any Actor)) { + Task.immediate { // @_inheritActorContext(always) + // 'actor'-isolated! + // (without having to capture 'actor explicitly') + } +} +``` + DISCUSSION: The reason why this does nothing when the closure is synchronous is since it does not have the ability to hop to the appropriate executor before it is run, so we may create concurrency errors. diff --git a/docs/SIL/Instructions.md b/docs/SIL/Instructions.md index abc7944d4b301..d077602d622b1 100644 --- a/docs/SIL/Instructions.md +++ b/docs/SIL/Instructions.md @@ -3467,6 +3467,20 @@ Constructs a statically initialized vector of elements. This instruction can only appear as final instruction in a global variable static initializer list. +### vector_base_addr + +``` +sil-instruction ::= 'vector_base_addr' sil-operand + +%1 = vector_base_addr %0 : $*Builtin.FixedArray +// %0 must have type $*Builtin.FixedArray +// %1 will be of the element type of the Builtin.FixedArray +``` + +Derives the address of the first element of a vector, i.e. a `Builtin.FixedArray`, +from the address of the vector itself. +Addresses of other vector elements can then be derived with `index_addr`. + ### ref_element_addr ``` diff --git a/include/swift/ABI/Metadata.h b/include/swift/ABI/Metadata.h index 52d6355ebb289..5fc46e5db6697 100644 --- a/include/swift/ABI/Metadata.h +++ b/include/swift/ABI/Metadata.h @@ -2352,12 +2352,7 @@ struct TargetExtendedExistentialTypeShape } bool isCopyable() const { - if (!hasGeneralizationSignature()) { - return true; - } - auto *reqts = getGenSigRequirements(); - for (unsigned i = 0, e = getNumGenSigRequirements(); i < e; ++i) { - auto &reqt = reqts[i]; + for (auto &reqt : getRequirementSignature().getRequirements()) { if (reqt.getKind() != GenericRequirementKind::InvertedProtocols) { continue; } diff --git a/include/swift/AST/ASTBridging.h b/include/swift/AST/ASTBridging.h index b4791d6a5836f..a2f683ffc9e7a 100644 --- a/include/swift/AST/ASTBridging.h +++ b/include/swift/AST/ASTBridging.h @@ -215,10 +215,23 @@ BridgedDeclNameLoc BridgedDeclNameLoc_createParsed( BridgedSourceLoc cLParenLoc, BridgedArrayRef cLabelLocs, BridgedSourceLoc cRParenLoc); +SWIFT_NAME("BridgedDeclNameLoc.createParsed(_:moduleSelectorLoc:baseNameLoc:" + "lParenLoc:argumentLabelLocs:rParenLoc:)") +BridgedDeclNameLoc BridgedDeclNameLoc_createParsed( + BridgedASTContext cContext, BridgedSourceLoc cModuleSelectorLoc, + BridgedSourceLoc cBaseNameLoc, BridgedSourceLoc cLParenLoc, + BridgedArrayRef cLabelLocs, BridgedSourceLoc cRParenLoc); + SWIFT_NAME("BridgedDeclNameLoc.createParsed(_:)") BridgedDeclNameLoc BridgedDeclNameLoc_createParsed(BridgedSourceLoc cBaseNameLoc); +SWIFT_NAME("BridgedDeclNameLoc.createParsed(_:moduleSelectorLoc:baseNameLoc:)") +BridgedDeclNameLoc +BridgedDeclNameLoc_createParsed( + BridgedASTContext cContext, BridgedSourceLoc cModuleSelectorLoc, + BridgedSourceLoc cBaseNameLoc); + //===----------------------------------------------------------------------===// // MARK: ASTContext //===----------------------------------------------------------------------===// @@ -592,6 +605,11 @@ void BridgedDiagnosticEngine_diagnose( BridgedArrayRef arguments, BridgedSourceLoc highlightStart, uint32_t hightlightLength, BridgedArrayRef fixIts); +SWIFT_NAME("BridgedDiagnosticEngine.getLocationFromExternalSource(self:path:line:column:)") +BridgedSourceLoc BridgedDiagnostic_getLocationFromExternalSource( + BridgedDiagnosticEngine bridgedEngine, BridgedStringRef path, + SwiftInt line, SwiftInt column); + SWIFT_NAME("getter:BridgedDiagnosticEngine.hadAnyError(self:)") bool BridgedDiagnosticEngine_hadAnyError(BridgedDiagnosticEngine); @@ -1241,6 +1259,18 @@ BridgedNonisolatedAttr_createParsed(BridgedASTContext cContext, BridgedSourceRange cRange, BridgedNonIsolatedModifier modifier); +enum ENUM_EXTENSIBILITY_ATTR(closed) BridgedInheritActorContextModifier { + BridgedInheritActorContextModifierNone, + BridgedInheritActorContextModifierAlways, +}; + +SWIFT_NAME("BridgedInheritActorContextAttr.createParsed(_:atLoc:range:modifier:)") +BridgedInheritActorContextAttr +BridgedInheritActorContextAttr_createParsed(BridgedASTContext cContext, + BridgedSourceLoc cAtLoc, + BridgedSourceRange cRange, + BridgedInheritActorContextModifier modifier); + SWIFT_NAME("BridgedObjCAttr.createParsedUnnamed(_:atLoc:attrNameLoc:)") BridgedObjCAttr BridgedObjCAttr_createParsedUnnamed(BridgedASTContext cContext, @@ -3102,7 +3132,10 @@ struct BridgedASTType { BRIDGED_INLINE bool isBuiltinInteger() const; BRIDGED_INLINE bool isBuiltinFloat() const; BRIDGED_INLINE bool isBuiltinVector() const; + BRIDGED_INLINE bool isBuiltinFixedArray() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedASTType getBuiltinVectorElementType() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedCanType getBuiltinFixedArrayElementType() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedCanType getBuiltinFixedArraySizeType() const; BRIDGED_INLINE bool isBuiltinFixedWidthInteger(SwiftInt width) const; BRIDGED_INLINE bool isOptional() const; BRIDGED_INLINE bool isBuiltinType() const; @@ -3113,6 +3146,7 @@ struct BridgedASTType { SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedASTType getStaticTypeOfDynamicSelf() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedASTType getSuperClassType() const; BRIDGED_INLINE MetatypeRepresentation getRepresentationOfMetatype() const; + BRIDGED_INLINE BridgedOptionalInt getValueOfIntegerType() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedSubstitutionMap getContextSubstitutionMap() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedGenericSignature getInvocationGenericSignatureOfFunctionType() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedASTType subst(BridgedSubstitutionMap substMap) const; diff --git a/include/swift/AST/ASTBridgingImpl.h b/include/swift/AST/ASTBridgingImpl.h index e746053673d75..ee23798b0de70 100644 --- a/include/swift/AST/ASTBridgingImpl.h +++ b/include/swift/AST/ASTBridgingImpl.h @@ -542,10 +542,22 @@ bool BridgedASTType::isBuiltinVector() const { return unbridged()->is(); } +bool BridgedASTType::isBuiltinFixedArray() const { + return unbridged()->is(); +} + BridgedASTType BridgedASTType::getBuiltinVectorElementType() const { return {unbridged()->castTo()->getElementType().getPointer()}; } +BridgedCanType BridgedASTType::getBuiltinFixedArrayElementType() const { + return unbridged()->castTo()->getElementType(); +} + +BridgedCanType BridgedASTType::getBuiltinFixedArraySizeType() const { + return unbridged()->castTo()->getSize(); +} + bool BridgedASTType::isBuiltinFixedWidthInteger(SwiftInt width) const { if (auto *intTy = unbridged()->getAs()) return intTy->isFixedWidth((unsigned)width); @@ -592,6 +604,10 @@ BridgedASTType::MetatypeRepresentation BridgedASTType::getRepresentationOfMetaty return MetatypeRepresentation(unbridged()->getAs()->getRepresentation()); } +BridgedOptionalInt BridgedASTType::getValueOfIntegerType() const { + return BridgedOptionalInt::getFromAPInt(unbridged()->getAs()->getValue()); +} + BridgedSubstitutionMap BridgedASTType::getContextSubstitutionMap() const { return unbridged()->getContextSubstitutionMap(); } diff --git a/include/swift/AST/ASTContext.h b/include/swift/AST/ASTContext.h index 47c712db6f993..aa864037e91fb 100644 --- a/include/swift/AST/ASTContext.h +++ b/include/swift/AST/ASTContext.h @@ -1093,10 +1093,6 @@ class ASTContext final { /// Retrieve the module interface checker associated with this AST context. ModuleInterfaceChecker *getModuleInterfaceChecker() const; - /// Compute the extra implicit framework search paths on Apple platforms: - /// $SDKROOT/System/Library/Frameworks/ and $SDKROOT/Library/Frameworks/. - std::vector getDarwinImplicitFrameworkSearchPaths() const; - /// Load extensions to the given nominal type from the external /// module loaders. /// diff --git a/include/swift/AST/Attr.h b/include/swift/AST/Attr.h index 0a49634fec4f4..9cf98597514c6 100644 --- a/include/swift/AST/Attr.h +++ b/include/swift/AST/Attr.h @@ -230,6 +230,10 @@ class DeclAttribute : public AttributeBase { Modifier : NumNonIsolatedModifierBits ); + SWIFT_INLINE_BITFIELD(InheritActorContextAttr, DeclAttribute, NumInheritActorContextKindBits, + Modifier : NumInheritActorContextKindBits + ); + SWIFT_INLINE_BITFIELD_FULL(AllowFeatureSuppressionAttr, DeclAttribute, 1+31, : NumPadBits, Inverted : 1, @@ -3011,6 +3015,50 @@ class NonisolatedAttr final : public DeclAttribute { } }; +/// Represents @_inheritActorContext modifier. +class InheritActorContextAttr final : public DeclAttribute { +public: + InheritActorContextAttr(SourceLoc atLoc, SourceRange range, + InheritActorContextModifier modifier, bool implicit) + : DeclAttribute(DeclAttrKind::InheritActorContext, atLoc, range, + implicit) { + Bits.InheritActorContextAttr.Modifier = static_cast(modifier); + assert((getModifier() == modifier) && "not enough bits for modifier"); + } + + InheritActorContextModifier getModifier() const { + return static_cast( + Bits.InheritActorContextAttr.Modifier); + } + + bool isAlways() const { + return getModifier() == InheritActorContextModifier::Always; + } + + static InheritActorContextAttr * + createImplicit(ASTContext &ctx, InheritActorContextModifier modifier = + InheritActorContextModifier::None) { + return new (ctx) + InheritActorContextAttr(/*atLoc*/ {}, /*range*/ {}, modifier, + /*implicit=*/true); + } + + static bool classof(const DeclAttribute *DA) { + return DA->getKind() == DeclAttrKind::InheritActorContext; + } + + /// Create a copy of this attribute. + InheritActorContextAttr *clone(ASTContext &ctx) const { + return new (ctx) + InheritActorContextAttr(AtLoc, Range, getModifier(), isImplicit()); + } + + bool isEquivalent(const InheritActorContextAttr *other, + Decl *attachedTo) const { + return getModifier() == other->getModifier(); + } +}; + /// A macro role attribute, spelled with either @attached or @freestanding, /// which declares one of the roles that a given macro can inhabit. class MacroRoleAttr final diff --git a/include/swift/AST/AttrKind.h b/include/swift/AST/AttrKind.h index 7ac94fb07c0e2..1d1a6226f7a91 100644 --- a/include/swift/AST/AttrKind.h +++ b/include/swift/AST/AttrKind.h @@ -142,6 +142,22 @@ enum : unsigned { static_cast(NonIsolatedModifier::Last_NonIsolatedModifier)) }; +enum class InheritActorContextModifier : uint8_t { + /// Inherit the actor execution context if the isolated parameter was + /// captured by the closure, context is nonisolated or isolated to a + /// global actor. + None = 0, + /// Always inherit the actor context, even when the isolated parameter + /// for the context is not closed over explicitly. + Always, + Last_InheritActorContextKind = Always +}; + +enum : unsigned { + NumInheritActorContextKindBits = countBitsUsed(static_cast( + InheritActorContextModifier::Last_InheritActorContextKind)) +}; + enum class DeclAttrKind : unsigned { #define DECL_ATTR(_, CLASS, ...) CLASS, #define LAST_DECL_ATTR(CLASS) Last_DeclAttr = CLASS, diff --git a/include/swift/AST/Decl.h b/include/swift/AST/Decl.h index c42f0b4c16bbc..daf2caa87b0b1 100644 --- a/include/swift/AST/Decl.h +++ b/include/swift/AST/Decl.h @@ -2523,9 +2523,7 @@ class PatternBindingDecl final : public Decl, Pattern *Pat, Expr *E, DeclContext *Parent); - SourceLoc getStartLoc() const { - return StaticLoc.isValid() ? StaticLoc : VarLoc; - } + SourceLoc getStartLoc() const; SourceRange getSourceRange() const; unsigned getNumPatternEntries() const { @@ -6997,6 +6995,10 @@ class ParamDecl : public VarDecl { /// Create a an identical copy of this ParamDecl. static ParamDecl *clone(const ASTContext &Ctx, ParamDecl *PD); + static ParamDecl *cloneAccessor(const ASTContext &Ctx, + ParamDecl const *subscriptParam, + DeclContext *Parent); + static ParamDecl * createImplicit(ASTContext &Context, SourceLoc specifierLoc, SourceLoc argumentNameLoc, Identifier argumentName, @@ -8413,9 +8415,8 @@ class FuncDecl : public AbstractFunctionDecl { SourceLoc getStaticLoc() const { return StaticLoc; } SourceLoc getFuncLoc() const { return FuncLoc; } - SourceLoc getStartLoc() const { - return StaticLoc.isValid() ? StaticLoc : FuncLoc; - } + SourceLoc getStartLoc() const; + SourceLoc getEndLoc() const; SourceRange getSourceRange() const; TypeRepr *getResultTypeRepr() const { return FnRetType.getTypeRepr(); } diff --git a/include/swift/AST/DeclAttr.def b/include/swift/AST/DeclAttr.def index 5ab0c87977644..28560878799c4 100644 --- a/include/swift/AST/DeclAttr.def +++ b/include/swift/AST/DeclAttr.def @@ -620,9 +620,10 @@ SIMPLE_DECL_ATTR(_implicitSelfCapture, ImplicitSelfCapture, UserInaccessible | ABIStableToAdd | ABIStableToRemove | APIStableToAdd | APIBreakingToRemove | ForbiddenInABIAttr, 115) -SIMPLE_DECL_ATTR(_inheritActorContext, InheritActorContext, +DECL_ATTR(_inheritActorContext, InheritActorContext, OnParam, - UserInaccessible | ABIStableToAdd | ABIStableToRemove | APIBreakingToAdd | APIBreakingToRemove | ForbiddenInABIAttr, + // since the _inheritActorContext(always) forces an actor capture, it changes ABI of the closure this applies to + UserInaccessible | ABIBreakingToAdd | ABIBreakingToRemove | APIBreakingToAdd | APIBreakingToRemove | UnconstrainedInABIAttr, 116) SIMPLE_DECL_ATTR(_eagerMove, EagerMove, diff --git a/include/swift/AST/DeclNameLoc.h b/include/swift/AST/DeclNameLoc.h index a4a65ef50be99..494a4ae721faf 100644 --- a/include/swift/AST/DeclNameLoc.h +++ b/include/swift/AST/DeclNameLoc.h @@ -20,6 +20,8 @@ #include "swift/Basic/LLVM.h" #include "swift/Basic/SourceLoc.h" +#include "llvm/ADT/ArrayRef.h" + class BridgedDeclNameLoc; namespace swift { @@ -71,6 +73,10 @@ class DeclNameLoc { explicit DeclNameLoc(SourceLoc baseNameLoc) : DeclNameLoc(baseNameLoc.getOpaquePointerValue(), 0) {} + explicit DeclNameLoc(ASTContext &ctx, SourceLoc moduleSelectorLoc, + SourceLoc baseNameLoc) + : DeclNameLoc(baseNameLoc) { } + /// Create declaration name location information for a compound /// name. DeclNameLoc(ASTContext &ctx, SourceLoc baseNameLoc, @@ -78,6 +84,13 @@ class DeclNameLoc { ArrayRef argumentLabelLocs, SourceLoc rParenLoc); + DeclNameLoc(ASTContext &ctx, SourceLoc moduleSelectorLoc, + SourceLoc baseNameLoc, + SourceLoc lParenLoc, + ArrayRef argumentLabelLocs, + SourceLoc rParenLoc) + : DeclNameLoc(ctx, baseNameLoc, lParenLoc, argumentLabelLocs, rParenLoc) { } + /// Whether the location information is valid. bool isValid() const { return getBaseNameLoc().isValid(); } @@ -111,6 +124,10 @@ class DeclNameLoc { return getSourceLocs()[FirstArgumentLabelIndex + index]; } + SourceLoc getModuleSelectorLoc() const { + return SourceLoc(); + } + SourceLoc getStartLoc() const { return getBaseNameLoc(); } diff --git a/include/swift/AST/DiagnosticsFrontend.def b/include/swift/AST/DiagnosticsFrontend.def index db4f2e792a1f9..113542b215a9b 100644 --- a/include/swift/AST/DiagnosticsFrontend.def +++ b/include/swift/AST/DiagnosticsFrontend.def @@ -520,7 +520,7 @@ REMARK(matching_output_produced,none, // Caching related diagnostics ERROR(error_caching_no_cas_fs, none, - "caching is enabled without -cas-fs option, input is not immutable", ()) + "caching is enabled without CAS file-system options, input is not immutable", ()) ERROR(error_prefix_mapping, none, "cannot create scanner prefix mapping: '%0'", (StringRef)) REMARK(replay_output, none, "replay output file '%0': key '%1'", (StringRef, StringRef)) @@ -534,6 +534,7 @@ ERROR(error_cache_key_creation, none, "cannot create cache key for compilation % ERROR(error_cas_file_ref, none, "cannot load file %0 from CAS filesystem", (StringRef)) ERROR(error_cas_conflict_options, none, "cannot setup CAS due to conflicting '-cas-*' options", ()) ERROR(error_cas_initialization, none, "CAS cannot be initialized from the specified '-cas-*' options: %0", (StringRef)) +ERROR(error_cas_malformed_input, none, "CAS input '%0' is malformed: %1", (StringRef, StringRef)) WARNING(cache_replay_failed, none, "cache replay failed: %0", (StringRef)) ERROR(error_failed_cached_diag, none, "failed to serialize cached diagnostics: %0", (StringRef)) diff --git a/include/swift/AST/DiagnosticsSema.def b/include/swift/AST/DiagnosticsSema.def index f93a592702e84..1c99d066ed8b9 100644 --- a/include/swift/AST/DiagnosticsSema.def +++ b/include/swift/AST/DiagnosticsSema.def @@ -8595,6 +8595,23 @@ GROUPED_ERROR(isolated_conformance_wrong_domain,IsolatedConformances,none, "%0 conformance of %1 to %2 cannot be used in %3 context", (ActorIsolation, Type, DeclName, ActorIsolation)) +//===----------------------------------------------------------------------===// +// MARK: @_inheritActorContext +//===----------------------------------------------------------------------===// +ERROR(inherit_actor_context_only_on_func_types,none, + "%0 only applies to parameters with function types (got: %1)", + (DeclAttribute, Type)) + +ERROR(inherit_actor_context_only_on_sending_or_Sendable_params,none, + "%0 only applies to 'sending' parameters or parameters with " + "'@Sendable' function types", + (DeclAttribute)) + +ERROR(inherit_actor_context_only_on_async_or_isolation_erased_params,none, + "%0 only applies to '@isolated(any)' parameters or parameters with " + "asynchronous function types", + (DeclAttribute)) + //===----------------------------------------------------------------------===// // MARK: @concurrent and nonisolated(nonsending) attributes //===----------------------------------------------------------------------===// diff --git a/include/swift/AST/ExistentialLayout.h b/include/swift/AST/ExistentialLayout.h index 7e4fa5e75189c..ad45c33a5e379 100644 --- a/include/swift/AST/ExistentialLayout.h +++ b/include/swift/AST/ExistentialLayout.h @@ -117,9 +117,24 @@ struct ExistentialLayout { LayoutConstraint getLayoutConstraint() const; + /// Whether this layout has any inverses within its signature. + bool hasInverses() const { + return !inverses.empty(); + } + + /// Whether this existential needs to have an extended existential shape. This + /// is relevant for the mangler to mangle as a symbolic link where possible + /// and for IRGen directly emitting some existentials. + /// + /// If 'allowInverses' is false, then regardless of if this existential layout + /// has inverse requirements those will not influence the need for having a + /// shape. + bool needsExtendedShape(bool allowInverses = true) const; + private: SmallVector protocols; SmallVector parameterized; + InvertibleProtocolSet inverses; }; } diff --git a/include/swift/AST/Expr.h b/include/swift/AST/Expr.h index 2d052da7ce819..fa7fc3664b083 100644 --- a/include/swift/AST/Expr.h +++ b/include/swift/AST/Expr.h @@ -267,7 +267,7 @@ class alignas(8) Expr : public ASTAllocated { Kind : 2 ); - SWIFT_INLINE_BITFIELD(ClosureExpr, AbstractClosureExpr, 1+1+1+1+1+1+1+1, + SWIFT_INLINE_BITFIELD(ClosureExpr, AbstractClosureExpr, 1+1+1+1+1+1+1+1+1, /// True if closure parameters were synthesized from anonymous closure /// variables. HasAnonymousClosureVars : 1, @@ -276,9 +276,11 @@ class alignas(8) Expr : public ASTAllocated { /// on each member reference. ImplicitSelfCapture : 1, - /// True if this @Sendable async closure parameter should implicitly - /// inherit the actor context from where it was formed. + /// True if this closure parameter should implicitly inherit the actor + /// context from where it was formed. InheritActorContext : 1, + /// The kind for inheritance - none or always at the moment. + InheritActorContextKind : 1, /// True if this closure's actor isolation behavior was determined by an /// \c \@preconcurrency declaration. @@ -4318,6 +4320,7 @@ class ClosureExpr : public AbstractClosureExpr { Bits.ClosureExpr.HasAnonymousClosureVars = false; Bits.ClosureExpr.ImplicitSelfCapture = false; Bits.ClosureExpr.InheritActorContext = false; + Bits.ClosureExpr.InheritActorContextKind = 0; Bits.ClosureExpr.IsPassedToSendingParameter = false; Bits.ClosureExpr.NoGlobalActorAttribute = false; Bits.ClosureExpr.RequiresDynamicIsolationChecking = false; @@ -4366,8 +4369,29 @@ class ClosureExpr : public AbstractClosureExpr { return Bits.ClosureExpr.InheritActorContext; } - void setInheritsActorContext(bool value = true) { + /// Whether this closure should _always_ implicitly inherit the actor context + /// regardless of whether the isolation parameter is captured or not. + bool alwaysInheritsActorContext() const { + if (!inheritsActorContext()) + return false; + return getInheritActorIsolationModifier() == + InheritActorContextModifier::Always; + } + + void setInheritsActorContext(bool value = true, + InheritActorContextModifier modifier = + InheritActorContextModifier::None) { Bits.ClosureExpr.InheritActorContext = value; + Bits.ClosureExpr.InheritActorContextKind = uint8_t(modifier); + assert((static_cast( + Bits.ClosureExpr.InheritActorContextKind) == modifier) && + "not enough bits for modifier"); + } + + InheritActorContextModifier getInheritActorIsolationModifier() const { + assert(inheritsActorContext()); + return static_cast( + Bits.ClosureExpr.InheritActorContextKind); } /// Whether the closure's concurrency behavior was determined by an diff --git a/include/swift/AST/Identifier.h b/include/swift/AST/Identifier.h index 036685873da73..7268aff1d1fbb 100644 --- a/include/swift/AST/Identifier.h +++ b/include/swift/AST/Identifier.h @@ -693,65 +693,73 @@ class DeclNameRef { void *getOpaqueValue() const { return FullName.getOpaqueValue(); } static DeclNameRef getFromOpaqueValue(void *p); + explicit DeclNameRef(ASTContext &C, Identifier moduleSelector, + DeclName fullName) + : FullName(fullName) { } + + explicit DeclNameRef(ASTContext &C, Identifier moduleSelector, + DeclBaseName baseName, ArrayRef argLabels) + : FullName(C, baseName, argLabels) { } + explicit DeclNameRef(DeclName FullName) : FullName(FullName) { } - explicit DeclNameRef(DeclBaseName BaseName) - : FullName(BaseName) { } + bool hasModuleSelector() const { + return false; + } - explicit DeclNameRef(Identifier BaseName) - : FullName(BaseName) { } + Identifier getModuleSelector() const { + return Identifier(); + } /// The name of the declaration being referenced. DeclName getFullName() const { return FullName; } - DeclName &getFullName() { - return FullName; - } - /// The base name of the declaration being referenced. DeclBaseName getBaseName() const { - return FullName.getBaseName(); + return getFullName().getBaseName(); } Identifier getBaseIdentifier() const { - return FullName.getBaseIdentifier(); + return getFullName().getBaseIdentifier(); } ArrayRef getArgumentNames() const { - return FullName.getArgumentNames(); + return getFullName().getArgumentNames(); } bool isSimpleName() const { - return FullName.isSimpleName(); + return getFullName().isSimpleName(); } bool isSimpleName(DeclBaseName name) const { - return FullName.isSimpleName(name); + return getFullName().isSimpleName(name); } bool isSimpleName(StringRef name) const { - return FullName.isSimpleName(name); + return getFullName().isSimpleName(name); } bool isSpecial() const { - return FullName.isSpecial(); + return getFullName().isSpecial(); } bool isOperator() const { - return FullName.isOperator(); + return getFullName().isOperator(); } - bool mustAlwaysBeEscaped() const { return FullName.mustAlwaysBeEscaped(); } + bool mustAlwaysBeEscaped() const { + return getFullName().mustAlwaysBeEscaped(); + } bool isCompoundName() const { - return FullName.isCompoundName(); + return getFullName().isCompoundName(); } explicit operator bool() const { - return (bool)FullName; + return (bool)getFullName(); } /// Compare two declaration names, producing -1 if \c *this comes before @@ -791,7 +799,7 @@ class DeclNameRef { return lhs.compare(rhs) >= 0; } - DeclNameRef withoutArgumentLabels() const; + DeclNameRef withoutArgumentLabels(ASTContext &C) const; DeclNameRef withArgumentLabels(ASTContext &C, ArrayRef argumentNames) const; @@ -824,16 +832,15 @@ inline DeclNameRef DeclNameRef::getFromOpaqueValue(void *p) { return DeclNameRef(DeclName::getFromOpaqueValue(p)); } -inline DeclNameRef DeclNameRef::withoutArgumentLabels() const { - return DeclNameRef(getBaseName()); +inline DeclNameRef DeclNameRef::withoutArgumentLabels(ASTContext &C) const { + return DeclNameRef(C, getModuleSelector(), getBaseName()); } inline DeclNameRef DeclNameRef::withArgumentLabels( ASTContext &C, ArrayRef argumentNames) const { - return DeclNameRef(DeclName(C, getBaseName(), argumentNames)); + return DeclNameRef(C, getModuleSelector(), getBaseName(), argumentNames); } - inline DeclNameRef DeclNameRef::createSubscript() { return DeclNameRef(DeclBaseName::createSubscript()); } diff --git a/include/swift/AST/KnownIdentifiers.def b/include/swift/AST/KnownIdentifiers.def index c4651036541ea..8be2729b9376a 100644 --- a/include/swift/AST/KnownIdentifiers.def +++ b/include/swift/AST/KnownIdentifiers.def @@ -325,6 +325,7 @@ IDENTIFIER(SerializationRequirement) IDENTIFIER_WITH_NAME(builderSelf, "$builderSelf") // Attribute options +IDENTIFIER(always) IDENTIFIER_(_always) IDENTIFIER_(assumed) IDENTIFIER(checked) diff --git a/include/swift/AST/KnownProtocols.def b/include/swift/AST/KnownProtocols.def index 89c14badf0464..8e647caedf31c 100644 --- a/include/swift/AST/KnownProtocols.def +++ b/include/swift/AST/KnownProtocols.def @@ -97,7 +97,7 @@ PROTOCOL(Executor) PROTOCOL(SerialExecutor) PROTOCOL(TaskExecutor) PROTOCOL(GlobalActor) -PROTOCOL(ExecutorFactory) +PROTOCOL_(ExecutorFactory) PROTOCOL_(BridgedNSError) PROTOCOL_(BridgedStoredNSError) diff --git a/include/swift/AST/ModuleDependencies.h b/include/swift/AST/ModuleDependencies.h index 998a57650f637..47e69d1bed37b 100644 --- a/include/swift/AST/ModuleDependencies.h +++ b/include/swift/AST/ModuleDependencies.h @@ -1000,7 +1000,7 @@ using ModuleDependenciesKindMap = /// Track swift dependency class SwiftDependencyTracker { public: - SwiftDependencyTracker(llvm::cas::CachingOnDiskFileSystem &FS, + SwiftDependencyTracker(std::shared_ptr CAS, llvm::PrefixMapper *Mapper, const CompilerInvocation &CI); @@ -1009,7 +1009,8 @@ class SwiftDependencyTracker { llvm::Expected createTreeFromDependencies(); private: - llvm::IntrusiveRefCntPtr FS; + llvm::IntrusiveRefCntPtr FS; + std::shared_ptr CAS; llvm::PrefixMapper *Mapper; struct FileEntry { @@ -1035,10 +1036,7 @@ class SwiftDependencyScanningService { ClangScanningService; /// CachingOnDiskFileSystem for dependency tracking. - llvm::IntrusiveRefCntPtr CacheFS; - - /// If use clang include tree. - bool UseClangIncludeTree = false; + llvm::IntrusiveRefCntPtr CacheFS; /// CAS Instance. std::shared_ptr CAS; @@ -1076,8 +1074,8 @@ class SwiftDependencyScanningService { return *SharedFilesystemCache; } - llvm::cas::CachingOnDiskFileSystem &getSharedCachingFS() const { - assert(CacheFS && "Expect CachingOnDiskFileSystem"); + llvm::vfs::FileSystem &getSharedCachingFS() const { + assert(CacheFS && "Expect a CASFileSystem"); return *CacheFS; } @@ -1088,20 +1086,17 @@ class SwiftDependencyScanningService { std::optional createSwiftDependencyTracker(const CompilerInvocation &CI) { - if (!CacheFS) + if (!CAS) return std::nullopt; - return SwiftDependencyTracker(*CacheFS, Mapper.get(), CI); + return SwiftDependencyTracker(CAS, Mapper.get(), CI); } llvm::IntrusiveRefCntPtr getClangScanningFS() const { - if (UseClangIncludeTree) + if (CAS) return llvm::cas::createCASProvidingFileSystem( CAS, llvm::vfs::createPhysicalFileSystem()); - if (CacheFS) - return CacheFS->createProxyFS(); - return llvm::vfs::createPhysicalFileSystem(); } diff --git a/include/swift/AST/ProtocolConformance.h b/include/swift/AST/ProtocolConformance.h index 61447600ee20a..f3760fe9835c4 100644 --- a/include/swift/AST/ProtocolConformance.h +++ b/include/swift/AST/ProtocolConformance.h @@ -918,9 +918,7 @@ class SelfProtocolConformance : public RootProtocolConformance { } ProtocolConformanceRef getAssociatedConformance(Type assocType, - ProtocolDecl *protocol) const{ - llvm_unreachable("self-conformances never have associated types"); - } + ProtocolDecl *protocol) const; bool hasWitness(ValueDecl *requirement) const { return true; diff --git a/include/swift/AST/SearchPathOptions.h b/include/swift/AST/SearchPathOptions.h index 1156288955327..0122d13fba2cc 100644 --- a/include/swift/AST/SearchPathOptions.h +++ b/include/swift/AST/SearchPathOptions.h @@ -35,7 +35,7 @@ namespace swift { enum class ModuleSearchPathKind { Import, Framework, - DarwinImplicitFramework, + ImplicitFramework, RuntimeLibrary, }; @@ -356,12 +356,8 @@ class SearchPathOptions { /// When on Darwin the framework paths that are implicitly imported. /// $SDKROOT/System/Library/Frameworks/ and $SDKROOT/Library/Frameworks/. /// - /// On non-Darwin platforms these are populated, but ignored. - /// - /// Computed when the SDK path is set and cached so we can reference the - /// Darwin implicit framework search paths as \c StringRef from - /// \c ModuleSearchPath. - std::vector DarwinImplicitFrameworkSearchPaths; + /// Must be modified through setter to keep \c Lookup in sync. + std::vector ImplicitFrameworkSearchPaths; /// Compiler plugin library search paths. std::vector CompilerPluginLibraryPaths; @@ -401,21 +397,6 @@ class SearchPathOptions { void setSDKPath(std::string NewSDKPath) { SDKPath = NewSDKPath; - - // Compute Darwin implicit framework search paths. - SmallString<128> systemFrameworksScratch(NewSDKPath); - llvm::sys::path::append(systemFrameworksScratch, "System", "Library", - "Frameworks"); - SmallString<128> systemSubFrameworksScratch(NewSDKPath); - llvm::sys::path::append(systemSubFrameworksScratch, "System", "Library", - "SubFrameworks"); - SmallString<128> frameworksScratch(NewSDKPath); - llvm::sys::path::append(frameworksScratch, "Library", "Frameworks"); - DarwinImplicitFrameworkSearchPaths = {systemFrameworksScratch.str().str(), - systemSubFrameworksScratch.str().str(), - frameworksScratch.str().str()}; - - Lookup.searchPathsDidChange(); } /// Retrieves the corresponding parent platform path for the SDK, or @@ -470,8 +451,14 @@ class SearchPathOptions { /// The extra implicit framework search paths on Apple platforms: /// $SDKROOT/System/Library/Frameworks/ and $SDKROOT/Library/Frameworks/. - ArrayRef getDarwinImplicitFrameworkSearchPaths() const { - return DarwinImplicitFrameworkSearchPaths; + ArrayRef getImplicitFrameworkSearchPaths() const { + return ImplicitFrameworkSearchPaths; + } + + void setImplicitFrameworkSearchPaths( + std::vector NewImplicitFrameworkSearchPaths) { + ImplicitFrameworkSearchPaths = NewImplicitFrameworkSearchPaths; + Lookup.searchPathsDidChange(); } ArrayRef getRuntimeLibraryImportPaths() const { @@ -505,11 +492,11 @@ class SearchPathOptions { /// Path to in-process plugin server shared library. std::string InProcessPluginServerPath; - /// Don't look in for compiler-provided modules. - bool SkipRuntimeLibraryImportPaths = false; + /// Don't automatically add any import paths. + bool SkipAllImplicitImportPaths = false; - /// Don't include SDK paths in the RuntimeLibraryImportPaths - bool ExcludeSDKPathsFromRuntimeLibraryImportPaths = false; + /// Don't automatically add any import paths from the SDK. + bool SkipSDKImportPaths = false; /// Scanner Prefix Mapper. std::vector ScannerPrefixMapper; @@ -619,6 +606,8 @@ class SearchPathOptions { RuntimeResourcePath, hash_combine_range(RuntimeLibraryImportPaths.begin(), RuntimeLibraryImportPaths.end()), + hash_combine_range(ImplicitFrameworkSearchPaths.begin(), + ImplicitFrameworkSearchPaths.end()), DisableModulesValidateSystemDependencies, ScannerModuleValidation, ModuleLoadMode); diff --git a/include/swift/AST/SemanticAttrs.def b/include/swift/AST/SemanticAttrs.def index f2b93fb575ffe..ffe2717cb304c 100644 --- a/include/swift/AST/SemanticAttrs.def +++ b/include/swift/AST/SemanticAttrs.def @@ -165,5 +165,7 @@ SEMANTICS_ATTR(USE_FRAME_POINTER, "use_frame_pointer") SEMANTICS_ATTR(FIXED_STORAGE_CHECK_INDEX, "fixed_storage.check_index") SEMANTICS_ATTR(FIXED_STORAGE_GET_COUNT, "fixed_storage.get_count") +SEMANTICS_ATTR(NO_SIL_VERIFICATION, "sil.verify_none") + #undef SEMANTICS_ATTR diff --git a/include/swift/AST/TypeTransform.h b/include/swift/AST/TypeTransform.h index 8348506c836a8..a45be7aa16d0c 100644 --- a/include/swift/AST/TypeTransform.h +++ b/include/swift/AST/TypeTransform.h @@ -1176,6 +1176,12 @@ case TypeKind::Id: if (transformedPack.getPointer() == element->getPackType().getPointer()) return element; + if (!transformedPack->isParameterPack() && + !transformedPack->is() && + !transformedPack->isTypeVariableOrMember()) { + return transformedPack; + } + return PackElementType::get(transformedPack, element->getLevel()); } diff --git a/include/swift/AST/Types.h b/include/swift/AST/Types.h index dc16ee631d578..4527d65ba803c 100644 --- a/include/swift/AST/Types.h +++ b/include/swift/AST/Types.h @@ -4049,6 +4049,7 @@ struct ParameterListInfo { SmallBitVector propertyWrappers; SmallBitVector implicitSelfCapture; SmallBitVector inheritActorContext; + SmallBitVector alwaysInheritActorContext; SmallBitVector variadicGenerics; SmallBitVector sendingParameters; @@ -4075,7 +4076,8 @@ struct ParameterListInfo { /// Whether the given parameter is a closure that should inherit the /// actor context from the context in which it was created. - bool inheritsActorContext(unsigned paramIdx) const; + std::pair + inheritsActorContext(unsigned paramIdx) const; bool isVariadicGenericParameter(unsigned paramIdx) const; diff --git a/include/swift/Basic/BasicBridging.h b/include/swift/Basic/BasicBridging.h index 36ea6df43908f..4563f446533ab 100644 --- a/include/swift/Basic/BasicBridging.h +++ b/include/swift/Basic/BasicBridging.h @@ -50,6 +50,7 @@ #include "swift/Basic/SourceLoc.h" #include "llvm/ADT/StringRef.h" +#include "llvm/ADT/APInt.h" #include #include #endif @@ -273,6 +274,24 @@ BRIDGED_INLINE SwiftInt BridgedOwnedString_count(BridgedOwnedString str); SWIFT_NAME("getter:BridgedOwnedString.isEmpty(self:)") BRIDGED_INLINE bool BridgedOwnedString_empty(BridgedOwnedString str); +//===----------------------------------------------------------------------===// +// MARK: BridgedOptionalInt +//===----------------------------------------------------------------------===// + +struct BridgedOptionalInt { + SwiftInt value; + bool hasValue; + +#ifdef USED_IN_CPP_SOURCE + static BridgedOptionalInt getFromAPInt(llvm::APInt i) { + if (i.getSignificantBits() <= std::min(std::numeric_limits::digits, 64)) { + return {(SwiftInt)i.getSExtValue(), true}; + } + return {0, false}; + } +#endif +}; + //===----------------------------------------------------------------------===// // MARK: OStream //===----------------------------------------------------------------------===// diff --git a/include/swift/Basic/CASOptions.h b/include/swift/Basic/CASOptions.h index fb63938e1f3fb..82f7731b88dd4 100644 --- a/include/swift/Basic/CASOptions.h +++ b/include/swift/Basic/CASOptions.h @@ -37,14 +37,11 @@ class CASOptions final { /// CASOptions clang::CASOptions CASOpts; - /// CASFS Root. - std::vector CASFSRootIDs; - /// Clang Include Trees. - std::vector ClangIncludeTrees; + std::string ClangIncludeTree; /// Clang Include Tree FileList. - std::vector ClangIncludeTreeFileList; + std::string ClangIncludeTreeFileList; /// CacheKey for input file. std::string InputFileKey; @@ -62,9 +59,8 @@ class CASOptions final { /// Check to see if a CASFileSystem is required. bool requireCASFS() const { return EnableCaching && - (!CASFSRootIDs.empty() || !ClangIncludeTrees.empty() || - !ClangIncludeTreeFileList.empty() || !InputFileKey.empty() || - !BridgingHeaderPCHCacheKey.empty()); + (!ClangIncludeTree.empty() || !ClangIncludeTreeFileList.empty() || + !InputFileKey.empty() || !BridgingHeaderPCHCacheKey.empty()); } /// Return a hash code of any components from these options that should diff --git a/include/swift/Basic/Features.def b/include/swift/Basic/Features.def index 1b46be47bb81a..ac2a9ad29e494 100644 --- a/include/swift/Basic/Features.def +++ b/include/swift/Basic/Features.def @@ -259,6 +259,7 @@ LANGUAGE_FEATURE(IsolatedConformances, 407, "Global-actor isolated conformances" LANGUAGE_FEATURE(ValueGenericsNameLookup, 452, "Value generics appearing as static members for namelookup") LANGUAGE_FEATURE(GeneralizedIsSameMetaTypeBuiltin, 465, "Builtin.is_same_metatype with support for noncopyable/nonescapable types") SUPPRESSIBLE_LANGUAGE_FEATURE(ABIAttributeSE0479, 479, "@abi attribute on functions, initializers, properties, and subscripts") +LANGUAGE_FEATURE(AlwaysInheritActorContext, 472, "@_inheritActorContext(always)") // Swift 6 UPCOMING_FEATURE(ConciseMagicFile, 274, 6) @@ -508,6 +509,9 @@ EXPERIMENTAL_FEATURE(CDecl, false) /// Allow use of `@extensible` on public enums SUPPRESSIBLE_EXPERIMENTAL_FEATURE(ExtensibleAttribute, false) +/// Allow use of `Module::name` syntax +EXPERIMENTAL_FEATURE(ModuleSelector, false) + #undef EXPERIMENTAL_FEATURE_EXCLUDED_FROM_MODULE_INTERFACE #undef EXPERIMENTAL_FEATURE #undef UPCOMING_FEATURE diff --git a/include/swift/Basic/LangOptions.h b/include/swift/Basic/LangOptions.h index 4613509989473..9e557da32c21a 100644 --- a/include/swift/Basic/LangOptions.h +++ b/include/swift/Basic/LangOptions.h @@ -1094,12 +1094,6 @@ namespace swift { /// built and provided to the compiler invocation. bool DisableImplicitClangModules = false; - /// Enable ClangIncludeTree for explicit module builds scanning. - bool UseClangIncludeTree = false; - - /// Using ClangIncludeTreeRoot for compilation. - bool HasClangIncludeTreeRoot = false; - /// Whether the dependency scanner should construct all swift-frontend /// invocations directly from clang cc1 args. bool ClangImporterDirectCC1Scan = false; diff --git a/include/swift/ClangImporter/ClangImporter.h b/include/swift/ClangImporter/ClangImporter.h index e4cc9825fb4df..0862c3c94df95 100644 --- a/include/swift/ClangImporter/ClangImporter.h +++ b/include/swift/ClangImporter/ClangImporter.h @@ -474,11 +474,6 @@ class ClangImporter final : public ClangModuleLoader { /// Reads the original source file name from PCH. std::string getOriginalSourceFile(StringRef PCHFilename); - /// Add clang dependency file names. - /// - /// \param files The list of file to append dependencies to. - void addClangInvovcationDependencies(std::vector &files); - /// Makes a temporary replica of the ClangImporter's CompilerInstance, reads a /// module map into the replica and emits a PCM file for one of the modules it /// declares. Delegates to clang for everything except construction of the diff --git a/include/swift/Frontend/CachingUtils.h b/include/swift/Frontend/CachingUtils.h index e478c22daf56c..d676ccbcaa4e6 100644 --- a/include/swift/Frontend/CachingUtils.h +++ b/include/swift/Frontend/CachingUtils.h @@ -70,9 +70,9 @@ std::unique_ptr loadCachedCompileResultFromCacheKey( llvm::StringRef Filename = ""); llvm::Expected> -createCASFileSystem(llvm::cas::ObjectStore &CAS, ArrayRef FSRoots, - ArrayRef IncludeTreeRoots, - ArrayRef IncludeTreeFileList); +createCASFileSystem(llvm::cas::ObjectStore &CAS, + const std::string &IncludeTreeRoot, + const std::string &IncludeTreeFileList); std::vector remapPathsFromCommandLine( ArrayRef Args, diff --git a/include/swift/Option/FrontendOptions.td b/include/swift/Option/FrontendOptions.td index f58a070c8836e..9586ba7bf05ec 100644 --- a/include/swift/Option/FrontendOptions.td +++ b/include/swift/Option/FrontendOptions.td @@ -1454,9 +1454,6 @@ def bridging_header_pch_key : Separate<["-"], "bridging-header-pch-key">, def no_clang_include_tree: Flag<["-"], "no-clang-include-tree">, HelpText<"Do not use clang include tree, fallback to use CAS filesystem to build clang modules">; -def cas_fs: Separate<["-"], "cas-fs">, - HelpText<"Root CASID for CAS FileSystem">, MetaVarName<"">; - def clang_include_tree_root: Separate<["-"], "clang-include-tree-root">, HelpText<"Clang Include Tree CASID">, MetaVarName<"">; def clang_include_tree_filelist: Separate<["-"], "clang-include-tree-filelist">, diff --git a/include/swift/Parse/IDEInspectionCallbacks.h b/include/swift/Parse/IDEInspectionCallbacks.h index 938083795af51..3605662f6ac1c 100644 --- a/include/swift/Parse/IDEInspectionCallbacks.h +++ b/include/swift/Parse/IDEInspectionCallbacks.h @@ -39,7 +39,8 @@ enum class ParameterizedDeclAttributeKind { Available, FreestandingMacro, AttachedMacro, - StorageRestrictions + StorageRestrictions, + InheritActorContext }; /// A bit of a hack. When completing inside the '@storageRestrictions' diff --git a/include/swift/SIL/AddressWalker.h b/include/swift/SIL/AddressWalker.h index 003f636a373a3..9edaeadcb0951 100644 --- a/include/swift/SIL/AddressWalker.h +++ b/include/swift/SIL/AddressWalker.h @@ -249,6 +249,7 @@ TransitiveAddressWalker::walk(SILValue projectedAddress) { isa(user) || isa(user) || isa(user) || isa(user) || isa(user) || + isa(user) || isa(user) || isa(user) || isa(user) || isa(user) || isa(user) || diff --git a/include/swift/SIL/InstructionUtils.h b/include/swift/SIL/InstructionUtils.h index a1ec3ea2fbbc4..12722d64ac3c0 100644 --- a/include/swift/SIL/InstructionUtils.h +++ b/include/swift/SIL/InstructionUtils.h @@ -247,6 +247,13 @@ lookUpFunctionInWitnessTable(WitnessMethodInst *wmi, SILModule::LinkingMode link /// struct-with-deinit drops the deinit. bool shouldExpand(SILModule &module, SILType ty); +/// Returns true if `arg` is mutated. +/// if `ignoreDestroys` is true, `destroy_addr` instructions are ignored. +/// `defaultIsMutating` specifies the state of instructions which are not explicitly handled. +/// For historical reasons this utility is implemented in SILVerifier.cpp. +bool isIndirectArgumentMutated(SILFunctionArgument *arg, bool ignoreDestroys = false, + bool defaultIsMutating = false); + } // end namespace swift #endif diff --git a/include/swift/SIL/SILBitfield.h b/include/swift/SIL/SILBitfield.h index ee46097540747..a3497f554941a 100644 --- a/include/swift/SIL/SILBitfield.h +++ b/include/swift/SIL/SILBitfield.h @@ -111,7 +111,7 @@ template class SILBitfield { } }; -/// A set which knowns its size. +/// A set which knows its size. /// /// This template adds a size property to a base `Set`. template diff --git a/include/swift/SIL/SILBridging.h b/include/swift/SIL/SILBridging.h index 2578d0ca6d3ee..3b6a0d53f7573 100644 --- a/include/swift/SIL/SILBridging.h +++ b/include/swift/SIL/SILBridging.h @@ -392,6 +392,12 @@ enum class BridgedMemoryBehavior { struct BridgedLocation { uint64_t storage[3]; + struct FilenameAndLocation { + BridgedStringRef path; + SwiftInt line; + SwiftInt column; + }; + BRIDGED_INLINE BridgedLocation(const swift::SILDebugLocation &loc); BRIDGED_INLINE const swift::SILDebugLocation &getLoc() const; @@ -402,6 +408,8 @@ struct BridgedLocation { BRIDGED_INLINE bool isInlined() const; BRIDGED_INLINE bool isEqualTo(BridgedLocation rhs) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedSourceLoc getSourceLocation() const; + BRIDGED_INLINE bool isFilenameAndLocation() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE FilenameAndLocation getFilenameAndLocation() const; BRIDGED_INLINE bool hasSameSourceLocation(BridgedLocation rhs) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedDeclObj getDecl() const; static BRIDGED_INLINE BridgedLocation fromNominalTypeDecl(BridgedDeclObj decl); @@ -691,11 +699,6 @@ struct BridgedInstruction { unknown }; - struct OptionalInt { - SwiftInt value; - bool hasValue; - }; - enum class MarkDependenceKind { Unresolved, Escaping, NonEscaping }; @@ -736,7 +739,7 @@ struct BridgedInstruction { 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; - BRIDGED_INLINE OptionalInt IntegerLiteralInst_getValue() const; + BRIDGED_INLINE BridgedOptionalInt IntegerLiteralInst_getValue() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef StringLiteralInst_getValue() const; BRIDGED_INLINE int StringLiteralInst_getEncoding() const; BRIDGED_INLINE SwiftInt TupleExtractInst_fieldIndex() const; @@ -854,7 +857,6 @@ struct BridgedInstruction { BRIDGED_INLINE SwiftInt FullApplySite_numIndirectResultArguments() const; BRIDGED_INLINE bool ConvertFunctionInst_withoutActuallyEscaping() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedCanType TypeValueInst_getParamType() const; - BRIDGED_INLINE SwiftInt TypeValueInst_getValue() const; // =========================================================================// // VarDeclInst and DebugVariableInst @@ -1258,6 +1260,7 @@ struct BridgedBuilder{ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createObject(BridgedType type, BridgedValueArray arguments, SwiftInt numBaseElements) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createVector(BridgedValueArray arguments) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createVectorBaseAddr(BridgedValue vector) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createGlobalAddr(BridgedGlobalVar global, OptionalBridgedValue dependencyToken) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createGlobalValue(BridgedGlobalVar global, diff --git a/include/swift/SIL/SILBridgingImpl.h b/include/swift/SIL/SILBridgingImpl.h index f807da6e1ab85..f9ac3c073b75b 100644 --- a/include/swift/SIL/SILBridgingImpl.h +++ b/include/swift/SIL/SILBridgingImpl.h @@ -639,6 +639,13 @@ BridgedSourceLoc BridgedLocation::getSourceLocation() const { swift::SourceLoc sourceLoc = silLoc.getSourceLoc(); return BridgedSourceLoc(sourceLoc.getOpaquePointerValue()); } +bool BridgedLocation::isFilenameAndLocation() const { + return getLoc().getLocation().isFilenameAndLocation(); +} +BridgedLocation::FilenameAndLocation BridgedLocation::getFilenameAndLocation() const { + auto fnal = getLoc().getLocation().getFilenameAndLocation(); + return {BridgedStringRef(fnal->filename), (SwiftInt)fnal->line, (SwiftInt)fnal->column}; +} bool BridgedLocation::hasSameSourceLocation(BridgedLocation rhs) const { return getLoc().hasSameSourceLocation(rhs.getLoc()); } @@ -1163,12 +1170,9 @@ BridgedFunction BridgedInstruction::FunctionRefBaseInst_getReferencedFunction() return {getAs()->getInitiallyReferencedFunction()}; } -BridgedInstruction::OptionalInt BridgedInstruction::IntegerLiteralInst_getValue() const { +BridgedOptionalInt 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}; + return BridgedOptionalInt::getFromAPInt(result); } BridgedStringRef BridgedInstruction::StringLiteralInst_getValue() const { @@ -1655,19 +1659,6 @@ BridgedCanType BridgedInstruction::TypeValueInst_getParamType() const { return getAs()->getParamType(); } -SwiftInt BridgedInstruction::TypeValueInst_getValue() const { - auto tvi = getAs(); - - // Assume we've already checked that the parameter type is an IntegerType. - auto integer = tvi->getParamType()->castTo(); - - if (integer->isNegative()) { - return integer->getValue().getSExtValue(); - } else { - return integer->getValue().getZExtValue(); - } -} - //===----------------------------------------------------------------------===// // VarDeclInst and DebugVariableInst //===----------------------------------------------------------------------===// @@ -2453,6 +2444,10 @@ BridgedInstruction BridgedBuilder::createVector(BridgedValueArray arguments) con return {unbridged().createVector(swift::ArtificialUnreachableLocation(), arguments.getValues(argValues))}; } +BridgedInstruction BridgedBuilder::createVectorBaseAddr(BridgedValue vector) const { + return {unbridged().createVectorBaseAddr(regularLoc(), vector.getSILValue())}; +} + BridgedInstruction BridgedBuilder::createGlobalAddr(BridgedGlobalVar global, OptionalBridgedValue dependencyToken) const { return {unbridged().createGlobalAddr(regularLoc(), global.getGlobal(), dependencyToken.getSILValue())}; diff --git a/include/swift/SIL/SILBuilder.h b/include/swift/SIL/SILBuilder.h index a37ea657ade9e..6c72b5583fd6a 100644 --- a/include/swift/SIL/SILBuilder.h +++ b/include/swift/SIL/SILBuilder.h @@ -22,6 +22,7 @@ #include "swift/SIL/SILInstruction.h" #include "swift/SIL/SILModule.h" #include "swift/SIL/SILUndef.h" +#include "swift/SIL/AbstractionPattern.h" #include "llvm/ADT/PointerUnion.h" #include "llvm/ADT/StringExtras.h" #include @@ -1923,6 +1924,15 @@ class SILBuilder { return createStructElementAddr(Loc, Operand, Field, ResultTy); } + VectorBaseAddrInst * + createVectorBaseAddr(SILLocation loc, SILValue vector) { + auto arrayTy = vector->getType().getAs(); + ASSERT(arrayTy && "operand of vector_extract must be a builtin array type"); + auto elemtTy = getFunction().getLoweredType(Lowering::AbstractionPattern::getOpaque(), arrayTy->getElementType()); + return insert(new (getModule()) VectorBaseAddrInst( + getSILDebugLocation(loc), vector, elemtTy.getAddressType())); + } + RefElementAddrInst *createRefElementAddr(SILLocation Loc, SILValue Operand, VarDecl *Field, SILType ResultTy, bool IsImmutable = false) { diff --git a/include/swift/SIL/SILCloner.h b/include/swift/SIL/SILCloner.h index dc985ed698d11..3be450dd60cc4 100644 --- a/include/swift/SIL/SILCloner.h +++ b/include/swift/SIL/SILCloner.h @@ -2542,6 +2542,16 @@ SILCloner::visitStructElementAddrInst(StructElementAddrInst *Inst) { Inst->getField(), getOpType(Inst->getType()))); } +template +void +SILCloner::visitVectorBaseAddrInst(VectorBaseAddrInst *Inst) { + getBuilder().setCurrentDebugScope(getOpScope(Inst->getDebugScope())); + recordClonedInstruction( + Inst, getBuilder().createVectorBaseAddr( + getOpLocation(Inst->getLoc()), + getOpValue(Inst->getVector()))); +} + template void SILCloner::visitRefElementAddrInst(RefElementAddrInst *Inst) { diff --git a/include/swift/SIL/SILInstruction.h b/include/swift/SIL/SILInstruction.h index 437fbc7596fad..4057ee62a29e0 100644 --- a/include/swift/SIL/SILInstruction.h +++ b/include/swift/SIL/SILInstruction.h @@ -6791,6 +6791,17 @@ class VectorInst final : public InstructionBaseWithTrailingOperands< } }; +class VectorBaseAddrInst + : public UnaryInstructionBase { + friend SILBuilder; + + VectorBaseAddrInst(SILDebugLocation debugLoc, SILValue vector, SILType resultTy) + : UnaryInstructionBase(debugLoc, vector, resultTy) {} +public: + SILValue getVector() const { return getOperand(); } +}; + /// TupleInst - Represents a constructed loadable tuple. class TupleInst final : public InstructionBaseWithTrailingOperands< SILInstructionKind::TupleInst, TupleInst, diff --git a/include/swift/SIL/SILInstructionWorklist.h b/include/swift/SIL/SILInstructionWorklist.h index f25d62f88b319..eda2dd2fb4eb3 100644 --- a/include/swift/SIL/SILInstructionWorklist.h +++ b/include/swift/SIL/SILInstructionWorklist.h @@ -302,9 +302,12 @@ class SILInstructionWorklist : SILInstructionWorklistBase { // method to delete the given instruction. void eraseInstFromFunction(SILInstruction &instruction, SILBasicBlock::iterator &iterator, - bool addOperandsToWorklist = true) { - // Try to salvage debug info first. - swift::salvageDebugInfo(&instruction); + bool addOperandsToWorklist = true, + bool salvageDebugInfo = true) { + if (salvageDebugInfo) { + // Try to salvage debug info first. + swift::salvageDebugInfo(&instruction); + } // Then delete old debug users. for (auto result : instruction.getResults()) { while (!result->use_empty()) { @@ -323,9 +326,11 @@ class SILInstructionWorklist : SILInstructionWorklistBase { } void eraseInstFromFunction(SILInstruction &instruction, - bool addOperandsToWorklist = true) { + bool addOperandsToWorklist = true, + bool salvageDebugInfo = true) { SILBasicBlock::iterator nullIter; - return eraseInstFromFunction(instruction, nullIter, addOperandsToWorklist); + return eraseInstFromFunction(instruction, nullIter, addOperandsToWorklist, + salvageDebugInfo); } void eraseSingleInstFromFunction(SILInstruction &instruction, diff --git a/include/swift/SIL/SILNodes.def b/include/swift/SIL/SILNodes.def index 27cb867792a97..4468b0a6c03e4 100644 --- a/include/swift/SIL/SILNodes.def +++ b/include/swift/SIL/SILNodes.def @@ -587,6 +587,8 @@ ABSTRACT_VALUE_AND_INST(SingleValueInstruction, ValueBase, SILInstruction) SingleValueInstruction, None, DoesNotRelease) SINGLE_VALUE_INST(VectorInst, vector, SingleValueInstruction, None, DoesNotRelease) + SINGLE_VALUE_INST(VectorBaseAddrInst, vector_base_addr, + SingleValueInstruction, None, DoesNotRelease) SINGLE_VALUE_INST(TupleInst, tuple, SingleValueInstruction, None, DoesNotRelease) SINGLE_VALUE_INST(TupleExtractInst, tuple_extract, diff --git a/include/swift/SILOptimizer/OptimizerBridging.h b/include/swift/SILOptimizer/OptimizerBridging.h index a12cfb8d59e2e..5cd1133f79d15 100644 --- a/include/swift/SILOptimizer/OptimizerBridging.h +++ b/include/swift/SILOptimizer/OptimizerBridging.h @@ -234,7 +234,7 @@ struct BridgedPassContext { SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlock splitBlockAfter(BridgedInstruction bridgedInst) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlock createBlockAfter(BridgedBasicBlock bridgedBlock) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlock appendBlock(BridgedFunction bridgedFunction) const; - BRIDGED_INLINE void eraseInstruction(BridgedInstruction inst) const; + BRIDGED_INLINE void eraseInstruction(BridgedInstruction inst, bool salvageDebugInfo) const; BRIDGED_INLINE void eraseBlock(BridgedBasicBlock block) const; static BRIDGED_INLINE void moveInstructionBefore(BridgedInstruction inst, BridgedInstruction beforeInst); bool tryOptimizeApplyOfPartialApply(BridgedInstruction closure) const; diff --git a/include/swift/SILOptimizer/OptimizerBridgingImpl.h b/include/swift/SILOptimizer/OptimizerBridgingImpl.h index 99c7093135c9c..7393f69822cd3 100644 --- a/include/swift/SILOptimizer/OptimizerBridgingImpl.h +++ b/include/swift/SILOptimizer/OptimizerBridgingImpl.h @@ -27,6 +27,7 @@ #include "swift/SILOptimizer/OptimizerBridging.h" #include "swift/SILOptimizer/PassManager/PassManager.h" #include "swift/SILOptimizer/Utils/InstOptUtils.h" +#include "swift/SILOptimizer/Utils/DebugOptUtils.h" SWIFT_BEGIN_NULLABILITY_ANNOTATIONS @@ -253,8 +254,8 @@ BridgedBasicBlock BridgedPassContext::appendBlock(BridgedFunction bridgedFunctio return {bridgedFunction.getFunction()->createBasicBlock()}; } -void BridgedPassContext::eraseInstruction(BridgedInstruction inst) const { - invocation->eraseInstruction(inst.unbridged()); +void BridgedPassContext::eraseInstruction(BridgedInstruction inst, bool salvageDebugInfo) const { + invocation->eraseInstruction(inst.unbridged(), salvageDebugInfo); } void BridgedPassContext::eraseBlock(BridgedBasicBlock block) const { diff --git a/include/swift/SILOptimizer/PassManager/PassManager.h b/include/swift/SILOptimizer/PassManager/PassManager.h index ea6a3983a831d..734a2456f45f9 100644 --- a/include/swift/SILOptimizer/PassManager/PassManager.h +++ b/include/swift/SILOptimizer/PassManager/PassManager.h @@ -138,7 +138,7 @@ class SwiftPassInvocation { void freeOperandSet(OperandSet *set); /// The top-level API to erase an instruction, called from the Swift pass. - void eraseInstruction(SILInstruction *inst); + void eraseInstruction(SILInstruction *inst, bool salvageDebugInfo); /// Called by the pass when changes are made to the SIL. void notifyChanges(SILAnalysis::InvalidationKind invalidationKind); diff --git a/lib/AST/ASTContext.cpp b/lib/AST/ASTContext.cpp index 6c1f7693af702..3a1fc4f977f02 100644 --- a/lib/AST/ASTContext.cpp +++ b/lib/AST/ASTContext.cpp @@ -2200,12 +2200,6 @@ Identifier ASTContext::getRealModuleName(Identifier key, ModuleAliasLookupOption return value.first; } -std::vector ASTContext::getDarwinImplicitFrameworkSearchPaths() -const { - assert(LangOpts.Target.isOSDarwin()); - return SearchPathOpts.getDarwinImplicitFrameworkSearchPaths(); -} - void ASTContext::loadExtensions(NominalTypeDecl *nominal, unsigned previousGeneration) { PrettyStackTraceDecl stackTrace("loading extensions for", nominal); @@ -3885,7 +3879,7 @@ PackElementType::PackElementType(Type packType, unsigned level, packType(packType), level(level) { assert(packType->isParameterPack() || packType->is() || - packType->is()); + packType->isTypeVariableOrMember()); assert(level > 0); } diff --git a/lib/AST/ASTDumper.cpp b/lib/AST/ASTDumper.cpp index 805d444ac8047..1bd7d6d6f9f55 100644 --- a/lib/AST/ASTDumper.cpp +++ b/lib/AST/ASTDumper.cpp @@ -4976,7 +4976,6 @@ class PrintAttribute : public AttributeVisitor, TRIVIAL_ATTR_PRINTER(ImplicitSelfCapture, implicit_self_capture) TRIVIAL_ATTR_PRINTER(Indirect, indirect) TRIVIAL_ATTR_PRINTER(Infix, infix) - TRIVIAL_ATTR_PRINTER(InheritActorContext, inherit_actor_context) TRIVIAL_ATTR_PRINTER(InheritsConvenienceInitializers, inherits_convenience_initializers) TRIVIAL_ATTR_PRINTER(Inlinable, inlinable) @@ -5301,6 +5300,12 @@ class PrintAttribute : public AttributeVisitor, printFlag(Attr->isNonSending(), "nonsending"); printFoot(); } + void visitInheritActorContextAttr(InheritActorContextAttr *Attr, + Label label) { + printCommon(Attr, "inherit_actor_context_attr", label); + printFlag(Attr->isAlways(), "always"); + printFoot(); + } void visitObjCAttr(ObjCAttr *Attr, Label label) { printCommon(Attr, "objc_attr", label); if (Attr->hasName()) diff --git a/lib/AST/ASTMangler.cpp b/lib/AST/ASTMangler.cpp index 740afb108789d..f8286d86f6403 100644 --- a/lib/AST/ASTMangler.cpp +++ b/lib/AST/ASTMangler.cpp @@ -1613,7 +1613,7 @@ void ASTMangler::appendType(Type type, GenericSignature sig, // ExtendedExistentialTypeShapes consider existential metatypes to // be part of the existential, so if we're symbolically referencing // shapes, we need to handle that at this level. - if (EMT->hasParameterizedExistential()) { + if (EMT->getExistentialLayout().needsExtendedShape(AllowInverses)) { auto referent = SymbolicReferent::forExtendedExistentialTypeShape(EMT); if (canSymbolicReference(referent)) { appendSymbolicExtendedExistentialType(referent, EMT, sig, forDecl); @@ -1622,7 +1622,7 @@ void ASTMangler::appendType(Type type, GenericSignature sig, } if (EMT->getInstanceType()->isExistentialType() && - EMT->hasParameterizedExistential()) + EMT->getExistentialLayout().needsExtendedShape(AllowInverses)) appendConstrainedExistential(EMT->getInstanceType(), sig, forDecl); else appendType(EMT->getInstanceType(), sig, forDecl); @@ -1678,8 +1678,7 @@ void ASTMangler::appendType(Type type, GenericSignature sig, return appendType(strippedTy, sig, forDecl); } - if (PCT->hasParameterizedExistential() - || (PCT->hasInverse() && AllowInverses)) + if (PCT->getExistentialLayout().needsExtendedShape(AllowInverses)) return appendConstrainedExistential(PCT, sig, forDecl); // We mangle ProtocolType and ProtocolCompositionType using the @@ -1693,7 +1692,8 @@ void ASTMangler::appendType(Type type, GenericSignature sig, case TypeKind::Existential: { auto *ET = cast(tybase); - if (ET->hasParameterizedExistential()) { + + if (ET->getExistentialLayout().needsExtendedShape(AllowInverses)) { auto referent = SymbolicReferent::forExtendedExistentialTypeShape(ET); if (canSymbolicReference(referent)) { appendSymbolicExtendedExistentialType(referent, ET, sig, forDecl); @@ -1703,6 +1703,7 @@ void ASTMangler::appendType(Type type, GenericSignature sig, return appendConstrainedExistential(ET->getConstraintType(), sig, forDecl); } + return appendType(ET->getConstraintType(), sig, forDecl); } diff --git a/lib/AST/Attr.cpp b/lib/AST/Attr.cpp index 37169d63a30b5..003b7ccb446da 100644 --- a/lib/AST/Attr.cpp +++ b/lib/AST/Attr.cpp @@ -1531,6 +1531,18 @@ bool DeclAttribute::printImpl(ASTPrinter &Printer, const PrintOptions &Options, break; } + case DeclAttrKind::InheritActorContext: { + Printer.printAttrName("@_inheritActorContext"); + switch (cast(this)->getModifier()) { + case InheritActorContextModifier::None: + break; + case InheritActorContextModifier::Always: + Printer << "(always)"; + break; + } + break; + } + case DeclAttrKind::MacroRole: { auto Attr = cast(this); @@ -1915,6 +1927,13 @@ StringRef DeclAttribute::getAttrName() const { case NonIsolatedModifier::NonSending: return "nonisolated(nonsending)"; } + case DeclAttrKind::InheritActorContext: + switch (cast(this)->getModifier()) { + case InheritActorContextModifier::None: + return "_inheritActorContext"; + case InheritActorContextModifier::Always: + return "_inheritActorContext(always)"; + } case DeclAttrKind::MacroRole: switch (cast(this)->getMacroSyntax()) { case MacroSyntax::Freestanding: diff --git a/lib/AST/Bridging/DeclAttributeBridging.cpp b/lib/AST/Bridging/DeclAttributeBridging.cpp index 6fffda31e53ee..6c67b7174bdc0 100644 --- a/lib/AST/Bridging/DeclAttributeBridging.cpp +++ b/lib/AST/Bridging/DeclAttributeBridging.cpp @@ -649,6 +649,25 @@ BridgedNonisolatedAttr_createParsed(BridgedASTContext cContext, /*implicit=*/false); } +static InheritActorContextModifier +unbridged(BridgedInheritActorContextModifier modifier) { + switch (modifier) { + case BridgedInheritActorContextModifierNone: + return InheritActorContextModifier::None; + case BridgedInheritActorContextModifierAlways: + return InheritActorContextModifier::Always; + } + llvm_unreachable("unhandled enum value"); +} + +BridgedInheritActorContextAttr BridgedInheritActorContextAttr_createParsed( + BridgedASTContext cContext, BridgedSourceLoc cAtLoc, + BridgedSourceRange cRange, BridgedInheritActorContextModifier modifier) { + return new (cContext.unbridged()) InheritActorContextAttr( + cAtLoc.unbridged(), cRange.unbridged(), unbridged(modifier), + /*implicit=*/false); +} + BridgedObjCAttr BridgedObjCAttr_createParsedUnnamed(BridgedASTContext cContext, BridgedSourceLoc cAtLoc, diff --git a/lib/AST/Bridging/DeclBridging.cpp b/lib/AST/Bridging/DeclBridging.cpp index bbf6b89917a0e..f9d5691c0d4c3 100644 --- a/lib/AST/Bridging/DeclBridging.cpp +++ b/lib/AST/Bridging/DeclBridging.cpp @@ -70,13 +70,23 @@ BridgedDeclNameLoc BridgedDeclNameLoc_createParsed( BridgedASTContext cContext, BridgedSourceLoc cBaseNameLoc, BridgedSourceLoc cLParenLoc, BridgedArrayRef cLabelLocs, BridgedSourceLoc cRParenLoc) { + return BridgedDeclNameLoc_createParsed( + cContext, BridgedSourceLoc(), cBaseNameLoc, cLParenLoc, cLabelLocs, + cRParenLoc); +} + +BridgedDeclNameLoc BridgedDeclNameLoc_createParsed( + BridgedASTContext cContext, BridgedSourceLoc cModuleSelectorLoc, + BridgedSourceLoc cBaseNameLoc, BridgedSourceLoc cLParenLoc, + BridgedArrayRef cLabelLocs, BridgedSourceLoc cRParenLoc) { ASTContext &context = cContext.unbridged(); SmallVector labelLocs; for (auto &cLabelLoc : cLabelLocs.unbridged()) labelLocs.push_back(cLabelLoc.unbridged()); - return DeclNameLoc(context, cBaseNameLoc.unbridged(), cLParenLoc.unbridged(), + return DeclNameLoc(context, cModuleSelectorLoc.unbridged(), + cBaseNameLoc.unbridged(), cLParenLoc.unbridged(), labelLocs, cRParenLoc.unbridged()); } @@ -85,6 +95,14 @@ BridgedDeclNameLoc_createParsed(BridgedSourceLoc cBaseNameLoc) { return DeclNameLoc(cBaseNameLoc.unbridged()); } +BridgedDeclNameLoc +BridgedDeclNameLoc_createParsed( + BridgedASTContext cContext, BridgedSourceLoc cModuleSelectorLoc, + BridgedSourceLoc cBaseNameLoc) { + return DeclNameLoc(cContext.unbridged(), cModuleSelectorLoc.unbridged(), + cBaseNameLoc.unbridged()); +} + //===----------------------------------------------------------------------===// // MARK: Decls //===----------------------------------------------------------------------===// diff --git a/lib/AST/Bridging/DiagnosticsBridging.cpp b/lib/AST/Bridging/DiagnosticsBridging.cpp index 89baf48a3f86c..7f218be10b57e 100644 --- a/lib/AST/Bridging/DiagnosticsBridging.cpp +++ b/lib/AST/Bridging/DiagnosticsBridging.cpp @@ -15,6 +15,7 @@ #include "swift/AST/DiagnosticEngine.h" #include "swift/AST/DiagnosticsCommon.h" #include "swift/Basic/Assertions.h" +#include "swift/Basic/SourceManager.h" using namespace swift; @@ -78,6 +79,14 @@ void BridgedDiagnosticEngine_diagnose( } } +BridgedSourceLoc BridgedDiagnostic_getLocationFromExternalSource( + BridgedDiagnosticEngine bridgedEngine, BridgedStringRef path, + SwiftInt line, SwiftInt column) { + auto *d = bridgedEngine.unbridged(); + auto loc = d->SourceMgr.getLocFromExternalSource(path.unbridged(), line, column); + return BridgedSourceLoc(loc.getOpaquePointerValue()); +} + bool BridgedDiagnosticEngine_hadAnyError( BridgedDiagnosticEngine bridgedEngine) { return bridgedEngine.unbridged()->hadAnyError(); diff --git a/lib/AST/CMakeLists.txt b/lib/AST/CMakeLists.txt index 5024c8cf4cfb5..88297820b9e64 100644 --- a/lib/AST/CMakeLists.txt +++ b/lib/AST/CMakeLists.txt @@ -95,6 +95,7 @@ add_swift_host_library(swiftAST STATIC RawComment.cpp Requirement.cpp RequirementEnvironment.cpp + RequirementMachine/ApplyInverses.cpp RequirementMachine/ConcreteContraction.cpp RequirementMachine/ConcreteTypeWitness.cpp RequirementMachine/Diagnostics.cpp diff --git a/lib/AST/Decl.cpp b/lib/AST/Decl.cpp index 866fa083f43a2..eeeb02ee01f36 100644 --- a/lib/AST/Decl.cpp +++ b/lib/AST/Decl.cpp @@ -2528,6 +2528,19 @@ StringRef PatternBindingEntry::getInitStringRepresentation( return extractInlinableText(ctx, init, scratch); } +SourceLoc PatternBindingDecl::getStartLoc() const { + if (StaticLoc.isValid()) + return StaticLoc; + + if (VarLoc.isValid()) + return VarLoc; + + if (getPatternList().empty()) + return SourceLoc(); + + return getPatternList().front().getStartLoc(); +} + SourceRange PatternBindingDecl::getSourceRange() const { SourceLoc startLoc = getStartLoc(); SourceLoc endLoc = getPatternList().empty() @@ -8919,6 +8932,21 @@ ParamDecl *ParamDecl::clone(const ASTContext &Ctx, ParamDecl *PD) { return Clone; } +ParamDecl *ParamDecl::cloneAccessor(const ASTContext &Ctx, + ParamDecl const *subscriptParam, + DeclContext *Parent) { + auto *param = new (Ctx) ParamDecl( + subscriptParam->getSpecifierLoc(), subscriptParam->getArgumentNameLoc(), + subscriptParam->getArgumentName(), subscriptParam->getNameLoc(), + subscriptParam->getName(), /*declContext*/ Parent); + param->setOptions(subscriptParam->getOptions()); + + // The cloned parameter is implicit. + param->setImplicit(); + + return param; +} + ParamDecl * ParamDecl::createImplicit(ASTContext &Context, SourceLoc specifierLoc, SourceLoc argumentNameLoc, Identifier argumentName, @@ -10308,30 +10336,20 @@ SourceRange AbstractFunctionDecl::getSignatureSourceRange() const { if (isImplicit()) return SourceRange(); - SourceLoc endLoc; - - // name(parameter list...) async throws(E) + SourceRange thrownTypeRange; if (auto *typeRepr = getThrownTypeRepr()) - endLoc = typeRepr->getSourceRange().End; - if (endLoc.isInvalid()) - endLoc = getThrowsLoc(); - if (endLoc.isInvalid()) - endLoc = getAsyncLoc(); + thrownTypeRange = typeRepr->getSourceRange(); - if (endLoc.isInvalid()) - return getParameterListSourceRange(); - return SourceRange(getNameLoc(), endLoc); + // name(parameter list...) async throws(E) + return SourceRange::combine(getParameterListSourceRange(), getAsyncLoc(), + getThrowsLoc(), thrownTypeRange); } SourceRange AbstractFunctionDecl::getParameterListSourceRange() const { if (isImplicit()) return SourceRange(); - auto endLoc = getParameters()->getSourceRange().End; - if (endLoc.isInvalid()) - return getNameLoc(); - - return SourceRange(getNameLoc(), endLoc); + return SourceRange::combine(getNameLoc(), getParameters()->getSourceRange()); } std::optional AbstractFunctionDecl::getBodyFingerprint() const { @@ -11138,23 +11156,7 @@ AccessorDecl *AccessorDecl::createParsed( paramsEnd = indices->getEndLoc(); } for (auto *subscriptParam : *indices) { - // Clone the parameter. - auto *param = new (ctx) ParamDecl( - subscriptParam->getSpecifierLoc(), - subscriptParam->getArgumentNameLoc(), - subscriptParam->getArgumentName(), subscriptParam->getNameLoc(), - subscriptParam->getName(), /*declContext*/ accessor); - param->setAutoClosure(subscriptParam->isAutoClosure()); - - // The cloned parameter is implicit. - param->setImplicit(); - - if (subscriptParam->isSending()) - param->setSending(); - - if (subscriptParam->isCallerIsolated()) - param->setCallerIsolated(); - + auto param = ParamDecl::cloneAccessor(ctx, subscriptParam, accessor); newParams.push_back(param); } @@ -11454,33 +11456,62 @@ DestructorDecl *DestructorDecl::getSuperDeinit() const { return nullptr; } -SourceRange FuncDecl::getSourceRange() const { - SourceLoc startLoc = getStartLoc(); +SourceLoc FuncDecl::getStartLoc() const { + if (StaticLoc) + return StaticLoc; - if (startLoc.isInvalid()) - return SourceRange(); + if (FuncLoc) + return FuncLoc; - if (getBodyKind() == BodyKind::Unparsed) - return { startLoc, BodyRange.End }; + auto nameLoc = getNameLoc(); + if (nameLoc) + return nameLoc; - SourceLoc endLoc = getOriginalBodySourceRange().End; - if (endLoc.isInvalid()) { - if (isa(this)) - return startLoc; + auto sigStart = getSignatureSourceRange().Start; + if (sigStart) + return sigStart; - if (getBodyKind() == BodyKind::Synthesize) - return SourceRange(); + auto resultTyStart = getResultTypeSourceRange().Start; + if (resultTyStart) + return resultTyStart; - endLoc = getGenericTrailingWhereClauseSourceRange().End; - } - if (endLoc.isInvalid()) - endLoc = getResultTypeSourceRange().End; - if (endLoc.isInvalid()) - endLoc = getSignatureSourceRange().End; - if (endLoc.isInvalid()) - endLoc = startLoc; + auto genericWhereStart = getGenericTrailingWhereClauseSourceRange().Start; + if (genericWhereStart) + return genericWhereStart; - return { startLoc, endLoc }; + auto bodyStart = getOriginalBodySourceRange().Start; + if (bodyStart) + return bodyStart; + + return SourceLoc(); +} + +SourceLoc FuncDecl::getEndLoc() const { + auto bodyEnd = getOriginalBodySourceRange().End; + if (bodyEnd) + return bodyEnd; + + auto genericWhereEnd = getGenericTrailingWhereClauseSourceRange().End; + if (genericWhereEnd) + return genericWhereEnd; + + auto resultTyEnd = getResultTypeSourceRange().End; + if (resultTyEnd) + return resultTyEnd; + + auto sigEnd = getSignatureSourceRange().End; + if (sigEnd) + return sigEnd; + + return getStartLoc(); +} + +SourceRange FuncDecl::getSourceRange() const { + SourceLoc startLoc = getStartLoc(); + if (startLoc.isInvalid()) + return SourceRange(); + + return { startLoc, getEndLoc() }; } EnumElementDecl::EnumElementDecl(SourceLoc IdentifierLoc, DeclName Name, diff --git a/lib/AST/DiagnosticEngine.cpp b/lib/AST/DiagnosticEngine.cpp index 7ac3e7166d441..49e38b7a16ccf 100644 --- a/lib/AST/DiagnosticEngine.cpp +++ b/lib/AST/DiagnosticEngine.cpp @@ -393,15 +393,17 @@ InFlightDiagnostic::fixItAddAttribute(const DeclAttribute *Attr, const ClosureExpr *E) { ASSERT(!E->isImplicit()); - SourceLoc insertionLoc; - - if (auto *paramList = E->getParameters()) { - // HACK: Don't set insertion loc to param list start loc if it's equal to - // closure start loc (meaning it's implicit). - // FIXME: Don't set the start loc of an implicit param list, or put an - // isImplicit bit on ParameterList. - if (paramList->getStartLoc() != E->getStartLoc()) { - insertionLoc = paramList->getStartLoc(); + SourceLoc insertionLoc = E->getBracketRange().Start; + + if (insertionLoc.isInvalid()) { + if (auto *paramList = E->getParameters()) { + // HACK: Don't set insertion loc to param list start loc if it's equal to + // closure start loc (meaning it's implicit). + // FIXME: Don't set the start loc of an implicit param list, or put an + // isImplicit bit on ParameterList. + if (paramList->getStartLoc() != E->getStartLoc()) { + insertionLoc = paramList->getStartLoc(); + } } } diff --git a/lib/AST/FeatureSet.cpp b/lib/AST/FeatureSet.cpp index ec5f8e7d7f947..9a9eee441b72e 100644 --- a/lib/AST/FeatureSet.cpp +++ b/lib/AST/FeatureSet.cpp @@ -126,6 +126,9 @@ UNINTERESTING_FEATURE(MacrosOnImports) UNINTERESTING_FEATURE(NonisolatedNonsendingByDefault) UNINTERESTING_FEATURE(KeyPathWithMethodMembers) +// TODO: Return true for inlinable function bodies with module selectors in them +UNINTERESTING_FEATURE(ModuleSelector) + static bool usesFeatureNonescapableTypes(Decl *decl) { auto containsNonEscapable = [](SmallVectorImpl &inverseReqs) { @@ -621,6 +624,21 @@ static bool usesFeatureExtensibleAttribute(Decl *decl) { return decl->getAttrs().hasAttribute(); } +static bool usesFeatureAlwaysInheritActorContext(Decl *decl) { + auto *VD = dyn_cast(decl); + if (!VD) + return false; + + if (auto *PL = VD->getParameterList()) { + return llvm::any_of(*PL, [&](const ParamDecl *P) { + auto *attr = P->getAttrs().getAttribute(); + return attr && attr->isAlways(); + }); + } + + return false; +} + // ---------------------------------------------------------------------------- // MARK: - FeatureSet // ---------------------------------------------------------------------------- diff --git a/lib/AST/Identifier.cpp b/lib/AST/Identifier.cpp index 90bf6e612f69c..0e32186ebdbee 100644 --- a/lib/AST/Identifier.cpp +++ b/lib/AST/Identifier.cpp @@ -55,6 +55,8 @@ void swift::simple_display(llvm::raw_ostream &out, DeclName name) { } raw_ostream &llvm::operator<<(raw_ostream &OS, DeclNameRef I) { + if (I.hasModuleSelector()) + OS << I.getModuleSelector() << "::"; OS << I.getFullName(); return OS; } @@ -208,17 +210,27 @@ void DeclNameRef::dump() const { } StringRef DeclNameRef::getString(llvm::SmallVectorImpl &scratch, - bool skipEmptyArgumentNames) const { - return FullName.getString(scratch, skipEmptyArgumentNames); + bool skipEmptyArgumentNames) const { + { + llvm::raw_svector_ostream out(scratch); + print(out, skipEmptyArgumentNames); + } + + return StringRef(scratch.data(), scratch.size()); } -llvm::raw_ostream &DeclNameRef::print(llvm::raw_ostream &os, - bool skipEmptyArgumentNames) const { - return FullName.print(os, skipEmptyArgumentNames); +llvm::raw_ostream & +DeclNameRef::print(llvm::raw_ostream &os, + bool skipEmptyArgumentNames) const { + if (hasModuleSelector()) + os << getModuleSelector() << "::"; + return getFullName().print(os, skipEmptyArgumentNames); } llvm::raw_ostream &DeclNameRef::printPretty(llvm::raw_ostream &os) const { - return FullName.printPretty(os); + if (hasModuleSelector()) + os << getModuleSelector() << "::"; + return getFullName().printPretty(os); } ObjCSelector::ObjCSelector(ASTContext &ctx, unsigned numArgs, diff --git a/lib/AST/ModuleDependencies.cpp b/lib/AST/ModuleDependencies.cpp index 4fa8bb918322c..149a85e514e4e 100644 --- a/lib/AST/ModuleDependencies.cpp +++ b/lib/AST/ModuleDependencies.cpp @@ -25,7 +25,6 @@ #include "swift/Strings.h" #include "clang/CAS/IncludeTree.h" #include "llvm/CAS/CASProvidingFileSystem.h" -#include "llvm/CAS/CachingOnDiskFileSystem.h" #include "llvm/Config/config.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" @@ -602,13 +601,16 @@ swift::dependencies::registerBackDeployLibraries( } SwiftDependencyTracker::SwiftDependencyTracker( - llvm::cas::CachingOnDiskFileSystem &FS, llvm::PrefixMapper *Mapper, + std::shared_ptr CAS, llvm::PrefixMapper *Mapper, const CompilerInvocation &CI) - : FS(FS.createProxyFS()), Mapper(Mapper) { + : CAS(CAS), Mapper(Mapper) { auto &SearchPathOpts = CI.getSearchPathOptions(); + FS = llvm::cas::createCASProvidingFileSystem( + CAS, llvm::vfs::createPhysicalFileSystem()); + auto addCommonFile = [&](StringRef path) { - auto file = FS.openFileForRead(path); + auto file = FS->openFileForRead(path); if (!file) return; auto status = (*file)->status(); @@ -679,7 +681,7 @@ SwiftDependencyTracker::createTreeFromDependencies() { llvm::SmallVector Files; for (auto &file : TrackedFiles) { auto includeTreeFile = clang::cas::IncludeTree::File::create( - FS->getCAS(), file.first, file.second.FileRef); + *CAS, file.first, file.second.FileRef); if (!includeTreeFile) { return llvm::createStringError("CASFS createTree failed for " + file.first + ": " + @@ -691,7 +693,7 @@ SwiftDependencyTracker::createTreeFromDependencies() { } auto includeTreeList = - clang::cas::IncludeTree::FileList::create(FS->getCAS(), Files, {}); + clang::cas::IncludeTree::FileList::create(*CAS, Files, {}); if (!includeTreeList) return llvm::createStringError("casfs include-tree filelist error: " + toString(includeTreeList.takeError())); @@ -719,14 +721,8 @@ bool SwiftDependencyScanningService::setupCachingDependencyScanningService( CAS = Instance.getSharedCASInstance(); ActionCache = Instance.getSharedCacheInstance(); - auto CachingFS = - llvm::cas::createCachingOnDiskFileSystem(Instance.getObjectStore()); - if (!CachingFS) { - Instance.getDiags().diagnose(SourceLoc(), diag::error_cas_fs_creation, - toString(CachingFS.takeError())); - return true; - } - CacheFS = std::move(*CachingFS); + CacheFS = llvm::cas::createCASProvidingFileSystem( + CAS, llvm::vfs::createPhysicalFileSystem()); // Setup prefix mapping. auto &ScannerPrefixMapper = @@ -744,19 +740,14 @@ bool SwiftDependencyScanningService::setupCachingDependencyScanningService( Mapper->sort(); } - UseClangIncludeTree = - Instance.getInvocation().getClangImporterOptions().UseClangIncludeTree; const clang::tooling::dependencies::ScanningOutputFormat ClangScanningFormat = - UseClangIncludeTree - ? clang::tooling::dependencies::ScanningOutputFormat::FullIncludeTree - : clang::tooling::dependencies::ScanningOutputFormat::FullTree; + clang::tooling::dependencies::ScanningOutputFormat::FullIncludeTree; ClangScanningService.emplace( clang::tooling::dependencies::ScanningMode::DependencyDirectivesScan, - ClangScanningFormat, - Instance.getInvocation().getCASOptions().CASOpts, + ClangScanningFormat, Instance.getInvocation().getCASOptions().CASOpts, Instance.getSharedCASInstance(), Instance.getSharedCacheInstance(), - UseClangIncludeTree ? nullptr : CacheFS, + /*CachingOnDiskFileSystem=*/nullptr, // The current working directory optimization (off by default) // should not impact CAS. We set the optization to all to be // consistent with the non-CAS case. diff --git a/lib/AST/ParameterPack.cpp b/lib/AST/ParameterPack.cpp index 0384104c5d35d..cd1f00f9e1e93 100644 --- a/lib/AST/ParameterPack.cpp +++ b/lib/AST/ParameterPack.cpp @@ -307,8 +307,6 @@ static CanPackType getReducedShapeOfPack(const ASTContext &ctx, } // Use () as a placeholder for scalar shape. - assert(!elt->template is() && - "Pack archetype outside of a pack expansion"); elts.push_back(ctx.TheEmptyTupleType); } diff --git a/lib/AST/PluginLoader.cpp b/lib/AST/PluginLoader.cpp index 271c484fc99b8..3fb2f6a5ec04d 100644 --- a/lib/AST/PluginLoader.cpp +++ b/lib/AST/PluginLoader.cpp @@ -64,9 +64,9 @@ static StringRef pluginModuleNameStringFromPath(StringRef path) { static llvm::IntrusiveRefCntPtr getPluginLoadingFS(ASTContext &Ctx) { - // If there is a clang include tree FS, using real file system to load plugin + // If there is an immutable file system, using real file system to load plugin // as the FS in SourceMgr doesn't support directory iterator. - if (Ctx.ClangImporterOpts.HasClangIncludeTreeRoot) + if (Ctx.CASOpts.HasImmutableFileSystem) return llvm::vfs::getRealFileSystem(); return Ctx.SourceMgr.getFileSystem(); } diff --git a/lib/AST/PluginRegistry.cpp b/lib/AST/PluginRegistry.cpp index 6dc98e0349727..c838a505be792 100644 --- a/lib/AST/PluginRegistry.cpp +++ b/lib/AST/PluginRegistry.cpp @@ -213,6 +213,7 @@ LoadedExecutablePlugin::PluginProcess::~PluginProcess() { #else close(input); close(output); + kill(process.Pid, SIGTERM); #endif // Set `SecondsToWait` non-zero so it waits for the timeout and kill it after diff --git a/lib/AST/ProtocolConformance.cpp b/lib/AST/ProtocolConformance.cpp index ce6afe4faea30..da9f1adc7d0ac 100644 --- a/lib/AST/ProtocolConformance.cpp +++ b/lib/AST/ProtocolConformance.cpp @@ -739,6 +739,13 @@ NormalProtocolConformance::getWitnessUncached(ValueDecl *requirement) const { return entry->second; } +ProtocolConformanceRef +SelfProtocolConformance::getAssociatedConformance(Type assocType, + ProtocolDecl *protocol) const { + ASSERT(assocType->isEqual(protocol->getSelfInterfaceType())); + return lookupConformance(getType(), protocol); +} + Witness SelfProtocolConformance::getWitness(ValueDecl *requirement) const { return Witness(requirement, SubstitutionMap(), nullptr, SubstitutionMap(), GenericSignature(), std::nullopt); diff --git a/lib/AST/RequirementMachine/ApplyInverses.cpp b/lib/AST/RequirementMachine/ApplyInverses.cpp new file mode 100644 index 0000000000000..a37726b7c4a48 --- /dev/null +++ b/lib/AST/RequirementMachine/ApplyInverses.cpp @@ -0,0 +1,268 @@ +//===--- ApplyInverses.cpp - Resolve `~Protocol` anti-constraints ---------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2021 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 +// +//===----------------------------------------------------------------------===// +// +// The `applyInverses` function takes the syntactic representation of a generic +// signature and applies implicit default constraints on generic parameters for +// core type capabilities like `Copyable` and `Escapable`. In doing so, it +// looks for explicit constraint suppression "requirements" like `T: ~Copyable` +// or same-type constraints that would contradict the implicit requirements and +// filters out unwanted default requirements. +// +//===----------------------------------------------------------------------===// + +#include "RequirementLowering.h" +#include "swift/AST/ASTContext.h" +#include "swift/AST/ConformanceLookup.h" +#include "swift/AST/Decl.h" +#include "swift/AST/DiagnosticsSema.h" +#include "swift/AST/Requirement.h" +#include "swift/AST/RequirementSignature.h" +#include "swift/AST/TypeCheckRequests.h" +#include "swift/AST/TypeMatcher.h" +#include "swift/AST/TypeRepr.h" +#include "swift/Basic/Assertions.h" +#include "swift/Basic/Defer.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/ADT/SetVector.h" +#include "Diagnostics.h" +#include "RewriteContext.h" +#include "NameLookup.h" + +using namespace swift; +using namespace rewriting; + +void swift::rewriting::applyInverses( + ASTContext &ctx, + ArrayRef gps, + ArrayRef inverseList, + ArrayRef explicitRequirements, + SmallVectorImpl &result, + SmallVectorImpl &errors) { + + // Are there even any inverses or same-type requirements to validate? + if (inverseList.empty() && explicitRequirements.empty()) { + return; + } + + const bool allowInverseOnAssocType = + ctx.LangOpts.hasFeature(Feature::SuppressedAssociatedTypes); + + llvm::DenseMap representativeGPs; + + // Start with an identity mapping. + for (auto gp : gps) { + auto canGP = gp->getCanonicalType(); + representativeGPs.insert({canGP, canGP}); + } + bool hadSameTypeConstraintInScope = false; + + // Return the in-scope generic parameter that represents the equivalence class + // for `gp`, or return null if the parameter is constrained out of scope. + auto representativeGPFor = [&](CanType gp) -> CanType { + while (true) { + auto found = representativeGPs.find(gp); + if (found == representativeGPs.end()) { + return CanType(); + } + if (found->second == CanType()) { + return CanType(); + } + + if (found->second == gp) { + return gp; + } + + gp = found->second; + } + }; + + // Look for same-type constraints that equate multiple generic parameters + // within the scope so we can treat the equivalence class as a unit. + for (auto &explicitReqt : explicitRequirements) { + if (explicitReqt.req.getKind() != RequirementKind::SameType) { + continue; + } + + // If one end of the same-type requirement is in scope, and the other is + // a concrete type or out-of-scope generic parameter, then the other + // parameter is also effectively out of scope. + auto firstTy = explicitReqt.req.getFirstType()->getCanonicalType(); + auto secondTy = explicitReqt.req.getSecondType()->getCanonicalType(); + if (!representativeGPs.count(firstTy) + && !representativeGPs.count(secondTy)) { + // Same type constraint doesn't involve any in-scope generic parameters. + continue; + } + + CanType typeInScope; + CanType typeOutOfScope; + + if (representativeGPs.count(firstTy) + && !representativeGPs.count(secondTy)){ + // First type is constrained out of scope. + typeInScope = firstTy; + typeOutOfScope = secondTy; + } else if (!representativeGPs.count(firstTy) + && representativeGPs.count(secondTy)) { + // Second type is constrained out of scope. + typeInScope = secondTy; + typeOutOfScope = firstTy; + } else { + // Otherwise, both ends of the same-type constraint are in scope. + // Fold the lexicographically-greater parameter with the lesser. + auto firstGP = cast(firstTy); + auto secondGP = cast(secondTy); + + if (firstGP == secondGP) { + // `T == T` has no effect. + continue; + } + + if (firstGP->getDepth() > secondGP->getDepth() + || (firstGP->getDepth() == secondGP->getDepth() + && firstGP->getIndex() > secondGP->getIndex())) { + std::swap(firstGP, secondGP); + } + + hadSameTypeConstraintInScope = true; + representativeGPs.insert_or_assign(secondGP, representativeGPFor(firstGP)); + continue; + } + + // If the out-of-scope type is another type parameter or associated type, + // then ignore this same-type constraint and allow defaulting to continue. + // + // It would probably have been more principled to suppress any defaulting + // in this case, but this behavior shipped in Swift 6.0 and 6.1, so we + // need to maintain source compatibility. + if (typeOutOfScope->isTypeParameter()) { + continue; + } + + // If the out-of-scope type contains errors, then similarly, ignore the + // same type constraint. Any additional diagnostics arising from the type + // parameter being left ~Copyable or ~Escapable might be misleading if the + // corrected code is attempting to refer to a Copyable or Escapable type. + if (typeOutOfScope->hasError()) { + continue; + } + + representativeGPs.insert_or_assign(representativeGPFor(typeInScope), + CanType()); + hadSameTypeConstraintInScope = true; + } + + // Summarize the inverses and diagnose ones that are incorrect. + llvm::DenseMap inverses; + for (auto inverse : inverseList) { + auto canSubject = inverse.subject->getCanonicalType(); + + // Inverses on associated types are experimental. + if (!allowInverseOnAssocType && canSubject->is()) { + // Special exception: allow if we're building the stdlib. + if (!ctx.MainModule->isStdlibModule()) { + errors.push_back(RequirementError::forInvalidInverseSubject(inverse)); + continue; + } + } + + // Noncopyable checking support for parameter packs is not implemented yet. + if (canSubject->isParameterPack()) { + errors.push_back(RequirementError::forInvalidInverseSubject(inverse)); + continue; + } + + // Value generics never have inverse requirements (or the positive thereof). + if (canSubject->isValueParameter()) { + continue; + } + + // If the inverse is on a subject that wasn't permitted by our caller, then + // remove and diagnose as an error. This can happen when an inner context + // has a constraint on some outer generic parameter, e.g., + // + // protocol P { + // func f() where Self: ~Copyable + // } + // + if (representativeGPs.find(canSubject) == representativeGPs.end()) { + errors.push_back( + RequirementError::forInvalidInverseOuterSubject(inverse)); + continue; + } + + auto representativeSubject = representativeGPFor(canSubject); + + // If the subject is in scope, but same-type constrained to a type out of + // scope, then allow inverses to be stated even though they are redundant. + // This is because older versions of Swift not only accepted but required + // `extension Foo where T == NonCopyableType, T: ~Copyable {}` to be + // written, so we need to continue to accept that formulation for source + // compatibility. + if (!representativeSubject) { + continue; + } + + auto state = inverses.getOrInsertDefault(representativeSubject); + + // Check if this inverse has already been seen. + auto inverseKind = inverse.getKind(); + if (state.contains(inverseKind)) + continue; + + state.insert(inverseKind); + inverses[representativeSubject] = state; + } + + // Fast-path: if there are no valid inverses or same-type constraints, then + // there are no requirements to be removed. + if (inverses.empty() && !hadSameTypeConstraintInScope) { + return; + } + + // Scan the structural requirements and cancel out any inferred requirements + // based on the inverses we saw. + result.erase(llvm::remove_if(result, [&](StructuralRequirement structReq) { + auto req = structReq.req; + + if (req.getKind() != RequirementKind::Conformance) + return false; + + // Only consider requirements involving an invertible protocol. + auto proto = req.getProtocolDecl()->getInvertibleProtocolKind(); + if (!proto) { + return false; + } + + // See if this subject is in-scope. + auto subject = req.getFirstType()->getCanonicalType(); + auto representative = representativeGPs.find(subject); + if (representative == representativeGPs.end()) { + return false; + } + + // If this type is same-type constrained into another equivalence class, + // then it doesn't need its own defaulted requirements. + if (representative->second != subject) { + return true; + } + + // We now have found the inferred constraint 'Subject : Proto'. + // So, remove it if we have recorded a 'Subject : ~Proto'. + auto foundInverses = inverses.find(subject); + if (foundInverses == inverses.end()) { + return false; + } + auto recordedInverses = foundInverses->getSecond(); + return recordedInverses.contains(*proto); + }), result.end()); +} diff --git a/lib/AST/RequirementMachine/RequirementLowering.cpp b/lib/AST/RequirementMachine/RequirementLowering.cpp index 46319d3c338f3..cb3cfcdb25583 100644 --- a/lib/AST/RequirementMachine/RequirementLowering.cpp +++ b/lib/AST/RequirementMachine/RequirementLowering.cpp @@ -159,6 +159,7 @@ #include "swift/AST/TypeMatcher.h" #include "swift/AST/TypeRepr.h" #include "swift/Basic/Assertions.h" +#include "swift/Basic/Defer.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/SetVector.h" #include "Diagnostics.h" @@ -511,11 +512,12 @@ void swift::rewriting::desugarRequirements( // Requirement realization and inference. // -static void realizeTypeRequirement(DeclContext *dc, - Type subjectType, Type constraintType, - SourceLoc loc, - SmallVectorImpl &result, - SmallVectorImpl &errors) { +void swift::rewriting::realizeTypeRequirement(DeclContext *dc, + Type subjectType, + Type constraintType, + SourceLoc loc, + SmallVectorImpl &result, + SmallVectorImpl &errors) { // The GenericSignatureBuilder allowed the right hand side of a // conformance or superclass requirement to reference a protocol // typealias whose underlying type was a protocol or class. @@ -798,106 +800,6 @@ void swift::rewriting::realizeRequirement( } } -void swift::rewriting::applyInverses( - ASTContext &ctx, - ArrayRef gps, - ArrayRef inverseList, - SmallVectorImpl &result, - SmallVectorImpl &errors) { - - // No inverses to even validate. - if (inverseList.empty()) - return; - - const bool allowInverseOnAssocType = - ctx.LangOpts.hasFeature(Feature::SuppressedAssociatedTypes); - - // Summarize the inverses and diagnose ones that are incorrect. - llvm::DenseMap inverses; - for (auto inverse : inverseList) { - auto canSubject = inverse.subject->getCanonicalType(); - - // Inverses on associated types are experimental. - if (!allowInverseOnAssocType && canSubject->is()) { - // Special exception: allow if we're building the stdlib. - if (!ctx.MainModule->isStdlibModule()) { - errors.push_back(RequirementError::forInvalidInverseSubject(inverse)); - continue; - } - } - - // Noncopyable checking support for parameter packs is not implemented yet. - if (canSubject->isParameterPack()) { - errors.push_back(RequirementError::forInvalidInverseSubject(inverse)); - continue; - } - - // Value generics never have inverse requirements (or the positive thereof). - if (canSubject->isValueParameter()) { - continue; - } - - // WARNING: possible quadratic behavior, but should be OK in practice. - auto notInScope = llvm::none_of(gps, [=](Type t) { - return t->getCanonicalType() == canSubject; - }); - - // If the inverse is on a subject that wasn't permitted by our caller, then - // remove and diagnose as an error. This can happen when an inner context - // has a constraint on some outer generic parameter, e.g., - // - // protocol P { - // func f() where Self: ~Copyable - // } - // - if (notInScope) { - errors.push_back( - RequirementError::forInvalidInverseOuterSubject(inverse)); - continue; - } - - auto state = inverses.getOrInsertDefault(canSubject); - - // Check if this inverse has already been seen. - auto inverseKind = inverse.getKind(); - if (state.contains(inverseKind)) - continue; - - state.insert(inverseKind); - inverses[canSubject] = state; - } - - // Fast-path: if there are no valid inverses, then there are no requirements - // to be removed. - if (inverses.empty()) - return; - - // Scan the structural requirements and cancel out any inferred requirements - // based on the inverses we saw. - result.erase(llvm::remove_if(result, [&](StructuralRequirement structReq) { - auto req = structReq.req; - - if (req.getKind() != RequirementKind::Conformance) - return false; - - // Only consider requirements involving an invertible protocol. - auto proto = req.getProtocolDecl()->getInvertibleProtocolKind(); - if (!proto) - return false; - - // See if this subject is in-scope. - auto subject = req.getFirstType()->getCanonicalType(); - auto result = inverses.find(subject); - if (result == inverses.end()) - return false; - - // We now have found the inferred constraint 'Subject : Proto'. - // So, remove it if we have recorded a 'Subject : ~Proto'. - auto recordedInverses = result->getSecond(); - return recordedInverses.contains(*proto); - }), result.end()); -} - /// Collect structural requirements written in the inheritance clause of an /// AssociatedTypeDecl, GenericTypeParamDecl, or ProtocolDecl. void swift::rewriting::realizeInheritedRequirements( @@ -1002,7 +904,8 @@ StructuralRequirementsRequest::evaluate(Evaluator &evaluator, SmallVector defaults; InverseRequirement::expandDefaults(ctx, needsDefaultRequirements, defaults); - applyInverses(ctx, needsDefaultRequirements, inverses, defaults, errors); + applyInverses(ctx, needsDefaultRequirements, inverses, result, + defaults, errors); result.append(defaults); diagnoseRequirementErrors(ctx, errors, @@ -1076,7 +979,8 @@ StructuralRequirementsRequest::evaluate(Evaluator &evaluator, && !proto->isSpecificProtocol(KnownProtocolKind::Sendable)) InverseRequirement::expandDefaults(ctx, needsDefaultRequirements, defaults); - applyInverses(ctx, needsDefaultRequirements, inverses, defaults, errors); + applyInverses(ctx, needsDefaultRequirements, inverses, result, + defaults, errors); result.append(defaults); diagnoseRequirementErrors(ctx, errors, diff --git a/lib/AST/RequirementMachine/RequirementLowering.h b/lib/AST/RequirementMachine/RequirementLowering.h index 1f3fbc57ad961..e83a9d13374a5 100644 --- a/lib/AST/RequirementMachine/RequirementLowering.h +++ b/lib/AST/RequirementMachine/RequirementLowering.h @@ -50,6 +50,13 @@ void desugarRequirement(Requirement req, SourceLoc loc, void inferRequirements(Type type, ModuleDecl *module, DeclContext *dc, SmallVectorImpl &result); +void realizeTypeRequirement(DeclContext *dc, + Type subjectType, + Type constraintType, + SourceLoc loc, + SmallVectorImpl &result, + SmallVectorImpl &errors); + void realizeRequirement(DeclContext *dc, Requirement req, RequirementRepr *reqRepr, bool shouldInferRequirements, @@ -64,6 +71,7 @@ void realizeInheritedRequirements(TypeDecl *decl, Type type, void applyInverses(ASTContext &ctx, ArrayRef gps, ArrayRef inverseList, + ArrayRef explicitRequirements, SmallVectorImpl &result, SmallVectorImpl &errors); diff --git a/lib/AST/RequirementMachine/RequirementMachineRequests.cpp b/lib/AST/RequirementMachine/RequirementMachineRequests.cpp index 97a46d677ad13..f05d6ca577a35 100644 --- a/lib/AST/RequirementMachine/RequirementMachineRequests.cpp +++ b/lib/AST/RequirementMachine/RequirementMachineRequests.cpp @@ -671,7 +671,8 @@ AbstractGenericSignatureRequest::evaluate( SmallVector defaults; InverseRequirement::expandDefaults(ctx, paramsAsTypes, defaults); - applyInverses(ctx, paramsAsTypes, inverses, defaults, errors); + applyInverses(ctx, paramsAsTypes, inverses, requirements, + defaults, errors); requirements.append(defaults); auto &rewriteCtx = ctx.getRewriteContext(); @@ -884,7 +885,8 @@ InferredGenericSignatureRequest::evaluate( SmallVector defaults; InverseRequirement::expandDefaults(ctx, paramTypes, defaults); - applyInverses(ctx, paramTypes, inverses, defaults, errors); + applyInverses(ctx, paramTypes, inverses, requirements, + defaults, errors); // Any remaining implicit defaults in a conditional inverse requirement // extension must be made explicit. diff --git a/lib/AST/SearchPathOptions.cpp b/lib/AST/SearchPathOptions.cpp index 23bb767a5bdf2..308c0fc4754a0 100644 --- a/lib/AST/SearchPathOptions.cpp +++ b/lib/AST/SearchPathOptions.cpp @@ -58,14 +58,10 @@ void ModuleSearchPathLookup::rebuildLookupTable(const SearchPathOptions *Opts, Entry.value().IsSystem, Entry.index()); } - // Apple platforms have extra implicit framework search paths: - // $SDKROOT/System/Library/Frameworks/ and $SDKROOT/Library/Frameworks/. - if (IsOSDarwin) { - for (auto Entry : llvm::enumerate(Opts->getDarwinImplicitFrameworkSearchPaths())) { - addFilesInPathToLookupTable(FS, Entry.value(), - ModuleSearchPathKind::DarwinImplicitFramework, - /*isSystem=*/true, Entry.index()); - } + for (auto Entry : llvm::enumerate(Opts->getImplicitFrameworkSearchPaths())) { + addFilesInPathToLookupTable(FS, Entry.value(), + ModuleSearchPathKind::ImplicitFramework, + /*isSystem=*/true, Entry.index()); } for (auto Entry : llvm::enumerate(Opts->getRuntimeLibraryImportPaths())) { @@ -123,12 +119,9 @@ void SearchPathOptions::dump(bool isDarwin) const { << Entry.value().Path << "\n"; } - if (isDarwin) { - llvm::errs() << "Darwin implicit framework search paths:\n"; - for (auto Entry : - llvm::enumerate(getDarwinImplicitFrameworkSearchPaths())) { - llvm::errs() << " [" << Entry.index() << "] " << Entry.value() << "\n"; - } + llvm::errs() << "Implicit framework search paths:\n"; + for (auto Entry : llvm::enumerate(getImplicitFrameworkSearchPaths())) { + llvm::errs() << " [" << Entry.index() << "] " << Entry.value() << "\n"; } llvm::errs() << "Runtime library import search paths:\n"; diff --git a/lib/AST/SubstitutionMap.cpp b/lib/AST/SubstitutionMap.cpp index 8fc7a1121fdfa..7affba9899246 100644 --- a/lib/AST/SubstitutionMap.cpp +++ b/lib/AST/SubstitutionMap.cpp @@ -285,12 +285,12 @@ SubstitutionMap::lookupConformance(CanType type, ProtocolDecl *proto) const { // anything but still end up with an ErrorType in the AST. if (conformance.isConcrete()) { auto concrete = conformance.getConcrete(); - auto normal = concrete->getRootNormalConformance(); - - if (!normal->hasComputedAssociatedConformances()) { - if (proto->getASTContext().evaluator.hasActiveRequest( - ResolveTypeWitnessesRequest{normal})) { - return ProtocolConformanceRef::forInvalid(); + if (auto normal = dyn_cast(concrete->getRootConformance())) { + if (!normal->hasComputedAssociatedConformances()) { + if (proto->getASTContext().evaluator.hasActiveRequest( + ResolveTypeWitnessesRequest{normal})) { + return ProtocolConformanceRef::forInvalid(); + } } } } diff --git a/lib/AST/Type.cpp b/lib/AST/Type.cpp index d78d66d68f649..61d8b37e0ded3 100644 --- a/lib/AST/Type.cpp +++ b/lib/AST/Type.cpp @@ -320,6 +320,8 @@ ExistentialLayout::ExistentialLayout(CanProtocolType type) { !protoDecl->isMarkerProtocol()); representsAnyObject = false; + inverses = InvertibleProtocolSet(); + protocols.push_back(protoDecl); expandDefaults(protocols, InvertibleProtocolSet(), type->getASTContext()); } @@ -353,7 +355,7 @@ ExistentialLayout::ExistentialLayout(CanProtocolCompositionType type) { protocols.push_back(protoDecl); } - auto inverses = type->getInverses(); + inverses = type->getInverses(); expandDefaults(protocols, inverses, type->getASTContext()); representsAnyObject = [&]() { @@ -433,6 +435,16 @@ Type ExistentialLayout::getSuperclass() const { return Type(); } +bool ExistentialLayout::needsExtendedShape(bool allowInverses) const { + if (!getParameterizedProtocols().empty()) + return true; + + if (allowInverses && hasInverses()) + return true; + + return false; +} + bool TypeBase::isObjCExistentialType() { return getCanonicalType().isObjCExistentialType(); } @@ -1366,6 +1378,7 @@ ParameterListInfo::ParameterListInfo( propertyWrappers.resize(params.size()); implicitSelfCapture.resize(params.size()); inheritActorContext.resize(params.size()); + alwaysInheritActorContext.resize(params.size()); variadicGenerics.resize(params.size()); sendingParameters.resize(params.size()); @@ -1422,8 +1435,13 @@ ParameterListInfo::ParameterListInfo( implicitSelfCapture.set(i); } - if (param->getAttrs().hasAttribute()) { - inheritActorContext.set(i); + if (auto *attr = + param->getAttrs().getAttribute()) { + if (attr->isAlways()) { + alwaysInheritActorContext.set(i); + } else { + inheritActorContext.set(i); + } } if (param->getInterfaceType()->is()) { @@ -1457,10 +1475,18 @@ bool ParameterListInfo::isImplicitSelfCapture(unsigned paramIdx) const { : false; } -bool ParameterListInfo::inheritsActorContext(unsigned paramIdx) const { - return paramIdx < inheritActorContext.size() - ? inheritActorContext[paramIdx] - : false; +std::pair +ParameterListInfo::inheritsActorContext(unsigned paramIdx) const { + if (paramIdx >= inheritActorContext.size()) + return std::make_pair(false, InheritActorContextModifier::None); + + if (inheritActorContext[paramIdx]) + return std::make_pair(true, InheritActorContextModifier::None); + + if (alwaysInheritActorContext[paramIdx]) + return std::make_pair(true, InheritActorContextModifier::Always); + + return std::make_pair(false, InheritActorContextModifier::None); } bool ParameterListInfo::isVariadicGenericParameter(unsigned paramIdx) const { diff --git a/lib/ASTGen/Sources/ASTGen/DeclAttrs.swift b/lib/ASTGen/Sources/ASTGen/DeclAttrs.swift index a9d37cd4ced22..1e8192ef7d22b 100644 --- a/lib/ASTGen/Sources/ASTGen/DeclAttrs.swift +++ b/lib/ASTGen/Sources/ASTGen/DeclAttrs.swift @@ -249,7 +249,6 @@ extension ASTGenVisitor { .ibSegueAction, .implementationOnly, .implicitSelfCapture, - .inheritActorContext, .inheritsConvenienceInitializers, .inlinable, .isolated, @@ -312,6 +311,9 @@ extension ASTGenVisitor { case .referenceOwnership: // TODO: Diagnose. return handle(self.generateReferenceOwnershipAttr(attribute: node, attrName: attrName)?.asDeclAttribute) + case .inheritActorContext: + return handle(self.generateInheritActorContextAttr(attribute: node)?.asDeclAttribute) + case .async, .consuming, .borrowing, @@ -1411,6 +1413,28 @@ extension ASTGenVisitor { ) } + func generateInheritActorContextAttr(attribute node: AttributeSyntax) -> BridgedInheritActorContextAttr? { + let modifier: BridgedInheritActorContextModifier? = self.generateSingleAttrOption( + attribute: node, + { + switch $0.rawText { + case "always": return .always + default: return nil + } + }, + valueIfOmitted: BridgedInheritActorContextModifier.none + ) + guard let modifier else { + return nil + } + return .createParsed( + self.ctx, + atLoc: self.generateSourceLoc(node.atSign), + range: self.generateAttrSourceRange(node), + modifier: modifier + ) + } + /// E.g.: /// ``` /// @objc diff --git a/lib/Basic/Program.cpp b/lib/Basic/Program.cpp index 1d53cdef6b300..473b41a860ef1 100644 --- a/lib/Basic/Program.cpp +++ b/lib/Basic/Program.cpp @@ -123,11 +123,15 @@ swift::ExecuteWithPipe(llvm::StringRef program, posix_spawn_file_actions_t FileActions; posix_spawn_file_actions_init(&FileActions); + // Redirect file descriptors... posix_spawn_file_actions_adddup2(&FileActions, p1.read, STDIN_FILENO); - posix_spawn_file_actions_addclose(&FileActions, p1.write); - posix_spawn_file_actions_adddup2(&FileActions, p2.write, STDOUT_FILENO); + + // Close all file descriptors, not needed as we duped them to the stdio. + posix_spawn_file_actions_addclose(&FileActions, p1.read); + posix_spawn_file_actions_addclose(&FileActions, p1.write); posix_spawn_file_actions_addclose(&FileActions, p2.read); + posix_spawn_file_actions_addclose(&FileActions, p2.write); // Spawn the subtask. int error = posix_spawn(&pid, progCStr, &FileActions, nullptr, @@ -156,13 +160,16 @@ swift::ExecuteWithPipe(llvm::StringRef program, // Child process. case 0: - close(p1.write); - close(p2.read); - // Redirect file descriptors... dup2(p1.read, STDIN_FILENO); dup2(p2.write, STDOUT_FILENO); + // Close all file descriptors, not needed as we duped them to the stdio. + close(p1.read); + close(p1.write); + close(p2.read); + close(p2.write); + // Execute the program. if (envp) { execve(progCStr, const_cast(argv), const_cast(envp)); @@ -180,11 +187,12 @@ swift::ExecuteWithPipe(llvm::StringRef program, // Parent process. default: + close(p1.read); + close(p2.write); break; } #endif - close(p1.read); - close(p2.write); + llvm::sys::ProcessInfo proc; proc.Pid = pid; proc.Process = pid; diff --git a/lib/Basic/SourceLoc.cpp b/lib/Basic/SourceLoc.cpp index 03b9ce15f1823..ed3f9e2aa3160 100644 --- a/lib/Basic/SourceLoc.cpp +++ b/lib/Basic/SourceLoc.cpp @@ -482,7 +482,7 @@ namespace { std::optional SourceManager::findBufferContainingLocInternal(SourceLoc Loc) const { - assert(Loc.isValid()); + ASSERT(Loc.isValid()); // If the cache is out-of-date, update it now. unsigned numBuffers = LLVMSourceMgr.getNumBuffers(); diff --git a/lib/ClangImporter/ClangImporter.cpp b/lib/ClangImporter/ClangImporter.cpp index 4b7e17d65a970..1db2ba6a5a890 100644 --- a/lib/ClangImporter/ClangImporter.cpp +++ b/lib/ClangImporter/ClangImporter.cpp @@ -90,6 +90,7 @@ #include "clang/Serialization/ASTReader.h" #include "clang/Serialization/ASTWriter.h" #include "clang/Serialization/ObjectFilePCHContainerReader.h" +#include "clang/Tooling/DependencyScanning/ModuleDepCollector.h" #include "clang/Tooling/DependencyScanning/ScanAndUpdateArgs.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/STLExtras.h" @@ -1038,27 +1039,6 @@ std::string ClangImporter::getOriginalSourceFile(StringRef PCHFilename) { Impl.Instance->getPCHContainerReader(), Impl.Instance->getDiagnostics()); } -void ClangImporter::addClangInvovcationDependencies( - std::vector &files) { - auto addFiles = [&files](const auto &F) { - files.insert(files.end(), F.begin(), F.end()); - }; - auto &invocation = *Impl.Invocation; - // FIXME: Add file dependencies that are not accounted. The long term solution - // is to do a dependency scanning for clang importer and use that directly. - SmallVector HeaderMapFileNames; - Impl.Instance->getPreprocessor().getHeaderSearchInfo().getHeaderMapFileNames( - HeaderMapFileNames); - addFiles(HeaderMapFileNames); - addFiles(invocation.getHeaderSearchOpts().VFSOverlayFiles); - // FIXME: Should not depend on working directory. Build system/swift driver - // should not pass working directory here but if that option is passed, - // repect that and add that into CASFS. - auto CWD = invocation.getFileSystemOpts().WorkingDir; - if (!CWD.empty()) - files.push_back(CWD); -} - std::optional ClangImporter::getPCHFilename(const ClangImporterOptions &ImporterOptions, StringRef SwiftPCHHash, bool &isExplicit) { @@ -1186,9 +1166,8 @@ std::optional> ClangImporter::getClangCC1Arguments( clang::frontend::ActionKind::GenerateModule || CI->getFrontendOpts().ProgramAction == clang::frontend::ActionKind::GeneratePCH) && - ctx.ClangImporterOpts.HasClangIncludeTreeRoot) { - CI->getFrontendOpts().CASIncludeTreeID = - ctx.CASOpts.ClangIncludeTrees.back(); + !ctx.CASOpts.ClangIncludeTree.empty()) { + CI->getFrontendOpts().CASIncludeTreeID = ctx.CASOpts.ClangIncludeTree; CI->getFrontendOpts().Inputs.clear(); } } @@ -1247,7 +1226,7 @@ std::optional> ClangImporter::getClangCC1Arguments( std::vector FilteredModuleMapFiles; for (auto ModuleMapFile : CI->getFrontendOpts().ModuleMapFiles) { - if (ctx.ClangImporterOpts.HasClangIncludeTreeRoot) { + if (ctx.CASOpts.HasImmutableFileSystem) { // There is no need to add any module map file here. Issue a warning and // drop the option. Impl.diagnose(SourceLoc(), diag::module_map_ignored, ModuleMapFile); @@ -1327,7 +1306,7 @@ ClangImporter::create(ASTContext &ctx, fileMapping.requiresBuiltinHeadersInSystemModules; // Avoid creating indirect file system when using include tree. - if (!ctx.ClangImporterOpts.HasClangIncludeTreeRoot) { + if (!ctx.CASOpts.HasImmutableFileSystem) { // Wrap Swift's FS to allow Clang to override the working directory VFS = llvm::vfs::RedirectingFileSystem::create( fileMapping.redirectedFiles, true, *ctx.SourceMgr.getFileSystem()); @@ -2732,7 +2711,6 @@ ClangImporter::Implementation::Implementation( !ctx.ClangImporterOpts.BridgingHeader.empty()), DisableOverlayModules(ctx.ClangImporterOpts.DisableOverlayModules), EnableClangSPI(ctx.ClangImporterOpts.EnableClangSPI), - UseClangIncludeTree(ctx.ClangImporterOpts.UseClangIncludeTree), IsReadingBridgingPCH(false), CurrentVersion(ImportNameVersion::fromOptions(ctx.LangOpts)), Walker(DiagnosticWalker(*this)), BuffersForDiagnostics(ctx.SourceMgr), @@ -4255,15 +4233,14 @@ ClangImporter::getSwiftExplicitModuleDirectCC1Args() const { PPOpts.MacroIncludes.clear(); PPOpts.Includes.clear(); - // CodeGenOptions. - auto &CGOpts = instance.getCodeGenOpts(); - CGOpts.DebugCompilationDir.clear(); + // Clear benign CodeGenOptions. + clang::tooling::dependencies::resetBenignCodeGenOptions( + clang::frontend::ActionKind::GenerateModule, instance.getLangOpts(), + instance.getCodeGenOpts()); - if (Impl.SwiftContext.ClangImporterOpts.UseClangIncludeTree) { - // FileSystemOptions. - auto &FSOpts = instance.getFileSystemOpts(); - FSOpts.WorkingDir.clear(); - } + // FileSystemOptions. + auto &FSOpts = instance.getFileSystemOpts(); + FSOpts.WorkingDir.clear(); if (!Impl.SwiftContext.SearchPathOpts.ScannerPrefixMapper.empty()) { // Remap all the paths if requested. diff --git a/lib/ClangImporter/ClangModuleDependencyScanner.cpp b/lib/ClangImporter/ClangModuleDependencyScanner.cpp index 44446c2551dd5..61c02e854c337 100644 --- a/lib/ClangImporter/ClangModuleDependencyScanner.cpp +++ b/lib/ClangImporter/ClangModuleDependencyScanner.cpp @@ -147,8 +147,8 @@ ModuleDependencyVector ClangImporter::bridgeClangModuleDependencies( // Swift frontend option for input file path (Foo.modulemap). swiftArgs.push_back(remapPath(clangModuleDep.ClangModuleMapFile)); - // Handle VFSOverlay. If include tree is used, there is no need for overlay. - if (!ctx.ClangImporterOpts.UseClangIncludeTree) { + // Handle VFSOverlay. If caching is enabled, there is no need for overlay. + if (!ctx.CASOpts.EnableCaching) { for (auto &overlay : ctx.SearchPathOpts.VFSOverlayFiles) { swiftArgs.push_back("-vfsoverlay"); swiftArgs.push_back(remapPath(overlay)); @@ -217,12 +217,6 @@ ModuleDependencyVector ClangImporter::bridgeClangModuleDependencies( ctx.CASOpts.enumerateCASConfigurationFlags( [&](StringRef Arg) { swiftArgs.push_back(Arg.str()); }); - if (!RootID.empty()) { - swiftArgs.push_back("-no-clang-include-tree"); - swiftArgs.push_back("-cas-fs"); - swiftArgs.push_back(RootID); - } - if (!IncludeTree.empty()) { swiftArgs.push_back("-clang-include-tree-root"); swiftArgs.push_back(IncludeTree); @@ -324,11 +318,6 @@ void ClangImporter::getBridgingHeaderOptions( swiftArgs.push_back("-clang-include-tree-root"); swiftArgs.push_back(*Tree); } - if (auto CASFS = deps.CASFileSystemRootID) { - swiftArgs.push_back("-no-clang-include-tree"); - swiftArgs.push_back("-cas-fs"); - swiftArgs.push_back(*CASFS); - } } ModuleDependencyVector diff --git a/lib/ClangImporter/ImportDecl.cpp b/lib/ClangImporter/ImportDecl.cpp index 7ddbb3383ec20..6ef169042a1f6 100644 --- a/lib/ClangImporter/ImportDecl.cpp +++ b/lib/ClangImporter/ImportDecl.cpp @@ -4630,9 +4630,14 @@ namespace { auto convertKind = ConstantConvertKind::None; // Request conversions on enums, and swift_wrapper((enum/struct)) // types - if (decl->getType()->isEnumeralType()) - convertKind = ConstantConvertKind::Construction; - else if (findSwiftNewtype(decl, Impl.getClangSema(), + if (decl->getType()->isEnumeralType()) { + if (type->getEnumOrBoundGenericEnum()) { + // When importing as an enum, also apply implicit force unwrap + convertKind = ConstantConvertKind::ConstructionWithUnwrap; + } else { + convertKind = ConstantConvertKind::Construction; + } + } else if (findSwiftNewtype(decl, Impl.getClangSema(), Impl.CurrentVersion)) convertKind = ConstantConvertKind::Construction; diff --git a/lib/ClangImporter/ImporterImpl.h b/lib/ClangImporter/ImporterImpl.h index db9baab4dd096..96038d675d615 100644 --- a/lib/ClangImporter/ImporterImpl.h +++ b/lib/ClangImporter/ImporterImpl.h @@ -478,7 +478,6 @@ class LLVM_LIBRARY_VISIBILITY ClangImporter::Implementation const bool BridgingHeaderExplicitlyRequested; const bool DisableOverlayModules; const bool EnableClangSPI; - const bool UseClangIncludeTree; bool IsReadingBridgingPCH; llvm::SmallVector PCHImportedSubmodules; diff --git a/lib/DependencyScan/ModuleDependencyScanner.cpp b/lib/DependencyScan/ModuleDependencyScanner.cpp index 358f4904ecfd7..5f8cae82a6f9e 100644 --- a/lib/DependencyScan/ModuleDependencyScanner.cpp +++ b/lib/DependencyScan/ModuleDependencyScanner.cpp @@ -595,14 +595,6 @@ ModuleDependencyScanner::getMainModuleDependencyInfo(ModuleDecl *mainModule) { auto mainDependencies = ModuleDependencyInfo::forSwiftSourceModule( {}, buildCommands, {}, {}, {}); - if (ScanASTContext.CASOpts.EnableCaching) { - std::vector clangDependencyFiles; - clangImporter->addClangInvovcationDependencies(clangDependencyFiles); - llvm::for_each(clangDependencyFiles, [&](std::string &file) { - mainDependencies.addAuxiliaryFile(file); - }); - } - llvm::StringSet<> alreadyAddedModules; // Compute Implicit dependencies of the main module { diff --git a/lib/DependencyScan/ScanDependencies.cpp b/lib/DependencyScan/ScanDependencies.cpp index 8547191c93df1..36520fd6f8d49 100644 --- a/lib/DependencyScan/ScanDependencies.cpp +++ b/lib/DependencyScan/ScanDependencies.cpp @@ -45,7 +45,7 @@ #include "swift/Frontend/FrontendOptions.h" #include "swift/Frontend/ModuleInterfaceLoader.h" #include "swift/Strings.h" -#include "clang/Basic/Module.h" +#include "clang/CAS/IncludeTree.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SetOperations.h" #include "llvm/ADT/SetVector.h" @@ -69,7 +69,6 @@ #include #include #include -#include using namespace swift; using namespace swift::dependencies; @@ -101,9 +100,6 @@ class ExplicitModuleDependencyResolver { if (resolvingDepInfo.isFinalized()) return false; - if (auto ID = resolvingDepInfo.getClangIncludeTree()) - includeTrees.push_back(*ID); - for (const auto &depModuleID : dependencies) { const auto &depInfo = cache.findKnownDependency(depModuleID); switch (depModuleID.Kind) { @@ -320,10 +316,10 @@ class ExplicitModuleDependencyResolver { } // Collect CAS deppendencies from clang modules. - if (!clangDepDetails.CASFileSystemRootID.empty()) - rootIDs.push_back(clangDepDetails.CASFileSystemRootID); - if (!clangDepDetails.CASClangIncludeTreeRootID.empty()) - includeTrees.push_back(clangDepDetails.CASClangIncludeTreeRootID); + if (!clangDepDetails.CASClangIncludeTreeRootID.empty()) { + if (addIncludeTree(clangDepDetails.CASClangIncludeTreeRootID)) + return true; + } collectUsedVFSOverlay(clangDepDetails); @@ -358,12 +354,14 @@ class ExplicitModuleDependencyResolver { auto bridgeRoot = tracker->createTreeFromDependencies(); if (!bridgeRoot) return diagnoseCASFSCreationError(bridgeRoot.takeError()); - fileListIDs.push_back(bridgeRoot->getID().toString()); + + fileListRefs.push_back(bridgeRoot->getRef()); } } - } else - includeTrees.push_back(sourceDepDetails.textualModuleDetails - .CASBridgingHeaderIncludeTreeRootID); + } else if (addIncludeTree(sourceDepDetails.textualModuleDetails + .CASBridgingHeaderIncludeTreeRootID)) + return true; + return false; }; @@ -499,9 +497,7 @@ class ExplicitModuleDependencyResolver { auto root = tracker->createTreeFromDependencies(); if (!root) return diagnoseCASFSCreationError(root.takeError()); - auto rootID = root->getID().toString(); - dependencyInfoCopy.updateCASFileSystemRootID(rootID); - fileListIDs.push_back(rootID); + fileListRefs.push_back(root->getRef()); } else if (auto *textualDep = resolvingDepInfo.getAsSwiftInterfaceModule()) { tracker->startTracking(); @@ -516,29 +512,15 @@ class ExplicitModuleDependencyResolver { auto root = tracker->createTreeFromDependencies(); if (!root) return diagnoseCASFSCreationError(root.takeError()); - auto rootID = root->getID().toString(); - dependencyInfoCopy.updateCASFileSystemRootID(rootID); - fileListIDs.push_back(rootID); + fileListRefs.push_back(root->getRef()); } // Update build command line. if (resolvingDepInfo.isSwiftInterfaceModule() || resolvingDepInfo.isSwiftSourceModule()) { // Update with casfs option. - for (auto rootID : rootIDs) { - commandline.push_back("-cas-fs"); - commandline.push_back(rootID); - } - - for (auto tree : includeTrees) { - commandline.push_back("-clang-include-tree-root"); - commandline.push_back(tree); - } - - for (auto list : fileListIDs) { - commandline.push_back("-clang-include-tree-filelist"); - commandline.push_back(list); - } + if (computeCASFileSystem(dependencyInfoCopy)) + return true; } // Compute and update module cache key. @@ -636,6 +618,53 @@ class ExplicitModuleDependencyResolver { cmd.push_back("-cache-disable-replay"); } + bool addIncludeTree(StringRef includeTree) { + auto &db = cache.getScanService().getCAS(); + auto casID = db.parseID(includeTree); + if (!casID) { + instance.getDiags().diagnose(SourceLoc(), diag::error_invalid_cas_id, + includeTree, toString(casID.takeError())); + return true; + } + auto ref = db.getReference(*casID); + if (!ref) { + instance.getDiags().diagnose(SourceLoc(), diag::error_load_input_from_cas, + includeTree); + return true; + } + + auto root = clang::cas::IncludeTreeRoot::get(db, *ref); + if (!root) { + instance.getDiags().diagnose(SourceLoc(), diag::error_cas_malformed_input, + includeTree, toString(root.takeError())); + return true; + } + + fileListRefs.push_back(root->getFileListRef()); + return false; + } + + bool computeCASFileSystem(ModuleDependencyInfo &dependencyInfoCopy) { + if (fileListRefs.empty()) + return false; + + auto &db = cache.getScanService().getCAS(); + auto casFS = + clang::cas::IncludeTree::FileList::create(db, {}, fileListRefs); + if (!casFS) { + instance.getDiags().diagnose(SourceLoc(), diag::error_cas, + "CAS IncludeTree FileList creation", + toString(casFS.takeError())); + return true; + } + + auto casID = casFS->getID().toString(); + dependencyInfoCopy.updateCASFileSystemRootID(casID); + commandline.push_back("-clang-include-tree-filelist"); + commandline.push_back(casID); + return false; + } + private: const ModuleDependencyID &moduleID; ModuleDependenciesCache &cache; @@ -643,9 +672,7 @@ class ExplicitModuleDependencyResolver { const ModuleDependencyInfo &resolvingDepInfo; std::optional tracker; - std::vector rootIDs; - std::vector includeTrees; - std::vector fileListIDs; + std::vector fileListRefs; std::vector commandline; std::vector bridgingHeaderBuildCmd; llvm::StringMap macros; diff --git a/lib/Driver/ToolChain.cpp b/lib/Driver/ToolChain.cpp index d9895d51c8522..5538e19eb4191 100644 --- a/lib/Driver/ToolChain.cpp +++ b/lib/Driver/ToolChain.cpp @@ -72,6 +72,11 @@ std::optional ToolChain::getResponseFileInfo(const Compilation &C, const char *executablePath, const ToolChain::InvocationInfo &invocationInfo, const ToolChain::JobContext &context) const { + // Never use a response file if this is a dummy driver for SourceKit, we + // just want the frontend arguments. + if (getDriver().isDummyDriverForFrontendInvocation()) + return std::nullopt; + const bool forceResponseFiles = C.getArgs().hasArg(options::OPT_driver_force_response_files); assert((invocationInfo.allowsResponseFiles || !forceResponseFiles) && diff --git a/lib/Frontend/CachingUtils.cpp b/lib/Frontend/CachingUtils.cpp index 7bc73326332b5..151db67c8f282 100644 --- a/lib/Frontend/CachingUtils.cpp +++ b/lib/Frontend/CachingUtils.cpp @@ -449,53 +449,14 @@ static llvm::Error createCASObjectNotFoundError(const llvm::cas::CASID &ID) { "CASID missing from Object Store " + ID.toString()); } -static Expected mergeCASFileSystem(ObjectStore &CAS, - ArrayRef FSRoots) { - llvm::cas::HierarchicalTreeBuilder Builder; - for (auto &Root : FSRoots) { - auto ID = CAS.parseID(Root); - if (!ID) - return ID.takeError(); - - auto Ref = CAS.getReference(*ID); - if (!Ref) - return createCASObjectNotFoundError(*ID); - Builder.pushTreeContent(*Ref, ""); - } - - auto NewRoot = Builder.create(CAS); - if (!NewRoot) - return NewRoot.takeError(); - - return NewRoot->getRef(); -} - Expected> -createCASFileSystem(ObjectStore &CAS, ArrayRef FSRoots, - ArrayRef IncludeTrees, - ArrayRef IncludeTreeFileList) { - assert(!FSRoots.empty() || !IncludeTrees.empty() || +createCASFileSystem(ObjectStore &CAS, const std::string &IncludeTree, + const std::string &IncludeTreeFileList) { + assert(!IncludeTree.empty() || !IncludeTreeFileList.empty() && "no root ID provided"); - if (FSRoots.size() == 1 && IncludeTrees.empty()) { - auto ID = CAS.parseID(FSRoots.front()); - if (!ID) - return ID.takeError(); - return createCASFileSystem(CAS, *ID); - } - auto NewRoot = mergeCASFileSystem(CAS, FSRoots); - if (!NewRoot) - return NewRoot.takeError(); - - auto FS = createCASFileSystem(CAS, CAS.getID(*NewRoot)); - if (!FS) - return FS.takeError(); - - auto CASFS = makeIntrusiveRefCnt(std::move(*FS)); - std::vector Files; - // Push all Include File System onto overlay. - for (auto &Tree : IncludeTrees) { - auto ID = CAS.parseID(Tree); + if (!IncludeTree.empty()) { + auto ID = CAS.parseID(IncludeTree); if (!ID) return ID.takeError(); @@ -510,47 +471,33 @@ createCASFileSystem(ObjectStore &CAS, ArrayRef FSRoots, if (!ITF) return ITF.takeError(); - auto Err = ITF->forEachFile( - [&](clang::cas::IncludeTree::File File, - clang::cas::IncludeTree::FileList::FileSizeTy Size) -> llvm::Error { - Files.push_back({File.getRef(), Size}); - return llvm::Error::success(); - }); + auto ITFS = clang::cas::createIncludeTreeFileSystem(*ITF); + if (!ITFS) + return ITFS.takeError(); - if (Err) - return std::move(Err); + return *ITFS; } - for (auto &List: IncludeTreeFileList) { - auto ID = CAS.parseID(List); + if (!IncludeTreeFileList.empty()) { + auto ID = CAS.parseID(IncludeTreeFileList); if (!ID) return ID.takeError(); auto Ref = CAS.getReference(*ID); if (!Ref) return createCASObjectNotFoundError(*ID); - auto IT = clang::cas::IncludeTree::FileList::get(CAS, *Ref); - if (!IT) - return IT.takeError(); + auto ITF = clang::cas::IncludeTree::FileList::get(CAS, *Ref); + if (!ITF) + return ITF.takeError(); - auto Err = IT->forEachFile( - [&](clang::cas::IncludeTree::File File, - clang::cas::IncludeTree::FileList::FileSizeTy Size) -> llvm::Error { - Files.push_back({File.getRef(), Size}); - return llvm::Error::success(); - }); + auto ITFS = clang::cas::createIncludeTreeFileSystem(*ITF); + if (!ITFS) + return ITFS.takeError(); - if (Err) - return std::move(Err); + return *ITFS; } - auto ITFS = clang::cas::createIncludeTreeFileSystem(CAS, Files); - if (!ITFS) - return ITFS.takeError(); - - CASFS->pushOverlay(std::move(*ITFS)); - - return CASFS; + return nullptr; } std::vector remapPathsFromCommandLine( diff --git a/lib/Frontend/CompilerInvocation.cpp b/lib/Frontend/CompilerInvocation.cpp index f3f151197c8eb..7ab6a99a7037b 100644 --- a/lib/Frontend/CompilerInvocation.cpp +++ b/lib/Frontend/CompilerInvocation.cpp @@ -254,7 +254,7 @@ static void updateRuntimeLibraryPaths(SearchPathOptions &SearchPathOpts, SearchPathOpts.RuntimeLibraryPaths.push_back(DARWIN_OS_LIBRARY_PATH); // If this is set, we don't want any runtime import paths. - if (SearchPathOpts.SkipRuntimeLibraryImportPaths) { + if (SearchPathOpts.SkipAllImplicitImportPaths) { SearchPathOpts.setRuntimeLibraryImportPaths({}); return; } @@ -270,7 +270,7 @@ static void updateRuntimeLibraryPaths(SearchPathOptions &SearchPathOpts, RuntimeLibraryImportPaths.push_back(std::string(LibPath.str())); } - if (!SearchPathOpts.ExcludeSDKPathsFromRuntimeLibraryImportPaths && !SearchPathOpts.getSDKPath().empty()) { + if (!SearchPathOpts.SkipSDKImportPaths && !SearchPathOpts.getSDKPath().empty()) { const char *swiftDir = FrontendOpts.UseSharedResourceFolder ? "swift" : "swift_static"; @@ -300,6 +300,35 @@ static void updateRuntimeLibraryPaths(SearchPathOptions &SearchPathOpts, SearchPathOpts.setRuntimeLibraryImportPaths(RuntimeLibraryImportPaths); } +static void +updateImplicitFrameworkSearchPaths(SearchPathOptions &SearchPathOpts, + const LangOptions &LangOpts) { + if (SearchPathOpts.SkipAllImplicitImportPaths) { + SearchPathOpts.setImplicitFrameworkSearchPaths({}); + return; + } + + std::vector ImplicitFrameworkSearchPaths; + if (LangOpts.Target.isOSDarwin()) { + if (!SearchPathOpts.SkipSDKImportPaths && + !SearchPathOpts.getSDKPath().empty()) { + StringRef SDKPath = SearchPathOpts.getSDKPath(); + SmallString<128> systemFrameworksScratch(SDKPath); + llvm::sys::path::append(systemFrameworksScratch, "System", "Library", + "Frameworks"); + SmallString<128> systemSubFrameworksScratch(SDKPath); + llvm::sys::path::append(systemSubFrameworksScratch, "System", "Library", + "SubFrameworks"); + SmallString<128> frameworksScratch(SDKPath); + llvm::sys::path::append(frameworksScratch, "Library", "Frameworks"); + ImplicitFrameworkSearchPaths = {systemFrameworksScratch.str().str(), + systemSubFrameworksScratch.str().str(), + frameworksScratch.str().str()}; + } + } + SearchPathOpts.setImplicitFrameworkSearchPaths(ImplicitFrameworkSearchPaths); +} + static void setIRGenOutputOptsFromFrontendOptions(IRGenOptions &IRGenOpts, const FrontendOptions &FrontendOpts) { @@ -411,11 +440,13 @@ void CompilerInvocation::setTargetTriple(StringRef Triple) { void CompilerInvocation::setTargetTriple(const llvm::Triple &Triple) { LangOpts.setTarget(Triple); updateRuntimeLibraryPaths(SearchPathOpts, FrontendOpts, LangOpts); + updateImplicitFrameworkSearchPaths(SearchPathOpts, LangOpts); } void CompilerInvocation::setSDKPath(const std::string &Path) { SearchPathOpts.setSDKPath(Path); updateRuntimeLibraryPaths(SearchPathOpts, FrontendOpts, LangOpts); + updateImplicitFrameworkSearchPaths(SearchPathOpts, LangOpts); } bool CompilerInvocation::setModuleAliasMap(std::vector args, @@ -761,12 +792,10 @@ static bool ParseCASArgs(CASOptions &Opts, ArgList &Args, std::string(Value)); } - for (const auto &A : Args.getAllArgValues(OPT_cas_fs)) - Opts.CASFSRootIDs.emplace_back(A); - for (const auto &A : Args.getAllArgValues(OPT_clang_include_tree_root)) - Opts.ClangIncludeTrees.emplace_back(A); - for (const auto &A : Args.getAllArgValues(OPT_clang_include_tree_filelist)) - Opts.ClangIncludeTreeFileList.emplace_back(A); + if (auto *A = Args.getLastArg(OPT_clang_include_tree_root)) + Opts.ClangIncludeTree = A->getValue(); + if (auto *A = Args.getLastArg(OPT_clang_include_tree_filelist)) + Opts.ClangIncludeTreeFileList = A->getValue(); if (const Arg *A = Args.getLastArg(OPT_input_file_key)) Opts.InputFileKey = A->getValue(); @@ -774,8 +803,7 @@ static bool ParseCASArgs(CASOptions &Opts, ArgList &Args, if (const Arg*A = Args.getLastArg(OPT_bridging_header_pch_key)) Opts.BridgingHeaderPCHCacheKey = A->getValue(); - if (!Opts.CASFSRootIDs.empty() || !Opts.ClangIncludeTrees.empty() || - !Opts.ClangIncludeTreeFileList.empty()) + if (!Opts.ClangIncludeTree.empty() || !Opts.ClangIncludeTreeFileList.empty()) Opts.HasImmutableFileSystem = true; return false; @@ -2130,10 +2158,6 @@ static bool ParseClangImporterArgs(ClangImporterOptions &Opts, ArgList &Args, // Forward the FrontendOptions to clang importer option so it can be // accessed when creating clang module compilation invocation. if (CASOpts.EnableCaching) { - // Only set UseClangIncludeTree when caching is enabled since it is not - // useful in non-caching context. - Opts.UseClangIncludeTree |= !Args.hasArg(OPT_no_clang_include_tree); - Opts.HasClangIncludeTreeRoot |= Args.hasArg(OPT_clang_include_tree_root); // Caching requires direct clang import cc1 scanning. Opts.ClangImporterDirectCC1Scan = true; } @@ -2387,8 +2411,8 @@ static bool ParseSearchPathArgs(SearchPathOptions &Opts, ArgList &Args, if (const Arg *A = Args.getLastArg(OPT_resource_dir)) Opts.RuntimeResourcePath = A->getValue(); - Opts.SkipRuntimeLibraryImportPaths |= Args.hasArg(OPT_nostdimport); - Opts.ExcludeSDKPathsFromRuntimeLibraryImportPaths |= Args.hasArg(OPT_nostdlibimport); + Opts.SkipAllImplicitImportPaths |= Args.hasArg(OPT_nostdimport); + Opts.SkipSDKImportPaths |= Args.hasArg(OPT_nostdlibimport); Opts.DisableModulesValidateSystemDependencies |= Args.hasArg(OPT_disable_modules_validate_system_headers); @@ -4056,6 +4080,7 @@ bool CompilerInvocation::parseArgs( } updateRuntimeLibraryPaths(SearchPathOpts, FrontendOpts, LangOpts); + updateImplicitFrameworkSearchPaths(SearchPathOpts, LangOpts); setDefaultPrebuiltCacheIfNecessary(); setDefaultBlocklistsIfNecessary(); setDefaultInProcessPluginServerPathIfNecessary(); diff --git a/lib/Frontend/Frontend.cpp b/lib/Frontend/Frontend.cpp index f95612e723286..d32e108f58d38 100644 --- a/lib/Frontend/Frontend.cpp +++ b/lib/Frontend/Frontend.cpp @@ -207,7 +207,6 @@ SerializationOptions CompilerInvocation::computeSerializationOptions( serializationOpts.ModuleLinkName = opts.ModuleLinkName; serializationOpts.UserModuleVersion = opts.UserModuleVersion; serializationOpts.AllowableClients = opts.AllowableClients; - serializationOpts.SerializeDebugInfoSIL = opts.SerializeDebugInfoSIL; serializationOpts.PublicDependentLibraries = getIRGenOptions().PublicLinkLibraries; @@ -268,6 +267,18 @@ SerializationOptions CompilerInvocation::computeSerializationOptions( serializationOpts.EmbeddedSwiftModule = LangOpts.hasFeature(Feature::Embedded); + serializationOpts.SerializeDebugInfoSIL = opts.SerializeDebugInfoSIL; + + // Enable serialization of debug info in embedded mode. + // This is important to get diagnostics for errors which are located in imported modules. + // Such errors can sometimes only be detected when building the client module, because + // the error can be in a generic function which is specialized in the client module. + if (serializationOpts.EmbeddedSwiftModule && + // Except for the stdlib core. We don't want to get error locations inside stdlib internals. + !getParseStdlib()) { + serializationOpts.SerializeDebugInfoSIL = true; + } + serializationOpts.IsOSSA = getSILOptions().EnableOSSAModules; serializationOpts.SkipNonExportableDecls = @@ -630,11 +641,9 @@ bool CompilerInstance::setUpVirtualFileSystemOverlays() { } if (Invocation.getCASOptions().requireCASFS()) { - if (!CASOpts.CASFSRootIDs.empty() || !CASOpts.ClangIncludeTrees.empty() || - !CASOpts.ClangIncludeTreeFileList.empty()) { + if (Invocation.getCASOptions().HasImmutableFileSystem) { // Set up CASFS as BaseFS. - auto FS = createCASFileSystem(*CAS, CASOpts.CASFSRootIDs, - CASOpts.ClangIncludeTrees, + auto FS = createCASFileSystem(*CAS, CASOpts.ClangIncludeTree, CASOpts.ClangIncludeTreeFileList); if (!FS) { Diagnostics.diagnose(SourceLoc(), diag::error_cas_fs_creation, @@ -682,8 +691,8 @@ bool CompilerInstance::setUpVirtualFileSystemOverlays() { } } llvm::IntrusiveRefCntPtr OverlayVFS = - new llvm::vfs::OverlayFileSystem(SourceMgr.getFileSystem()); - OverlayVFS->pushOverlay(MemFS); + new llvm::vfs::OverlayFileSystem(MemFS); + OverlayVFS->pushOverlay(SourceMgr.getFileSystem()); SourceMgr.setFileSystem(std::move(OverlayVFS)); } @@ -785,15 +794,6 @@ bool CompilerInstance::setUpModuleLoaders() { this->DefaultSerializedLoader = ISML.get(); Context->addModuleLoader(std::move(ISML)); - // When caching is enabled, we rely on ClangImporter for - // 'addClangInvovcationDependencies' - if (Invocation.getCASOptions().EnableCaching) { - std::unique_ptr clangImporter = - ClangImporter::create(*Context, Invocation.getPCHHash(), - getDependencyTracker()); - Context->addModuleLoader(std::move(clangImporter), /*isClang*/ true); - } - return false; } @@ -967,10 +967,10 @@ std::string CompilerInstance::getBridgingHeaderPath() const { } bool CompilerInstance::setUpInputs() { - // There is no input file when building PCM using ClangIncludeTree. + // There is no input file when building PCM using Caching. if (Invocation.getFrontendOptions().RequestedAction == FrontendOptions::ActionType::EmitPCM && - Invocation.getClangImporterOptions().HasClangIncludeTreeRoot) + Invocation.getCASOptions().EnableCaching) return false; // Adds to InputSourceCodeBufferIDs, so may need to happen before the diff --git a/lib/Frontend/ModuleInterfaceLoader.cpp b/lib/Frontend/ModuleInterfaceLoader.cpp index 4c85d49f18d69..002918eb63c6d 100644 --- a/lib/Frontend/ModuleInterfaceLoader.cpp +++ b/lib/Frontend/ModuleInterfaceLoader.cpp @@ -1815,13 +1815,6 @@ void InterfaceSubContextDelegateImpl::inheritOptionsForBuildingInterface( casOpts.HasImmutableFileSystem; casOpts.enumerateCASConfigurationFlags( [&](StringRef Arg) { GenericArgs.push_back(ArgSaver.save(Arg)); }); - // ClangIncludeTree is default on when caching is enabled. - genericSubInvocation.getClangImporterOptions().UseClangIncludeTree = true; - } - - if (!clangImporterOpts.UseClangIncludeTree) { - genericSubInvocation.getClangImporterOptions().UseClangIncludeTree = false; - GenericArgs.push_back("-no-clang-include-tree"); } } @@ -2521,8 +2514,7 @@ struct ExplicitCASModuleLoader::Implementation { }; for (auto &entry : ExplicitClangModuleMap) { const auto &moduleMapPath = entry.getValue().moduleMapPath; - if (!moduleMapPath.empty() && - !Ctx.ClangImporterOpts.UseClangIncludeTree && + if (!moduleMapPath.empty() && !Ctx.CASOpts.EnableCaching && moduleMapsSeen.find(moduleMapPath) == moduleMapsSeen.end()) { moduleMapsSeen.insert(moduleMapPath); extraClangArgs.push_back( diff --git a/lib/IDE/CompletionLookup.cpp b/lib/IDE/CompletionLookup.cpp index 2dee28a4455bf..ab861f006e627 100644 --- a/lib/IDE/CompletionLookup.cpp +++ b/lib/IDE/CompletionLookup.cpp @@ -3141,6 +3141,9 @@ void CompletionLookup::getAttributeDeclParamCompletions( addDeclAttrParamKeyword("unsafe", /*Parameters=*/{}, "", false); addDeclAttrParamKeyword("nonsending", /*Parameters=*/{}, "", false); break; + case ParameterizedDeclAttributeKind::InheritActorContext: + addDeclAttrParamKeyword("always", /*Parameters=*/{}, "", false); + break; case ParameterizedDeclAttributeKind::AccessControl: addDeclAttrParamKeyword("set", /*Parameters=*/{}, "", false); break; diff --git a/lib/IDE/PostfixCompletion.cpp b/lib/IDE/PostfixCompletion.cpp index 02849e6b72980..7fbad08e902f2 100644 --- a/lib/IDE/PostfixCompletion.cpp +++ b/lib/IDE/PostfixCompletion.cpp @@ -110,9 +110,6 @@ getClosureActorIsolation(const Solution &S, AbstractClosureExpr *ACE) { if (auto Ty = target->getClosureContextualType()) return Ty; } - if (!S.hasType(E)) { - return Type(); - } return getTypeForCompletion(S, E); }; auto getClosureActorIsolationThunk = [&S](AbstractClosureExpr *ACE) { diff --git a/lib/IDE/TypeCheckCompletionCallback.cpp b/lib/IDE/TypeCheckCompletionCallback.cpp index e068312deee23..58406f9d8215c 100644 --- a/lib/IDE/TypeCheckCompletionCallback.cpp +++ b/lib/IDE/TypeCheckCompletionCallback.cpp @@ -58,7 +58,7 @@ Type swift::ide::getTypeForCompletion(const constraints::Solution &S, } if (!S.hasType(Node)) { - assert(false && "Expression wasn't type checked?"); + CONDITIONAL_ASSERT(false && "Expression wasn't type checked?"); return nullptr; } diff --git a/lib/IRGen/GenCall.cpp b/lib/IRGen/GenCall.cpp index d85cb1c54afbe..309d6e0e06eef 100644 --- a/lib/IRGen/GenCall.cpp +++ b/lib/IRGen/GenCall.cpp @@ -5023,6 +5023,8 @@ static void emitRetconCoroutineEntry( for (auto *arg : finalArguments) { arguments.push_back(arg); } + ArtificialLocation Loc(IGF.getDebugScope(), IGF.IGM.DebugInfo.get(), + IGF.Builder); llvm::Value *id = IGF.Builder.CreateIntrinsicCall(idIntrinsic, arguments); // Call 'llvm.coro.begin', just for consistency with the normal pattern. @@ -5127,7 +5129,6 @@ void irgen::emitYieldOnceCoroutineEntry( allocFn = IGF.IGM.getOpaquePtr(IGF.IGM.getMallocFn()); } - ArtificialLocation Loc(IGF.getDebugScope(), IGF.IGM.DebugInfo.get(), IGF.Builder); emitRetconCoroutineEntry(IGF, fnType, buffer, llvm::Intrinsic::coro_id_retcon_once, getYieldOnceCoroutineBufferSize(IGF.IGM), diff --git a/lib/IRGen/GenMeta.cpp b/lib/IRGen/GenMeta.cpp index 62facbd61f240..5851cd73f6b48 100644 --- a/lib/IRGen/GenMeta.cpp +++ b/lib/IRGen/GenMeta.cpp @@ -6014,12 +6014,14 @@ namespace { if (!layoutStringsEnabled(IGM)) { return false; } - return !!getLayoutString() || - (IGM.Context.LangOpts.hasFeature( - Feature::LayoutStringValueWitnessesInstantiation) && - IGM.getOptions().EnableLayoutStringValueWitnessesInstantiation && - (HasDependentVWT || HasDependentMetadata) && - !isa(IGM.getTypeInfo(getLoweredType()))); + const auto &TI = IGM.getTypeInfo(getLoweredType()); + return (!!getLayoutString() || + (IGM.Context.LangOpts.hasFeature( + Feature::LayoutStringValueWitnessesInstantiation) && + IGM.getOptions().EnableLayoutStringValueWitnessesInstantiation && + (HasDependentVWT || HasDependentMetadata) && + !isa(TI))) && + TI.isCopyable(ResilienceExpansion::Maximal); } llvm::Constant *emitNominalTypeDescriptor() { @@ -6547,13 +6549,15 @@ namespace { if (!layoutStringsEnabled(IGM)) { return false; } + auto &TI = IGM.getTypeInfo(getLoweredType()); - return !!getLayoutString() || - (IGM.Context.LangOpts.hasFeature( - Feature::LayoutStringValueWitnessesInstantiation) && - IGM.getOptions().EnableLayoutStringValueWitnessesInstantiation && - (HasDependentVWT || HasDependentMetadata) && - !isa(IGM.getTypeInfo(getLoweredType()))); + return (!!getLayoutString() || + (IGM.Context.LangOpts.hasFeature( + Feature::LayoutStringValueWitnessesInstantiation) && + IGM.getOptions().EnableLayoutStringValueWitnessesInstantiation && + (HasDependentVWT || HasDependentMetadata) && + !isa(TI))) && + TI.isCopyable(ResilienceExpansion::Maximal); } llvm::Constant *emitNominalTypeDescriptor() { @@ -7852,8 +7856,10 @@ irgen::emitExtendedExistentialTypeShape(IRGenModule &IGM, // You can have a superclass with a generic parameter pack in a composition, // like `C & P` - assert(genHeader->GenericPackArguments.empty() && + if (genSig) { + assert(genHeader->GenericPackArguments.empty() && "Generic parameter packs not supported here yet"); + } return b.finishAndCreateFuture(); }, [&](llvm::GlobalVariable *var) { diff --git a/lib/IRGen/IRGenSIL.cpp b/lib/IRGen/IRGenSIL.cpp index f1c820e2c3fed..0ef5c1616f234 100644 --- a/lib/IRGen/IRGenSIL.cpp +++ b/lib/IRGen/IRGenSIL.cpp @@ -1158,12 +1158,10 @@ class IRGenSILFunction : } emitTypeMetadataRef(archetype); - } else if (auto packArchetype = dyn_cast(t)) { - emitTypeMetadataRef(packArchetype); - } else if (auto packtype = dyn_cast(t)) { + } else if (auto packType = dyn_cast(t)) { llvm::Value *Shape = emitPackShapeExpression(t); emitPackCountDebugVariable(Shape); - } else if (auto packtype = dyn_cast(t)) { + } else if (auto packType = dyn_cast(t)) { llvm::Value *Shape = emitPackShapeExpression(t); emitPackCountDebugVariable(Shape); } @@ -1212,8 +1210,13 @@ class IRGenSILFunction : SILResultInfo ErrorInfo, DebugValueInst *DbgValue); void emitPoisonDebugValueInst(DebugValueInst *i); - void emitDebugInfoForAllocStack(AllocStackInst *i, const TypeInfo &type, - llvm::Value *addr); + void emitDebugInfoBeforeAllocStack(AllocStackInst *i, + const TypeInfo &type, + DebugTypeInfo &DbgTy); + void emitDebugInfoAfterAllocStack(AllocStackInst *i, + const TypeInfo &type, + const DebugTypeInfo &DbgTy, + llvm::Value *addr); void visitAllocStackInst(AllocStackInst *i); void visitAllocPackInst(AllocPackInst *i); void visitAllocPackMetadataInst(AllocPackMetadataInst *i); @@ -1352,6 +1355,7 @@ class IRGenSILFunction : void visitTupleElementAddrInst(TupleElementAddrInst *i); void visitStructExtractInst(StructExtractInst *i); void visitStructElementAddrInst(StructElementAddrInst *i); + void visitVectorBaseAddrInst(VectorBaseAddrInst *i); void visitRefElementAddrInst(RefElementAddrInst *i); void visitRefTailAddrInst(RefTailAddrInst *i); @@ -5639,6 +5643,13 @@ void IRGenSILFunction::visitStructElementAddrInst( setLoweredAddress(i, field); } +void IRGenSILFunction::visitVectorBaseAddrInst(VectorBaseAddrInst *i) { + auto addr = getLoweredAddress(i->getVector()); + auto &ti = getTypeInfo(i->getType()); + auto result = Builder.CreateElementBitCast(addr, ti.getStorageType()); + setLoweredAddress(i, result); +} + void IRGenSILFunction::visitRefElementAddrInst(swift::RefElementAddrInst *i) { Explosion base = getLoweredExplosion(i->getOperand()); llvm::Value *value = base.claimNext(); @@ -6402,14 +6413,52 @@ void IRGenSILFunction::visitDestroyNotEscapedClosureInst( setLoweredExplosion(i, out); } -void IRGenSILFunction::emitDebugInfoForAllocStack(AllocStackInst *i, - const TypeInfo &type, - llvm::Value *addr) { +void IRGenSILFunction::emitDebugInfoBeforeAllocStack(AllocStackInst *i, + const TypeInfo &type, + DebugTypeInfo &DbgTy) { auto VarInfo = i->getVarInfo(); - if (!VarInfo) + if (!VarInfo || + !i->getDebugScope() || + i->getDebugScope()->getInlinedFunction()->isTransparent()) return; VarDecl *Decl = i->getDecl(); + + SILType SILTy; + if (auto MaybeSILTy = VarInfo->Type) { + // If there is auxiliary type info, use it + SILTy = *MaybeSILTy; + } else { + SILTy = i->getType(); + } + auto RealType = SILTy.getASTType(); + if (Decl) { + DbgTy = DebugTypeInfo::getLocalVariable(Decl, RealType, type, IGM); + } else if (i->getFunction()->isBare() && !SILTy.hasArchetype() && + !VarInfo->Name.empty()) { + DbgTy = DebugTypeInfo::getFromTypeInfo(RealType, getTypeInfo(SILTy), IGM); + } else + return; + + bindArchetypes(DbgTy.getType()); +} + +/// Do not instantiate type metadata in here, since this may allocate on-stack +/// packs which will then be cleaned up in the wrong order with respect to the +/// value stack allocation. +void IRGenSILFunction::emitDebugInfoAfterAllocStack(AllocStackInst *i, + const TypeInfo &type, + const DebugTypeInfo &DbgTy, + llvm::Value *addr) { + auto VarInfo = i->getVarInfo(); + if (!VarInfo || + !i->getDebugScope() || + i->getDebugScope()->getInlinedFunction()->isTransparent()) + return; + + VarDecl *Decl = i->getDecl(); + auto *DS = i->getDebugScope(); + // Describe the underlying alloca. This way an llvm.dbg.declare intrinsic // is used, which is valid for the entire lifetime of the alloca. if (auto *BitCast = dyn_cast(addr)) { @@ -6426,13 +6475,6 @@ void IRGenSILFunction::emitDebugInfoForAllocStack(AllocStackInst *i, (void)isTaskAlloc; } } - - auto DS = i->getDebugScope(); - if (!DS) - return; - - if (i->getDebugScope()->getInlinedFunction()->isTransparent()) - return; bool IsAnonymous = false; VarInfo->Name = getVarName(i, IsAnonymous); @@ -6467,25 +6509,15 @@ void IRGenSILFunction::emitDebugInfoForAllocStack(AllocStackInst *i, } } - SILType SILTy; - if (auto MaybeSILTy = VarInfo->Type) { - // If there is auxiliary type info, use it - SILTy = *MaybeSILTy; - } else { - SILTy = i->getType(); - } - auto RealType = SILTy.getASTType(); - DebugTypeInfo DbgTy; - if (Decl) { - DbgTy = DebugTypeInfo::getLocalVariable(Decl, RealType, type, IGM); - } else if (i->getFunction()->isBare() && !SILTy.hasArchetype() && - !VarInfo->Name.empty()) { - DbgTy = DebugTypeInfo::getFromTypeInfo(RealType, getTypeInfo(SILTy), IGM); - } else - return; + if (DbgTy.getType() && IGM.DebugInfo) { + SILType SILTy; + if (auto MaybeSILTy = VarInfo->Type) { + // If there is auxiliary type info, use it + SILTy = *MaybeSILTy; + } else { + SILTy = i->getType(); + } - bindArchetypes(DbgTy.getType()); - if (IGM.DebugInfo) { emitDebugVariableDeclaration( addr, DbgTy, SILTy, DS, i->getLoc(), *VarInfo, Indirection, AddrDbgInstrKind(i->usesMoveableValueDebugInfo())); @@ -6503,6 +6535,9 @@ void IRGenSILFunction::visitAllocStackInst(swift::AllocStackInst *i) { dbgname = getVarName(i, IsAnonymous); # endif + DebugTypeInfo DbgTy; + emitDebugInfoBeforeAllocStack(i, type, DbgTy); + auto stackAddr = type.allocateStack(*this, i->getElementType(), dbgname); setLoweredStackAddress(i, stackAddr); Address addr = stackAddr.getAddress(); @@ -6517,7 +6552,7 @@ void IRGenSILFunction::visitAllocStackInst(swift::AllocStackInst *i) { Ty->getStructOrBoundGenericStruct()) zeroInit(dyn_cast(addr.getAddress())); } - emitDebugInfoForAllocStack(i, type, addr.getAddress()); + emitDebugInfoAfterAllocStack(i, type, DbgTy, addr.getAddress()); } void IRGenSILFunction::visitAllocPackInst(swift::AllocPackInst *i) { diff --git a/lib/IRGen/MetadataRequest.cpp b/lib/IRGen/MetadataRequest.cpp index 9ace5d10a316a..f9d440e6f09d8 100644 --- a/lib/IRGen/MetadataRequest.cpp +++ b/lib/IRGen/MetadataRequest.cpp @@ -264,41 +264,6 @@ MetadataDependency MetadataDependencyCollector::finish(IRGenFunction &IGF) { return result; } -static bool usesExtendedExistentialMetadata(CanType type) { - auto layout = type.getExistentialLayout(); - // If there are parameterized protocol types that we want to - // treat as equal to unparameterized protocol types (maybe - // something like `P`?), then AST type canonicalization - // should turn them into unparameterized protocol types. If the - // structure makes it to IRGen, we have to honor that decision that - // they represent different types. - return !layout.getParameterizedProtocols().empty(); -} - -static std::optional> -usesExtendedExistentialMetadata(CanExistentialMetatypeType type) { - unsigned depth = 1; - auto cur = type.getInstanceType(); - while (auto metatype = dyn_cast(cur)) { - cur = metatype.getInstanceType(); - depth++; - } - - // The only existential types that don't currently use ExistentialType - // are Any and AnyObject, which don't use extended metadata. - if (usesExtendedExistentialMetadata(cur)) { - // HACK: The AST for an existential metatype of a (parameterized) protocol - // still directly wraps the existential type as its instance, which means - // we need to reconstitute the enclosing ExistentialType. - assert(cur->isExistentialType()); - if (!cur->is()) { - cur = ExistentialType::get(cur)->getCanonicalType(); - } - return std::make_pair(cast(cur), depth); - } - return std::nullopt; -} - llvm::Constant *IRGenModule::getAddrOfStringForMetadataRef( StringRef symbolName, unsigned alignment, @@ -1998,7 +1963,7 @@ namespace { // Existential metatypes for extended existentials don't use // ExistentialMetatypeMetadata. - if (usesExtendedExistentialMetadata(type)) { + if (type->getExistentialLayout().needsExtendedShape()) { auto metadata = emitExtendedExistentialTypeMetadata(type); return setLocal(type, MetadataResponse::forComplete(metadata)); } @@ -3110,8 +3075,8 @@ static bool shouldAccessByMangledName(IRGenModule &IGM, CanType type) { void visitExistentialMetatypeType(CanExistentialMetatypeType meta) { // Extended existential metatypes just emit a different shape // and don't do any wrapping. - if (auto typeAndDepth = usesExtendedExistentialMetadata(meta)) { - return visit(typeAndDepth.first); + if (meta->getExistentialLayout().needsExtendedShape()) { + // return visit(unwrapExistentialMetatype(meta)); } // The number of accesses turns out the same as the instance type, diff --git a/lib/Parse/ParseDecl.cpp b/lib/Parse/ParseDecl.cpp index 2294a70f66fbf..6f18c4f6429a0 100644 --- a/lib/Parse/ParseDecl.cpp +++ b/lib/Parse/ParseDecl.cpp @@ -3773,6 +3773,25 @@ ParserStatus Parser::parseNewDeclAttribute(DeclAttributes &Attributes, } break; } + case DeclAttrKind::InheritActorContext: { + AttrRange = Loc; + std::optional Modifier( + InheritActorContextModifier::None); + Modifier = parseSingleAttrOption( + *this, Loc, AttrRange, AttrName, DK, + {{Context.Id_always, InheritActorContextModifier::Always}}, *Modifier, + ParameterizedDeclAttributeKind::InheritActorContext); + if (!Modifier) { + return makeParserSuccess(); + } + + if (!DiscardAttribute) { + Attributes.add(new (Context) InheritActorContextAttr( + AtLoc, AttrRange, *Modifier, /*implicit=*/false)); + } + + break; + } case DeclAttrKind::MacroRole: { auto syntax = (AttrName == "freestanding" ? MacroSyntax::Freestanding : MacroSyntax::Attached); @@ -9009,7 +9028,7 @@ Parser::parseAbstractFunctionBodyDelayed(AbstractFunctionDecl *AFD) { auto bodyRange = AFD->getBodySourceRange(); auto BeginParserPosition = getParserPosition(bodyRange.Start, /*previousLoc*/ SourceLoc()); - auto EndLexerState = L->getStateForEndOfTokenLoc(AFD->getEndLoc()); + auto EndLexerState = L->getStateForEndOfTokenLoc(bodyRange.End); // ParserPositionRAII needs a primed parser to restore to. if (Tok.is(tok::NUM_TOKENS)) diff --git a/lib/Parse/ParseExpr.cpp b/lib/Parse/ParseExpr.cpp index 13ce47b55b684..6b0ffdac82f14 100644 --- a/lib/Parse/ParseExpr.cpp +++ b/lib/Parse/ParseExpr.cpp @@ -421,12 +421,14 @@ ParserResult Parser::parseExprSequenceElement(Diag<> message, if (Tok.isContextualKeyword("unsafe") && !(peekToken().isAtStartOfLine() || - peekToken().isAny(tok::r_paren, tok::r_brace, tok::r_square, - tok::equal, tok::colon, tok::comma, tok::eof) || + peekToken().isAny(tok::r_paren, tok::r_brace, tok::r_square, tok::equal, + tok::colon, tok::comma, tok::eof) || (isExprBasic && peekToken().is(tok::l_brace)) || peekToken().is(tok::period) || (peekToken().isAny(tok::l_paren, tok::l_square) && - peekToken().getRange().getStart() == Tok.getRange().getEnd()))) { + peekToken().getRange().getStart() == Tok.getRange().getEnd()) || + peekToken().isBinaryOperatorLike() || + peekToken().isPostfixOperatorLike())) { Tok.setKind(tok::contextual_keyword); SourceLoc unsafeLoc = consumeToken(); ParserResult sub = @@ -3637,7 +3639,7 @@ Parser::parseExprCollectionElement(std::optional &isDictionary) { } else { diagnose(Tok, diag::expected_colon_in_dictionary_literal); Value = makeParserResult(makeParserError(), - new (Context) ErrorExpr(SourceRange())); + new (Context) ErrorExpr(PreviousLoc)); } // Make a tuple of Key Value pair. diff --git a/lib/PrintAsClang/DeclAndTypePrinter.cpp b/lib/PrintAsClang/DeclAndTypePrinter.cpp index 3faea40cab102..771782096e88e 100644 --- a/lib/PrintAsClang/DeclAndTypePrinter.cpp +++ b/lib/PrintAsClang/DeclAndTypePrinter.cpp @@ -2289,6 +2289,14 @@ class DeclAndTypePrinter::Implementation return false; } + std::optional + getKnownType(const TypeDecl *typeDecl) { + if (outputLang == OutputLanguageMode::C) + return owningPrinter.typeMapping.getKnownCTypeInfo(typeDecl); + + return owningPrinter.typeMapping.getKnownObjCTypeInfo(typeDecl); + } + /// If \p typeDecl is one of the standard library types used to map in Clang /// primitives and basic types, print out the appropriate spelling and /// return true. @@ -2297,8 +2305,7 @@ class DeclAndTypePrinter::Implementation /// for interfacing with C and Objective-C. bool printIfKnownSimpleType(const TypeDecl *typeDecl, std::optional optionalKind) { - auto knownTypeInfo = - owningPrinter.typeMapping.getKnownObjCTypeInfo(typeDecl); + auto knownTypeInfo = getKnownType(typeDecl); if (!knownTypeInfo) return false; os << knownTypeInfo->name; @@ -2999,6 +3006,22 @@ bool DeclAndTypePrinter::shouldInclude(const ValueDecl *VD) { return false; } + // In C output mode print only the C variant `@cdecl` (no `@_cdecl`), + // while in other modes print only `@_cdecl`. + std::optional cdeclKind = std::nullopt; + if (auto *FD = dyn_cast(VD)) + cdeclKind = FD->getCDeclKind(); + if (cdeclKind && + (*cdeclKind == ForeignLanguage::C) != + (outputLang == OutputLanguageMode::C)) + return false; + + // C output mode only accepts @cdecl functions. + if (outputLang == OutputLanguageMode::C && + !cdeclKind) { + return false; + } + if (VD->getAttrs().hasAttribute()) return false; diff --git a/lib/PrintAsClang/ModuleContentsWriter.cpp b/lib/PrintAsClang/ModuleContentsWriter.cpp index ef164898bbaed..be886fa13667d 100644 --- a/lib/PrintAsClang/ModuleContentsWriter.cpp +++ b/lib/PrintAsClang/ModuleContentsWriter.cpp @@ -1118,6 +1118,17 @@ void swift::printModuleContentsAsObjC( .write(); } +void swift::printModuleContentsAsC( + raw_ostream &os, llvm::SmallPtrSetImpl &imports, + ModuleDecl &M, SwiftToClangInteropContext &interopContext) { + llvm::raw_null_ostream prologueOS; + llvm::StringSet<> exposedModules; + ModuleWriter(os, prologueOS, imports, M, interopContext, getRequiredAccess(M), + /*requiresExposedAttribute=*/false, exposedModules, + OutputLanguageMode::C) + .write(); +} + EmittedClangHeaderDependencyInfo swift::printModuleContentsAsCxx( raw_ostream &os, ModuleDecl &M, SwiftToClangInteropContext &interopContext, bool requiresExposedAttribute, llvm::StringSet<> &exposedModules) { diff --git a/lib/PrintAsClang/ModuleContentsWriter.h b/lib/PrintAsClang/ModuleContentsWriter.h index f6a175fc4b6e4..0e7edca689caa 100644 --- a/lib/PrintAsClang/ModuleContentsWriter.h +++ b/lib/PrintAsClang/ModuleContentsWriter.h @@ -37,6 +37,11 @@ void printModuleContentsAsObjC(raw_ostream &os, ModuleDecl &M, SwiftToClangInteropContext &interopContext); +void printModuleContentsAsC(raw_ostream &os, + llvm::SmallPtrSetImpl &imports, + ModuleDecl &M, + SwiftToClangInteropContext &interopContext); + struct EmittedClangHeaderDependencyInfo { /// The set of imported modules used by this module. SmallPtrSet imports; diff --git a/lib/PrintAsClang/OutputLanguageMode.h b/lib/PrintAsClang/OutputLanguageMode.h index 5828aa0306239..b39c625c044a1 100644 --- a/lib/PrintAsClang/OutputLanguageMode.h +++ b/lib/PrintAsClang/OutputLanguageMode.h @@ -15,7 +15,7 @@ namespace swift { -enum class OutputLanguageMode { ObjC, Cxx }; +enum class OutputLanguageMode { ObjC, Cxx, C }; } // end namespace swift diff --git a/lib/PrintAsClang/PrintAsClang.cpp b/lib/PrintAsClang/PrintAsClang.cpp index 0cfdf1c389708..9ae35dd83a35f 100644 --- a/lib/PrintAsClang/PrintAsClang.cpp +++ b/lib/PrintAsClang/PrintAsClang.cpp @@ -58,6 +58,17 @@ static void emitObjCConditional(raw_ostream &out, out << "#endif\n"; } +static void emitExternC(raw_ostream &out, + llvm::function_ref cCase) { + emitCxxConditional(out, [&] { + out << "extern \"C\" {\n"; + }); + cCase(); + emitCxxConditional(out, [&] { + out << "} // extern \"C\"\n"; + }); +} + static void writePtrauthPrologue(raw_ostream &os, ASTContext &ctx) { emitCxxConditional(os, [&]() { ClangSyntaxPrinter(ctx, os).printIgnoredDiagnosticBlock( @@ -207,6 +218,21 @@ static void writePrologue(raw_ostream &out, ASTContext &ctx, static_assert(SWIFT_MAX_IMPORTED_SIMD_ELEMENTS == 4, "need to add SIMD typedefs here if max elements is increased"); + + if (ctx.LangOpts.hasFeature(Feature::CDecl)) { + // For C compilers which don’t support nullability attributes, ignore them; + // for ones which do, suppress warnings about them being an extension. + out << "#if !__has_feature(nullability)\n" + "# define _Nonnull\n" + "# define _Nullable\n" + "# define _Null_unspecified\n" + "#elif !defined(__OBJC__)\n" + "# pragma clang diagnostic ignored \"-Wnullability-extension\"\n" + "#endif\n" + "#if !__has_feature(nullability_nullable_result)\n" + "# define _Nullable_result _Nullable\n" + "#endif\n"; + } } static int compareImportModulesByName(const ImportModuleTy *left, @@ -577,12 +603,21 @@ bool swift::printAsClangHeader(raw_ostream &os, ModuleDecl *M, llvm::PrettyStackTraceString trace("While generating Clang header"); SwiftToClangInteropContext interopContext(*M, irGenOpts); + writePrologue(os, M->getASTContext(), computeMacroGuard(M)); + + // C content (@cdecl) + if (M->getASTContext().LangOpts.hasFeature(Feature::CDecl)) { + SmallPtrSet imports; + emitExternC(os, [&] { + printModuleContentsAsC(os, imports, *M, interopContext); + }); + } + // Objective-C content SmallPtrSet imports; std::string objcModuleContentsBuf; llvm::raw_string_ostream objcModuleContents{objcModuleContentsBuf}; printModuleContentsAsObjC(objcModuleContents, imports, *M, interopContext); - writePrologue(os, M->getASTContext(), computeMacroGuard(M)); emitObjCConditional(os, [&] { llvm::StringMap exposedModuleHeaderNames; writeImports(os, imports, *M, bridgingHeader, frontendOpts, @@ -591,6 +626,8 @@ bool swift::printAsClangHeader(raw_ostream &os, ModuleDecl *M, writePostImportPrologue(os, *M); emitObjCConditional(os, [&] { os << "\n" << objcModuleContents.str(); }); writeObjCEpilogue(os); + + // C++ content emitCxxConditional(os, [&] { // FIXME: Expose Swift with @expose by default. bool enableCxx = frontendOpts.ClangHeaderExposedDecls.has_value() || diff --git a/lib/SIL/IR/OperandOwnership.cpp b/lib/SIL/IR/OperandOwnership.cpp index 5765c57f9f66c..ffb4729be8959 100644 --- a/lib/SIL/IR/OperandOwnership.cpp +++ b/lib/SIL/IR/OperandOwnership.cpp @@ -171,6 +171,7 @@ OPERAND_OWNERSHIP(TrivialUse, DestroyAddr) OPERAND_OWNERSHIP(TrivialUse, EndAccess) OPERAND_OWNERSHIP(TrivialUse, EndUnpairedAccess) OPERAND_OWNERSHIP(TrivialUse, GetAsyncContinuationAddr) +OPERAND_OWNERSHIP(TrivialUse, VectorBaseAddr) OPERAND_OWNERSHIP(TrivialUse, IndexAddr) OPERAND_OWNERSHIP(TrivialUse, IndexRawPointer) OPERAND_OWNERSHIP(TrivialUse, InitBlockStorageHeader) diff --git a/lib/SIL/IR/SILPrinter.cpp b/lib/SIL/IR/SILPrinter.cpp index 5b87a78f9b174..35e57ae916a81 100644 --- a/lib/SIL/IR/SILPrinter.cpp +++ b/lib/SIL/IR/SILPrinter.cpp @@ -2500,6 +2500,9 @@ class SILPrinter : public SILInstructionVisitor { printFullContext(EI->getField()->getDeclContext(), PrintState.OS); *this << EI->getField()->getName().get(); } + void visitVectorBaseAddrInst(VectorBaseAddrInst *vbai) { + *this << getIDAndType(vbai->getVector()); + } void visitRefElementAddrInst(RefElementAddrInst *EI) { *this << (EI->isImmutable() ? "[immutable] " : "") << getIDAndType(EI->getOperand()) << ", #"; diff --git a/lib/SIL/IR/TypeLowering.cpp b/lib/SIL/IR/TypeLowering.cpp index 2b9c26ea8031f..c8a91866b985f 100644 --- a/lib/SIL/IR/TypeLowering.cpp +++ b/lib/SIL/IR/TypeLowering.cpp @@ -4676,6 +4676,24 @@ TypeConverter::getLoweredLocalCaptures(SILDeclRef fn) { collectConstantCaptures(fn); + // @_inheritActorContext(always) attribute allows implicit + // capture of isolation parameter from the context. This + // cannot be done as part of computing captures because + // isolation is not available at that point because it in + // turn depends on captures sometimes. + if (auto *closure = fn.getClosureExpr()) { + if (closure->alwaysInheritsActorContext()) { + auto isolation = closure->getActorIsolation(); + if (isolation.isActorInstanceIsolated()) { + if (auto *var = isolation.getActorInstance()) { + recordCapture(CapturedValue(var, /*flags=*/0, SourceLoc())); + } else if (auto *actorExpr = isolation.getActorInstanceExpr()) { + recordCapture(CapturedValue(actorExpr, /*flags=*/0)); + } + } + } + } + SmallVector resultingCaptures; for (auto capturePair : varCaptures) { resultingCaptures.push_back(capturePair.second); diff --git a/lib/SIL/IR/ValueOwnership.cpp b/lib/SIL/IR/ValueOwnership.cpp index 77d5c6fbcf9fb..8a7da389229e7 100644 --- a/lib/SIL/IR/ValueOwnership.cpp +++ b/lib/SIL/IR/ValueOwnership.cpp @@ -125,6 +125,7 @@ CONSTANT_OWNERSHIP_INST(None, PreviousDynamicFunctionRef) CONSTANT_OWNERSHIP_INST(None, GlobalAddr) CONSTANT_OWNERSHIP_INST(None, BaseAddrForOffset) CONSTANT_OWNERSHIP_INST(None, HasSymbol) +CONSTANT_OWNERSHIP_INST(None, VectorBaseAddr) CONSTANT_OWNERSHIP_INST(None, IndexAddr) CONSTANT_OWNERSHIP_INST(None, IndexRawPointer) CONSTANT_OWNERSHIP_INST(None, InitEnumDataAddr) diff --git a/lib/SIL/Parser/ParseSIL.cpp b/lib/SIL/Parser/ParseSIL.cpp index bc7845144f084..741dfe45b4836 100644 --- a/lib/SIL/Parser/ParseSIL.cpp +++ b/lib/SIL/Parser/ParseSIL.cpp @@ -5891,6 +5891,12 @@ bool SILParser::parseSpecificSILInstruction(SILBuilder &B, ResultVal = B.createIndexAddr(InstLoc, Val, IndexVal, needsStackProtection); break; } + case SILInstructionKind::VectorBaseAddrInst: { + if (parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B)) + return true; + ResultVal = B.createVectorBaseAddr(InstLoc, Val); + break; + } case SILInstructionKind::TailAddrInst: { SILValue IndexVal; SILType ResultObjTy; diff --git a/lib/SIL/Utils/InstructionUtils.cpp b/lib/SIL/Utils/InstructionUtils.cpp index a69056caea38c..19005d5e8220b 100644 --- a/lib/SIL/Utils/InstructionUtils.cpp +++ b/lib/SIL/Utils/InstructionUtils.cpp @@ -581,6 +581,7 @@ RuntimeEffect swift::getRuntimeEffect(SILInstruction *inst, SILType &impactType) case SILInstructionKind::TupleExtractInst: case SILInstructionKind::StructInst: case SILInstructionKind::StructExtractInst: + case SILInstructionKind::VectorBaseAddrInst: case SILInstructionKind::RefElementAddrInst: case SILInstructionKind::EnumInst: case SILInstructionKind::UncheckedEnumDataInst: diff --git a/lib/SIL/Verifier/SILOwnershipVerifier.cpp b/lib/SIL/Verifier/SILOwnershipVerifier.cpp index 1c8cd02b5a30d..9ada227b9b268 100644 --- a/lib/SIL/Verifier/SILOwnershipVerifier.cpp +++ b/lib/SIL/Verifier/SILOwnershipVerifier.cpp @@ -20,6 +20,7 @@ #include "swift/AST/Decl.h" #include "swift/AST/GenericEnvironment.h" #include "swift/AST/Module.h" +#include "swift/AST/SemanticAttrs.h" #include "swift/AST/Types.h" #include "swift/Basic/Assertions.h" #include "swift/Basic/Range.h" @@ -866,6 +867,14 @@ void SILInstruction::verifyOperandOwnership( return; #endif + if (getModule().getOptions().VerifyNone) { + return; + } + + if (getFunction()->hasSemanticsAttr(semantics::NO_SIL_VERIFICATION)) { + return; + } + // If SILOwnership is not enabled, do not perform verification. if (!getModule().getOptions().VerifySILOwnership) return; diff --git a/lib/SIL/Verifier/SILVerifier.cpp b/lib/SIL/Verifier/SILVerifier.cpp index bfb895052b21e..52015af926082 100644 --- a/lib/SIL/Verifier/SILVerifier.cpp +++ b/lib/SIL/Verifier/SILVerifier.cpp @@ -35,6 +35,7 @@ #include "swift/SIL/DebugUtils.h" #include "swift/SIL/Dominance.h" #include "swift/SIL/DynamicCasts.h" +#include "swift/SIL/InstructionUtils.h" #include "swift/SIL/MemAccessUtils.h" #include "swift/SIL/OwnershipLiveness.h" #include "swift/SIL/OwnershipUtils.h" @@ -572,6 +573,11 @@ void verifyKeyPathComponent(SILModule &M, /// open_existential_addr. We should expand it as needed. struct ImmutableAddressUseVerifier { SmallVector worklist; + bool ignoreDestroys; + bool defaultIsMutating; + + ImmutableAddressUseVerifier(bool ignoreDestroys = false, bool defaultIsMutating = false) + : ignoreDestroys(ignoreDestroys), defaultIsMutating(defaultIsMutating) {} bool isConsumingOrMutatingArgumentConvention(SILArgumentConvention conv) { switch (conv) { @@ -704,10 +710,9 @@ struct ImmutableAddressUseVerifier { } } - // Otherwise this is a builtin that we are not expecting to see, so bail - // and assert. - llvm::errs() << "Unhandled, unexpected builtin instruction: " << *inst; - llvm_unreachable("invoking standard assertion failure"); + // Otherwise this is a builtin that we are not expecting to see. + if (defaultIsMutating) + return true; break; } case SILInstructionKind::MarkDependenceInst: @@ -775,7 +780,9 @@ struct ImmutableAddressUseVerifier { else break; case SILInstructionKind::DestroyAddrInst: - return true; + if (!ignoreDestroys) + return true; + break; case SILInstructionKind::UpcastInst: case SILInstructionKind::UncheckedAddrCastInst: { if (isAddrCastToNonConsuming(cast(inst))) { @@ -821,6 +828,7 @@ struct ImmutableAddressUseVerifier { LLVM_FALLTHROUGH; case SILInstructionKind::MoveOnlyWrapperToCopyableAddrInst: case SILInstructionKind::CopyableToMoveOnlyWrapperAddrInst: + case SILInstructionKind::VectorBaseAddrInst: case SILInstructionKind::StructElementAddrInst: case SILInstructionKind::TupleElementAddrInst: case SILInstructionKind::IndexAddrInst: @@ -841,9 +849,7 @@ struct ImmutableAddressUseVerifier { } break; } - llvm::errs() << "Unhandled, unexpected instruction: " << *inst; - llvm_unreachable("invoking standard assertion failure"); - break; + return true; } case SILInstructionKind::TuplePackElementAddrInst: { if (&cast(inst)->getOperandRef( @@ -865,8 +871,8 @@ struct ImmutableAddressUseVerifier { return false; } default: - llvm::errs() << "Unhandled, unexpected instruction: " << *inst; - llvm_unreachable("invoking standard assertion failure"); + if (defaultIsMutating) + return true; break; } } @@ -7385,6 +7391,11 @@ class SILVerifier : public SILVerifierBase { #undef require #undef requireObjectType +bool swift::isIndirectArgumentMutated(SILFunctionArgument *arg, bool ignoreDestroys, + bool defaultIsMutating) { + return ImmutableAddressUseVerifier(ignoreDestroys, defaultIsMutating).isMutatingOrConsuming(arg); +} + //===----------------------------------------------------------------------===// // Out of Line Verifier Run Functions //===----------------------------------------------------------------------===// @@ -7419,6 +7430,10 @@ void SILFunction::verify(CalleeCache *calleeCache, if (!verificationEnabled(getModule())) return; + if (hasSemanticsAttr(semantics::NO_SIL_VERIFICATION)) { + return; + } + // Please put all checks in visitSILFunction in SILVerifier, not here. This // ensures that the pretty stack trace in the verifier is included with the // back trace when the verifier crashes. diff --git a/lib/SILGen/SILGen.cpp b/lib/SILGen/SILGen.cpp index f0d201afab947..b2c2af37f6ed4 100644 --- a/lib/SILGen/SILGen.cpp +++ b/lib/SILGen/SILGen.cpp @@ -515,7 +515,7 @@ Type SILGenModule::getConfiguredExecutorFactory() { auto &ctx = getASTContext(); // Look in the main module for a typealias - Type factory = ctx.getNamedSwiftType(ctx.MainModule, "DefaultExecutorFactory"); + Type factory = ctx.getNamedSwiftType(ctx.MainModule, "_DefaultExecutorFactory"); // If we don't find it, fall back to _Concurrency.PlatformExecutorFactory if (!factory) @@ -531,7 +531,7 @@ Type SILGenModule::getDefaultExecutorFactory() { if (!module) return Type(); - return ctx.getNamedSwiftType(module, "DefaultExecutorFactory"); + return ctx.getNamedSwiftType(module, "_DefaultExecutorFactory"); } ProtocolConformance *SILGenModule::getNSErrorConformanceToError() { diff --git a/lib/SILGen/SILGenBuiltin.cpp b/lib/SILGen/SILGenBuiltin.cpp index e02a87385ea74..7ae2a7058ce15 100644 --- a/lib/SILGen/SILGenBuiltin.cpp +++ b/lib/SILGen/SILGenBuiltin.cpp @@ -477,6 +477,29 @@ static ManagedValue emitBuiltinUnprotectedAddressOf(SILGenFunction &SGF, /*stackProtected=*/ false); } +// Like `tryEmitAddressableParameterAsAddress`, but also handles struct element projections. +static SILValue emitAddressOf(Expr *e, SILGenFunction &SGF, SILLocation loc) { + + if (auto *memberRef = dyn_cast(e)) { + VarDecl *fieldDecl = dyn_cast(memberRef->getDecl().getDecl()); + if (!fieldDecl) + return SILValue(); + SILValue addr = emitAddressOf(memberRef->getBase(), SGF, loc); + if (!addr) + return SILValue(); + if (addr->getType().getStructOrBoundGenericStruct() != fieldDecl->getDeclContext()) + return SILValue(); + return SGF.B.createStructElementAddr(loc, addr, fieldDecl); + } + + if (auto addressableAddr = SGF.tryEmitAddressableParameterAsAddress( + ArgumentSource(e), + ValueOwnership::Shared)) { + return addressableAddr.getValue(); + } + return SILValue(); +} + /// Specialized emitter for Builtin.addressOfBorrow. static ManagedValue emitBuiltinAddressOfBorrowBuiltins(SILGenFunction &SGF, SILLocation loc, @@ -491,15 +514,11 @@ static ManagedValue emitBuiltinAddressOfBorrowBuiltins(SILGenFunction &SGF, auto argument = (*argsOrError)[0]; - SILValue addr; // Try to borrow the argument at +0 indirect. // If the argument is a reference to a borrowed addressable parameter, then // use that parameter's stable address. - if (auto addressableAddr = SGF.tryEmitAddressableParameterAsAddress( - ArgumentSource(argument), - ValueOwnership::Shared)) { - addr = addressableAddr.getValue(); - } else { + SILValue addr = emitAddressOf(argument, SGF, loc); + if (!addr) { // We otherwise only support the builtin applied to values that // are naturally emitted borrowed in memory. (But it would probably be good // to phase this out since it's not really well-defined how long diff --git a/lib/SILGen/SILGenExpr.cpp b/lib/SILGen/SILGenExpr.cpp index ca38704b70c77..187adea7d4a4e 100644 --- a/lib/SILGen/SILGenExpr.cpp +++ b/lib/SILGen/SILGenExpr.cpp @@ -4992,7 +4992,7 @@ static RValue emitInlineArrayLiteral(SILGenFunction &SGF, CollectionExpr *E, SGFContext C) { ArgumentScope scope(SGF, E); - auto iaTy = E->getType()->castTo(); + auto iaTy = E->getType()->castTo(); auto loweredIAType = SGF.getLoweredType(iaTy); // If this is an empty InlineArray literal and it's loadable, then create an @@ -5007,9 +5007,19 @@ static RValue emitInlineArrayLiteral(SILGenFunction &SGF, CollectionExpr *E, auto elementType = iaTy->getGenericArgs()[1]->getCanonicalType(); auto &eltTL = SGF.getTypeLowering(AbstractionPattern::getOpaque(), elementType); + + auto *arrayDecl = cast(iaTy->getDecl()); + VarDecl *storageProperty = nullptr; + for (VarDecl *property : arrayDecl->getStoredProperties()) { + if ((property->getTypeInContext()->is())) { + storageProperty = property; + break; + } + } + SILValue alloc = SGF.emitTemporaryAllocation(E, loweredIAType); - SILValue addr = SGF.B.createUncheckedAddrCast(E, alloc, - eltTL.getLoweredType().getAddressType()); + SILValue storage = SGF.B.createStructElementAddr(E, alloc, storageProperty); + SILValue addr = SGF.B.createVectorBaseAddr(E, storage); // Cleanups for any elements that have been initialized so far. SmallVector cleanups; diff --git a/lib/SILOptimizer/Analysis/RegionAnalysis.cpp b/lib/SILOptimizer/Analysis/RegionAnalysis.cpp index 454deacf0f460..12e3acb12fb68 100644 --- a/lib/SILOptimizer/Analysis/RegionAnalysis.cpp +++ b/lib/SILOptimizer/Analysis/RegionAnalysis.cpp @@ -3411,6 +3411,7 @@ CONSTANT_TRANSLATION(InitExistentialValueInst, LookThrough) CONSTANT_TRANSLATION(UncheckedEnumDataInst, LookThrough) CONSTANT_TRANSLATION(TupleElementAddrInst, LookThrough) CONSTANT_TRANSLATION(StructElementAddrInst, LookThrough) +CONSTANT_TRANSLATION(VectorBaseAddrInst, LookThrough) CONSTANT_TRANSLATION(UncheckedTakeEnumDataAddrInst, LookThrough) //===--- diff --git a/lib/SILOptimizer/Analysis/SimplifyInstruction.cpp b/lib/SILOptimizer/Analysis/SimplifyInstruction.cpp index e5881fb9f2895..ca8b1b7a501ff 100644 --- a/lib/SILOptimizer/Analysis/SimplifyInstruction.cpp +++ b/lib/SILOptimizer/Analysis/SimplifyInstruction.cpp @@ -52,7 +52,6 @@ namespace { SILValue visitUnconditionalCheckedCastInst(UnconditionalCheckedCastInst *UCCI); SILValue visitUncheckedRefCastInst(UncheckedRefCastInst *OPRI); - SILValue visitUncheckedAddrCastInst(UncheckedAddrCastInst *UACI); SILValue visitStructInst(StructInst *SI); SILValue visitTupleInst(TupleInst *SI); SILValue visitBuiltinInst(BuiltinInst *AI); @@ -357,21 +356,6 @@ visitUncheckedRefCastInst(UncheckedRefCastInst *OPRI) { return simplifyDeadCast(OPRI); } -SILValue -InstSimplifier:: -visitUncheckedAddrCastInst(UncheckedAddrCastInst *UACI) { - // (unchecked-addr-cast Y->X (unchecked-addr-cast x X->Y)) -> x - if (auto *OtherUACI = dyn_cast(&*UACI->getOperand())) - if (OtherUACI->getOperand()->getType() == UACI->getType()) - return OtherUACI->getOperand(); - - // (unchecked-addr-cast X->X x) -> x - if (UACI->getOperand()->getType() == UACI->getType()) - return UACI->getOperand(); - - return SILValue(); -} - SILValue InstSimplifier::visitUpcastInst(UpcastInst *UI) { // (upcast Y->X (unchecked-ref-cast x X->Y)) -> x if (auto *URCI = dyn_cast(UI->getOperand())) diff --git a/lib/SILOptimizer/FunctionSignatureTransforms/OwnedToGuaranteedTransform.cpp b/lib/SILOptimizer/FunctionSignatureTransforms/OwnedToGuaranteedTransform.cpp index 0f9d449925eb5..268170041ec25 100644 --- a/lib/SILOptimizer/FunctionSignatureTransforms/OwnedToGuaranteedTransform.cpp +++ b/lib/SILOptimizer/FunctionSignatureTransforms/OwnedToGuaranteedTransform.cpp @@ -88,6 +88,15 @@ bool FunctionSignatureTransform::OwnedToGuaranteedAnalyzeParameters() { continue; } + // Make sure that an @in argument is not mutated otherwise than destroyed, + // because an @in_guaranteed argument must not be mutated. + if (A.hasConvention(SILArgumentConvention::Indirect_In) && + // With opaque values, @in arguments can have non-address types. + A.Arg->getType().isAddress() && + isIndirectArgumentMutated(A.Arg, /*ignoreDestroys=*/ true, /*defaultIsMutating=*/true)) { + continue; + } + // See if we can find a ref count equivalent strong_release or release_value // at the end of this function if our argument is an @owned parameter. // See if we can find a destroy_addr at the end of this function if our diff --git a/lib/SILOptimizer/Mandatory/ConsumeOperatorCopyableAddressesChecker.cpp b/lib/SILOptimizer/Mandatory/ConsumeOperatorCopyableAddressesChecker.cpp index 882a543d1c58f..cbd794f7504e0 100644 --- a/lib/SILOptimizer/Mandatory/ConsumeOperatorCopyableAddressesChecker.cpp +++ b/lib/SILOptimizer/Mandatory/ConsumeOperatorCopyableAddressesChecker.cpp @@ -1340,11 +1340,11 @@ bool GatherLexicalLifetimeUseVisitor::visitUse(Operand *op, return true; } - // Then see if we have a inout_aliasable full apply site use. In that case, we - // are going to try and extend move checking into the partial apply using - // cloning to eliminate destroys or reinits. if (auto fas = FullApplySite::isa(op->getUser())) { - if (stripAccessMarkers(op->get()) != useState.address) { + auto convention = fas.getCaptureConvention(*op); + // Bail on non-inout apply uses of fields. + if (convention != SILArgumentConvention::Indirect_Inout && + stripAccessMarkers(op->get()) != useState.address) { LLVM_DEBUG( llvm::dbgs() << "!!! Error! Found consuming closure use not on base address: " @@ -1352,8 +1352,10 @@ bool GatherLexicalLifetimeUseVisitor::visitUse(Operand *op, return false; } - if (fas.getCaptureConvention(*op) == - SILArgumentConvention::Indirect_InoutAliasable) { + // Then see if we have an inout_aliasable full apply site use. In that case, + // we are going to try and extend move checking into the partial apply + // using cloning to eliminate destroys or reinits. + if (convention == SILArgumentConvention::Indirect_InoutAliasable) { // If we don't find the function, we can't handle this, so bail. auto *func = fas.getCalleeFunction(); if (!func || !func->isDefer()) diff --git a/lib/SILOptimizer/SILCombiner/SILCombine.cpp b/lib/SILOptimizer/SILCombiner/SILCombine.cpp index 459d32f468266..f79c6d0eedf1b 100644 --- a/lib/SILOptimizer/SILCombiner/SILCombine.cpp +++ b/lib/SILOptimizer/SILCombiner/SILCombine.cpp @@ -694,11 +694,13 @@ SILTransform *swift::createSILCombine() { // SwiftFunctionPassContext //===----------------------------------------------------------------------===// -void SwiftPassInvocation::eraseInstruction(SILInstruction *inst) { +void SwiftPassInvocation::eraseInstruction(SILInstruction *inst, bool salvageDebugInfo) { if (silCombiner) { - silCombiner->eraseInstFromFunction(*inst); + silCombiner->eraseInstFromFunction(*inst, /*addOperandsToWorklist=*/ true, salvageDebugInfo); } else { - swift::salvageDebugInfo(inst); + if (salvageDebugInfo) { + swift::salvageDebugInfo(inst); + } if (inst->isStaticInitializerInst()) { inst->getParent()->erase(inst, *getPassManager()->getModule()); } else { diff --git a/lib/SILOptimizer/SILCombiner/SILCombiner.h b/lib/SILOptimizer/SILCombiner/SILCombiner.h index 5f5de2e0bb1bc..f1c452b12073c 100644 --- a/lib/SILOptimizer/SILCombiner/SILCombiner.h +++ b/lib/SILOptimizer/SILCombiner/SILCombiner.h @@ -220,8 +220,10 @@ class SILCombiner : // by this method. SILInstruction *eraseInstFromFunction(SILInstruction &I, SILBasicBlock::iterator &InstIter, - bool AddOperandsToWorklist = true) { - Worklist.eraseInstFromFunction(I, InstIter, AddOperandsToWorklist); + bool AddOperandsToWorklist = true, + bool salvageDebugInfo = true) { + Worklist.eraseInstFromFunction(I, InstIter, AddOperandsToWorklist, + salvageDebugInfo); MadeChange = true; // Dummy return, so the caller doesn't need to explicitly return nullptr. return nullptr; @@ -232,9 +234,10 @@ class SILCombiner : void eraseInstIncludingUsers(SILInstruction *inst); SILInstruction *eraseInstFromFunction(SILInstruction &I, - bool AddOperandsToWorklist = true) { + bool AddOperandsToWorklist = true, + bool salvageDebugInfo = true) { SILBasicBlock::iterator nullIter; - return eraseInstFromFunction(I, nullIter, AddOperandsToWorklist); + return eraseInstFromFunction(I, nullIter, AddOperandsToWorklist, salvageDebugInfo); } void addInitialGroup(ArrayRef List) { @@ -260,7 +263,6 @@ class SILCombiner : bool optimizeStackAllocatedEnum(AllocStackInst *AS); SILInstruction *visitSwitchEnumAddrInst(SwitchEnumAddrInst *SEAI); SILInstruction *visitInjectEnumAddrInst(InjectEnumAddrInst *IEAI); - SILInstruction *visitUncheckedAddrCastInst(UncheckedAddrCastInst *UADCI); SILInstruction *visitUncheckedRefCastInst(UncheckedRefCastInst *URCI); SILInstruction *visitEndCOWMutationInst(EndCOWMutationInst *URCI); SILInstruction *visitUncheckedRefCastAddrInst(UncheckedRefCastAddrInst *URCI); diff --git a/lib/SILOptimizer/SILCombiner/SILCombinerCastVisitors.cpp b/lib/SILOptimizer/SILCombiner/SILCombinerCastVisitors.cpp index 9e28834bb1c27..09f14c969e1a4 100644 --- a/lib/SILOptimizer/SILCombiner/SILCombinerCastVisitors.cpp +++ b/lib/SILOptimizer/SILCombiner/SILCombinerCastVisitors.cpp @@ -219,23 +219,6 @@ SILInstruction *SILCombiner::visitUpcastInst(UpcastInst *uci) { return nullptr; } -SILInstruction * -SILCombiner::visitUncheckedAddrCastInst(UncheckedAddrCastInst *UADCI) { - // These are always safe to perform due to interior pointer ownership - // requirements being transitive along addresses. - - Builder.setCurrentDebugScope(UADCI->getDebugScope()); - - // (unchecked_addr_cast (unchecked_addr_cast x X->Y) Y->Z) - // -> - // (unchecked_addr_cast x X->Z) - if (auto *OtherUADCI = dyn_cast(UADCI->getOperand())) - return Builder.createUncheckedAddrCast(UADCI->getLoc(), - OtherUADCI->getOperand(), - UADCI->getType()); - return nullptr; -} - SILInstruction * SILCombiner::visitUncheckedRefCastInst(UncheckedRefCastInst *urci) { // %0 = unchecked_ref_cast %x : $X->Y diff --git a/lib/SILOptimizer/SILCombiner/Simplifications.def b/lib/SILOptimizer/SILCombiner/Simplifications.def index 0b4444664bf31..2fd5d6720466b 100644 --- a/lib/SILOptimizer/SILCombiner/Simplifications.def +++ b/lib/SILOptimizer/SILCombiner/Simplifications.def @@ -47,6 +47,7 @@ INSTRUCTION_SIMPLIFICATION(DestructureStructInst) INSTRUCTION_SIMPLIFICATION(DestructureTupleInst) INSTRUCTION_SIMPLIFICATION(PointerToAddressInst) INSTRUCTION_SIMPLIFICATION(TypeValueInst) +INSTRUCTION_SIMPLIFICATION(UncheckedAddrCastInst) INSTRUCTION_SIMPLIFICATION(UncheckedEnumDataInst) INSTRUCTION_SIMPLIFICATION(WitnessMethodInst) INSTRUCTION_SIMPLIFICATION_WITH_LEGACY(AllocStackInst) diff --git a/lib/SILOptimizer/UtilityPasses/SerializeSILPass.cpp b/lib/SILOptimizer/UtilityPasses/SerializeSILPass.cpp index 2be680f257449..69ed207bbe67e 100644 --- a/lib/SILOptimizer/UtilityPasses/SerializeSILPass.cpp +++ b/lib/SILOptimizer/UtilityPasses/SerializeSILPass.cpp @@ -209,6 +209,7 @@ static bool hasOpaqueArchetype(TypeExpansionContext context, case SILInstructionKind::ObjCProtocolInst: case SILInstructionKind::ObjectInst: case SILInstructionKind::VectorInst: + case SILInstructionKind::VectorBaseAddrInst: case SILInstructionKind::TupleInst: case SILInstructionKind::TupleAddrConstructorInst: case SILInstructionKind::TupleExtractInst: diff --git a/lib/SILOptimizer/Utils/InstructionDeleter.cpp b/lib/SILOptimizer/Utils/InstructionDeleter.cpp index 6e9e178a58101..f7d4761b23a4d 100644 --- a/lib/SILOptimizer/Utils/InstructionDeleter.cpp +++ b/lib/SILOptimizer/Utils/InstructionDeleter.cpp @@ -63,6 +63,12 @@ static bool isScopeAffectingInstructionDead(SILInstruction *inst, return false; } + // Don't delete dead drop_deinit instruction. They are a marker to eliminate + // user-defined deinit and we do not want to lose it. + if (isa(inst)) { + return false; + } + for (auto result : inst->getResults()) { // If inst has any owned move-only value as a result, deleting it may // shorten that value's lifetime which is illegal according to language @@ -268,9 +274,16 @@ void InstructionDeleter::deleteWithUses(SILInstruction *inst, bool fixLifetimes, if (fixLifetimes) { LoadInst *li = nullptr; if (operand.isConsuming()) { - SILBuilderWithScope builder(inst); - auto *dvi = builder.createDestroyValue(inst->getLoc(), operandValue); - getCallbacks().createdNewInst(dvi); + if (isa(operandValue)) { + SILBuilderWithScope builder(inst); + auto *eli = builder.createEndLifetime(inst->getLoc(), operandValue); + getCallbacks().createdNewInst(eli); + } else { + SILBuilderWithScope builder(inst); + auto *dvi = + builder.createDestroyValue(inst->getLoc(), operandValue); + getCallbacks().createdNewInst(dvi); + } } else if ((li = dyn_cast(inst)) && li->getOwnershipQualifier() == LoadOwnershipQualifier::Take) { diff --git a/lib/SILOptimizer/Utils/OptimizerBridging.cpp b/lib/SILOptimizer/Utils/OptimizerBridging.cpp index 02390165da18a..fcf142548c08d 100644 --- a/lib/SILOptimizer/Utils/OptimizerBridging.cpp +++ b/lib/SILOptimizer/Utils/OptimizerBridging.cpp @@ -11,7 +11,13 @@ //===----------------------------------------------------------------------===// #include "swift/SILOptimizer/OptimizerBridging.h" +#include "../../IRGen/IRGenModule.h" +#include "swift/AST/SemanticAttrs.h" +#include "swift/SIL/DynamicCasts.h" +#include "swift/SIL/OSSALifetimeCompletion.h" +#include "swift/SIL/SILCloner.h" #include "swift/SILOptimizer/Analysis/Analysis.h" +#include "swift/SILOptimizer/IPO/ClosureSpecializer.h" #include "swift/SILOptimizer/Utils/CFGOptUtils.h" #include "swift/SILOptimizer/Utils/ConstantFolding.h" #include "swift/SILOptimizer/Utils/Devirtualize.h" @@ -21,11 +27,6 @@ #include "swift/SILOptimizer/Utils/SILOptFunctionBuilder.h" #include "swift/SILOptimizer/Utils/SpecializationMangler.h" #include "swift/SILOptimizer/Utils/StackNesting.h" -#include "swift/SILOptimizer/IPO/ClosureSpecializer.h" -#include "swift/SIL/DynamicCasts.h" -#include "swift/SIL/OSSALifetimeCompletion.h" -#include "swift/SIL/SILCloner.h" -#include "../../IRGen/IRGenModule.h" using namespace swift; @@ -63,6 +64,10 @@ void SILPassManager::runSwiftFunctionVerification(SILFunction *f) { if (DisableSwiftVerification) return; + if (f->hasSemanticsAttr(semantics::NO_SIL_VERIFICATION)) { + return; + } + getSwiftPassInvocation()->beginVerifyFunction(f); verifyFunctionFunction({getSwiftPassInvocation()}, {f}); getSwiftPassInvocation()->endVerifyFunction(); diff --git a/lib/SILOptimizer/Utils/SILInliner.cpp b/lib/SILOptimizer/Utils/SILInliner.cpp index 94d44400920df..ef15f35ad20ac 100644 --- a/lib/SILOptimizer/Utils/SILInliner.cpp +++ b/lib/SILOptimizer/Utils/SILInliner.cpp @@ -1096,6 +1096,7 @@ InlineCost swift::instructionInlineCost(SILInstruction &I) { case SILInstructionKind::DynamicMethodBranchInst: case SILInstructionKind::EnumInst: case SILInstructionKind::IndexAddrInst: + case SILInstructionKind::VectorBaseAddrInst: case SILInstructionKind::TailAddrInst: case SILInstructionKind::IndexRawPointerInst: case SILInstructionKind::InitEnumDataAddrInst: diff --git a/lib/Sema/CSApply.cpp b/lib/Sema/CSApply.cpp index 12ecc020414b7..09e66754859ce 100644 --- a/lib/Sema/CSApply.cpp +++ b/lib/Sema/CSApply.cpp @@ -6097,15 +6097,20 @@ static bool hasCurriedSelf(ConstraintSystem &cs, ConcreteDeclRef callee, } /// Apply the contextually Sendable flag to the given expression, -static void applyContextualClosureFlags(Expr *expr, bool implicitSelfCapture, - bool inheritActorContext, - bool isPassedToSendingParameter, +static void applyContextualClosureFlags(Expr *expr, unsigned paramIdx, + const ParameterListInfo ¶mInfo, bool requiresDynamicIsolationChecking, bool isMacroArg) { if (auto closure = dyn_cast(expr)) { - closure->setAllowsImplicitSelfCapture(implicitSelfCapture); - closure->setInheritsActorContext(inheritActorContext); - closure->setIsPassedToSendingParameter(isPassedToSendingParameter); + closure->setAllowsImplicitSelfCapture( + paramInfo.isImplicitSelfCapture(paramIdx)); + + auto [inheritActorContext, modifier] = + paramInfo.inheritsActorContext(paramIdx); + closure->setInheritsActorContext(inheritActorContext, modifier); + + closure->setIsPassedToSendingParameter( + paramInfo.isSendingParameter(paramIdx)); closure->setRequiresDynamicIsolationChecking( requiresDynamicIsolationChecking); closure->setIsMacroArgument(isMacroArg); @@ -6113,19 +6118,14 @@ static void applyContextualClosureFlags(Expr *expr, bool implicitSelfCapture, } if (auto captureList = dyn_cast(expr)) { - applyContextualClosureFlags(captureList->getClosureBody(), - implicitSelfCapture, inheritActorContext, - isPassedToSendingParameter, - requiresDynamicIsolationChecking, + applyContextualClosureFlags(captureList->getClosureBody(), paramIdx, + paramInfo, requiresDynamicIsolationChecking, isMacroArg); } if (auto identity = dyn_cast(expr)) { - applyContextualClosureFlags(identity->getSubExpr(), implicitSelfCapture, - inheritActorContext, - isPassedToSendingParameter, - requiresDynamicIsolationChecking, - isMacroArg); + applyContextualClosureFlags(identity->getSubExpr(), paramIdx, paramInfo, + requiresDynamicIsolationChecking, isMacroArg); } } @@ -6251,19 +6251,13 @@ ArgumentList *ExprRewriter::coerceCallArguments( auto applyFlagsToArgument = [¶mInfo, &closuresRequireDynamicIsolationChecking, - &locator]( - unsigned paramIdx, Expr *argument) { + &locator](unsigned paramIdx, Expr *argument) { if (!isClosureLiteralExpr(argument)) return; - bool isImplicitSelfCapture = paramInfo.isImplicitSelfCapture(paramIdx); - bool inheritsActorContext = paramInfo.inheritsActorContext(paramIdx); - bool isPassedToSendingParameter = paramInfo.isSendingParameter(paramIdx); bool isMacroArg = isExpr(locator.getAnchor()); - applyContextualClosureFlags(argument, isImplicitSelfCapture, - inheritsActorContext, - isPassedToSendingParameter, + applyContextualClosureFlags(argument, paramIdx, paramInfo, closuresRequireDynamicIsolationChecking, isMacroArg); }; diff --git a/lib/Sema/CSDiagnostics.cpp b/lib/Sema/CSDiagnostics.cpp index acc0f261b3d7c..821a3168b4f5f 100644 --- a/lib/Sema/CSDiagnostics.cpp +++ b/lib/Sema/CSDiagnostics.cpp @@ -4449,8 +4449,9 @@ bool MissingMemberFailure::diagnoseAsError() { auto &cs = getConstraintSystem(); auto result = cs.performMemberLookup( - ConstraintKind::ValueMember, getName().withoutArgumentLabels(), - metatypeTy, FunctionRefInfo::doubleBaseNameApply(), getLocator(), + ConstraintKind::ValueMember, + getName().withoutArgumentLabels(getASTContext()), metatypeTy, + FunctionRefInfo::doubleBaseNameApply(), getLocator(), /*includeInaccessibleMembers=*/true); // If there are no `init` members at all produce a tailored diff --git a/lib/Sema/CodeSynthesis.cpp b/lib/Sema/CodeSynthesis.cpp index 23ea558f8ff2d..3fd3c836ecc08 100644 --- a/lib/Sema/CodeSynthesis.cpp +++ b/lib/Sema/CodeSynthesis.cpp @@ -1723,7 +1723,8 @@ bool swift::hasLetStoredPropertyWithInitialValue(NominalTypeDecl *nominal) { }); } -/// Determine whether a synth +/// Determine whether a synthesized requirement for the given conformance +/// should be explicitly marked as 'nonisolated'. static bool synthesizedRequirementIsNonIsolated( const NormalProtocolConformance *conformance) { // @preconcurrency suppresses this. diff --git a/lib/Sema/ConstraintSystem.cpp b/lib/Sema/ConstraintSystem.cpp index 6b55b6746cbcc..10c55bcbb5d8b 100644 --- a/lib/Sema/ConstraintSystem.cpp +++ b/lib/Sema/ConstraintSystem.cpp @@ -1414,11 +1414,6 @@ FunctionType::ExtInfo ClosureEffectsRequest::evaluate( bool async = expr->getAsyncLoc().isValid(); bool sendable = expr->getAttrs().hasAttribute(); - // `@concurrent` attribute is only valid on asynchronous function types. - if (expr->getAttrs().hasAttribute()) { - async = true; - } - if (throws || async) { return ASTExtInfoBuilder() .withThrows(throws, /*FIXME:*/Type()) @@ -1432,11 +1427,17 @@ FunctionType::ExtInfo ClosureEffectsRequest::evaluate( if (!body) return ASTExtInfoBuilder().withSendable(sendable).build(); + // `@concurrent` attribute is only valid on asynchronous function types. + bool asyncFromAttr = false; + if (expr->getAttrs().hasAttribute()) { + asyncFromAttr = true; + } + auto throwFinder = FindInnerThrows(expr); body->walk(throwFinder); return ASTExtInfoBuilder() .withThrows(throwFinder.foundThrow(), /*FIXME:*/Type()) - .withAsync(bool(findAsyncNode(expr))) + .withAsync(asyncFromAttr || bool(findAsyncNode(expr))) .withSendable(sendable) .build(); } diff --git a/lib/Sema/DerivedConformance/DerivedConformanceRawRepresentable.cpp b/lib/Sema/DerivedConformance/DerivedConformanceRawRepresentable.cpp index 209bb71fcd1c2..1463e794c2f84 100644 --- a/lib/Sema/DerivedConformance/DerivedConformanceRawRepresentable.cpp +++ b/lib/Sema/DerivedConformance/DerivedConformanceRawRepresentable.cpp @@ -105,7 +105,9 @@ deriveBodyRawRepresentable_raw(AbstractFunctionDecl *toRawDecl, void *) { auto *argList = ArgumentList::forImplicitCallTo(functionRef->getName(), {selfRef, typeExpr}, C); - auto call = CallExpr::createImplicit(C, functionRef, argList); + Expr *call = CallExpr::createImplicit(C, functionRef, argList); + if (C.LangOpts.hasFeature(Feature::StrictMemorySafety)) + call = UnsafeExpr::createImplicit(C, SourceLoc(), call); auto *returnStmt = ReturnStmt::createImplicit(C, call); auto body = BraceStmt::create(C, SourceLoc(), ASTNode(returnStmt), SourceLoc()); diff --git a/lib/Sema/TypeCheckAttr.cpp b/lib/Sema/TypeCheckAttr.cpp index cee993d42311c..2edcc31fb553b 100644 --- a/lib/Sema/TypeCheckAttr.cpp +++ b/lib/Sema/TypeCheckAttr.cpp @@ -184,7 +184,6 @@ class AttributeChecker : public AttributeVisitor { IGNORED_ATTR(AtRethrows) IGNORED_ATTR(AtReasync) IGNORED_ATTR(ImplicitSelfCapture) - IGNORED_ATTR(InheritActorContext) IGNORED_ATTR(Preconcurrency) IGNORED_ATTR(BackDeployed) IGNORED_ATTR(Documentation) @@ -442,8 +441,10 @@ class AttributeChecker : public AttributeVisitor { void visitNonisolatedAttr(NonisolatedAttr *attr); void visitIsolatedAttr(IsolatedAttr *attr); + void visitInheritActorContextAttr(InheritActorContextAttr *attr); + void visitNoImplicitCopyAttr(NoImplicitCopyAttr *attr); - + void visitAlwaysEmitConformanceMetadataAttr(AlwaysEmitConformanceMetadataAttr *attr); void visitExtractConstantsFromMembersAttr(ExtractConstantsFromMembersAttr *attr); @@ -4281,8 +4282,25 @@ void AttributeChecker::visitImplementsAttr(ImplementsAttr *attr) { ProtocolDecl *PD = attr->getProtocol(DC); if (!PD) { - diagnose(attr->getLocation(), diag::implements_attr_non_protocol_type) - .highlight(attr->getProtocolTypeRepr()->getSourceRange()); + // `ImplementsAttr::getProtocol()` returns `nullptr` both when a type fails + // to resolve, and when it resolves to something other than a protocol. + // Due to layering concerns, it doesn't resolve in a way that emits + // diagnostics. + // + // Distinguish between these situations by trying to resolve the type again. + // If it doesn't resolve, TypeResolution will have diagnosed the problem; if + // it does, it must have resolved to a non-protocol, so emit a diagnostic to + // that effect. + TypeResolutionOptions options(TypeResolverContext::None); + auto resolvedType = TypeResolution::resolveContextualType( + attr->getProtocolTypeRepr(), DC, options, + // Unbound generics and placeholders are not allowed within this attr. + /*unboundTyOpener*/ nullptr, /*placeholderHandler*/ nullptr, + /*packElementOpener*/ nullptr); + + if (resolvedType && !resolvedType->hasError()) + diagnose(attr->getLocation(), diag::implements_attr_non_protocol_type) + .highlight(attr->getProtocolTypeRepr()->getSourceRange()); return; } @@ -7829,6 +7847,40 @@ void AttributeChecker::visitAsyncAttr(AsyncAttr *attr) { } } +void AttributeChecker::visitInheritActorContextAttr( + InheritActorContextAttr *attr) { + auto *P = dyn_cast(D); + if (!P) + return; + + auto paramTy = P->getInterfaceType(); + auto *funcTy = + paramTy->lookThroughAllOptionalTypes()->getAs(); + if (!funcTy) { + diagnoseAndRemoveAttr(attr, diag::inherit_actor_context_only_on_func_types, + attr, paramTy); + return; + } + + // The type has to be either `@Sendable` or `sending` _and_ + // `async` or `@isolated(any)`. + if (!(funcTy->isSendable() || P->isSending())) { + diagnose(attr->getLocation(), + diag::inherit_actor_context_only_on_sending_or_Sendable_params, + attr) + .warnUntilFutureSwiftVersion(); + } + + // Eiether `async` or `@isolated(any)`. + if (!(funcTy->isAsync() || funcTy->getIsolation().isErased())) { + diagnose( + attr->getLocation(), + diag::inherit_actor_context_only_on_async_or_isolation_erased_params, + attr) + .warnUntilFutureSwiftVersion(); + } +} + void AttributeChecker::visitMarkerAttr(MarkerAttr *attr) { auto proto = dyn_cast(D); if (!proto) @@ -8372,9 +8424,10 @@ ValueDecl *RenamedDeclRequest::evaluate(Evaluator &evaluator, if (attr->Rename.empty()) return nullptr; + auto &ctx = attached->getASTContext(); auto attachedContext = attached->getDeclContext(); auto parsedName = parseDeclName(attr->Rename); - auto nameRef = parsedName.formDeclNameRef(attached->getASTContext()); + auto nameRef = parsedName.formDeclNameRef(ctx); // Handle types separately if (isa(attached)) { @@ -8383,7 +8436,7 @@ ValueDecl *RenamedDeclRequest::evaluate(Evaluator &evaluator, SmallVector lookupResults; attachedContext->lookupQualified(attachedContext->getParentModule(), - nameRef.withoutArgumentLabels(), + nameRef.withoutArgumentLabels(ctx), attr->getLocation(), NL_OnlyTypes, lookupResults); if (lookupResults.size() == 1) diff --git a/lib/Sema/TypeCheckConcurrency.cpp b/lib/Sema/TypeCheckConcurrency.cpp index 94b0770646304..fb10cf82419e4 100644 --- a/lib/Sema/TypeCheckConcurrency.cpp +++ b/lib/Sema/TypeCheckConcurrency.cpp @@ -2274,12 +2274,6 @@ static bool safeToDropGlobalActor( if (otherIsolation.isErased()) return true; - // We currently allow unconditional dropping of global actors from - // async function types, despite this confusing Sendable checking - // in light of SE-338. - if (funcTy->isAsync()) - return true; - // If the argument is passed over an isolation boundary, it's not // safe to erase actor isolation, because the callee can call the // function synchronously from outside the isolation domain. @@ -2629,7 +2623,8 @@ namespace { /// be correct AND the solver doesn't know, so we must emit a diagnostic. void checkFunctionConversion(Expr *funcConv, Type fromType, Type toType) { auto diagnoseNonSendableParametersAndResult = - [&](FunctionType *fnType, bool downgradeToWarning = false) { + [&](FunctionType *fnType, + std::optional warnUntilSwiftMode = std::nullopt) { auto *dc = getDeclContext(); llvm::SmallPtrSet nonSendableTypes; @@ -2659,8 +2654,8 @@ namespace { diag::invalid_function_conversion_with_non_sendable, fromType, toType); - if (downgradeToWarning) - diag.warnUntilFutureSwiftVersion(); + if (warnUntilSwiftMode) + diag.warnUntilSwiftVersion(*warnUntilSwiftMode); } for (auto type : nonSendableTypes) { @@ -2677,20 +2672,27 @@ namespace { auto toIsolation = toFnType->getIsolation(); if (auto fromActor = fromFnType->getGlobalActor()) { - if (toFnType->hasGlobalActor() || - (toFnType->isAsync() && !toIsolation.isNonIsolatedCaller())) - return; + if (!toFnType->hasGlobalActor()) { + auto dc = const_cast(getDeclContext()); + // If it's unsafe to drop global actor attribute: + // - for Sendable types we are going to perform Sendability + // checking of parameters/result. + // - for non-Sendable types we either leave it to region-based + // isolation to determine whether it's okay or not or + // diagnose if types are not-async. + if (safeToDropGlobalActor(dc, fromActor, toType, + getImmediateApply())) { + return; + } - auto dc = const_cast(getDeclContext()); - if (!safeToDropGlobalActor(dc, fromActor, toType, - getImmediateApply())) { - // otherwise, it's not a safe cast. - ctx.Diags - .diagnose(funcConv->getLoc(), - diag::converting_func_loses_global_actor, fromType, - toType, fromActor) - .warnUntilSwiftVersion(6); - return; + if (!toFnType->isAsync()) { + ctx.Diags + .diagnose(funcConv->getLoc(), + diag::converting_func_loses_global_actor, + fromType, toType, fromActor) + .warnUntilSwiftVersion(6); + return; + } } } @@ -2756,11 +2758,12 @@ namespace { case FunctionTypeIsolation::Kind::NonIsolatedCaller: case FunctionTypeIsolation::Kind::Erased: diagnoseNonSendableParametersAndResult( - toFnType, /*downgradeToWarning=*/true); + toFnType, version::Version::getFutureMajorLanguageVersion()); break; case FunctionTypeIsolation::Kind::GlobalActor: { - // Handled above by `safeToDropGlobalActor` check. + diagnoseNonSendableParametersAndResult(toFnType, + /*warnUntilSwiftMode*/ 6); break; } @@ -2768,7 +2771,8 @@ namespace { // nonisolated synchronous <-> @concurrent if (fromFnType->isAsync() != toFnType->isAsync()) { diagnoseNonSendableParametersAndResult( - toFnType, /*downgradeToWarning=*/true); + toFnType, + version::Version::getFutureMajorLanguageVersion()); } break; } @@ -2783,7 +2787,7 @@ namespace { case FunctionTypeIsolation::Kind::Parameter: case FunctionTypeIsolation::Kind::Erased: diagnoseNonSendableParametersAndResult( - toFnType, /*downgradeToWarning=*/true); + toFnType, version::Version::getFutureMajorLanguageVersion()); break; case FunctionTypeIsolation::Kind::NonIsolated: { @@ -2793,7 +2797,8 @@ namespace { // actor isolation. if (fromFnType->isAsync()) { diagnoseNonSendableParametersAndResult( - toFnType, /*downgradeToWarning=*/true); + toFnType, + version::Version::getFutureMajorLanguageVersion()); break; } // Runs on the actor. @@ -2805,7 +2810,9 @@ namespace { break; case FunctionTypeIsolation::Kind::GlobalActor: - llvm_unreachable("invalid conversion"); + diagnoseNonSendableParametersAndResult( + toFnType, version::Version::getFutureMajorLanguageVersion()); + break; } break; } @@ -2823,6 +2830,29 @@ namespace { } } + /// Function object that refines isolation for each actor isolation it is + /// given, returning true if all of the provided isolations have been + /// accounted for, or false if the caller should handle them. + class RefineConformances { + ActorIsolationChecker &self; + + public: + RefineConformances(ActorIsolationChecker &self) : self(self) { } + + bool operator()(ArrayRef isolations) const { + bool anyRefined = false; + bool anyUnrefined = false; + for (const auto &isolation : isolations) { + if (self.refineRequiredIsolation(isolation)) + anyRefined = true; + else + anyUnrefined = true; + } + + return anyRefined && !anyUnrefined; + } + }; + bool refineRequiredIsolation(ActorIsolation refinedIsolation) { if (requiredIsolationLoc.isInvalid()) return false; @@ -3332,13 +3362,13 @@ namespace { if (auto erasureExpr = dyn_cast(expr)) { checkIsolatedConformancesInContext( erasureExpr->getConformances(), erasureExpr->getLoc(), - getDeclContext()); + getDeclContext(), RefineConformances{*this}); } if (auto *underlyingToOpaque = dyn_cast(expr)) { checkIsolatedConformancesInContext( underlyingToOpaque->substitutions, underlyingToOpaque->getLoc(), - getDeclContext()); + getDeclContext(), RefineConformances{*this}); } return Action::Continue(expr); @@ -4447,7 +4477,8 @@ namespace { return false; // Make sure isolated conformances are formed in the right context. - checkIsolatedConformancesInContext(declRef, loc, getDeclContext()); + checkIsolatedConformancesInContext(declRef, loc, getDeclContext(), + RefineConformances{*this}); auto *const decl = declRef.getDecl(); @@ -4752,6 +4783,16 @@ ActorIsolation ActorIsolationChecker::determineClosureIsolation( if (checkIsolatedCapture) { if (auto param = closure->getCaptureInfo().getIsolatedParamCapture()) return ActorIsolation::forActorInstanceCapture(param); + + auto *explicitClosure = dyn_cast(closure); + // @_inheritActorContext(always) forces the isolation capture. + if (explicitClosure && explicitClosure->alwaysInheritsActorContext()) { + if (parentIsolation.isActorInstanceIsolated()) { + if (auto *param = parentIsolation.getActorInstance()) + return ActorIsolation::forActorInstanceCapture(param); + } + return parentIsolation; + } } else { // If we don't have capture information during code completion, assume // that the closure captures the `isolated` parameter from the parent @@ -8015,11 +8056,14 @@ namespace { class MismatchedIsolatedConformances { llvm::TinyPtrVector badIsolatedConformances; DeclContext *fromDC; + HandleConformanceIsolationFn handleBad; mutable std::optional fromIsolation; public: - MismatchedIsolatedConformances(const DeclContext *fromDC) - : fromDC(const_cast(fromDC)) { } + MismatchedIsolatedConformances(const DeclContext *fromDC, + HandleConformanceIsolationFn handleBad) + : fromDC(const_cast(fromDC)), + handleBad(handleBad) { } ActorIsolation getContextIsolation() const { if (!fromIsolation) @@ -8059,6 +8103,16 @@ namespace { if (badIsolatedConformances.empty()) return false; + if (handleBad) { + // Capture all of the actor isolations from the conformances. + std::vector badIsolations; + for (auto conformance : badIsolatedConformances) + badIsolations.push_back(conformance->getIsolation()); + + if (handleBad(badIsolations)) + return false; + } + ASTContext &ctx = fromDC->getASTContext(); auto firstConformance = badIsolatedConformances.front(); ctx.Diags.diagnose( @@ -8074,32 +8128,40 @@ namespace { } +bool swift::doNotDiagnoseConformanceIsolation(ArrayRef) { + return false; +} + bool swift::checkIsolatedConformancesInContext( - ConcreteDeclRef declRef, SourceLoc loc, const DeclContext *dc) { - MismatchedIsolatedConformances mismatched(dc); + ConcreteDeclRef declRef, SourceLoc loc, const DeclContext *dc, + HandleConformanceIsolationFn handleBad) { + MismatchedIsolatedConformances mismatched(dc, handleBad); forEachConformance(declRef, mismatched); return mismatched.diagnose(loc); } bool swift::checkIsolatedConformancesInContext( ArrayRef conformances, SourceLoc loc, - const DeclContext *dc) { - MismatchedIsolatedConformances mismatched(dc); + const DeclContext *dc, + HandleConformanceIsolationFn handleBad) { + MismatchedIsolatedConformances mismatched(dc, handleBad); for (auto conformance: conformances) forEachConformance(conformance, mismatched); return mismatched.diagnose(loc); } bool swift::checkIsolatedConformancesInContext( - SubstitutionMap subs, SourceLoc loc, const DeclContext *dc) { - MismatchedIsolatedConformances mismatched(dc); + SubstitutionMap subs, SourceLoc loc, const DeclContext *dc, + HandleConformanceIsolationFn handleBad) { + MismatchedIsolatedConformances mismatched(dc, handleBad); forEachConformance(subs, mismatched); return mismatched.diagnose(loc); } bool swift::checkIsolatedConformancesInContext( - Type type, SourceLoc loc, const DeclContext *dc) { - MismatchedIsolatedConformances mismatched(dc); + Type type, SourceLoc loc, const DeclContext *dc, + HandleConformanceIsolationFn handleBad) { + MismatchedIsolatedConformances mismatched(dc, handleBad); forEachConformance(type, mismatched); return mismatched.diagnose(loc); } diff --git a/lib/Sema/TypeCheckConcurrency.h b/lib/Sema/TypeCheckConcurrency.h index 5a3c868a3952b..37868c9ee512b 100644 --- a/lib/Sema/TypeCheckConcurrency.h +++ b/lib/Sema/TypeCheckConcurrency.h @@ -734,12 +734,22 @@ void introduceUnsafeInheritExecutorReplacements( void introduceUnsafeInheritExecutorReplacements( const DeclContext *dc, Type base, SourceLoc loc, LookupResult &result); +/// Function that attempts to handle all of the "bad" conformance isolation +/// found somewhere, and returns true if it handled them. If not, returns +/// false so that the conformances can be diagnose. +using HandleConformanceIsolationFn = + llvm::function_ref)>; + +/// Function used as a default HandleConformanceIsolationFn. +bool doNotDiagnoseConformanceIsolation(ArrayRef); + /// Check for correct use of isolated conformances in the given reference. /// /// This checks that any isolated conformances that occur in the given /// declaration reference match the isolated of the context. bool checkIsolatedConformancesInContext( - ConcreteDeclRef declRef, SourceLoc loc, const DeclContext *dc); + ConcreteDeclRef declRef, SourceLoc loc, const DeclContext *dc, + HandleConformanceIsolationFn handleBad = doNotDiagnoseConformanceIsolation); /// Check for correct use of isolated conformances in the set given set of /// protocol conformances. @@ -748,7 +758,8 @@ bool checkIsolatedConformancesInContext( /// declaration reference match the isolated of the context. bool checkIsolatedConformancesInContext( ArrayRef conformances, SourceLoc loc, - const DeclContext *dc); + const DeclContext *dc, + HandleConformanceIsolationFn handleBad = doNotDiagnoseConformanceIsolation); /// Check for correct use of isolated conformances in the given substitution /// map. @@ -756,14 +767,16 @@ bool checkIsolatedConformancesInContext( /// This checks that any isolated conformances that occur in the given /// substitution map match the isolated of the context. bool checkIsolatedConformancesInContext( - SubstitutionMap subs, SourceLoc loc, const DeclContext *dc); + SubstitutionMap subs, SourceLoc loc, const DeclContext *dc, + HandleConformanceIsolationFn handleBad = doNotDiagnoseConformanceIsolation); /// Check for correct use of isolated conformances in the given type. /// /// This checks that any isolated conformances that occur in the given /// type match the isolated of the context. bool checkIsolatedConformancesInContext( - Type type, SourceLoc loc, const DeclContext *dc); + Type type, SourceLoc loc, const DeclContext *dc, + HandleConformanceIsolationFn handleBad = doNotDiagnoseConformanceIsolation); } // end namespace swift diff --git a/lib/Sema/TypeCheckMacros.cpp b/lib/Sema/TypeCheckMacros.cpp index 4428cf052f4ae..b2ea98fe99a18 100644 --- a/lib/Sema/TypeCheckMacros.cpp +++ b/lib/Sema/TypeCheckMacros.cpp @@ -282,7 +282,7 @@ initializePlugin(ASTContext &ctx, CompilerPlugin *plugin, StringRef libraryPath, if (!libraryPath.empty()) { #if SWIFT_BUILD_SWIFT_SYNTAX llvm::SmallString<128> resolvedLibraryPath; - auto fs = ctx.ClangImporterOpts.HasClangIncludeTreeRoot + auto fs = ctx.CASOpts.HasImmutableFileSystem ? llvm::vfs::getRealFileSystem() : ctx.SourceMgr.getFileSystem(); if (auto err = fs->getRealPath(libraryPath, resolvedLibraryPath)) { diff --git a/lib/Sema/TypeCheckPattern.cpp b/lib/Sema/TypeCheckPattern.cpp index 7d32bc32ecdf8..87e0a39c13651 100644 --- a/lib/Sema/TypeCheckPattern.cpp +++ b/lib/Sema/TypeCheckPattern.cpp @@ -138,7 +138,7 @@ static EnumElementDecl * lookupUnqualifiedEnumMemberElement(DeclContext *DC, DeclNameRef name, SourceLoc UseLoc) { // FIXME: We should probably pay attention to argument labels someday. - name = name.withoutArgumentLabels(); + name = name.withoutArgumentLabels(DC->getASTContext()); auto lookup = TypeChecker::lookupUnqualified(DC, name, UseLoc, @@ -153,7 +153,7 @@ static LookupResult lookupMembers(DeclContext *DC, Type ty, DeclNameRef name, return LookupResult(); // FIXME: We should probably pay attention to argument labels someday. - name = name.withoutArgumentLabels(); + name = name.withoutArgumentLabels(DC->getASTContext()); // Look up the case inside the enum. // FIXME: We should be able to tell if this is a private lookup. diff --git a/lib/Sema/TypeCheckProtocol.cpp b/lib/Sema/TypeCheckProtocol.cpp index 8619559ea1bda..29bfb2f3f23a6 100644 --- a/lib/Sema/TypeCheckProtocol.cpp +++ b/lib/Sema/TypeCheckProtocol.cpp @@ -1489,7 +1489,7 @@ swift::lookupValueWitnesses(DeclContext *DC, ValueDecl *req, bool *ignoringNames lookupValueWitnessesViaImplementsAttr(DC, req, witnesses); auto reqName = req->createNameRef(); - auto reqBaseName = reqName.withoutArgumentLabels(); + auto reqBaseName = reqName.withoutArgumentLabels(DC->getASTContext()); // An operator function is the only kind of witness that requires global // lookup. However, because global lookup doesn't enter local contexts, diff --git a/lib/Sema/TypeCheckStmt.cpp b/lib/Sema/TypeCheckStmt.cpp index 343aa461aef54..9d21dfdd038b4 100644 --- a/lib/Sema/TypeCheckStmt.cpp +++ b/lib/Sema/TypeCheckStmt.cpp @@ -1433,8 +1433,7 @@ class StmtChecker : public StmtVisitor { } Stmt *visitForEachStmt(ForEachStmt *S) { - if (TypeChecker::typeCheckForEachPreamble(DC, S)) - return nullptr; + TypeChecker::typeCheckForEachPreamble(DC, S); // Type-check the body of the loop. auto sourceFile = DC->getParentSourceFile(); @@ -2462,12 +2461,29 @@ bool TypeCheckASTNodeAtLocRequest::evaluate( return MacroWalking::ArgumentsAndExpansion; } + /// Checks whether the given range, when treated as a character range, + /// contains the searched location. + bool charRangeContainsLoc(SourceRange range) { + if (!range) + return false; + + if (SM.isBefore(Loc, range.Start)) + return false; + + // NOTE: We need to check the character loc here because the target + // loc can be inside the last token of the node. i.e. interpolated + // string. + return SM.isBefore(Loc, Lexer::getLocForEndOfToken(SM, range.End)); + } + PreWalkResult walkToStmtPre(Stmt *S) override { if (auto *brace = dyn_cast(S)) { - auto braceCharRange = Lexer::getCharSourceRangeFromSourceRange( - SM, brace->getSourceRange()); + auto braceRange = brace->getSourceRange(); + auto braceCharRange = SourceRange( + braceRange.Start, Lexer::getLocForEndOfToken(SM, braceRange.End)); + // Unless this brace contains the loc, there's nothing to do. - if (!braceCharRange.contains(Loc)) + if (!SM.containsLoc(braceCharRange, Loc)) return Action::SkipNode(S); // Reset the node found in a parent context if it's not part of this @@ -2477,22 +2493,22 @@ bool TypeCheckASTNodeAtLocRequest::evaluate( // syntactically part of the brace stmt's range but won't be walked as // a child of the brace stmt. if (!brace->isImplicit() && FoundNode) { - auto foundNodeCharRange = Lexer::getCharSourceRangeFromSourceRange( - SM, FoundNode->getSourceRange()); - if (!braceCharRange.contains(foundNodeCharRange)) { + auto foundRange = FoundNode->getSourceRange(); + auto foundCharRange = SourceRange( + foundRange.Start, Lexer::getLocForEndOfToken(SM, foundRange.End)); + if (!SM.encloses(braceCharRange, foundCharRange)) FoundNode = nullptr; - } } for (ASTNode &node : brace->getElements()) { - if (SM.isBeforeInBuffer(Loc, node.getStartLoc())) + auto range = node.getSourceRange(); + if (SM.isBefore(Loc, range.Start)) break; // NOTE: We need to check the character loc here because the target // loc can be inside the last token of the node. i.e. interpolated // string. - SourceLoc endLoc = Lexer::getLocForEndOfToken(SM, node.getEndLoc()); - if (SM.isBeforeInBuffer(endLoc, Loc) || endLoc == Loc) + if (!SM.isBefore(Loc, Lexer::getLocForEndOfToken(SM, range.End))) continue; // 'node' may be the target node, except 'CaseStmt' which cannot be @@ -2509,13 +2525,11 @@ bool TypeCheckASTNodeAtLocRequest::evaluate( return Action::Stop(); } else if (auto Conditional = dyn_cast(S)) { for (StmtConditionElement &Cond : Conditional->getCond()) { - if (SM.isBeforeInBuffer(Loc, Cond.getStartLoc())) { + auto range = Cond.getSourceRange(); + if (SM.isBefore(Loc, range.Start)) break; - } - SourceLoc endLoc = Lexer::getLocForEndOfToken(SM, Cond.getEndLoc()); - if (SM.isBeforeInBuffer(endLoc, Loc) || endLoc == Loc) { + if (!SM.isBefore(Loc, Lexer::getLocForEndOfToken(SM, range.End))) continue; - } FoundNodeStorage = ASTNode(&Cond); FoundNode = &FoundNodeStorage; @@ -2527,11 +2541,7 @@ bool TypeCheckASTNodeAtLocRequest::evaluate( } PreWalkResult walkToExprPre(Expr *E) override { - if (SM.isBeforeInBuffer(Loc, E->getStartLoc())) - return Action::SkipNode(E); - - SourceLoc endLoc = Lexer::getLocForEndOfToken(SM, E->getEndLoc()); - if (SM.isBeforeInBuffer(endLoc, Loc)) + if (!charRangeContainsLoc(E->getSourceRange())) return Action::SkipNode(E); // Don't walk into 'TapExpr'. They should be type checked with parent @@ -2546,9 +2556,7 @@ bool TypeCheckASTNodeAtLocRequest::evaluate( if (auto *SVE = dyn_cast(E)) { SmallVector scratch; for (auto *result : SVE->getResultExprs(scratch)) { - auto resultCharRange = Lexer::getCharSourceRangeFromSourceRange( - SM, result->getSourceRange()); - if (resultCharRange.contains(Loc)) { + if (charRangeContainsLoc(result->getSourceRange())) { if (!result->walk(*this)) return Action::Stop(); @@ -2570,20 +2578,15 @@ bool TypeCheckASTNodeAtLocRequest::evaluate( } PreWalkAction walkToDeclPre(Decl *D) override { + if (!charRangeContainsLoc(D->getSourceRange())) + return Action::SkipNode(); + if (auto *newDC = dyn_cast(D)) DC = newDC; - if (!SM.isBeforeInBuffer(Loc, D->getStartLoc())) { - // NOTE: We need to check the character loc here because the target - // loc can be inside the last token of the node. i.e. interpolated - // string. - SourceLoc endLoc = Lexer::getLocForEndOfToken(SM, D->getEndLoc()); - if (!(SM.isBeforeInBuffer(endLoc, Loc) || endLoc == Loc)) { - if (!isa(D)) { - FoundNodeStorage = ASTNode(D); - FoundNode = &FoundNodeStorage; - } - } + if (!isa(D)) { + FoundNodeStorage = ASTNode(D); + FoundNode = &FoundNodeStorage; } return Action::Continue(); } diff --git a/lib/Sema/TypeCheckType.cpp b/lib/Sema/TypeCheckType.cpp index db9c65f867202..fb4a10055eb7d 100644 --- a/lib/Sema/TypeCheckType.cpp +++ b/lib/Sema/TypeCheckType.cpp @@ -2407,6 +2407,11 @@ namespace { class TypeAttrSet { const ASTContext &ctx; + /// FIXME: + /// `nonisolated(nonsending)` is modeled as a separate `TypeRepr`, but + /// needs to be considered together with subsequent attributes. + CallerIsolatedTypeRepr *nonisolatedNonsendingAttr; + llvm::TinyPtrVector customAttrs; EnumMap typeAttrs; @@ -2418,7 +2423,9 @@ namespace { #endif public: - TypeAttrSet(const ASTContext &ctx) : ctx(ctx) {} + TypeAttrSet(const ASTContext &ctx, + CallerIsolatedTypeRepr *nonisolatedNonsendingAttr = nullptr) + : ctx(ctx), nonisolatedNonsendingAttr(nonisolatedNonsendingAttr) {} TypeAttrSet(const TypeAttrSet &) = delete; TypeAttrSet &operator=(const TypeAttrSet &) = delete; @@ -2437,6 +2444,10 @@ namespace { /// will be diagnosed. void accumulate(ArrayRef attrs); + CallerIsolatedTypeRepr *getNonisolatedNonsendingAttr() const { + return nonisolatedNonsendingAttr; + } + /// Return all of the custom attributes. ArrayRef getCustomAttrs() const { return customAttrs; @@ -2536,9 +2547,17 @@ namespace { } template - AttrClass *getWithoutClaiming(TypeAttrSet *attrs) { + std::enable_if_t, AttrClass *> + getWithoutClaiming(TypeAttrSet *attrs) { return (attrs ? getWithoutClaiming(*attrs) : nullptr); } + + template + std::enable_if_t, + CallerIsolatedTypeRepr *> + getWithoutClaiming(TypeAttrSet *attrs) { + return attrs ? attrs->getNonisolatedNonsendingAttr() : nullptr; + } } // end anonymous namespace Type TypeResolution::resolveContextualType( @@ -4233,10 +4252,19 @@ NeverNullType TypeResolver::resolveASTFunctionType( }; if (auto concurrentAttr = claim(attrs)) { + if (auto *nonisolatedNonsendingAttr = + getWithoutClaiming(attrs)) { + diagnoseInvalid( + nonisolatedNonsendingAttr, nonisolatedNonsendingAttr->getStartLoc(), + diag::cannot_use_nonisolated_nonsending_together_with_concurrent, + nonisolatedNonsendingAttr); + } + checkExecutionBehaviorAttribute(concurrentAttr); + if (!repr->isInvalid()) isolation = FunctionTypeIsolation::forNonIsolated(); - } else { + } else if (!getWithoutClaiming(attrs)) { if (ctx.LangOpts.getFeatureState(Feature::NonisolatedNonsendingByDefault) .isEnabledForMigration()) { // Diagnose only in the interface stage, which is run once. @@ -5267,7 +5295,20 @@ TypeResolver::resolveSendingTypeRepr(SendingTypeRepr *repr, NeverNullType TypeResolver::resolveCallerIsolatedTypeRepr(CallerIsolatedTypeRepr *repr, TypeResolutionOptions options) { - Type type = resolveType(repr->getBase(), options); + Type type; + { + TypeAttrSet attrs(getASTContext(), repr); + + auto *baseRepr = repr->getBase(); + if (auto *attrRepr = dyn_cast(baseRepr)) { + baseRepr = attrs.accumulate(attrRepr); + } + + type = resolveAttributedType(baseRepr, options, attrs); + + attrs.diagnoseUnclaimed(resolution, options, type); + } + if (type->hasError()) return ErrorType::get(getASTContext()); @@ -5283,15 +5324,6 @@ TypeResolver::resolveCallerIsolatedTypeRepr(CallerIsolatedTypeRepr *repr, diag::nonisolated_nonsending_only_on_async, repr); } - if (auto *ATR = dyn_cast(repr->getBase())) { - if (ATR->get(TypeAttrKind::Concurrent)) { - diagnoseInvalid( - repr, repr->getStartLoc(), - diag::cannot_use_nonisolated_nonsending_together_with_concurrent, - repr); - } - } - switch (fnType->getIsolation().getKind()) { case FunctionTypeIsolation::Kind::NonIsolated: break; diff --git a/lib/Serialization/DeclTypeRecordNodes.def b/lib/Serialization/DeclTypeRecordNodes.def index 3ffd7b345a76f..0ee58b5d3e668 100644 --- a/lib/Serialization/DeclTypeRecordNodes.def +++ b/lib/Serialization/DeclTypeRecordNodes.def @@ -213,12 +213,12 @@ OTHER(DERIVATIVE_FUNCTION_CONFIGURATION, 154) OTHER(ERROR_FLAG, 155) OTHER(ABI_ONLY_COUNTERPART, 156) +OTHER(DECL_NAME_REF, 157) TRAILING_INFO(CONDITIONAL_SUBSTITUTION) TRAILING_INFO(CONDITIONAL_SUBSTITUTION_COND) OTHER(LIFETIME_DEPENDENCE, 160) - TRAILING_INFO(INHERITED_PROTOCOLS) #ifndef DECL_ATTR diff --git a/lib/Serialization/Deserialization.cpp b/lib/Serialization/Deserialization.cpp index e00c099d3f225..24018bf5a1425 100644 --- a/lib/Serialization/Deserialization.cpp +++ b/lib/Serialization/Deserialization.cpp @@ -3498,6 +3498,58 @@ class DeclDeserializer { /// offsets in \c customAttrOffsets. llvm::Error deserializeCustomAttrs(); + DeclNameRef deserializeDeclNameRefIfPresent() { + using namespace decls_block; + + SmallVector scratch; + StringRef blobData; + + BCOffsetRAII restoreOffset(MF.DeclTypeCursor); + llvm::BitstreamEntry entry = + MF.fatalIfUnexpected(MF.DeclTypeCursor.advance()); + + unsigned recordID = MF.fatalIfUnexpected( + MF.DeclTypeCursor.readRecord(entry.ID, scratch, &blobData)); + + if (recordID != DECL_NAME_REF) + // This is normal--it just means there isn't a DeclNameRef here. + return { DeclNameRef() }; + + bool isCompoundName; + bool hasModuleSelector; + ArrayRef rawPieceIDs; + + DeclNameRefLayout::readRecord(scratch, isCompoundName, hasModuleSelector, + rawPieceIDs); + restoreOffset.cancel(); + + Identifier moduleSelector; + DeclBaseName baseName; + + unsigned restIndex = 0; + + ASSERT(rawPieceIDs.size() > 0); + if (hasModuleSelector) { + moduleSelector = MF.getIdentifier(rawPieceIDs[restIndex]); + restIndex++; + } + + ASSERT(rawPieceIDs.size() > restIndex); + baseName = MF.getDeclBaseName(rawPieceIDs[restIndex]); + restIndex++; + + if (isCompoundName) { + SmallVector argLabels; + for (auto rawArgLabel : rawPieceIDs.drop_front(restIndex)) + argLabels.push_back(MF.getIdentifier(rawArgLabel)); + + return DeclNameRef(ctx, moduleSelector, baseName, argLabels); + } + + ASSERT(rawPieceIDs.size() == restIndex); + return DeclNameRef(ctx, moduleSelector, baseName); + } + Expected getDeclCheckedImpl( llvm::function_ref matchAttributes = nullptr); @@ -6141,56 +6193,32 @@ llvm::Error DeclDeserializer::deserializeDeclCommon() { unsigned specializationKindVal; GenericSignatureID specializedSigID; - ArrayRef rawPieceIDs; - uint64_t numArgs; + ArrayRef rawTrailingIDs; uint64_t numSPIGroups; uint64_t numAvailabilityAttrs; - uint64_t numTypeErasedParams; DeclID targetFunID; serialization::decls_block::SpecializeDeclAttrLayout::readRecord( scratch, exported, specializationKindVal, specializedSigID, - targetFunID, numArgs, numSPIGroups, numAvailabilityAttrs, - numTypeErasedParams, rawPieceIDs); + targetFunID, numSPIGroups, numAvailabilityAttrs, rawTrailingIDs); - assert(rawPieceIDs.size() == numArgs + numSPIGroups + numTypeErasedParams || - rawPieceIDs.size() == (numArgs - 1 + numSPIGroups + numTypeErasedParams)); specializationKind = specializationKindVal ? SpecializeAttr::SpecializationKind::Partial : SpecializeAttr::SpecializationKind::Full; - // The 'target' parameter. - DeclNameRef replacedFunctionName; - if (numArgs) { - bool numArgumentLabels = (numArgs == 1) ? 0 : numArgs - 2; - auto baseName = MF.getDeclBaseName(rawPieceIDs[0]); - SmallVector pieces; - if (numArgumentLabels) { - for (auto pieceID : rawPieceIDs.slice(1, numArgumentLabels)) - pieces.push_back(MF.getIdentifier(pieceID)); - } - replacedFunctionName = (numArgs == 1) - ? DeclNameRef({baseName}) // simple name - : DeclNameRef({ctx, baseName, pieces}); - } + auto specializedSig = MF.getGenericSignature(specializedSigID); + + // Take `numSPIGroups` trailing identifiers for the SPI groups. SmallVector spis; - if (numSPIGroups) { - auto numTargetFunctionPiecesToSkip = - (rawPieceIDs.size() == numArgs + numSPIGroups + numTypeErasedParams) ? numArgs - : numArgs - 1; - for (auto id : rawPieceIDs.slice(numTargetFunctionPiecesToSkip)) + for (auto id : rawTrailingIDs.take_front(numSPIGroups)) spis.push_back(MF.getIdentifier(id)); - } + // Take the rest for type-erased parameters. SmallVector typeErasedParams; - if (numTypeErasedParams) { - auto numTargetFunctionPiecesToSkip = - (rawPieceIDs.size() == numArgs + numSPIGroups + numTypeErasedParams) ? numArgs + numSPIGroups - : numArgs - 1 + numSPIGroups; - for (auto id : rawPieceIDs.slice(numTargetFunctionPiecesToSkip)) - typeErasedParams.push_back(MF.getType(id)); - } + for (auto id : rawTrailingIDs.drop_front(numSPIGroups)) + typeErasedParams.push_back(MF.getType(id)); + // Read availability attrs. SmallVector availabilityAttrs; while (numAvailabilityAttrs) { // Prepare to read the next record. @@ -6220,10 +6248,12 @@ llvm::Error DeclDeserializer::deserializeDeclCommon() { --numAvailabilityAttrs; } - auto specializedSig = MF.getGenericSignature(specializedSigID); + // Read target function DeclNameRef, if present. + DeclNameRef targetFunName = deserializeDeclNameRefIfPresent(); + Attr = SpecializeAttr::create(ctx, exported != 0, specializationKind, spis, availabilityAttrs, typeErasedParams, - specializedSig, replacedFunctionName, &MF, + specializedSig, targetFunName, &MF, targetFunID); break; } @@ -6254,21 +6284,15 @@ llvm::Error DeclDeserializer::deserializeDeclCommon() { case decls_block::DynamicReplacement_DECL_ATTR: { bool isImplicit; - uint64_t numArgs; - ArrayRef rawPieceIDs; DeclID replacedFunID; serialization::decls_block::DynamicReplacementDeclAttrLayout:: - readRecord(scratch, isImplicit, replacedFunID, numArgs, rawPieceIDs); + readRecord(scratch, isImplicit, replacedFunID); - auto baseName = MF.getDeclBaseName(rawPieceIDs[0]); - SmallVector pieces; - for (auto pieceID : rawPieceIDs.slice(1)) - pieces.push_back(MF.getIdentifier(pieceID)); + DeclNameRef replacedFunName = deserializeDeclNameRefIfPresent(); - assert(numArgs != 0); assert(!isImplicit && "Need to update for implicit"); - Attr = DynamicReplacementAttr::create( - ctx, DeclNameRef({ ctx, baseName, pieces }), &MF, replacedFunID); + Attr = DynamicReplacementAttr::create(ctx, replacedFunName, &MF, + replacedFunID); break; } @@ -6339,7 +6363,6 @@ llvm::Error DeclDeserializer::deserializeDeclCommon() { case decls_block::Derivative_DECL_ATTR: { bool isImplicit; - uint64_t origNameId; bool hasAccessorKind; uint64_t rawAccessorKind; DeclID origDeclId; @@ -6347,7 +6370,7 @@ llvm::Error DeclDeserializer::deserializeDeclCommon() { ArrayRef parameters; serialization::decls_block::DerivativeDeclAttrLayout::readRecord( - scratch, isImplicit, origNameId, hasAccessorKind, rawAccessorKind, + scratch, isImplicit, hasAccessorKind, rawAccessorKind, origDeclId, rawDerivativeKind, parameters); std::optional accessorKind = std::nullopt; @@ -6358,8 +6381,6 @@ llvm::Error DeclDeserializer::deserializeDeclCommon() { accessorKind = *maybeAccessorKind; } - DeclNameRefWithLoc origName{DeclNameRef(MF.getDeclBaseName(origNameId)), - DeclNameLoc(), accessorKind}; auto derivativeKind = getActualAutoDiffDerivativeFunctionKind(rawDerivativeKind); if (!derivativeKind) @@ -6369,9 +6390,14 @@ llvm::Error DeclDeserializer::deserializeDeclCommon() { parametersBitVector[i] = parameters[i]; auto *indices = IndexSubset::get(ctx, parametersBitVector); + auto origName = deserializeDeclNameRefIfPresent(); + DeclNameRefWithLoc origNameWithLoc{origName, DeclNameLoc(), + accessorKind}; + auto *derivativeAttr = DerivativeAttr::create(ctx, isImplicit, SourceLoc(), SourceRange(), - /*baseType*/ nullptr, origName, indices); + /*baseType*/ nullptr, origNameWithLoc, + indices); derivativeAttr->setOriginalFunctionResolver(&MF, origDeclId); derivativeAttr->setDerivativeKind(*derivativeKind); Attr = derivativeAttr; @@ -6380,20 +6406,21 @@ llvm::Error DeclDeserializer::deserializeDeclCommon() { case decls_block::Transpose_DECL_ATTR: { bool isImplicit; - uint64_t origNameId; DeclID origDeclId; ArrayRef parameters; serialization::decls_block::TransposeDeclAttrLayout::readRecord( - scratch, isImplicit, origNameId, origDeclId, parameters); + scratch, isImplicit, origDeclId, parameters); - DeclNameRefWithLoc origName{DeclNameRef(MF.getDeclBaseName(origNameId)), - DeclNameLoc(), std::nullopt}; auto *origDecl = cast(MF.getDecl(origDeclId)); llvm::SmallBitVector parametersBitVector(parameters.size()); for (unsigned i : indices(parameters)) parametersBitVector[i] = parameters[i]; auto *indices = IndexSubset::get(ctx, parametersBitVector); + + auto origNameRef = deserializeDeclNameRefIfPresent(); + DeclNameRefWithLoc origName{origNameRef, DeclNameLoc(), std::nullopt}; + auto *transposeAttr = TransposeAttr::create(ctx, isImplicit, SourceLoc(), SourceRange(), /*baseTypeRepr*/ nullptr, origName, indices); @@ -6517,6 +6544,17 @@ llvm::Error DeclDeserializer::deserializeDeclCommon() { break; } + case decls_block::InheritActorContext_DECL_ATTR: { + unsigned modifier; + bool isImplicit{}; + serialization::decls_block::InheritActorContextDeclAttrLayout:: + readRecord(scratch, modifier, isImplicit); + Attr = new (ctx) InheritActorContextAttr( + {}, {}, static_cast(modifier), + isImplicit); + break; + } + case decls_block::MacroRole_DECL_ATTR: { bool isImplicit; uint8_t rawMacroSyntax; diff --git a/lib/Serialization/DeserializeSIL.cpp b/lib/Serialization/DeserializeSIL.cpp index 75d10adf1e213..2cffe5ae07f3a 100644 --- a/lib/Serialization/DeserializeSIL.cpp +++ b/lib/Serialization/DeserializeSIL.cpp @@ -2452,6 +2452,15 @@ bool SILDeserializer::readSILInstruction(SILFunction *Fn, getSILType(Ty2, (SILValueCategory)TyCategory2, Fn))); break; } + case SILInstructionKind::VectorBaseAddrInst: { + assert(RecordKind == SIL_ONE_TYPE_ONE_OPERAND); + ResultInst = Builder.createVectorBaseAddr( + Loc, + getLocalValue( + Builder.maybeGetFunction(), ValID, + getSILType(MF->getType(TyID2), (SILValueCategory)TyCategory2, Fn))); + break; + } case SILInstructionKind::IndexAddrInst: { auto Ty = MF->getType(TyID); auto Ty2 = MF->getType(TyID2); diff --git a/lib/Serialization/ModuleFormat.h b/lib/Serialization/ModuleFormat.h index 461c59d27ad36..fe4b2a33216ef 100644 --- a/lib/Serialization/ModuleFormat.h +++ b/lib/Serialization/ModuleFormat.h @@ -58,7 +58,7 @@ const uint16_t SWIFTMODULE_VERSION_MAJOR = 0; /// describe what change you made. The content of this comment isn't important; /// it just ensures a conflict if two people change the module format. /// Don't worry about adhering to the 80-column limit for this line. -const uint16_t SWIFTMODULE_VERSION_MINOR = 948; // remove SwiftSettings +const uint16_t SWIFTMODULE_VERSION_MINOR = 951; // add modifier to @_inheritActorContext /// A standard hash seed used for all string hashes in a serialized module. /// @@ -1258,6 +1258,15 @@ namespace decls_block { DeclIDField // API decl >; + /// A field containing the pieces of a \c DeclNameRef and the information + /// needed to reconstruct it. + using DeclNameRefLayout = BCRecordLayout< + DECL_NAME_REF, + BCFixed<1>, // isCompoundName + BCFixed<1>, // hasModuleSelector + BCArray // module selector, base name, arg labels + >; + /// A placeholder for invalid types TYPE_LAYOUT(ErrorTypeLayout, ERROR_TYPE, @@ -2444,11 +2453,9 @@ namespace decls_block { BCFixed<1>, // specialization kind GenericSignatureIDField, // specialized signature DeclIDField, // target function - BCVBR<4>, // # of arguments (+1) or 1 if simple decl name, 0 if no target BCVBR<4>, // # of SPI groups BCVBR<4>, // # of availability attributes - BCVBR<4>, // # of type erased parameters - BCArray // target function pieces, spi groups, type erased params + BCArray // spi groups, type erased params >; using StorageRestrictionsDeclAttrLayout = BCRecordLayout< @@ -2468,7 +2475,6 @@ namespace decls_block { using DerivativeDeclAttrLayout = BCRecordLayout< Derivative_DECL_ATTR, BCFixed<1>, // Implicit flag. - IdentifierIDField, // Original name. BCFixed<1>, // Has original accessor kind? AccessorKindField, // Original accessor kind. DeclIDField, // Original function declaration. @@ -2479,7 +2485,6 @@ namespace decls_block { using TransposeDeclAttrLayout = BCRecordLayout< Transpose_DECL_ATTR, BCFixed<1>, // Implicit flag. - IdentifierIDField, // Original name. DeclIDField, // Original function declaration. BCArray> // Transposed parameter indices' bitvector. >; @@ -2494,9 +2499,7 @@ namespace decls_block { using DynamicReplacementDeclAttrLayout = BCRecordLayout< DynamicReplacement_DECL_ATTR, BCFixed<1>, // implicit flag - DeclIDField, // replaced function - BCVBR<4>, // # of arguments (+1) or zero if no name - BCArray + DeclIDField // replaced function >; using TypeEraserDeclAttrLayout = BCRecordLayout< @@ -2553,6 +2556,12 @@ namespace decls_block { BCFixed<1> // implicit flag >; + using InheritActorContextDeclAttrLayout = + BCRecordLayout, // the modifier (none = 0, always = 1) + BCFixed<1> // implicit flag + >; + using MacroRoleDeclAttrLayout = BCRecordLayout< MacroRole_DECL_ATTR, BCFixed<1>, // implicit flag diff --git a/lib/Serialization/ScanningLoaders.cpp b/lib/Serialization/ScanningLoaders.cpp index 516b834f580b7..2b90236952336 100644 --- a/lib/Serialization/ScanningLoaders.cpp +++ b/lib/Serialization/ScanningLoaders.cpp @@ -231,16 +231,6 @@ SwiftModuleScanner::scanInterfaceFile(Twine moduleInterfacePath, InPath, compiledCandidatesRefs, ArgsRefs, {}, {}, linkLibraries, isFramework, isStatic, {}, /*module-cache-key*/ "", UserModVer); - if (Ctx.CASOpts.EnableCaching) { - std::vector clangDependencyFiles; - auto clangImporter = - static_cast(Ctx.getClangModuleLoader()); - clangImporter->addClangInvovcationDependencies(clangDependencyFiles); - llvm::for_each(clangDependencyFiles, [&](std::string &file) { - Result->addAuxiliaryFile(file); - }); - } - // Walk the source file to find the import declarations. llvm::StringSet<> alreadyAddedModules; Result->addModuleImports(*sourceFile, alreadyAddedModules, diff --git a/lib/Serialization/Serialization.cpp b/lib/Serialization/Serialization.cpp index adc4742aeb497..e27c7033c0d52 100644 --- a/lib/Serialization/Serialization.cpp +++ b/lib/Serialization/Serialization.cpp @@ -3204,49 +3204,34 @@ class Serializer::DeclSerializer : public DeclVisitor { case DeclAttrKind::Specialize: { auto abbrCode = S.DeclTypeAbbrCodes[SpecializeDeclAttrLayout::Code]; auto attr = cast(DA); - auto targetFun = attr->getTargetFunctionName(); auto *afd = cast(D); auto *targetFunDecl = attr->getTargetFunctionDecl(afd); SmallVector pieces; - // encodes whether this a a simple or compound name by adding one. - size_t numArgs = 0; - if (targetFun) { - pieces.push_back(S.addDeclBaseNameRef(targetFun.getBaseName())); - for (auto argName : targetFun.getArgumentNames()) - pieces.push_back(S.addDeclBaseNameRef(argName)); - if (targetFun.isSimpleName()) { - assert(pieces.size() == 1); - numArgs = 1; - } else - numArgs = pieces.size() + 1; - } - + // SPI groups + auto numSPIGroups = attr->getSPIGroups().size(); for (auto spi : attr->getSPIGroups()) { assert(!spi.empty() && "Empty SPI name"); pieces.push_back(S.addDeclBaseNameRef(spi)); } + // Type-erased params for (auto ty : attr->getTypeErasedParams()) { pieces.push_back(S.addTypeRef(ty)); } - auto numSPIGroups = attr->getSPIGroups().size(); - auto numTypeErasedParams = attr->getTypeErasedParams().size(); - assert(pieces.size() == numArgs + numSPIGroups + numTypeErasedParams || - pieces.size() == (numArgs - 1 + numSPIGroups + numTypeErasedParams)); auto numAvailabilityAttrs = attr->getAvailableAttrs().size(); SpecializeDeclAttrLayout::emitRecord( S.Out, S.ScratchRecord, abbrCode, (unsigned)attr->isExported(), (unsigned)attr->getSpecializationKind(), S.addGenericSignatureRef(attr->getSpecializedSignature(afd)), - S.addDeclRef(targetFunDecl), numArgs, numSPIGroups, - numAvailabilityAttrs, numTypeErasedParams, + S.addDeclRef(targetFunDecl), numSPIGroups, numAvailabilityAttrs, pieces); for (auto availAttr : attr->getAvailableAttrs()) { writeDeclAttribute(D, availAttr); } + writeDeclNameRefIfNeeded(attr->getTargetFunctionName()); return; } @@ -3278,16 +3263,13 @@ class Serializer::DeclSerializer : public DeclVisitor { auto abbrCode = S.DeclTypeAbbrCodes[DynamicReplacementDeclAttrLayout::Code]; auto theAttr = cast(DA); - auto replacedFun = theAttr->getReplacedFunctionName(); - SmallVector pieces; - pieces.push_back(S.addDeclBaseNameRef(replacedFun.getBaseName())); - for (auto argName : replacedFun.getArgumentNames()) - pieces.push_back(S.addDeclBaseNameRef(argName)); + auto *afd = cast(D)->getDynamicallyReplacedDecl(); assert(afd && "Missing replaced decl!"); DynamicReplacementDeclAttrLayout::emitRecord( S.Out, S.ScratchRecord, abbrCode, false, /*implicit flag*/ - S.addDeclRef(afd), pieces.size(), pieces); + S.addDeclRef(afd)); + writeDeclNameRefIfNeeded(theAttr->getReplacedFunctionName()); return; } @@ -3360,8 +3342,7 @@ class Serializer::DeclSerializer : public DeclVisitor { "`@derivative` attribute should have original declaration set " "during construction or parsing"); auto origDeclNameRef = attr->getOriginalFunctionName(); - auto origName = origDeclNameRef.Name.getBaseName(); - IdentifierID origNameId = S.addDeclBaseNameRef(origName); + DeclID origDeclID = S.addDeclRef(attr->getOriginalFunction(ctx)); auto derivativeKind = getRawStableAutoDiffDerivativeFunctionKind(attr->getDerivativeKind()); @@ -3375,9 +3356,10 @@ class Serializer::DeclSerializer : public DeclVisitor { for (unsigned i : range(parameterIndices->getCapacity())) paramIndicesVector.push_back(parameterIndices->contains(i)); DerivativeDeclAttrLayout::emitRecord( - S.Out, S.ScratchRecord, abbrCode, attr->isImplicit(), origNameId, + S.Out, S.ScratchRecord, abbrCode, attr->isImplicit(), origAccessorKind.has_value(), rawAccessorKind, origDeclID, derivativeKind, paramIndicesVector); + writeDeclNameRefIfNeeded(origDeclNameRef.Name); return; } @@ -3387,8 +3369,7 @@ class Serializer::DeclSerializer : public DeclVisitor { assert(attr->getOriginalFunction() && "`@transpose` attribute should have original declaration set " "during construction or parsing"); - auto origName = attr->getOriginalFunctionName().Name.getBaseName(); - IdentifierID origNameId = S.addDeclBaseNameRef(origName); + DeclID origDeclID = S.addDeclRef(attr->getOriginalFunction()); auto *parameterIndices = attr->getParameterIndices(); assert(parameterIndices && "Parameter indices must be resolved"); @@ -3396,8 +3377,9 @@ class Serializer::DeclSerializer : public DeclVisitor { for (unsigned i : range(parameterIndices->getCapacity())) paramIndicesVector.push_back(parameterIndices->contains(i)); TransposeDeclAttrLayout::emitRecord( - S.Out, S.ScratchRecord, abbrCode, attr->isImplicit(), origNameId, - origDeclID, paramIndicesVector); + S.Out, S.ScratchRecord, abbrCode, attr->isImplicit(), origDeclID, + paramIndicesVector); + writeDeclNameRefIfNeeded(attr->getOriginalFunctionName().Name); return; } @@ -3469,6 +3451,16 @@ class Serializer::DeclSerializer : public DeclVisitor { return; } + case DeclAttrKind::InheritActorContext: { + auto *theAttr = cast(DA); + auto abbrCode = + S.DeclTypeAbbrCodes[InheritActorContextDeclAttrLayout::Code]; + InheritActorContextDeclAttrLayout::emitRecord( + S.Out, S.ScratchRecord, abbrCode, + static_cast(theAttr->getModifier()), theAttr->isImplicit()); + return; + } + case DeclAttrKind::MacroRole: { auto *theAttr = cast(DA); auto abbrCode = S.DeclTypeAbbrCodes[MacroRoleDeclAttrLayout::Code]; @@ -3621,6 +3613,32 @@ class Serializer::DeclSerializer : public DeclVisitor { } } + void writeDeclNameRefIfNeeded(DeclNameRef name) { + using namespace decls_block; + + // DeclNameRefs are always optional and write nothing when absent. + if (!name) + return; + + bool isCompoundName = name.isCompoundName(); + bool hasModuleSelector = name.hasModuleSelector(); + SmallVector rawPieceIDs; + + if (hasModuleSelector) + rawPieceIDs.push_back(S.addDeclBaseNameRef(name.getModuleSelector())); + + rawPieceIDs.push_back(S.addDeclBaseNameRef(name.getBaseName())); + + if (isCompoundName) + for (auto argName : name.getArgumentNames()) + rawPieceIDs.push_back(S.addDeclBaseNameRef(argName)); + + auto abbrCode = S.DeclTypeAbbrCodes[DeclNameRefLayout::Code]; + DeclNameRefLayout::emitRecord(S.Out, S.ScratchRecord, abbrCode, + isCompoundName, hasModuleSelector, + rawPieceIDs); + } + size_t addConformances(const IterableDeclContext *declContext, ConformanceLookupKind lookupKind, SmallVectorImpl &data) { @@ -6337,6 +6355,7 @@ void Serializer::writeAllDeclsAndTypes() { registerDeclTypeAbbr(); registerDeclTypeAbbr(); registerDeclTypeAbbr(); + registerDeclTypeAbbr(); registerDeclTypeAbbr(); diff --git a/lib/Serialization/SerializeSIL.cpp b/lib/Serialization/SerializeSIL.cpp index 043b2dc17b0a5..facf968ab331f 100644 --- a/lib/Serialization/SerializeSIL.cpp +++ b/lib/Serialization/SerializeSIL.cpp @@ -2177,6 +2177,7 @@ void SILSerializer::writeSILInstruction(const SILInstruction &SI) { case SILInstructionKind::UncheckedTrivialBitCastInst: case SILInstructionKind::UncheckedBitwiseCastInst: case SILInstructionKind::UncheckedValueCastInst: + case SILInstructionKind::VectorBaseAddrInst: case SILInstructionKind::BridgeObjectToRefInst: case SILInstructionKind::BridgeObjectToWordInst: case SILInstructionKind::UpcastInst: diff --git a/lib/Serialization/SerializedModuleLoader.cpp b/lib/Serialization/SerializedModuleLoader.cpp index 7973372e613bc..ab37e7c368020 100644 --- a/lib/Serialization/SerializedModuleLoader.cpp +++ b/lib/Serialization/SerializedModuleLoader.cpp @@ -108,14 +108,11 @@ std::optional forEachModuleSearchPath( callback(path.Path, ModuleSearchPathKind::Framework, path.IsSystem)) return result; - // Apple platforms have extra implicit framework search paths: - // $SDKROOT/System/Library/Frameworks/ and $SDKROOT/Library/Frameworks/. - if (Ctx.LangOpts.Target.isOSDarwin()) { - for (const auto &path : Ctx.getDarwinImplicitFrameworkSearchPaths()) - if (auto result = - callback(path, ModuleSearchPathKind::DarwinImplicitFramework, - /*isSystem=*/true)) - return result; + for (const auto &path : + Ctx.SearchPathOpts.getImplicitFrameworkSearchPaths()) { + if (auto result = callback(path, ModuleSearchPathKind::ImplicitFramework, + /*isSystem=*/true)) + return result; } for (const auto &importPath : @@ -240,7 +237,7 @@ void SerializedModuleLoaderBase::collectVisibleTopLevelModuleNamesImpl( return std::nullopt; } case ModuleSearchPathKind::Framework: - case ModuleSearchPathKind::DarwinImplicitFramework: { + case ModuleSearchPathKind::ImplicitFramework: { // Look for: // $PATH/{name}.framework/Modules/{name}.swiftmodule/{arch}.{extension} forEachDirectoryEntryPath(searchPath, [&](StringRef path) { @@ -964,7 +961,7 @@ bool SerializedModuleLoaderBase::findModule( continue; } case ModuleSearchPathKind::Framework: - case ModuleSearchPathKind::DarwinImplicitFramework: { + case ModuleSearchPathKind::ImplicitFramework: { isFramework = true; llvm::sys::path::append(currPath, moduleName + ".framework"); diff --git a/stdlib/public/CommandLineSupport/CommandLine.cpp b/stdlib/public/CommandLineSupport/CommandLine.cpp index e1bc1e87df6bc..f6f7e58d7c684 100644 --- a/stdlib/public/CommandLineSupport/CommandLine.cpp +++ b/stdlib/public/CommandLineSupport/CommandLine.cpp @@ -135,7 +135,11 @@ char **_swift_stdlib_getUnsafeArgvArgc(int *outArgLen) { } } +#if defined(_WIN32) + argv[argc] = _strdup(arg); +#else argv[argc] = strdup(arg); +#endif argc += 1; }); diff --git a/stdlib/public/Concurrency/CFExecutor.swift b/stdlib/public/Concurrency/CFExecutor.swift index 451e0860e7975..4a28ace18f6db 100644 --- a/stdlib/public/Concurrency/CFExecutor.swift +++ b/stdlib/public/Concurrency/CFExecutor.swift @@ -44,13 +44,13 @@ enum CoreFoundation { // .. Main Executor ............................................................ @available(SwiftStdlib 6.2, *) -public final class CFMainExecutor: DispatchMainExecutor, @unchecked Sendable { +public final class _CFMainExecutor: _DispatchMainExecutor, @unchecked Sendable { - override public func run() throws { + override public func _run() throws { CoreFoundation.CFRunLoopRun() } - override public func stop() { + override public func _stop() { unsafe CoreFoundation.CFRunLoopStop(CoreFoundation.CFRunLoopGetMain()) } @@ -59,8 +59,8 @@ public final class CFMainExecutor: DispatchMainExecutor, @unchecked Sendable { // .. Task Executor ............................................................ @available(SwiftStdlib 6.2, *) -public final class CFTaskExecutor: DispatchGlobalTaskExecutor, - @unchecked Sendable { +public final class _CFTaskExecutor: _DispatchGlobalTaskExecutor, + @unchecked Sendable { } diff --git a/stdlib/public/Concurrency/Clock.swift b/stdlib/public/Concurrency/Clock.swift index 8c6864ca3447c..2d363883260e5 100644 --- a/stdlib/public/Concurrency/Clock.swift +++ b/stdlib/public/Concurrency/Clock.swift @@ -44,7 +44,7 @@ public protocol Clock: Sendable { /// The traits associated with this clock instance. @available(SwiftStdlib 6.2, *) - var traits: ClockTraits { get } + var _traits: _ClockTraits { get } /// Convert a Clock-specific Duration to a Swift Duration /// @@ -60,7 +60,7 @@ public protocol Clock: Sendable { /// Returns: A `Swift.Duration` representing the equivalent duration, or /// `nil` if this function is not supported. @available(SwiftStdlib 6.2, *) - func convert(from duration: Duration) -> Swift.Duration? + func _convert(from duration: Duration) -> Swift.Duration? /// Convert a Swift Duration to a Clock-specific Duration /// @@ -71,7 +71,7 @@ public protocol Clock: Sendable { /// Returns: A `Duration` representing the equivalent duration, or /// `nil` if this function is not supported. @available(SwiftStdlib 6.2, *) - func convert(from duration: Swift.Duration) -> Duration? + func _convert(from duration: Swift.Duration) -> Duration? /// Convert an `Instant` from some other clock's `Instant` /// @@ -83,8 +83,8 @@ public protocol Clock: Sendable { /// Returns: An `Instant` representing the equivalent instant, or /// `nil` if this function is not supported. @available(SwiftStdlib 6.2, *) - func convert(instant: OtherClock.Instant, - from clock: OtherClock) -> Instant? + func _convert(instant: OtherClock.Instant, + from clock: OtherClock) -> Instant? } @available(SwiftStdlib 5.7, *) @@ -143,27 +143,27 @@ extension Clock { @available(SwiftStdlib 6.2, *) extension Clock { // For compatibility, return `nil` if this is not implemented - public func convert(from duration: Duration) -> Swift.Duration? { + public func _convert(from duration: Duration) -> Swift.Duration? { return nil } - public func convert(from duration: Swift.Duration) -> Duration? { + public func _convert(from duration: Swift.Duration) -> Duration? { return nil } - public func convert(instant: OtherClock.Instant, - from clock: OtherClock) -> Instant? { + public func _convert(instant: OtherClock.Instant, + from clock: OtherClock) -> Instant? { let ourNow = now let otherNow = clock.now let otherDuration = otherNow.duration(to: instant) // Convert to `Swift.Duration` - guard let duration = clock.convert(from: otherDuration) else { + guard let duration = clock._convert(from: otherDuration) else { return nil } // Convert from `Swift.Duration` - guard let ourDuration = convert(from: duration) else { + guard let ourDuration = _convert(from: duration) else { return nil } @@ -173,7 +173,7 @@ extension Clock { @available(SwiftStdlib 6.2, *) extension Clock where Duration == Swift.Duration { - public func convert(from duration: Duration) -> Duration? { + public func _convert(from duration: Duration) -> Duration? { return duration } } @@ -208,7 +208,7 @@ extension Clock { /// time or delay in. Executors are expected to do this on a best effort /// basis. @available(SwiftStdlib 6.2, *) -public struct ClockTraits: OptionSet { +public struct _ClockTraits: OptionSet { public let rawValue: UInt32 public init(rawValue: UInt32) { @@ -216,20 +216,20 @@ public struct ClockTraits: OptionSet { } /// Clocks with this trait continue running while the machine is asleep. - public static let continuous = ClockTraits(rawValue: 1 << 0) + public static let continuous = _ClockTraits(rawValue: 1 << 0) /// Indicates that a clock's time will only ever increase. - public static let monotonic = ClockTraits(rawValue: 1 << 1) + public static let monotonic = _ClockTraits(rawValue: 1 << 1) /// Clocks with this trait are tied to "wall time". - public static let wallTime = ClockTraits(rawValue: 1 << 2) + public static let wallTime = _ClockTraits(rawValue: 1 << 2) } @available(SwiftStdlib 6.2, *) extension Clock { /// The traits associated with this clock instance. @available(SwiftStdlib 6.2, *) - public var traits: ClockTraits { + public var _traits: _ClockTraits { return [] } } diff --git a/stdlib/public/Concurrency/ContinuousClock.swift b/stdlib/public/Concurrency/ContinuousClock.swift index 2841ca4036788..90b7a3e41b775 100644 --- a/stdlib/public/Concurrency/ContinuousClock.swift +++ b/stdlib/public/Concurrency/ContinuousClock.swift @@ -102,7 +102,7 @@ extension ContinuousClock: Clock { /// The continuous clock is continuous and monotonic @available(SwiftStdlib 6.2, *) - public var traits: ClockTraits { + public var _traits: _ClockTraits { return [.continuous, .monotonic] } diff --git a/stdlib/public/Concurrency/CooperativeExecutor.swift b/stdlib/public/Concurrency/CooperativeExecutor.swift index 794f9fc542a2a..3bb8efabc93f9 100644 --- a/stdlib/public/Concurrency/CooperativeExecutor.swift +++ b/stdlib/public/Concurrency/CooperativeExecutor.swift @@ -21,37 +21,37 @@ import Swift extension ExecutorJob { fileprivate var cooperativeExecutorTimestampIsIndirect: Bool { return MemoryLayout<(Int, Int)>.size - < MemoryLayout.size + < MemoryLayout<_CooperativeExecutor.Timestamp>.size } - fileprivate var cooperativeExecutorTimestampPointer: UnsafeMutablePointer { + fileprivate var cooperativeExecutorTimestampPointer: UnsafeMutablePointer<_CooperativeExecutor.Timestamp> { get { assert(cooperativeExecutorTimestampIsIndirect) - return unsafe withUnsafeExecutorPrivateData { - unsafe $0.withMemoryRebound(to: UnsafeMutablePointer.self) { + return unsafe _withUnsafeExecutorPrivateData { + unsafe $0.withMemoryRebound(to: UnsafeMutablePointer<_CooperativeExecutor.Timestamp>.self) { return unsafe $0[0] } } } set { assert(cooperativeExecutorTimestampIsIndirect) - unsafe withUnsafeExecutorPrivateData { - unsafe $0.withMemoryRebound(to: UnsafeMutablePointer.self) { + unsafe _withUnsafeExecutorPrivateData { + unsafe $0.withMemoryRebound(to: UnsafeMutablePointer<_CooperativeExecutor.Timestamp>.self) { unsafe $0[0] = newValue } } } } - fileprivate var cooperativeExecutorTimestamp: CooperativeExecutor.Timestamp { + fileprivate var cooperativeExecutorTimestamp: _CooperativeExecutor.Timestamp { get { if cooperativeExecutorTimestampIsIndirect { let ptr = unsafe cooperativeExecutorTimestampPointer return unsafe ptr.pointee } else { - return unsafe withUnsafeExecutorPrivateData { + return unsafe _withUnsafeExecutorPrivateData { return unsafe $0.assumingMemoryBound( - to: CooperativeExecutor.Timestamp.self + to: _CooperativeExecutor.Timestamp.self )[0] } } @@ -61,8 +61,8 @@ extension ExecutorJob { let ptr = unsafe cooperativeExecutorTimestampPointer unsafe ptr.pointee = newValue } else { - unsafe withUnsafeExecutorPrivateData { - unsafe $0.withMemoryRebound(to: CooperativeExecutor.Timestamp.self) { + unsafe _withUnsafeExecutorPrivateData { + unsafe $0.withMemoryRebound(to: _CooperativeExecutor.Timestamp.self) { unsafe $0[0] = newValue } } @@ -73,10 +73,10 @@ extension ExecutorJob { fileprivate mutating func setupCooperativeExecutorTimestamp() { // If a Timestamp won't fit, allocate if cooperativeExecutorTimestampIsIndirect { - let ptr: UnsafeMutablePointer + let ptr: UnsafeMutablePointer<_CooperativeExecutor.Timestamp> // Try to use the task allocator if it has one if let allocator { - unsafe ptr = allocator.allocate(as: CooperativeExecutor.Timestamp.self) + unsafe ptr = allocator.allocate(as: _CooperativeExecutor.Timestamp.self) } else { unsafe ptr = .allocate(capacity: 1) } @@ -100,7 +100,7 @@ extension ExecutorJob { /// A co-operative executor that can be used as the main executor or as a /// task executor. @available(SwiftStdlib 6.2, *) -class CooperativeExecutor: Executor, @unchecked Sendable { +class _CooperativeExecutor: Executor, @unchecked Sendable { var runQueue: PriorityQueue var waitQueue: PriorityQueue var shouldStop: Bool = false @@ -174,13 +174,13 @@ class CooperativeExecutor: Executor, @unchecked Sendable { runQueue.push(UnownedJob(job)) } - public var isMainExecutor: Bool { true } + public var _isMainExecutor: Bool { true } - public var asSchedulable: any SchedulableExecutor { self } + public var _asSchedulable: any _SchedulableExecutor { self } } @available(SwiftStdlib 6.2, *) -extension CooperativeExecutor: SchedulableExecutor { +extension _CooperativeExecutor: _SchedulableExecutor { var currentTime: Timestamp { var now: Timestamp = .zero unsafe _getTime(seconds: &now.seconds, @@ -189,11 +189,11 @@ extension CooperativeExecutor: SchedulableExecutor { return now } - public func enqueue(_ job: consuming ExecutorJob, - after delay: C.Duration, - tolerance: C.Duration? = nil, - clock: C) { - let duration = Duration(from: clock.convert(from: delay)!) + public func _enqueue(_ job: consuming ExecutorJob, + after delay: C.Duration, + tolerance: C.Duration? = nil, + clock: C) { + let duration = Duration(from: clock._convert(from: delay)!) let deadline = self.currentTime + duration job.setupCooperativeExecutorTimestamp() @@ -203,12 +203,12 @@ extension CooperativeExecutor: SchedulableExecutor { } @available(SwiftStdlib 6.2, *) -extension CooperativeExecutor: RunLoopExecutor { - public func run() throws { - try runUntil { false } +extension _CooperativeExecutor: _RunLoopExecutor { + public func _run() throws { + try _runUntil { false } } - public func runUntil(_ condition: () -> Bool) throws { + public func _runUntil(_ condition: () -> Bool) throws { shouldStop = false while !shouldStop && !condition() { // Process the timer queue @@ -244,18 +244,18 @@ extension CooperativeExecutor: RunLoopExecutor { } } - public func stop() { + public func _stop() { shouldStop = true } } @available(SwiftStdlib 6.2, *) -extension CooperativeExecutor: SerialExecutor {} +extension _CooperativeExecutor: SerialExecutor {} @available(SwiftStdlib 6.2, *) -extension CooperativeExecutor: TaskExecutor {} +extension _CooperativeExecutor: TaskExecutor {} @available(SwiftStdlib 6.2, *) -extension CooperativeExecutor: MainExecutor {} +extension _CooperativeExecutor: _MainExecutor {} #endif // !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY diff --git a/stdlib/public/Concurrency/DispatchExecutor.swift b/stdlib/public/Concurrency/DispatchExecutor.swift index 11a372b14d1f9..df2b1a149bf63 100644 --- a/stdlib/public/Concurrency/DispatchExecutor.swift +++ b/stdlib/public/Concurrency/DispatchExecutor.swift @@ -24,12 +24,12 @@ import Swift // .. Main Executor ............................................................ @available(SwiftStdlib 6.2, *) -public class DispatchMainExecutor: RunLoopExecutor, @unchecked Sendable { +public class _DispatchMainExecutor: _RunLoopExecutor, @unchecked Sendable { var threaded = false public init() {} - public func run() throws { + public func _run() throws { if threaded { fatalError("DispatchMainExecutor does not support recursion") } @@ -38,19 +38,19 @@ public class DispatchMainExecutor: RunLoopExecutor, @unchecked Sendable { _dispatchMain() } - public func stop() { + public func _stop() { fatalError("DispatchMainExecutor cannot be stopped") } } @available(SwiftStdlib 6.2, *) -extension DispatchMainExecutor: SerialExecutor { +extension _DispatchMainExecutor: SerialExecutor { public func enqueue(_ job: consuming ExecutorJob) { _dispatchEnqueueMain(UnownedJob(job)) } - public var isMainExecutor: Bool { true } + public var _isMainExecutor: Bool { true } public func checkIsolated() { _dispatchAssertMainQueue() @@ -58,15 +58,15 @@ extension DispatchMainExecutor: SerialExecutor { } @available(SwiftStdlib 6.2, *) -extension DispatchMainExecutor: SchedulableExecutor { - public var asSchedulable: SchedulableExecutor? { +extension _DispatchMainExecutor: _SchedulableExecutor { + public var _asSchedulable: _SchedulableExecutor? { return self } - public func enqueue(_ job: consuming ExecutorJob, - at instant: C.Instant, - tolerance: C.Duration? = nil, - clock: C) { + public func _enqueue(_ job: consuming ExecutorJob, + at instant: C.Instant, + tolerance: C.Duration? = nil, + clock: C) { let tolSec, tolNanosec: CLongLong if let tolerance = tolerance { (tolSec, tolNanosec) = delay(from: tolerance, clock: clock) @@ -86,25 +86,25 @@ extension DispatchMainExecutor: SchedulableExecutor { } @available(SwiftStdlib 6.2, *) -extension DispatchMainExecutor: MainExecutor {} +extension _DispatchMainExecutor: _MainExecutor {} // .. Task Executor ............................................................ @available(SwiftStdlib 6.2, *) -public class DispatchGlobalTaskExecutor: TaskExecutor, SchedulableExecutor, - @unchecked Sendable { +public class _DispatchGlobalTaskExecutor: TaskExecutor, _SchedulableExecutor, + @unchecked Sendable { public init() {} public func enqueue(_ job: consuming ExecutorJob) { _dispatchEnqueueGlobal(UnownedJob(job)) } - public var isMainExecutor: Bool { false } + public var _isMainExecutor: Bool { false } - public func enqueue(_ job: consuming ExecutorJob, - at instant: C.Instant, - tolerance: C.Duration? = nil, - clock: C) { + public func _enqueue(_ job: consuming ExecutorJob, + at instant: C.Instant, + tolerance: C.Duration? = nil, + clock: C) { let tolSec, tolNanosec: CLongLong if let tolerance = tolerance { (tolSec, tolNanosec) = delay(from: tolerance, clock: clock) @@ -172,9 +172,9 @@ extension DispatchExecutorProtocol { func timestamp(for instant: C.Instant, clock: C) -> (clockID: DispatchClockID, seconds: Int64, nanoseconds: Int64) { - if clock.traits.contains(.continuous) { + if clock._traits.contains(.continuous) { let dispatchClock: ContinuousClock = .continuous - let instant = dispatchClock.convert(instant: instant, from: clock)! + let instant = dispatchClock._convert(instant: instant, from: clock)! let (seconds, attoseconds) = clamp(instant._value.components) let nanoseconds = attoseconds / 1_000_000_000 return (clockID: .continuous, @@ -182,7 +182,7 @@ extension DispatchExecutorProtocol { nanoseconds: Int64(nanoseconds)) } else { let dispatchClock: SuspendingClock = .suspending - let instant = dispatchClock.convert(instant: instant, from: clock)! + let instant = dispatchClock._convert(instant: instant, from: clock)! let (seconds, attoseconds) = clamp(instant._value.components) let nanoseconds = attoseconds / 1_000_000_000 return (clockID: .suspending, @@ -193,7 +193,7 @@ extension DispatchExecutorProtocol { func delay(from duration: C.Duration, clock: C) -> (seconds: Int64, nanoseconds: Int64) { - let swiftDuration = clock.convert(from: duration)! + let swiftDuration = clock._convert(from: duration)! let (seconds, attoseconds) = clamp(swiftDuration.components) let nanoseconds = attoseconds / 1_000_000_000 return (seconds: seconds, nanoseconds: nanoseconds) @@ -202,11 +202,11 @@ extension DispatchExecutorProtocol { } @available(SwiftStdlib 6.2, *) -extension DispatchGlobalTaskExecutor: DispatchExecutorProtocol { +extension _DispatchGlobalTaskExecutor: DispatchExecutorProtocol { } @available(SwiftStdlib 6.2, *) -extension DispatchMainExecutor: DispatchExecutorProtocol { +extension _DispatchMainExecutor: DispatchExecutorProtocol { } #endif // !$Embedded && !os(WASI) diff --git a/stdlib/public/Concurrency/DummyExecutor.swift b/stdlib/public/Concurrency/DummyExecutor.swift index ec7bc7897198a..cae02bc60c23d 100644 --- a/stdlib/public/Concurrency/DummyExecutor.swift +++ b/stdlib/public/Concurrency/DummyExecutor.swift @@ -15,14 +15,14 @@ import Swift // .. Main Executor ............................................................ @available(SwiftStdlib 6.2, *) -public final class DummyMainExecutor: MainExecutor, @unchecked Sendable { +public final class _DummyMainExecutor: _MainExecutor, @unchecked Sendable { public init() {} - public func run() throws { + public func _run() throws { fatalError("There is no executor implementation active") } - public func stop() { + public func _stop() { fatalError("There is no executor implementation active") } @@ -36,7 +36,7 @@ public final class DummyMainExecutor: MainExecutor, @unchecked Sendable { } #endif - public var isMainExecutor: Bool { true } + public var _isMainExecutor: Bool { true } public func checkIsolated() { // Do nothing @@ -46,7 +46,7 @@ public final class DummyMainExecutor: MainExecutor, @unchecked Sendable { // .. Task Executor ............................................................ @available(SwiftStdlib 6.2, *) -public final class DummyTaskExecutor: TaskExecutor, @unchecked Sendable { +public final class _DummyTaskExecutor: TaskExecutor, @unchecked Sendable { public init() {} #if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY @@ -59,5 +59,5 @@ public final class DummyTaskExecutor: TaskExecutor, @unchecked Sendable { } #endif - public var isMainExecutor: Bool { false } + public var _isMainExecutor: Bool { false } } diff --git a/stdlib/public/Concurrency/Executor.swift b/stdlib/public/Concurrency/Executor.swift index ff642319e29a6..47205c71d6af3 100644 --- a/stdlib/public/Concurrency/Executor.swift +++ b/stdlib/public/Concurrency/Executor.swift @@ -39,12 +39,12 @@ public protocol Executor: AnyObject, Sendable { #if !$Embedded /// `true` if this is the main executor. @available(SwiftStdlib 6.2, *) - var isMainExecutor: Bool { get } + var _isMainExecutor: Bool { get } #endif } @available(SwiftStdlib 6.2, *) -public protocol SchedulableExecutor: Executor { +public protocol _SchedulableExecutor: Executor { #if !$Embedded && !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY @@ -64,10 +64,10 @@ public protocol SchedulableExecutor: Executor { /// job is executed. `nil` means no limit. /// - clock: The clock used for the delay. @available(SwiftStdlib 6.2, *) - func enqueue(_ job: consuming ExecutorJob, - after delay: C.Duration, - tolerance: C.Duration?, - clock: C) + func _enqueue(_ job: consuming ExecutorJob, + after delay: C.Duration, + tolerance: C.Duration?, + clock: C) /// Enqueue a job to run at a specified time. /// @@ -84,10 +84,10 @@ public protocol SchedulableExecutor: Executor { /// job is executed. `nil` means no limit. /// - clock: The clock used for the delay.. @available(SwiftStdlib 6.2, *) - func enqueue(_ job: consuming ExecutorJob, - at instant: C.Instant, - tolerance: C.Duration?, - clock: C) + func _enqueue(_ job: consuming ExecutorJob, + at instant: C.Instant, + tolerance: C.Duration?, + clock: C) #endif // !$Embedded && !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY @@ -126,8 +126,8 @@ extension Executor { /// own copy of this method, which will allow the compiler to avoid a /// potentially expensive runtime cast. @available(SwiftStdlib 6.2, *) - var asSchedulable: SchedulableExecutor? { - return self as? SchedulableExecutor + var _asSchedulable: _SchedulableExecutor? { + return self as? _SchedulableExecutor } } @@ -149,37 +149,37 @@ extension Executor { // This defaults to `false` so that existing third-party Executor // implementations will work as expected. @available(SwiftStdlib 6.2, *) - public var isMainExecutor: Bool { false } + public var _isMainExecutor: Bool { false } #endif } // Delay support @available(SwiftStdlib 6.2, *) -extension SchedulableExecutor { +extension _SchedulableExecutor { #if !$Embedded && !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY @available(SwiftStdlib 6.2, *) - public func enqueue(_ job: consuming ExecutorJob, - after delay: C.Duration, - tolerance: C.Duration? = nil, - clock: C) { + public func _enqueue(_ job: consuming ExecutorJob, + after delay: C.Duration, + tolerance: C.Duration? = nil, + clock: C) { // If you crash here with a mutual recursion, it's because you didn't // implement one of these two functions - enqueue(job, at: clock.now.advanced(by: delay), - tolerance: tolerance, clock: clock) + _enqueue(job, at: clock.now.advanced(by: delay), + tolerance: tolerance, clock: clock) } @available(SwiftStdlib 6.2, *) - public func enqueue(_ job: consuming ExecutorJob, - at instant: C.Instant, - tolerance: C.Duration? = nil, - clock: C) { + public func _enqueue(_ job: consuming ExecutorJob, + at instant: C.Instant, + tolerance: C.Duration? = nil, + clock: C) { // If you crash here with a mutual recursion, it's because you didn't // implement one of these two functions - enqueue(job, after: clock.now.duration(to: instant), - tolerance: tolerance, clock: clock) + _enqueue(job, after: clock.now.duration(to: instant), + tolerance: tolerance, clock: clock) } #endif // !$Embedded && !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY @@ -370,7 +370,7 @@ extension SerialExecutor { #if !$Embedded && !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY @available(SwiftStdlib 6.2, *) - public var isMainExecutor: Bool { return MainActor.executor._isSameExecutor(self) } + public var _isMainExecutor: Bool { return MainActor._executor._isSameExecutor(self) } #endif @available(SwiftStdlib 6.0, *) @@ -528,13 +528,13 @@ extension SerialExecutor where Self: Equatable { /// that processes events of some sort; we want a way to enter that loop, /// and we would also like a way to trigger the loop to exit. @available(SwiftStdlib 6.2, *) -public protocol RunLoopExecutor: Executor { +public protocol _RunLoopExecutor: Executor { /// Run the executor's run loop. /// /// This method will synchronously block the calling thread. Nested calls to /// `run()` may be permitted, however it is not permitted to call `run()` on a /// single executor instance from more than one thread. - func run() throws + func _run() throws /// Run the executor's run loop until a condition is satisfied. /// @@ -546,7 +546,7 @@ public protocol RunLoopExecutor: Executor { /// /// - condition: A closure that returns `true` if the run loop should /// stop. - func runUntil(_ condition: () -> Bool) throws + func _runUntil(_ condition: () -> Bool) throws /// Signal to the run loop to stop running and return. /// @@ -555,13 +555,13 @@ public protocol RunLoopExecutor: Executor { /// stop; calling this method simply signals that the run loop *should*, as /// soon as is practicable, stop the innermost `run()` invocation and make /// that `run()` invocation return. - func stop() + func _stop() } @available(SwiftStdlib 6.2, *) -extension RunLoopExecutor { +extension _RunLoopExecutor { - public func runUntil(_ condition: () -> Bool) throws { + public func _runUntil(_ condition: () -> Bool) throws { fatalError("run(until condition:) not supported on this executor") } @@ -571,18 +571,18 @@ extension RunLoopExecutor { /// The main executor must conform to these three protocols; we have to /// make this a protocol for compatibility with Embedded Swift. @available(SwiftStdlib 6.2, *) -public protocol MainExecutor: RunLoopExecutor, SerialExecutor { +public protocol _MainExecutor: _RunLoopExecutor, SerialExecutor { } /// An ExecutorFactory is used to create the default main and task /// executors. @available(SwiftStdlib 6.2, *) -public protocol ExecutorFactory { +public protocol _ExecutorFactory { #if !$Embedded /// Constructs and returns the main executor, which is started implicitly /// by the `async main` entry point and owns the "main" thread. - static var mainExecutor: any MainExecutor { get } + static var mainExecutor: any _MainExecutor { get } #endif /// Constructs and returns the default or global executor, which is the @@ -591,29 +591,29 @@ public protocol ExecutorFactory { } @available(SwiftStdlib 6.2, *) -typealias DefaultExecutorFactory = PlatformExecutorFactory +typealias _DefaultExecutorFactory = _PlatformExecutorFactory @available(SwiftStdlib 6.2, *) @_silgen_name("swift_createExecutors") -public func _createExecutors(factory: F.Type) { +public func _createExecutors(factory: F.Type) { #if !$Embedded && !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY - MainActor._executor = factory.mainExecutor + MainActor.__executor = factory.mainExecutor #endif - Task._defaultExecutor = factory.defaultExecutor + Task.__defaultExecutor = factory.defaultExecutor } @available(SwiftStdlib 6.2, *) @_silgen_name("swift_createDefaultExecutors") func _createDefaultExecutors() { - if Task._defaultExecutor == nil { - _createExecutors(factory: DefaultExecutorFactory.self) + if Task.__defaultExecutor == nil { + _createExecutors(factory: _DefaultExecutorFactory.self) } } #if !$Embedded && !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY extension MainActor { @available(SwiftStdlib 6.2, *) - static var _executor: (any MainExecutor)? = nil + static var __executor: (any _MainExecutor)? = nil /// The main executor, which is started implicitly by the `async main` /// entry point and owns the "main" thread. @@ -621,17 +621,17 @@ extension MainActor { /// Attempting to set this after the first `enqueue` on the main /// executor is a fatal error. @available(SwiftStdlib 6.2, *) - public static var executor: any MainExecutor { + public static var _executor: any _MainExecutor { // It would be good if there was a Swift way to do this _createDefaultExecutorsOnce() - return _executor! + return __executor! } } #endif // !$Embedded && !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY extension Task where Success == Never, Failure == Never { @available(SwiftStdlib 6.2, *) - static var _defaultExecutor: (any TaskExecutor)? = nil + static var __defaultExecutor: (any TaskExecutor)? = nil /// The default or global executor, which is the default place in which /// we run tasks. @@ -639,10 +639,10 @@ extension Task where Success == Never, Failure == Never { /// Attempting to set this after the first `enqueue` on the global /// executor is a fatal error. @available(SwiftStdlib 6.2, *) - public static var defaultExecutor: any TaskExecutor { + public static var _defaultExecutor: any TaskExecutor { // It would be good if there was a Swift way to do this _createDefaultExecutorsOnce() - return _defaultExecutor! + return __defaultExecutor! } } @@ -660,21 +660,21 @@ extension Task where Success == Never, Failure == Never { /// If none of these exist, returns the default executor. @available(SwiftStdlib 6.2, *) @_unavailableInEmbedded - public static var currentExecutor: any Executor { - if let activeExecutor = unsafe _getActiveExecutor().asSerialExecutor() { + public static var _currentExecutor: any Executor { + if let activeExecutor = unsafe _getActiveExecutor()._asSerialExecutor() { return activeExecutor - } else if let taskExecutor = unsafe _getPreferredTaskExecutor().asTaskExecutor() { + } else if let taskExecutor = unsafe _getPreferredTaskExecutor()._asTaskExecutor() { return taskExecutor - } else if let taskExecutor = unsafe _getCurrentTaskExecutor().asTaskExecutor() { + } else if let taskExecutor = unsafe _getCurrentTaskExecutor()._asTaskExecutor() { return taskExecutor } - return defaultExecutor + return _defaultExecutor } /// Get the preferred executor for the current `Task`, if any. @available(SwiftStdlib 6.2, *) - public static var preferredExecutor: (any TaskExecutor)? { - if let taskExecutor = unsafe _getPreferredTaskExecutor().asTaskExecutor() { + public static var _preferredExecutor: (any TaskExecutor)? { + if let taskExecutor = unsafe _getPreferredTaskExecutor()._asTaskExecutor() { return taskExecutor } return nil @@ -686,20 +686,20 @@ extension Task where Success == Never, Failure == Never { /// any executor that isn't a `SchedulableExecutor`. @available(SwiftStdlib 6.2, *) @_unavailableInEmbedded - public static var currentSchedulableExecutor: (any SchedulableExecutor)? { - if let activeExecutor = unsafe _getActiveExecutor().asSerialExecutor(), - let schedulable = activeExecutor.asSchedulable { + public static var _currentSchedulableExecutor: (any _SchedulableExecutor)? { + if let activeExecutor = unsafe _getActiveExecutor()._asSerialExecutor(), + let schedulable = activeExecutor._asSchedulable { return schedulable } - if let taskExecutor = unsafe _getPreferredTaskExecutor().asTaskExecutor(), - let schedulable = taskExecutor.asSchedulable { + if let taskExecutor = unsafe _getPreferredTaskExecutor()._asTaskExecutor(), + let schedulable = taskExecutor._asSchedulable { return schedulable } - if let taskExecutor = unsafe _getCurrentTaskExecutor().asTaskExecutor(), - let schedulable = taskExecutor.asSchedulable { + if let taskExecutor = unsafe _getCurrentTaskExecutor()._asTaskExecutor(), + let schedulable = taskExecutor._asSchedulable { return schedulable } - if let schedulable = defaultExecutor.asSchedulable { + if let schedulable = _defaultExecutor._asSchedulable { return schedulable } return nil @@ -777,7 +777,7 @@ public struct UnownedSerialExecutor: Sendable { } @available(SwiftStdlib 6.2, *) - public func asSerialExecutor() -> (any SerialExecutor)? { + public func _asSerialExecutor() -> (any SerialExecutor)? { return unsafe unsafeBitCast(executor, to: (any SerialExecutor)?.self) } } @@ -814,7 +814,7 @@ public struct UnownedTaskExecutor: Sendable { } @available(SwiftStdlib 6.2, *) - public func asTaskExecutor() -> (any TaskExecutor)? { + public func _asTaskExecutor() -> (any TaskExecutor)? { return unsafe unsafeBitCast(executor, to: (any TaskExecutor)?.self) } } diff --git a/stdlib/public/Concurrency/ExecutorBridge.swift b/stdlib/public/Concurrency/ExecutorBridge.swift index 7eb570c73ef74..f91d6203c0542 100644 --- a/stdlib/public/Concurrency/ExecutorBridge.swift +++ b/stdlib/public/Concurrency/ExecutorBridge.swift @@ -25,7 +25,7 @@ internal func _exit(result: CInt) @available(SwiftStdlib 6.2, *) @_silgen_name("_swift_task_isMainExecutorSwift") internal func _isMainExecutor(_ executor: E) -> Bool where E: SerialExecutor { - return executor.isMainExecutor + return executor._isMainExecutor } #endif @@ -92,7 +92,7 @@ internal func _jobGetExecutorPrivateData( @available(SwiftStdlib 6.2, *) @_silgen_name("swift_getMainExecutor") internal func _getMainExecutor() -> any SerialExecutor { - return MainActor.executor + return MainActor._executor } #else // For task-to-thread model, this is implemented in C++ diff --git a/stdlib/public/Concurrency/ExecutorImpl.swift b/stdlib/public/Concurrency/ExecutorImpl.swift index 29a2438aa3ec0..a8bc48da57085 100644 --- a/stdlib/public/Concurrency/ExecutorImpl.swift +++ b/stdlib/public/Concurrency/ExecutorImpl.swift @@ -24,7 +24,7 @@ import Swift @_silgen_name("swift_task_asyncMainDrainQueueImpl") internal func drainMainQueue() { #if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY - try! MainActor.executor.run() + try! MainActor._executor._run() _exit(result: 0) #else fatalError("swift_task_asyncMainDrainQueue() not supported with task-to-thread") @@ -37,8 +37,8 @@ internal func donateToGlobalExecutor( condition: @convention(c) (_ ctx: UnsafeMutableRawPointer) -> CBool, context: UnsafeMutableRawPointer ) { - if let runnableExecutor = Task.defaultExecutor as? RunLoopExecutor { - try! runnableExecutor.runUntil { unsafe Bool(condition(context)) } + if let runnableExecutor = Task._defaultExecutor as? _RunLoopExecutor { + try! runnableExecutor._runUntil { unsafe Bool(condition(context)) } } else { fatalError("Global executor does not support thread donation") } @@ -54,7 +54,7 @@ internal func getMainExecutor() -> UnownedSerialExecutor { @_silgen_name("swift_task_enqueueMainExecutorImpl") internal func enqueueOnMainExecutor(job unownedJob: UnownedJob) { #if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY - MainActor.executor.enqueue(unownedJob) + MainActor._executor.enqueue(unownedJob) #else fatalError("swift_task_enqueueMainExecutor() not supported for task-to-thread") #endif @@ -63,7 +63,7 @@ internal func enqueueOnMainExecutor(job unownedJob: UnownedJob) { @available(SwiftStdlib 6.2, *) @_silgen_name("swift_task_enqueueGlobalImpl") internal func enqueueOnGlobalExecutor(job unownedJob: UnownedJob) { - Task.defaultExecutor.enqueue(unownedJob) + Task._defaultExecutor.enqueue(unownedJob) } #if !$Embedded @@ -72,9 +72,9 @@ internal func enqueueOnGlobalExecutor(job unownedJob: UnownedJob) { internal func enqueueOnGlobalExecutor(delay: CUnsignedLongLong, job unownedJob: UnownedJob) { #if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY - Task.defaultExecutor.asSchedulable!.enqueue(ExecutorJob(unownedJob), - after: .nanoseconds(delay), - clock: .continuous) + Task._defaultExecutor._asSchedulable!._enqueue(ExecutorJob(unownedJob), + after: .nanoseconds(delay), + clock: .continuous) #else fatalError("swift_task_enqueueGlobalWithDelay() not supported for task-to-thread") #endif @@ -93,15 +93,15 @@ internal func enqueueOnGlobalExecutor(seconds: CLongLong, let leeway = Duration.seconds(leewaySeconds) + Duration.nanoseconds(leewayNanoseconds) switch clock { case _ClockID.suspending.rawValue: - Task.defaultExecutor.asSchedulable!.enqueue(ExecutorJob(unownedJob), - after: delay, - tolerance: leeway, - clock: .suspending) + Task._defaultExecutor._asSchedulable!._enqueue(ExecutorJob(unownedJob), + after: delay, + tolerance: leeway, + clock: .suspending) case _ClockID.continuous.rawValue: - Task.defaultExecutor.asSchedulable!.enqueue(ExecutorJob(unownedJob), - after: delay, - tolerance: leeway, - clock: .continuous) + Task._defaultExecutor._asSchedulable!._enqueue(ExecutorJob(unownedJob), + after: delay, + tolerance: leeway, + clock: .continuous) default: fatalError("Unknown clock ID \(clock)") } diff --git a/stdlib/public/Concurrency/GlobalConcurrentExecutor.swift b/stdlib/public/Concurrency/GlobalConcurrentExecutor.swift index 7c876a99472d1..4366615f058a9 100644 --- a/stdlib/public/Concurrency/GlobalConcurrentExecutor.swift +++ b/stdlib/public/Concurrency/GlobalConcurrentExecutor.swift @@ -31,12 +31,11 @@ import Swift /// /// Customizing the global concurrent executor is currently not supported. @available(SwiftStdlib 6.0, *) -@available(*, deprecated, renamed: "Task.defaultExecutor") @_unavailableInEmbedded public var globalConcurrentExecutor: any TaskExecutor { get { if #available(SwiftStdlib 6.2, *) { - return Task.defaultExecutor + return Task._defaultExecutor } else { return _DefaultGlobalConcurrentExecutor.shared } diff --git a/stdlib/public/Concurrency/PartialAsyncTask.swift b/stdlib/public/Concurrency/PartialAsyncTask.swift index 952c601ec1935..11fc21e0539af 100644 --- a/stdlib/public/Concurrency/PartialAsyncTask.swift +++ b/stdlib/public/Concurrency/PartialAsyncTask.swift @@ -323,7 +323,7 @@ public struct ExecutorJob: Sendable, ~Copyable { /// /// Returns the result of executing the closure. @available(SwiftStdlib 6.2, *) - public func withUnsafeExecutorPrivateData(body: (UnsafeMutableRawBufferPointer) throws(E) -> R) throws(E) -> R { + public func _withUnsafeExecutorPrivateData(body: (UnsafeMutableRawBufferPointer) throws(E) -> R) throws(E) -> R { let base = _jobGetExecutorPrivateData(self.context) let size = unsafe 2 * MemoryLayout.stride return unsafe try body(UnsafeMutableRawBufferPointer(start: base, @@ -333,7 +333,7 @@ public struct ExecutorJob: Sendable, ~Copyable { /// Kinds of schedulable jobs @available(SwiftStdlib 6.2, *) @frozen - public struct Kind: Sendable, RawRepresentable { + public struct _Kind: Sendable, RawRepresentable { public typealias RawValue = UInt8 /// The raw job kind value. @@ -345,16 +345,16 @@ public struct ExecutorJob: Sendable, ~Copyable { } /// A task. - public static let task = Kind(rawValue: RawValue(0))! + public static let task = _Kind(rawValue: RawValue(0))! // Job kinds >= 192 are private to the implementation. - public static let firstReserved = Kind(rawValue: RawValue(192))! + public static let firstReserved = _Kind(rawValue: RawValue(192))! } /// What kind of job this is. @available(SwiftStdlib 6.2, *) - public var kind: Kind { - return Kind(rawValue: _jobGetKind(self.context))! + public var _kind: _Kind { + return _Kind(rawValue: _jobGetKind(self.context))! } // TODO: move only types cannot conform to protocols, so we can't conform to CustomStringConvertible; @@ -455,7 +455,7 @@ extension ExecutorJob { /// /// If the job does not support allocation, this property will be `nil`. public var allocator: LocalAllocator? { - guard self.kind == .task else { + guard self._kind == .task else { return nil } diff --git a/stdlib/public/Concurrency/PlatformExecutorCooperative.swift b/stdlib/public/Concurrency/PlatformExecutorCooperative.swift index 5c17e1d2ba084..ba45e97be3656 100644 --- a/stdlib/public/Concurrency/PlatformExecutorCooperative.swift +++ b/stdlib/public/Concurrency/PlatformExecutorCooperative.swift @@ -14,8 +14,8 @@ import Swift // This platform uses a single, global, CooperativeExecutor @available(SwiftStdlib 6.2, *) -public struct PlatformExecutorFactory: ExecutorFactory { - static let executor = CooperativeExecutor() - public static var mainExecutor: any MainExecutor { executor } +public struct _PlatformExecutorFactory: _ExecutorFactory { + static let executor = _CooperativeExecutor() + public static var mainExecutor: any _MainExecutor { executor } public static var defaultExecutor: any TaskExecutor { executor } } diff --git a/stdlib/public/Concurrency/PlatformExecutorDarwin.swift b/stdlib/public/Concurrency/PlatformExecutorDarwin.swift index 90017beb45106..edd63376ca579 100644 --- a/stdlib/public/Concurrency/PlatformExecutorDarwin.swift +++ b/stdlib/public/Concurrency/PlatformExecutorDarwin.swift @@ -15,20 +15,20 @@ import Swift @available(SwiftStdlib 6.2, *) -public struct PlatformExecutorFactory: ExecutorFactory { - public static var mainExecutor: any MainExecutor { +public struct _PlatformExecutorFactory: _ExecutorFactory { + public static var mainExecutor: any _MainExecutor { if CoreFoundation.isPresent { - return CFMainExecutor() + return _CFMainExecutor() } else { - return DispatchMainExecutor() + return _DispatchMainExecutor() } } public static var defaultExecutor: any TaskExecutor { if CoreFoundation.isPresent { - return CFTaskExecutor() + return _CFTaskExecutor() } else { - return DispatchGlobalTaskExecutor() + return _DispatchGlobalTaskExecutor() } } } diff --git a/stdlib/public/Concurrency/PlatformExecutorFreeBSD.swift b/stdlib/public/Concurrency/PlatformExecutorFreeBSD.swift index b7a4deb25356c..e7c8fad63d327 100644 --- a/stdlib/public/Concurrency/PlatformExecutorFreeBSD.swift +++ b/stdlib/public/Concurrency/PlatformExecutorFreeBSD.swift @@ -16,10 +16,10 @@ import Swift // The default executors for now are Dispatch-based @available(SwiftStdlib 6.2, *) -public struct PlatformExecutorFactory: ExecutorFactory { - public static let mainExecutor: any MainExecutor = DispatchMainExecutor() +public struct _PlatformExecutorFactory: _ExecutorFactory { + public static let mainExecutor: any _MainExecutor = _DispatchMainExecutor() public static let defaultExecutor: any TaskExecutor - = DispatchGlobalTaskExecutor() + = _DispatchGlobalTaskExecutor() } #endif // os(FreeBSD) diff --git a/stdlib/public/Concurrency/PlatformExecutorLinux.swift b/stdlib/public/Concurrency/PlatformExecutorLinux.swift index a14c492c8ab59..6531d4be50803 100644 --- a/stdlib/public/Concurrency/PlatformExecutorLinux.swift +++ b/stdlib/public/Concurrency/PlatformExecutorLinux.swift @@ -16,10 +16,10 @@ import Swift // The default executors for now are Dispatch-based @available(SwiftStdlib 6.2, *) -public struct PlatformExecutorFactory: ExecutorFactory { - public static let mainExecutor: any MainExecutor = DispatchMainExecutor() +public struct _PlatformExecutorFactory: _ExecutorFactory { + public static let mainExecutor: any _MainExecutor = _DispatchMainExecutor() public static let defaultExecutor: any TaskExecutor - = DispatchGlobalTaskExecutor() + = _DispatchGlobalTaskExecutor() } #endif // os(Linux) diff --git a/stdlib/public/Concurrency/PlatformExecutorNone.swift b/stdlib/public/Concurrency/PlatformExecutorNone.swift index a524f07005d85..f6c8fc7e46812 100644 --- a/stdlib/public/Concurrency/PlatformExecutorNone.swift +++ b/stdlib/public/Concurrency/PlatformExecutorNone.swift @@ -13,7 +13,7 @@ import Swift @available(SwiftStdlib 6.2, *) -public struct PlatformExecutorFactory: ExecutorFactory { - public static let mainExecutor: any MainExecutor = DummyMainExecutor() - public static let defaultExecutor: any TaskExecutor = DummyTaskExecutor() +public struct _PlatformExecutorFactory: _ExecutorFactory { + public static let mainExecutor: any _MainExecutor = _DummyMainExecutor() + public static let defaultExecutor: any TaskExecutor = _DummyTaskExecutor() } diff --git a/stdlib/public/Concurrency/PlatformExecutorOpenBSD.swift b/stdlib/public/Concurrency/PlatformExecutorOpenBSD.swift index 4bd2db9d5ebdc..67e12cf748f1d 100644 --- a/stdlib/public/Concurrency/PlatformExecutorOpenBSD.swift +++ b/stdlib/public/Concurrency/PlatformExecutorOpenBSD.swift @@ -16,10 +16,10 @@ import Swift // The default executors for now are Dispatch-based @available(SwiftStdlib 6.2, *) -public struct PlatformExecutorFactory: ExecutorFactory { - public static let mainExecutor: any MainExecutor = DispatchMainExecutor() +public struct _PlatformExecutorFactory: _ExecutorFactory { + public static let mainExecutor: any _MainExecutor = _DispatchMainExecutor() public static let defaultExecutor: any TaskExecutor - = DispatchGlobalTaskExecutor() + = _DispatchGlobalTaskExecutor() } #endif diff --git a/stdlib/public/Concurrency/PlatformExecutorWindows.swift b/stdlib/public/Concurrency/PlatformExecutorWindows.swift index e64665a94da37..7d812348a6910 100644 --- a/stdlib/public/Concurrency/PlatformExecutorWindows.swift +++ b/stdlib/public/Concurrency/PlatformExecutorWindows.swift @@ -16,10 +16,10 @@ import Swift // The default executors for now are Dispatch-based @available(SwiftStdlib 6.2, *) -public struct PlatformExecutorFactory: ExecutorFactory { - public static let mainExecutor: any MainExecutor = DispatchMainExecutor() +public struct _PlatformExecutorFactory: _ExecutorFactory { + public static let mainExecutor: any _MainExecutor = _DispatchMainExecutor() public static let defaultExecutor: any TaskExecutor = - DispatchGlobalTaskExecutor() + _DispatchGlobalTaskExecutor() } #endif // os(Windows) diff --git a/stdlib/public/Concurrency/SuspendingClock.swift b/stdlib/public/Concurrency/SuspendingClock.swift index a58d62918e035..0bc1bf7d02736 100644 --- a/stdlib/public/Concurrency/SuspendingClock.swift +++ b/stdlib/public/Concurrency/SuspendingClock.swift @@ -89,7 +89,7 @@ extension SuspendingClock: Clock { /// The suspending clock is monotonic @available(SwiftStdlib 6.2, *) - public var traits: ClockTraits { + public var _traits: _ClockTraits { return [.monotonic] } diff --git a/stdlib/public/Concurrency/Task.swift b/stdlib/public/Concurrency/Task.swift index 8db587e5863f8..cc1c0bd6cb602 100644 --- a/stdlib/public/Concurrency/Task.swift +++ b/stdlib/public/Concurrency/Task.swift @@ -1255,7 +1255,7 @@ extension Task where Success == Never, Failure == Never { #if !$Embedded && !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY if #available(SwiftStdlib 6.2, *) { - let executor = Task.currentExecutor + let executor = Task._currentExecutor executor.enqueue(ExecutorJob(context: job)) } else { @@ -1516,7 +1516,7 @@ internal func _runAsyncMain(_ asyncFun: @Sendable @escaping () async throws -> ( let job = Builtin.convertTaskToJob(theTask) if #available(SwiftStdlib 6.2, *) { - MainActor.executor.enqueue(ExecutorJob(context: job)) + MainActor._executor.enqueue(ExecutorJob(context: job)) } else { Builtin.unreachable() } diff --git a/stdlib/public/Concurrency/TaskSleep.swift b/stdlib/public/Concurrency/TaskSleep.swift index 653a343c546d8..083264b5b02f6 100644 --- a/stdlib/public/Concurrency/TaskSleep.swift +++ b/stdlib/public/Concurrency/TaskSleep.swift @@ -30,10 +30,10 @@ extension Task where Success == Never, Failure == Never { if #available(SwiftStdlib 6.2, *) { #if !$Embedded - if let executor = Task.currentSchedulableExecutor { - executor.enqueue(ExecutorJob(context: job), - after: .nanoseconds(duration), - clock: .continuous) + if let executor = Task._currentSchedulableExecutor { + executor._enqueue(ExecutorJob(context: job), + after: .nanoseconds(duration), + clock: .continuous) return } #endif @@ -274,10 +274,10 @@ extension Task where Success == Never, Failure == Never { if #available(SwiftStdlib 6.2, *) { #if !$Embedded - if let executor = Task.currentSchedulableExecutor { - executor.enqueue(ExecutorJob(context: job), - after: .nanoseconds(duration), - clock: .continuous) + if let executor = Task._currentSchedulableExecutor { + executor._enqueue(ExecutorJob(context: job), + after: .nanoseconds(duration), + clock: .continuous) return } #endif diff --git a/stdlib/public/Concurrency/TaskSleepDuration.swift b/stdlib/public/Concurrency/TaskSleepDuration.swift index d9e3876c69534..fc7b1292f9724 100644 --- a/stdlib/public/Concurrency/TaskSleepDuration.swift +++ b/stdlib/public/Concurrency/TaskSleepDuration.swift @@ -18,7 +18,7 @@ fileprivate func timestamp(for instant: C.Instant, clock: C) -> (clockID: _ClockID, seconds: Int64, nanoseconds: Int64) { var clockID: _ClockID if #available(SwiftStdlib 6.2, *) { - if clock.traits.contains(.continuous) { + if clock._traits.contains(.continuous) { clockID = .continuous } else { clockID = .suspending @@ -35,7 +35,7 @@ fileprivate func timestamp(for instant: C.Instant, clock: C) let delta: Swift.Duration if #available(SwiftStdlib 6.2, *) { - delta = clock.convert(from: clock.now.duration(to: instant))! + delta = clock._convert(from: clock.now.duration(to: instant))! } else { Builtin.unreachable() } @@ -99,11 +99,11 @@ extension Task where Success == Never, Failure == Never { if #available(SwiftStdlib 6.2, *) { #if !$Embedded - if let executor = Task.currentSchedulableExecutor { - executor.enqueue(ExecutorJob(context: job), - at: instant, - tolerance: tolerance, - clock: clock) + if let executor = Task._currentSchedulableExecutor { + executor._enqueue(ExecutorJob(context: job), + at: instant, + tolerance: tolerance, + clock: clock) return } #endif @@ -119,7 +119,7 @@ extension Task where Success == Never, Failure == Never { let toleranceNanoseconds: Int64 if #available(SwiftStdlib 6.2, *) { if let tolerance = tolerance, - let components = clock.convert(from: tolerance)?.components { + let components = clock._convert(from: tolerance)?.components { toleranceSeconds = components.seconds toleranceNanoseconds = components.attoseconds / 1_000_000_000 } else { diff --git a/stdlib/public/Concurrency/TaskStatus.cpp b/stdlib/public/Concurrency/TaskStatus.cpp index 81c0fd44cc139..d236615eb09b8 100644 --- a/stdlib/public/Concurrency/TaskStatus.cpp +++ b/stdlib/public/Concurrency/TaskStatus.cpp @@ -654,8 +654,13 @@ void AsyncTask::pushInitialTaskName(const char* _taskName) { auto taskNameLen = strlen(_taskName); char* taskNameCopy = reinterpret_cast( _swift_task_alloc_specific(this, taskNameLen + 1/*null terminator*/)); +#if defined(_WIN32) + static_cast(strncpy_s(taskNameCopy, taskNameLen + 1, + _taskName, _TRUNCATE)); +#else (void) strncpy(/*dst=*/taskNameCopy, /*src=*/_taskName, taskNameLen); taskNameCopy[taskNameLen] = '\0'; // make sure we null-terminate +#endif auto record = ::new (allocation) TaskNameStatusRecord(taskNameCopy); diff --git a/stdlib/public/core/InlineArray.swift b/stdlib/public/core/InlineArray.swift index 1edc026eab9e8..2bf9c6339e2cf 100644 --- a/stdlib/public/core/InlineArray.swift +++ b/stdlib/public/core/InlineArray.swift @@ -46,7 +46,7 @@ @_addressableForDependencies public struct InlineArray: ~Copyable { @usableFromInline - internal let _storage: Builtin.FixedArray + internal var _storage: Builtin.FixedArray } @available(SwiftStdlib 6.2, *) @@ -69,7 +69,7 @@ extension InlineArray where Element: ~Copyable { @_alwaysEmitIntoClient @_transparent internal var _address: UnsafePointer { - unsafe UnsafePointer(Builtin.unprotectedAddressOfBorrow(self)) + unsafe UnsafePointer(Builtin.unprotectedAddressOfBorrow(_storage)) } /// Returns a buffer pointer over the entire array. @@ -86,7 +86,7 @@ extension InlineArray where Element: ~Copyable { @_transparent internal var _mutableAddress: UnsafeMutablePointer { mutating get { - unsafe UnsafeMutablePointer(Builtin.unprotectedAddressOf(&self)) + unsafe UnsafeMutablePointer(Builtin.unprotectedAddressOf(&_storage)) } } @@ -147,7 +147,7 @@ extension InlineArray where Element: ~Copyable { @_alwaysEmitIntoClient public init(_ body: (Index) throws(E) -> Element) throws(E) { #if $BuiltinEmplaceTypedThrows - self = try Builtin.emplace { (rawPtr) throws(E) -> () in + _storage = try Builtin.emplace { (rawPtr) throws(E) -> () in let buffer = unsafe Self._initializationBuffer(start: rawPtr) for i in 0 ..< count { @@ -204,7 +204,7 @@ extension InlineArray where Element: ~Copyable { // and take the underlying value within the closure. var o: Element? = first - self = try Builtin.emplace { (rawPtr) throws(E) -> () in + _storage = try Builtin.emplace { (rawPtr) throws(E) -> () in let buffer = unsafe Self._initializationBuffer(start: rawPtr) guard Self.count > 0 else { @@ -248,7 +248,7 @@ extension InlineArray where Element: Copyable { @_alwaysEmitIntoClient public init(repeating value: Element) { #if $ValueGenericsNameLookup - self = Builtin.emplace { + _storage = Builtin.emplace { let buffer = unsafe Self._initializationBuffer(start: $0) unsafe buffer.initialize(repeating: value) diff --git a/stdlib/public/runtime/Casting.cpp b/stdlib/public/runtime/Casting.cpp index f495c03d0c0e5..254fdcc10669e 100644 --- a/stdlib/public/runtime/Casting.cpp +++ b/stdlib/public/runtime/Casting.cpp @@ -1436,10 +1436,31 @@ extern "C" const _ObjectiveCBridgeableWitnessTable BRIDGING_CONFORMANCE_SYM; /// Nominal type descriptor for Swift.String. extern "C" const StructDescriptor NOMINAL_TYPE_DESCR_SYM(SS); +struct ObjCBridgeWitnessCacheEntry { + const Metadata *metadata; + const _ObjectiveCBridgeableWitnessTable *witness; +}; + +// String is so important that we cache it permanently, so we don't want to +// pollute this temporary cache with the String entry +static const _ObjectiveCBridgeableWitnessTable * +swift_conformsToObjectiveCBridgeableNoCache(const Metadata *T) { + auto w = swift_conformsToProtocolCommon( + T, &PROTOCOL_DESCR_SYM(s21_ObjectiveCBridgeable)); + return reinterpret_cast(w); +} + static const _ObjectiveCBridgeableWitnessTable * swift_conformsToObjectiveCBridgeable(const Metadata *T) { - return reinterpret_cast - (swift_conformsToProtocolCommon(T, &PROTOCOL_DESCR_SYM(s21_ObjectiveCBridgeable))); + static std::atomic _objcBridgeWitnessCache = {}; + auto cached = _objcBridgeWitnessCache.load(SWIFT_MEMORY_ORDER_CONSUME); + if (cached.metadata == T) { + return cached.witness; + } + cached.witness = swift_conformsToObjectiveCBridgeableNoCache(T); + cached.metadata = T; + _objcBridgeWitnessCache.store(cached, std::memory_order_release); + return cached.witness; } static const _ObjectiveCBridgeableWitnessTable * @@ -1451,7 +1472,7 @@ findBridgeWitness(const Metadata *T) { if (T->getKind() == MetadataKind::Struct) { auto structDescription = cast(T)->Description; if (structDescription == &NOMINAL_TYPE_DESCR_SYM(SS)) { - static auto *Swift_String_ObjectiveCBridgeable = swift_conformsToObjectiveCBridgeable(T); + static auto *Swift_String_ObjectiveCBridgeable = swift_conformsToObjectiveCBridgeableNoCache(T); return Swift_String_ObjectiveCBridgeable; } } diff --git a/stdlib/public/runtime/Demangle.cpp b/stdlib/public/runtime/Demangle.cpp index 0befba2969756..9fd0edd57977b 100644 --- a/stdlib/public/runtime/Demangle.cpp +++ b/stdlib/public/runtime/Demangle.cpp @@ -465,6 +465,69 @@ _buildDemanglingForNominalType(const Metadata *type, Demangle::Demangler &Dem) { return _buildDemanglingForContext(description, demangledGenerics, Dem); } +static Demangle::NodePointer +_replaceGeneralizationArg(Demangle::NodePointer type, + SubstGenericParametersFromMetadata substitutions, + Demangle::Demangler &Dem) { + assert(type->getKind() == Node::Kind::Type); + auto genericParam = type->getChild(0); + + if (genericParam->getKind() != Node::Kind::DependentGenericParamType) + return type; + + auto depth = genericParam->getChild(0)->getIndex(); + auto index = genericParam->getChild(1)->getIndex(); + + auto arg = substitutions.getMetadata(depth, index); + assert(arg.isMetadata()); + return _swift_buildDemanglingForMetadata(arg.getMetadata(), Dem); +} + +static Demangle::NodePointer +_buildDemanglingForExtendedExistential(const Metadata *type, + Demangle::Demangler &Dem) { + auto ee = cast(type); + + auto demangledExistential = Dem.demangleType(ee->Shape->ExistentialType.get(), + ResolveToDemanglingForContext(Dem)); + + if (!ee->Shape->hasGeneralizationSignature()) + return demangledExistential; + + SubstGenericParametersFromMetadata substitutions(ee->Shape, + ee->getGeneralizationArguments()); + + // Dig out the requirement list. + auto constrainedExistential = demangledExistential->getChild(0); + assert(constrainedExistential->getKind() == Node::Kind::ConstrainedExistential); + auto reqList = constrainedExistential->getChild(1); + assert(reqList->getKind() == Node::Kind::ConstrainedExistentialRequirementList); + + auto newReqList = Dem.createNode(Node::Kind::ConstrainedExistentialRequirementList); + + for (auto req : *reqList) { + // Currently, the only requirements that can create generalization arguments + // are same types. + if (req->getKind() != Node::Kind::DependentGenericSameTypeRequirement) { + newReqList->addChild(req, Dem); + continue; + } + + auto lhs = _replaceGeneralizationArg(req->getChild(0), substitutions, Dem); + auto rhs = _replaceGeneralizationArg(req->getChild(1), substitutions, Dem); + + auto newReq = Dem.createNode(Node::Kind::DependentGenericSameTypeRequirement); + newReq->addChild(lhs, Dem); + newReq->addChild(rhs, Dem); + + newReqList->addChild(newReq, Dem); + } + + constrainedExistential->replaceChild(1, newReqList); + + return demangledExistential; +} + // Build a demangled type tree for a type. // // FIXME: This should use MetadataReader.h. @@ -596,13 +659,7 @@ swift::_swift_buildDemanglingForMetadata(const Metadata *type, return proto_list; } case MetadataKind::ExtendedExistential: { - // FIXME: Implement this by demangling the extended existential and - // substituting the generalization arguments into the demangle tree. - // For now, unconditional casts will report '<<< invalid type >>>' when - // they fail. - // TODO: for clients that need to guarantee round-tripping, demangle - // to a SymbolicExtendedExistentialType. - return nullptr; + return _buildDemanglingForExtendedExistential(type, Dem); } case MetadataKind::ExistentialMetatype: { auto metatype = static_cast(type); diff --git a/stdlib/public/runtime/DynamicCast.cpp b/stdlib/public/runtime/DynamicCast.cpp index 6f197aaca2ceb..dc8a16f37a839 100644 --- a/stdlib/public/runtime/DynamicCast.cpp +++ b/stdlib/public/runtime/DynamicCast.cpp @@ -206,13 +206,86 @@ struct _ObjectiveCBridgeableWitnessTable : WitnessTable { extern "C" const ProtocolDescriptor PROTOCOL_DESCR_SYM(s21_ObjectiveCBridgeable); +#if SWIFT_OBJC_INTEROP +#define BRIDGING_CONFORMANCE_SYM \ + MANGLE_SYM(s19_BridgeableMetatypeVs21_ObjectiveCBridgeablesWP) + +extern "C" const _ObjectiveCBridgeableWitnessTable BRIDGING_CONFORMANCE_SYM; +#endif + +/// Nominal type descriptor for Swift.String. +extern "C" const StructDescriptor NOMINAL_TYPE_DESCR_SYM(SS); + +struct ObjCBridgeWitnessCacheEntry { + const Metadata *metadata; + const _ObjectiveCBridgeableWitnessTable *witness; +}; + static const _ObjectiveCBridgeableWitnessTable * -findBridgeWitness(const Metadata *T) { +swift_conformsToObjectiveCBridgeableNoCache(const Metadata *T) { auto w = swift_conformsToProtocolCommon( - T, &PROTOCOL_DESCR_SYM(s21_ObjectiveCBridgeable)); + T, &PROTOCOL_DESCR_SYM(s21_ObjectiveCBridgeable)); return reinterpret_cast(w); } +static const _ObjectiveCBridgeableWitnessTable * +swift_conformsToObjectiveCBridgeable(const Metadata *T) { + static std::atomic _objcBridgeWitnessCache = {}; + auto cached = _objcBridgeWitnessCache.load(SWIFT_MEMORY_ORDER_CONSUME); + if (cached.metadata == T) { + return cached.witness; + } + cached.witness = swift_conformsToObjectiveCBridgeableNoCache(T); + cached.metadata = T; + _objcBridgeWitnessCache.store(cached, std::memory_order_release); + return cached.witness; +} + +static const _ObjectiveCBridgeableWitnessTable * +findBridgeWitness(const Metadata *T) { + // Special case: Memoize the bridge witness for Swift.String. + // Swift.String is the most heavily used bridge because of the prevalence of + // string-keyed dictionaries in Obj-C. It's worth burning a few words of static + // storage to avoid repeatedly looking up this conformance. + if (T->getKind() == MetadataKind::Struct) { + auto structDescription = cast(T)->Description; + if (structDescription == &NOMINAL_TYPE_DESCR_SYM(SS)) { + static auto *Swift_String_ObjectiveCBridgeable = swift_conformsToObjectiveCBridgeableNoCache(T); + return Swift_String_ObjectiveCBridgeable; + } + } + + auto w = swift_conformsToObjectiveCBridgeable(T); + if (SWIFT_LIKELY(w)) + return reinterpret_cast(w); + // Class and ObjC existential metatypes can be bridged, but metatypes can't + // directly conform to protocols yet. Use a stand-in conformance for a type + // that looks like a metatype value if the metatype can be bridged. + switch (T->getKind()) { + case MetadataKind::Metatype: { +#if SWIFT_OBJC_INTEROP + auto metaTy = static_cast(T); + if (metaTy->InstanceType->isAnyClass()) + return &BRIDGING_CONFORMANCE_SYM; +#endif + break; + } + case MetadataKind::ExistentialMetatype: { +#if SWIFT_OBJC_INTEROP + auto existentialMetaTy = + static_cast(T); + if (existentialMetaTy->isObjC()) + return &BRIDGING_CONFORMANCE_SYM; +#endif + break; + } + + default: + break; + } + return nullptr; +} + /// Retrieve the bridged Objective-C type for the given type that /// conforms to \c _ObjectiveCBridgeable. MetadataResponse @@ -734,7 +807,7 @@ struct ObjCBridgeMemo { #if !NDEBUG memo->destType = setupData->destType; #endif - memo->destBridgeWitness = findBridgeWitness(setupData->destType); + memo->destBridgeWitness = swift_conformsToObjectiveCBridgeableNoCache(setupData->destType); if (memo->destBridgeWitness == nullptr) { memo->targetBridgedType = nullptr; memo->targetBridgedObjCClass = nullptr; diff --git a/test/ASTGen/attrs.swift b/test/ASTGen/attrs.swift index 9b9c3aba5e497..a223977aa26f2 100644 --- a/test/ASTGen/attrs.swift +++ b/test/ASTGen/attrs.swift @@ -256,3 +256,6 @@ struct LayoutOuter { struct AnyEraser: EraserProto { init(erasing: T) {} } + +func takeNone(@_inheritActorContext param: @Sendable () async -> ()) { } +func takeAlways(@_inheritActorContext(always) param: sending @isolated(any) () -> ()) { } diff --git a/test/AutoDiff/Serialization/derivative_attr.swift b/test/AutoDiff/Serialization/derivative_attr.swift index c41c0a36d1a50..2063f0283423e 100644 --- a/test/AutoDiff/Serialization/derivative_attr.swift +++ b/test/AutoDiff/Serialization/derivative_attr.swift @@ -141,7 +141,7 @@ extension S { self } - // CHECK: @derivative(of: subscript, wrt: self) + // CHECK: @derivative(of: subscript(_:), wrt: self) @derivative(of: subscript(_:), wrt: self) func derivativeSubscript(x: T) -> (value: S, differential: (S) -> S) { (self, { $0 }) diff --git a/test/AutoDiff/Serialization/transpose_attr.swift b/test/AutoDiff/Serialization/transpose_attr.swift index 9f864862cda95..d969da11c3b8c 100644 --- a/test/AutoDiff/Serialization/transpose_attr.swift +++ b/test/AutoDiff/Serialization/transpose_attr.swift @@ -89,7 +89,7 @@ extension S { extension S { subscript(x: T) -> Self { self } - // CHECK: @transpose(of: subscript, wrt: self) + // CHECK: @transpose(of: subscript(_:), wrt: self) @transpose(of: subscript(_:), wrt: self) static func transposeSubscript(x: T, t: Self) -> Self { t diff --git a/test/CAS/cas_fs.swift b/test/CAS/cas_fs.swift deleted file mode 100644 index a4b0e2cab6ea5..0000000000000 --- a/test/CAS/cas_fs.swift +++ /dev/null @@ -1,28 +0,0 @@ -// RUN: %empty-directory(%t) -// RUN: mkdir -p %t/empty -// RUN: mkdir -p %t/cas - -// RUN: llvm-cas --cas %t/cas --ingest %t/empty > %t/empty.casid -// RUN: not %target-swift-frontend -typecheck -cache-compile-job -cas-fs @%t/empty.casid -cas-path %t/cas %s 2>&1 | %FileCheck %s --check-prefix NO-INPUTS -// NO-INPUTS: error: error opening input file - -// RUN: llvm-cas --cas %t/cas --ingest %s > %t/source.casid -// RUN: not %target-swift-frontend -typecheck -cache-compile-job -cas-fs @%t/source.casid -cas-path %t/cas %s 2>&1 | %FileCheck %s --check-prefix NO-RESOURCES -// NO-RESOURCES: error: unable to load standard library - -/// Ingest the resource directory to satisfy the file system requirement. Also switch CWD to resource dir. -// RUN: llvm-cas --cas %t/cas --merge @%t/source.casid %test-resource-dir > %t/full.casid -// RUN: cd %test-resource-dir -// RUN: %target-swift-frontend -typecheck -cache-compile-job -cas-fs @%t/full.casid -cas-path %t/cas %s - -/// Try clang importer. -// RUN: not %target-swift-frontend -typecheck -cache-compile-job -cas-fs @%t/full.casid -cas-path %t/cas %s -import-objc-header %S/Inputs/objc.h 2>&1 | %FileCheck %s --check-prefix NO-BRIDGING-HEADER -// NO-BRIDGING-HEADER: error: bridging header - -// RUN: llvm-cas --cas %t/cas --merge @%t/full.casid %S/Inputs/objc.h > %t/bridging_header.casid -// RUN: %target-swift-frontend -typecheck -cache-compile-job -cas-fs @%t/bridging_header.casid -cas-path %t/cas %s -import-objc-header %S/Inputs/objc.h - -/// Clean the CAS to save space. -// RUN: %empty-directory(%t) - -func testFunc() {} diff --git a/test/CAS/cas_output_backend.swift b/test/CAS/cas_output_backend.swift index 603bc5d58adbb..992c4b6425f7c 100644 --- a/test/CAS/cas_output_backend.swift +++ b/test/CAS/cas_output_backend.swift @@ -2,7 +2,7 @@ // RUN: mkdir -p %t/cas // RUN: not %target-swift-frontend -c -cache-compile-job -cas-path %t/cas %s -o %t/test.o 2>&1 | %FileCheck %s --check-prefix=NO-CASFS -// NO-CASFS: caching is enabled without -cas-fs option +// NO-CASFS: caching is enabled without CAS file-system options // RUN: %target-swift-frontend -scan-dependencies -module-name Test -O \ // RUN: -disable-implicit-string-processing-module-import -disable-implicit-concurrency-module-import -parse-stdlib \ diff --git a/test/CAS/coverage-dir.swift b/test/CAS/coverage-dir.swift new file mode 100644 index 0000000000000..69d79c94831fb --- /dev/null +++ b/test/CAS/coverage-dir.swift @@ -0,0 +1,28 @@ +// RUN: %empty-directory(%t) +// RUN: split-file %s %t + +// RUN: %target-swift-frontend -scan-dependencies -module-name Test -O -I %t/include \ +// RUN: -disable-implicit-string-processing-module-import -disable-implicit-concurrency-module-import \ +// RUN: %t/main.swift -o %t/deps.json -cache-compile-job -cas-path %t/cas -profile-coverage-mapping -profile-generate + +// RUN: %{python} %S/Inputs/BuildCommandExtractor.py %t/deps.json clang:SwiftShims > %t/shim.cmd +// RUN: %swift_frontend_plain @%t/shim.cmd +// RUN: %{python} %S/Inputs/BuildCommandExtractor.py %t/deps.json A > %t/A.cmd +// RUN: %swift_frontend_plain @%t/A.cmd + +// RUN: %FileCheck %s --input-file=%t/shim.cmd +// RUN: %FileCheck %s --input-file=%t/A.cmd + +// CHECK: -direct-clang-cc1-module-build +// CHECK-NOT: -fcoverage-compilation-dir + +//--- main.swift +import A +func test() { + a(); +} + +//--- include/A.swiftinterface +// swift-interface-format-version: 1.0 +// swift-module-flags: -module-name A -O -disable-implicit-string-processing-module-import -disable-implicit-concurrency-module-import -parse-stdlib -user-module-version 1.0 +public func a() { } diff --git a/test/CAS/module_deps.swift b/test/CAS/module_deps.swift deleted file mode 100644 index 509f3d2984b3b..0000000000000 --- a/test/CAS/module_deps.swift +++ /dev/null @@ -1,197 +0,0 @@ -// REQUIRES: objc_interop - -// RUN: %empty-directory(%t) -// RUN: mkdir -p %t/clang-module-cache -// RUN: mkdir -p %t/cas - -// RUN: %target-swift-frontend -scan-dependencies -module-load-mode prefer-interface -module-cache-path %t/clang-module-cache %s -o %t/deps.json -I %S/../ScanDependencies/Inputs/CHeaders -I %S/../ScanDependencies/Inputs/Swift -emit-dependencies -emit-dependencies-path %t/deps.d -import-objc-header %S/../ScanDependencies/Inputs/CHeaders/Bridging.h -swift-version 4 -enable-cross-import-overlays -cache-compile-job -cas-path %t/cas -no-clang-include-tree -scanner-output-dir %t -auto-bridging-header-chaining -// Check the contents of the JSON output -// RUN: %validate-json %t/deps.json &>/dev/null -// RUN: %FileCheck -check-prefix CHECK -check-prefix CHECK_NO_CLANG_TARGET %s < %t/deps.json - -// Check the contents of the JSON output -// RUN: %FileCheck %s -check-prefix CHECK -check-prefix CHECK-NO-SEARCH-PATHS < %t/deps.json - -// Check the make-style dependencies file -// RUN: %FileCheck %s -check-prefix CHECK-MAKE-DEPS < %t/deps.d - -// RUN: %target-swift-frontend -scan-dependencies -module-load-mode prefer-interface -test-dependency-scan-cache-serialization -module-cache-path %t/clang-module-cache %s -o %t/deps.json -I %S/../ScanDependencies/Inputs/CHeaders -I %S/../ScanDependencies/Inputs/Swift -import-objc-header %S/../ScanDependencies/Inputs/CHeaders/Bridging.h -swift-version 4 -enable-cross-import-overlays -cache-compile-job -cas-path %t/cas -no-clang-include-tree -scanner-output-dir %t -auto-bridging-header-chaining -// RUN: %validate-json %t/deps.json &>/dev/null -// RUN: %FileCheck -check-prefix CHECK -check-prefix CHECK_NO_CLANG_TARGET %s < %t/deps.json - -// Ensure that scanning with `-clang-target` makes sure that Swift modules' respective PCM-dependency-build-argument sets do not contain target triples. -// RUN: %target-swift-frontend -scan-dependencies -module-load-mode prefer-interface -module-cache-path %t/clang-module-cache %s -o %t/deps_clang_target.json -I %S/../ScanDependencies/Inputs/CHeaders -I %S/../ScanDependencies/Inputs/Swift -import-objc-header %S/../ScanDependencies/Inputs/CHeaders/Bridging.h -swift-version 4 -enable-cross-import-overlays -clang-target %target-cpu-apple-macosx10.14 -cache-compile-job -cas-path %t/cas -no-clang-include-tree - -/// check cas-fs content -// RUN: %{python} %S/Inputs/SwiftDepsExtractor.py %t/deps.json E casFSRootID > %t/E_fs.casid -// RUN: %cache-tool -cas-path %t/cas -cache-tool-action print-include-tree-list @%t/E_fs.casid | %FileCheck %s -check-prefix FS_ROOT_E -// RUN: %{python} %S/Inputs/SwiftDepsExtractor.py %t/deps.json clang:F casFSRootID > %t/F_fs.casid -// RUN: llvm-cas --cas %t/cas --ls-tree-recursive @%t/F_fs.casid | %FileCheck %s -check-prefix FS_ROOT_F - -// RUN: %{python} %S/Inputs/SwiftDepsExtractor.py %t/deps.json deps commandLine > %t/deps.cmd -// RUN: %FileCheck %s -check-prefix MAIN_CMD -input-file=%t/deps.cmd - -// FS_ROOT_E-DAG: E.swiftinterface -// FS_ROOT_E-DAG: SDKSettings.json - -// FS_ROOT_F: CHeaders/A.h -// FS_ROOT_F: CHeaders/B.h -// FS_ROOT_F: CHeaders/C.h -// FS_ROOT_F: CHeaders/D.h -// FS_ROOT_F: CHeaders/F.h -// FS_ROOT_F: CHeaders/G.h -// FS_ROOT_F: CHeaders/H.h -// FS_ROOT_F: CHeaders/I.h -// FS_ROOT_F: CHeaders/X.h -// FS_ROOT_F: CHeaders/module.modulemap - -// MAIN_CMD: -direct-clang-cc1-module-build -// MAIN_CMD: -cas-fs -// MAIN_CMD-NOT: -clang-include-tree-root - -import C -import E -import G -import SubE - -// CHECK: "mainModuleName": "deps" - -/// --------Main module -// CHECK-LABEL: "modulePath": "deps.swiftmodule", -// CHECK-NEXT: sourceFiles -// CHECK-NEXT: module_deps.swift -// CHECK-NEXT: ], -// CHECK-NEXT: "directDependencies": [ -// CHECK-DAG: "clang": "C" -// CHECK-DAG: "swift": "E" -// CHECK-DAG: "swift": "G" -// CHECK-DAG: "swift": "SubE" -// CHECK-DAG: "swift": "Swift" -// CHECK-DAG: "swift": "SwiftOnoneSupport" -// CHECK-DAG: "swift": "_Concurrency" -// CHECK-DAG: "swift": "_cross_import_E" -// CHECK: ], -// CHECK: "commandLine": -// CHECK: "casFSRootID": -// CHECK-NOT: "error: cannot open Swift placeholder dependency module map from" -// CHECK: "bridgingHeader": -// CHECK-NEXT: "path": -// CHECK-SAME: Bridging.h - -// CHECK-NEXT: "sourceFiles": -// CHECK-NEXT: ChainedBridgingHeader.h -// CHECK-NEXT: Bridging.h -// CHECK-NEXT: BridgingOther.h - -// CHECK: "moduleDependencies": [ -// CHECK-NEXT: "F" -// CHECK-NEXT: ] - -// CHECK: "swiftOverlayDependencies": [ -// CHECK-DAG: "swift": "A" -// CHECK-DAG: "swift": "F" - -/// --------Clang module C -// CHECK-LABEL: "modulePath": "{{.*}}{{/|\\}}C-{{.*}}.pcm", - -// CHECK: "sourceFiles": [ -// CHECK-DAG: module.modulemap -// CHECK-DAG: C.h - -// CHECK: directDependencies -// CHECK-NEXT: { -// CHECK-NEXT: "clang": "B" - -// CHECK: "moduleMapPath" -// CHECK-SAME: module.modulemap - -// CHECK: "contextHash" -// CHECK-SAME: "{{.*}}" - -/// --------Clang module B -// CHECK-LABEL: "modulePath": "{{.*}}{{/|\\}}B-{{.*}}.pcm", -// CHECK: "contextHash": "[[B_CONTEXT:.*]]", -// CHECK: "-o" -// CHECK-NEXT: B-{{.*}}[[B_CONTEXT]].pcm - -// Check make-style dependencies -// CHECK-MAKE-DEPS: module_deps.swift -// CHECK-MAKE-DEPS-SAME: A.swiftinterface -// CHECK-MAKE-DEPS-SAME: G.swiftinterface -// CHECK-MAKE-DEPS-SAME: B.h -// CHECK-MAKE-DEPS-SAME: Bridging.h -// CHECK-MAKE-DEPS-SAME: BridgingOther.h -// CHECK-MAKE-DEPS-SAME: module.modulemap - -/// --------Swift module F -// CHECK: "modulePath": "{{.*}}{{/|\\}}F-{{.*}}.swiftmodule", -// CHECK-NEXT: "sourceFiles": [ -// CHECK-NEXT: ], -// CHECK-NEXT: "directDependencies": [ -// CHECK-NEXT: { -// CHECK-DAG: "clang": "F" -// CHECK-DAG: "swift": "Swift" -// CHECK-DAG: "swift": "SwiftOnoneSupport" -// CHECK-NEXT: } -// CHECK-NEXT: ], -// CHECK: "details": -// CHECK: "moduleCacheKey": - -/// --------Swift module A -// CHECK-LABEL: "modulePath": "{{.*}}{{/|\\}}A-{{.*}}.swiftmodule", - -// CHECK: directDependencies -// CHECK-NEXT: { -// CHECK-DAG: "clang": "A" -// CHECK-DAG: "swift": "Swift" -// CHECK-DAG: "swift": "SwiftOnoneSupport" -// CHECK-NEXT: } -// CHECK: "details": -// CHECK: "moduleCacheKey": - -/// --------Swift module G -// CHECK-LABEL: "modulePath": "{{.*}}{{/|\\}}G-{{.*}}.swiftmodule" -// CHECK: "directDependencies" -// CHECK-NEXT: { -// CHECK-DAG: "clang": "G" -// CHECK-DAG: "swift": "Swift" -// CHECK-DAG: "swift": "SwiftOnoneSupport" -// CHECK: ], -// CHECK-NEXT: "linkLibraries": [ -// CHECK: "details": { - -// CHECK: "commandLine": [ -// CHECK: "-compile-module-from-interface" -// CHECK: "-target" -// CHECK: "-cache-compile-job" -// CHECK: "-cas-path" -// CHECK: "-module-name" -// CHECK: "G" -// CHECK: "-swift-version" -// CHECK: "5" -// CHECK: ], -// CHECK: "contextHash": "{{.*}}", - -/// --------Swift module E -// CHECK: "swift": "E" -// CHECK-LABEL: modulePath": "{{.*}}{{/|\\}}E-{{.*}}.swiftmodule" -// CHECK: "directDependencies" -// CHECK-NEXT: { -// CHECK-NEXT: "swift": "Swift" - -// CHECK: "moduleInterfacePath" -// CHECK-SAME: E.swiftinterface - -/// --------Swift module Swift -// CHECK-LABEL: "modulePath": "{{.*}}{{/|\\}}Swift-{{.*}}.swiftmodule", - -// CHECK: directDependencies -// CHECK-NEXT: { -// CHECK-NEXT: "clang": "SwiftShims" - -/// --------Clang module SwiftShims -// CHECK-LABEL: "modulePath": "{{.*}}{{/|\\}}SwiftShims-{{.*}}.pcm", -// CHECK: "contextHash": "[[SHIMS_CONTEXT:.*]]", -// CHECK: "-o" -// CHECK-NEXT: SwiftShims-{{.*}}[[SHIMS_CONTEXT]].pcm -// CHECK-NO-SEARCH-PATHS-NOT: "-prebuilt-module-cache-path" diff --git a/test/CAS/module_deps_clang_extras.swift b/test/CAS/module_deps_clang_extras.swift index b0950f6e23502..e11709da3b839 100644 --- a/test/CAS/module_deps_clang_extras.swift +++ b/test/CAS/module_deps_clang_extras.swift @@ -4,46 +4,99 @@ // RUN: mkdir -p %t/clang-module-cache // RUN: mkdir -p %t/cas // RUN: split-file %s %t -// RUN: %hmaptool write %t/hmap.json %t/empty.hmap +// RUN: sed "s|DIR|%/t|g" %t/hmap.json.template > %t/hmap.json +// RUN: sed "s|DIR|%/t|g" %t/test.yaml.template > %t/test.yaml +// RUN: %hmaptool write %t/hmap.json %t/test.hmap // RUN: %target-swift-frontend -scan-dependencies -module-cache-path %t/clang-module-cache \ -// RUN: %t/Test.swift -o %t/deps.json -cache-compile-job -cas-path %t/cas \ -// RUN: -Xcc -fmodule-map-file=%t/module.modulemap -Xcc -ivfsoverlay -Xcc %t/empty.yaml \ -// RUN: -Xcc -I%t/empty.hmap +// RUN: %t/Test.swift -module-name Test -o %t/deps.json -cache-compile-job -cas-path %t/cas \ +// RUN: -disable-implicit-string-processing-module-import -disable-implicit-concurrency-module-import \ +// RUN: -Xcc -fmodule-map-file=%t/include/module.modulemap -Xcc -ivfsoverlay -Xcc %t/test.yaml \ +// RUN: -Xcc -I%t/test.hmap -module-load-mode prefer-serialized -scanner-output-dir %t \ +// RUN: -import-objc-header %t/Bridge.h -auto-bridging-header-chaining // RUN: %validate-json %t/deps.json &>/dev/null -// RUN: %{python} %S/Inputs/SwiftDepsExtractor.py %t/deps.json deps casFSRootID > %t/fs.casid +// RUN: %{python} %S/Inputs/SwiftDepsExtractor.py %t/deps.json Test casFSRootID > %t/fs.casid // RUN: %cache-tool -cas-path %t/cas -cache-tool-action print-include-tree-list @%t/fs.casid | %FileCheck %s -DDIR=%basename_t -check-prefix FS_ROOT -// RUN: %{python} %S/Inputs/SwiftDepsExtractor.py %t/deps.json clang:Dummy clangIncludeTree > %t/tree.casid -// RUN: clang-cas-test --cas %t/cas --print-include-tree @%t/tree.casid | %FileCheck %s -DDIR=%basename_t -check-prefix INCLUDE_TREE -// FS_ROOT: [[DIR]].tmp/empty.hmap -// FS_ROOT: [[DIR]].tmp/empty.yaml +// FS_ROOT: [[DIR]].tmp/hidden/Dummy.h +// FS_ROOT: [[DIR]].tmp/hidden/a.h +// FS_ROOT: [[DIR]].tmp/hidden/b.h -// INCLUDE_TREE: [[DIR]].tmp/Dummy.h +// RUN: %{python} %S/Inputs/BuildCommandExtractor.py %t/deps.json clang:SwiftShims > %t/shim.cmd +// RUN: %swift_frontend_plain @%t/shim.cmd +// RUN: %{python} %S/Inputs/BuildCommandExtractor.py %t/deps.json clang:Dummy > %t/dummy.cmd +// RUN: %swift_frontend_plain @%t/dummy.cmd + +// RUN: %{python} %S/Inputs/BuildCommandExtractor.py %t/deps.json bridgingHeader > %t/header.cmd +// RUN: %target-swift-frontend @%t/header.cmd -disable-implicit-swift-modules -O -o %t/objc.pch +// RUN: %cache-tool -cas-path %t/cas -cache-tool-action print-output-keys -- \ +// RUN: %target-swift-frontend @%t/header.cmd -disable-implicit-swift-modules -O -o %t/objc.pch > %t/keys.json +// RUN: %{python} %S/Inputs/ExtractOutputKey.py %t/keys.json > %t/key + +// RUN: %{python} %S/Inputs/GenerateExplicitModuleMap.py %t/deps.json > %t/map.json +// RUN: llvm-cas --cas %t/cas --make-blob --data %t/map.json > %t/map.casid + +// RUN: %{python} %S/Inputs/BuildCommandExtractor.py %t/deps.json Test > %t/MyApp.cmd +// RUN: echo "\"-disable-implicit-string-processing-module-import\"" >> %t/MyApp.cmd +// RUN: echo "\"-disable-implicit-concurrency-module-import\"" >> %t/MyApp.cmd +// RUN: echo "\"-disable-implicit-swift-modules\"" >> %t/MyApp.cmd +// RUN: echo "\"-import-objc-header\"" >> %t/MyApp.cmd +// RUN: echo "\"%t/objc.pch\"" >> %t/MyApp.cmd +// RUN: echo "\"-bridging-header-pch-key\"" >> %t/MyApp.cmd +// RUN: echo "\"@%t/key\"" >> %t/MyApp.cmd +// RUN: echo "\"-explicit-swift-module-map-file\"" >> %t/MyApp.cmd +// RUN: echo "\"@%t/map.casid\"" >> %t/MyApp.cmd + +// RUN: %target-swift-frontend -cache-compile-job -module-name Test -O -cas-path %t/cas @%t/MyApp.cmd %t/Test.swift \ +// RUN: -emit-module -o %t/test.swiftmodule //--- Test.swift import Dummy func test() {} -//--- module.modulemap +//--- Bridge.h +#include "b.h" + +//--- hidden/module.modulemap module Dummy { umbrella header "Dummy.h" } -//--- Dummy.h +//--- hidden/Dummy.h +#include "a.h" void dummy(void); -//--- hmap.json +//--- hidden/a.h +/* empty file */ + +//--- hidden/b.h +/* empty file */ + +//--- hmap.json.template { - "mappings": {} + "mappings": { + "a.h": "DIR/hidden/a.h", + "b.h": "DIR/hidden/b.h" + } } -//--- empty.yaml +//--- test.yaml.template { "version": 0, "case-sensitive": "false", "use-external-names": true, - "roots": [] + "roots": [ + { + "type": "file", + "name": "DIR/include/module.modulemap", + "external-contents": "DIR/hidden/module.modulemap" + }, + { + "type": "file", + "name": "DIR/include/Dummy.h", + "external-contents": "DIR/hidden/Dummy.h" + }, + ] } diff --git a/test/CAS/module_deps_include_tree.swift b/test/CAS/module_deps_include_tree.swift index 711d84a680864..5ae9d06981603 100644 --- a/test/CAS/module_deps_include_tree.swift +++ b/test/CAS/module_deps_include_tree.swift @@ -41,7 +41,6 @@ // INCLUDE_TREE_F-NEXT: CHeaders/F.h // MAIN_CMD: -direct-clang-cc1-module-build -// MAIN_CMD: -clang-include-tree-root // MAIN_CMD: -clang-include-tree-filelist import C diff --git a/test/ClangImporter/const_values_apinotes.swift b/test/ClangImporter/const_values_apinotes.swift new file mode 100644 index 0000000000000..d8b00bae165e4 --- /dev/null +++ b/test/ClangImporter/const_values_apinotes.swift @@ -0,0 +1,38 @@ +// RUN: %empty-directory(%t/src) +// RUN: split-file %s %t/src + +// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) %t/src/main.swift \ +// RUN: -module-name main -I %t/src -emit-sil -sil-verify-all | %FileCheck %s + +//--- test.h + +typedef long NSInteger; +typedef enum XCTestErrorCode: NSInteger { + XCTestErrorCodeTimeoutWhileWaiting, + XCTestErrorCodeFailureWhileWaiting, +} XCTestErrorCode; + +static XCTestErrorCode const XCTestErrorUnsupported = (XCTestErrorCode)109; + +//--- Framework.apinotes +--- +Name: Framework +Tags: +- Name: XCTestErrorCode + NSErrorDomain: XCTestErrorDomain + +//--- module.modulemap +module Framework { + header "test.h" +} + +//--- main.swift +import Framework +func foo() { + print(XCTestError.timeoutWhileWaiting) + print(XCTestErrorUnsupported) +} + + +// CHECK: // XCTestErrorUnsupported.getter +// CHECK: sil shared [transparent] @$sSo22XCTestErrorUnsupportedSo0aB4CodeVvg : $@convention(thin) () -> XCTestError { diff --git a/test/Concurrency/Runtime/async_parameter_pack.swift b/test/Concurrency/Runtime/async_parameter_pack.swift new file mode 100644 index 0000000000000..bc6a82776178a --- /dev/null +++ b/test/Concurrency/Runtime/async_parameter_pack.swift @@ -0,0 +1,21 @@ +// RUN: %target-run-simple-swift( -target %target-swift-5.9-abi-triple) +// REQUIRES: executable_test +// REQUIRES: concurrency + +protocol P { + associatedtype A + var a: A { get } +} + +func f(_ t: repeat each T) async -> (repeat (each T).A) { + let x = (repeat (each t).a) + return x +} + +struct S: P { + var a: String { "" } +} + +_ = await f() +_ = await f(S()) +_ = await f(S(), S()) diff --git a/test/Concurrency/Runtime/async_task_executor_nsobject.swift b/test/Concurrency/Runtime/async_task_executor_nsobject.swift index d652f7d246f01..cc1d85d3edbc3 100644 --- a/test/Concurrency/Runtime/async_task_executor_nsobject.swift +++ b/test/Concurrency/Runtime/async_task_executor_nsobject.swift @@ -22,7 +22,7 @@ import Darwin // This test specifically checks that our reference counting accounts for existence of // objective-c types as TaskExecutors -- which was a bug where we'd swift_release // obj-c excecutors by accident (rdar://131151645). -final class NSQueueTaskExecutor: NSData, TaskExecutor, SchedulableExecutor, @unchecked Sendable { +final class NSQueueTaskExecutor: NSData, TaskExecutor, _SchedulableExecutor, @unchecked Sendable { public func enqueue(_ _job: consuming ExecutorJob) { let job = UnownedJob(_job) DispatchQueue.main.async { @@ -30,12 +30,12 @@ final class NSQueueTaskExecutor: NSData, TaskExecutor, SchedulableExecutor, @unc } } - public func enqueue(_ _job: consuming ExecutorJob, - after delay: C.Duration, - tolerance: C.Duration? = nil, - clock: C) { + public func _enqueue(_ _job: consuming ExecutorJob, + after delay: C.Duration, + tolerance: C.Duration? = nil, + clock: C) { // Convert to `Swift.Duration` - let duration = clock.convert(from: delay)! + let duration = clock._convert(from: delay)! // Now turn that into nanoseconds let (seconds, attoseconds) = duration.components diff --git a/test/Concurrency/Runtime/clocks.swift b/test/Concurrency/Runtime/clocks.swift index 731cda3503d42..8024a5c358e39 100644 --- a/test/Concurrency/Runtime/clocks.swift +++ b/test/Concurrency/Runtime/clocks.swift @@ -58,7 +58,7 @@ struct TickingClock: Clock { private var _now: Instant var now: Instant { return _now } var minimumResolution: Duration { return Duration(ticks: 1) } - var traits: ClockTraits { [.monotonic] } + var traits: _ClockTraits { [.monotonic] } init() { _now = Instant(ticksFromStart: 0) @@ -67,11 +67,11 @@ struct TickingClock: Clock { // These are a bit of a lie, since this clock is weird and doesn't // actually tell the time; for the purposes of this test, we pretend // that the ticks are 20ms. - func convert(from duration: Duration) -> Swift.Duration? { + func _convert(from duration: Duration) -> Swift.Duration? { return .seconds(Double(duration.ticks) / 50) } - func convert(from duration: Swift.Duration) -> Duration? { + func _convert(from duration: Swift.Duration) -> Duration? { let (seconds, attoseconds) = duration.components let extraTicks = attoseconds / 20_000_000_000_000_000 return Duration(ticks: Int(seconds * 50) + Int(extraTicks)) @@ -136,7 +136,7 @@ struct TockingClock: Clock { private var _now: Instant var now: Instant { return _now } var minimumResolution: Duration { return Duration(tocks: 1) } - var traits: ClockTraits { [.monotonic] } + var traits: _ClockTraits { [.monotonic] } init() { _now = Instant(tocksFromStart: 1000) @@ -145,11 +145,11 @@ struct TockingClock: Clock { // These are a bit of a lie, since this clock is weird and doesn't // actually tell the time; for the purposes of this test, we pretend // that the tocks are 10ms. - func convert(from duration: Duration) -> Swift.Duration? { + func _convert(from duration: Duration) -> Swift.Duration? { return .seconds(Double(duration.tocks) / 100) } - func convert(from duration: Swift.Duration) -> Duration? { + func _convert(from duration: Swift.Duration) -> Duration? { let (seconds, attoseconds) = duration.components let extraTocks = attoseconds / 10_000_000_000_000_000 return Duration(tocks: Int(seconds * 100) + Int(extraTocks)) @@ -196,14 +196,14 @@ struct TockingClock: Clock { expectEqual(futureA.ticksFromStart, 26) expectEqual(futureB.ticksFromStart, 42) - let futureAinB = clockB.convert(instant: futureA, from: clockA)! - let futureBinA = clockA.convert(instant: futureB, from: clockB)! + let futureAinB = clockB._convert(instant: futureA, from: clockA)! + let futureBinA = clockA._convert(instant: futureB, from: clockB)! expectEqual(futureAinB.ticksFromStart, 23) expectEqual(futureBinA.ticksFromStart, 45) - let futureAinBinA = clockA.convert(instant: futureAinB, from: clockB)! - let futureBinAinB = clockB.convert(instant: futureBinA, from: clockA)! + let futureAinBinA = clockA._convert(instant: futureAinB, from: clockB)! + let futureBinAinB = clockB._convert(instant: futureBinA, from: clockA)! expectEqual(futureAinBinA.ticksFromStart, futureA.ticksFromStart) expectEqual(futureBinAinB.ticksFromStart, futureB.ticksFromStart) @@ -222,14 +222,14 @@ struct TockingClock: Clock { expectEqual(futureA.ticksFromStart, 26) expectEqual(futureC.tocksFromStart, 1043) - let futureAinC = clockC.convert(instant: futureA, from: clockA)! - let futureCinA = clockA.convert(instant: futureC, from: clockC)! + let futureAinC = clockC._convert(instant: futureA, from: clockA)! + let futureCinA = clockA._convert(instant: futureC, from: clockC)! expectEqual(futureAinC.tocksFromStart, 1047) expectEqual(futureCinA.ticksFromStart, 24) - let futureAinCinA = clockA.convert(instant: futureAinC, from: clockC)! - let futureCinAinC = clockC.convert(instant: futureCinA, from: clockA)! + let futureAinCinA = clockA._convert(instant: futureAinC, from: clockC)! + let futureCinAinC = clockC._convert(instant: futureCinA, from: clockA)! expectEqual(futureAinCinA.ticksFromStart, futureA.ticksFromStart) expectEqual(futureCinAinC.tocksFromStart, futureC.tocksFromStart) @@ -245,15 +245,15 @@ struct TockingClock: Clock { let futureC = nowC.advanced(by: .seconds(5.3)) let futureS = nowS.advanced(by: .seconds(4.2)) - let futureCinS = suspending.convert(instant: futureC, - from: .continuous)! - let futureSinC = continuous.convert(instant: futureS, - from: .suspending)! + let futureCinS = suspending._convert(instant: futureC, + from: .continuous)! + let futureSinC = continuous._convert(instant: futureS, + from: .suspending)! - let futureCinSinC = continuous.convert(instant: futureCinS, - from: .suspending)! - let futureSinCinS = suspending.convert(instant: futureSinC, - from: .continuous)! + let futureCinSinC = continuous._convert(instant: futureCinS, + from: .suspending)! + let futureSinCinS = suspending._convert(instant: futureSinC, + from: .continuous)! // These clocks may not be exact, so allow differences of up to 50ms var delta1 = futureCinSinC - futureC diff --git a/test/Concurrency/Runtime/custom_main_executor.swift b/test/Concurrency/Runtime/custom_main_executor.swift index 08e9b8f7ce64e..6bc56f29c52b3 100644 --- a/test/Concurrency/Runtime/custom_main_executor.swift +++ b/test/Concurrency/Runtime/custom_main_executor.swift @@ -13,10 +13,10 @@ import StdlibUnittest import Synchronization -typealias DefaultExecutorFactory = SimpleExecutorFactory +typealias _DefaultExecutorFactory = SimpleExecutorFactory -struct SimpleExecutorFactory: ExecutorFactory { - public static var mainExecutor: any MainExecutor { +struct SimpleExecutorFactory: _ExecutorFactory { + public static var mainExecutor: any _MainExecutor { print("Creating main executor") return SimpleMainExecutor() } @@ -27,7 +27,7 @@ struct SimpleExecutorFactory: ExecutorFactory { } @available(SwiftStdlib 6.2, *) -final class SimpleMainExecutor: MainExecutor, @unchecked Sendable { +final class SimpleMainExecutor: _MainExecutor, @unchecked Sendable { public var isRunning: Bool = false var shouldStop: Bool = false @@ -41,7 +41,7 @@ final class SimpleMainExecutor: MainExecutor, @unchecked Sendable { } } - func run() throws { + func _run() throws { print("Running") isRunning = true while !shouldStop { @@ -58,7 +58,7 @@ final class SimpleMainExecutor: MainExecutor, @unchecked Sendable { isRunning = false } - func stop() { + func _stop() { shouldStop = true } } @@ -66,7 +66,7 @@ final class SimpleMainExecutor: MainExecutor, @unchecked Sendable { @available(SwiftStdlib 6.2, *) final class SimpleTaskExecutor: TaskExecutor, @unchecked Sendable { func enqueue(_ job: consuming ExecutorJob) { - MainActor.executor.enqueue(job) + MainActor._executor.enqueue(job) } } diff --git a/test/Concurrency/Runtime/sleep_executor.swift b/test/Concurrency/Runtime/sleep_executor.swift index f4767e5a068b3..d78bed96a47d2 100644 --- a/test/Concurrency/Runtime/sleep_executor.swift +++ b/test/Concurrency/Runtime/sleep_executor.swift @@ -21,8 +21,8 @@ actor MyActor { } @available(SwiftStdlib 6.2, *) -final class TestExecutor: TaskExecutor, SchedulableExecutor, @unchecked Sendable { - var asSchedulable: SchedulableExecutor? { +final class TestExecutor: TaskExecutor, _SchedulableExecutor, @unchecked Sendable { + var asSchedulable: _SchedulableExecutor? { return self } @@ -33,12 +33,12 @@ final class TestExecutor: TaskExecutor, SchedulableExecutor, @unchecked Sendable } } - public func enqueue(_ _job: consuming ExecutorJob, - after delay: C.Duration, - tolerance: C.Duration? = nil, - clock: C) { + public func _enqueue(_ _job: consuming ExecutorJob, + after delay: C.Duration, + tolerance: C.Duration? = nil, + clock: C) { // Convert to `Swift.Duration` - let duration = clock.convert(from: delay)! + let duration = clock._convert(from: delay)! // Now turn that into nanoseconds let (seconds, attoseconds) = duration.components diff --git a/test/Concurrency/actor_isolation.swift b/test/Concurrency/actor_isolation.swift index c4c533e7a9628..b308185529cc7 100644 --- a/test/Concurrency/actor_isolation.swift +++ b/test/Concurrency/actor_isolation.swift @@ -1210,6 +1210,8 @@ actor MyServer : Server { func acceptAsyncSendableClosure(_: @Sendable () async -> T) { } @available(SwiftStdlib 5.1, *) func acceptAsyncSendableClosureInheriting(@_inheritActorContext _: @Sendable () async -> T) { } +@available(SwiftStdlib 5.1, *) +func acceptAsyncSendableClosureInheritingAlways(@_inheritActorContext(always) _: @Sendable () async -> T) { } @available(SwiftStdlib 5.1, *) extension MyActor { @@ -1237,6 +1239,10 @@ extension MyActor { _ = await synchronous() // expected-warning{{no 'async' operations occur within 'await' expression}} counter += 1 // okay } + + acceptAsyncSendableClosureInheritingAlways { + counter += 1 // Ok + } } } @@ -1257,6 +1263,32 @@ func testGlobalActorInheritance() { acceptAsyncSendableClosureInheriting { counter += 1 // ok } + + acceptAsyncSendableClosureInheritingAlways { + counter += 1 // ok + } +} + +@available(SwiftStdlib 5.1, *) +func testIsolatedParameter1(_: isolated any Actor, v: inout Int) { + acceptAsyncSendableClosureInheriting { + v += 1 // expected-warning {{mutable capture of 'inout' parameter 'v' is not allowed in concurrently-executing code}} + } + + acceptAsyncSendableClosureInheritingAlways { + v += 1 // Ok + } +} + +@available(SwiftStdlib 5.1, *) +func testIsolatedParameter2(_: isolated (any Actor)? = #isolation, v: inout Int) { + acceptAsyncSendableClosureInheriting { + v += 1 // expected-warning {{mutable capture of 'inout' parameter 'v' is not allowed in concurrently-executing code}} + } + + acceptAsyncSendableClosureInheritingAlways { + v += 1 // Ok + } } @available(SwiftStdlib 5.1, *) @@ -1763,4 +1795,4 @@ actor UserDefinedActorSelfDotMethod { // error message changes with InferSendabaleFromCaptures - see actor_isolation_swift6.swift return functionRef // expected-error {{cannot convert return expression of type '(isolated Self) -> () -> ()' to return type '(UserDefinedActorSelfDotMethod) -> @isolated(any) () -> Void'}} } -} \ No newline at end of file +} diff --git a/test/Concurrency/async_main_resolution.swift b/test/Concurrency/async_main_resolution.swift index fbace4d1ff457..604ffeca8cebb 100644 --- a/test/Concurrency/async_main_resolution.swift +++ b/test/Concurrency/async_main_resolution.swift @@ -63,11 +63,11 @@ extension MainProtocol { #endif // CHECK-IS-SYNC-LABEL: "MyMain" interface_type="MyMain.Type" -// CHECK-IS-SYNC: (func_decl {{.*}}implicit "$main()" interface_type="(MyMain.Type) -> () -> ()" +// CHECK-IS-SYNC: (func_decl {{.*}}implicit range={{.*}} "$main()" interface_type="(MyMain.Type) -> () -> ()" // CHECK-IS-SYNC: (declref_expr implicit type="(MyMain.Type) -> () -> ()" // CHECK-IS-ASYNC-LABEL: "MyMain" interface_type="MyMain.Type" -// CHECK-IS-ASYNC: (func_decl {{.*}}implicit "$main()" interface_type="(MyMain.Type) -> () async -> ()" +// CHECK-IS-ASYNC: (func_decl {{.*}}implicit range={{.*}} "$main()" interface_type="(MyMain.Type) -> () async -> ()" // CHECK-IS-ASYNC: (declref_expr implicit type="(MyMain.Type) -> () async -> ()" // CHECK-IS-ERROR1: error: 'MyMain' is annotated with '@main' and must provide a main static function of type {{\(\) -> Void or \(\) throws -> Void|\(\) -> Void, \(\) throws -> Void, \(\) async -> Void, or \(\) async throws -> Void}} diff --git a/test/Concurrency/attr_execution/adoption_mode.swift b/test/Concurrency/attr_execution/adoption_mode.swift index 0cd5ac5bb5eb4..dd4154bb52fd6 100644 --- a/test/Concurrency/attr_execution/adoption_mode.swift +++ b/test/Concurrency/attr_execution/adoption_mode.swift @@ -12,8 +12,8 @@ struct G { // MARK: Functions do { func syncF() {} - @concurrent func executionConcurrentAsyncF() async {} - nonisolated(nonsending) func executionCallerAsyncF() async {} + @concurrent func concurrentAsyncF() async {} + nonisolated(nonsending) func nonisolatedNonsendingAsyncF() async {} @MainActor func mainActorAsyncF() async {} func isolatedParamAsyncF( isolation: isolated (any Actor)? = #isolation @@ -24,13 +24,15 @@ do { struct S { init(sync: ()) {} - @concurrent init(executionAsync: ()) async {} + @concurrent init(concurrentAsync: ()) async {} + nonisolated(nonsending) init(nonisolatedNonsendingAsync: ()) async {} @MainActor init(mainActorAsync: ()) async {} // expected-warning@+1:5 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async initializer 'init' to run on the caller's actor; use @concurrent to preserve behavior}}{{5-5=@concurrent }}{{none}} init(async: ()) async {} func syncF() {} - @concurrent func executionAsyncF() async {} + @concurrent func concurrentAsyncF() async {} + nonisolated(nonsending) func nonisolatedNonsendingAsyncF() async {} @MainActor func mainActorAsyncF() async {} // expected-warning@+2:17 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async instance method 'asyncF' to run on the caller's actor; use @concurrent to preserve behavior}}{{-1:5-5=@concurrent }}{{none}} nonisolated @@ -39,13 +41,15 @@ do { protocol P { init(sync: ()) - @concurrent init(executionAsync: ()) async + @concurrent init(concurrentAsync: ()) async + nonisolated(nonsending) init(nonisolatedNonsendingAsync: ()) async @MainActor init(mainActorAsync: ()) async // expected-warning@+1:5 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async initializer 'init' to run on the caller's actor; use @concurrent to preserve behavior}}{{5-5=@concurrent }}{{none}} init(async: ()) async func syncF() - @concurrent func executionAsyncF() async + @concurrent func concurrentAsyncF() async + nonisolated(nonsending) func nonisolatedNonsendingAsyncF() async @MainActor func mainActorAsyncF() async // expected-warning@+1:10 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async instance method 'asyncF' to run on the caller's actor; use @concurrent to preserve behavior}}{{5-5=@concurrent }}{{none}} func asyncF() async @@ -54,13 +58,15 @@ do { protocol Functions {} extension Functions { init(sync: ()) {} - @concurrent init(executionAsync: ()) async {} + @concurrent init(concurrentAsync: ()) async {} + nonisolated(nonsending) init(nonisolatedNonsendingAsync: ()) async {} @MainActor init(mainActorAsync: ()) async {} // expected-warning@+1:3 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async initializer 'init' to run on the caller's actor; use @concurrent to preserve behavior}}{{3-3=@concurrent }}{{none}} init(async: ()) async {} func syncF() {} - @concurrent func executionAsyncF() async {} + @concurrent func concurrentAsyncF() async {} + nonisolated(nonsending) func nonisolatedNonsendingAsyncF() async {} @MainActor func mainActorAsyncF() async {} // expected-warning@+1:8 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async instance method 'asyncF' to run on the caller's actor; use @concurrent to preserve behavior}}{{3-3=@concurrent }}{{none}} func asyncF() async {} @@ -75,8 +81,11 @@ do { var syncS: Int { get {} set {} } subscript(syncS _: Int) -> Int { get {} } - @concurrent var executionAsyncS: Int { get async {} } - @concurrent subscript(executionAsyncS _: Int) -> Int { get async {} } + @concurrent var concurrentAsyncS: Int { get async {} } + @concurrent subscript(concurrentAsyncS _: Int) -> Int { get async {} } + + nonisolated(nonsending) var nonisolatedNonsendingAsyncS: Int { get async {} } + nonisolated(nonsending) subscript(nonisolatedNonsendingAsyncS _: Int) -> Int { get async {} } @MainActor var mainActorAsyncS: Int { get async {} } @MainActor subscript(mainActorAsyncS _: Int) -> Int { get async {} } @@ -95,8 +104,11 @@ do { var syncS: Int { get } subscript(syncS _: Int) -> Int { get } - @concurrent var executionAsyncS: Int { get async } - @concurrent subscript(executionAsyncS _: Int) -> Int { get async } + @concurrent var concurrentAsyncS: Int { get async } + @concurrent subscript(concurrentAsyncS _: Int) -> Int { get async } + + nonisolated(nonsending) var nonisolatedNonsendingAsyncS: Int { get async } + nonisolated(nonsending) subscript(nonisolatedNonsendingAsyncS _: Int) -> Int { get async } @MainActor var mainActorAsyncS: Int { get async } @MainActor subscript(mainActorAsyncS _: Int) -> Int { get async } @@ -112,8 +124,11 @@ extension Storage { var syncS: Int { get {} set {} } subscript(syncS _: Int) -> Int { get {} } - @concurrent var executionAsyncS: Int { get async {} } - @concurrent subscript(executionAsyncS _: Int) -> Int { get async {} } + @concurrent var concurrentAsyncS: Int { get async {} } + @concurrent subscript(concurrentAsyncS _: Int) -> Int { get async {} } + + nonisolated(nonsending) var nonisolatedNonsendingAsyncS: Int { get async {} } + nonisolated(nonsending) subscript(nonisolatedNonsendingAsyncS _: Int) -> Int { get async {} } @MainActor var mainActorAsyncS: Int { get async {} } @MainActor subscript(mainActorAsyncS _: Int) -> Int { get async {} } @@ -134,7 +149,8 @@ do { enum E { case esac( sync: () -> Void, - executionAsync: @concurrent () async -> Void, + concurrentAsync: @concurrent () async -> Void, + nonisolatedNonsendingAsync: nonisolated(nonsending) () async -> Void, mainActorAsync: @MainActor () async -> Void, // expected-warning@+1:14 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async function type to be treated as specified to run on the caller's actor; use @concurrent to preserve behavior}}{{14-14=@concurrent }}{{none}} async: () async -> Void, @@ -146,7 +162,8 @@ do { struct S { subscript( sync: () -> Void, - executionAsync: @concurrent () async -> Void, + concurrentAsync: @concurrent () async -> Void, + nonisolatedNonsendingAsync: nonisolated(nonsending) () async -> Void, mainActorAsync: @MainActor () async -> Void, // expected-warning@+1:14 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async function type to be treated as specified to run on the caller's actor; use @concurrent to preserve behavior}}{{14-14=@concurrent }}{{none}} async: () async -> Void, @@ -159,7 +176,8 @@ do { func foo( sync: () -> Void, - executionAsync: @concurrent () async -> Void, + concurrentAsync: @concurrent () async -> Void, + nonisolatedNonsendingAsync: nonisolated(nonsending) () async -> Void, mainActorAsync: @MainActor () async -> Void, // expected-warning@+1:12 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async function type to be treated as specified to run on the caller's actor; use @concurrent to preserve behavior}}{{12-12=@concurrent }}{{none}} async: () async -> Void, @@ -169,7 +187,8 @@ do { let _ = { ( sync: () -> Void, - executionAsync: @concurrent () async -> Void, + concurrentAsync: @concurrent () async -> Void, + nonisolatedNonsendingAsync: nonisolated(nonsending) () async -> Void, mainActorAsync: @MainActor () async -> Void, // expected-warning@+1:12 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async function type to be treated as specified to run on the caller's actor; use @concurrent to preserve behavior}}{{12-12=@concurrent }}{{none}} async: () async -> Void, @@ -183,7 +202,8 @@ do { do { struct G { struct Sync where T == () -> Void {} - struct ExecutionAsync where T == @concurrent () async -> Void {} + struct ConcurrentAsync where T == @concurrent () async -> Void {} + struct NonisolatedNonsendingAsync where T == nonisolated(nonsending) () async -> Void {} struct MainActorAsync where T == @MainActor () async -> Void {} // expected-warning@+1:29 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async function type to be treated as specified to run on the caller's actor; use @concurrent to preserve behavior}}{{29-29=@concurrent }}{{none}} struct Async where T == () async -> Void {} @@ -196,6 +216,7 @@ do { do { let _: () -> Void let _: @concurrent () async -> Void + let _: nonisolated(nonsending) () async -> Void let _: @MainActor () async -> Void // expected-warning@+1:10 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async function type to be treated as specified to run on the caller's actor; use @concurrent to preserve behavior}}{{10-10=@concurrent }}{{none}} let _: () async -> Void @@ -209,6 +230,7 @@ do { let _ = anything as? () -> Void let _ = anything as? @concurrent () async -> Void + let _ = anything as? nonisolated(nonsending) () async -> Void let _ = anything as? @MainActor () async -> Void // expected-warning@+1:24 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async function type to be treated as specified to run on the caller's actor; use @concurrent to preserve behavior}}{{24-24=@concurrent }}{{none}} let _ = anything as? () async -> Void @@ -220,6 +242,8 @@ do { do { nonisolated func nonisolatedF() { + let x = 0 + let _ = { () -> Void in } let _ = { @concurrent () async -> Void in } @@ -227,11 +251,14 @@ do { // expected-warning@+1:13 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async closure to run on the caller's actor; use @concurrent to preserve behavior}}{{15-15=@concurrent }}{{none}} let _ = { () async -> Void in } - - func takesInts(_: Int...) {} + // expected-warning@+1:13 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async closure to run on the caller's actor; use @concurrent to preserve behavior}}{{15-15=@concurrent }}{{none}} + let _ = { [x] () async -> Void in _ = x } // expected-warning@+1:13 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async closure to run on the caller's actor; use @concurrent to preserve behavior}}{{14-14= @concurrent in }}{{none}} let _ = {await globalAsyncF()} + // expected-warning@+1:13 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async closure to run on the caller's actor; use @concurrent to preserve behavior}}{{14-14=@concurrent }}{{none}} + let _ = {[x] in await globalAsyncF(); _ = x} + // expected-warning@+1:13 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async closure to run on the caller's actor; use @concurrent to preserve behavior}}{{14-14= @concurrent in }}{{none}} let _ = { await globalAsyncF() @@ -239,26 +266,40 @@ do { // expected-warning@+1:13 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async closure to run on the caller's actor; use @concurrent to preserve behavior}}{{14-14= @concurrent in }}{{none}} let _ = { await globalAsyncF() + func takesInts(_: Int...) {} takesInts($0, $1, $2) } + // expected-warning@+1:13 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async closure to run on the caller's actor; use @concurrent to preserve behavior}}{{25-25=@concurrent }}{{none}} let _ = { @Sendable in await globalAsyncF() } + // expected-warning@+1:13 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async closure to run on the caller's actor; use @concurrent to preserve behavior}}{{25-25=@concurrent }}{{none}} + let _ = { @Sendable [x] in + _ = x + await globalAsyncF() + } + // expected-warning@+2:18 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async function type to be treated as specified to run on the caller's actor; use @concurrent to preserve behavior}}{{18-18=@concurrent }}{{none}} // expected-warning@+1:45 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async closure to run on the caller's actor; use @concurrent to preserve behavior}}{{47-47=@concurrent }}{{none}} var closure: (Int, Int) async -> Void = { a, b in await globalAsyncF() } + // expected-warning@+1:15 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async closure to run on the caller's actor; use @concurrent to preserve behavior}}{{17-17=@concurrent }}{{none}} + closure = { [x] a, b in _ = x } // expected-warning@+1:15 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async closure to run on the caller's actor; use @concurrent to preserve behavior}}{{+1:7-7=@concurrent }}{{none}} closure = { - a, b async in - await globalAsyncF() + a, b async in () } - // expected-warning@+1:15 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async closure to run on the caller's actor; use @concurrent to preserve behavior}}{{17-17=@concurrent }}{{none}} - closure = { (a, b) in - await globalAsyncF() + // expected-warning@+1:15 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async closure to run on the caller's actor; use @concurrent to preserve behavior}}{{+1:7-7=@concurrent }}{{none}} + closure = { + [x] a, b async in _ = x } + // expected-warning@+1:15 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async closure to run on the caller's actor; use @concurrent to preserve behavior}}{{17-17=@concurrent }}{{none}} + closure = { (a, b) in () } + + // expected-warning@+1:15 {{feature 'NonisolatedNonsendingByDefault' will cause nonisolated async closure to run on the caller's actor; use @concurrent to preserve behavior}}{{17-17=@concurrent }}{{none}} + closure = { [x] (a, b) in _ = x } let _ = closure } diff --git a/test/Concurrency/attr_execution/conversions.swift b/test/Concurrency/attr_execution/conversions.swift index 75a996f093af9..6462cd83a2490 100644 --- a/test/Concurrency/attr_execution/conversions.swift +++ b/test/Concurrency/attr_execution/conversions.swift @@ -117,6 +117,11 @@ func testNonSendableDiagnostics( let _: nonisolated(nonsending) () async -> NonSendable = globalActor2 // expected-note {{type 'NonSendable' does not conform to 'Sendable' protocol}} // expected-error@-1 {{cannot convert '@MainActor @Sendable () async -> NonSendable' to 'nonisolated(nonsending) () async -> NonSendable' because crossing of an isolation boundary requires parameter and result types to conform to 'Sendable' protocol}} + let _: @concurrent (NonSendable) async -> Void = globalActor1 // expected-note {{type 'NonSendable' does not conform to 'Sendable' protocol}} + // expected-warning@-1 {{cannot convert '@MainActor @Sendable (NonSendable) async -> Void' to '(NonSendable) async -> Void' because crossing of an isolation boundary requires parameter and result types to conform to 'Sendable' protocol}} + let _: @concurrent () async -> NonSendable = globalActor2 // expected-note {{type 'NonSendable' does not conform to 'Sendable' protocol}} + // expected-warning@-1 {{cannot convert '@MainActor @Sendable () async -> NonSendable' to '() async -> NonSendable' because crossing of an isolation boundary requires parameter and result types to conform to 'Sendable' protocol}} + let _: nonisolated(nonsending) (NonSendable) async -> Void = erased1 // expected-note {{type 'NonSendable' does not conform to 'Sendable' protocol}} // expected-error@-1 {{cannot convert '@isolated(any) @Sendable (NonSendable) async -> Void' to 'nonisolated(nonsending) (NonSendable) async -> Void' because crossing of an isolation boundary requires parameter and result types to conform to 'Sendable' protocol}} let _: nonisolated(nonsending) () async -> NonSendable = erased2 // expected-note {{type 'NonSendable' does not conform to 'Sendable' protocol}} diff --git a/test/Concurrency/attr_execution/conversions_silgen.swift b/test/Concurrency/attr_execution/conversions_silgen.swift index 287955239d0e4..f6389f5ea2451 100644 --- a/test/Concurrency/attr_execution/conversions_silgen.swift +++ b/test/Concurrency/attr_execution/conversions_silgen.swift @@ -396,8 +396,8 @@ func globalActorConversions3(_ x: @escaping @concurrent (SendableKlass) async -> _ = await v5(SendableKlass()) } -// CHECK-LABEL: sil hidden [ossa] @$s21attr_execution_silgen26conversionsFromSyncToAsyncyyyAA16NonSendableKlassCYbc_yAA0jK0CYbScMYccyADYbScMYcctYaF : $@convention(thin) @async (@guaranteed @Sendable @callee_guaranteed (@guaranteed NonSendableKlass) -> (), @guaranteed @Sendable @callee_guaranteed (@guaranteed SendableKlass) -> (), @guaranteed @Sendable @callee_guaranteed (@guaranteed NonSendableKlass) -> ()) -> () { -// CHECK: bb0([[X:%.*]] : @guaranteed $@Sendable @callee_guaranteed (@guaranteed NonSendableKlass) -> (), [[Y:%.*]] : @guaranteed $@Sendable @callee_guaranteed (@guaranteed SendableKlass) -> (), [[Z:%.*]] : @guaranteed $@Sendable @callee_guaranteed (@guaranteed NonSendableKlass) -> ()): +// CHECK-LABEL: sil hidden [ossa] @$s21attr_execution_silgen26conversionsFromSyncToAsyncyyyAA16NonSendableKlassCYbc_yAA0jK0CYbScMYcctYaF : $@convention(thin) @async (@guaranteed @Sendable @callee_guaranteed (@guaranteed NonSendableKlass) -> (), @guaranteed @Sendable @callee_guaranteed (@guaranteed SendableKlass) -> ()) -> () +// CHECK: bb0([[X:%.*]] : @guaranteed $@Sendable @callee_guaranteed (@guaranteed NonSendableKlass) -> (), [[Y:%.*]] : @guaranteed $@Sendable @callee_guaranteed (@guaranteed SendableKlass) -> ()): // CHECK: [[X_C:%.*]] = copy_value [[X]] // CHECK: [[THUNK:%.*]] = function_ref @$s21attr_execution_silgen16NonSendableKlassCIeghg_ScA_pSgACIegHgg_TR : $@convention(thin) @async (@sil_isolated @sil_implicit_leading_param @guaranteed Optional, @guaranteed NonSendableKlass, @guaranteed @Sendable @callee_guaranteed (@guaranteed NonSendableKlass) -> ()) -> () @@ -411,19 +411,13 @@ func globalActorConversions3(_ x: @escaping @concurrent (SendableKlass) async -> // CHECK: [[THUNK:%.*]] = function_ref @$s21attr_execution_silgen13SendableKlassCIeghg_ACIegHg_TRScMTU : $@convention(thin) @async (@guaranteed SendableKlass, @guaranteed @Sendable @callee_guaranteed (@guaranteed SendableKlass) -> ()) -> () // CHECK: [[PAI:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[Y_C]]) -// CHECK: [[Z_C:%.*]] = copy_value [[Z]] -// CHECK: [[THUNK:%.*]] = function_ref @$s21attr_execution_silgen16NonSendableKlassCIeghg_ACIegHg_TRScMTU : $@convention(thin) @async (@guaranteed NonSendableKlass, @guaranteed @Sendable @callee_guaranteed (@guaranteed NonSendableKlass) -> ()) -> () -// CHECK: [[PAI:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[Z_C]]) - -// CHECK: } // end sil function '$s21attr_execution_silgen26conversionsFromSyncToAsyncyyyAA16NonSendableKlassCYbc_yAA0jK0CYbScMYccyADYbScMYcctYaF' +// CHECK: } // end sil function '$s21attr_execution_silgen26conversionsFromSyncToAsyncyyyAA16NonSendableKlassCYbc_yAA0jK0CYbScMYcctYaF' func conversionsFromSyncToAsync(_ x: @escaping @Sendable (NonSendableKlass) -> Void, - _ y: @escaping @MainActor @Sendable (SendableKlass) -> Void, - _ z: @escaping @MainActor @Sendable (NonSendableKlass) -> Void) async { + _ y: @escaping @MainActor @Sendable (SendableKlass) -> Void) async { let _: nonisolated(nonsending) (NonSendableKlass) async -> Void = x let _: nonisolated(nonsending) (SendableKlass) async -> Void = y let _: @concurrent (SendableKlass) async -> Void = y - let _: @concurrent (NonSendableKlass) async -> Void = z } func testThatClosuresAssumeIsolation(fn: inout nonisolated(nonsending) (Int) async -> Void) { diff --git a/test/Concurrency/global_actor_function_types_swift6.swift b/test/Concurrency/global_actor_function_types_swift6.swift new file mode 100644 index 0000000000000..2d422c06c6eb4 --- /dev/null +++ b/test/Concurrency/global_actor_function_types_swift6.swift @@ -0,0 +1,15 @@ +// RUN: %target-typecheck-verify-swift -target %target-swift-5.1-abi-triple -language-mode 6 + +final class NonSendable { +} + +@available(*, unavailable) +extension NonSendable: Sendable {} + +actor Test { + func testNonSendableCrossingIsolationinAsync(v: NonSendable) { + let _: () async -> NonSendable = { @MainActor in v } + // expected-error@-1 {{cannot convert '@MainActor @Sendable () async -> NonSendable' to '() async -> NonSendable' because crossing of an isolation boundary requires parameter and result types to conform to 'Sendable' protocol}} + // expected-note@-2 {{type 'NonSendable' does not conform to 'Sendable' protocol}} + } +} diff --git a/test/Concurrency/isolated_conformance_default_actor.swift b/test/Concurrency/isolated_conformance_default_actor.swift index 1b4c4b577dc2e..cd97d07306657 100644 --- a/test/Concurrency/isolated_conformance_default_actor.swift +++ b/test/Concurrency/isolated_conformance_default_actor.swift @@ -60,6 +60,10 @@ class CodableClass: Codable { var state: Int = 0 } +class OtherClass { + var otherState: any Encodable.Type = CodableClass.self +} + func acceptSendablePMeta(_: T.Type) { } func acceptSendableQMeta(_: T.Type) { } diff --git a/test/Concurrency/isolated_conformance_inference.swift b/test/Concurrency/isolated_conformance_inference.swift index e73591be5ea04..d3481c2c651c5 100644 --- a/test/Concurrency/isolated_conformance_inference.swift +++ b/test/Concurrency/isolated_conformance_inference.swift @@ -73,3 +73,22 @@ nonisolated func testConformancesFromNonisolated(tdc: TestDerivedCodable) { let _: any Codable = tdc } + +protocol P2 { + func g() +} + +struct DifferingConformances: @MainActor P { + @MainActor func f() { } +} + +extension DifferingConformances: @SomeGlobalActor P2 { + @SomeGlobalActor func g() { } +} + +@MainActor +class InferMeDefaults { + var mainState: any P.Type = DifferingConformances.self + var someGlobalActorState: any P2.Type = DifferingConformances.self // expected-error{{global actor 'SomeGlobalActor'-isolated default value in a main actor-isolated context}} + var bothState: any (P & P2).Type = DifferingConformances.self // expected-error{{default argument cannot be both main actor-isolated and global actor 'SomeGlobalActor'-isolated}} +} diff --git a/test/Concurrency/isolated_parameters.swift b/test/Concurrency/isolated_parameters.swift index 0a6ba477a8da1..9c3d35524b33d 100644 --- a/test/Concurrency/isolated_parameters.swift +++ b/test/Concurrency/isolated_parameters.swift @@ -8,7 +8,7 @@ @available(SwiftStdlib 5.1, *) actor A { - func f() { } // expected-typechecker-note 5{{calls to instance method 'f()' from outside of its actor context are implicitly asynchronous}} + func f() { } // expected-typechecker-note 3{{calls to instance method 'f()' from outside of its actor context are implicitly asynchronous}} } @available(SwiftStdlib 5.1, *) @@ -364,11 +364,8 @@ func isolatedClosures() { // expected-typechecker-warning@+2 {{cannot have more than one 'isolated' parameter; this is an error in the Swift 6 language mode}} // expected-typechecker-warning@+1 {{subscript with 'isolated' parameter cannot be 'nonisolated'; this is an error in the Swift 6 language mode}}{{3-15=}} nonisolated subscript(_ a: isolated A, _ b: isolated A) -> Int { - // FIXME: wrong isolation. should be isolated to `a`. - #if ALLOW_TYPECHECKER_ERRORS - a.f() // expected-typechecker-error {{call to actor-isolated instance method 'f()' in a synchronous actor-isolated context}} - b.f() // expected-typechecker-error {{call to actor-isolated instance method 'f()' in a synchronous actor-isolated context}} - #endif + a.f() + b.f() return 0 } @@ -591,3 +588,14 @@ public actor MyActorIsolatedParameterMerge { class ClassWithIsolatedAsyncInitializer { init(isolation: isolated (any Actor)? = #isolation) async {} } + +// https://github.com/swiftlang/swift/issues/80992 +struct WritableActorKeyPath: Sendable { + var getter: @Sendable (isolated Root) -> Value + var setter: @Sendable (isolated Root, Value) -> Void + + subscript(_ root: isolated Root) -> Value { + get { getter(root) } + nonmutating set { setter(root, newValue) } + } +} diff --git a/test/Concurrency/transfernonsendable_closureliterals_isolationinference.swift b/test/Concurrency/transfernonsendable_closureliterals_isolationinference.swift index e073badfbf2ac..0c52bb1d73cbd 100644 --- a/test/Concurrency/transfernonsendable_closureliterals_isolationinference.swift +++ b/test/Concurrency/transfernonsendable_closureliterals_isolationinference.swift @@ -24,10 +24,6 @@ func normalAcceptsClosure(_ x: () -> ()) {} func normalAcceptsSendingClosure(_ x: sending () -> ()) {} func normalAcceptsSendableClosure(_ x: @Sendable () -> ()) {} -func inheritActorContextAcceptsClosure(@_inheritActorContext _ x: () -> ()) { } -func inheritActorContextAcceptsSendingClosure(@_inheritActorContext _ x: sending () -> ()) { } -func inheritActorContextAcceptsSendableClosure(@_inheritActorContext _ x: @Sendable () -> ()) { } - @MainActor func normalGlobalActorAcceptsClosure(_ x: () -> ()) { } @MainActor @@ -35,18 +31,10 @@ func normalGlobalActorAcceptsSendingClosure(_ x: sending () -> ()) { } @MainActor func normalGlobalActorAcceptsSendableClosure(_ x: @Sendable () -> ()) { } -@MainActor -func inheritActorContextGlobalActorAcceptsClosure(@_inheritActorContext _ x: () -> ()) { } -@MainActor -func inheritActorContextGlobalActorAcceptsSendingClosure(@_inheritActorContext _ x: sending () -> ()) { } -@MainActor -func inheritActorContextGlobalActorAcceptsSendableClosure(@_inheritActorContext _ x: @Sendable () -> ()) { } - func normalAcceptsAsyncClosure(_ x: () async -> ()) {} func normalAcceptsSendingAsyncClosure(_ x: sending () async -> ()) {} func normalAcceptsSendableAsyncClosure(_ x: @Sendable () async -> ()) {} -func inheritActorContextAcceptsAsyncClosure(@_inheritActorContext _ x: () async -> ()) { } func inheritActorContextAcceptsSendingAsyncClosure(@_inheritActorContext _ x: sending () async -> ()) { } func inheritActorContextAcceptsSendableAsyncClosure(@_inheritActorContext _ x: @Sendable () async -> ()) { } @@ -57,8 +45,6 @@ func normalGlobalActorAcceptsSendingAsyncClosure(_ x: sending () async -> ()) { @MainActor func normalGlobalActorAcceptsSendableAsyncClosure(_ x: @Sendable () async -> ()) { } -@MainActor -func inheritActorContextGlobalActorAcceptsAsyncClosure(@_inheritActorContext _ x: () async -> ()) { } @MainActor func inheritActorContextGlobalActorAcceptsSendingAsyncClosure(@_inheritActorContext _ x: sending () async -> ()) { } @MainActor @@ -68,10 +54,6 @@ func asyncNormalAcceptsClosure(_ x: () -> ()) async {} func asyncNormalAcceptsSendingClosure(_ x: sending () -> ()) async {} func asyncNormalAcceptsSendableClosure(_ x: @Sendable () -> ()) async {} -func asyncInheritActorContextAcceptsClosure(@_inheritActorContext _ x: () -> ()) async {} -func asyncInheritActorContextAcceptsSendingClosure(@_inheritActorContext _ x: sending () -> ()) async {} -func asyncInheritActorContextAcceptsSendableClosure(@_inheritActorContext _ x: @Sendable () -> ()) async {} - @MainActor func asyncNormalGlobalActorAcceptsClosure(_ x: () -> ()) async {} @MainActor @@ -79,18 +61,10 @@ func asyncNormalGlobalActorAcceptsSendingClosure(_ x: sending () -> ()) async {} @MainActor func asyncNormalGlobalActorAcceptsSendableClosure(_ x: @Sendable () -> ()) async {} -@MainActor -func asyncInheritActorContextGlobalActorAcceptsClosure(@_inheritActorContext _ x: () -> ()) async {} -@MainActor -func asyncInheritActorContextGlobalActorAcceptsSendingClosure(@_inheritActorContext _ x: sending () -> ()) async {} -@MainActor -func asyncInheritActorContextGlobalActorAcceptsSendableClosure(@_inheritActorContext _ x: @Sendable () -> ()) async {} - func asyncNormalAcceptsAsyncClosure(_ x: () async -> ()) async {} func asyncNormalAcceptsSendingAsyncClosure(_ x: sending () async -> ()) async {} func asyncNormalAcceptsSendableAsyncClosure(_ x: @Sendable () async -> ()) async {} -func asyncInheritActorContextAcceptsAsyncClosure(@_inheritActorContext _ x: () async -> ()) async {} func asyncInheritActorContextAcceptsSendingAsyncClosure(@_inheritActorContext _ x: sending () async -> ()) async {} func asyncInheritActorContextAcceptsSendableAsyncClosure(@_inheritActorContext _ x: @Sendable () async -> ()) async {} @@ -101,8 +75,6 @@ func asyncNormalGlobalActorAcceptsSendingAsyncClosure(_ x: sending () async -> ( @MainActor func asyncNormalGlobalActorAcceptsSendableAsyncClosure(_ x: @Sendable () async -> ()) async {} -@MainActor -func asyncInheritActorContextGlobalActorAcceptsAsyncClosure(@_inheritActorContext _ x: () async -> ()) async {} @MainActor func asyncInheritActorContextGlobalActorAcceptsSendingAsyncClosure(@_inheritActorContext _ x: sending () async -> ()) async {} @MainActor @@ -138,26 +110,6 @@ func test_CallerSyncNormal_CalleeSyncNonIsolated() async { normalAcceptsSendableClosure { } } -@CustomActor -func test_CallerSyncInheritsActorContext_CalleeSyncNonisolated() { - // CHECK: } // end sil function '$s54transfernonsendable_closureliterals_isolationinference042test_CallerSyncInheritsActorContext_CalleeF11NonisolatedyyF' - - // CHECK-LABEL: // closure #1 in test_CallerSyncInheritsActorContext_CalleeSyncNonisolated() - // CHECK-NEXT: // Isolation: global_actor. type: CustomActor - inheritActorContextAcceptsClosure { } - - // This is a synchronous closure, so we error here. - // - // CHECK-LABEL: // closure #2 in test_CallerSyncInheritsActorContext_CalleeSyncNonisolated() - // CHECK-NEXT: // Isolation: global_actor. type: CustomActor - inheritActorContextAcceptsSendingClosure { } // expected-error {{sending value of non-Sendable type '() -> ()' risks causing data races}} - // expected-note @-1 {{Passing global actor 'CustomActor'-isolated value of non-Sendable type '() -> ()' as a 'sending' parameter to global function 'inheritActorContextAcceptsSendingClosure' risks causing races inbetween global actor 'CustomActor'-isolated uses and uses reachable from 'inheritActorContextAcceptsSendingClosure'}} - - // CHECK-LABEL: // closure #3 in test_CallerSyncInheritsActorContext_CalleeSyncNonisolated() - // CHECK-NEXT: // Isolation: global_actor. type: CustomActor - inheritActorContextAcceptsSendableClosure { } -} - @CustomActor func test_CallerSyncNormal_CalleeSyncMainActorIsolated() async { // CHECK-LABEL: } // end sil function '$s54transfernonsendable_closureliterals_isolationinference028test_CallerSyncNormal_CalleeF17MainActorIsolatedyyYaF' @@ -176,27 +128,6 @@ func test_CallerSyncNormal_CalleeSyncMainActorIsolated() async { await normalGlobalActorAcceptsSendableClosure { } } -@CustomActor -func test_CallerSyncInheritsActorContext_CalleeSyncMainActorIsolated() async { - // CHECK-LABEL: } // end sil function '$s54transfernonsendable_closureliterals_isolationinference042test_CallerSyncInheritsActorContext_Calleef4MainH8IsolatedyyYaF' - - // CHECK-LABEL: // closure #1 in test_CallerSyncInheritsActorContext_CalleeSyncMainActorIsolated() - // CHECK-NEXT: // Isolation: global_actor. type: CustomActor - await inheritActorContextGlobalActorAcceptsClosure { } // expected-error {{sending value of non-Sendable type '() -> ()' risks causing data races}} - // expected-note @-1 {{sending global actor 'CustomActor'-isolated value of non-Sendable type '() -> ()' to main actor-isolated global function 'inheritActorContextGlobalActorAcceptsClosure' risks causing races in between global actor 'CustomActor'-isolated and main actor-isolated uses}} - - // This is a synchronous closure, so we error here. - // - // CHECK-LABEL: // closure #2 in test_CallerSyncInheritsActorContext_CalleeSyncMainActorIsolated() - // CHECK-NEXT: // Isolation: global_actor. type: CustomActor - await inheritActorContextGlobalActorAcceptsSendingClosure { } // expected-error {{sending value of non-Sendable type '() -> ()' risks causing data races}} - // expected-note @-1 {{Passing global actor 'CustomActor'-isolated value of non-Sendable type '() -> ()' as a 'sending' parameter to global function 'inheritActorContextGlobalActorAcceptsSendingClosure' risks causing races inbetween global actor 'CustomActor'-isolated uses and uses reachable from 'inheritActorContextGlobalActorAcceptsSendingClosure'}} - - // CHECK-LABEL: // closure #3 in test_CallerSyncInheritsActorContext_CalleeSyncMainActorIsolated() - // CHECK-NEXT: // Isolation: global_actor. type: CustomActor - await inheritActorContextGlobalActorAcceptsSendableClosure { } -} - //////////////////////////////////////////////// // MARK: Global Actor Sync User Async Closure // //////////////////////////////////////////////// @@ -223,13 +154,9 @@ func test_CallerSyncInheritsActorContext_CalleeAsyncNonisolated() { // CHECK-LABEL: // closure #1 in test_CallerSyncInheritsActorContext_CalleeAsyncNonisolated() // CHECK-NEXT: // Isolation: global_actor. type: CustomActor - inheritActorContextAcceptsAsyncClosure { } - - // CHECK-LABEL: // closure #2 in test_CallerSyncInheritsActorContext_CalleeAsyncNonisolated() - // CHECK-NEXT: // Isolation: global_actor. type: CustomActor inheritActorContextAcceptsSendingAsyncClosure { } - // CHECK-LABEL: // closure #3 in test_CallerSyncInheritsActorContext_CalleeAsyncNonisolated() + // CHECK-LABEL: // closure #2 in test_CallerSyncInheritsActorContext_CalleeAsyncNonisolated() // CHECK-NEXT: // Isolation: global_actor. type: CustomActor inheritActorContextAcceptsSendableAsyncClosure { } } @@ -258,13 +185,9 @@ func test_CallerSyncInheritsActorContext_CalleeAsyncMainActorIsolated() async { // CHECK-LABEL: // closure #1 in test_CallerSyncInheritsActorContext_CalleeAsyncMainActorIsolated() // CHECK-NEXT: // Isolation: global_actor. type: CustomActor - await inheritActorContextGlobalActorAcceptsAsyncClosure { } - - // CHECK-LABEL: // closure #2 in test_CallerSyncInheritsActorContext_CalleeAsyncMainActorIsolated() - // CHECK-NEXT: // Isolation: global_actor. type: CustomActor await inheritActorContextGlobalActorAcceptsSendingAsyncClosure { } - // CHECK-LABEL: // closure #3 in test_CallerSyncInheritsActorContext_CalleeAsyncMainActorIsolated() + // CHECK-LABEL: // closure #2 in test_CallerSyncInheritsActorContext_CalleeAsyncMainActorIsolated() // CHECK-NEXT: // Isolation: global_actor. type: CustomActor await inheritActorContextGlobalActorAcceptsSendableAsyncClosure { } } @@ -293,27 +216,6 @@ func test_CallerAsyncNormal_CalleeSyncNonIsolated() async { await asyncNormalAcceptsSendableClosure { } } -@CustomActor -func test_CallerAsyncInheritsActorContext_CalleeSyncNonisolated() async { - // CHECK: } // end sil function '$s54transfernonsendable_closureliterals_isolationinference58test_CallerAsyncInheritsActorContext_CalleeSyncNonisolatedyyYaF' - - // CHECK-LABEL: // closure #1 in test_CallerAsyncInheritsActorContext_CalleeSyncNonisolated() - // CHECK-NEXT: // Isolation: global_actor. type: CustomActor - await asyncInheritActorContextAcceptsClosure { } // expected-error {{sending value of non-Sendable type '() -> ()' risks causing data races}} - // expected-note @-1 {{sending global actor 'CustomActor'-isolated value of non-Sendable type '() -> ()' to nonisolated global function 'asyncInheritActorContextAcceptsClosure' risks causing races in between global actor 'CustomActor'-isolated and nonisolated uses}} - - // This is a synchronous closure, so we error here. - // - // CHECK-LABEL: // closure #2 in test_CallerAsyncInheritsActorContext_CalleeSyncNonisolated() - // CHECK-NEXT: // Isolation: global_actor. type: CustomActor - await asyncInheritActorContextAcceptsSendingClosure { } // expected-error {{sending value of non-Sendable type '() -> ()' risks causing data races}} - // expected-note @-1 {{Passing global actor 'CustomActor'-isolated value of non-Sendable type '() -> ()' as a 'sending' parameter to global function 'asyncInheritActorContextAcceptsSendingClosure' risks causing races inbetween global actor 'CustomActor'-isolated uses and uses reachable from 'asyncInheritActorContextAcceptsSendingClosure'}} - - // CHECK-LABEL: // closure #3 in test_CallerAsyncInheritsActorContext_CalleeSyncNonisolated() - // CHECK-NEXT: // Isolation: global_actor. type: CustomActor - await asyncInheritActorContextAcceptsSendableClosure { } -} - @CustomActor func test_CallerAsyncNormal_CalleeSyncMainActorIsolated() async { // CHECK-LABEL: } // end sil function '$s54transfernonsendable_closureliterals_isolationinference50test_CallerAsyncNormal_CalleeSyncMainActorIsolatedyyYaF' @@ -332,27 +234,6 @@ func test_CallerAsyncNormal_CalleeSyncMainActorIsolated() async { await asyncNormalGlobalActorAcceptsSendableClosure { } } -@CustomActor -func test_CallerAsyncInheritsActorContext_CalleeSyncMainActorIsolated() async { - // CHECK-LABEL: } // end sil function '$s54transfernonsendable_closureliterals_isolationinference051test_CallerAsyncInheritsActorContext_CalleeSyncMainH8IsolatedyyYaF' - - // CHECK-LABEL: // closure #1 in test_CallerAsyncInheritsActorContext_CalleeSyncMainActorIsolated() - // CHECK-NEXT: // Isolation: global_actor. type: CustomActor - await asyncInheritActorContextGlobalActorAcceptsClosure { } // expected-error {{sending value of non-Sendable type '() -> ()' risks causing data races}} - // expected-note @-1 {{sending global actor 'CustomActor'-isolated value of non-Sendable type '() -> ()' to main actor-isolated global function 'asyncInheritActorContextGlobalActorAcceptsClosure' risks causing races in between global actor 'CustomActor'-isolated and main actor-isolated uses}} - - // This is a synchronous closure, so we error here. - // - // CHECK-LABEL: // closure #2 in test_CallerAsyncInheritsActorContext_CalleeSyncMainActorIsolated() - // CHECK-NEXT: // Isolation: global_actor. type: CustomActor - await asyncInheritActorContextGlobalActorAcceptsSendingClosure { } // expected-error {{sending value of non-Sendable type '() -> ()' risks causing data races}} - // expected-note @-1 {{Passing global actor 'CustomActor'-isolated value of non-Sendable type '() -> ()' as a 'sending' parameter to global function 'asyncInheritActorContextGlobalActorAcceptsSendingClosure' risks causing races inbetween global actor 'CustomActor'-isolated uses and uses reachable from 'asyncInheritActorContextGlobalActorAcceptsSendingClosure'}} - - // CHECK-LABEL: // closure #3 in test_CallerAsyncInheritsActorContext_CalleeSyncMainActorIsolated() - // CHECK-NEXT: // Isolation: global_actor. type: CustomActor - await asyncInheritActorContextGlobalActorAcceptsSendableClosure { } -} - ///////////////////////////////////////////////// // MARK: Global Actor Async User Async Closure // ///////////////////////////////////////////////// @@ -381,21 +262,17 @@ func test_CallerAsyncInheritsActorContext_CalleeAsyncNonisolated() async { // CHECK-LABEL: // closure #1 in test_CallerAsyncInheritsActorContext_CalleeAsyncNonisolated() // CHECK-NEXT: // Isolation: global_actor. type: CustomActor - await asyncInheritActorContextAcceptsAsyncClosure { } - - // CHECK-LABEL: // closure #2 in test_CallerAsyncInheritsActorContext_CalleeAsyncNonisolated() - // CHECK-NEXT: // Isolation: global_actor. type: CustomActor await asyncInheritActorContextAcceptsSendingAsyncClosure { } - // CHECK-LABEL: // closure #3 in test_CallerAsyncInheritsActorContext_CalleeAsyncNonisolated() + // CHECK-LABEL: // closure #2 in test_CallerAsyncInheritsActorContext_CalleeAsyncNonisolated() // CHECK-NEXT: // Isolation: global_actor. type: CustomActor await asyncInheritActorContextAcceptsSendingAsyncClosure { @CustomActor in } - // CHECK-LABEL: // closure #4 in test_CallerAsyncInheritsActorContext_CalleeAsyncNonisolated() + // CHECK-LABEL: // closure #3 in test_CallerAsyncInheritsActorContext_CalleeAsyncNonisolated() // CHECK-NEXT: // Isolation: global_actor. type: MainActor await asyncInheritActorContextAcceptsSendingAsyncClosure { @MainActor in } - // CHECK-LABEL: // closure #5 in test_CallerAsyncInheritsActorContext_CalleeAsyncNonisolated() + // CHECK-LABEL: // closure #4 in test_CallerAsyncInheritsActorContext_CalleeAsyncNonisolated() // CHECK-NEXT: // Isolation: global_actor. type: CustomActor await asyncInheritActorContextAcceptsSendableAsyncClosure { } } @@ -424,21 +301,17 @@ func test_CallerAsyncInheritsActorContext_CalleeAsyncMainActorIsolated() async { // CHECK-LABEL: // closure #1 in test_CallerAsyncInheritsActorContext_CalleeAsyncMainActorIsolated() // CHECK-NEXT: // Isolation: global_actor. type: CustomActor - await asyncInheritActorContextGlobalActorAcceptsAsyncClosure { } - - // CHECK-LABEL: // closure #2 in test_CallerAsyncInheritsActorContext_CalleeAsyncMainActorIsolated() - // CHECK-NEXT: // Isolation: global_actor. type: CustomActor await asyncInheritActorContextGlobalActorAcceptsSendingAsyncClosure { } - // CHECK-LABEL: // closure #3 in test_CallerAsyncInheritsActorContext_CalleeAsyncMainActorIsolated() + // CHECK-LABEL: // closure #2 in test_CallerAsyncInheritsActorContext_CalleeAsyncMainActorIsolated() // CHECK-NEXT: // Isolation: global_actor. type: CustomActor await asyncInheritActorContextGlobalActorAcceptsSendingAsyncClosure { @CustomActor in } - // CHECK-LABEL: // closure #4 in test_CallerAsyncInheritsActorContext_CalleeAsyncMainActorIsolated() + // CHECK-LABEL: // closure #3 in test_CallerAsyncInheritsActorContext_CalleeAsyncMainActorIsolated() // CHECK-NEXT: // Isolation: global_actor. type: MainActor await asyncInheritActorContextGlobalActorAcceptsSendingAsyncClosure { @MainActor in } - // CHECK-LABEL: // closure #5 in test_CallerAsyncInheritsActorContext_CalleeAsyncMainActorIsolated() + // CHECK-LABEL: // closure #4 in test_CallerAsyncInheritsActorContext_CalleeAsyncMainActorIsolated() // CHECK-NEXT: // Isolation: global_actor. type: CustomActor await asyncInheritActorContextGlobalActorAcceptsSendableAsyncClosure { } } @@ -464,26 +337,6 @@ extension MyActor { normalAcceptsSendableClosure { print(self) } } - func test_CallerSyncInheritsActorContext_CalleeSyncNonisolated() { - // CHECK: } // end sil function '$s54transfernonsendable_closureliterals_isolationinference7MyActorC023test_CallerSyncInheritse14Context_CalleeH11NonisolatedyyF' - - // CHECK-LABEL: // closure #1 in MyActor.test_CallerSyncInheritsActorContext_CalleeSyncNonisolated() - // CHECK-NEXT: // Isolation: actor_instance. name: 'self' - inheritActorContextAcceptsClosure { print(self) } - - // This is a synchronous closure, so we error here. - // - // CHECK-LABEL: // closure #2 in MyActor.test_CallerSyncInheritsActorContext_CalleeSyncNonisolated() - // CHECK-NEXT: // Isolation: actor_instance. name: 'self' - inheritActorContextAcceptsSendingClosure { // expected-error {{passing closure as a 'sending' parameter risks causing data races between 'self'-isolated code and concurrent execution of the closure}} - print(self) // expected-note {{closure captures 'self'}} - } - - // CHECK-LABEL: // closure #3 in MyActor.test_CallerSyncInheritsActorContext_CalleeSyncNonisolated() - // CHECK-NEXT: // Isolation: actor_instance. name: 'self' - inheritActorContextAcceptsSendableClosure { print(self) } - } - func test_CallerSyncNormal_CalleeSyncMainActorIsolated() async { // CHECK-LABEL: } // end sil function '$s54transfernonsendable_closureliterals_isolationinference7MyActorC028test_CallerSyncNormal_Calleeh4MainE8IsolatedyyYaF' @@ -500,27 +353,6 @@ extension MyActor { // CHECK-NEXT: // Isolation: nonisolated await normalGlobalActorAcceptsSendableClosure { print(self) } } - - func test_CallerSyncInheritsActorContext_CalleeSyncMainActorIsolated() async { - // CHECK-LABEL: } // end sil function '$s54transfernonsendable_closureliterals_isolationinference7MyActorC023test_CallerSyncInheritse14Context_Calleeh4MainE8IsolatedyyYaF' - - // CHECK-LABEL: // closure #1 in MyActor.test_CallerSyncInheritsActorContext_CalleeSyncMainActorIsolated() - // CHECK-NEXT: // Isolation: actor_instance. name: 'self' - await inheritActorContextGlobalActorAcceptsClosure { print(self) } // expected-error {{sending value of non-Sendable type '() -> ()' risks causing data races}} - // expected-note @-1 {{sending 'self'-isolated value of non-Sendable type '() -> ()' to main actor-isolated global function 'inheritActorContextGlobalActorAcceptsClosure' risks causing races in between 'self'-isolated and main actor-isolated uses}} - - // This is a synchronous closure, so we error here. - // - // CHECK-LABEL: // closure #2 in MyActor.test_CallerSyncInheritsActorContext_CalleeSyncMainActorIsolated() - // CHECK-NEXT: // Isolation: actor_instance. name: 'self' - await inheritActorContextGlobalActorAcceptsSendingClosure { // expected-error {{passing closure as a 'sending' parameter risks causing data races between 'self'-isolated code and concurrent execution of the closure}} - print(self) // expected-note {{closure captures 'self'}} - } - - // CHECK-LABEL: // closure #3 in MyActor.test_CallerSyncInheritsActorContext_CalleeSyncMainActorIsolated() - // CHECK-NEXT: // Isolation: actor_instance. name: 'self' - await inheritActorContextGlobalActorAcceptsSendableClosure { print(self) } - } } ////////////////////////////////////////////////// @@ -550,13 +382,9 @@ extension MyActor { // CHECK-LABEL: // closure #1 in MyActor.test_CallerSyncInheritsActorContext_CalleeAsyncNonisolated() // CHECK-NEXT: // Isolation: actor_instance. name: 'self' - inheritActorContextAcceptsAsyncClosure { print(self) } - - // CHECK-LABEL: // closure #2 in MyActor.test_CallerSyncInheritsActorContext_CalleeAsyncNonisolated() - // CHECK-NEXT: // Isolation: actor_instance. name: 'self' inheritActorContextAcceptsSendingAsyncClosure { print(self) } - // CHECK-LABEL: // closure #3 in MyActor.test_CallerSyncInheritsActorContext_CalleeAsyncNonisolated() + // CHECK-LABEL: // closure #2 in MyActor.test_CallerSyncInheritsActorContext_CalleeAsyncNonisolated() // CHECK-NEXT: // Isolation: actor_instance. name: 'self' inheritActorContextAcceptsSendableAsyncClosure { print(self) } } @@ -583,13 +411,9 @@ extension MyActor { // CHECK-LABEL: // closure #1 in MyActor.test_CallerSyncInheritsActorContext_CalleeAsyncMainActorIsolated() // CHECK-NEXT: // Isolation: actor_instance. name: 'self' - await inheritActorContextGlobalActorAcceptsAsyncClosure { print(self) } - - // CHECK-LABEL: // closure #2 in MyActor.test_CallerSyncInheritsActorContext_CalleeAsyncMainActorIsolated() - // CHECK-NEXT: // Isolation: actor_instance. name: 'self' await inheritActorContextGlobalActorAcceptsSendingAsyncClosure { print(self) } - // CHECK-LABEL: // closure #3 in MyActor.test_CallerSyncInheritsActorContext_CalleeAsyncMainActorIsolated() + // CHECK-LABEL: // closure #2 in MyActor.test_CallerSyncInheritsActorContext_CalleeAsyncMainActorIsolated() // CHECK-NEXT: // Isolation: actor_instance. name: 'self' await inheritActorContextGlobalActorAcceptsSendableAsyncClosure { print(self) } } @@ -620,27 +444,6 @@ extension MyActor { await asyncNormalAcceptsSendableClosure { print(self) } } - func test_CallerAsyncInheritsActorContext_CalleeSyncNonisolated() async { - // CHECK: } // end sil function '$s54transfernonsendable_closureliterals_isolationinference7MyActorC024test_CallerAsyncInheritsE29Context_CalleeSyncNonisolatedyyYaF' - - // CHECK-LABEL: // closure #1 in MyActor.test_CallerAsyncInheritsActorContext_CalleeSyncNonisolated() - // CHECK-NEXT: // Isolation: actor_instance. name: 'self' - await asyncInheritActorContextAcceptsClosure { print(self) } // expected-error {{sending value of non-Sendable type '() -> ()' risks causing data races}} - // expected-note @-1 {{sending 'self'-isolated value of non-Sendable type '() -> ()' to nonisolated global function 'asyncInheritActorContextAcceptsClosure' risks causing races in between 'self'-isolated and nonisolated uses}} - - // This is a synchronous closure, so we error here. - // - // CHECK-LABEL: // closure #2 in MyActor.test_CallerAsyncInheritsActorContext_CalleeSyncNonisolated() - // CHECK-NEXT: // Isolation: actor_instance. name: 'self' - await asyncInheritActorContextAcceptsSendingClosure { // expected-error {{passing closure as a 'sending' parameter risks causing data races between 'self'-isolated code and concurrent execution of the closure}} - print(self) // expected-note {{closure captures 'self'}} - } - - // CHECK-LABEL: // closure #3 in MyActor.test_CallerAsyncInheritsActorContext_CalleeSyncNonisolated() - // CHECK-NEXT: // Isolation: actor_instance. name: 'self' - await asyncInheritActorContextAcceptsSendableClosure { print(self) } - } - func test_CallerAsyncNormal_CalleeSyncMainActorIsolated() async { // CHECK-LABEL: } // end sil function '$s54transfernonsendable_closureliterals_isolationinference7MyActorC037test_CallerAsyncNormal_CalleeSyncMainE8IsolatedyyYaF' @@ -657,27 +460,6 @@ extension MyActor { // CHECK-NEXT: // Isolation: nonisolated await asyncNormalGlobalActorAcceptsSendableClosure { print(self) } } - - func test_CallerAsyncInheritsActorContext_CalleeSyncMainActorIsolated() async { - // CHECK-LABEL: } // end sil function '$s54transfernonsendable_closureliterals_isolationinference7MyActorC024test_CallerAsyncInheritse22Context_CalleeSyncMainE8IsolatedyyYaF' - - // CHECK-LABEL: // closure #1 in MyActor.test_CallerAsyncInheritsActorContext_CalleeSyncMainActorIsolated() - // CHECK-NEXT: // Isolation: actor_instance. name: 'self' - await asyncInheritActorContextGlobalActorAcceptsClosure { print(self) } // expected-error {{sending value of non-Sendable type '() -> ()' risks causing data races}} - // expected-note @-1 {{sending 'self'-isolated value of non-Sendable type '() -> ()' to main actor-isolated global function 'asyncInheritActorContextGlobalActorAcceptsClosure' risks causing races in between 'self'-isolated and main actor-isolated uses}} - - // This is a synchronous function, so we error. - // - // CHECK-LABEL: // closure #2 in MyActor.test_CallerAsyncInheritsActorContext_CalleeSyncMainActorIsolated() - // CHECK-NEXT: // Isolation: actor_instance. name: 'self' - await asyncInheritActorContextGlobalActorAcceptsSendingClosure { // expected-error {{passing closure as a 'sending' parameter risks causing data races between 'self'-isolated code and concurrent execution of the closure}} - print(self) // expected-note {{closure captures 'self'}} - } - - // CHECK-LABEL: // closure #3 in MyActor.test_CallerAsyncInheritsActorContext_CalleeSyncMainActorIsolated() - // CHECK-NEXT: // Isolation: actor_instance. name: 'self' - await asyncInheritActorContextGlobalActorAcceptsSendableClosure { print(self) } - } } /////////////////////////////////////////////////// @@ -708,21 +490,17 @@ extension MyActor { // CHECK-LABEL: // closure #1 in MyActor.test_CallerAsyncInheritsActorContext_CalleeAsyncNonisolated() // CHECK-NEXT: // Isolation: actor_instance. name: 'self' - await asyncInheritActorContextAcceptsAsyncClosure { print(self) } - - // CHECK-LABEL: // closure #2 in MyActor.test_CallerAsyncInheritsActorContext_CalleeAsyncNonisolated() - // CHECK-NEXT: // Isolation: actor_instance. name: 'self' await asyncInheritActorContextAcceptsSendingAsyncClosure { print(self) } - // CHECK-LABEL: // closure #3 in MyActor.test_CallerAsyncInheritsActorContext_CalleeAsyncNonisolated() + // CHECK-LABEL: // closure #2 in MyActor.test_CallerAsyncInheritsActorContext_CalleeAsyncNonisolated() // CHECK-NEXT: // Isolation: global_actor. type: CustomActor await asyncInheritActorContextAcceptsSendingAsyncClosure { @CustomActor in print(self) } - // CHECK-LABEL: // closure #4 in MyActor.test_CallerAsyncInheritsActorContext_CalleeAsyncNonisolated() + // CHECK-LABEL: // closure #3 in MyActor.test_CallerAsyncInheritsActorContext_CalleeAsyncNonisolated() // CHECK-NEXT: // Isolation: global_actor. type: MainActor await asyncInheritActorContextAcceptsSendingAsyncClosure { @MainActor in print(self) } - // CHECK-LABEL: // closure #5 in MyActor.test_CallerAsyncInheritsActorContext_CalleeAsyncNonisolated() + // CHECK-LABEL: // closure #4 in MyActor.test_CallerAsyncInheritsActorContext_CalleeAsyncNonisolated() // CHECK-NEXT: // Isolation: actor_instance. name: 'self' await asyncInheritActorContextAcceptsSendableAsyncClosure { print(self) } } @@ -749,21 +527,17 @@ extension MyActor { // CHECK-LABEL: // closure #1 in MyActor.test_CallerAsyncInheritsActorContext_CalleeAsyncMainActorIsolated() // CHECK-NEXT: // Isolation: actor_instance. name: 'self' - await asyncInheritActorContextGlobalActorAcceptsAsyncClosure { print(self) } - - // CHECK-LABEL: // closure #2 in MyActor.test_CallerAsyncInheritsActorContext_CalleeAsyncMainActorIsolated() - // CHECK-NEXT: // Isolation: actor_instance. name: 'self' await asyncInheritActorContextGlobalActorAcceptsSendingAsyncClosure { print(self) } - // CHECK-LABEL: // closure #3 in MyActor.test_CallerAsyncInheritsActorContext_CalleeAsyncMainActorIsolated() + // CHECK-LABEL: // closure #2 in MyActor.test_CallerAsyncInheritsActorContext_CalleeAsyncMainActorIsolated() // CHECK-NEXT: // Isolation: global_actor. type: CustomActor await asyncInheritActorContextGlobalActorAcceptsSendingAsyncClosure { @CustomActor in print(self) } - // CHECK-LABEL: // closure #4 in MyActor.test_CallerAsyncInheritsActorContext_CalleeAsyncMainActorIsolated() + // CHECK-LABEL: // closure #3 in MyActor.test_CallerAsyncInheritsActorContext_CalleeAsyncMainActorIsolated() // CHECK-NEXT: // Isolation: global_actor. type: MainActor await asyncInheritActorContextGlobalActorAcceptsSendingAsyncClosure { @MainActor in print(self) } - // CHECK-LABEL: // closure #5 in MyActor.test_CallerAsyncInheritsActorContext_CalleeAsyncMainActorIsolated() + // CHECK-LABEL: // closure #4 in MyActor.test_CallerAsyncInheritsActorContext_CalleeAsyncMainActorIsolated() // CHECK-NEXT: // Isolation: actor_instance. name: 'self' await asyncInheritActorContextGlobalActorAcceptsSendableAsyncClosure { print(self) } } diff --git a/test/Concurrency/where_clause_main_resolution.swift b/test/Concurrency/where_clause_main_resolution.swift index 4caeb9c724e64..3c81370b7e3f0 100644 --- a/test/Concurrency/where_clause_main_resolution.swift +++ b/test/Concurrency/where_clause_main_resolution.swift @@ -25,19 +25,19 @@ protocol App { // CHECK-SAME: interface_type=" (Self.Type) -> () async -> ()" extension App where Configuration == Config1 { -// CHECK-CONFIG1: (func_decl {{.*}}implicit "$main()" interface_type="(MainType.Type) -> () -> ()" +// CHECK-CONFIG1: (func_decl {{.*}}implicit range=[{{.*}}:[[@LINE+20]]:1 - line:[[@LINE+20]]:1] "$main()" interface_type="(MainType.Type) -> () -> ()" // CHECK-CONFIG1: [[SOURCE_FILE]]:[[# @LINE+1 ]] static func main() { } } extension App where Configuration == Config2 { -// CHECK-CONFIG2: (func_decl {{.*}}implicit "$main()" interface_type="(MainType.Type) -> () async -> ()" +// CHECK-CONFIG2: (func_decl {{.*}}implicit range=[{{.*}}:[[@LINE+14]]:1 - line:[[@LINE+14]]:1] "$main()" interface_type="(MainType.Type) -> () async -> ()" // CHECK-CONFIG2: [[SOURCE_FILE]]:[[# @LINE+1 ]] static func main() async { } } extension App where Configuration == Config3 { -// CHECK-CONFIG3-ASYNC: (func_decl {{.*}}implicit "$main()" interface_type="(MainType.Type) -> () async -> ()" +// CHECK-CONFIG3-ASYNC: (func_decl {{.*}}implicit range=[{{.*}}:[[@LINE+8]]:1 - line:[[@LINE+8]]:1] "$main()" interface_type="(MainType.Type) -> () async -> ()" // CHECK-CONFIG3-ASYNC: [[SOURCE_FILE]]:[[DEFAULT_ASYNCHRONOUS_MAIN_LINE]] } diff --git a/test/Constraints/opened_existentials.swift b/test/Constraints/opened_existentials.swift index a8519e23d4df8..ebbcae1227f10 100644 --- a/test/Constraints/opened_existentials.swift +++ b/test/Constraints/opened_existentials.swift @@ -565,3 +565,29 @@ do { types.assertTypesAreEqual() } } + +struct G: PP3 {} + +protocol PP1 { + associatedtype A +} + +extension PP1 { + func f(p: any PP2>) { + p.g(t: self) + } +} + +protocol PP2 { + associatedtype A + associatedtype B: PP3 where Self.B.A == Self.A +} + +extension PP2 { + func g(t: T) where Self.B == G {} +} + +protocol PP3 { + associatedtype A +} + diff --git a/test/Frontend/default-search-paths.swift b/test/Frontend/default-search-paths.swift new file mode 100644 index 0000000000000..a6fb64c2bb450 --- /dev/null +++ b/test/Frontend/default-search-paths.swift @@ -0,0 +1,43 @@ +// UNSUPPORTED: OS=windows-msvc + +// Standard Apple paths. +// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource) -target arm64-apple-macos15.4 -parse %s -Rmodule-loading 2>&1 | %FileCheck -check-prefix=APPLE %s +// APPLE: Implicit framework search paths: +// APPLE-NEXT: [0] SOURCE_DIR/test/Inputs/clang-importer-sdk/System/Library/Frameworks +// APPLE-NEXT: [1] SOURCE_DIR/test/Inputs/clang-importer-sdk/System/Library/SubFrameworks +// APPLE-NEXT: [2] SOURCE_DIR/test/Inputs/clang-importer-sdk/Library/Frameworks +// APPLE-NEXT: Runtime library import search paths: +// APPLE-NEXT: [0] BUILD_DIR/lib/swift/macosx +// APPLE-NEXT: [1] SOURCE_DIR/test/Inputs/clang-importer-sdk/usr/lib/swift +// APPLE-NEXT: (End of search path lists.) + +// Non-Apple platforms don't have any implicit framework search paths. +// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource) -target x86_64-unknown-linux-android -parse %s -Rmodule-loading 2>&1 | %FileCheck -check-prefix=ANDROID %s +// ANDROID: Implicit framework search paths: +// ANDROID-NEXT: Runtime library import search paths: +// ANDROID-NEXT: [0] BUILD_DIR/lib/swift/android +// ANDROID-NEXT: [1] BUILD_DIR/lib/swift/android/x86_64 +// ANDROID-NEXT: [2] SOURCE_DIR/test/Inputs/clang-importer-sdk/usr/lib/swift/android +// ANDROID-NEXT: [3] SOURCE_DIR/test/Inputs/clang-importer-sdk/usr/lib/swift/android/x86_64 +// ANDROID-NEXT: (End of search path lists.) + +// -nostdimport doesn't set up any standard import paths at all. +// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource) -target arm64-apple-macos15.4 -nostdimport -parse %s -Rmodule-loading 2>&1 | %FileCheck -check-prefix=NOSTDIMPORT %s +// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource) -target x86_64-unknown-linux-android -nostdimport -parse %s -Rmodule-loading 2>&1 | %FileCheck -check-prefix=NOSTDIMPORT %s +// NOSTDIMPORT: Implicit framework search paths: +// NOSTDIMPORT-NEXT: Runtime library import search paths: +// NOSTDIMPORT-NEXT: (End of search path lists.) + +// -nostdlibimport removes all of the standard imports from the SDK but leaves the toolchain ones. +// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource) -target arm64-apple-macos15.4 -nostdlibimport -parse %s -Rmodule-loading 2>&1 | %FileCheck -check-prefix=APPLE-NOSTDLIBIMPORT %s +// APPLE-NOSTDLIBIMPORT: Implicit framework search paths: +// APPLE-NOSTDLIBIMPORT-NEXT: Runtime library import search paths: +// APPLE-NOSTDLIBIMPORT-NEXT: [0] BUILD_DIR/lib/swift/macosx +// APPLE-NOSTDLIBIMPORT-NEXT: (End of search path lists.) + +// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource) -target x86_64-unknown-linux-android -nostdlibimport -parse %s -Rmodule-loading 2>&1 | %FileCheck -check-prefix=ANDROID-NOSTDLIBIMPORT %s +// ANDROID-NOSTDLIBIMPORT: Implicit framework search paths: +// ANDROID-NOSTDLIBIMPORT-NEXT: Runtime library import search paths: +// ANDROID-NOSTDLIBIMPORT-NEXT: [0] BUILD_DIR/lib/swift/android +// ANDROID-NOSTDLIBIMPORT-NEXT: [1] BUILD_DIR/lib/swift/android/x86_64 +// ANDROID-NOSTDLIBIMPORT-NEXT: (End of search path lists.) diff --git a/test/Generics/inverse_generics.swift b/test/Generics/inverse_generics.swift index 3930eda3a3c1e..aaa6e36511014 100644 --- a/test/Generics/inverse_generics.swift +++ b/test/Generics/inverse_generics.swift @@ -365,9 +365,9 @@ func conflict13(_ t: T) {} // expected-warning@+1 {{same-type requirement makes generic parameters 'U' and 'T' equivalent}} -func conflict14(_ t: T, _ u: U) - where T: ~Copyable, // expected-error {{'T' required to be 'Copyable' but is marked with '~Copyable'}} - U: ~Escapable, // expected-error {{'U' required to be 'Escapable' but is marked with '~Escapable'}} +func conflict14(_ t: borrowing T, _ u: borrowing U) + where T: ~Copyable, + U: ~Escapable, T == U {} protocol Conflict15 { diff --git a/test/IRGen/CoroutineAccessorsDebugLoc.swift b/test/IRGen/CoroutineAccessorsDebugLoc.swift new file mode 100644 index 0000000000000..7cfeb50be1547 --- /dev/null +++ b/test/IRGen/CoroutineAccessorsDebugLoc.swift @@ -0,0 +1,19 @@ +// REQUIRES: swift_feature_CoroutineAccessors +// RUN: %target-swift-frontend %s -g -c -O -o - -emit-irgen -enable-experimental-feature CoroutineAccessors | %FileCheck %s + +// This test checks to made sure that the ReadAccessor s26CoroutineAccessorsDebugLoc1SV3irmSivr that has a call to @llvm.coro.id.retcon.once, also has a debug location set. + +// CHECK-LABEL: @"$s26CoroutineAccessorsDebugLoc1SV3irmSivr" +// CHECK: %{{.*}} = call token ({{.*}}) @llvm.coro.id.retcon.once({{.*}}), !dbg ![[DBGLOC:[0-9]+]] +// CHECK-NEXT: %{{.*}} = call ptr @llvm.coro.begin({{.*}}), !dbg ![[DBGLOC]] + +public struct S { +public var o: any AnyObject +public var _i: Int = 0 + +public var irm: Int { + _read { + yield _i + } +} // public var irm +} diff --git a/test/IRGen/pack_metadata_dealloc.swift b/test/IRGen/pack_metadata_dealloc.swift new file mode 100644 index 0000000000000..1bdb24a4d3369 --- /dev/null +++ b/test/IRGen/pack_metadata_dealloc.swift @@ -0,0 +1,30 @@ +// RUN: %target-swift-frontend -emit-ir %s -target %target-swift-5.9-abi-triple | %FileCheck %s + +protocol P { + associatedtype A + var a: A { get } +} + +func f(_ t: repeat each T) -> (repeat (each T).A) { + let data = (repeat (each t).a) + return data +} + +// CHECK-LABEL: define {{.*}} void @"$s21pack_metadata_dealloc1fy1AQzxQp_txxQpRvzAA1PRzlF" +// CHECK: [[SPSAVE:%.*]] = call ptr @llvm.stacksave.p0() +// CHECK: call void @llvm.stackrestore.p0(ptr [[SPSAVE]]) +// CHECK: [[SPSAVE1:%.*]] = call ptr @llvm.stacksave.p0() +// CHECK: [[SPSAVE2:%.*]] = call ptr @llvm.stacksave.p0() +// CHECK-NOT: call ptr llvm.stacksave.p0() +// CHECK: call void @llvm.stackrestore.p0(ptr [[SPSAVE2]]) +// CHECK: call void @llvm.stackrestore.p0(ptr [[SPSAVE1]]) +// CHECK: ret void + +struct G { + init(_: repeat each T) {} +} + +func f2(t: repeat each T, u: repeat each U) async -> (repeat G<(each T).A, repeat each U>) { + let x = (repeat G((each t).a, repeat each u)) + return x +} \ No newline at end of file diff --git a/test/Interpreter/Inputs/layout_string_witnesses_types.swift b/test/Interpreter/Inputs/layout_string_witnesses_types.swift index 65060bfb66c72..b1bb42bd254fe 100644 --- a/test/Interpreter/Inputs/layout_string_witnesses_types.swift +++ b/test/Interpreter/Inputs/layout_string_witnesses_types.swift @@ -673,6 +673,21 @@ public enum MultiPayloadAnyObject { case z(AnyObject) } +public struct NonCopyableGenericStruct: ~Copyable { + let x: Int + let y: T + + public init(x: Int, y: T) { + self.x = x + self.y = y + } +} + +public enum NonCopyableGenericEnum: ~Copyable { + case x(Int, T?) + case y(Int) +} + @inline(never) public func consume(_ x: T.Type) { withExtendedLifetime(x) {} @@ -751,6 +766,11 @@ public func testGenericArrayDestroy(_ buffer: UnsafeMutableBufferPointer) buffer.deinitialize() } +@inline(never) +public func testGenericArrayDestroy(_ buffer: UnsafeMutableBufferPointer) { + buffer.deinitialize() +} + @inline(never) public func testGenericArrayInitWithCopy(dest: UnsafeMutableBufferPointer, src: UnsafeMutableBufferPointer) { _ = dest.initialize(fromContentsOf: src) diff --git a/test/Interpreter/extended_existential.swift b/test/Interpreter/extended_existential.swift new file mode 100644 index 0000000000000..020977aaa9ed3 --- /dev/null +++ b/test/Interpreter/extended_existential.swift @@ -0,0 +1,49 @@ +// RUN: %empty-directory(%t) +// RUN: %target-build-swift -O -target %target-cpu-apple-macos15.0 %s -o %t/a.out +// RUN: %target-codesign %t/a.out +// RUN: %target-run %t/a.out | %FileCheck %s + +// REQUIRES: OS=macosx +// REQUIRES: executable_test + +protocol A: ~Copyable { + associatedtype B +} + +protocol B: ~Copyable {} + +let a: Any = (any ~Copyable).self +// CHECK: any Any +print(a) + +let b: Any = (any ~Escapable).self +// CHECK: any Any +print(b) + +let c: Any = (any ~Copyable & ~Escapable).self +// CHECK: any Any +print(c) + +let d: Any = (any A).self +// CHECK: A +print(d) + +let e: Any = (any B).self +// CHECK: B +print(e) + +let f: Any = (any A & B).self +// CHECK: A & B +print(f) + +let g: Any = (any A & ~Copyable).self +// CHECK: any A +print(g) + +let h: Any = (any B & ~Copyable).self +// CHECK: any B +print(h) + +let i: Any = (any A & B & ~Copyable).self +// CHECK: any A & B +print(i) diff --git a/test/Interpreter/layout_string_witnesses_dynamic.swift b/test/Interpreter/layout_string_witnesses_dynamic.swift index 418ebbabfc064..b91bf03a1a068 100644 --- a/test/Interpreter/layout_string_witnesses_dynamic.swift +++ b/test/Interpreter/layout_string_witnesses_dynamic.swift @@ -1239,6 +1239,42 @@ func testGenericResilientWithUnmanagedAndWeak() { testGenericResilientWithUnmanagedAndWeak() +func testNonCopyableGenericStructSimpleClass() { + let ptr = UnsafeMutableBufferPointer>.allocate(capacity: 1) + + let x = NonCopyableGenericStruct(x: 23, y: SimpleClass(x: 23)) + ptr[0] = x + + // CHECK-NEXT: Before deinit + print("Before deinit") + + + // CHECK-NEXT: SimpleClass deinitialized! + testGenericArrayDestroy(ptr) + + ptr.deallocate() +} + +testNonCopyableGenericStructSimpleClass() + +func testNonCopyableGenericEnumSimpleClass() { + let ptr = UnsafeMutableBufferPointer>.allocate(capacity: 1) + + let x = NonCopyableGenericEnum.x(23, SimpleClass(x: 23)) + ptr[0] = x + + // CHECK-NEXT: Before deinit + print("Before deinit") + + + // CHECK-NEXT: SimpleClass deinitialized! + testGenericArrayDestroy(ptr) + + ptr.deallocate() +} + +testNonCopyableGenericEnumSimpleClass() + #if os(macOS) import Foundation diff --git a/test/ModuleInterface/inheritActorContext_attr.swift b/test/ModuleInterface/inheritActorContext_attr.swift new file mode 100644 index 0000000000000..d36bc1b655457 --- /dev/null +++ b/test/ModuleInterface/inheritActorContext_attr.swift @@ -0,0 +1,43 @@ +// RUN: %empty-directory(%t) +// RUN: %target-swift-emit-module-interface(%t/Library.swiftinterface) %s -module-name Library +// RUN: %target-swift-typecheck-module-from-interface(%t/Library.swiftinterface) -module-name Library +// RUN: %FileCheck %s < %t/Library.swiftinterface + +// CHECK-NOT: #if compiler(>=5.3) && $AlwaysInheritActorContext +// CHECK: public func globalTest(@_inheritActorContext _: @Sendable () async -> Swift.Void) +// CHECK-NOT: #endif +public func globalTest(@_inheritActorContext _: @Sendable () async -> Void) {} + +// CHECK: #if compiler(>=5.3) && $AlwaysInheritActorContext +// CHECK-NEXT: public func globalTestAlways(@_inheritActorContext(always) _: @Sendable () async -> Swift.Void) +// CHECK-NEXT: #endif +public func globalTestAlways(@_inheritActorContext(always) _: @Sendable () async -> Void) {} + +public struct Test { + // CHECK-NOT: #if compiler(>=5.3) && $AlwaysInheritActorContext + // CHECK: public init(@_inheritActorContext x: @Sendable () async -> Swift.Int) + // CHECK-NOT: #endif + public init(@_inheritActorContext x: @Sendable () async -> Int) {} + + // CHECK: #if compiler(>=5.3) && $AlwaysInheritActorContext + // CHECK-NEXT: #if compiler(>=5.3) && $SendingArgsAndResults + // CHECK-NEXT: public init(@_inheritActorContext(always) y: sending () async -> Swift.Void) + // CHECK-NEXT: #else + // CHECK-NEXT: public init(@_inheritActorContext(always) y: () async -> Swift.Void) + // CHECK-NEXT: #endif + // CHECK-NEXT: #endif + public init(@_inheritActorContext(always) y: sending () async -> Void) {} + + // CHECK-NOT: #if compiler(>=5.3) && $AlwaysInheritActorContext + // CHECK: public subscript(@_inheritActorContext _: @Sendable () async -> Swift.Void) -> Swift.Bool { + // CHECK-NEXT: get + // CHECK-NEXT: } + // CHECK-NOT: #endif + public subscript(@_inheritActorContext _: @Sendable () async -> Void) -> Bool { false } + + // CHECK: #if compiler(>=5.3) && $AlwaysInheritActorContext + // CHECK-NEXT: public subscript(@_inheritActorContext(always) _: @Sendable (Swift.Int) async -> Swift.Void) -> Swift.Bool { + // CHECK-NEXT: get + // CHECK-NEXT: } + public subscript(@_inheritActorContext(always) _: @Sendable (Int) async -> Void) -> Bool { false } +} diff --git a/test/NameLookup/module_selector.swift b/test/NameLookup/module_selector.swift new file mode 100644 index 0000000000000..0efc97316ec2c --- /dev/null +++ b/test/NameLookup/module_selector.swift @@ -0,0 +1,3 @@ +// RUN: %target-typecheck-verify-swift -enable-experimental-feature ModuleSelector + +// REQUIRES: swift_feature_ModuleSelector diff --git a/test/Parse/recovery.swift b/test/Parse/recovery.swift index c44dcc08ed60c..5de4126dbe725 100644 --- a/test/Parse/recovery.swift +++ b/test/Parse/recovery.swift @@ -210,8 +210,10 @@ func missingControllingExprInForEach() { // The #if block is used to provide a scope for the for stmt to force it to end // where necessary to provoke the crash. #if true // compiler crashes on "for{{" - // expected-error @+2 {{expected pattern}} - // expected-error @+1 {{expected Sequence expression for for-each loop}} + // expected-error @+4 {{expected pattern}} + // expected-error @+3 {{expected Sequence expression for for-each loop}} + // expected-error @+2 {{closure expression is unused}} + // expected-note @+1 {{did you mean to use a 'do' statement?}} for{{ // expected-note 2 {{to match this opening '{'}} #endif // expected-error {{expected '}' at end of closure}} expected-error {{expected '}' at end of brace statement}} diff --git a/test/PrintAsObjC/cdecl-imports.swift b/test/PrintAsObjC/cdecl-imports.swift index 41540286ccc23..7b153be5e6883 100644 --- a/test/PrintAsObjC/cdecl-imports.swift +++ b/test/PrintAsObjC/cdecl-imports.swift @@ -2,6 +2,7 @@ // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) %s -parse-as-library -typecheck -verify -emit-objc-header-path %t/swift.h // RUN: %FileCheck %s < %t/swift.h // RUN: %check-in-clang %t/swift.h +// RUN: %check-in-clang-c %t/swift.h // RUN: %check-in-clang-cxx %t/swift.h // REQUIRES: objc_interop diff --git a/test/PrintAsObjC/cdecl-official-for-objc-clients.swift b/test/PrintAsObjC/cdecl-official-for-objc-clients.swift new file mode 100644 index 0000000000000..94be91e72f2c0 --- /dev/null +++ b/test/PrintAsObjC/cdecl-official-for-objc-clients.swift @@ -0,0 +1,23 @@ +/// Similar test to cdecl-official but gated to objc-interop compatibility + +// RUN: %empty-directory(%t) +// RUN: split-file %S/cdecl-official.swift %t --leading-lines + +/// Generate cdecl.h +// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) \ +// RUN: %t/Lib.swift -emit-module -verify -o %t -emit-module-doc \ +// RUN: -emit-clang-header-path %t/cdecl.h \ +// RUN: -enable-experimental-feature CDecl + +/// Check cdecl.h directly +// RUN: %check-in-clang %t/cdecl.h +// RUN: %check-in-clang-cxx %t/cdecl.h + +/// Build an Objective-C client against cdecl.h +// RUN: %clang -c %t/Client.c -fmodules -I %t \ +// RUN: -F %S/../Inputs/clang-importer-sdk-path/frameworks \ +// RUN: -I %clang-include-dir -Werror \ +// RUN: -isysroot %S/../Inputs/clang-importer-sdk + +// REQUIRES: swift_feature_CDecl +// REQUIRES: objc_interop diff --git a/test/PrintAsObjC/cdecl-official.swift b/test/PrintAsObjC/cdecl-official.swift new file mode 100644 index 0000000000000..012afa967262e --- /dev/null +++ b/test/PrintAsObjC/cdecl-official.swift @@ -0,0 +1,78 @@ +// RUN: %empty-directory(%t) +// RUN: split-file %s %t --leading-lines + +/// Generate cdecl.h +// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) \ +// RUN: %t/Lib.swift -emit-module -verify -o %t -emit-module-doc \ +// RUN: -emit-clang-header-path %t/cdecl.h \ +// RUN: -enable-experimental-feature CDecl + +/// Check cdecl.h directly +// RUN: %FileCheck %s --input-file %t/cdecl.h +// RUN: %check-in-clang-c %t/cdecl.h -Wnullable-to-nonnull-conversion + +/// Build a client against cdecl.h +// RUN: %clang-no-modules -c %t/Client.c -I %t \ +// RUN: -F %S/../Inputs/clang-importer-sdk-path/frameworks \ +// RUN: -I %clang-include-dir -Werror \ +// RUN: -isysroot %S/../Inputs/clang-importer-sdk + +// REQUIRES: swift_feature_CDecl + +//--- Lib.swift + +// CHECK-NOT: assume_nonnull + +// CHECK: #if defined(__cplusplus) +// CHECK: extern "C" { +// CHECK: #endif + +/// My documentation +@cdecl("simple") +func a_simple(x: Int, bar y: Int) -> Int { return x } +// CHECK-LABEL: // My documentation +// CHECK-LABEL: SWIFT_EXTERN ptrdiff_t simple(ptrdiff_t x, ptrdiff_t y) SWIFT_NOEXCEPT SWIFT_WARN_UNUSED_RESULT; + +@cdecl("primitiveTypes") +public func b_primitiveTypes(i: Int, ci: CInt, l: CLong, c: CChar, f: Float, d: Double, b: Bool) {} +// CHECK-LABEL: SWIFT_EXTERN void primitiveTypes(ptrdiff_t i, int ci, long l, char c, float f, double d, bool b) SWIFT_NOEXCEPT; + +@cdecl("has_keyword_arg_names") +func c_keywordArgNames(auto: Int, union: Int) {} +// CHECK-LABEL: SWIFT_EXTERN void has_keyword_arg_names(ptrdiff_t auto_, ptrdiff_t union_) SWIFT_NOEXCEPT; + +@cdecl("return_never") +func d_returnNever() -> Never { fatalError() } +// CHECK-LABEL: SWIFT_EXTERN void return_never(void) SWIFT_NOEXCEPT SWIFT_NORETURN; + +/// Pointer types +// CHECK: /// Pointer types + +@cdecl("pointers") +func f_pointers(_ x: UnsafeMutablePointer, + y: UnsafePointer, + z: UnsafeMutableRawPointer, + w: UnsafeRawPointer, + u: OpaquePointer) {} +// CHECK: SWIFT_EXTERN void pointers(ptrdiff_t * _Nonnull x, ptrdiff_t const * _Nonnull y, void * _Nonnull z, void const * _Nonnull w, void * _Nonnull u) SWIFT_NOEXCEPT; + +@cdecl("nullable_pointers") +func g_nullablePointers(_ x: UnsafeMutableRawPointer, + y: UnsafeMutableRawPointer?, + z: UnsafeMutableRawPointer!) {} +// CHECK: SWIFT_EXTERN void nullable_pointers(void * _Nonnull x, void * _Nullable y, void * _Null_unspecified z) SWIFT_NOEXCEPT; + +// CHECK: #if defined(__cplusplus) +// CHECK-NEXT: } +// CHECK-NEXT: #endif + +//--- Client.c + +#include "cdecl.h" + +int main() { + ptrdiff_t x = simple(42, 43); + primitiveTypes(1, 2, 3, 'a', 1.0f, 2.0, true); + has_keyword_arg_names(1, 2); + return_never(); +} diff --git a/test/PrintAsObjC/cdecl-with-objc.swift b/test/PrintAsObjC/cdecl-with-objc.swift new file mode 100644 index 0000000000000..f6cd9a4bc0b4f --- /dev/null +++ b/test/PrintAsObjC/cdecl-with-objc.swift @@ -0,0 +1,33 @@ +/// Ensure we print @cdecl and @_cdecl only once. + +// RUN: %empty-directory(%t) + +/// Generate cdecl.h +// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) \ +// RUN: %s -emit-module -verify -o %t -emit-module-doc \ +// RUN: -emit-objc-header-path %t/cdecl.h \ +// RUN: -disable-objc-attr-requires-foundation-module \ +// RUN: -enable-experimental-feature CDecl + +/// Check cdecl.h directly +// RUN: %FileCheck %s --input-file %t/cdecl.h +// RUN: %check-in-clang %t/cdecl.h +// RUN: %check-in-clang-c %t/cdecl.h -Wnullable-to-nonnull-conversion +// RUN: %check-in-clang-cxx %t/cdecl.h + +// REQUIRES: swift_feature_CDecl +// REQUIRES: objc_interop + +@cdecl("cFunc") +func cFunc() { } +// CHECK: cFunc +// CHECK-NOT: cFunc + +/// The class would break C parsing if printed in wrong block +@objc +class ObjCClass {} + +@_cdecl("objcFunc") +func objcFunc() -> ObjCClass! { return ObjCClass() } +// CHECK: objcFunc +// CHECK-NOT: objcFunc diff --git a/test/PrintAsObjC/cdecl.swift b/test/PrintAsObjC/cdecl.swift index 307159d956171..780121bb97d68 100644 --- a/test/PrintAsObjC/cdecl.swift +++ b/test/PrintAsObjC/cdecl.swift @@ -4,6 +4,7 @@ // RUN: %FileCheck %s < %t/cdecl.h // RUN: %check-in-clang %t/cdecl.h // RUN: %check-in-clang -fno-modules -Qunused-arguments %t/cdecl.h -include ctypes.h -include CoreFoundation.h +// RUN: %check-in-clang-c -fno-modules -Qunused-arguments %t/cdecl.h -include ctypes.h -include CoreFoundation.h // RUN: %check-in-clang-cxx -fno-modules -Qunused-arguments %t/cdecl.h -include ctypes.h -include CoreFoundation.h // REQUIRES: objc_interop diff --git a/test/PrintAsObjC/lit.local.cfg b/test/PrintAsObjC/lit.local.cfg index a517a4a80ca14..c7f4cd06a3431 100644 --- a/test/PrintAsObjC/lit.local.cfg +++ b/test/PrintAsObjC/lit.local.cfg @@ -10,6 +10,14 @@ config.substitutions.insert(0, ('%check-in-clang', '-I %%clang-include-dir ' '-isysroot %r/Inputs/clang-importer-sdk' % config.test_source_root) ) +config.substitutions.insert(0, ('%check-in-clang-c', + '%%clang-no-modules -fsyntax-only -x c-header -std=c99 ' + '-Weverything -Werror -Wno-unused-macros -Wno-incomplete-module ' + '-Wno-auto-import -Wno-poison-system-directories ' + '-F %%clang-importer-sdk-path/frameworks ' + '-I %%clang-include-dir ' + '-isysroot %r/Inputs/clang-importer-sdk' % config.test_source_root) ) + config.substitutions.insert(0, ('%check-in-clang-cxx', '%%clang -fsyntax-only -x objective-c++-header -std=c++17 ' '-fobjc-arc -fmodules -fmodules-validate-system-headers ' diff --git a/test/SIL/Parser/basic.sil b/test/SIL/Parser/basic.sil index 2af0a635ce4d1..9dabff5a02b6a 100644 --- a/test/SIL/Parser/basic.sil +++ b/test/SIL/Parser/basic.sil @@ -1220,6 +1220,16 @@ sil @alloc_stack_test : $() -> () { // CHECK: } // end sil function 'alloc_stack_test' } +// CHECK-LABEL: sil @vector_base_addr : +// CHECK: %1 = vector_base_addr %0 : $*Builtin.FixedArray<10, Int> +// CHECK-LABEL: } // end sil function 'vector_base_addr' +sil @vector_base_addr : $@convention(thin) (@inout Builtin.FixedArray<10, Int>) -> Int { +bb0(%0 : $*Builtin.FixedArray<10, Int>): + %1 = vector_base_addr %0 + %2 = load %1 + return %2 +} + sil_global @staticProp: $Int // CHECK-LABEL: sil private @globalinit_func0 : $@convention(thin) () -> () { diff --git a/test/SIL/verifier_nofail.sil b/test/SIL/verifier_nofail.sil index 27f337f7e4539..2559624ee52a3 100644 --- a/test/SIL/verifier_nofail.sil +++ b/test/SIL/verifier_nofail.sil @@ -23,3 +23,13 @@ bb0(%0 : $*P): %9999 = tuple() return %9999 : $() } + + +class Klass {} + +sil [ossa] [_semantics "sil.verify_none"] @foo : $@convention(thin) (@guaranteed Klass) -> () { +bb0(%0 : @guaranteed $Klass): + destroy_value %0 + %t = tuple() + return %t +} diff --git a/test/SILGen/hop_to_executor.swift b/test/SILGen/hop_to_executor.swift index 63736dad7c1b6..a1daf20bed2c5 100644 --- a/test/SILGen/hop_to_executor.swift +++ b/test/SILGen/hop_to_executor.swift @@ -324,6 +324,8 @@ func testGlobalActorFuncValue(_ fn: @RedActor () -> Void) async { } func acceptAsyncSendableClosureInheriting(@_inheritActorContext _: @Sendable () async -> T) { } +func acceptAsyncSendableClosureAlwaysInheriting(@_inheritActorContext(always) _: @Sendable () async -> T) { } +func acceptAsyncSendableClosureAlwaysInheritingErased(@_inheritActorContext(always) _: sending @isolated(any) () async -> T) { } extension MyActor { func synchronous() { } @@ -338,6 +340,66 @@ extension MyActor { synchronous() } } + + // CHECK-LABEL: sil private [ossa] @$s4test7MyActorC0A16AlwaysInheritingyyFyyYaYbXEfU_ + // CHECK: debug_value [[SELF:%[0-9]+]] : $MyActor + // CHECK-NEXT: [[COPY:%[0-9]+]] = copy_value [[SELF]] : $MyActor + // CHECK-NEXT: [[BORROW:%[0-9]+]] = begin_borrow [[COPY]] : $MyActor + // CHECK-NEXT: hop_to_executor [[BORROW]] : $MyActor + func testAlwaysInheriting() { + acceptAsyncSendableClosureAlwaysInheriting { + } + } +} + +func testIsolatedParameterWithInheritActorContext(_ isolation: isolated (any Actor)?) { + // CHECK-LABEL: sil private [ossa] @$s4test0A40IsolatedParameterWithInheritActorContextyyScA_pSgYiFyyYaYbXEfU_ + // CHECK: debug_value [[ISOLATION:%[0-9]+]] : $Optional + // CHECK-NEXT: [[COPY:%[0-9]+]] = copy_value [[ISOLATION]] : $Optional + // CHECK-NEXT: [[BORROW:%[0-9]+]] = begin_borrow [[COPY]] : $Optional + // CHECK-NEXT: hop_to_executor [[BORROW]] : $Optional + acceptAsyncSendableClosureAlwaysInheriting { + } + + // CHECK-LABEL: sil private [ossa] @$s4test0A40IsolatedParameterWithInheritActorContextyyScA_pSgYiFyyYaYbScMYcXEfU0_ + // CHECK: hop_to_executor {{.*}} : $MainActor + acceptAsyncSendableClosureAlwaysInheriting { @MainActor in + // CHECK-LABEL: sil private [ossa] @$s4test0A40IsolatedParameterWithInheritActorContextyyScA_pSgYiFyyYaYbScMYcXEfU0_yyYaYbXEfU_ + // CHECK: hop_to_executor {{.*}} : $MainActor + acceptAsyncSendableClosureAlwaysInheriting { + } + } + + // CHECK-LABEL: sil private [ossa] @$s4test0A40IsolatedParameterWithInheritActorContextyyScA_pSgYiFyyYaYbXEfU1_ + // CHECK: debug_value [[ISOLATION:%[0-9]+]] : $Optional + // CHECK-NEXT: [[COPY:%[0-9]+]] = copy_value [[ISOLATION]] : $Optional + // CHECK-NEXT: [[BORROW:%[0-9]+]] = begin_borrow [[COPY]] : $Optional + // CHECK-NEXT: hop_to_executor [[BORROW]] : $Optional + acceptAsyncSendableClosureAlwaysInheriting { + // CHECK-LABEL: sil private [ossa] @$s4test0A40IsolatedParameterWithInheritActorContextyyScA_pSgYiFyyYaYbXEfU1_yyYaYbXEfU_ + // CHECK: debug_value [[ISOLATION:%[0-9]+]] : $Optional + // CHECK-NEXT: [[COPY:%[0-9]+]] = copy_value [[ISOLATION]] : $Optional + // CHECK-NEXT: [[BORROW:%[0-9]+]] = begin_borrow [[COPY]] : $Optional + // CHECK-NEXT: hop_to_executor [[BORROW]] : $Optional + acceptAsyncSendableClosureAlwaysInheriting { + } + } +} + +// CHECK-LABEL: sil hidden [ossa] @$s4test0a17IsolatedParamWithB3AnyyyScA_pYiF +// CHECK: [[CLOSURE_REF:%.*]] = function_ref @$s4test0a17IsolatedParamWithB3AnyyyScA_pYiFyyYaXEfU_ +// CHECK-NEXT: [[ISOLATION_COPY_1:%.*]] = copy_value %0 : $any Actor +// CHECK-NEXT: [[ISOLATION_COPY_2:%.*]] = copy_value [[ISOLATION_COPY_1]] : $any Actor +// CHECK-NEXT: [[DYNAMIC_ISOLATION:%.*]] = enum $Optional, #Optional.some!enumelt, [[ISOLATION_COPY_2]] : $any Actor +// CHECK-NEXT: [[CLOSURE_WITH_APPLIED_ISOLATION:%.*]] = partial_apply [callee_guaranteed] [isolated_any] [[CLOSURE_REF]]([[DYNAMIC_ISOLATION]], [[ISOLATION_COPY_1]]) +func testIsolatedParamWithIsolatedAny(_ isolation: isolated any Actor) { + // CHECK-LABEL: sil private [ossa] @$s4test0a17IsolatedParamWithB3AnyyyScA_pYiFyyYaXEfU_ + // CHECK: bb0(%0 : $*(), [[DYNAMIC_ISOLATION:%[0-9]+]] : @guaranteed $Optional, [[CAPTURED_ISOLATION:%[0-9]+]] : @closureCapture @guaranteed $any Actor): + // CHECK: [[COPY:%[0-9]+]] = copy_value [[CAPTURED_ISOLATION]] : $any Actor + // CHECK-NEXT: [[BORROW:%[0-9]+]] = begin_borrow [[COPY]] : $any Actor + // CHECK-NEXT: hop_to_executor [[BORROW]] : $any Actor + acceptAsyncSendableClosureAlwaysInheritingErased { + } } func acceptAsyncClosure(_: () async -> Void) { } diff --git a/test/SILGen/inlinearray_literal.swift b/test/SILGen/inlinearray_literal.swift index c48a3dbf35a3d..26becddbe69ab 100644 --- a/test/SILGen/inlinearray_literal.swift +++ b/test/SILGen/inlinearray_literal.swift @@ -37,7 +37,8 @@ func emptyNoncopyable() -> InlineArray<0, Atomic> { // CHECK-LABEL: sil{{.*}} @$s19inlinearray_literal7trivials11InlineArrayVy$3_SiGyF : $@convention(thin) () -> InlineArray<4, Int> { // CHECK: [[SLAB_ALLOC:%.*]] = alloc_stack $InlineArray<4, Int> -// CHECK-NEXT: [[ELEMENT_PTR:%.*]] = unchecked_addr_cast [[SLAB_ALLOC]] to $*Int +// CHECK-NEXT: [[SE:%.*]] = struct_element_addr [[SLAB_ALLOC]], #InlineArray._storage +// CHECK-NEXT: [[ELEMENT_PTR:%.*]] = vector_base_addr [[SE]] // CHECK-NEXT: [[ELT_0_LITERAL:%.*]] = integer_literal $Builtin.IntLiteral, 1 // CHECK: [[ELT_0:%.*]] = apply {{%.*}}([[ELT_0_LITERAL]], {{%.*}}) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int // CHECK-NEXT: store [[ELT_0]] to [trivial] [[ELEMENT_PTR]] @@ -66,7 +67,8 @@ func trivial() -> InlineArray<4, Int> { // CHECK-LABEL: sil{{.*}} @$s19inlinearray_literal10nontrivials11InlineArrayVy$1_SSGyF : $@convention(thin) () -> @owned InlineArray<2, String> { // CHECK: [[SLAB_ALLOC:%.*]] = alloc_stack $InlineArray<2, String> -// CHECK-NEXT: [[ELEMENT_PTR:%.*]] = unchecked_addr_cast [[SLAB_ALLOC]] to $*String +// CHECK-NEXT: [[SE:%.*]] = struct_element_addr [[SLAB_ALLOC]], #InlineArray._storage +// CHECK-NEXT: [[ELEMENT_PTR:%.*]] = vector_base_addr [[SE]] // CHECK-NEXT: [[ELT_0_LITERAL:%.*]] = string_literal utf8 "hello" // CHECK: [[ELT_0:%.*]] = apply {{%.*}}([[ELT_0_LITERAL]], {{.*}}) : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String // CHECK-NEXT: store [[ELT_0]] to [init] [[ELEMENT_PTR]] @@ -86,7 +88,8 @@ func nontrivial() -> InlineArray<2, String> { // CHECK-LABEL: sil{{.*}} @$s19inlinearray_literal11noncopyables11InlineArrayVy$1_15Synchronization6AtomicVySiGGyF : $@convention(thin) () -> @out InlineArray<2, Atomic> { // CHECK: bb0([[SLAB_RETURN:%.*]] : $*InlineArray<2, Atomic>): // CHECK-NEXT: [[SLAB_ALLOC:%.*]] = alloc_stack $InlineArray<2, Atomic> -// CHECK-NEXT: [[ELEMENT_PTR:%.*]] = unchecked_addr_cast [[SLAB_ALLOC]] to $*Atomic +// CHECK-NEXT: [[SE:%.*]] = struct_element_addr [[SLAB_ALLOC]], #InlineArray._storage +// CHECK-NEXT: [[ELEMENT_PTR:%.*]] = vector_base_addr [[SE]] // CHECK: [[ATOMIC_INIT:%.*]] = function_ref @$s15Synchronization6AtomicVyACyxGxcfC // CHECK-NEXT: [[ELT_0:%.*]] = apply [[ATOMIC_INIT]]([[ELEMENT_PTR]], {{.*}}) : $@convention(method) <Ï„_0_0 where Ï„_0_0 : AtomicRepresentable> (@in Ï„_0_0, @thin Atomic<Ï„_0_0>.Type) -> @out Atomic<Ï„_0_0> // CHECK: [[ELT_1_OFFSET:%.*]] = integer_literal $Builtin.Word, 1 @@ -109,10 +112,11 @@ func noncopyable() -> InlineArray<2, Atomic> { // CHECK-LABEL: sil{{.*}} @$s19inlinearray_literal7closures11InlineArrayVy$0_S2icGyF : $@convention(thin) () -> @owned InlineArray<1, (Int) -> Int> { // CHECK: [[IA_ALLOC:%.*]] = alloc_stack $InlineArray<1, (Int) -> Int> -// CHECK-NEXT: [[ADDR_CAST:%.*]] = unchecked_addr_cast [[IA_ALLOC]] to $*@callee_guaranteed @substituted <Ï„_0_0, Ï„_0_1> (@in_guaranteed Ï„_0_0) -> @out Ï„_0_1 for +// CHECK-NEXT: [[SE:%.*]] = struct_element_addr [[IA_ALLOC]], #InlineArray._storage +// CHECK-NEXT: [[ELEMENT_PTR:%.*]] = vector_base_addr [[SE]] // CHECK: [[FN_REF:%.*]] = function_ref // CHECK-NEXT: [[THIN_TO_THICK_FN:%.*]] = thin_to_thick_function [[FN_REF]] to $@callee_guaranteed @substituted <Ï„_0_0, Ï„_0_1> (@in_guaranteed Ï„_0_0) -> @out Ï„_0_1 for -// CHECK-NEXT: store [[THIN_TO_THICK_FN]] to [init] [[ADDR_CAST]] +// CHECK-NEXT: store [[THIN_TO_THICK_FN]] to [init] [[ELEMENT_PTR]] // CHECK-NEXT: [[IA:%.*]] = load [take] [[IA_ALLOC]] // CHECK-NEXT: dealloc_stack [[IA_ALLOC]] // CHECK-NEXT: return [[IA]] diff --git a/test/SILOptimizer/accessutils.sil b/test/SILOptimizer/accessutils.sil index a098496ceea7f..a3381efc51b99 100644 --- a/test/SILOptimizer/accessutils.sil +++ b/test/SILOptimizer/accessutils.sil @@ -27,6 +27,10 @@ struct Ptr { var p: Int64 } +struct VectorStruct { + var a: Builtin.FixedArray<100, Int64> +} + class C {} sil @_getC : $@convention(thin) () -> @owned C @@ -707,3 +711,20 @@ bb0(%0 : @guaranteed $List): return %6 : $Int64 } +// CHECK-LABEL: Accesses for vectors +// CHECK: Value: %4 = index_addr %2 : $*Int64, %3 : $Builtin.Int64 +// CHECK-NEXT: Scope: base +// CHECK-NEXT: Base: argument - %0 = argument of bb0 : $*VectorStruct +// CHECK-NEXT: Path: "s0.b.i5" +// CHECK-NEXT: no Storage paths +// CHECK-LABEL: End accesses for vectors +sil [ossa] @vectors : $@convention(thin) (@in_guaranteed VectorStruct) -> Int64 { +bb0(%0 : $*VectorStruct): + %1 = struct_element_addr %0, #VectorStruct.a + %2 = vector_base_addr %1 + %3 = integer_literal $Builtin.Int64, 5 + %4 = index_addr %2, %3 + %5 = load [trivial] %4 + return %5 +} + diff --git a/test/SILOptimizer/alias-analysis.sil b/test/SILOptimizer/alias-analysis.sil index 19e8e72fa82fc..d9cd41613fd39 100644 --- a/test/SILOptimizer/alias-analysis.sil +++ b/test/SILOptimizer/alias-analysis.sil @@ -99,3 +99,44 @@ bb0(%0 : $*MyStruct, %1 : $Builtin.Word): %99 = tuple () return %99 : $() } + +// CHECK-LABEL: @testVectorBaseAddr +// CHECK: PAIR #18. +// CHECK-NEXT: %2 = vector_base_addr %0 : $*Builtin.FixedArray<10, Int> +// CHECK-NEXT: %3 = index_addr %2 : $*Int, %1 : $Builtin.Word +// CHECK-NEXT: MayAlias +// CHECK: PAIR #21. +// CHECK-NEXT: %2 = vector_base_addr %0 : $*Builtin.FixedArray<10, Int> +// CHECK-NEXT: %6 = index_addr %2 : $*Int, %4 : $Builtin.Word +// CHECK-NEXT: NoAlias +// CHECK: PAIR #22. +// CHECK-NEXT: %2 = vector_base_addr %0 : $*Builtin.FixedArray<10, Int> +// CHECK-NEXT: %7 = index_addr %2 : $*Int, %5 : $Builtin.Word +// CHECK-NEXT: NoAlias +// CHECK: PAIR #27. +// CHECK-NEXT: %3 = index_addr %2 : $*Int, %1 : $Builtin.Word +// CHECK-NEXT: %6 = index_addr %2 : $*Int, %4 : $Builtin.Word +// CHECK-NEXT: MayAlias +// CHECK: PAIR #28. +// CHECK-NEXT: %3 = index_addr %2 : $*Int, %1 : $Builtin.Word +// CHECK-NEXT: %7 = index_addr %2 : $*Int, %5 : $Builtin.Word +// CHECK-NEXT: MayAlias +// CHECK: PAIR #40. +// CHECK-NEXT: %6 = index_addr %2 : $*Int, %4 : $Builtin.Word +// CHECK-NEXT: %7 = index_addr %2 : $*Int, %5 : $Builtin.Word +// CHECK-NEXT: NoAlias +sil @testVectorBaseAddr : $@convention(thin) (@inout Builtin.FixedArray<10, Int>, Builtin.Word) -> () { +bb0(%0 : $*Builtin.FixedArray<10, Int>, %1 : $Builtin.Word): + %2 = vector_base_addr %0 + %3 = index_addr %2, %1 + %4 = integer_literal $Builtin.Word, 1 + %5 = integer_literal $Builtin.Word, 2 + %6 = index_addr %2, %4 + %7 = index_addr %2, %5 + fix_lifetime %2 + fix_lifetime %3 + fix_lifetime %6 + fix_lifetime %7 + %99 = tuple () + return %99 : $() +} diff --git a/test/SILOptimizer/drop_deinit_opt.sil b/test/SILOptimizer/drop_deinit_opt.sil new file mode 100644 index 0000000000000..1fe18325c3286 --- /dev/null +++ b/test/SILOptimizer/drop_deinit_opt.sil @@ -0,0 +1,47 @@ +// RUN: %target-sil-opt %s -early-inline -mem2reg | %FileCheck %s + +import Swift +import Builtin + +struct FileDescriptor : ~Copyable { + @_hasStorage private var fd: Int { get set } + init(_ fd: Int) + deinit +} + +sil hidden [ossa] @fd_close : $@convention(thin) (Int) -> () { +bb0(%0 : $Int): + debug_value %0, let, name "fd", argno 1 + %2 = tuple () + return %2 +} + +// CHECK-LABEL: sil hidden [ossa] @fd_deinit1 : +// CHECK: drop_deinit +// CHECK-LABEL: } // end sil function 'fd_deinit1' +sil hidden [ossa] @fd_deinit1 : $@convention(method) (@owned FileDescriptor) -> () { +bb0(%0 : @owned $FileDescriptor): + %1 = alloc_stack $FileDescriptor, let, name "self", argno 1 + store %0 to [init] %1 + %3 = drop_deinit %1 + %6 = struct_element_addr %3, #FileDescriptor.fd + %7 = load [trivial] %6 + %9 = function_ref @fd_close : $@convention(thin) (Int) -> () + %10 = apply %9(%7) : $@convention(thin) (Int) -> () + dealloc_stack %1 + %12 = tuple () + return %12 +} + +// CHECK-LABEL: sil hidden [ossa] @fd_deinit2 : +// CHECK: end_lifetime +// CHECK-LABEL: } // end sil function 'fd_deinit2' +sil hidden [ossa] @fd_deinit2 : $@convention(method) (@owned FileDescriptor) -> () { +bb0(%0 : @owned $FileDescriptor): + %3 = drop_deinit %0 + %6 = destructure_struct %3 + %9 = function_ref @fd_close : $@convention(thin) (Int) -> () + %10 = apply %9(%6) : $@convention(thin) (Int) -> () + %12 = tuple () + return %12 +} diff --git a/test/SILOptimizer/escape_info.sil b/test/SILOptimizer/escape_info.sil index 2230c83e8e223..285c7d5dfd7f6 100644 --- a/test/SILOptimizer/escape_info.sil +++ b/test/SILOptimizer/escape_info.sil @@ -1510,3 +1510,21 @@ bb0: dealloc_stack %0 : $*X return %4 : $Builtin.RawPointer } + +// CHECK-LABEL: Escape information for test_vector_base_addr_escaping: +// CHECK: return[]: %1 = alloc_ref $X +// CHECK: End function test_vector_base_addr_escaping +sil @test_vector_base_addr_escaping : $@convention(thin) () -> @owned X { +bb0: + %0 = alloc_stack $Builtin.FixedArray<10, X> + %1 = alloc_ref $X + %2 = vector_base_addr %0 + %3 = integer_literal $Builtin.Int64, 1 + %4 = index_addr %2, %3 + store %1 to %4 + %6 = vector_base_addr %0 + %7 = index_addr %6, %3 + %8 = load %4 + dealloc_stack %0 + return %8 +} diff --git a/test/SILOptimizer/functionsigopts_crash.swift b/test/SILOptimizer/functionsigopts_crash.swift index 60f87eb25f358..f499fc72d4cae 100644 --- a/test/SILOptimizer/functionsigopts_crash.swift +++ b/test/SILOptimizer/functionsigopts_crash.swift @@ -35,3 +35,21 @@ func testit(_ p: P) { public func callit(s: S) { testit(s) } + +// Check that FSO does not trigger a verifier error caused by a mutated @in argument which is +// converted to an @in_guaranteed argument (which must not be mutated). + +public protocol IP { + associatedtype Element + + init(iterator: consuming Iterator) where Iterator: IteratorProtocol, Iterator.Element == Element +} + +extension Array: IP { + public init(iterator: consuming Iterator) where Iterator: IteratorProtocol, Iterator.Element == Element { + self.init() + while let next = iterator.next() { + append(next) + } + } +} diff --git a/test/SILOptimizer/globalopt_resilience.swift b/test/SILOptimizer/globalopt_resilience.swift index 12a62efd2bea3..64a4c73395c26 100644 --- a/test/SILOptimizer/globalopt_resilience.swift +++ b/test/SILOptimizer/globalopt_resilience.swift @@ -37,13 +37,9 @@ public func cannotConvertToValueUse() { } // CHECK-LABEL: sil @$s4test23cannotConvertToValueUseyyF : $@convention(thin) () -> () -// CHECK: [[INT:%.*]] = integer_literal $Builtin.Int{{32|64}}, 27 -// CHECK: [[S1:%.*]] = struct $Int ([[INT]] : $Builtin.Int{{32|64}}) -// CHECK: [[S2:%.*]] = struct $ResilientStruct ([[S1]] : $Int) -// CHECK: [[TMP:%.*]] = alloc_stack $ResilientStruct -// CHECK: store [[S2]] to [[TMP]] : $*ResilientStruct +// CHECK: [[GA:%.*]] = global_addr @$s4test15ResilientStructV9staticValACvpZ // CHECK: [[METHOD:%.*]] = function_ref @$s4test15ResilientStructV6methodyyF : $@convention(method) (@in_guaranteed ResilientStruct) -> () -// CHECK: apply [[METHOD]]([[TMP]]) : $@convention(method) (@in_guaranteed ResilientStruct) -> () +// CHECK: apply [[METHOD]]([[GA]]) : $@convention(method) (@in_guaranteed ResilientStruct) -> () // CHECK: [[RESULT:%.*]] = tuple () // CHECK: return [[RESULT]] : $() diff --git a/test/SILOptimizer/init_static_globals.sil b/test/SILOptimizer/init_static_globals.sil index 21e58e0cfc1c5..13296ec649897 100644 --- a/test/SILOptimizer/init_static_globals.sil +++ b/test/SILOptimizer/init_static_globals.sil @@ -107,7 +107,8 @@ sil_global [let] @g9 : $TwoFields // CHECK-NEXT: %3 = struct $Int32 (%2) // CHECK-NEXT: %4 = integer_literal $Builtin.Int32, 3 // CHECK-NEXT: %5 = struct $Int32 (%4) -// CHECK-NEXT: %initval = vector (%1, %3, %5) +// CHECK-NEXT: %6 = vector (%1, %3, %5) +// CHECK-NEXT: %initval = struct $InlineArray<3, Int32> (%6) // CHECK-NEXT: } sil_global [let] @inline_array1 : $InlineArray<3, Int32> @@ -127,7 +128,8 @@ sil_global [let] @inline_array1 : $InlineArray<3, Int32> // CHECK-NEXT: %12 = integer_literal $Builtin.Int32, 60 // CHECK-NEXT: %13 = struct $Int32 (%12) // CHECK-NEXT: %14 = tuple (%11, %13) -// CHECK-NEXT: %initval = vector (%4, %9, %14) +// CHECK-NEXT: %15 = vector (%4, %9, %14) +// CHECK-NEXT: %initval = struct $InlineArray<3, (Int32, Int32)> (%15) // CHECK-NEXT: } sil_global [let] @inline_array2 : $InlineArray<3, (Int32, Int32)> @@ -357,8 +359,8 @@ sil [global_init_once_fn] [ossa] @globalinit_inline_array : $@convention(c) (Bui bb0(%0 : $Builtin.RawPointer): alloc_global @inline_array1 %2 = global_addr @inline_array1 : $*InlineArray<3, Int32> - %3 = alloc_stack $InlineArray<3, Int32> - %4 = unchecked_addr_cast %3 to $*Int32 + %3 = alloc_stack $Builtin.FixedArray<3, Int32> + %4 = vector_base_addr %3 %5 = integer_literal $Builtin.Int32, 1 %6 = struct $Int32 (%5) store %6 to [trivial] %4 @@ -373,8 +375,9 @@ bb0(%0 : $Builtin.RawPointer): %16 = struct $Int32 (%15) store %16 to [trivial] %14 %18 = load [trivial] %3 + %19 = struct $InlineArray<3, Int32> (%18) dealloc_stack %3 - store %18 to [trivial] %2 + store %19 to [trivial] %2 %21 = tuple () return %21 } @@ -388,8 +391,8 @@ sil [global_init_once_fn] [ossa] @globalinit_inline_array_of_tuples : $@conventi bb0(%0 : $Builtin.RawPointer): alloc_global @inline_array2 %2 = global_addr @inline_array2 : $*InlineArray<3, (Int32, Int32)> - %3 = alloc_stack $InlineArray<3, (Int32, Int32)> - %4 = unchecked_addr_cast %3 to $*(Int32, Int32) + %3 = alloc_stack $Builtin.FixedArray<3, (Int32, Int32)> + %4 = vector_base_addr %3 %5 = tuple_element_addr %4, 0 %6 = tuple_element_addr %4, 1 %7 = integer_literal $Builtin.Int32, 10 @@ -419,8 +422,9 @@ bb0(%0 : $Builtin.RawPointer): %31 = struct $Int32 (%30) store %31 to [trivial] %26 %33 = load [trivial] %3 + %34 = struct $InlineArray<3, (Int32, Int32)> (%33) dealloc_stack %3 - store %33 to [trivial] %2 + store %34 to [trivial] %2 %36 = tuple () return %36 } @@ -434,8 +438,8 @@ sil [global_init_once_fn] [ossa] @no_globalinit_double_store: $@convention(c) (B bb0(%0 : $Builtin.RawPointer): alloc_global @inline_array3 %2 = global_addr @inline_array3 : $*InlineArray<2, Int32> - %3 = alloc_stack $InlineArray<2, Int32> - %4 = unchecked_addr_cast %3 to $*Int32 + %3 = alloc_stack $Builtin.FixedArray<2, Int32> + %4 = vector_base_addr %3 %5 = integer_literal $Builtin.Int32, 1 %6 = struct $Int32 (%5) store %6 to [trivial] %4 @@ -446,8 +450,9 @@ bb0(%0 : $Builtin.RawPointer): store %11 to [trivial] %9 store %6 to [trivial] %9 %18 = load [trivial] %3 + %19 = struct $InlineArray<2, Int32> (%18) dealloc_stack %3 - store %18 to [trivial] %2 + store %19 to [trivial] %2 %21 = tuple () return %21 } @@ -461,8 +466,8 @@ sil [global_init_once_fn] [ossa] @no_globalinit_extra_load: $@convention(c) (Bui bb0(%0 : $Builtin.RawPointer): alloc_global @inline_array4 %2 = global_addr @inline_array4 : $*InlineArray<2, Int32> - %3 = alloc_stack $InlineArray<2, Int32> - %4 = unchecked_addr_cast %3 to $*Int32 + %3 = alloc_stack $Builtin.FixedArray<2, Int32> + %4 = vector_base_addr %3 %5 = integer_literal $Builtin.Int32, 1 %6 = struct $Int32 (%5) store %6 to [trivial] %4 @@ -471,8 +476,9 @@ bb0(%0 : $Builtin.RawPointer): %10 = load [trivial] %4 store %10 to [trivial] %9 %18 = load [trivial] %3 + %19 = struct $InlineArray<2, Int32> (%18) dealloc_stack %3 - store %18 to [trivial] %2 + store %19 to [trivial] %2 %21 = tuple () return %21 } @@ -486,8 +492,8 @@ sil [global_init_once_fn] [ossa] @no_globalinit_no_load: $@convention(c) (Builti bb0(%0 : $Builtin.RawPointer): alloc_global @gint %2 = global_addr @gint : $*Int32 - %3 = alloc_stack $InlineArray<2, Int32> - %4 = unchecked_addr_cast %3 to $*Int32 + %3 = alloc_stack $Builtin.FixedArray<2, Int32> + %4 = vector_base_addr %3 %5 = integer_literal $Builtin.Int32, 1 %6 = struct $Int32 (%5) store %6 to [trivial] %4 @@ -511,11 +517,12 @@ sil [global_init_once_fn] [ossa] @no_globalinit_empty_inline_array : $@conventio bb0(%0 : $Builtin.RawPointer): alloc_global @empty_inline_array %2 = global_addr @empty_inline_array : $*InlineArray<0, Int32> - %3 = alloc_stack $InlineArray<0, Int32> - %4 = unchecked_addr_cast %3 to $*Int32 + %3 = alloc_stack $Builtin.FixedArray<0, Int32> + %4 = vector_base_addr %3 %18 = load [trivial] %3 + %19 = struct $InlineArray<0, Int32> (%18) dealloc_stack %3 - store %18 to [trivial] %2 + store %19 to [trivial] %2 %21 = tuple () return %21 } @@ -529,15 +536,16 @@ sil [global_init_once_fn] [ossa] @no_globalinit_inline_array_empty_elements : $@ bb0(%0 : $Builtin.RawPointer): alloc_global @inline_array_empty_elements %2 = global_addr @inline_array_empty_elements : $*InlineArray<3, ()> - %3 = alloc_stack $InlineArray<3, ()> - %4 = unchecked_addr_cast %3 to $*() + %3 = alloc_stack $Builtin.FixedArray<3, ()> + %4 = vector_base_addr %3 %13 = integer_literal $Builtin.Word, 2 %14 = index_addr %4, %13 %15 = tuple () store %15 to [trivial] %14 %18 = load [trivial] %3 + %19 = struct $InlineArray<3, ()> (%18) dealloc_stack %3 - store %18 to [trivial] %2 + store %19 to [trivial] %2 %21 = tuple () return %21 } diff --git a/test/SILOptimizer/inline_arrays.swift b/test/SILOptimizer/inline_arrays.swift new file mode 100644 index 0000000000000..28df586be1f30 --- /dev/null +++ b/test/SILOptimizer/inline_arrays.swift @@ -0,0 +1,35 @@ +// RUN: %target-swift-frontend -primary-file %s -O -disable-availability-checking -module-name=test -emit-sil | %FileCheck %s + +// REQUIRES: swift_stdlib_no_asserts, optimized_stdlib + +// CHECK-LABEL: sil @$s4test0A9Subscriptys5UInt8Vs11InlineArrayVy$255_ADGz_SitF : +// CHECK: [[S:%.*]] = struct_element_addr %0, #InlineArray._storage +// CHECK: [[BA:%.*]] = vector_base_addr [[S]] +// CHECK: [[EA:%.*]] = index_addr [stack_protection] [[BA]], +// CHECK: [[E:%.*]] = load [[EA]] +// CHECK: return [[E]] +// CHECK: } // end sil function '$s4test0A9Subscriptys5UInt8Vs11InlineArrayVy$255_ADGz_SitF' +public func testSubscript(_ a: inout InlineArray<256, UInt8>, _ i: Int) -> UInt8 { + return a[i] +} + +public final class C { + let a: InlineArray<256, UInt8> + + init(_ a: InlineArray<256, UInt8>) { + self.a = a + } + + // CHECK-LABEL: sil @$s4test1CC0A9Subscriptys5UInt8VSiF : + // CHECK: [[CA:%.*]] = ref_element_addr [immutable] %1, #C.a + // CHECK: [[S:%.*]] = struct_element_addr [[CA]], #InlineArray._storage + // CHECK: [[BA:%.*]] = vector_base_addr [[S]] + // CHECK: [[EA:%.*]] = index_addr [stack_protection] [[BA]], + // CHECK: [[E:%.*]] = load [[EA]] + // CHECK: return [[E]] + // CHECK: } // end sil function '$s4test1CC0A9Subscriptys5UInt8VSiF' + public func testSubscript(_ i: Int) -> UInt8 { + return a[i] + } +} + diff --git a/test/SILOptimizer/pre_specialize_layouts.swift b/test/SILOptimizer/pre_specialize_layouts.swift index 66839d524e054..c0f2f6f4ea7bc 100644 --- a/test/SILOptimizer/pre_specialize_layouts.swift +++ b/test/SILOptimizer/pre_specialize_layouts.swift @@ -189,7 +189,6 @@ public func usePrespecializedEntryPoints(wrapperStruct: ReferenceWrapperStruct, // OPT: [[A1:%.*]] = unchecked_ref_cast [[P1]] : $SomeClass to $AnyObject // OPT: [[R3:%.*]] = apply [[F1]]([[A1]]) : $@convention(thin) (@guaranteed AnyObject) -> @owned AnyObject // OPT: store [[R3]] to [[R2]] : $*AnyObject -// OPT: [[A2:%.*]] = load [[R1]] : $*SomeClass // OPT: [[F2:%.*]] = function_ref @$s22pre_specialize_layouts7consumeyyxlF0a20_specialized_module_C09SomeClassC_Ttg5 : $@convention(thin) () -> () // OPT: apply [[F2]]() : $@convention(thin) () -> () // OPT: dealloc_stack [[R1]] : $*SomeClass diff --git a/test/SILOptimizer/redundant_load_elim_ossa.sil b/test/SILOptimizer/redundant_load_elim_ossa.sil index 2084ba1154ff9..8ddedacace959 100644 --- a/test/SILOptimizer/redundant_load_elim_ossa.sil +++ b/test/SILOptimizer/redundant_load_elim_ossa.sil @@ -1743,3 +1743,18 @@ bb0(%0 : $Int): dealloc_stack %3 return %6 } + +// CHECK-LABEL: sil [ossa] @vector : +// CHECK: return %1 +// CHECK-LABEL: } // end sil function 'vector' +sil [ossa] @vector : $@convention(thin) (@inout Builtin.FixedArray<10, Int>, Int, Int) -> Int { +bb0(%0 : $*Builtin.FixedArray<10, Int>, %1 : $Int, %2 : $Int): + %3 = vector_base_addr %0 + %4 = integer_literal $Builtin.Word, 1 + %5 = index_addr %3, %4 + store %1 to [trivial] %5 + store %2 to [trivial] %3 + %6 = load [trivial] %5 + return %6 +} + diff --git a/test/SILOptimizer/simplify_unchecked_addr_cast.sil b/test/SILOptimizer/simplify_unchecked_addr_cast.sil new file mode 100644 index 0000000000000..43a83f0f7dd13 --- /dev/null +++ b/test/SILOptimizer/simplify_unchecked_addr_cast.sil @@ -0,0 +1,73 @@ +// RUN: %target-sil-opt %s -onone-simplification -simplify-instruction=unchecked_addr_cast | %FileCheck %s +// RUN: %target-sil-opt %s -simplification -simplify-instruction=unchecked_addr_cast | %FileCheck %s + +import Swift +import Builtin + +// CHECK-LABEL: sil [ossa] @same_type : +// CHECK-NOT: unchecked_addr_cast +// CHECK: %1 = load [trivial] %0 +// CHECK: } // end sil function 'same_type' +sil [ossa] @same_type : $@convention(thin) (@inout Int) -> Int { +bb0(%0 : $*Int): + %1 = unchecked_addr_cast %0 to $*Int + %2 = load [trivial] %1 + return %2 +} + +// CHECK-LABEL: sil [ossa] @not_same_type : +// CHECK: %1 = unchecked_addr_cast %0 to $*Float +// CHECK: %2 = load [trivial] %1 +// CHECK: } // end sil function 'not_same_type' +sil [ossa] @not_same_type : $@convention(thin) (@inout Int) -> Float { +bb0(%0 : $*Int): + %1 = unchecked_addr_cast %0 to $*Float + %2 = load [trivial] %1 + return %2 +} + +// CHECK-LABEL: sil [ossa] @double_cast : +// CHECK: %1 = unchecked_addr_cast %0 to $*Bool +// CHECK: %2 = load [trivial] %1 +// CHECK: } // end sil function 'double_cast' +sil [ossa] @double_cast : $@convention(thin) (@inout Int) -> Bool { +bb0(%0 : $*Int): + %1 = unchecked_addr_cast %0 to $*Float + %2 = unchecked_addr_cast %1 to $*Bool + %3 = load [trivial] %2 + return %3 +} + +// CHECK-LABEL: sil [ossa] @vector_base : +// CHECK: %1 = vector_base_addr %0 +// CHECK: %2 = load [trivial] %1 +// CHECK: } // end sil function 'vector_base' +sil [ossa] @vector_base : $@convention(thin) (@inout Builtin.FixedArray<10, Int>) -> Int { +bb0(%0 : $*Builtin.FixedArray<10, Int>): + %1 = unchecked_addr_cast %0 to $*Int + %2 = load [trivial] %1 + return %2 +} + +// CHECK-LABEL: sil [ossa] @vector_base_wrong_type : +// CHECK: %1 = unchecked_addr_cast %0 to $*Bool +// CHECK: %2 = load [trivial] %1 +// CHECK: } // end sil function 'vector_base_wrong_type' +sil [ossa] @vector_base_wrong_type : $@convention(thin) (@inout Builtin.FixedArray<10, Int>) -> Bool { +bb0(%0 : $*Builtin.FixedArray<10, Int>): + %1 = unchecked_addr_cast %0 to $*Bool + %2 = load [trivial] %1 + return %2 +} + +// CHECK-LABEL: sil [ossa] @vector_base_function_type : +// CHECK: %1 = vector_base_addr %0 +// CHECK: %2 = load [copy] %1 +// CHECK: } // end sil function 'vector_base_function_type' +sil [ossa] @vector_base_function_type : $@convention(thin) (@inout Builtin.FixedArray<10, ()->()>) -> @owned @callee_guaranteed @substituted <Ï„_0_0> () -> @out Ï„_0_0 for <()> { +bb0(%0 : $*Builtin.FixedArray<10, ()->()>): + %1 = unchecked_addr_cast %0 to $*@callee_guaranteed @substituted <Ï„_0_0> () -> @out Ï„_0_0 for <()> + %2 = load [copy] %1 + return %2 +} + diff --git a/test/SILOptimizer/specialize_opaque_type_archetypes.swift b/test/SILOptimizer/specialize_opaque_type_archetypes.swift index dfb75b3f02beb..bd64c80c5f2db 100644 --- a/test/SILOptimizer/specialize_opaque_type_archetypes.swift +++ b/test/SILOptimizer/specialize_opaque_type_archetypes.swift @@ -421,12 +421,12 @@ struct PAEM : P4EM { // CHECK: apply [[F]]([[V]]) // CHECK-64-LABEL: sil hidden @$s1A2PAV4testyyF : $@convention(method) (PA) -> () -// CHECK-64: [[V:%.*]] = integer_literal $Builtin.Int64, 5 -// CHECK-64: [[I:%.*]] = struct $Int64 ([[V]] : $Builtin.Int64) -// CHECK-64: [[F:%.*]] = function_ref @$s1A4usePyyxAA1PRzlFs5Int64V_Tg5 -// CHECK-64: apply [[F]]([[I]]) : $@convention(thin) (Int64) -> () -// CHECK-64: apply [[F]]([[I]]) : $@convention(thin) (Int64) -> () - +// CHECK-64: [[V:%.*]] = integer_literal $Builtin.Int64, 5 +// CHECK-64-DAG: [[I:%.*]] = struct $Int64 ([[V]] : $Builtin.Int64) +// CHECK-64-DAG: [[F:%.*]] = function_ref @$s1A4usePyyxAA1PRzlFs5Int64V_Tg5 +// CHECK-64: apply [[F]]([[I]]) : $@convention(thin) (Int64) -> () +// CHECK-64: apply [[F]]([[I]]) : $@convention(thin) (Int64) -> () +// CHECK-64: } // end sil function '$s1A2PAV4testyyF' @inline(never) func testIt(cl: (Int64) throws -> T) { do { diff --git a/test/SILOptimizer/specialize_self_conforming.swift b/test/SILOptimizer/specialize_self_conforming.swift index 40aea0ce9bbb3..50421f0623530 100644 --- a/test/SILOptimizer/specialize_self_conforming.swift +++ b/test/SILOptimizer/specialize_self_conforming.swift @@ -5,14 +5,26 @@ import Foundation -@objc protocol P {} +@objc protocol P: Q { + func foo() +} + +@objc protocol Q { + func bar() +} + +@_optimize(none) +func takesP(_ t: T) {} @_optimize(none) -func takesP(_: T) {} +func takesQ(_ t: T) {} @inline(__always) func callsTakesP(_ t: T) { takesP(t) + takesQ(t) + t.foo() + t.bar() } // CHECK-LABEL: sil hidden @$s26specialize_self_conforming16callsTakesPWithPyyAA1P_pF : $@convention(thin) (@guaranteed any P) -> () { diff --git a/test/SILOptimizer/static_inline_arrays.swift b/test/SILOptimizer/static_inline_arrays.swift index 9009913c87c60..a5af2dd878b35 100644 --- a/test/SILOptimizer/static_inline_arrays.swift +++ b/test/SILOptimizer/static_inline_arrays.swift @@ -25,18 +25,21 @@ struct IntByteAndByte { struct S { // CHECK-LABEL: sil_global hidden [let] @$s4test1SV6simples11InlineArrayVy$2_SiGvpZ : $InlineArray<3, Int> = { - // CHECK: %initval = vector + // CHECK: [[V:%.*]] = vector + // CHECK: %initval = struct $InlineArray<3, Int> ([[V]]) // CHECK: } static let simple: InlineArray = [1, 2, 3] // CHECK-LABEL: sil_global hidden [let] @$s4test1SV12optionalIntss11InlineArrayVy$2_SiSgGvpZ : $InlineArray<3, Optional> = { - // CHECK: %initval = vector + // CHECK: [[V:%.*]] = vector + // CHECK: %initval = struct $InlineArray<3, Optional> ([[V]]) // CHECK: } static let optionalInts: InlineArray<_, Int?> = [10, 20, 30] // CHECK-LABEL: sil_global hidden [let] @$s4test1SV13optionalArrays06InlineC0Vy$2_SiGSgvpZ : $Optional> = { // CHECK: [[V:%.*]] = vector - // CHECK: %initval = enum $Optional>, #Optional.some!enumelt, [[V]] + // CHECK: [[A:%.*]] = struct $InlineArray<3, Int> ([[V]]) + // CHECK: %initval = enum $Optional>, #Optional.some!enumelt, [[A]] // CHECK: } static let optionalArray: InlineArray? = [1, 2, 3] @@ -44,13 +47,15 @@ struct S { // CHECK: [[S0:%.*]] = struct $IntByte // CHECK: [[S1:%.*]] = struct $IntByte // CHECK: [[S2:%.*]] = struct $IntByte - // CHECK: %initval = vector ([[S0]], [[S1]], [[S2]]) + // CHECK: [[V:%.*]] = vector ([[S0]], [[S1]], [[S2]]) + // CHECK: %initval = struct $InlineArray<3, IntByte> ([[V]]) // CHECK: } static let intBytePairs: InlineArray<_, IntByte> = [IntByte(i: 1, b: 2), IntByte(i: 3, b: 4), IntByte(i: 5, b: 6)] // CHECK-LABEL: sil_global hidden [let] @$s4test1SV26optionalInlineArrayOfPairss0cD0Vy$2_AA7IntByteVGSgvpZ : $Optional> = { // CHECK: [[V:%.*]] = vector - // CHECK: %initval = enum $Optional>, #Optional.some!enumelt, [[V]] + // CHECK: [[A:%.*]] = struct $InlineArray<3, IntByte> ([[V]]) + // CHECK: %initval = enum $Optional>, #Optional.some!enumelt, [[A]] // CHECK: } static let optionalInlineArrayOfPairs: InlineArray<_, IntByte>? = [IntByte(i: 11, b: 12), IntByte(i: 13, b: 14), IntByte(i: 15, b: 16)] @@ -58,21 +63,27 @@ struct S { // CHECK: [[T0:%.*]] = tuple // CHECK: [[T1:%.*]] = tuple // CHECK: [[T2:%.*]] = tuple - // CHECK: %initval = vector ([[T0]], [[T1]], [[T2]]) + // CHECK: [[V:%.*]] = vector ([[T0]], [[T1]], [[T2]]) + // CHECK: %initval = struct $InlineArray<3, (Int, Int)> ([[V]]) // CHECK: } static let tuples: InlineArray = [(10, 20), (30, 40), (50, 60)] // CHECK-LABEL: sil_global hidden [let] @$s4test1SV6nesteds11InlineArrayVy$2_AFy$1_SiGGvpZ : $InlineArray<3, InlineArray<2, Int>> = { // CHECK: [[V0:%.*]] = vector + // CHECK: [[A0:%.*]] = struct $InlineArray<2, Int> ([[V0]]) // CHECK: [[V1:%.*]] = vector + // CHECK: [[A1:%.*]] = struct $InlineArray<2, Int> ([[V1]]) // CHECK: [[V2:%.*]] = vector - // CHECK: %initval = vector ([[V0]], [[V1]], [[V2]]) + // CHECK: [[A2:%.*]] = struct $InlineArray<2, Int> ([[V2]]) + // CHECK: [[V:%.*]] = vector ([[A0]], [[A1]], [[A2]]) + // CHECK: %initval = struct $InlineArray<3, InlineArray<2, Int>> ([[V]]) // CHECK: } static let nested: InlineArray<3, InlineArray<2, Int>> = [[100, 200], [300, 400], [500, 600]] // CHECK-LABEL: sil_global hidden [let] @$s4test1SV010intByteAndC0AA03IntcdC0VvpZ : $IntByteAndByte = { // CHECK: [[V:%.*]] = vector - // CHECK: %initval = struct $IntByteAndByte ([[V]], + // CHECK: [[A:%.*]] = struct $InlineArray<3, IntByte> ([[V]]) + // CHECK: %initval = struct $IntByteAndByte ([[A]], // CHECK: } static let intByteAndByte = IntByteAndByte(a: [IntByte(i: 1, b: 2), IntByte(i: 3, b: 4), IntByte(i: 5, b: 6)], x: 27) } diff --git a/test/SILOptimizer/temp_rvalue_opt.sil b/test/SILOptimizer/temp_rvalue_opt.sil index 3ddaae8dfc38d..c7924fa07b6b1 100644 --- a/test/SILOptimizer/temp_rvalue_opt.sil +++ b/test/SILOptimizer/temp_rvalue_opt.sil @@ -827,3 +827,18 @@ bb0: return %12 } +// CHECK-LABEL: sil @store_to_temp : +// CHECK: %1 = load %0 +// CHECK-NEXT: return %1 +// CHECK-LABEL: } // end sil function 'store_to_temp' +sil @store_to_temp : $@convention(thin) (@in_guaranteed Klass) -> @owned Klass { +bb0(%0 : $*Klass): + %1 = load %0 + %2 = alloc_stack $Klass + store %1 to %2 + %4 = load %2 + destroy_addr %2 + dealloc_stack %2 + return %4 +} + diff --git a/test/SILOptimizer/temp_rvalue_opt_ossa.sil b/test/SILOptimizer/temp_rvalue_opt_ossa.sil index 32dc0ebb382a1..5c8f67019eeff 100644 --- a/test/SILOptimizer/temp_rvalue_opt_ossa.sil +++ b/test/SILOptimizer/temp_rvalue_opt_ossa.sil @@ -1472,3 +1472,119 @@ bb0(%0 : $*P): %15 = tuple () return %15 } + +// CHECK-LABEL: sil [ossa] @store_to_temp : +// CHECK: %1 = load [copy] %0 +// CHECK-NEXT: return %1 +// CHECK-LABEL: } // end sil function 'store_to_temp' +sil [ossa] @store_to_temp : $@convention(thin) (@in_guaranteed Klass) -> @owned Klass { +bb0(%0 : $*Klass): + %1 = load [copy] %0 + %2 = alloc_stack $Klass + store %1 to [init] %2 + %4 = load [copy] %2 + destroy_addr %2 + dealloc_stack %2 + return %4 +} + +// CHECK-LABEL: sil [ossa] @store_to_temp_take : +// CHECK: %1 = load [copy] %0 +// CHECK-NEXT: destroy_addr %0 +// CHECK-NEXT: return %1 +// CHECK-LABEL: } // end sil function 'store_to_temp_take' +sil [ossa] @store_to_temp_take : $@convention(thin) (@in Klass) -> @owned Klass { +bb0(%0 : $*Klass): + %1 = load [take] %0 + %2 = alloc_stack $Klass + store %1 to [init] %2 + %4 = load [copy] %2 + destroy_addr %2 + dealloc_stack %2 + return %4 +} + +// CHECK-LABEL: sil [ossa] @store_to_temp_trivial : +// CHECK: %1 = load [trivial] %0 +// CHECK-NEXT: return %1 +// CHECK-LABEL: } // end sil function 'store_to_temp_trivial' +sil [ossa] @store_to_temp_trivial : $@convention(thin) (@in_guaranteed Int) -> @owned Int { +bb0(%0 : $*Int): + %1 = load [trivial] %0 + %2 = alloc_stack $Int + store %1 to [trivial] %2 + %4 = load [trivial] %2 + destroy_addr %2 + dealloc_stack %2 + return %4 +} + +// CHECK-LABEL: sil [ossa] @store_with_early_destroy_of_src : +// CHECK: alloc_stack +// CHECK-NEXT: store %1 +// CHECK-LABEL: } // end sil function 'store_with_early_destroy_of_src' +sil [ossa] @store_with_early_destroy_of_src : $@convention(thin) (@in Klass) -> @owned Klass { +bb0(%0 : $*Klass): + %1 = load [copy] %0 + fix_lifetime %0 + destroy_addr %0 + %2 = alloc_stack $Klass + store %1 to [init] %2 + %4 = load [copy] %2 + destroy_addr %2 + dealloc_stack %2 + return %4 +} + +// CHECK-LABEL: sil [ossa] @store_with_load_in_different_block : +// CHECK: alloc_stack +// CHECK-NEXT: store %1 +// CHECK-LABEL: } // end sil function 'store_with_load_in_different_block' +sil [ossa] @store_with_load_in_different_block : $@convention(thin) (@in Klass) -> @owned Klass { +bb0(%0 : $*Klass): + %1 = load [copy] %0 + br bb1 +bb1: + fix_lifetime %0 + destroy_addr %0 + br bb2 +bb2: + %2 = alloc_stack $Klass + store %1 to [init] %2 + %4 = load [copy] %2 + destroy_addr %2 + dealloc_stack %2 + return %4 +} + +// CHECK-LABEL: sil [ossa] @store_with_load_with_multiple_uses : +// CHECK: fix_lifetime +// CHECK: alloc_stack +// CHECK-NEXT: store %1 +// CHECK-LABEL: } // end sil function 'store_with_load_with_multiple_uses' +sil [ossa] @store_with_load_with_multiple_uses : $@convention(thin) (@in_guaranteed Klass) -> @owned Klass { +bb0(%0 : $*Klass): + %1 = load [copy] %0 + fix_lifetime %1 + %2 = alloc_stack $Klass + store %1 to [init] %2 + %4 = load [copy] %2 + destroy_addr %2 + dealloc_stack %2 + return %4 +} + +// CHECK-LABEL: sil [ossa] @store_without_load : +// CHECK: alloc_stack +// CHECK-NEXT: store %0 +// CHECK-LABEL: } // end sil function 'store_without_load' +sil [ossa] @store_without_load : $@convention(thin) (@owned Klass) -> @owned Klass { +bb0(%0 : @owned $Klass): + %2 = alloc_stack $Klass + store %0 to [init] %2 + %4 = load [copy] %2 + destroy_addr %2 + dealloc_stack %2 + return %4 +} + diff --git a/test/Sema/copyable_constraint_defaulting_with_same_type_constraints.swift b/test/Sema/copyable_constraint_defaulting_with_same_type_constraints.swift new file mode 100644 index 0000000000000..70500917b2469 --- /dev/null +++ b/test/Sema/copyable_constraint_defaulting_with_same_type_constraints.swift @@ -0,0 +1,77 @@ +// RUN: %target-swift-frontend -typecheck -verify %s + +struct Bar: ~Copyable {} + +struct Foo { + func foo() -> T { fatalError() } +} + +extension Foo where T == Bar { + func bar() -> Bar { + return foo() + } +} + +struct Foo2 { + func foo1() -> T { fatalError() } + func foo2() -> U { fatalError() } +} + +extension Foo2 where T == Bar, U == Bar { + func bar1_1() -> Bar { + return foo1() + } + func bar1_2() -> Bar { + return foo2() + } +} + +extension Foo2 where T == U, U == Bar { + func bar2_1() -> Bar { + return foo1() + } + func bar2_2() -> Bar { + return foo2() + } +} + +extension Foo2 where T == Bar, U == T { + func bar3_1() -> Bar { + return foo1() + } + func bar3_2() -> Bar { + return foo2() + } +} + +func needsCopyable(_: T) {} + +// T and U are still Copyable by default here, since the equivalence class of +// the same-type-constrained parameters is entirely within the scope of the +// extension, and there is no explicit suppression of the default. +extension Foo2 where T == U { + func test(_ x: T) { + needsCopyable(x) + } +} + +// Explicitly suppressing Copyable on one type parameter also prevents the other +// parameters in the equivalence class from defaulting to Copyable. +extension Foo2 where T == U, T: ~Copyable { + func bar4_1() -> T { + return foo1() + } + func bar4_2() -> T { + return foo2() + } +} + +extension Foo2 where T == U, U: ~Copyable { + func bar5_1() -> T { + return foo1() + } + func bar5_2() -> T { + return foo2() + } +} + diff --git a/test/Serialization/Inputs/def_basic.sil b/test/Serialization/Inputs/def_basic.sil index bc78012a84e3b..35b2ca427caf3 100644 --- a/test/Serialization/Inputs/def_basic.sil +++ b/test/Serialization/Inputs/def_basic.sil @@ -120,6 +120,16 @@ bb0(%0 : $Int): // CHECK: bb0(%0 : $Int): return %3 : $Int // CHECK: return {{.*}} : $Int } +// CHECK-LABEL: sil public_external @vector_base_addr : +// CHECK: %1 = vector_base_addr %0 : $*Builtin.FixedArray<10, Int> +// CHECK-LABEL: } // end sil function 'vector_base_addr' +sil [serialized] @vector_base_addr : $@convention(thin) (@inout Builtin.FixedArray<10, Int>) -> Int { +bb0(%0 : $*Builtin.FixedArray<10, Int>): + %1 = vector_base_addr %0 + %2 = load %1 + return %2 +} + // CHECK-LABEL: @call_fn_pointer : $@convention(thin) (() -> Int) -> Int { sil [transparent] [serialized] @call_fn_pointer : $@convention(thin) (() -> Int) -> Int { bb0(%0 : $() -> Int): @@ -1528,6 +1538,7 @@ bb0: %4 = function_ref @test2 : $@convention(thin) (Int) -> () %6 = function_ref @named_tuple : $@convention(thin) () -> (Builtin.Word, Builtin.Word) %9 = function_ref @return_int : $@convention(thin) (Int) -> Int + %10 = function_ref @vector_base_addr : $@convention(thin) (@inout Builtin.FixedArray<10, Int>) -> Int %11 = function_ref @call_fn_pointer : $@convention(thin) (() -> Int) -> Int %13 = function_ref @return_constant : $@convention(thin) () -> Int %23 = function_ref @existentials : $@convention(thin) (@in P) -> () diff --git a/test/SourceKit/Misc/rdar98880399.swift b/test/SourceKit/Misc/rdar98880399.swift new file mode 100644 index 0000000000000..541bfe797797a --- /dev/null +++ b/test/SourceKit/Misc/rdar98880399.swift @@ -0,0 +1,4 @@ +// Make sure we don't create any temporary files. +// RUN: %empty-directory(%t) +// RUN: env TMP=%t TMPDIR=%t %sourcekitd-test -req=open %s -- %s -driver-force-response-files +// RUN: not ls %t/* >/dev/null 2>&1 diff --git a/test/Unsafe/safe.swift b/test/Unsafe/safe.swift index 5c41f37c4534f..acaea12e5bd68 100644 --- a/test/Unsafe/safe.swift +++ b/test/Unsafe/safe.swift @@ -200,6 +200,8 @@ func unsafeFun() { _ = color if unsafe { } + + _ = unsafe ? 1 : 0 } func moreUnsafeFunc(unsafe: [Int]) { @@ -218,6 +220,13 @@ func yetMoreUnsafeFunc(unsafe: () -> Void) { // expected-warning@-1{{no unsafe operations occur within 'unsafe' expression}} } +func yetMoreMoreUnsafeFunc(unsafe: Int?) { + _ = unsafe! + if let unsafe { + _ = unsafe + 1 + } +} + // @safe suppresses unsafe-type-related diagnostics on an entity struct MyArray { @safe func withUnsafeBufferPointer( diff --git a/test/abi/Inputs/macOS/arm64/concurrency/baseline b/test/abi/Inputs/macOS/arm64/concurrency/baseline index 8aa55b3098c58..002cd69dc8e7d 100644 --- a/test/abi/Inputs/macOS/arm64/concurrency/baseline +++ b/test/abi/Inputs/macOS/arm64/concurrency/baseline @@ -23,8 +23,8 @@ _$sScEMa _$sScEMn _$sScEN _$sScEs5ErrorsMc -_$sScF14isMainExecutorSbvgTj -_$sScF14isMainExecutorSbvgTq +_$sScF15_isMainExecutorSbvgTj +_$sScF15_isMainExecutorSbvgTq _$sScF7enqueueyyScJFTj _$sScF7enqueueyyScJFTq _$sScF7enqueueyys11ExecutorJobVnFTj @@ -33,8 +33,8 @@ _$sScF7enqueueyys3JobVnFTj _$sScF7enqueueyys3JobVnFTq _$sScFMp _$sScFTL -_$sScFsE14isMainExecutorSbvg -_$sScFsE14isMainExecutorSbvpMV +_$sScFsE15_isMainExecutorSbvg +_$sScFsE15_isMainExecutorSbvpMV _$sScFsE18_isComplexEqualitySbvg _$sScFsE18_isComplexEqualitySbvpMV _$sScFsE7enqueueyyScJF @@ -96,8 +96,8 @@ _$sScM3run10resultType4bodyxxm_xyYbKScMYcXEtYaKlFZ _$sScM3run10resultType4bodyxxm_xyYbKScMYcXEtYaKlFZTu _$sScM6sharedScMvgZ _$sScM7enqueueyyScJF -_$sScM8executors12MainExecutor_pvgZ -_$sScM8executors12MainExecutor_pvpZMV +_$sScM9_executors13_MainExecutor_pvgZ +_$sScM9_executors13_MainExecutor_pvpZMV _$sScMMa _$sScMMm _$sScMMn @@ -211,16 +211,16 @@ _$sScTss5NeverORs_rlE5valuexvgTu _$sScTss5NeverORs_rlE5valuexvpMV _$sScTss5NeverORszABRs_rlE11isCancelledSbvgZ _$sScTss5NeverORszABRs_rlE12basePriorityScPSgvgZ -_$sScTss5NeverORszABRs_rlE15currentExecutorScF_pvgZ -_$sScTss5NeverORszABRs_rlE15currentExecutorScF_pvpZMV _$sScTss5NeverORszABRs_rlE15currentPriorityScPvgZ -_$sScTss5NeverORszABRs_rlE15defaultExecutorSch_pvgZ -_$sScTss5NeverORszABRs_rlE15defaultExecutorSch_pvpZMV +_$sScTss5NeverORszABRs_rlE16_currentExecutorScF_pvgZ +_$sScTss5NeverORszABRs_rlE16_currentExecutorScF_pvpZMV +_$sScTss5NeverORszABRs_rlE16_defaultExecutorSch_pvgZ +_$sScTss5NeverORszABRs_rlE16_defaultExecutorSch_pvpZMV _$sScTss5NeverORszABRs_rlE17checkCancellationyyKFZ -_$sScTss5NeverORszABRs_rlE17preferredExecutorSch_pSgvgZ -_$sScTss5NeverORszABRs_rlE17preferredExecutorSch_pSgvpZMV -_$sScTss5NeverORszABRs_rlE26currentSchedulableExecutors0cD0_pSgvgZ -_$sScTss5NeverORszABRs_rlE26currentSchedulableExecutors0cD0_pSgvpZMV +_$sScTss5NeverORszABRs_rlE18_preferredExecutorSch_pSgvgZ +_$sScTss5NeverORszABRs_rlE18_preferredExecutorSch_pSgvpZMV +_$sScTss5NeverORszABRs_rlE27_currentSchedulableExecutors01_cD0_pSgvgZ +_$sScTss5NeverORszABRs_rlE27_currentSchedulableExecutors01_cD0_pSgvpZMV _$sScTss5NeverORszABRs_rlE5sleep11nanosecondsys6UInt64V_tYaKFZ _$sScTss5NeverORszABRs_rlE5sleep11nanosecondsys6UInt64V_tYaKFZTu _$sScTss5NeverORszABRs_rlE5sleep5until9tolerance5clocky7InstantQyd___8DurationQyd__Sgqd__tYaKs5ClockRd__lFZ @@ -238,7 +238,7 @@ _$sScc7contextBcvs _$sSccMa _$sSccMn _$sSce15complexEqualityScexh_tcScfRzlufC -_$sSce16asSerialExecutorScf_pSgyF +_$sSce17_asSerialExecutorScf_pSgyF _$sSce18_isComplexEqualitySbvg _$sSce18_isComplexEqualitySbvpMV _$sSce8executorBevM @@ -267,8 +267,8 @@ _$sScfMp _$sScfScFTb _$sScfTL _$sScfsE14assertIsolated_4file4lineySSyXK_s12StaticStringVSutF -_$sScfsE14isMainExecutorSbvg -_$sScfsE14isMainExecutorSbvpMV +_$sScfsE15_isMainExecutorSbvg +_$sScfsE15_isMainExecutorSbvpMV _$sScfsE20preconditionIsolated_4file4lineySSyXK_s12StaticStringVSutF _$sScfsE23asUnownedSerialExecutorSceyF _$sScfsE31isSameExclusiveExecutionContext5otherSbx_tF @@ -405,24 +405,7 @@ _$sSctN _$sSctSHsMc _$sSctSQsMc _$ss039_checkIllegalTaskLocalBindingWithinWithC5Group4file4lineySS_SutF -_$ss11ClockTraitsV10continuousABvgZ -_$ss11ClockTraitsV10continuousABvpZMV -_$ss11ClockTraitsV8rawValueABs6UInt32V_tcfC -_$ss11ClockTraitsV8rawValues6UInt32Vvg -_$ss11ClockTraitsV8rawValues6UInt32VvpMV -_$ss11ClockTraitsV8wallTimeABvgZ -_$ss11ClockTraitsV8wallTimeABvpZMV -_$ss11ClockTraitsV9monotonicABvgZ -_$ss11ClockTraitsV9monotonicABvpZMV -_$ss11ClockTraitsVMa -_$ss11ClockTraitsVMn -_$ss11ClockTraitsVN -_$ss11ClockTraitsVSQsMc -_$ss11ClockTraitsVSYsMc -_$ss11ClockTraitsVs10SetAlgebrasMc -_$ss11ClockTraitsVs25ExpressibleByArrayLiteralsMc -_$ss11ClockTraitsVs9OptionSetsMc -_$ss11ExecutorJobV010withUnsafeA11PrivateData4bodyxxSwq_YKXE_tq_YKs5ErrorR_r0_lF +_$ss11ExecutorJobV011_withUnsafeA11PrivateData4bodyxxSwq_YKXE_tq_YKs5ErrorR_r0_lF _$ss11ExecutorJobV11descriptionSSvg _$ss11ExecutorJobV14LocalAllocatorV10deallocateyySpyxGlF _$ss11ExecutorJobV14LocalAllocatorV10deallocateyySryxGlF @@ -433,20 +416,20 @@ _$ss11ExecutorJobV14LocalAllocatorV8allocate8capacitySwSi_tF _$ss11ExecutorJobV14LocalAllocatorVMa _$ss11ExecutorJobV14LocalAllocatorVMn _$ss11ExecutorJobV14LocalAllocatorVN -_$ss11ExecutorJobV4KindV13firstReservedADvgZ -_$ss11ExecutorJobV4KindV13firstReservedADvpZMV -_$ss11ExecutorJobV4KindV4taskADvgZ -_$ss11ExecutorJobV4KindV4taskADvpZMV -_$ss11ExecutorJobV4KindV8rawValueADSgs5UInt8V_tcfC -_$ss11ExecutorJobV4KindV8rawValues5UInt8VvM -_$ss11ExecutorJobV4KindV8rawValues5UInt8Vvg -_$ss11ExecutorJobV4KindV8rawValues5UInt8VvpMV -_$ss11ExecutorJobV4KindV8rawValues5UInt8Vvs -_$ss11ExecutorJobV4KindVMa -_$ss11ExecutorJobV4KindVMn -_$ss11ExecutorJobV4KindVN -_$ss11ExecutorJobV4KindVSYsMc -_$ss11ExecutorJobV4kindAB4KindVvg +_$ss11ExecutorJobV5_KindV13firstReservedADvgZ +_$ss11ExecutorJobV5_KindV13firstReservedADvpZMV +_$ss11ExecutorJobV5_KindV4taskADvgZ +_$ss11ExecutorJobV5_KindV4taskADvpZMV +_$ss11ExecutorJobV5_KindV8rawValueADSgs5UInt8V_tcfC +_$ss11ExecutorJobV5_KindV8rawValues5UInt8VvM +_$ss11ExecutorJobV5_KindV8rawValues5UInt8Vvg +_$ss11ExecutorJobV5_KindV8rawValues5UInt8VvpMV +_$ss11ExecutorJobV5_KindV8rawValues5UInt8Vvs +_$ss11ExecutorJobV5_KindVMa +_$ss11ExecutorJobV5_KindVMn +_$ss11ExecutorJobV5_KindVN +_$ss11ExecutorJobV5_KindVSYsMc +_$ss11ExecutorJobV5_kindAB5_KindVvg _$ss11ExecutorJobV7contextABBjn_tcfC _$ss11ExecutorJobV8prioritys0B8PriorityVvg _$ss11ExecutorJobV9allocatorAB14LocalAllocatorVSgvg @@ -480,33 +463,30 @@ _$ss11JobPriorityVMn _$ss11JobPriorityVN _$ss11JobPriorityVSLsMc _$ss11JobPriorityVSQsMc -_$ss12MainExecutorMp -_$ss12MainExecutorPScfTb -_$ss12MainExecutorPs07RunLoopB0Tb -_$ss12MainExecutorTL +_$ss12_ClockTraitsV10continuousABvgZ +_$ss12_ClockTraitsV10continuousABvpZMV +_$ss12_ClockTraitsV8rawValueABs6UInt32V_tcfC +_$ss12_ClockTraitsV8rawValues6UInt32Vvg +_$ss12_ClockTraitsV8rawValues6UInt32VvpMV +_$ss12_ClockTraitsV8wallTimeABvgZ +_$ss12_ClockTraitsV8wallTimeABvpZMV +_$ss12_ClockTraitsV9monotonicABvgZ +_$ss12_ClockTraitsV9monotonicABvpZMV +_$ss12_ClockTraitsVMa +_$ss12_ClockTraitsVMn +_$ss12_ClockTraitsVN +_$ss12_ClockTraitsVSQsMc +_$ss12_ClockTraitsVSYsMc +_$ss12_ClockTraitsVs10SetAlgebrasMc +_$ss12_ClockTraitsVs25ExpressibleByArrayLiteralsMc +_$ss12_ClockTraitsVs9OptionSetsMc +_$ss13_MainExecutorMp +_$ss13_MainExecutorPScfTb +_$ss13_MainExecutorPs08_RunLoopB0Tb +_$ss13_MainExecutorTL _$ss13_runAsyncMainyyyyYaKcF _$ss13withTaskGroup2of9returning4bodyq_xm_q_mq_ScGyxGzYaXEtYar0_lF _$ss13withTaskGroup2of9returning4bodyq_xm_q_mq_ScGyxGzYaXEtYar0_lFTu -_$ss14CFMainExecutorC3runyyKF -_$ss14CFMainExecutorC4stopyyF -_$ss14CFMainExecutorCABycfC -_$ss14CFMainExecutorCABycfc -_$ss14CFMainExecutorCMa -_$ss14CFMainExecutorCMm -_$ss14CFMainExecutorCMn -_$ss14CFMainExecutorCMo -_$ss14CFMainExecutorCN -_$ss14CFMainExecutorCfD -_$ss14CFMainExecutorCfd -_$ss14CFTaskExecutorCABycfC -_$ss14CFTaskExecutorCABycfc -_$ss14CFTaskExecutorCMa -_$ss14CFTaskExecutorCMm -_$ss14CFTaskExecutorCMn -_$ss14CFTaskExecutorCMo -_$ss14CFTaskExecutorCN -_$ss14CFTaskExecutorCfD -_$ss14CFTaskExecutorCfd _$ss15ContinuousClockV17minimumResolutions8DurationVvg _$ss15ContinuousClockV17minimumResolutions8DurationVvpMV _$ss15ContinuousClockV3nowAB7InstantVvg @@ -514,8 +494,6 @@ _$ss15ContinuousClockV3nowAB7InstantVvgZ _$ss15ContinuousClockV3nowAB7InstantVvpMV _$ss15ContinuousClockV5sleep5until9toleranceyAB7InstantV_s8DurationVSgtYaKF _$ss15ContinuousClockV5sleep5until9toleranceyAB7InstantV_s8DurationVSgtYaKFTu -_$ss15ContinuousClockV6traitss0B6TraitsVvg -_$ss15ContinuousClockV6traitss0B6TraitsVvpMV _$ss15ContinuousClockV7InstantV1loiySbAD_ADtFZ _$ss15ContinuousClockV7InstantV2eeoiySbAD_ADtFZ _$ss15ContinuousClockV7InstantV3nowADvgZ @@ -535,28 +513,14 @@ _$ss15ContinuousClockV7InstantVSLsMc _$ss15ContinuousClockV7InstantVSQsMc _$ss15ContinuousClockV7InstantVSesMc _$ss15ContinuousClockV7InstantVs0C8ProtocolsMc +_$ss15ContinuousClockV7_traitss01_B6TraitsVvg +_$ss15ContinuousClockV7_traitss01_B6TraitsVvpMV _$ss15ContinuousClockVABycfC _$ss15ContinuousClockVMa _$ss15ContinuousClockVMn _$ss15ContinuousClockVN _$ss15ContinuousClockVs0B0sMc _$ss15ContinuousClockVs0B0sWP -_$ss15ExecutorFactoryMp -_$ss15ExecutorFactoryP04mainA0s04MainA0_pvgZTj -_$ss15ExecutorFactoryP04mainA0s04MainA0_pvgZTq -_$ss15ExecutorFactoryP07defaultA0Sch_pvgZTj -_$ss15ExecutorFactoryP07defaultA0Sch_pvgZTq -_$ss15ExecutorFactoryTL -_$ss15RunLoopExecutorMp -_$ss15RunLoopExecutorP3runyyKFTj -_$ss15RunLoopExecutorP3runyyKFTq -_$ss15RunLoopExecutorP4stopyyFTj -_$ss15RunLoopExecutorP4stopyyFTq -_$ss15RunLoopExecutorP8runUntilyySbyXEKFTj -_$ss15RunLoopExecutorP8runUntilyySbyXEKFTq -_$ss15RunLoopExecutorPScFTb -_$ss15RunLoopExecutorPsE8runUntilyySbyXEKF -_$ss15RunLoopExecutorTL _$ss15SuspendingClockV17minimumResolutions8DurationVvg _$ss15SuspendingClockV17minimumResolutions8DurationVvpMV _$ss15SuspendingClockV3nowAB7InstantVvg @@ -564,8 +528,6 @@ _$ss15SuspendingClockV3nowAB7InstantVvgZ _$ss15SuspendingClockV3nowAB7InstantVvpMV _$ss15SuspendingClockV5sleep5until9toleranceyAB7InstantV_s8DurationVSgtYaKF _$ss15SuspendingClockV5sleep5until9toleranceyAB7InstantV_s8DurationVSgtYaKFTu -_$ss15SuspendingClockV6traitss0B6TraitsVvg -_$ss15SuspendingClockV6traitss0B6TraitsVvpMV _$ss15SuspendingClockV7InstantV1loiySbAD_ADtFZ _$ss15SuspendingClockV7InstantV1poiyA2D_s8DurationVtFZ _$ss15SuspendingClockV7InstantV1soiyA2D_s8DurationVtFZ @@ -590,12 +552,34 @@ _$ss15SuspendingClockV7InstantVSLsMc _$ss15SuspendingClockV7InstantVSQsMc _$ss15SuspendingClockV7InstantVSesMc _$ss15SuspendingClockV7InstantVs0C8ProtocolsMc +_$ss15SuspendingClockV7_traitss01_B6TraitsVvg +_$ss15SuspendingClockV7_traitss01_B6TraitsVvpMV _$ss15SuspendingClockVABycfC _$ss15SuspendingClockVMa _$ss15SuspendingClockVMn _$ss15SuspendingClockVN _$ss15SuspendingClockVs0B0sMc _$ss15SuspendingClockVs0B0sWP +_$ss15_CFMainExecutorC4_runyyKF +_$ss15_CFMainExecutorC5_stopyyF +_$ss15_CFMainExecutorCABycfC +_$ss15_CFMainExecutorCABycfc +_$ss15_CFMainExecutorCMa +_$ss15_CFMainExecutorCMm +_$ss15_CFMainExecutorCMn +_$ss15_CFMainExecutorCMo +_$ss15_CFMainExecutorCN +_$ss15_CFMainExecutorCfD +_$ss15_CFMainExecutorCfd +_$ss15_CFTaskExecutorCABycfC +_$ss15_CFTaskExecutorCABycfc +_$ss15_CFTaskExecutorCMa +_$ss15_CFTaskExecutorCMm +_$ss15_CFTaskExecutorCMn +_$ss15_CFTaskExecutorCMo +_$ss15_CFTaskExecutorCN +_$ss15_CFTaskExecutorCfD +_$ss15_CFTaskExecutorCfd _$ss16AsyncMapSequenceV04makeA8IteratorAB0E0Vyxq__GyF _$ss16AsyncMapSequenceV4basexvg _$ss16AsyncMapSequenceV4basexvpMV @@ -617,51 +601,67 @@ _$ss16AsyncMapSequenceVMa _$ss16AsyncMapSequenceVMn _$ss16AsyncMapSequenceV_9transformAByxq_Gx_q_7ElementQzYactcfC _$ss16AsyncMapSequenceVyxq_GScisMc -_$ss17DummyMainExecutorC02isbC0Sbvg -_$ss17DummyMainExecutorC02isbC0SbvpMV -_$ss17DummyMainExecutorC13checkIsolatedyyF -_$ss17DummyMainExecutorC3runyyKF -_$ss17DummyMainExecutorC4stopyyF -_$ss17DummyMainExecutorC7enqueueyys0C3JobVnF -_$ss17DummyMainExecutorCABycfC -_$ss17DummyMainExecutorCABycfCTj -_$ss17DummyMainExecutorCABycfCTq -_$ss17DummyMainExecutorCABycfc -_$ss17DummyMainExecutorCMa -_$ss17DummyMainExecutorCMm -_$ss17DummyMainExecutorCMn -_$ss17DummyMainExecutorCMo -_$ss17DummyMainExecutorCMu -_$ss17DummyMainExecutorCN -_$ss17DummyMainExecutorCScFsMc -_$ss17DummyMainExecutorCScFsWP -_$ss17DummyMainExecutorCScfsMc -_$ss17DummyMainExecutorCScfsWP -_$ss17DummyMainExecutorCfD -_$ss17DummyMainExecutorCfd -_$ss17DummyMainExecutorCs07RunLoopC0sMc -_$ss17DummyMainExecutorCs07RunLoopC0sWP -_$ss17DummyMainExecutorCs0bC0sMc -_$ss17DummyMainExecutorCs0bC0sWP -_$ss17DummyTaskExecutorC06isMainC0Sbvg -_$ss17DummyTaskExecutorC06isMainC0SbvpMV -_$ss17DummyTaskExecutorC7enqueueyys0C3JobVnF -_$ss17DummyTaskExecutorCABycfC -_$ss17DummyTaskExecutorCABycfCTj -_$ss17DummyTaskExecutorCABycfCTq -_$ss17DummyTaskExecutorCABycfc -_$ss17DummyTaskExecutorCMa -_$ss17DummyTaskExecutorCMm -_$ss17DummyTaskExecutorCMn -_$ss17DummyTaskExecutorCMo -_$ss17DummyTaskExecutorCMu -_$ss17DummyTaskExecutorCN -_$ss17DummyTaskExecutorCScFsMc -_$ss17DummyTaskExecutorCScFsWP -_$ss17DummyTaskExecutorCSchsMc -_$ss17DummyTaskExecutorCSchsWP -_$ss17DummyTaskExecutorCfD -_$ss17DummyTaskExecutorCfd +_$ss16_ExecutorFactoryMp +_$ss16_ExecutorFactoryP04mainA0s05_MainA0_pvgZTj +_$ss16_ExecutorFactoryP04mainA0s05_MainA0_pvgZTq +_$ss16_ExecutorFactoryP07defaultA0Sch_pvgZTj +_$ss16_ExecutorFactoryP07defaultA0Sch_pvgZTq +_$ss16_ExecutorFactoryTL +_$ss16_RunLoopExecutorMp +_$ss16_RunLoopExecutorP4_runyyKFTj +_$ss16_RunLoopExecutorP4_runyyKFTq +_$ss16_RunLoopExecutorP5_stopyyFTj +_$ss16_RunLoopExecutorP5_stopyyFTq +_$ss16_RunLoopExecutorP9_runUntilyySbyXEKFTj +_$ss16_RunLoopExecutorP9_runUntilyySbyXEKFTq +_$ss16_RunLoopExecutorPScFTb +_$ss16_RunLoopExecutorPsE9_runUntilyySbyXEKF +_$ss16_RunLoopExecutorTL +_$ss18_DummyMainExecutorC03_isbC0Sbvg +_$ss18_DummyMainExecutorC03_isbC0SbvpMV +_$ss18_DummyMainExecutorC13checkIsolatedyyF +_$ss18_DummyMainExecutorC4_runyyKF +_$ss18_DummyMainExecutorC5_stopyyF +_$ss18_DummyMainExecutorC7enqueueyys0C3JobVnF +_$ss18_DummyMainExecutorCABycfC +_$ss18_DummyMainExecutorCABycfCTj +_$ss18_DummyMainExecutorCABycfCTq +_$ss18_DummyMainExecutorCABycfc +_$ss18_DummyMainExecutorCMa +_$ss18_DummyMainExecutorCMm +_$ss18_DummyMainExecutorCMn +_$ss18_DummyMainExecutorCMo +_$ss18_DummyMainExecutorCMu +_$ss18_DummyMainExecutorCN +_$ss18_DummyMainExecutorCScFsMc +_$ss18_DummyMainExecutorCScFsWP +_$ss18_DummyMainExecutorCScfsMc +_$ss18_DummyMainExecutorCScfsWP +_$ss18_DummyMainExecutorCfD +_$ss18_DummyMainExecutorCfd +_$ss18_DummyMainExecutorCs01_bC0sMc +_$ss18_DummyMainExecutorCs01_bC0sWP +_$ss18_DummyMainExecutorCs08_RunLoopC0sMc +_$ss18_DummyMainExecutorCs08_RunLoopC0sWP +_$ss18_DummyTaskExecutorC07_isMainC0Sbvg +_$ss18_DummyTaskExecutorC07_isMainC0SbvpMV +_$ss18_DummyTaskExecutorC7enqueueyys0C3JobVnF +_$ss18_DummyTaskExecutorCABycfC +_$ss18_DummyTaskExecutorCABycfCTj +_$ss18_DummyTaskExecutorCABycfCTq +_$ss18_DummyTaskExecutorCABycfc +_$ss18_DummyTaskExecutorCMa +_$ss18_DummyTaskExecutorCMm +_$ss18_DummyTaskExecutorCMn +_$ss18_DummyTaskExecutorCMo +_$ss18_DummyTaskExecutorCMu +_$ss18_DummyTaskExecutorCN +_$ss18_DummyTaskExecutorCScFsMc +_$ss18_DummyTaskExecutorCScFsWP +_$ss18_DummyTaskExecutorCSchsMc +_$ss18_DummyTaskExecutorCSchsWP +_$ss18_DummyTaskExecutorCfD +_$ss18_DummyTaskExecutorCfd _$ss19AsyncFilterSequenceV04makeA8IteratorAB0E0Vyx_GyF _$ss19AsyncFilterSequenceV10isIncludedySb7ElementQzYacvg _$ss19AsyncFilterSequenceV10isIncludedySb7ElementQzYacvpMV @@ -719,16 +719,7 @@ _$ss19DiscardingTaskGroupV9cancelAllyyF _$ss19DiscardingTaskGroupVMa _$ss19DiscardingTaskGroupVMn _$ss19DiscardingTaskGroupVN -_$ss19SchedulableExecutorMp -_$ss19SchedulableExecutorP7enqueue_2at9tolerance5clockys0B3JobVn_7InstantQyd__8DurationQyd__Sgqd__ts5ClockRd__lFTj -_$ss19SchedulableExecutorP7enqueue_2at9tolerance5clockys0B3JobVn_7InstantQyd__8DurationQyd__Sgqd__ts5ClockRd__lFTq -_$ss19SchedulableExecutorP7enqueue_5after9tolerance5clockys0B3JobVn_8DurationQyd__AJSgqd__ts5ClockRd__lFTj -_$ss19SchedulableExecutorP7enqueue_5after9tolerance5clockys0B3JobVn_8DurationQyd__AJSgqd__ts5ClockRd__lFTq -_$ss19SchedulableExecutorPScFTb -_$ss19SchedulableExecutorPsE7enqueue_2at9tolerance5clockys0B3JobVn_7InstantQyd__8DurationQyd__Sgqd__ts5ClockRd__lF -_$ss19SchedulableExecutorPsE7enqueue_5after9tolerance5clockys0B3JobVn_8DurationQyd__AJSgqd__ts5ClockRd__lF -_$ss19SchedulableExecutorTL -_$ss19UnownedTaskExecutorV02asbC0Sch_pSgyF +_$ss19UnownedTaskExecutorV03_asbC0Sch_pSgyF _$ss19UnownedTaskExecutorVyABxhcSchRzlufC _$ss20AsyncFlatMapSequenceV04makeA8IteratorAB0F0Vyxq__GyF _$ss20AsyncFlatMapSequenceV4basexvg @@ -759,39 +750,48 @@ _$ss20AsyncFlatMapSequenceVMa _$ss20AsyncFlatMapSequenceVMn _$ss20AsyncFlatMapSequenceV_9transformAByxq_Gx_q_7ElementQzYactcfC _$ss20AsyncFlatMapSequenceVyxq_GScisMc -_$ss20DispatchMainExecutorC02isbC0Sbvg -_$ss20DispatchMainExecutorC02isbC0SbvpMV -_$ss20DispatchMainExecutorC13asSchedulables0eC0_pSgvg -_$ss20DispatchMainExecutorC13asSchedulables0eC0_pSgvpMV -_$ss20DispatchMainExecutorC13checkIsolatedyyF -_$ss20DispatchMainExecutorC3runyyKFTj -_$ss20DispatchMainExecutorC3runyyKFTq -_$ss20DispatchMainExecutorC4stopyyFTj -_$ss20DispatchMainExecutorC4stopyyFTq -_$ss20DispatchMainExecutorC7enqueue_2at9tolerance5clockys0C3JobVn_7InstantQz8DurationQzSgxts5ClockRzlF -_$ss20DispatchMainExecutorC7enqueueyys0C3JobVnF -_$ss20DispatchMainExecutorCABycfC -_$ss20DispatchMainExecutorCABycfCTj -_$ss20DispatchMainExecutorCABycfCTq -_$ss20DispatchMainExecutorCABycfc -_$ss20DispatchMainExecutorCMa -_$ss20DispatchMainExecutorCMm -_$ss20DispatchMainExecutorCMn -_$ss20DispatchMainExecutorCMo -_$ss20DispatchMainExecutorCMu -_$ss20DispatchMainExecutorCN -_$ss20DispatchMainExecutorCScFsMc -_$ss20DispatchMainExecutorCScFsWP -_$ss20DispatchMainExecutorCScfsMc -_$ss20DispatchMainExecutorCScfsWP -_$ss20DispatchMainExecutorCfD -_$ss20DispatchMainExecutorCfd -_$ss20DispatchMainExecutorCs011SchedulableC0sMc -_$ss20DispatchMainExecutorCs011SchedulableC0sWP -_$ss20DispatchMainExecutorCs07RunLoopC0sMc -_$ss20DispatchMainExecutorCs07RunLoopC0sWP -_$ss20DispatchMainExecutorCs0bC0sMc -_$ss20DispatchMainExecutorCs0bC0sWP +_$ss20_SchedulableExecutorMp +_$ss20_SchedulableExecutorP8_enqueue_2at9tolerance5clockys0B3JobVn_7InstantQyd__8DurationQyd__Sgqd__ts5ClockRd__lFTj +_$ss20_SchedulableExecutorP8_enqueue_2at9tolerance5clockys0B3JobVn_7InstantQyd__8DurationQyd__Sgqd__ts5ClockRd__lFTq +_$ss20_SchedulableExecutorP8_enqueue_5after9tolerance5clockys0B3JobVn_8DurationQyd__AJSgqd__ts5ClockRd__lFTj +_$ss20_SchedulableExecutorP8_enqueue_5after9tolerance5clockys0B3JobVn_8DurationQyd__AJSgqd__ts5ClockRd__lFTq +_$ss20_SchedulableExecutorPScFTb +_$ss20_SchedulableExecutorPsE8_enqueue_2at9tolerance5clockys0B3JobVn_7InstantQyd__8DurationQyd__Sgqd__ts5ClockRd__lF +_$ss20_SchedulableExecutorPsE8_enqueue_5after9tolerance5clockys0B3JobVn_8DurationQyd__AJSgqd__ts5ClockRd__lF +_$ss20_SchedulableExecutorTL +_$ss21_DispatchMainExecutorC03_isbC0Sbvg +_$ss21_DispatchMainExecutorC03_isbC0SbvpMV +_$ss21_DispatchMainExecutorC13checkIsolatedyyF +_$ss21_DispatchMainExecutorC14_asSchedulables01_eC0_pSgvg +_$ss21_DispatchMainExecutorC14_asSchedulables01_eC0_pSgvpMV +_$ss21_DispatchMainExecutorC4_runyyKFTj +_$ss21_DispatchMainExecutorC4_runyyKFTq +_$ss21_DispatchMainExecutorC5_stopyyFTj +_$ss21_DispatchMainExecutorC5_stopyyFTq +_$ss21_DispatchMainExecutorC7enqueueyys0C3JobVnF +_$ss21_DispatchMainExecutorC8_enqueue_2at9tolerance5clockys0C3JobVn_7InstantQz8DurationQzSgxts5ClockRzlF +_$ss21_DispatchMainExecutorCABycfC +_$ss21_DispatchMainExecutorCABycfCTj +_$ss21_DispatchMainExecutorCABycfCTq +_$ss21_DispatchMainExecutorCABycfc +_$ss21_DispatchMainExecutorCMa +_$ss21_DispatchMainExecutorCMm +_$ss21_DispatchMainExecutorCMn +_$ss21_DispatchMainExecutorCMo +_$ss21_DispatchMainExecutorCMu +_$ss21_DispatchMainExecutorCN +_$ss21_DispatchMainExecutorCScFsMc +_$ss21_DispatchMainExecutorCScFsWP +_$ss21_DispatchMainExecutorCScfsMc +_$ss21_DispatchMainExecutorCScfsWP +_$ss21_DispatchMainExecutorCfD +_$ss21_DispatchMainExecutorCfd +_$ss21_DispatchMainExecutorCs012_SchedulableC0sMc +_$ss21_DispatchMainExecutorCs012_SchedulableC0sWP +_$ss21_DispatchMainExecutorCs01_bC0sMc +_$ss21_DispatchMainExecutorCs01_bC0sWP +_$ss21_DispatchMainExecutorCs08_RunLoopC0sMc +_$ss21_DispatchMainExecutorCs08_RunLoopC0sWP _$ss21withThrowingTaskGroup2of9returning4bodyq_xm_q_mq_Scgyxs5Error_pGzYaKXEtYaKr0_lF _$ss21withThrowingTaskGroup2of9returning4bodyq_xm_q_mq_Scgyxs5Error_pGzYaKXEtYaKr0_lFTu _$ss21withUnsafeCurrentTask4bodyxxSctSgKXE_tKlF @@ -864,15 +864,6 @@ _$ss23AsyncCompactMapSequenceVMa _$ss23AsyncCompactMapSequenceVMn _$ss23AsyncCompactMapSequenceV_9transformAByxq_Gx_q_Sg7ElementQzYactcfC _$ss23AsyncCompactMapSequenceVyxq_GScisMc -_$ss23PlatformExecutorFactoryV04mainB0s04MainB0_pvgZ -_$ss23PlatformExecutorFactoryV04mainB0s04MainB0_pvpZMV -_$ss23PlatformExecutorFactoryV07defaultB0Sch_pvgZ -_$ss23PlatformExecutorFactoryV07defaultB0Sch_pvpZMV -_$ss23PlatformExecutorFactoryVMa -_$ss23PlatformExecutorFactoryVMn -_$ss23PlatformExecutorFactoryVN -_$ss23PlatformExecutorFactoryVs0bC0sMc -_$ss23PlatformExecutorFactoryVs0bC0sWP _$ss23withCheckedContinuation8function_xSS_yScCyxs5NeverOGXEtYalF _$ss23withCheckedContinuation8function_xSS_yScCyxs5NeverOGXEtYalFTu _$ss23withDiscardingTaskGroup9returning4bodyxxm_xs0bcD0VzYaXEtYalF @@ -927,31 +918,15 @@ _$ss24AsyncThrowingMapSequenceVMa _$ss24AsyncThrowingMapSequenceVMn _$ss24AsyncThrowingMapSequenceV_9transformAByxq_Gx_q_7ElementQzYaKctcfC _$ss24AsyncThrowingMapSequenceVyxq_GScisMc -_$ss26DispatchGlobalTaskExecutorC06isMainD0SbvgTj -_$ss26DispatchGlobalTaskExecutorC06isMainD0SbvgTq -_$ss26DispatchGlobalTaskExecutorC06isMainD0SbvpMV -_$ss26DispatchGlobalTaskExecutorC7enqueue_2at9tolerance5clockys0D3JobVn_7InstantQz8DurationQzSgxts5ClockRzlFTj -_$ss26DispatchGlobalTaskExecutorC7enqueue_2at9tolerance5clockys0D3JobVn_7InstantQz8DurationQzSgxts5ClockRzlFTq -_$ss26DispatchGlobalTaskExecutorC7enqueueyys0D3JobVnFTj -_$ss26DispatchGlobalTaskExecutorC7enqueueyys0D3JobVnFTq -_$ss26DispatchGlobalTaskExecutorCABycfC -_$ss26DispatchGlobalTaskExecutorCABycfCTj -_$ss26DispatchGlobalTaskExecutorCABycfCTq -_$ss26DispatchGlobalTaskExecutorCABycfc -_$ss26DispatchGlobalTaskExecutorCMa -_$ss26DispatchGlobalTaskExecutorCMm -_$ss26DispatchGlobalTaskExecutorCMn -_$ss26DispatchGlobalTaskExecutorCMo -_$ss26DispatchGlobalTaskExecutorCMu -_$ss26DispatchGlobalTaskExecutorCN -_$ss26DispatchGlobalTaskExecutorCScFsMc -_$ss26DispatchGlobalTaskExecutorCScFsWP -_$ss26DispatchGlobalTaskExecutorCSchsMc -_$ss26DispatchGlobalTaskExecutorCSchsWP -_$ss26DispatchGlobalTaskExecutorCfD -_$ss26DispatchGlobalTaskExecutorCfd -_$ss26DispatchGlobalTaskExecutorCs011SchedulableD0sMc -_$ss26DispatchGlobalTaskExecutorCs011SchedulableD0sWP +_$ss24_PlatformExecutorFactoryV04mainB0s05_MainB0_pvgZ +_$ss24_PlatformExecutorFactoryV04mainB0s05_MainB0_pvpZMV +_$ss24_PlatformExecutorFactoryV07defaultB0Sch_pvgZ +_$ss24_PlatformExecutorFactoryV07defaultB0Sch_pvpZMV +_$ss24_PlatformExecutorFactoryVMa +_$ss24_PlatformExecutorFactoryVMn +_$ss24_PlatformExecutorFactoryVN +_$ss24_PlatformExecutorFactoryVs01_bC0sMc +_$ss24_PlatformExecutorFactoryVs01_bC0sWP _$ss27AsyncThrowingFilterSequenceV04makeA8IteratorAB0F0Vyx_GyF _$ss27AsyncThrowingFilterSequenceV10isIncludedySb7ElementQzYaKcvg _$ss27AsyncThrowingFilterSequenceV10isIncludedySb7ElementQzYaKcvpMV @@ -989,6 +964,31 @@ _$ss27ThrowingDiscardingTaskGroupV7isEmptySbvpMV _$ss27ThrowingDiscardingTaskGroupV9cancelAllyyF _$ss27ThrowingDiscardingTaskGroupVMa _$ss27ThrowingDiscardingTaskGroupVMn +_$ss27_DispatchGlobalTaskExecutorC07_isMainD0SbvgTj +_$ss27_DispatchGlobalTaskExecutorC07_isMainD0SbvgTq +_$ss27_DispatchGlobalTaskExecutorC07_isMainD0SbvpMV +_$ss27_DispatchGlobalTaskExecutorC7enqueueyys0D3JobVnFTj +_$ss27_DispatchGlobalTaskExecutorC7enqueueyys0D3JobVnFTq +_$ss27_DispatchGlobalTaskExecutorC8_enqueue_2at9tolerance5clockys0D3JobVn_7InstantQz8DurationQzSgxts5ClockRzlFTj +_$ss27_DispatchGlobalTaskExecutorC8_enqueue_2at9tolerance5clockys0D3JobVn_7InstantQz8DurationQzSgxts5ClockRzlFTq +_$ss27_DispatchGlobalTaskExecutorCABycfC +_$ss27_DispatchGlobalTaskExecutorCABycfCTj +_$ss27_DispatchGlobalTaskExecutorCABycfCTq +_$ss27_DispatchGlobalTaskExecutorCABycfc +_$ss27_DispatchGlobalTaskExecutorCMa +_$ss27_DispatchGlobalTaskExecutorCMm +_$ss27_DispatchGlobalTaskExecutorCMn +_$ss27_DispatchGlobalTaskExecutorCMo +_$ss27_DispatchGlobalTaskExecutorCMu +_$ss27_DispatchGlobalTaskExecutorCN +_$ss27_DispatchGlobalTaskExecutorCScFsMc +_$ss27_DispatchGlobalTaskExecutorCScFsWP +_$ss27_DispatchGlobalTaskExecutorCSchsMc +_$ss27_DispatchGlobalTaskExecutorCSchsWP +_$ss27_DispatchGlobalTaskExecutorCfD +_$ss27_DispatchGlobalTaskExecutorCfd +_$ss27_DispatchGlobalTaskExecutorCs012_SchedulableD0sMc +_$ss27_DispatchGlobalTaskExecutorCs012_SchedulableD0sWP _$ss27withTaskCancellationHandler9operation8onCancelxxyYaKXE_yyYbXEtYaKlF _$ss27withTaskCancellationHandler9operation8onCancelxxyYaKXE_yyYbXEtYaKlFTu _$ss28AsyncThrowingFlatMapSequenceV04makeA8IteratorAB0G0Vyxq__GyF @@ -1119,26 +1119,26 @@ _$ss5ClockP3now7InstantQzvgTq _$ss5ClockP5sleep5until9tolerancey7InstantQz_8DurationQzSgtYaKFTj _$ss5ClockP5sleep5until9tolerancey7InstantQz_8DurationQzSgtYaKFTjTu _$ss5ClockP5sleep5until9tolerancey7InstantQz_8DurationQzSgtYaKFTq -_$ss5ClockP6traitss0A6TraitsVvgTj -_$ss5ClockP6traitss0A6TraitsVvgTq _$ss5ClockP7InstantAB_s0B8ProtocolTn -_$ss5ClockP7convert4from8DurationQzSgsAEV_tFTj -_$ss5ClockP7convert4from8DurationQzSgsAEV_tFTq -_$ss5ClockP7convert4froms8DurationVSgAEQz_tFTj -_$ss5ClockP7convert4froms8DurationVSgAEQz_tFTq -_$ss5ClockP7convert7instant4from7InstantQzSgAFQyd___qd__tsAARd__lFTj -_$ss5ClockP7convert7instant4from7InstantQzSgAFQyd___qd__tsAARd__lFTq -_$ss5ClockPsE6traitss0A6TraitsVvg -_$ss5ClockPsE6traitss0A6TraitsVvpMV -_$ss5ClockPsE7convert4from8DurationQzSgsAEV_tF -_$ss5ClockPsE7convert4froms8DurationVSgAEQz_tF -_$ss5ClockPsE7convert7instant4from7InstantQzSgAFQyd___qd__tsAARd__lF +_$ss5ClockP7_traitss01_A6TraitsVvgTj +_$ss5ClockP7_traitss01_A6TraitsVvgTq +_$ss5ClockP8_convert4from8DurationQzSgsAEV_tFTj +_$ss5ClockP8_convert4from8DurationQzSgsAEV_tFTq +_$ss5ClockP8_convert4froms8DurationVSgAEQz_tFTj +_$ss5ClockP8_convert4froms8DurationVSgAEQz_tFTq +_$ss5ClockP8_convert7instant4from7InstantQzSgAFQyd___qd__tsAARd__lFTj +_$ss5ClockP8_convert7instant4from7InstantQzSgAFQyd___qd__tsAARd__lFTq +_$ss5ClockPsE7_traitss01_A6TraitsVvg +_$ss5ClockPsE7_traitss01_A6TraitsVvpMV _$ss5ClockPsE7measurey8DurationQzyyKXEKF _$ss5ClockPsE7measurey8DurationQzyyYaKXEYaKF _$ss5ClockPsE7measurey8DurationQzyyYaKXEYaKFTu +_$ss5ClockPsE8_convert4from8DurationQzSgsAEV_tF +_$ss5ClockPsE8_convert4froms8DurationVSgAEQz_tF +_$ss5ClockPsE8_convert7instant4from7InstantQzSgAFQyd___qd__tsAARd__lF _$ss5ClockPss010ContinuousA0VRszrlE10continuousADvgZ _$ss5ClockPss010SuspendingA0VRszrlE10suspendingADvgZ -_$ss5ClockPss8DurationVACRtzrlE7convert4fromADSgAD_tF +_$ss5ClockPss8DurationVACRtzrlE8_convert4fromADSgAD_tF _$ss5ClockTL _$ss6_first_5where7ElementQzSgx_SbADYaKXEtYaKSciRzlF _$ss6_first_5where7ElementQzSgx_SbADYaKXEtYaKSciRzlFTu diff --git a/test/abi/Inputs/macOS/arm64/concurrency/baseline-asserts b/test/abi/Inputs/macOS/arm64/concurrency/baseline-asserts index 8aa55b3098c58..002cd69dc8e7d 100644 --- a/test/abi/Inputs/macOS/arm64/concurrency/baseline-asserts +++ b/test/abi/Inputs/macOS/arm64/concurrency/baseline-asserts @@ -23,8 +23,8 @@ _$sScEMa _$sScEMn _$sScEN _$sScEs5ErrorsMc -_$sScF14isMainExecutorSbvgTj -_$sScF14isMainExecutorSbvgTq +_$sScF15_isMainExecutorSbvgTj +_$sScF15_isMainExecutorSbvgTq _$sScF7enqueueyyScJFTj _$sScF7enqueueyyScJFTq _$sScF7enqueueyys11ExecutorJobVnFTj @@ -33,8 +33,8 @@ _$sScF7enqueueyys3JobVnFTj _$sScF7enqueueyys3JobVnFTq _$sScFMp _$sScFTL -_$sScFsE14isMainExecutorSbvg -_$sScFsE14isMainExecutorSbvpMV +_$sScFsE15_isMainExecutorSbvg +_$sScFsE15_isMainExecutorSbvpMV _$sScFsE18_isComplexEqualitySbvg _$sScFsE18_isComplexEqualitySbvpMV _$sScFsE7enqueueyyScJF @@ -96,8 +96,8 @@ _$sScM3run10resultType4bodyxxm_xyYbKScMYcXEtYaKlFZ _$sScM3run10resultType4bodyxxm_xyYbKScMYcXEtYaKlFZTu _$sScM6sharedScMvgZ _$sScM7enqueueyyScJF -_$sScM8executors12MainExecutor_pvgZ -_$sScM8executors12MainExecutor_pvpZMV +_$sScM9_executors13_MainExecutor_pvgZ +_$sScM9_executors13_MainExecutor_pvpZMV _$sScMMa _$sScMMm _$sScMMn @@ -211,16 +211,16 @@ _$sScTss5NeverORs_rlE5valuexvgTu _$sScTss5NeverORs_rlE5valuexvpMV _$sScTss5NeverORszABRs_rlE11isCancelledSbvgZ _$sScTss5NeverORszABRs_rlE12basePriorityScPSgvgZ -_$sScTss5NeverORszABRs_rlE15currentExecutorScF_pvgZ -_$sScTss5NeverORszABRs_rlE15currentExecutorScF_pvpZMV _$sScTss5NeverORszABRs_rlE15currentPriorityScPvgZ -_$sScTss5NeverORszABRs_rlE15defaultExecutorSch_pvgZ -_$sScTss5NeverORszABRs_rlE15defaultExecutorSch_pvpZMV +_$sScTss5NeverORszABRs_rlE16_currentExecutorScF_pvgZ +_$sScTss5NeverORszABRs_rlE16_currentExecutorScF_pvpZMV +_$sScTss5NeverORszABRs_rlE16_defaultExecutorSch_pvgZ +_$sScTss5NeverORszABRs_rlE16_defaultExecutorSch_pvpZMV _$sScTss5NeverORszABRs_rlE17checkCancellationyyKFZ -_$sScTss5NeverORszABRs_rlE17preferredExecutorSch_pSgvgZ -_$sScTss5NeverORszABRs_rlE17preferredExecutorSch_pSgvpZMV -_$sScTss5NeverORszABRs_rlE26currentSchedulableExecutors0cD0_pSgvgZ -_$sScTss5NeverORszABRs_rlE26currentSchedulableExecutors0cD0_pSgvpZMV +_$sScTss5NeverORszABRs_rlE18_preferredExecutorSch_pSgvgZ +_$sScTss5NeverORszABRs_rlE18_preferredExecutorSch_pSgvpZMV +_$sScTss5NeverORszABRs_rlE27_currentSchedulableExecutors01_cD0_pSgvgZ +_$sScTss5NeverORszABRs_rlE27_currentSchedulableExecutors01_cD0_pSgvpZMV _$sScTss5NeverORszABRs_rlE5sleep11nanosecondsys6UInt64V_tYaKFZ _$sScTss5NeverORszABRs_rlE5sleep11nanosecondsys6UInt64V_tYaKFZTu _$sScTss5NeverORszABRs_rlE5sleep5until9tolerance5clocky7InstantQyd___8DurationQyd__Sgqd__tYaKs5ClockRd__lFZ @@ -238,7 +238,7 @@ _$sScc7contextBcvs _$sSccMa _$sSccMn _$sSce15complexEqualityScexh_tcScfRzlufC -_$sSce16asSerialExecutorScf_pSgyF +_$sSce17_asSerialExecutorScf_pSgyF _$sSce18_isComplexEqualitySbvg _$sSce18_isComplexEqualitySbvpMV _$sSce8executorBevM @@ -267,8 +267,8 @@ _$sScfMp _$sScfScFTb _$sScfTL _$sScfsE14assertIsolated_4file4lineySSyXK_s12StaticStringVSutF -_$sScfsE14isMainExecutorSbvg -_$sScfsE14isMainExecutorSbvpMV +_$sScfsE15_isMainExecutorSbvg +_$sScfsE15_isMainExecutorSbvpMV _$sScfsE20preconditionIsolated_4file4lineySSyXK_s12StaticStringVSutF _$sScfsE23asUnownedSerialExecutorSceyF _$sScfsE31isSameExclusiveExecutionContext5otherSbx_tF @@ -405,24 +405,7 @@ _$sSctN _$sSctSHsMc _$sSctSQsMc _$ss039_checkIllegalTaskLocalBindingWithinWithC5Group4file4lineySS_SutF -_$ss11ClockTraitsV10continuousABvgZ -_$ss11ClockTraitsV10continuousABvpZMV -_$ss11ClockTraitsV8rawValueABs6UInt32V_tcfC -_$ss11ClockTraitsV8rawValues6UInt32Vvg -_$ss11ClockTraitsV8rawValues6UInt32VvpMV -_$ss11ClockTraitsV8wallTimeABvgZ -_$ss11ClockTraitsV8wallTimeABvpZMV -_$ss11ClockTraitsV9monotonicABvgZ -_$ss11ClockTraitsV9monotonicABvpZMV -_$ss11ClockTraitsVMa -_$ss11ClockTraitsVMn -_$ss11ClockTraitsVN -_$ss11ClockTraitsVSQsMc -_$ss11ClockTraitsVSYsMc -_$ss11ClockTraitsVs10SetAlgebrasMc -_$ss11ClockTraitsVs25ExpressibleByArrayLiteralsMc -_$ss11ClockTraitsVs9OptionSetsMc -_$ss11ExecutorJobV010withUnsafeA11PrivateData4bodyxxSwq_YKXE_tq_YKs5ErrorR_r0_lF +_$ss11ExecutorJobV011_withUnsafeA11PrivateData4bodyxxSwq_YKXE_tq_YKs5ErrorR_r0_lF _$ss11ExecutorJobV11descriptionSSvg _$ss11ExecutorJobV14LocalAllocatorV10deallocateyySpyxGlF _$ss11ExecutorJobV14LocalAllocatorV10deallocateyySryxGlF @@ -433,20 +416,20 @@ _$ss11ExecutorJobV14LocalAllocatorV8allocate8capacitySwSi_tF _$ss11ExecutorJobV14LocalAllocatorVMa _$ss11ExecutorJobV14LocalAllocatorVMn _$ss11ExecutorJobV14LocalAllocatorVN -_$ss11ExecutorJobV4KindV13firstReservedADvgZ -_$ss11ExecutorJobV4KindV13firstReservedADvpZMV -_$ss11ExecutorJobV4KindV4taskADvgZ -_$ss11ExecutorJobV4KindV4taskADvpZMV -_$ss11ExecutorJobV4KindV8rawValueADSgs5UInt8V_tcfC -_$ss11ExecutorJobV4KindV8rawValues5UInt8VvM -_$ss11ExecutorJobV4KindV8rawValues5UInt8Vvg -_$ss11ExecutorJobV4KindV8rawValues5UInt8VvpMV -_$ss11ExecutorJobV4KindV8rawValues5UInt8Vvs -_$ss11ExecutorJobV4KindVMa -_$ss11ExecutorJobV4KindVMn -_$ss11ExecutorJobV4KindVN -_$ss11ExecutorJobV4KindVSYsMc -_$ss11ExecutorJobV4kindAB4KindVvg +_$ss11ExecutorJobV5_KindV13firstReservedADvgZ +_$ss11ExecutorJobV5_KindV13firstReservedADvpZMV +_$ss11ExecutorJobV5_KindV4taskADvgZ +_$ss11ExecutorJobV5_KindV4taskADvpZMV +_$ss11ExecutorJobV5_KindV8rawValueADSgs5UInt8V_tcfC +_$ss11ExecutorJobV5_KindV8rawValues5UInt8VvM +_$ss11ExecutorJobV5_KindV8rawValues5UInt8Vvg +_$ss11ExecutorJobV5_KindV8rawValues5UInt8VvpMV +_$ss11ExecutorJobV5_KindV8rawValues5UInt8Vvs +_$ss11ExecutorJobV5_KindVMa +_$ss11ExecutorJobV5_KindVMn +_$ss11ExecutorJobV5_KindVN +_$ss11ExecutorJobV5_KindVSYsMc +_$ss11ExecutorJobV5_kindAB5_KindVvg _$ss11ExecutorJobV7contextABBjn_tcfC _$ss11ExecutorJobV8prioritys0B8PriorityVvg _$ss11ExecutorJobV9allocatorAB14LocalAllocatorVSgvg @@ -480,33 +463,30 @@ _$ss11JobPriorityVMn _$ss11JobPriorityVN _$ss11JobPriorityVSLsMc _$ss11JobPriorityVSQsMc -_$ss12MainExecutorMp -_$ss12MainExecutorPScfTb -_$ss12MainExecutorPs07RunLoopB0Tb -_$ss12MainExecutorTL +_$ss12_ClockTraitsV10continuousABvgZ +_$ss12_ClockTraitsV10continuousABvpZMV +_$ss12_ClockTraitsV8rawValueABs6UInt32V_tcfC +_$ss12_ClockTraitsV8rawValues6UInt32Vvg +_$ss12_ClockTraitsV8rawValues6UInt32VvpMV +_$ss12_ClockTraitsV8wallTimeABvgZ +_$ss12_ClockTraitsV8wallTimeABvpZMV +_$ss12_ClockTraitsV9monotonicABvgZ +_$ss12_ClockTraitsV9monotonicABvpZMV +_$ss12_ClockTraitsVMa +_$ss12_ClockTraitsVMn +_$ss12_ClockTraitsVN +_$ss12_ClockTraitsVSQsMc +_$ss12_ClockTraitsVSYsMc +_$ss12_ClockTraitsVs10SetAlgebrasMc +_$ss12_ClockTraitsVs25ExpressibleByArrayLiteralsMc +_$ss12_ClockTraitsVs9OptionSetsMc +_$ss13_MainExecutorMp +_$ss13_MainExecutorPScfTb +_$ss13_MainExecutorPs08_RunLoopB0Tb +_$ss13_MainExecutorTL _$ss13_runAsyncMainyyyyYaKcF _$ss13withTaskGroup2of9returning4bodyq_xm_q_mq_ScGyxGzYaXEtYar0_lF _$ss13withTaskGroup2of9returning4bodyq_xm_q_mq_ScGyxGzYaXEtYar0_lFTu -_$ss14CFMainExecutorC3runyyKF -_$ss14CFMainExecutorC4stopyyF -_$ss14CFMainExecutorCABycfC -_$ss14CFMainExecutorCABycfc -_$ss14CFMainExecutorCMa -_$ss14CFMainExecutorCMm -_$ss14CFMainExecutorCMn -_$ss14CFMainExecutorCMo -_$ss14CFMainExecutorCN -_$ss14CFMainExecutorCfD -_$ss14CFMainExecutorCfd -_$ss14CFTaskExecutorCABycfC -_$ss14CFTaskExecutorCABycfc -_$ss14CFTaskExecutorCMa -_$ss14CFTaskExecutorCMm -_$ss14CFTaskExecutorCMn -_$ss14CFTaskExecutorCMo -_$ss14CFTaskExecutorCN -_$ss14CFTaskExecutorCfD -_$ss14CFTaskExecutorCfd _$ss15ContinuousClockV17minimumResolutions8DurationVvg _$ss15ContinuousClockV17minimumResolutions8DurationVvpMV _$ss15ContinuousClockV3nowAB7InstantVvg @@ -514,8 +494,6 @@ _$ss15ContinuousClockV3nowAB7InstantVvgZ _$ss15ContinuousClockV3nowAB7InstantVvpMV _$ss15ContinuousClockV5sleep5until9toleranceyAB7InstantV_s8DurationVSgtYaKF _$ss15ContinuousClockV5sleep5until9toleranceyAB7InstantV_s8DurationVSgtYaKFTu -_$ss15ContinuousClockV6traitss0B6TraitsVvg -_$ss15ContinuousClockV6traitss0B6TraitsVvpMV _$ss15ContinuousClockV7InstantV1loiySbAD_ADtFZ _$ss15ContinuousClockV7InstantV2eeoiySbAD_ADtFZ _$ss15ContinuousClockV7InstantV3nowADvgZ @@ -535,28 +513,14 @@ _$ss15ContinuousClockV7InstantVSLsMc _$ss15ContinuousClockV7InstantVSQsMc _$ss15ContinuousClockV7InstantVSesMc _$ss15ContinuousClockV7InstantVs0C8ProtocolsMc +_$ss15ContinuousClockV7_traitss01_B6TraitsVvg +_$ss15ContinuousClockV7_traitss01_B6TraitsVvpMV _$ss15ContinuousClockVABycfC _$ss15ContinuousClockVMa _$ss15ContinuousClockVMn _$ss15ContinuousClockVN _$ss15ContinuousClockVs0B0sMc _$ss15ContinuousClockVs0B0sWP -_$ss15ExecutorFactoryMp -_$ss15ExecutorFactoryP04mainA0s04MainA0_pvgZTj -_$ss15ExecutorFactoryP04mainA0s04MainA0_pvgZTq -_$ss15ExecutorFactoryP07defaultA0Sch_pvgZTj -_$ss15ExecutorFactoryP07defaultA0Sch_pvgZTq -_$ss15ExecutorFactoryTL -_$ss15RunLoopExecutorMp -_$ss15RunLoopExecutorP3runyyKFTj -_$ss15RunLoopExecutorP3runyyKFTq -_$ss15RunLoopExecutorP4stopyyFTj -_$ss15RunLoopExecutorP4stopyyFTq -_$ss15RunLoopExecutorP8runUntilyySbyXEKFTj -_$ss15RunLoopExecutorP8runUntilyySbyXEKFTq -_$ss15RunLoopExecutorPScFTb -_$ss15RunLoopExecutorPsE8runUntilyySbyXEKF -_$ss15RunLoopExecutorTL _$ss15SuspendingClockV17minimumResolutions8DurationVvg _$ss15SuspendingClockV17minimumResolutions8DurationVvpMV _$ss15SuspendingClockV3nowAB7InstantVvg @@ -564,8 +528,6 @@ _$ss15SuspendingClockV3nowAB7InstantVvgZ _$ss15SuspendingClockV3nowAB7InstantVvpMV _$ss15SuspendingClockV5sleep5until9toleranceyAB7InstantV_s8DurationVSgtYaKF _$ss15SuspendingClockV5sleep5until9toleranceyAB7InstantV_s8DurationVSgtYaKFTu -_$ss15SuspendingClockV6traitss0B6TraitsVvg -_$ss15SuspendingClockV6traitss0B6TraitsVvpMV _$ss15SuspendingClockV7InstantV1loiySbAD_ADtFZ _$ss15SuspendingClockV7InstantV1poiyA2D_s8DurationVtFZ _$ss15SuspendingClockV7InstantV1soiyA2D_s8DurationVtFZ @@ -590,12 +552,34 @@ _$ss15SuspendingClockV7InstantVSLsMc _$ss15SuspendingClockV7InstantVSQsMc _$ss15SuspendingClockV7InstantVSesMc _$ss15SuspendingClockV7InstantVs0C8ProtocolsMc +_$ss15SuspendingClockV7_traitss01_B6TraitsVvg +_$ss15SuspendingClockV7_traitss01_B6TraitsVvpMV _$ss15SuspendingClockVABycfC _$ss15SuspendingClockVMa _$ss15SuspendingClockVMn _$ss15SuspendingClockVN _$ss15SuspendingClockVs0B0sMc _$ss15SuspendingClockVs0B0sWP +_$ss15_CFMainExecutorC4_runyyKF +_$ss15_CFMainExecutorC5_stopyyF +_$ss15_CFMainExecutorCABycfC +_$ss15_CFMainExecutorCABycfc +_$ss15_CFMainExecutorCMa +_$ss15_CFMainExecutorCMm +_$ss15_CFMainExecutorCMn +_$ss15_CFMainExecutorCMo +_$ss15_CFMainExecutorCN +_$ss15_CFMainExecutorCfD +_$ss15_CFMainExecutorCfd +_$ss15_CFTaskExecutorCABycfC +_$ss15_CFTaskExecutorCABycfc +_$ss15_CFTaskExecutorCMa +_$ss15_CFTaskExecutorCMm +_$ss15_CFTaskExecutorCMn +_$ss15_CFTaskExecutorCMo +_$ss15_CFTaskExecutorCN +_$ss15_CFTaskExecutorCfD +_$ss15_CFTaskExecutorCfd _$ss16AsyncMapSequenceV04makeA8IteratorAB0E0Vyxq__GyF _$ss16AsyncMapSequenceV4basexvg _$ss16AsyncMapSequenceV4basexvpMV @@ -617,51 +601,67 @@ _$ss16AsyncMapSequenceVMa _$ss16AsyncMapSequenceVMn _$ss16AsyncMapSequenceV_9transformAByxq_Gx_q_7ElementQzYactcfC _$ss16AsyncMapSequenceVyxq_GScisMc -_$ss17DummyMainExecutorC02isbC0Sbvg -_$ss17DummyMainExecutorC02isbC0SbvpMV -_$ss17DummyMainExecutorC13checkIsolatedyyF -_$ss17DummyMainExecutorC3runyyKF -_$ss17DummyMainExecutorC4stopyyF -_$ss17DummyMainExecutorC7enqueueyys0C3JobVnF -_$ss17DummyMainExecutorCABycfC -_$ss17DummyMainExecutorCABycfCTj -_$ss17DummyMainExecutorCABycfCTq -_$ss17DummyMainExecutorCABycfc -_$ss17DummyMainExecutorCMa -_$ss17DummyMainExecutorCMm -_$ss17DummyMainExecutorCMn -_$ss17DummyMainExecutorCMo -_$ss17DummyMainExecutorCMu -_$ss17DummyMainExecutorCN -_$ss17DummyMainExecutorCScFsMc -_$ss17DummyMainExecutorCScFsWP -_$ss17DummyMainExecutorCScfsMc -_$ss17DummyMainExecutorCScfsWP -_$ss17DummyMainExecutorCfD -_$ss17DummyMainExecutorCfd -_$ss17DummyMainExecutorCs07RunLoopC0sMc -_$ss17DummyMainExecutorCs07RunLoopC0sWP -_$ss17DummyMainExecutorCs0bC0sMc -_$ss17DummyMainExecutorCs0bC0sWP -_$ss17DummyTaskExecutorC06isMainC0Sbvg -_$ss17DummyTaskExecutorC06isMainC0SbvpMV -_$ss17DummyTaskExecutorC7enqueueyys0C3JobVnF -_$ss17DummyTaskExecutorCABycfC -_$ss17DummyTaskExecutorCABycfCTj -_$ss17DummyTaskExecutorCABycfCTq -_$ss17DummyTaskExecutorCABycfc -_$ss17DummyTaskExecutorCMa -_$ss17DummyTaskExecutorCMm -_$ss17DummyTaskExecutorCMn -_$ss17DummyTaskExecutorCMo -_$ss17DummyTaskExecutorCMu -_$ss17DummyTaskExecutorCN -_$ss17DummyTaskExecutorCScFsMc -_$ss17DummyTaskExecutorCScFsWP -_$ss17DummyTaskExecutorCSchsMc -_$ss17DummyTaskExecutorCSchsWP -_$ss17DummyTaskExecutorCfD -_$ss17DummyTaskExecutorCfd +_$ss16_ExecutorFactoryMp +_$ss16_ExecutorFactoryP04mainA0s05_MainA0_pvgZTj +_$ss16_ExecutorFactoryP04mainA0s05_MainA0_pvgZTq +_$ss16_ExecutorFactoryP07defaultA0Sch_pvgZTj +_$ss16_ExecutorFactoryP07defaultA0Sch_pvgZTq +_$ss16_ExecutorFactoryTL +_$ss16_RunLoopExecutorMp +_$ss16_RunLoopExecutorP4_runyyKFTj +_$ss16_RunLoopExecutorP4_runyyKFTq +_$ss16_RunLoopExecutorP5_stopyyFTj +_$ss16_RunLoopExecutorP5_stopyyFTq +_$ss16_RunLoopExecutorP9_runUntilyySbyXEKFTj +_$ss16_RunLoopExecutorP9_runUntilyySbyXEKFTq +_$ss16_RunLoopExecutorPScFTb +_$ss16_RunLoopExecutorPsE9_runUntilyySbyXEKF +_$ss16_RunLoopExecutorTL +_$ss18_DummyMainExecutorC03_isbC0Sbvg +_$ss18_DummyMainExecutorC03_isbC0SbvpMV +_$ss18_DummyMainExecutorC13checkIsolatedyyF +_$ss18_DummyMainExecutorC4_runyyKF +_$ss18_DummyMainExecutorC5_stopyyF +_$ss18_DummyMainExecutorC7enqueueyys0C3JobVnF +_$ss18_DummyMainExecutorCABycfC +_$ss18_DummyMainExecutorCABycfCTj +_$ss18_DummyMainExecutorCABycfCTq +_$ss18_DummyMainExecutorCABycfc +_$ss18_DummyMainExecutorCMa +_$ss18_DummyMainExecutorCMm +_$ss18_DummyMainExecutorCMn +_$ss18_DummyMainExecutorCMo +_$ss18_DummyMainExecutorCMu +_$ss18_DummyMainExecutorCN +_$ss18_DummyMainExecutorCScFsMc +_$ss18_DummyMainExecutorCScFsWP +_$ss18_DummyMainExecutorCScfsMc +_$ss18_DummyMainExecutorCScfsWP +_$ss18_DummyMainExecutorCfD +_$ss18_DummyMainExecutorCfd +_$ss18_DummyMainExecutorCs01_bC0sMc +_$ss18_DummyMainExecutorCs01_bC0sWP +_$ss18_DummyMainExecutorCs08_RunLoopC0sMc +_$ss18_DummyMainExecutorCs08_RunLoopC0sWP +_$ss18_DummyTaskExecutorC07_isMainC0Sbvg +_$ss18_DummyTaskExecutorC07_isMainC0SbvpMV +_$ss18_DummyTaskExecutorC7enqueueyys0C3JobVnF +_$ss18_DummyTaskExecutorCABycfC +_$ss18_DummyTaskExecutorCABycfCTj +_$ss18_DummyTaskExecutorCABycfCTq +_$ss18_DummyTaskExecutorCABycfc +_$ss18_DummyTaskExecutorCMa +_$ss18_DummyTaskExecutorCMm +_$ss18_DummyTaskExecutorCMn +_$ss18_DummyTaskExecutorCMo +_$ss18_DummyTaskExecutorCMu +_$ss18_DummyTaskExecutorCN +_$ss18_DummyTaskExecutorCScFsMc +_$ss18_DummyTaskExecutorCScFsWP +_$ss18_DummyTaskExecutorCSchsMc +_$ss18_DummyTaskExecutorCSchsWP +_$ss18_DummyTaskExecutorCfD +_$ss18_DummyTaskExecutorCfd _$ss19AsyncFilterSequenceV04makeA8IteratorAB0E0Vyx_GyF _$ss19AsyncFilterSequenceV10isIncludedySb7ElementQzYacvg _$ss19AsyncFilterSequenceV10isIncludedySb7ElementQzYacvpMV @@ -719,16 +719,7 @@ _$ss19DiscardingTaskGroupV9cancelAllyyF _$ss19DiscardingTaskGroupVMa _$ss19DiscardingTaskGroupVMn _$ss19DiscardingTaskGroupVN -_$ss19SchedulableExecutorMp -_$ss19SchedulableExecutorP7enqueue_2at9tolerance5clockys0B3JobVn_7InstantQyd__8DurationQyd__Sgqd__ts5ClockRd__lFTj -_$ss19SchedulableExecutorP7enqueue_2at9tolerance5clockys0B3JobVn_7InstantQyd__8DurationQyd__Sgqd__ts5ClockRd__lFTq -_$ss19SchedulableExecutorP7enqueue_5after9tolerance5clockys0B3JobVn_8DurationQyd__AJSgqd__ts5ClockRd__lFTj -_$ss19SchedulableExecutorP7enqueue_5after9tolerance5clockys0B3JobVn_8DurationQyd__AJSgqd__ts5ClockRd__lFTq -_$ss19SchedulableExecutorPScFTb -_$ss19SchedulableExecutorPsE7enqueue_2at9tolerance5clockys0B3JobVn_7InstantQyd__8DurationQyd__Sgqd__ts5ClockRd__lF -_$ss19SchedulableExecutorPsE7enqueue_5after9tolerance5clockys0B3JobVn_8DurationQyd__AJSgqd__ts5ClockRd__lF -_$ss19SchedulableExecutorTL -_$ss19UnownedTaskExecutorV02asbC0Sch_pSgyF +_$ss19UnownedTaskExecutorV03_asbC0Sch_pSgyF _$ss19UnownedTaskExecutorVyABxhcSchRzlufC _$ss20AsyncFlatMapSequenceV04makeA8IteratorAB0F0Vyxq__GyF _$ss20AsyncFlatMapSequenceV4basexvg @@ -759,39 +750,48 @@ _$ss20AsyncFlatMapSequenceVMa _$ss20AsyncFlatMapSequenceVMn _$ss20AsyncFlatMapSequenceV_9transformAByxq_Gx_q_7ElementQzYactcfC _$ss20AsyncFlatMapSequenceVyxq_GScisMc -_$ss20DispatchMainExecutorC02isbC0Sbvg -_$ss20DispatchMainExecutorC02isbC0SbvpMV -_$ss20DispatchMainExecutorC13asSchedulables0eC0_pSgvg -_$ss20DispatchMainExecutorC13asSchedulables0eC0_pSgvpMV -_$ss20DispatchMainExecutorC13checkIsolatedyyF -_$ss20DispatchMainExecutorC3runyyKFTj -_$ss20DispatchMainExecutorC3runyyKFTq -_$ss20DispatchMainExecutorC4stopyyFTj -_$ss20DispatchMainExecutorC4stopyyFTq -_$ss20DispatchMainExecutorC7enqueue_2at9tolerance5clockys0C3JobVn_7InstantQz8DurationQzSgxts5ClockRzlF -_$ss20DispatchMainExecutorC7enqueueyys0C3JobVnF -_$ss20DispatchMainExecutorCABycfC -_$ss20DispatchMainExecutorCABycfCTj -_$ss20DispatchMainExecutorCABycfCTq -_$ss20DispatchMainExecutorCABycfc -_$ss20DispatchMainExecutorCMa -_$ss20DispatchMainExecutorCMm -_$ss20DispatchMainExecutorCMn -_$ss20DispatchMainExecutorCMo -_$ss20DispatchMainExecutorCMu -_$ss20DispatchMainExecutorCN -_$ss20DispatchMainExecutorCScFsMc -_$ss20DispatchMainExecutorCScFsWP -_$ss20DispatchMainExecutorCScfsMc -_$ss20DispatchMainExecutorCScfsWP -_$ss20DispatchMainExecutorCfD -_$ss20DispatchMainExecutorCfd -_$ss20DispatchMainExecutorCs011SchedulableC0sMc -_$ss20DispatchMainExecutorCs011SchedulableC0sWP -_$ss20DispatchMainExecutorCs07RunLoopC0sMc -_$ss20DispatchMainExecutorCs07RunLoopC0sWP -_$ss20DispatchMainExecutorCs0bC0sMc -_$ss20DispatchMainExecutorCs0bC0sWP +_$ss20_SchedulableExecutorMp +_$ss20_SchedulableExecutorP8_enqueue_2at9tolerance5clockys0B3JobVn_7InstantQyd__8DurationQyd__Sgqd__ts5ClockRd__lFTj +_$ss20_SchedulableExecutorP8_enqueue_2at9tolerance5clockys0B3JobVn_7InstantQyd__8DurationQyd__Sgqd__ts5ClockRd__lFTq +_$ss20_SchedulableExecutorP8_enqueue_5after9tolerance5clockys0B3JobVn_8DurationQyd__AJSgqd__ts5ClockRd__lFTj +_$ss20_SchedulableExecutorP8_enqueue_5after9tolerance5clockys0B3JobVn_8DurationQyd__AJSgqd__ts5ClockRd__lFTq +_$ss20_SchedulableExecutorPScFTb +_$ss20_SchedulableExecutorPsE8_enqueue_2at9tolerance5clockys0B3JobVn_7InstantQyd__8DurationQyd__Sgqd__ts5ClockRd__lF +_$ss20_SchedulableExecutorPsE8_enqueue_5after9tolerance5clockys0B3JobVn_8DurationQyd__AJSgqd__ts5ClockRd__lF +_$ss20_SchedulableExecutorTL +_$ss21_DispatchMainExecutorC03_isbC0Sbvg +_$ss21_DispatchMainExecutorC03_isbC0SbvpMV +_$ss21_DispatchMainExecutorC13checkIsolatedyyF +_$ss21_DispatchMainExecutorC14_asSchedulables01_eC0_pSgvg +_$ss21_DispatchMainExecutorC14_asSchedulables01_eC0_pSgvpMV +_$ss21_DispatchMainExecutorC4_runyyKFTj +_$ss21_DispatchMainExecutorC4_runyyKFTq +_$ss21_DispatchMainExecutorC5_stopyyFTj +_$ss21_DispatchMainExecutorC5_stopyyFTq +_$ss21_DispatchMainExecutorC7enqueueyys0C3JobVnF +_$ss21_DispatchMainExecutorC8_enqueue_2at9tolerance5clockys0C3JobVn_7InstantQz8DurationQzSgxts5ClockRzlF +_$ss21_DispatchMainExecutorCABycfC +_$ss21_DispatchMainExecutorCABycfCTj +_$ss21_DispatchMainExecutorCABycfCTq +_$ss21_DispatchMainExecutorCABycfc +_$ss21_DispatchMainExecutorCMa +_$ss21_DispatchMainExecutorCMm +_$ss21_DispatchMainExecutorCMn +_$ss21_DispatchMainExecutorCMo +_$ss21_DispatchMainExecutorCMu +_$ss21_DispatchMainExecutorCN +_$ss21_DispatchMainExecutorCScFsMc +_$ss21_DispatchMainExecutorCScFsWP +_$ss21_DispatchMainExecutorCScfsMc +_$ss21_DispatchMainExecutorCScfsWP +_$ss21_DispatchMainExecutorCfD +_$ss21_DispatchMainExecutorCfd +_$ss21_DispatchMainExecutorCs012_SchedulableC0sMc +_$ss21_DispatchMainExecutorCs012_SchedulableC0sWP +_$ss21_DispatchMainExecutorCs01_bC0sMc +_$ss21_DispatchMainExecutorCs01_bC0sWP +_$ss21_DispatchMainExecutorCs08_RunLoopC0sMc +_$ss21_DispatchMainExecutorCs08_RunLoopC0sWP _$ss21withThrowingTaskGroup2of9returning4bodyq_xm_q_mq_Scgyxs5Error_pGzYaKXEtYaKr0_lF _$ss21withThrowingTaskGroup2of9returning4bodyq_xm_q_mq_Scgyxs5Error_pGzYaKXEtYaKr0_lFTu _$ss21withUnsafeCurrentTask4bodyxxSctSgKXE_tKlF @@ -864,15 +864,6 @@ _$ss23AsyncCompactMapSequenceVMa _$ss23AsyncCompactMapSequenceVMn _$ss23AsyncCompactMapSequenceV_9transformAByxq_Gx_q_Sg7ElementQzYactcfC _$ss23AsyncCompactMapSequenceVyxq_GScisMc -_$ss23PlatformExecutorFactoryV04mainB0s04MainB0_pvgZ -_$ss23PlatformExecutorFactoryV04mainB0s04MainB0_pvpZMV -_$ss23PlatformExecutorFactoryV07defaultB0Sch_pvgZ -_$ss23PlatformExecutorFactoryV07defaultB0Sch_pvpZMV -_$ss23PlatformExecutorFactoryVMa -_$ss23PlatformExecutorFactoryVMn -_$ss23PlatformExecutorFactoryVN -_$ss23PlatformExecutorFactoryVs0bC0sMc -_$ss23PlatformExecutorFactoryVs0bC0sWP _$ss23withCheckedContinuation8function_xSS_yScCyxs5NeverOGXEtYalF _$ss23withCheckedContinuation8function_xSS_yScCyxs5NeverOGXEtYalFTu _$ss23withDiscardingTaskGroup9returning4bodyxxm_xs0bcD0VzYaXEtYalF @@ -927,31 +918,15 @@ _$ss24AsyncThrowingMapSequenceVMa _$ss24AsyncThrowingMapSequenceVMn _$ss24AsyncThrowingMapSequenceV_9transformAByxq_Gx_q_7ElementQzYaKctcfC _$ss24AsyncThrowingMapSequenceVyxq_GScisMc -_$ss26DispatchGlobalTaskExecutorC06isMainD0SbvgTj -_$ss26DispatchGlobalTaskExecutorC06isMainD0SbvgTq -_$ss26DispatchGlobalTaskExecutorC06isMainD0SbvpMV -_$ss26DispatchGlobalTaskExecutorC7enqueue_2at9tolerance5clockys0D3JobVn_7InstantQz8DurationQzSgxts5ClockRzlFTj -_$ss26DispatchGlobalTaskExecutorC7enqueue_2at9tolerance5clockys0D3JobVn_7InstantQz8DurationQzSgxts5ClockRzlFTq -_$ss26DispatchGlobalTaskExecutorC7enqueueyys0D3JobVnFTj -_$ss26DispatchGlobalTaskExecutorC7enqueueyys0D3JobVnFTq -_$ss26DispatchGlobalTaskExecutorCABycfC -_$ss26DispatchGlobalTaskExecutorCABycfCTj -_$ss26DispatchGlobalTaskExecutorCABycfCTq -_$ss26DispatchGlobalTaskExecutorCABycfc -_$ss26DispatchGlobalTaskExecutorCMa -_$ss26DispatchGlobalTaskExecutorCMm -_$ss26DispatchGlobalTaskExecutorCMn -_$ss26DispatchGlobalTaskExecutorCMo -_$ss26DispatchGlobalTaskExecutorCMu -_$ss26DispatchGlobalTaskExecutorCN -_$ss26DispatchGlobalTaskExecutorCScFsMc -_$ss26DispatchGlobalTaskExecutorCScFsWP -_$ss26DispatchGlobalTaskExecutorCSchsMc -_$ss26DispatchGlobalTaskExecutorCSchsWP -_$ss26DispatchGlobalTaskExecutorCfD -_$ss26DispatchGlobalTaskExecutorCfd -_$ss26DispatchGlobalTaskExecutorCs011SchedulableD0sMc -_$ss26DispatchGlobalTaskExecutorCs011SchedulableD0sWP +_$ss24_PlatformExecutorFactoryV04mainB0s05_MainB0_pvgZ +_$ss24_PlatformExecutorFactoryV04mainB0s05_MainB0_pvpZMV +_$ss24_PlatformExecutorFactoryV07defaultB0Sch_pvgZ +_$ss24_PlatformExecutorFactoryV07defaultB0Sch_pvpZMV +_$ss24_PlatformExecutorFactoryVMa +_$ss24_PlatformExecutorFactoryVMn +_$ss24_PlatformExecutorFactoryVN +_$ss24_PlatformExecutorFactoryVs01_bC0sMc +_$ss24_PlatformExecutorFactoryVs01_bC0sWP _$ss27AsyncThrowingFilterSequenceV04makeA8IteratorAB0F0Vyx_GyF _$ss27AsyncThrowingFilterSequenceV10isIncludedySb7ElementQzYaKcvg _$ss27AsyncThrowingFilterSequenceV10isIncludedySb7ElementQzYaKcvpMV @@ -989,6 +964,31 @@ _$ss27ThrowingDiscardingTaskGroupV7isEmptySbvpMV _$ss27ThrowingDiscardingTaskGroupV9cancelAllyyF _$ss27ThrowingDiscardingTaskGroupVMa _$ss27ThrowingDiscardingTaskGroupVMn +_$ss27_DispatchGlobalTaskExecutorC07_isMainD0SbvgTj +_$ss27_DispatchGlobalTaskExecutorC07_isMainD0SbvgTq +_$ss27_DispatchGlobalTaskExecutorC07_isMainD0SbvpMV +_$ss27_DispatchGlobalTaskExecutorC7enqueueyys0D3JobVnFTj +_$ss27_DispatchGlobalTaskExecutorC7enqueueyys0D3JobVnFTq +_$ss27_DispatchGlobalTaskExecutorC8_enqueue_2at9tolerance5clockys0D3JobVn_7InstantQz8DurationQzSgxts5ClockRzlFTj +_$ss27_DispatchGlobalTaskExecutorC8_enqueue_2at9tolerance5clockys0D3JobVn_7InstantQz8DurationQzSgxts5ClockRzlFTq +_$ss27_DispatchGlobalTaskExecutorCABycfC +_$ss27_DispatchGlobalTaskExecutorCABycfCTj +_$ss27_DispatchGlobalTaskExecutorCABycfCTq +_$ss27_DispatchGlobalTaskExecutorCABycfc +_$ss27_DispatchGlobalTaskExecutorCMa +_$ss27_DispatchGlobalTaskExecutorCMm +_$ss27_DispatchGlobalTaskExecutorCMn +_$ss27_DispatchGlobalTaskExecutorCMo +_$ss27_DispatchGlobalTaskExecutorCMu +_$ss27_DispatchGlobalTaskExecutorCN +_$ss27_DispatchGlobalTaskExecutorCScFsMc +_$ss27_DispatchGlobalTaskExecutorCScFsWP +_$ss27_DispatchGlobalTaskExecutorCSchsMc +_$ss27_DispatchGlobalTaskExecutorCSchsWP +_$ss27_DispatchGlobalTaskExecutorCfD +_$ss27_DispatchGlobalTaskExecutorCfd +_$ss27_DispatchGlobalTaskExecutorCs012_SchedulableD0sMc +_$ss27_DispatchGlobalTaskExecutorCs012_SchedulableD0sWP _$ss27withTaskCancellationHandler9operation8onCancelxxyYaKXE_yyYbXEtYaKlF _$ss27withTaskCancellationHandler9operation8onCancelxxyYaKXE_yyYbXEtYaKlFTu _$ss28AsyncThrowingFlatMapSequenceV04makeA8IteratorAB0G0Vyxq__GyF @@ -1119,26 +1119,26 @@ _$ss5ClockP3now7InstantQzvgTq _$ss5ClockP5sleep5until9tolerancey7InstantQz_8DurationQzSgtYaKFTj _$ss5ClockP5sleep5until9tolerancey7InstantQz_8DurationQzSgtYaKFTjTu _$ss5ClockP5sleep5until9tolerancey7InstantQz_8DurationQzSgtYaKFTq -_$ss5ClockP6traitss0A6TraitsVvgTj -_$ss5ClockP6traitss0A6TraitsVvgTq _$ss5ClockP7InstantAB_s0B8ProtocolTn -_$ss5ClockP7convert4from8DurationQzSgsAEV_tFTj -_$ss5ClockP7convert4from8DurationQzSgsAEV_tFTq -_$ss5ClockP7convert4froms8DurationVSgAEQz_tFTj -_$ss5ClockP7convert4froms8DurationVSgAEQz_tFTq -_$ss5ClockP7convert7instant4from7InstantQzSgAFQyd___qd__tsAARd__lFTj -_$ss5ClockP7convert7instant4from7InstantQzSgAFQyd___qd__tsAARd__lFTq -_$ss5ClockPsE6traitss0A6TraitsVvg -_$ss5ClockPsE6traitss0A6TraitsVvpMV -_$ss5ClockPsE7convert4from8DurationQzSgsAEV_tF -_$ss5ClockPsE7convert4froms8DurationVSgAEQz_tF -_$ss5ClockPsE7convert7instant4from7InstantQzSgAFQyd___qd__tsAARd__lF +_$ss5ClockP7_traitss01_A6TraitsVvgTj +_$ss5ClockP7_traitss01_A6TraitsVvgTq +_$ss5ClockP8_convert4from8DurationQzSgsAEV_tFTj +_$ss5ClockP8_convert4from8DurationQzSgsAEV_tFTq +_$ss5ClockP8_convert4froms8DurationVSgAEQz_tFTj +_$ss5ClockP8_convert4froms8DurationVSgAEQz_tFTq +_$ss5ClockP8_convert7instant4from7InstantQzSgAFQyd___qd__tsAARd__lFTj +_$ss5ClockP8_convert7instant4from7InstantQzSgAFQyd___qd__tsAARd__lFTq +_$ss5ClockPsE7_traitss01_A6TraitsVvg +_$ss5ClockPsE7_traitss01_A6TraitsVvpMV _$ss5ClockPsE7measurey8DurationQzyyKXEKF _$ss5ClockPsE7measurey8DurationQzyyYaKXEYaKF _$ss5ClockPsE7measurey8DurationQzyyYaKXEYaKFTu +_$ss5ClockPsE8_convert4from8DurationQzSgsAEV_tF +_$ss5ClockPsE8_convert4froms8DurationVSgAEQz_tF +_$ss5ClockPsE8_convert7instant4from7InstantQzSgAFQyd___qd__tsAARd__lF _$ss5ClockPss010ContinuousA0VRszrlE10continuousADvgZ _$ss5ClockPss010SuspendingA0VRszrlE10suspendingADvgZ -_$ss5ClockPss8DurationVACRtzrlE7convert4fromADSgAD_tF +_$ss5ClockPss8DurationVACRtzrlE8_convert4fromADSgAD_tF _$ss5ClockTL _$ss6_first_5where7ElementQzSgx_SbADYaKXEtYaKSciRzlF _$ss6_first_5where7ElementQzSgx_SbADYaKXEtYaKSciRzlFTu diff --git a/test/abi/Inputs/macOS/x86_64/concurrency/baseline b/test/abi/Inputs/macOS/x86_64/concurrency/baseline index 8aa55b3098c58..002cd69dc8e7d 100644 --- a/test/abi/Inputs/macOS/x86_64/concurrency/baseline +++ b/test/abi/Inputs/macOS/x86_64/concurrency/baseline @@ -23,8 +23,8 @@ _$sScEMa _$sScEMn _$sScEN _$sScEs5ErrorsMc -_$sScF14isMainExecutorSbvgTj -_$sScF14isMainExecutorSbvgTq +_$sScF15_isMainExecutorSbvgTj +_$sScF15_isMainExecutorSbvgTq _$sScF7enqueueyyScJFTj _$sScF7enqueueyyScJFTq _$sScF7enqueueyys11ExecutorJobVnFTj @@ -33,8 +33,8 @@ _$sScF7enqueueyys3JobVnFTj _$sScF7enqueueyys3JobVnFTq _$sScFMp _$sScFTL -_$sScFsE14isMainExecutorSbvg -_$sScFsE14isMainExecutorSbvpMV +_$sScFsE15_isMainExecutorSbvg +_$sScFsE15_isMainExecutorSbvpMV _$sScFsE18_isComplexEqualitySbvg _$sScFsE18_isComplexEqualitySbvpMV _$sScFsE7enqueueyyScJF @@ -96,8 +96,8 @@ _$sScM3run10resultType4bodyxxm_xyYbKScMYcXEtYaKlFZ _$sScM3run10resultType4bodyxxm_xyYbKScMYcXEtYaKlFZTu _$sScM6sharedScMvgZ _$sScM7enqueueyyScJF -_$sScM8executors12MainExecutor_pvgZ -_$sScM8executors12MainExecutor_pvpZMV +_$sScM9_executors13_MainExecutor_pvgZ +_$sScM9_executors13_MainExecutor_pvpZMV _$sScMMa _$sScMMm _$sScMMn @@ -211,16 +211,16 @@ _$sScTss5NeverORs_rlE5valuexvgTu _$sScTss5NeverORs_rlE5valuexvpMV _$sScTss5NeverORszABRs_rlE11isCancelledSbvgZ _$sScTss5NeverORszABRs_rlE12basePriorityScPSgvgZ -_$sScTss5NeverORszABRs_rlE15currentExecutorScF_pvgZ -_$sScTss5NeverORszABRs_rlE15currentExecutorScF_pvpZMV _$sScTss5NeverORszABRs_rlE15currentPriorityScPvgZ -_$sScTss5NeverORszABRs_rlE15defaultExecutorSch_pvgZ -_$sScTss5NeverORszABRs_rlE15defaultExecutorSch_pvpZMV +_$sScTss5NeverORszABRs_rlE16_currentExecutorScF_pvgZ +_$sScTss5NeverORszABRs_rlE16_currentExecutorScF_pvpZMV +_$sScTss5NeverORszABRs_rlE16_defaultExecutorSch_pvgZ +_$sScTss5NeverORszABRs_rlE16_defaultExecutorSch_pvpZMV _$sScTss5NeverORszABRs_rlE17checkCancellationyyKFZ -_$sScTss5NeverORszABRs_rlE17preferredExecutorSch_pSgvgZ -_$sScTss5NeverORszABRs_rlE17preferredExecutorSch_pSgvpZMV -_$sScTss5NeverORszABRs_rlE26currentSchedulableExecutors0cD0_pSgvgZ -_$sScTss5NeverORszABRs_rlE26currentSchedulableExecutors0cD0_pSgvpZMV +_$sScTss5NeverORszABRs_rlE18_preferredExecutorSch_pSgvgZ +_$sScTss5NeverORszABRs_rlE18_preferredExecutorSch_pSgvpZMV +_$sScTss5NeverORszABRs_rlE27_currentSchedulableExecutors01_cD0_pSgvgZ +_$sScTss5NeverORszABRs_rlE27_currentSchedulableExecutors01_cD0_pSgvpZMV _$sScTss5NeverORszABRs_rlE5sleep11nanosecondsys6UInt64V_tYaKFZ _$sScTss5NeverORszABRs_rlE5sleep11nanosecondsys6UInt64V_tYaKFZTu _$sScTss5NeverORszABRs_rlE5sleep5until9tolerance5clocky7InstantQyd___8DurationQyd__Sgqd__tYaKs5ClockRd__lFZ @@ -238,7 +238,7 @@ _$sScc7contextBcvs _$sSccMa _$sSccMn _$sSce15complexEqualityScexh_tcScfRzlufC -_$sSce16asSerialExecutorScf_pSgyF +_$sSce17_asSerialExecutorScf_pSgyF _$sSce18_isComplexEqualitySbvg _$sSce18_isComplexEqualitySbvpMV _$sSce8executorBevM @@ -267,8 +267,8 @@ _$sScfMp _$sScfScFTb _$sScfTL _$sScfsE14assertIsolated_4file4lineySSyXK_s12StaticStringVSutF -_$sScfsE14isMainExecutorSbvg -_$sScfsE14isMainExecutorSbvpMV +_$sScfsE15_isMainExecutorSbvg +_$sScfsE15_isMainExecutorSbvpMV _$sScfsE20preconditionIsolated_4file4lineySSyXK_s12StaticStringVSutF _$sScfsE23asUnownedSerialExecutorSceyF _$sScfsE31isSameExclusiveExecutionContext5otherSbx_tF @@ -405,24 +405,7 @@ _$sSctN _$sSctSHsMc _$sSctSQsMc _$ss039_checkIllegalTaskLocalBindingWithinWithC5Group4file4lineySS_SutF -_$ss11ClockTraitsV10continuousABvgZ -_$ss11ClockTraitsV10continuousABvpZMV -_$ss11ClockTraitsV8rawValueABs6UInt32V_tcfC -_$ss11ClockTraitsV8rawValues6UInt32Vvg -_$ss11ClockTraitsV8rawValues6UInt32VvpMV -_$ss11ClockTraitsV8wallTimeABvgZ -_$ss11ClockTraitsV8wallTimeABvpZMV -_$ss11ClockTraitsV9monotonicABvgZ -_$ss11ClockTraitsV9monotonicABvpZMV -_$ss11ClockTraitsVMa -_$ss11ClockTraitsVMn -_$ss11ClockTraitsVN -_$ss11ClockTraitsVSQsMc -_$ss11ClockTraitsVSYsMc -_$ss11ClockTraitsVs10SetAlgebrasMc -_$ss11ClockTraitsVs25ExpressibleByArrayLiteralsMc -_$ss11ClockTraitsVs9OptionSetsMc -_$ss11ExecutorJobV010withUnsafeA11PrivateData4bodyxxSwq_YKXE_tq_YKs5ErrorR_r0_lF +_$ss11ExecutorJobV011_withUnsafeA11PrivateData4bodyxxSwq_YKXE_tq_YKs5ErrorR_r0_lF _$ss11ExecutorJobV11descriptionSSvg _$ss11ExecutorJobV14LocalAllocatorV10deallocateyySpyxGlF _$ss11ExecutorJobV14LocalAllocatorV10deallocateyySryxGlF @@ -433,20 +416,20 @@ _$ss11ExecutorJobV14LocalAllocatorV8allocate8capacitySwSi_tF _$ss11ExecutorJobV14LocalAllocatorVMa _$ss11ExecutorJobV14LocalAllocatorVMn _$ss11ExecutorJobV14LocalAllocatorVN -_$ss11ExecutorJobV4KindV13firstReservedADvgZ -_$ss11ExecutorJobV4KindV13firstReservedADvpZMV -_$ss11ExecutorJobV4KindV4taskADvgZ -_$ss11ExecutorJobV4KindV4taskADvpZMV -_$ss11ExecutorJobV4KindV8rawValueADSgs5UInt8V_tcfC -_$ss11ExecutorJobV4KindV8rawValues5UInt8VvM -_$ss11ExecutorJobV4KindV8rawValues5UInt8Vvg -_$ss11ExecutorJobV4KindV8rawValues5UInt8VvpMV -_$ss11ExecutorJobV4KindV8rawValues5UInt8Vvs -_$ss11ExecutorJobV4KindVMa -_$ss11ExecutorJobV4KindVMn -_$ss11ExecutorJobV4KindVN -_$ss11ExecutorJobV4KindVSYsMc -_$ss11ExecutorJobV4kindAB4KindVvg +_$ss11ExecutorJobV5_KindV13firstReservedADvgZ +_$ss11ExecutorJobV5_KindV13firstReservedADvpZMV +_$ss11ExecutorJobV5_KindV4taskADvgZ +_$ss11ExecutorJobV5_KindV4taskADvpZMV +_$ss11ExecutorJobV5_KindV8rawValueADSgs5UInt8V_tcfC +_$ss11ExecutorJobV5_KindV8rawValues5UInt8VvM +_$ss11ExecutorJobV5_KindV8rawValues5UInt8Vvg +_$ss11ExecutorJobV5_KindV8rawValues5UInt8VvpMV +_$ss11ExecutorJobV5_KindV8rawValues5UInt8Vvs +_$ss11ExecutorJobV5_KindVMa +_$ss11ExecutorJobV5_KindVMn +_$ss11ExecutorJobV5_KindVN +_$ss11ExecutorJobV5_KindVSYsMc +_$ss11ExecutorJobV5_kindAB5_KindVvg _$ss11ExecutorJobV7contextABBjn_tcfC _$ss11ExecutorJobV8prioritys0B8PriorityVvg _$ss11ExecutorJobV9allocatorAB14LocalAllocatorVSgvg @@ -480,33 +463,30 @@ _$ss11JobPriorityVMn _$ss11JobPriorityVN _$ss11JobPriorityVSLsMc _$ss11JobPriorityVSQsMc -_$ss12MainExecutorMp -_$ss12MainExecutorPScfTb -_$ss12MainExecutorPs07RunLoopB0Tb -_$ss12MainExecutorTL +_$ss12_ClockTraitsV10continuousABvgZ +_$ss12_ClockTraitsV10continuousABvpZMV +_$ss12_ClockTraitsV8rawValueABs6UInt32V_tcfC +_$ss12_ClockTraitsV8rawValues6UInt32Vvg +_$ss12_ClockTraitsV8rawValues6UInt32VvpMV +_$ss12_ClockTraitsV8wallTimeABvgZ +_$ss12_ClockTraitsV8wallTimeABvpZMV +_$ss12_ClockTraitsV9monotonicABvgZ +_$ss12_ClockTraitsV9monotonicABvpZMV +_$ss12_ClockTraitsVMa +_$ss12_ClockTraitsVMn +_$ss12_ClockTraitsVN +_$ss12_ClockTraitsVSQsMc +_$ss12_ClockTraitsVSYsMc +_$ss12_ClockTraitsVs10SetAlgebrasMc +_$ss12_ClockTraitsVs25ExpressibleByArrayLiteralsMc +_$ss12_ClockTraitsVs9OptionSetsMc +_$ss13_MainExecutorMp +_$ss13_MainExecutorPScfTb +_$ss13_MainExecutorPs08_RunLoopB0Tb +_$ss13_MainExecutorTL _$ss13_runAsyncMainyyyyYaKcF _$ss13withTaskGroup2of9returning4bodyq_xm_q_mq_ScGyxGzYaXEtYar0_lF _$ss13withTaskGroup2of9returning4bodyq_xm_q_mq_ScGyxGzYaXEtYar0_lFTu -_$ss14CFMainExecutorC3runyyKF -_$ss14CFMainExecutorC4stopyyF -_$ss14CFMainExecutorCABycfC -_$ss14CFMainExecutorCABycfc -_$ss14CFMainExecutorCMa -_$ss14CFMainExecutorCMm -_$ss14CFMainExecutorCMn -_$ss14CFMainExecutorCMo -_$ss14CFMainExecutorCN -_$ss14CFMainExecutorCfD -_$ss14CFMainExecutorCfd -_$ss14CFTaskExecutorCABycfC -_$ss14CFTaskExecutorCABycfc -_$ss14CFTaskExecutorCMa -_$ss14CFTaskExecutorCMm -_$ss14CFTaskExecutorCMn -_$ss14CFTaskExecutorCMo -_$ss14CFTaskExecutorCN -_$ss14CFTaskExecutorCfD -_$ss14CFTaskExecutorCfd _$ss15ContinuousClockV17minimumResolutions8DurationVvg _$ss15ContinuousClockV17minimumResolutions8DurationVvpMV _$ss15ContinuousClockV3nowAB7InstantVvg @@ -514,8 +494,6 @@ _$ss15ContinuousClockV3nowAB7InstantVvgZ _$ss15ContinuousClockV3nowAB7InstantVvpMV _$ss15ContinuousClockV5sleep5until9toleranceyAB7InstantV_s8DurationVSgtYaKF _$ss15ContinuousClockV5sleep5until9toleranceyAB7InstantV_s8DurationVSgtYaKFTu -_$ss15ContinuousClockV6traitss0B6TraitsVvg -_$ss15ContinuousClockV6traitss0B6TraitsVvpMV _$ss15ContinuousClockV7InstantV1loiySbAD_ADtFZ _$ss15ContinuousClockV7InstantV2eeoiySbAD_ADtFZ _$ss15ContinuousClockV7InstantV3nowADvgZ @@ -535,28 +513,14 @@ _$ss15ContinuousClockV7InstantVSLsMc _$ss15ContinuousClockV7InstantVSQsMc _$ss15ContinuousClockV7InstantVSesMc _$ss15ContinuousClockV7InstantVs0C8ProtocolsMc +_$ss15ContinuousClockV7_traitss01_B6TraitsVvg +_$ss15ContinuousClockV7_traitss01_B6TraitsVvpMV _$ss15ContinuousClockVABycfC _$ss15ContinuousClockVMa _$ss15ContinuousClockVMn _$ss15ContinuousClockVN _$ss15ContinuousClockVs0B0sMc _$ss15ContinuousClockVs0B0sWP -_$ss15ExecutorFactoryMp -_$ss15ExecutorFactoryP04mainA0s04MainA0_pvgZTj -_$ss15ExecutorFactoryP04mainA0s04MainA0_pvgZTq -_$ss15ExecutorFactoryP07defaultA0Sch_pvgZTj -_$ss15ExecutorFactoryP07defaultA0Sch_pvgZTq -_$ss15ExecutorFactoryTL -_$ss15RunLoopExecutorMp -_$ss15RunLoopExecutorP3runyyKFTj -_$ss15RunLoopExecutorP3runyyKFTq -_$ss15RunLoopExecutorP4stopyyFTj -_$ss15RunLoopExecutorP4stopyyFTq -_$ss15RunLoopExecutorP8runUntilyySbyXEKFTj -_$ss15RunLoopExecutorP8runUntilyySbyXEKFTq -_$ss15RunLoopExecutorPScFTb -_$ss15RunLoopExecutorPsE8runUntilyySbyXEKF -_$ss15RunLoopExecutorTL _$ss15SuspendingClockV17minimumResolutions8DurationVvg _$ss15SuspendingClockV17minimumResolutions8DurationVvpMV _$ss15SuspendingClockV3nowAB7InstantVvg @@ -564,8 +528,6 @@ _$ss15SuspendingClockV3nowAB7InstantVvgZ _$ss15SuspendingClockV3nowAB7InstantVvpMV _$ss15SuspendingClockV5sleep5until9toleranceyAB7InstantV_s8DurationVSgtYaKF _$ss15SuspendingClockV5sleep5until9toleranceyAB7InstantV_s8DurationVSgtYaKFTu -_$ss15SuspendingClockV6traitss0B6TraitsVvg -_$ss15SuspendingClockV6traitss0B6TraitsVvpMV _$ss15SuspendingClockV7InstantV1loiySbAD_ADtFZ _$ss15SuspendingClockV7InstantV1poiyA2D_s8DurationVtFZ _$ss15SuspendingClockV7InstantV1soiyA2D_s8DurationVtFZ @@ -590,12 +552,34 @@ _$ss15SuspendingClockV7InstantVSLsMc _$ss15SuspendingClockV7InstantVSQsMc _$ss15SuspendingClockV7InstantVSesMc _$ss15SuspendingClockV7InstantVs0C8ProtocolsMc +_$ss15SuspendingClockV7_traitss01_B6TraitsVvg +_$ss15SuspendingClockV7_traitss01_B6TraitsVvpMV _$ss15SuspendingClockVABycfC _$ss15SuspendingClockVMa _$ss15SuspendingClockVMn _$ss15SuspendingClockVN _$ss15SuspendingClockVs0B0sMc _$ss15SuspendingClockVs0B0sWP +_$ss15_CFMainExecutorC4_runyyKF +_$ss15_CFMainExecutorC5_stopyyF +_$ss15_CFMainExecutorCABycfC +_$ss15_CFMainExecutorCABycfc +_$ss15_CFMainExecutorCMa +_$ss15_CFMainExecutorCMm +_$ss15_CFMainExecutorCMn +_$ss15_CFMainExecutorCMo +_$ss15_CFMainExecutorCN +_$ss15_CFMainExecutorCfD +_$ss15_CFMainExecutorCfd +_$ss15_CFTaskExecutorCABycfC +_$ss15_CFTaskExecutorCABycfc +_$ss15_CFTaskExecutorCMa +_$ss15_CFTaskExecutorCMm +_$ss15_CFTaskExecutorCMn +_$ss15_CFTaskExecutorCMo +_$ss15_CFTaskExecutorCN +_$ss15_CFTaskExecutorCfD +_$ss15_CFTaskExecutorCfd _$ss16AsyncMapSequenceV04makeA8IteratorAB0E0Vyxq__GyF _$ss16AsyncMapSequenceV4basexvg _$ss16AsyncMapSequenceV4basexvpMV @@ -617,51 +601,67 @@ _$ss16AsyncMapSequenceVMa _$ss16AsyncMapSequenceVMn _$ss16AsyncMapSequenceV_9transformAByxq_Gx_q_7ElementQzYactcfC _$ss16AsyncMapSequenceVyxq_GScisMc -_$ss17DummyMainExecutorC02isbC0Sbvg -_$ss17DummyMainExecutorC02isbC0SbvpMV -_$ss17DummyMainExecutorC13checkIsolatedyyF -_$ss17DummyMainExecutorC3runyyKF -_$ss17DummyMainExecutorC4stopyyF -_$ss17DummyMainExecutorC7enqueueyys0C3JobVnF -_$ss17DummyMainExecutorCABycfC -_$ss17DummyMainExecutorCABycfCTj -_$ss17DummyMainExecutorCABycfCTq -_$ss17DummyMainExecutorCABycfc -_$ss17DummyMainExecutorCMa -_$ss17DummyMainExecutorCMm -_$ss17DummyMainExecutorCMn -_$ss17DummyMainExecutorCMo -_$ss17DummyMainExecutorCMu -_$ss17DummyMainExecutorCN -_$ss17DummyMainExecutorCScFsMc -_$ss17DummyMainExecutorCScFsWP -_$ss17DummyMainExecutorCScfsMc -_$ss17DummyMainExecutorCScfsWP -_$ss17DummyMainExecutorCfD -_$ss17DummyMainExecutorCfd -_$ss17DummyMainExecutorCs07RunLoopC0sMc -_$ss17DummyMainExecutorCs07RunLoopC0sWP -_$ss17DummyMainExecutorCs0bC0sMc -_$ss17DummyMainExecutorCs0bC0sWP -_$ss17DummyTaskExecutorC06isMainC0Sbvg -_$ss17DummyTaskExecutorC06isMainC0SbvpMV -_$ss17DummyTaskExecutorC7enqueueyys0C3JobVnF -_$ss17DummyTaskExecutorCABycfC -_$ss17DummyTaskExecutorCABycfCTj -_$ss17DummyTaskExecutorCABycfCTq -_$ss17DummyTaskExecutorCABycfc -_$ss17DummyTaskExecutorCMa -_$ss17DummyTaskExecutorCMm -_$ss17DummyTaskExecutorCMn -_$ss17DummyTaskExecutorCMo -_$ss17DummyTaskExecutorCMu -_$ss17DummyTaskExecutorCN -_$ss17DummyTaskExecutorCScFsMc -_$ss17DummyTaskExecutorCScFsWP -_$ss17DummyTaskExecutorCSchsMc -_$ss17DummyTaskExecutorCSchsWP -_$ss17DummyTaskExecutorCfD -_$ss17DummyTaskExecutorCfd +_$ss16_ExecutorFactoryMp +_$ss16_ExecutorFactoryP04mainA0s05_MainA0_pvgZTj +_$ss16_ExecutorFactoryP04mainA0s05_MainA0_pvgZTq +_$ss16_ExecutorFactoryP07defaultA0Sch_pvgZTj +_$ss16_ExecutorFactoryP07defaultA0Sch_pvgZTq +_$ss16_ExecutorFactoryTL +_$ss16_RunLoopExecutorMp +_$ss16_RunLoopExecutorP4_runyyKFTj +_$ss16_RunLoopExecutorP4_runyyKFTq +_$ss16_RunLoopExecutorP5_stopyyFTj +_$ss16_RunLoopExecutorP5_stopyyFTq +_$ss16_RunLoopExecutorP9_runUntilyySbyXEKFTj +_$ss16_RunLoopExecutorP9_runUntilyySbyXEKFTq +_$ss16_RunLoopExecutorPScFTb +_$ss16_RunLoopExecutorPsE9_runUntilyySbyXEKF +_$ss16_RunLoopExecutorTL +_$ss18_DummyMainExecutorC03_isbC0Sbvg +_$ss18_DummyMainExecutorC03_isbC0SbvpMV +_$ss18_DummyMainExecutorC13checkIsolatedyyF +_$ss18_DummyMainExecutorC4_runyyKF +_$ss18_DummyMainExecutorC5_stopyyF +_$ss18_DummyMainExecutorC7enqueueyys0C3JobVnF +_$ss18_DummyMainExecutorCABycfC +_$ss18_DummyMainExecutorCABycfCTj +_$ss18_DummyMainExecutorCABycfCTq +_$ss18_DummyMainExecutorCABycfc +_$ss18_DummyMainExecutorCMa +_$ss18_DummyMainExecutorCMm +_$ss18_DummyMainExecutorCMn +_$ss18_DummyMainExecutorCMo +_$ss18_DummyMainExecutorCMu +_$ss18_DummyMainExecutorCN +_$ss18_DummyMainExecutorCScFsMc +_$ss18_DummyMainExecutorCScFsWP +_$ss18_DummyMainExecutorCScfsMc +_$ss18_DummyMainExecutorCScfsWP +_$ss18_DummyMainExecutorCfD +_$ss18_DummyMainExecutorCfd +_$ss18_DummyMainExecutorCs01_bC0sMc +_$ss18_DummyMainExecutorCs01_bC0sWP +_$ss18_DummyMainExecutorCs08_RunLoopC0sMc +_$ss18_DummyMainExecutorCs08_RunLoopC0sWP +_$ss18_DummyTaskExecutorC07_isMainC0Sbvg +_$ss18_DummyTaskExecutorC07_isMainC0SbvpMV +_$ss18_DummyTaskExecutorC7enqueueyys0C3JobVnF +_$ss18_DummyTaskExecutorCABycfC +_$ss18_DummyTaskExecutorCABycfCTj +_$ss18_DummyTaskExecutorCABycfCTq +_$ss18_DummyTaskExecutorCABycfc +_$ss18_DummyTaskExecutorCMa +_$ss18_DummyTaskExecutorCMm +_$ss18_DummyTaskExecutorCMn +_$ss18_DummyTaskExecutorCMo +_$ss18_DummyTaskExecutorCMu +_$ss18_DummyTaskExecutorCN +_$ss18_DummyTaskExecutorCScFsMc +_$ss18_DummyTaskExecutorCScFsWP +_$ss18_DummyTaskExecutorCSchsMc +_$ss18_DummyTaskExecutorCSchsWP +_$ss18_DummyTaskExecutorCfD +_$ss18_DummyTaskExecutorCfd _$ss19AsyncFilterSequenceV04makeA8IteratorAB0E0Vyx_GyF _$ss19AsyncFilterSequenceV10isIncludedySb7ElementQzYacvg _$ss19AsyncFilterSequenceV10isIncludedySb7ElementQzYacvpMV @@ -719,16 +719,7 @@ _$ss19DiscardingTaskGroupV9cancelAllyyF _$ss19DiscardingTaskGroupVMa _$ss19DiscardingTaskGroupVMn _$ss19DiscardingTaskGroupVN -_$ss19SchedulableExecutorMp -_$ss19SchedulableExecutorP7enqueue_2at9tolerance5clockys0B3JobVn_7InstantQyd__8DurationQyd__Sgqd__ts5ClockRd__lFTj -_$ss19SchedulableExecutorP7enqueue_2at9tolerance5clockys0B3JobVn_7InstantQyd__8DurationQyd__Sgqd__ts5ClockRd__lFTq -_$ss19SchedulableExecutorP7enqueue_5after9tolerance5clockys0B3JobVn_8DurationQyd__AJSgqd__ts5ClockRd__lFTj -_$ss19SchedulableExecutorP7enqueue_5after9tolerance5clockys0B3JobVn_8DurationQyd__AJSgqd__ts5ClockRd__lFTq -_$ss19SchedulableExecutorPScFTb -_$ss19SchedulableExecutorPsE7enqueue_2at9tolerance5clockys0B3JobVn_7InstantQyd__8DurationQyd__Sgqd__ts5ClockRd__lF -_$ss19SchedulableExecutorPsE7enqueue_5after9tolerance5clockys0B3JobVn_8DurationQyd__AJSgqd__ts5ClockRd__lF -_$ss19SchedulableExecutorTL -_$ss19UnownedTaskExecutorV02asbC0Sch_pSgyF +_$ss19UnownedTaskExecutorV03_asbC0Sch_pSgyF _$ss19UnownedTaskExecutorVyABxhcSchRzlufC _$ss20AsyncFlatMapSequenceV04makeA8IteratorAB0F0Vyxq__GyF _$ss20AsyncFlatMapSequenceV4basexvg @@ -759,39 +750,48 @@ _$ss20AsyncFlatMapSequenceVMa _$ss20AsyncFlatMapSequenceVMn _$ss20AsyncFlatMapSequenceV_9transformAByxq_Gx_q_7ElementQzYactcfC _$ss20AsyncFlatMapSequenceVyxq_GScisMc -_$ss20DispatchMainExecutorC02isbC0Sbvg -_$ss20DispatchMainExecutorC02isbC0SbvpMV -_$ss20DispatchMainExecutorC13asSchedulables0eC0_pSgvg -_$ss20DispatchMainExecutorC13asSchedulables0eC0_pSgvpMV -_$ss20DispatchMainExecutorC13checkIsolatedyyF -_$ss20DispatchMainExecutorC3runyyKFTj -_$ss20DispatchMainExecutorC3runyyKFTq -_$ss20DispatchMainExecutorC4stopyyFTj -_$ss20DispatchMainExecutorC4stopyyFTq -_$ss20DispatchMainExecutorC7enqueue_2at9tolerance5clockys0C3JobVn_7InstantQz8DurationQzSgxts5ClockRzlF -_$ss20DispatchMainExecutorC7enqueueyys0C3JobVnF -_$ss20DispatchMainExecutorCABycfC -_$ss20DispatchMainExecutorCABycfCTj -_$ss20DispatchMainExecutorCABycfCTq -_$ss20DispatchMainExecutorCABycfc -_$ss20DispatchMainExecutorCMa -_$ss20DispatchMainExecutorCMm -_$ss20DispatchMainExecutorCMn -_$ss20DispatchMainExecutorCMo -_$ss20DispatchMainExecutorCMu -_$ss20DispatchMainExecutorCN -_$ss20DispatchMainExecutorCScFsMc -_$ss20DispatchMainExecutorCScFsWP -_$ss20DispatchMainExecutorCScfsMc -_$ss20DispatchMainExecutorCScfsWP -_$ss20DispatchMainExecutorCfD -_$ss20DispatchMainExecutorCfd -_$ss20DispatchMainExecutorCs011SchedulableC0sMc -_$ss20DispatchMainExecutorCs011SchedulableC0sWP -_$ss20DispatchMainExecutorCs07RunLoopC0sMc -_$ss20DispatchMainExecutorCs07RunLoopC0sWP -_$ss20DispatchMainExecutorCs0bC0sMc -_$ss20DispatchMainExecutorCs0bC0sWP +_$ss20_SchedulableExecutorMp +_$ss20_SchedulableExecutorP8_enqueue_2at9tolerance5clockys0B3JobVn_7InstantQyd__8DurationQyd__Sgqd__ts5ClockRd__lFTj +_$ss20_SchedulableExecutorP8_enqueue_2at9tolerance5clockys0B3JobVn_7InstantQyd__8DurationQyd__Sgqd__ts5ClockRd__lFTq +_$ss20_SchedulableExecutorP8_enqueue_5after9tolerance5clockys0B3JobVn_8DurationQyd__AJSgqd__ts5ClockRd__lFTj +_$ss20_SchedulableExecutorP8_enqueue_5after9tolerance5clockys0B3JobVn_8DurationQyd__AJSgqd__ts5ClockRd__lFTq +_$ss20_SchedulableExecutorPScFTb +_$ss20_SchedulableExecutorPsE8_enqueue_2at9tolerance5clockys0B3JobVn_7InstantQyd__8DurationQyd__Sgqd__ts5ClockRd__lF +_$ss20_SchedulableExecutorPsE8_enqueue_5after9tolerance5clockys0B3JobVn_8DurationQyd__AJSgqd__ts5ClockRd__lF +_$ss20_SchedulableExecutorTL +_$ss21_DispatchMainExecutorC03_isbC0Sbvg +_$ss21_DispatchMainExecutorC03_isbC0SbvpMV +_$ss21_DispatchMainExecutorC13checkIsolatedyyF +_$ss21_DispatchMainExecutorC14_asSchedulables01_eC0_pSgvg +_$ss21_DispatchMainExecutorC14_asSchedulables01_eC0_pSgvpMV +_$ss21_DispatchMainExecutorC4_runyyKFTj +_$ss21_DispatchMainExecutorC4_runyyKFTq +_$ss21_DispatchMainExecutorC5_stopyyFTj +_$ss21_DispatchMainExecutorC5_stopyyFTq +_$ss21_DispatchMainExecutorC7enqueueyys0C3JobVnF +_$ss21_DispatchMainExecutorC8_enqueue_2at9tolerance5clockys0C3JobVn_7InstantQz8DurationQzSgxts5ClockRzlF +_$ss21_DispatchMainExecutorCABycfC +_$ss21_DispatchMainExecutorCABycfCTj +_$ss21_DispatchMainExecutorCABycfCTq +_$ss21_DispatchMainExecutorCABycfc +_$ss21_DispatchMainExecutorCMa +_$ss21_DispatchMainExecutorCMm +_$ss21_DispatchMainExecutorCMn +_$ss21_DispatchMainExecutorCMo +_$ss21_DispatchMainExecutorCMu +_$ss21_DispatchMainExecutorCN +_$ss21_DispatchMainExecutorCScFsMc +_$ss21_DispatchMainExecutorCScFsWP +_$ss21_DispatchMainExecutorCScfsMc +_$ss21_DispatchMainExecutorCScfsWP +_$ss21_DispatchMainExecutorCfD +_$ss21_DispatchMainExecutorCfd +_$ss21_DispatchMainExecutorCs012_SchedulableC0sMc +_$ss21_DispatchMainExecutorCs012_SchedulableC0sWP +_$ss21_DispatchMainExecutorCs01_bC0sMc +_$ss21_DispatchMainExecutorCs01_bC0sWP +_$ss21_DispatchMainExecutorCs08_RunLoopC0sMc +_$ss21_DispatchMainExecutorCs08_RunLoopC0sWP _$ss21withThrowingTaskGroup2of9returning4bodyq_xm_q_mq_Scgyxs5Error_pGzYaKXEtYaKr0_lF _$ss21withThrowingTaskGroup2of9returning4bodyq_xm_q_mq_Scgyxs5Error_pGzYaKXEtYaKr0_lFTu _$ss21withUnsafeCurrentTask4bodyxxSctSgKXE_tKlF @@ -864,15 +864,6 @@ _$ss23AsyncCompactMapSequenceVMa _$ss23AsyncCompactMapSequenceVMn _$ss23AsyncCompactMapSequenceV_9transformAByxq_Gx_q_Sg7ElementQzYactcfC _$ss23AsyncCompactMapSequenceVyxq_GScisMc -_$ss23PlatformExecutorFactoryV04mainB0s04MainB0_pvgZ -_$ss23PlatformExecutorFactoryV04mainB0s04MainB0_pvpZMV -_$ss23PlatformExecutorFactoryV07defaultB0Sch_pvgZ -_$ss23PlatformExecutorFactoryV07defaultB0Sch_pvpZMV -_$ss23PlatformExecutorFactoryVMa -_$ss23PlatformExecutorFactoryVMn -_$ss23PlatformExecutorFactoryVN -_$ss23PlatformExecutorFactoryVs0bC0sMc -_$ss23PlatformExecutorFactoryVs0bC0sWP _$ss23withCheckedContinuation8function_xSS_yScCyxs5NeverOGXEtYalF _$ss23withCheckedContinuation8function_xSS_yScCyxs5NeverOGXEtYalFTu _$ss23withDiscardingTaskGroup9returning4bodyxxm_xs0bcD0VzYaXEtYalF @@ -927,31 +918,15 @@ _$ss24AsyncThrowingMapSequenceVMa _$ss24AsyncThrowingMapSequenceVMn _$ss24AsyncThrowingMapSequenceV_9transformAByxq_Gx_q_7ElementQzYaKctcfC _$ss24AsyncThrowingMapSequenceVyxq_GScisMc -_$ss26DispatchGlobalTaskExecutorC06isMainD0SbvgTj -_$ss26DispatchGlobalTaskExecutorC06isMainD0SbvgTq -_$ss26DispatchGlobalTaskExecutorC06isMainD0SbvpMV -_$ss26DispatchGlobalTaskExecutorC7enqueue_2at9tolerance5clockys0D3JobVn_7InstantQz8DurationQzSgxts5ClockRzlFTj -_$ss26DispatchGlobalTaskExecutorC7enqueue_2at9tolerance5clockys0D3JobVn_7InstantQz8DurationQzSgxts5ClockRzlFTq -_$ss26DispatchGlobalTaskExecutorC7enqueueyys0D3JobVnFTj -_$ss26DispatchGlobalTaskExecutorC7enqueueyys0D3JobVnFTq -_$ss26DispatchGlobalTaskExecutorCABycfC -_$ss26DispatchGlobalTaskExecutorCABycfCTj -_$ss26DispatchGlobalTaskExecutorCABycfCTq -_$ss26DispatchGlobalTaskExecutorCABycfc -_$ss26DispatchGlobalTaskExecutorCMa -_$ss26DispatchGlobalTaskExecutorCMm -_$ss26DispatchGlobalTaskExecutorCMn -_$ss26DispatchGlobalTaskExecutorCMo -_$ss26DispatchGlobalTaskExecutorCMu -_$ss26DispatchGlobalTaskExecutorCN -_$ss26DispatchGlobalTaskExecutorCScFsMc -_$ss26DispatchGlobalTaskExecutorCScFsWP -_$ss26DispatchGlobalTaskExecutorCSchsMc -_$ss26DispatchGlobalTaskExecutorCSchsWP -_$ss26DispatchGlobalTaskExecutorCfD -_$ss26DispatchGlobalTaskExecutorCfd -_$ss26DispatchGlobalTaskExecutorCs011SchedulableD0sMc -_$ss26DispatchGlobalTaskExecutorCs011SchedulableD0sWP +_$ss24_PlatformExecutorFactoryV04mainB0s05_MainB0_pvgZ +_$ss24_PlatformExecutorFactoryV04mainB0s05_MainB0_pvpZMV +_$ss24_PlatformExecutorFactoryV07defaultB0Sch_pvgZ +_$ss24_PlatformExecutorFactoryV07defaultB0Sch_pvpZMV +_$ss24_PlatformExecutorFactoryVMa +_$ss24_PlatformExecutorFactoryVMn +_$ss24_PlatformExecutorFactoryVN +_$ss24_PlatformExecutorFactoryVs01_bC0sMc +_$ss24_PlatformExecutorFactoryVs01_bC0sWP _$ss27AsyncThrowingFilterSequenceV04makeA8IteratorAB0F0Vyx_GyF _$ss27AsyncThrowingFilterSequenceV10isIncludedySb7ElementQzYaKcvg _$ss27AsyncThrowingFilterSequenceV10isIncludedySb7ElementQzYaKcvpMV @@ -989,6 +964,31 @@ _$ss27ThrowingDiscardingTaskGroupV7isEmptySbvpMV _$ss27ThrowingDiscardingTaskGroupV9cancelAllyyF _$ss27ThrowingDiscardingTaskGroupVMa _$ss27ThrowingDiscardingTaskGroupVMn +_$ss27_DispatchGlobalTaskExecutorC07_isMainD0SbvgTj +_$ss27_DispatchGlobalTaskExecutorC07_isMainD0SbvgTq +_$ss27_DispatchGlobalTaskExecutorC07_isMainD0SbvpMV +_$ss27_DispatchGlobalTaskExecutorC7enqueueyys0D3JobVnFTj +_$ss27_DispatchGlobalTaskExecutorC7enqueueyys0D3JobVnFTq +_$ss27_DispatchGlobalTaskExecutorC8_enqueue_2at9tolerance5clockys0D3JobVn_7InstantQz8DurationQzSgxts5ClockRzlFTj +_$ss27_DispatchGlobalTaskExecutorC8_enqueue_2at9tolerance5clockys0D3JobVn_7InstantQz8DurationQzSgxts5ClockRzlFTq +_$ss27_DispatchGlobalTaskExecutorCABycfC +_$ss27_DispatchGlobalTaskExecutorCABycfCTj +_$ss27_DispatchGlobalTaskExecutorCABycfCTq +_$ss27_DispatchGlobalTaskExecutorCABycfc +_$ss27_DispatchGlobalTaskExecutorCMa +_$ss27_DispatchGlobalTaskExecutorCMm +_$ss27_DispatchGlobalTaskExecutorCMn +_$ss27_DispatchGlobalTaskExecutorCMo +_$ss27_DispatchGlobalTaskExecutorCMu +_$ss27_DispatchGlobalTaskExecutorCN +_$ss27_DispatchGlobalTaskExecutorCScFsMc +_$ss27_DispatchGlobalTaskExecutorCScFsWP +_$ss27_DispatchGlobalTaskExecutorCSchsMc +_$ss27_DispatchGlobalTaskExecutorCSchsWP +_$ss27_DispatchGlobalTaskExecutorCfD +_$ss27_DispatchGlobalTaskExecutorCfd +_$ss27_DispatchGlobalTaskExecutorCs012_SchedulableD0sMc +_$ss27_DispatchGlobalTaskExecutorCs012_SchedulableD0sWP _$ss27withTaskCancellationHandler9operation8onCancelxxyYaKXE_yyYbXEtYaKlF _$ss27withTaskCancellationHandler9operation8onCancelxxyYaKXE_yyYbXEtYaKlFTu _$ss28AsyncThrowingFlatMapSequenceV04makeA8IteratorAB0G0Vyxq__GyF @@ -1119,26 +1119,26 @@ _$ss5ClockP3now7InstantQzvgTq _$ss5ClockP5sleep5until9tolerancey7InstantQz_8DurationQzSgtYaKFTj _$ss5ClockP5sleep5until9tolerancey7InstantQz_8DurationQzSgtYaKFTjTu _$ss5ClockP5sleep5until9tolerancey7InstantQz_8DurationQzSgtYaKFTq -_$ss5ClockP6traitss0A6TraitsVvgTj -_$ss5ClockP6traitss0A6TraitsVvgTq _$ss5ClockP7InstantAB_s0B8ProtocolTn -_$ss5ClockP7convert4from8DurationQzSgsAEV_tFTj -_$ss5ClockP7convert4from8DurationQzSgsAEV_tFTq -_$ss5ClockP7convert4froms8DurationVSgAEQz_tFTj -_$ss5ClockP7convert4froms8DurationVSgAEQz_tFTq -_$ss5ClockP7convert7instant4from7InstantQzSgAFQyd___qd__tsAARd__lFTj -_$ss5ClockP7convert7instant4from7InstantQzSgAFQyd___qd__tsAARd__lFTq -_$ss5ClockPsE6traitss0A6TraitsVvg -_$ss5ClockPsE6traitss0A6TraitsVvpMV -_$ss5ClockPsE7convert4from8DurationQzSgsAEV_tF -_$ss5ClockPsE7convert4froms8DurationVSgAEQz_tF -_$ss5ClockPsE7convert7instant4from7InstantQzSgAFQyd___qd__tsAARd__lF +_$ss5ClockP7_traitss01_A6TraitsVvgTj +_$ss5ClockP7_traitss01_A6TraitsVvgTq +_$ss5ClockP8_convert4from8DurationQzSgsAEV_tFTj +_$ss5ClockP8_convert4from8DurationQzSgsAEV_tFTq +_$ss5ClockP8_convert4froms8DurationVSgAEQz_tFTj +_$ss5ClockP8_convert4froms8DurationVSgAEQz_tFTq +_$ss5ClockP8_convert7instant4from7InstantQzSgAFQyd___qd__tsAARd__lFTj +_$ss5ClockP8_convert7instant4from7InstantQzSgAFQyd___qd__tsAARd__lFTq +_$ss5ClockPsE7_traitss01_A6TraitsVvg +_$ss5ClockPsE7_traitss01_A6TraitsVvpMV _$ss5ClockPsE7measurey8DurationQzyyKXEKF _$ss5ClockPsE7measurey8DurationQzyyYaKXEYaKF _$ss5ClockPsE7measurey8DurationQzyyYaKXEYaKFTu +_$ss5ClockPsE8_convert4from8DurationQzSgsAEV_tF +_$ss5ClockPsE8_convert4froms8DurationVSgAEQz_tF +_$ss5ClockPsE8_convert7instant4from7InstantQzSgAFQyd___qd__tsAARd__lF _$ss5ClockPss010ContinuousA0VRszrlE10continuousADvgZ _$ss5ClockPss010SuspendingA0VRszrlE10suspendingADvgZ -_$ss5ClockPss8DurationVACRtzrlE7convert4fromADSgAD_tF +_$ss5ClockPss8DurationVACRtzrlE8_convert4fromADSgAD_tF _$ss5ClockTL _$ss6_first_5where7ElementQzSgx_SbADYaKXEtYaKSciRzlF _$ss6_first_5where7ElementQzSgx_SbADYaKXEtYaKSciRzlFTu diff --git a/test/abi/Inputs/macOS/x86_64/concurrency/baseline-asserts b/test/abi/Inputs/macOS/x86_64/concurrency/baseline-asserts index 8aa55b3098c58..002cd69dc8e7d 100644 --- a/test/abi/Inputs/macOS/x86_64/concurrency/baseline-asserts +++ b/test/abi/Inputs/macOS/x86_64/concurrency/baseline-asserts @@ -23,8 +23,8 @@ _$sScEMa _$sScEMn _$sScEN _$sScEs5ErrorsMc -_$sScF14isMainExecutorSbvgTj -_$sScF14isMainExecutorSbvgTq +_$sScF15_isMainExecutorSbvgTj +_$sScF15_isMainExecutorSbvgTq _$sScF7enqueueyyScJFTj _$sScF7enqueueyyScJFTq _$sScF7enqueueyys11ExecutorJobVnFTj @@ -33,8 +33,8 @@ _$sScF7enqueueyys3JobVnFTj _$sScF7enqueueyys3JobVnFTq _$sScFMp _$sScFTL -_$sScFsE14isMainExecutorSbvg -_$sScFsE14isMainExecutorSbvpMV +_$sScFsE15_isMainExecutorSbvg +_$sScFsE15_isMainExecutorSbvpMV _$sScFsE18_isComplexEqualitySbvg _$sScFsE18_isComplexEqualitySbvpMV _$sScFsE7enqueueyyScJF @@ -96,8 +96,8 @@ _$sScM3run10resultType4bodyxxm_xyYbKScMYcXEtYaKlFZ _$sScM3run10resultType4bodyxxm_xyYbKScMYcXEtYaKlFZTu _$sScM6sharedScMvgZ _$sScM7enqueueyyScJF -_$sScM8executors12MainExecutor_pvgZ -_$sScM8executors12MainExecutor_pvpZMV +_$sScM9_executors13_MainExecutor_pvgZ +_$sScM9_executors13_MainExecutor_pvpZMV _$sScMMa _$sScMMm _$sScMMn @@ -211,16 +211,16 @@ _$sScTss5NeverORs_rlE5valuexvgTu _$sScTss5NeverORs_rlE5valuexvpMV _$sScTss5NeverORszABRs_rlE11isCancelledSbvgZ _$sScTss5NeverORszABRs_rlE12basePriorityScPSgvgZ -_$sScTss5NeverORszABRs_rlE15currentExecutorScF_pvgZ -_$sScTss5NeverORszABRs_rlE15currentExecutorScF_pvpZMV _$sScTss5NeverORszABRs_rlE15currentPriorityScPvgZ -_$sScTss5NeverORszABRs_rlE15defaultExecutorSch_pvgZ -_$sScTss5NeverORszABRs_rlE15defaultExecutorSch_pvpZMV +_$sScTss5NeverORszABRs_rlE16_currentExecutorScF_pvgZ +_$sScTss5NeverORszABRs_rlE16_currentExecutorScF_pvpZMV +_$sScTss5NeverORszABRs_rlE16_defaultExecutorSch_pvgZ +_$sScTss5NeverORszABRs_rlE16_defaultExecutorSch_pvpZMV _$sScTss5NeverORszABRs_rlE17checkCancellationyyKFZ -_$sScTss5NeverORszABRs_rlE17preferredExecutorSch_pSgvgZ -_$sScTss5NeverORszABRs_rlE17preferredExecutorSch_pSgvpZMV -_$sScTss5NeverORszABRs_rlE26currentSchedulableExecutors0cD0_pSgvgZ -_$sScTss5NeverORszABRs_rlE26currentSchedulableExecutors0cD0_pSgvpZMV +_$sScTss5NeverORszABRs_rlE18_preferredExecutorSch_pSgvgZ +_$sScTss5NeverORszABRs_rlE18_preferredExecutorSch_pSgvpZMV +_$sScTss5NeverORszABRs_rlE27_currentSchedulableExecutors01_cD0_pSgvgZ +_$sScTss5NeverORszABRs_rlE27_currentSchedulableExecutors01_cD0_pSgvpZMV _$sScTss5NeverORszABRs_rlE5sleep11nanosecondsys6UInt64V_tYaKFZ _$sScTss5NeverORszABRs_rlE5sleep11nanosecondsys6UInt64V_tYaKFZTu _$sScTss5NeverORszABRs_rlE5sleep5until9tolerance5clocky7InstantQyd___8DurationQyd__Sgqd__tYaKs5ClockRd__lFZ @@ -238,7 +238,7 @@ _$sScc7contextBcvs _$sSccMa _$sSccMn _$sSce15complexEqualityScexh_tcScfRzlufC -_$sSce16asSerialExecutorScf_pSgyF +_$sSce17_asSerialExecutorScf_pSgyF _$sSce18_isComplexEqualitySbvg _$sSce18_isComplexEqualitySbvpMV _$sSce8executorBevM @@ -267,8 +267,8 @@ _$sScfMp _$sScfScFTb _$sScfTL _$sScfsE14assertIsolated_4file4lineySSyXK_s12StaticStringVSutF -_$sScfsE14isMainExecutorSbvg -_$sScfsE14isMainExecutorSbvpMV +_$sScfsE15_isMainExecutorSbvg +_$sScfsE15_isMainExecutorSbvpMV _$sScfsE20preconditionIsolated_4file4lineySSyXK_s12StaticStringVSutF _$sScfsE23asUnownedSerialExecutorSceyF _$sScfsE31isSameExclusiveExecutionContext5otherSbx_tF @@ -405,24 +405,7 @@ _$sSctN _$sSctSHsMc _$sSctSQsMc _$ss039_checkIllegalTaskLocalBindingWithinWithC5Group4file4lineySS_SutF -_$ss11ClockTraitsV10continuousABvgZ -_$ss11ClockTraitsV10continuousABvpZMV -_$ss11ClockTraitsV8rawValueABs6UInt32V_tcfC -_$ss11ClockTraitsV8rawValues6UInt32Vvg -_$ss11ClockTraitsV8rawValues6UInt32VvpMV -_$ss11ClockTraitsV8wallTimeABvgZ -_$ss11ClockTraitsV8wallTimeABvpZMV -_$ss11ClockTraitsV9monotonicABvgZ -_$ss11ClockTraitsV9monotonicABvpZMV -_$ss11ClockTraitsVMa -_$ss11ClockTraitsVMn -_$ss11ClockTraitsVN -_$ss11ClockTraitsVSQsMc -_$ss11ClockTraitsVSYsMc -_$ss11ClockTraitsVs10SetAlgebrasMc -_$ss11ClockTraitsVs25ExpressibleByArrayLiteralsMc -_$ss11ClockTraitsVs9OptionSetsMc -_$ss11ExecutorJobV010withUnsafeA11PrivateData4bodyxxSwq_YKXE_tq_YKs5ErrorR_r0_lF +_$ss11ExecutorJobV011_withUnsafeA11PrivateData4bodyxxSwq_YKXE_tq_YKs5ErrorR_r0_lF _$ss11ExecutorJobV11descriptionSSvg _$ss11ExecutorJobV14LocalAllocatorV10deallocateyySpyxGlF _$ss11ExecutorJobV14LocalAllocatorV10deallocateyySryxGlF @@ -433,20 +416,20 @@ _$ss11ExecutorJobV14LocalAllocatorV8allocate8capacitySwSi_tF _$ss11ExecutorJobV14LocalAllocatorVMa _$ss11ExecutorJobV14LocalAllocatorVMn _$ss11ExecutorJobV14LocalAllocatorVN -_$ss11ExecutorJobV4KindV13firstReservedADvgZ -_$ss11ExecutorJobV4KindV13firstReservedADvpZMV -_$ss11ExecutorJobV4KindV4taskADvgZ -_$ss11ExecutorJobV4KindV4taskADvpZMV -_$ss11ExecutorJobV4KindV8rawValueADSgs5UInt8V_tcfC -_$ss11ExecutorJobV4KindV8rawValues5UInt8VvM -_$ss11ExecutorJobV4KindV8rawValues5UInt8Vvg -_$ss11ExecutorJobV4KindV8rawValues5UInt8VvpMV -_$ss11ExecutorJobV4KindV8rawValues5UInt8Vvs -_$ss11ExecutorJobV4KindVMa -_$ss11ExecutorJobV4KindVMn -_$ss11ExecutorJobV4KindVN -_$ss11ExecutorJobV4KindVSYsMc -_$ss11ExecutorJobV4kindAB4KindVvg +_$ss11ExecutorJobV5_KindV13firstReservedADvgZ +_$ss11ExecutorJobV5_KindV13firstReservedADvpZMV +_$ss11ExecutorJobV5_KindV4taskADvgZ +_$ss11ExecutorJobV5_KindV4taskADvpZMV +_$ss11ExecutorJobV5_KindV8rawValueADSgs5UInt8V_tcfC +_$ss11ExecutorJobV5_KindV8rawValues5UInt8VvM +_$ss11ExecutorJobV5_KindV8rawValues5UInt8Vvg +_$ss11ExecutorJobV5_KindV8rawValues5UInt8VvpMV +_$ss11ExecutorJobV5_KindV8rawValues5UInt8Vvs +_$ss11ExecutorJobV5_KindVMa +_$ss11ExecutorJobV5_KindVMn +_$ss11ExecutorJobV5_KindVN +_$ss11ExecutorJobV5_KindVSYsMc +_$ss11ExecutorJobV5_kindAB5_KindVvg _$ss11ExecutorJobV7contextABBjn_tcfC _$ss11ExecutorJobV8prioritys0B8PriorityVvg _$ss11ExecutorJobV9allocatorAB14LocalAllocatorVSgvg @@ -480,33 +463,30 @@ _$ss11JobPriorityVMn _$ss11JobPriorityVN _$ss11JobPriorityVSLsMc _$ss11JobPriorityVSQsMc -_$ss12MainExecutorMp -_$ss12MainExecutorPScfTb -_$ss12MainExecutorPs07RunLoopB0Tb -_$ss12MainExecutorTL +_$ss12_ClockTraitsV10continuousABvgZ +_$ss12_ClockTraitsV10continuousABvpZMV +_$ss12_ClockTraitsV8rawValueABs6UInt32V_tcfC +_$ss12_ClockTraitsV8rawValues6UInt32Vvg +_$ss12_ClockTraitsV8rawValues6UInt32VvpMV +_$ss12_ClockTraitsV8wallTimeABvgZ +_$ss12_ClockTraitsV8wallTimeABvpZMV +_$ss12_ClockTraitsV9monotonicABvgZ +_$ss12_ClockTraitsV9monotonicABvpZMV +_$ss12_ClockTraitsVMa +_$ss12_ClockTraitsVMn +_$ss12_ClockTraitsVN +_$ss12_ClockTraitsVSQsMc +_$ss12_ClockTraitsVSYsMc +_$ss12_ClockTraitsVs10SetAlgebrasMc +_$ss12_ClockTraitsVs25ExpressibleByArrayLiteralsMc +_$ss12_ClockTraitsVs9OptionSetsMc +_$ss13_MainExecutorMp +_$ss13_MainExecutorPScfTb +_$ss13_MainExecutorPs08_RunLoopB0Tb +_$ss13_MainExecutorTL _$ss13_runAsyncMainyyyyYaKcF _$ss13withTaskGroup2of9returning4bodyq_xm_q_mq_ScGyxGzYaXEtYar0_lF _$ss13withTaskGroup2of9returning4bodyq_xm_q_mq_ScGyxGzYaXEtYar0_lFTu -_$ss14CFMainExecutorC3runyyKF -_$ss14CFMainExecutorC4stopyyF -_$ss14CFMainExecutorCABycfC -_$ss14CFMainExecutorCABycfc -_$ss14CFMainExecutorCMa -_$ss14CFMainExecutorCMm -_$ss14CFMainExecutorCMn -_$ss14CFMainExecutorCMo -_$ss14CFMainExecutorCN -_$ss14CFMainExecutorCfD -_$ss14CFMainExecutorCfd -_$ss14CFTaskExecutorCABycfC -_$ss14CFTaskExecutorCABycfc -_$ss14CFTaskExecutorCMa -_$ss14CFTaskExecutorCMm -_$ss14CFTaskExecutorCMn -_$ss14CFTaskExecutorCMo -_$ss14CFTaskExecutorCN -_$ss14CFTaskExecutorCfD -_$ss14CFTaskExecutorCfd _$ss15ContinuousClockV17minimumResolutions8DurationVvg _$ss15ContinuousClockV17minimumResolutions8DurationVvpMV _$ss15ContinuousClockV3nowAB7InstantVvg @@ -514,8 +494,6 @@ _$ss15ContinuousClockV3nowAB7InstantVvgZ _$ss15ContinuousClockV3nowAB7InstantVvpMV _$ss15ContinuousClockV5sleep5until9toleranceyAB7InstantV_s8DurationVSgtYaKF _$ss15ContinuousClockV5sleep5until9toleranceyAB7InstantV_s8DurationVSgtYaKFTu -_$ss15ContinuousClockV6traitss0B6TraitsVvg -_$ss15ContinuousClockV6traitss0B6TraitsVvpMV _$ss15ContinuousClockV7InstantV1loiySbAD_ADtFZ _$ss15ContinuousClockV7InstantV2eeoiySbAD_ADtFZ _$ss15ContinuousClockV7InstantV3nowADvgZ @@ -535,28 +513,14 @@ _$ss15ContinuousClockV7InstantVSLsMc _$ss15ContinuousClockV7InstantVSQsMc _$ss15ContinuousClockV7InstantVSesMc _$ss15ContinuousClockV7InstantVs0C8ProtocolsMc +_$ss15ContinuousClockV7_traitss01_B6TraitsVvg +_$ss15ContinuousClockV7_traitss01_B6TraitsVvpMV _$ss15ContinuousClockVABycfC _$ss15ContinuousClockVMa _$ss15ContinuousClockVMn _$ss15ContinuousClockVN _$ss15ContinuousClockVs0B0sMc _$ss15ContinuousClockVs0B0sWP -_$ss15ExecutorFactoryMp -_$ss15ExecutorFactoryP04mainA0s04MainA0_pvgZTj -_$ss15ExecutorFactoryP04mainA0s04MainA0_pvgZTq -_$ss15ExecutorFactoryP07defaultA0Sch_pvgZTj -_$ss15ExecutorFactoryP07defaultA0Sch_pvgZTq -_$ss15ExecutorFactoryTL -_$ss15RunLoopExecutorMp -_$ss15RunLoopExecutorP3runyyKFTj -_$ss15RunLoopExecutorP3runyyKFTq -_$ss15RunLoopExecutorP4stopyyFTj -_$ss15RunLoopExecutorP4stopyyFTq -_$ss15RunLoopExecutorP8runUntilyySbyXEKFTj -_$ss15RunLoopExecutorP8runUntilyySbyXEKFTq -_$ss15RunLoopExecutorPScFTb -_$ss15RunLoopExecutorPsE8runUntilyySbyXEKF -_$ss15RunLoopExecutorTL _$ss15SuspendingClockV17minimumResolutions8DurationVvg _$ss15SuspendingClockV17minimumResolutions8DurationVvpMV _$ss15SuspendingClockV3nowAB7InstantVvg @@ -564,8 +528,6 @@ _$ss15SuspendingClockV3nowAB7InstantVvgZ _$ss15SuspendingClockV3nowAB7InstantVvpMV _$ss15SuspendingClockV5sleep5until9toleranceyAB7InstantV_s8DurationVSgtYaKF _$ss15SuspendingClockV5sleep5until9toleranceyAB7InstantV_s8DurationVSgtYaKFTu -_$ss15SuspendingClockV6traitss0B6TraitsVvg -_$ss15SuspendingClockV6traitss0B6TraitsVvpMV _$ss15SuspendingClockV7InstantV1loiySbAD_ADtFZ _$ss15SuspendingClockV7InstantV1poiyA2D_s8DurationVtFZ _$ss15SuspendingClockV7InstantV1soiyA2D_s8DurationVtFZ @@ -590,12 +552,34 @@ _$ss15SuspendingClockV7InstantVSLsMc _$ss15SuspendingClockV7InstantVSQsMc _$ss15SuspendingClockV7InstantVSesMc _$ss15SuspendingClockV7InstantVs0C8ProtocolsMc +_$ss15SuspendingClockV7_traitss01_B6TraitsVvg +_$ss15SuspendingClockV7_traitss01_B6TraitsVvpMV _$ss15SuspendingClockVABycfC _$ss15SuspendingClockVMa _$ss15SuspendingClockVMn _$ss15SuspendingClockVN _$ss15SuspendingClockVs0B0sMc _$ss15SuspendingClockVs0B0sWP +_$ss15_CFMainExecutorC4_runyyKF +_$ss15_CFMainExecutorC5_stopyyF +_$ss15_CFMainExecutorCABycfC +_$ss15_CFMainExecutorCABycfc +_$ss15_CFMainExecutorCMa +_$ss15_CFMainExecutorCMm +_$ss15_CFMainExecutorCMn +_$ss15_CFMainExecutorCMo +_$ss15_CFMainExecutorCN +_$ss15_CFMainExecutorCfD +_$ss15_CFMainExecutorCfd +_$ss15_CFTaskExecutorCABycfC +_$ss15_CFTaskExecutorCABycfc +_$ss15_CFTaskExecutorCMa +_$ss15_CFTaskExecutorCMm +_$ss15_CFTaskExecutorCMn +_$ss15_CFTaskExecutorCMo +_$ss15_CFTaskExecutorCN +_$ss15_CFTaskExecutorCfD +_$ss15_CFTaskExecutorCfd _$ss16AsyncMapSequenceV04makeA8IteratorAB0E0Vyxq__GyF _$ss16AsyncMapSequenceV4basexvg _$ss16AsyncMapSequenceV4basexvpMV @@ -617,51 +601,67 @@ _$ss16AsyncMapSequenceVMa _$ss16AsyncMapSequenceVMn _$ss16AsyncMapSequenceV_9transformAByxq_Gx_q_7ElementQzYactcfC _$ss16AsyncMapSequenceVyxq_GScisMc -_$ss17DummyMainExecutorC02isbC0Sbvg -_$ss17DummyMainExecutorC02isbC0SbvpMV -_$ss17DummyMainExecutorC13checkIsolatedyyF -_$ss17DummyMainExecutorC3runyyKF -_$ss17DummyMainExecutorC4stopyyF -_$ss17DummyMainExecutorC7enqueueyys0C3JobVnF -_$ss17DummyMainExecutorCABycfC -_$ss17DummyMainExecutorCABycfCTj -_$ss17DummyMainExecutorCABycfCTq -_$ss17DummyMainExecutorCABycfc -_$ss17DummyMainExecutorCMa -_$ss17DummyMainExecutorCMm -_$ss17DummyMainExecutorCMn -_$ss17DummyMainExecutorCMo -_$ss17DummyMainExecutorCMu -_$ss17DummyMainExecutorCN -_$ss17DummyMainExecutorCScFsMc -_$ss17DummyMainExecutorCScFsWP -_$ss17DummyMainExecutorCScfsMc -_$ss17DummyMainExecutorCScfsWP -_$ss17DummyMainExecutorCfD -_$ss17DummyMainExecutorCfd -_$ss17DummyMainExecutorCs07RunLoopC0sMc -_$ss17DummyMainExecutorCs07RunLoopC0sWP -_$ss17DummyMainExecutorCs0bC0sMc -_$ss17DummyMainExecutorCs0bC0sWP -_$ss17DummyTaskExecutorC06isMainC0Sbvg -_$ss17DummyTaskExecutorC06isMainC0SbvpMV -_$ss17DummyTaskExecutorC7enqueueyys0C3JobVnF -_$ss17DummyTaskExecutorCABycfC -_$ss17DummyTaskExecutorCABycfCTj -_$ss17DummyTaskExecutorCABycfCTq -_$ss17DummyTaskExecutorCABycfc -_$ss17DummyTaskExecutorCMa -_$ss17DummyTaskExecutorCMm -_$ss17DummyTaskExecutorCMn -_$ss17DummyTaskExecutorCMo -_$ss17DummyTaskExecutorCMu -_$ss17DummyTaskExecutorCN -_$ss17DummyTaskExecutorCScFsMc -_$ss17DummyTaskExecutorCScFsWP -_$ss17DummyTaskExecutorCSchsMc -_$ss17DummyTaskExecutorCSchsWP -_$ss17DummyTaskExecutorCfD -_$ss17DummyTaskExecutorCfd +_$ss16_ExecutorFactoryMp +_$ss16_ExecutorFactoryP04mainA0s05_MainA0_pvgZTj +_$ss16_ExecutorFactoryP04mainA0s05_MainA0_pvgZTq +_$ss16_ExecutorFactoryP07defaultA0Sch_pvgZTj +_$ss16_ExecutorFactoryP07defaultA0Sch_pvgZTq +_$ss16_ExecutorFactoryTL +_$ss16_RunLoopExecutorMp +_$ss16_RunLoopExecutorP4_runyyKFTj +_$ss16_RunLoopExecutorP4_runyyKFTq +_$ss16_RunLoopExecutorP5_stopyyFTj +_$ss16_RunLoopExecutorP5_stopyyFTq +_$ss16_RunLoopExecutorP9_runUntilyySbyXEKFTj +_$ss16_RunLoopExecutorP9_runUntilyySbyXEKFTq +_$ss16_RunLoopExecutorPScFTb +_$ss16_RunLoopExecutorPsE9_runUntilyySbyXEKF +_$ss16_RunLoopExecutorTL +_$ss18_DummyMainExecutorC03_isbC0Sbvg +_$ss18_DummyMainExecutorC03_isbC0SbvpMV +_$ss18_DummyMainExecutorC13checkIsolatedyyF +_$ss18_DummyMainExecutorC4_runyyKF +_$ss18_DummyMainExecutorC5_stopyyF +_$ss18_DummyMainExecutorC7enqueueyys0C3JobVnF +_$ss18_DummyMainExecutorCABycfC +_$ss18_DummyMainExecutorCABycfCTj +_$ss18_DummyMainExecutorCABycfCTq +_$ss18_DummyMainExecutorCABycfc +_$ss18_DummyMainExecutorCMa +_$ss18_DummyMainExecutorCMm +_$ss18_DummyMainExecutorCMn +_$ss18_DummyMainExecutorCMo +_$ss18_DummyMainExecutorCMu +_$ss18_DummyMainExecutorCN +_$ss18_DummyMainExecutorCScFsMc +_$ss18_DummyMainExecutorCScFsWP +_$ss18_DummyMainExecutorCScfsMc +_$ss18_DummyMainExecutorCScfsWP +_$ss18_DummyMainExecutorCfD +_$ss18_DummyMainExecutorCfd +_$ss18_DummyMainExecutorCs01_bC0sMc +_$ss18_DummyMainExecutorCs01_bC0sWP +_$ss18_DummyMainExecutorCs08_RunLoopC0sMc +_$ss18_DummyMainExecutorCs08_RunLoopC0sWP +_$ss18_DummyTaskExecutorC07_isMainC0Sbvg +_$ss18_DummyTaskExecutorC07_isMainC0SbvpMV +_$ss18_DummyTaskExecutorC7enqueueyys0C3JobVnF +_$ss18_DummyTaskExecutorCABycfC +_$ss18_DummyTaskExecutorCABycfCTj +_$ss18_DummyTaskExecutorCABycfCTq +_$ss18_DummyTaskExecutorCABycfc +_$ss18_DummyTaskExecutorCMa +_$ss18_DummyTaskExecutorCMm +_$ss18_DummyTaskExecutorCMn +_$ss18_DummyTaskExecutorCMo +_$ss18_DummyTaskExecutorCMu +_$ss18_DummyTaskExecutorCN +_$ss18_DummyTaskExecutorCScFsMc +_$ss18_DummyTaskExecutorCScFsWP +_$ss18_DummyTaskExecutorCSchsMc +_$ss18_DummyTaskExecutorCSchsWP +_$ss18_DummyTaskExecutorCfD +_$ss18_DummyTaskExecutorCfd _$ss19AsyncFilterSequenceV04makeA8IteratorAB0E0Vyx_GyF _$ss19AsyncFilterSequenceV10isIncludedySb7ElementQzYacvg _$ss19AsyncFilterSequenceV10isIncludedySb7ElementQzYacvpMV @@ -719,16 +719,7 @@ _$ss19DiscardingTaskGroupV9cancelAllyyF _$ss19DiscardingTaskGroupVMa _$ss19DiscardingTaskGroupVMn _$ss19DiscardingTaskGroupVN -_$ss19SchedulableExecutorMp -_$ss19SchedulableExecutorP7enqueue_2at9tolerance5clockys0B3JobVn_7InstantQyd__8DurationQyd__Sgqd__ts5ClockRd__lFTj -_$ss19SchedulableExecutorP7enqueue_2at9tolerance5clockys0B3JobVn_7InstantQyd__8DurationQyd__Sgqd__ts5ClockRd__lFTq -_$ss19SchedulableExecutorP7enqueue_5after9tolerance5clockys0B3JobVn_8DurationQyd__AJSgqd__ts5ClockRd__lFTj -_$ss19SchedulableExecutorP7enqueue_5after9tolerance5clockys0B3JobVn_8DurationQyd__AJSgqd__ts5ClockRd__lFTq -_$ss19SchedulableExecutorPScFTb -_$ss19SchedulableExecutorPsE7enqueue_2at9tolerance5clockys0B3JobVn_7InstantQyd__8DurationQyd__Sgqd__ts5ClockRd__lF -_$ss19SchedulableExecutorPsE7enqueue_5after9tolerance5clockys0B3JobVn_8DurationQyd__AJSgqd__ts5ClockRd__lF -_$ss19SchedulableExecutorTL -_$ss19UnownedTaskExecutorV02asbC0Sch_pSgyF +_$ss19UnownedTaskExecutorV03_asbC0Sch_pSgyF _$ss19UnownedTaskExecutorVyABxhcSchRzlufC _$ss20AsyncFlatMapSequenceV04makeA8IteratorAB0F0Vyxq__GyF _$ss20AsyncFlatMapSequenceV4basexvg @@ -759,39 +750,48 @@ _$ss20AsyncFlatMapSequenceVMa _$ss20AsyncFlatMapSequenceVMn _$ss20AsyncFlatMapSequenceV_9transformAByxq_Gx_q_7ElementQzYactcfC _$ss20AsyncFlatMapSequenceVyxq_GScisMc -_$ss20DispatchMainExecutorC02isbC0Sbvg -_$ss20DispatchMainExecutorC02isbC0SbvpMV -_$ss20DispatchMainExecutorC13asSchedulables0eC0_pSgvg -_$ss20DispatchMainExecutorC13asSchedulables0eC0_pSgvpMV -_$ss20DispatchMainExecutorC13checkIsolatedyyF -_$ss20DispatchMainExecutorC3runyyKFTj -_$ss20DispatchMainExecutorC3runyyKFTq -_$ss20DispatchMainExecutorC4stopyyFTj -_$ss20DispatchMainExecutorC4stopyyFTq -_$ss20DispatchMainExecutorC7enqueue_2at9tolerance5clockys0C3JobVn_7InstantQz8DurationQzSgxts5ClockRzlF -_$ss20DispatchMainExecutorC7enqueueyys0C3JobVnF -_$ss20DispatchMainExecutorCABycfC -_$ss20DispatchMainExecutorCABycfCTj -_$ss20DispatchMainExecutorCABycfCTq -_$ss20DispatchMainExecutorCABycfc -_$ss20DispatchMainExecutorCMa -_$ss20DispatchMainExecutorCMm -_$ss20DispatchMainExecutorCMn -_$ss20DispatchMainExecutorCMo -_$ss20DispatchMainExecutorCMu -_$ss20DispatchMainExecutorCN -_$ss20DispatchMainExecutorCScFsMc -_$ss20DispatchMainExecutorCScFsWP -_$ss20DispatchMainExecutorCScfsMc -_$ss20DispatchMainExecutorCScfsWP -_$ss20DispatchMainExecutorCfD -_$ss20DispatchMainExecutorCfd -_$ss20DispatchMainExecutorCs011SchedulableC0sMc -_$ss20DispatchMainExecutorCs011SchedulableC0sWP -_$ss20DispatchMainExecutorCs07RunLoopC0sMc -_$ss20DispatchMainExecutorCs07RunLoopC0sWP -_$ss20DispatchMainExecutorCs0bC0sMc -_$ss20DispatchMainExecutorCs0bC0sWP +_$ss20_SchedulableExecutorMp +_$ss20_SchedulableExecutorP8_enqueue_2at9tolerance5clockys0B3JobVn_7InstantQyd__8DurationQyd__Sgqd__ts5ClockRd__lFTj +_$ss20_SchedulableExecutorP8_enqueue_2at9tolerance5clockys0B3JobVn_7InstantQyd__8DurationQyd__Sgqd__ts5ClockRd__lFTq +_$ss20_SchedulableExecutorP8_enqueue_5after9tolerance5clockys0B3JobVn_8DurationQyd__AJSgqd__ts5ClockRd__lFTj +_$ss20_SchedulableExecutorP8_enqueue_5after9tolerance5clockys0B3JobVn_8DurationQyd__AJSgqd__ts5ClockRd__lFTq +_$ss20_SchedulableExecutorPScFTb +_$ss20_SchedulableExecutorPsE8_enqueue_2at9tolerance5clockys0B3JobVn_7InstantQyd__8DurationQyd__Sgqd__ts5ClockRd__lF +_$ss20_SchedulableExecutorPsE8_enqueue_5after9tolerance5clockys0B3JobVn_8DurationQyd__AJSgqd__ts5ClockRd__lF +_$ss20_SchedulableExecutorTL +_$ss21_DispatchMainExecutorC03_isbC0Sbvg +_$ss21_DispatchMainExecutorC03_isbC0SbvpMV +_$ss21_DispatchMainExecutorC13checkIsolatedyyF +_$ss21_DispatchMainExecutorC14_asSchedulables01_eC0_pSgvg +_$ss21_DispatchMainExecutorC14_asSchedulables01_eC0_pSgvpMV +_$ss21_DispatchMainExecutorC4_runyyKFTj +_$ss21_DispatchMainExecutorC4_runyyKFTq +_$ss21_DispatchMainExecutorC5_stopyyFTj +_$ss21_DispatchMainExecutorC5_stopyyFTq +_$ss21_DispatchMainExecutorC7enqueueyys0C3JobVnF +_$ss21_DispatchMainExecutorC8_enqueue_2at9tolerance5clockys0C3JobVn_7InstantQz8DurationQzSgxts5ClockRzlF +_$ss21_DispatchMainExecutorCABycfC +_$ss21_DispatchMainExecutorCABycfCTj +_$ss21_DispatchMainExecutorCABycfCTq +_$ss21_DispatchMainExecutorCABycfc +_$ss21_DispatchMainExecutorCMa +_$ss21_DispatchMainExecutorCMm +_$ss21_DispatchMainExecutorCMn +_$ss21_DispatchMainExecutorCMo +_$ss21_DispatchMainExecutorCMu +_$ss21_DispatchMainExecutorCN +_$ss21_DispatchMainExecutorCScFsMc +_$ss21_DispatchMainExecutorCScFsWP +_$ss21_DispatchMainExecutorCScfsMc +_$ss21_DispatchMainExecutorCScfsWP +_$ss21_DispatchMainExecutorCfD +_$ss21_DispatchMainExecutorCfd +_$ss21_DispatchMainExecutorCs012_SchedulableC0sMc +_$ss21_DispatchMainExecutorCs012_SchedulableC0sWP +_$ss21_DispatchMainExecutorCs01_bC0sMc +_$ss21_DispatchMainExecutorCs01_bC0sWP +_$ss21_DispatchMainExecutorCs08_RunLoopC0sMc +_$ss21_DispatchMainExecutorCs08_RunLoopC0sWP _$ss21withThrowingTaskGroup2of9returning4bodyq_xm_q_mq_Scgyxs5Error_pGzYaKXEtYaKr0_lF _$ss21withThrowingTaskGroup2of9returning4bodyq_xm_q_mq_Scgyxs5Error_pGzYaKXEtYaKr0_lFTu _$ss21withUnsafeCurrentTask4bodyxxSctSgKXE_tKlF @@ -864,15 +864,6 @@ _$ss23AsyncCompactMapSequenceVMa _$ss23AsyncCompactMapSequenceVMn _$ss23AsyncCompactMapSequenceV_9transformAByxq_Gx_q_Sg7ElementQzYactcfC _$ss23AsyncCompactMapSequenceVyxq_GScisMc -_$ss23PlatformExecutorFactoryV04mainB0s04MainB0_pvgZ -_$ss23PlatformExecutorFactoryV04mainB0s04MainB0_pvpZMV -_$ss23PlatformExecutorFactoryV07defaultB0Sch_pvgZ -_$ss23PlatformExecutorFactoryV07defaultB0Sch_pvpZMV -_$ss23PlatformExecutorFactoryVMa -_$ss23PlatformExecutorFactoryVMn -_$ss23PlatformExecutorFactoryVN -_$ss23PlatformExecutorFactoryVs0bC0sMc -_$ss23PlatformExecutorFactoryVs0bC0sWP _$ss23withCheckedContinuation8function_xSS_yScCyxs5NeverOGXEtYalF _$ss23withCheckedContinuation8function_xSS_yScCyxs5NeverOGXEtYalFTu _$ss23withDiscardingTaskGroup9returning4bodyxxm_xs0bcD0VzYaXEtYalF @@ -927,31 +918,15 @@ _$ss24AsyncThrowingMapSequenceVMa _$ss24AsyncThrowingMapSequenceVMn _$ss24AsyncThrowingMapSequenceV_9transformAByxq_Gx_q_7ElementQzYaKctcfC _$ss24AsyncThrowingMapSequenceVyxq_GScisMc -_$ss26DispatchGlobalTaskExecutorC06isMainD0SbvgTj -_$ss26DispatchGlobalTaskExecutorC06isMainD0SbvgTq -_$ss26DispatchGlobalTaskExecutorC06isMainD0SbvpMV -_$ss26DispatchGlobalTaskExecutorC7enqueue_2at9tolerance5clockys0D3JobVn_7InstantQz8DurationQzSgxts5ClockRzlFTj -_$ss26DispatchGlobalTaskExecutorC7enqueue_2at9tolerance5clockys0D3JobVn_7InstantQz8DurationQzSgxts5ClockRzlFTq -_$ss26DispatchGlobalTaskExecutorC7enqueueyys0D3JobVnFTj -_$ss26DispatchGlobalTaskExecutorC7enqueueyys0D3JobVnFTq -_$ss26DispatchGlobalTaskExecutorCABycfC -_$ss26DispatchGlobalTaskExecutorCABycfCTj -_$ss26DispatchGlobalTaskExecutorCABycfCTq -_$ss26DispatchGlobalTaskExecutorCABycfc -_$ss26DispatchGlobalTaskExecutorCMa -_$ss26DispatchGlobalTaskExecutorCMm -_$ss26DispatchGlobalTaskExecutorCMn -_$ss26DispatchGlobalTaskExecutorCMo -_$ss26DispatchGlobalTaskExecutorCMu -_$ss26DispatchGlobalTaskExecutorCN -_$ss26DispatchGlobalTaskExecutorCScFsMc -_$ss26DispatchGlobalTaskExecutorCScFsWP -_$ss26DispatchGlobalTaskExecutorCSchsMc -_$ss26DispatchGlobalTaskExecutorCSchsWP -_$ss26DispatchGlobalTaskExecutorCfD -_$ss26DispatchGlobalTaskExecutorCfd -_$ss26DispatchGlobalTaskExecutorCs011SchedulableD0sMc -_$ss26DispatchGlobalTaskExecutorCs011SchedulableD0sWP +_$ss24_PlatformExecutorFactoryV04mainB0s05_MainB0_pvgZ +_$ss24_PlatformExecutorFactoryV04mainB0s05_MainB0_pvpZMV +_$ss24_PlatformExecutorFactoryV07defaultB0Sch_pvgZ +_$ss24_PlatformExecutorFactoryV07defaultB0Sch_pvpZMV +_$ss24_PlatformExecutorFactoryVMa +_$ss24_PlatformExecutorFactoryVMn +_$ss24_PlatformExecutorFactoryVN +_$ss24_PlatformExecutorFactoryVs01_bC0sMc +_$ss24_PlatformExecutorFactoryVs01_bC0sWP _$ss27AsyncThrowingFilterSequenceV04makeA8IteratorAB0F0Vyx_GyF _$ss27AsyncThrowingFilterSequenceV10isIncludedySb7ElementQzYaKcvg _$ss27AsyncThrowingFilterSequenceV10isIncludedySb7ElementQzYaKcvpMV @@ -989,6 +964,31 @@ _$ss27ThrowingDiscardingTaskGroupV7isEmptySbvpMV _$ss27ThrowingDiscardingTaskGroupV9cancelAllyyF _$ss27ThrowingDiscardingTaskGroupVMa _$ss27ThrowingDiscardingTaskGroupVMn +_$ss27_DispatchGlobalTaskExecutorC07_isMainD0SbvgTj +_$ss27_DispatchGlobalTaskExecutorC07_isMainD0SbvgTq +_$ss27_DispatchGlobalTaskExecutorC07_isMainD0SbvpMV +_$ss27_DispatchGlobalTaskExecutorC7enqueueyys0D3JobVnFTj +_$ss27_DispatchGlobalTaskExecutorC7enqueueyys0D3JobVnFTq +_$ss27_DispatchGlobalTaskExecutorC8_enqueue_2at9tolerance5clockys0D3JobVn_7InstantQz8DurationQzSgxts5ClockRzlFTj +_$ss27_DispatchGlobalTaskExecutorC8_enqueue_2at9tolerance5clockys0D3JobVn_7InstantQz8DurationQzSgxts5ClockRzlFTq +_$ss27_DispatchGlobalTaskExecutorCABycfC +_$ss27_DispatchGlobalTaskExecutorCABycfCTj +_$ss27_DispatchGlobalTaskExecutorCABycfCTq +_$ss27_DispatchGlobalTaskExecutorCABycfc +_$ss27_DispatchGlobalTaskExecutorCMa +_$ss27_DispatchGlobalTaskExecutorCMm +_$ss27_DispatchGlobalTaskExecutorCMn +_$ss27_DispatchGlobalTaskExecutorCMo +_$ss27_DispatchGlobalTaskExecutorCMu +_$ss27_DispatchGlobalTaskExecutorCN +_$ss27_DispatchGlobalTaskExecutorCScFsMc +_$ss27_DispatchGlobalTaskExecutorCScFsWP +_$ss27_DispatchGlobalTaskExecutorCSchsMc +_$ss27_DispatchGlobalTaskExecutorCSchsWP +_$ss27_DispatchGlobalTaskExecutorCfD +_$ss27_DispatchGlobalTaskExecutorCfd +_$ss27_DispatchGlobalTaskExecutorCs012_SchedulableD0sMc +_$ss27_DispatchGlobalTaskExecutorCs012_SchedulableD0sWP _$ss27withTaskCancellationHandler9operation8onCancelxxyYaKXE_yyYbXEtYaKlF _$ss27withTaskCancellationHandler9operation8onCancelxxyYaKXE_yyYbXEtYaKlFTu _$ss28AsyncThrowingFlatMapSequenceV04makeA8IteratorAB0G0Vyxq__GyF @@ -1119,26 +1119,26 @@ _$ss5ClockP3now7InstantQzvgTq _$ss5ClockP5sleep5until9tolerancey7InstantQz_8DurationQzSgtYaKFTj _$ss5ClockP5sleep5until9tolerancey7InstantQz_8DurationQzSgtYaKFTjTu _$ss5ClockP5sleep5until9tolerancey7InstantQz_8DurationQzSgtYaKFTq -_$ss5ClockP6traitss0A6TraitsVvgTj -_$ss5ClockP6traitss0A6TraitsVvgTq _$ss5ClockP7InstantAB_s0B8ProtocolTn -_$ss5ClockP7convert4from8DurationQzSgsAEV_tFTj -_$ss5ClockP7convert4from8DurationQzSgsAEV_tFTq -_$ss5ClockP7convert4froms8DurationVSgAEQz_tFTj -_$ss5ClockP7convert4froms8DurationVSgAEQz_tFTq -_$ss5ClockP7convert7instant4from7InstantQzSgAFQyd___qd__tsAARd__lFTj -_$ss5ClockP7convert7instant4from7InstantQzSgAFQyd___qd__tsAARd__lFTq -_$ss5ClockPsE6traitss0A6TraitsVvg -_$ss5ClockPsE6traitss0A6TraitsVvpMV -_$ss5ClockPsE7convert4from8DurationQzSgsAEV_tF -_$ss5ClockPsE7convert4froms8DurationVSgAEQz_tF -_$ss5ClockPsE7convert7instant4from7InstantQzSgAFQyd___qd__tsAARd__lF +_$ss5ClockP7_traitss01_A6TraitsVvgTj +_$ss5ClockP7_traitss01_A6TraitsVvgTq +_$ss5ClockP8_convert4from8DurationQzSgsAEV_tFTj +_$ss5ClockP8_convert4from8DurationQzSgsAEV_tFTq +_$ss5ClockP8_convert4froms8DurationVSgAEQz_tFTj +_$ss5ClockP8_convert4froms8DurationVSgAEQz_tFTq +_$ss5ClockP8_convert7instant4from7InstantQzSgAFQyd___qd__tsAARd__lFTj +_$ss5ClockP8_convert7instant4from7InstantQzSgAFQyd___qd__tsAARd__lFTq +_$ss5ClockPsE7_traitss01_A6TraitsVvg +_$ss5ClockPsE7_traitss01_A6TraitsVvpMV _$ss5ClockPsE7measurey8DurationQzyyKXEKF _$ss5ClockPsE7measurey8DurationQzyyYaKXEYaKF _$ss5ClockPsE7measurey8DurationQzyyYaKXEYaKFTu +_$ss5ClockPsE8_convert4from8DurationQzSgsAEV_tF +_$ss5ClockPsE8_convert4froms8DurationVSgAEQz_tF +_$ss5ClockPsE8_convert7instant4from7InstantQzSgAFQyd___qd__tsAARd__lF _$ss5ClockPss010ContinuousA0VRszrlE10continuousADvgZ _$ss5ClockPss010SuspendingA0VRszrlE10suspendingADvgZ -_$ss5ClockPss8DurationVACRtzrlE7convert4fromADSgAD_tF +_$ss5ClockPss8DurationVACRtzrlE8_convert4fromADSgAD_tF _$ss5ClockTL _$ss6_first_5where7ElementQzSgx_SbADYaKXEtYaKSciRzlF _$ss6_first_5where7ElementQzSgx_SbADYaKXEtYaKSciRzlFTu diff --git a/test/abi/macOS/arm64/stdlib.swift b/test/abi/macOS/arm64/stdlib.swift index 1e8c39edcaa35..6517b81aef889 100644 --- a/test/abi/macOS/arm64/stdlib.swift +++ b/test/abi/macOS/arm64/stdlib.swift @@ -1122,3 +1122,8 @@ Added: $ld$previous$@rpath/libswiftCompatibilitySpan.dylib$$1$10.14$15.0$_$ss7Ra // Duration.nanoseconds(_:) Added: _$ss8DurationV11nanosecondsyABSdFZ + +// var InlineArray._storage +Added: _$ss11InlineArrayVsRi__rlE8_storagexq_BVvM +Added: _$ss11InlineArrayVsRi__rlE8_storagexq_BVvs + diff --git a/test/abi/macOS/x86_64/stdlib.swift b/test/abi/macOS/x86_64/stdlib.swift index ea0cdc82b5da4..4aef353b83dbc 100644 --- a/test/abi/macOS/x86_64/stdlib.swift +++ b/test/abi/macOS/x86_64/stdlib.swift @@ -1123,3 +1123,8 @@ Added: $ld$previous$@rpath/libswiftCompatibilitySpan.dylib$$1$10.14$15.0$_$ss7Ra // Duration.nanoseconds(_:) Added: _$ss8DurationV11nanosecondsyABSdFZ + +// var InlineArray._storage +Added: _$ss11InlineArrayVsRi__rlE8_storagexq_BVvM +Added: _$ss11InlineArrayVsRi__rlE8_storagexq_BVvs + diff --git a/test/attr/ApplicationMain/attr_main_throws.swift b/test/attr/ApplicationMain/attr_main_throws.swift index 959a0f21b8eec..df6493ed0679a 100644 --- a/test/attr/ApplicationMain/attr_main_throws.swift +++ b/test/attr/ApplicationMain/attr_main_throws.swift @@ -7,7 +7,7 @@ struct MyBase { } } -// CHECK-AST: (func_decl {{.*}} implicit "$main()" interface_type="(MyBase.Type) -> () throws -> ()" access=internal static +// CHECK-AST: (func_decl {{.*}} implicit range=[{{.*}}:[[@LINE-6]]:1 - line:[[@LINE-6]]:1] "$main()" interface_type="(MyBase.Type) -> () throws -> ()" access=internal static // CHECK-AST-NEXT: (parameter "self" {{.*}}) // CHECK-AST-NEXT: (parameter_list) // CHECK-AST-NEXT: (brace_stmt implicit diff --git a/test/attr/attr_abi.swift b/test/attr/attr_abi.swift index 49116208b3740..3b163dac05c99 100644 --- a/test/attr/attr_abi.swift +++ b/test/attr/attr_abi.swift @@ -1406,16 +1406,19 @@ func nonEphemeral2(_: UnsafeRawPointer) {} @abi(func disfavoredOverload3(_: UnsafeRawPointer)) func nonEphemeral3(@_nonEphemeral _: UnsafeRawPointer) {} -// @_inheritActorContext -- banned in @abi -@abi(func inheritActorContext1(@_inheritActorContext fn: @Sendable @escaping () async -> Void)) // expected-error {{unused '_inheritActorContext' attribute in '@abi'}} {{32-53=}} +// @_inheritActorContext +@abi(func inheritActorContext1(@_inheritActorContext fn: @Sendable @escaping () async -> Void)) func inheritActorContext1(@_inheritActorContext fn: @Sendable @escaping () async -> Void) {} -@abi(func inheritActorContext2(@_inheritActorContext fn: @Sendable @escaping () async -> Void)) // expected-error {{unused '_inheritActorContext' attribute in '@abi'}} {{32-53=}} +@abi(func inheritActorContext2(@_inheritActorContext fn: @Sendable @escaping () async -> Void)) func inheritActorContext2(fn: @Sendable @escaping () async -> Void) {} @abi(func inheritActorContext3(fn: @Sendable @escaping () async -> Void)) func inheritActorContext3(@_inheritActorContext fn: @Sendable @escaping () async -> Void) {} +@abi(func inheritActorContext4(@_inheritActorContext(always) fn: @Sendable @escaping () async -> Void)) +func inheritActorContext4(fn: @Sendable @escaping () async -> Void) {} + // @excusivity(checked/unchecked) -- banned in @abi class Exclusivity { @abi(var checked00: Int) diff --git a/test/attr/attr_cdecl_official.swift b/test/attr/attr_cdecl_official.swift index 3ca28adfbb731..00ae03cdd36d0 100644 --- a/test/attr/attr_cdecl_official.swift +++ b/test/attr/attr_cdecl_official.swift @@ -55,3 +55,19 @@ class Foo { @cdecl("throwing") // expected-error{{raising errors from @cdecl functions is not supported}} func throwing() throws { } + +@cdecl("acceptedPointers") +func acceptedPointers(_ x: UnsafeMutablePointer, + y: UnsafePointer, + z: UnsafeMutableRawPointer, + w: UnsafeRawPointer, + u: OpaquePointer) {} + +@cdecl("rejectedPointers") +func rejectedPointers( // expected-error 6 {{global function cannot be marked '@cdecl' because the type of the parameter}} + x: UnsafePointer, // expected-note {{Swift structs cannot be represented in Objective-C}} // FIXME: Should reference C. + y: CVaListPointer, // expected-note {{Swift structs cannot be represented in Objective-C}} + z: UnsafeBufferPointer, // expected-note {{Swift structs cannot be represented in Objective-C}} + u: UnsafeMutableBufferPointer, // expected-note {{Swift structs cannot be represented in Objective-C}} + v: UnsafeRawBufferPointer, // expected-note {{Swift structs cannot be represented in Objective-C}} + t: UnsafeMutableRawBufferPointer) {} // expected-note {{Swift structs cannot be represented in Objective-C}} diff --git a/test/attr/attr_implements_bad_types.swift b/test/attr/attr_implements_bad_types.swift index ea010f343c2d4..8bcc341280a83 100644 --- a/test/attr/attr_implements_bad_types.swift +++ b/test/attr/attr_implements_bad_types.swift @@ -21,5 +21,9 @@ struct S0 : NeedsF0 { // expected-error {{type 'S0' does not conform to protoco @_implements(Equatable, ==(_:_:)) // expected-error {{containing type 'S0' does not conform to protocol 'Equatable'}} static func gg2(x:S0, y:S0) -> Bool { } + + @_implements(NonexistentType, ff3()) // expected-error {{cannot find type 'NonexistentType' in scope}} + func gg3() { + } } diff --git a/test/attr/attr_inheritActorContext.swift b/test/attr/attr_inheritActorContext.swift new file mode 100644 index 0000000000000..7d490878a12c5 --- /dev/null +++ b/test/attr/attr_inheritActorContext.swift @@ -0,0 +1,38 @@ +// RUN: %target-typecheck-verify-swift + +func test1(@_inheritActorContext _: @Sendable () async -> Void) {} // Ok +func test2(@_inheritActorContext(always) _: sending () async -> Void) {} // Ok + +func test3(@_inheritActorContext _: () async -> Void) {} +// expected-warning@-1 {{@_inheritActorContext only applies to 'sending' parameters or parameters with '@Sendable' function types}} +func test3(@_inheritActorContext _: @Sendable () -> Void) {} +// expected-warning@-1 {{@_inheritActorContext only applies to '@isolated(any)' parameters or parameters with asynchronous function types}} + +func test4(@_inheritActorContext _: Int) {} +// expected-error@-1 {{@_inheritActorContext only applies to parameters with function types (got: 'Int')}} + +func test5(@_inheritActorContext _: sending Optional<() async -> Int>) {} // Ok +func test6(@_inheritActorContext _: (Optional<@Sendable () async -> Int>)?) {} // Ok +func test6(@_inheritActorContext _: (Optional<@Sendable @isolated(any) () -> Int>)?) {} // Ok + +func test7(@_inheritActorContext _: Int?) {} // Ok +// expected-error@-1 {{@_inheritActorContext only applies to parameters with function types (got: 'Int?')}} + +struct S { + init(@_inheritActorContext(always) _: @escaping @Sendable () async -> Void) {} // Ok + + var test: @_inheritActorContext () async -> Void { // expected-error {{attribute can only be applied to declarations, not types}} + { } + } + + subscript(@_inheritActorContext _: @Sendable () async -> Void) -> Bool { false } // Ok + subscript(@_inheritActorContext(always) _: @Sendable (Int) async -> Void) -> Bool { false } // Ok + + subscript(@_inheritActorContext _: sending (String) async -> Void) -> Bool { false } + subscript(x: Int, @_inheritActorContext(always) _: @Sendable (Int, Int) async -> Void) -> Bool { false } + + func testClosure() { + _ = { @_inheritActorContext in // expected-error {{attribute @_inheritActorContext is not supported on a closure}} + } + } +} diff --git a/test/attr/execution_behavior_attrs.swift b/test/attr/execution_behavior_attrs.swift index 90a9a818c0c30..c763e84ca0463 100644 --- a/test/attr/execution_behavior_attrs.swift +++ b/test/attr/execution_behavior_attrs.swift @@ -137,3 +137,24 @@ _ = { @MainActor @concurrent in _ = { @concurrent () -> Int in // expected-error@-1 {{@concurrent on non-async closure}} } + +// Make sure that explicit use of `@concurrent` doesn't interfere with inference of `throws` from the body. +do { + func acceptsThrowing(_ body: () async throws -> Void) async { + } + + struct Invocation { + func throwingFn() async throws { + } + } + + func test(invocation: Invocation) async { + await acceptsThrowing({ @concurrent in try await invocation.throwingFn() }) // Ok + await acceptsThrowing({ @concurrent [invocation] in try await invocation.throwingFn() }) // Ok + + await acceptsThrowing({ @concurrent in // Ok + _ = 42 + try await invocation.throwingFn() + }) + } +} diff --git a/test/embedded/multi-module-debug-info.swift b/test/embedded/multi-module-debug-info.swift new file mode 100644 index 0000000000000..644e40bb51b8d --- /dev/null +++ b/test/embedded/multi-module-debug-info.swift @@ -0,0 +1,35 @@ +// RUN: %empty-directory(%t) +// RUN: %{python} %utils/split_file.py -o %t %s + +// RUN: %target-swift-frontend -emit-module -o %t/MyModule.swiftmodule %t/MyModule.swift -enable-experimental-feature Embedded -parse-as-library +// RUN: %target-swift-frontend -c -I %t %t/Main.swift -enable-experimental-feature Embedded -verify -o /dev/null + +// REQUIRES: OS=macosx || OS=linux-gnu +// REQUIRES: swift_feature_Embedded + +// BEGIN MyModule.swift + +public struct MyError: Error { +} + +@inline(never) +public func foo(_ t: T) throws { + throw MyError() // expected-error {{cannot use a value of protocol type 'any Error' in embedded Swift}} +} + +@inline(never) +public func callit(_ t: T) { + do { + try foo(t) + } catch { + } +} + +// BEGIN Main.swift + +import MyModule + +public func testit() { + callit(27) // expected-note {{generic specialization called here}} +} + diff --git a/test/expr/capture/top-level-guard.swift b/test/expr/capture/top-level-guard.swift index 154c5804dad97..c0b2d8f4d492d 100644 --- a/test/expr/capture/top-level-guard.swift +++ b/test/expr/capture/top-level-guard.swift @@ -39,7 +39,7 @@ let closureCapture: () -> Void = { [x] in } // CHECK-LABEL: (defer_stmt -// CHECK-NEXT: (func_decl{{.*}}implicit "$defer()" interface_type="() -> ()" access=fileprivate captures=(x) +// CHECK-NEXT: (func_decl{{.*}}implicit range={{.*}} "$defer()" interface_type="() -> ()" access=fileprivate captures=(x) defer { _ = x } diff --git a/test/lit.cfg b/test/lit.cfg index 7e4730f1685f3..073aed46f8083 100644 --- a/test/lit.cfg +++ b/test/lit.cfg @@ -789,6 +789,11 @@ config.substitutions.append( ('%clangxx', "%r %s" % (config.clangxx, clang_mcp_opt)) ) +# Alternative to %clang that doesn't require -fmodules. +config.substitutions.append( ('%clang-no-modules', + "%r" % + (config.clang)) ) + # This must come after all substitutions containing "%clang". # Note: %clang is the locally-built clang. # To get Xcode's clang, use %target-clang. diff --git a/test/stmt/c_style_for.swift b/test/stmt/c_style_for.swift index 7bd75d0e03147..4919681f20cb6 100644 --- a/test/stmt/c_style_for.swift +++ b/test/stmt/c_style_for.swift @@ -32,9 +32,9 @@ for ; other Int) -> Int { 0 } + + for _ in undefined { // expected-error {{cannot find 'undefined' in scope}} + let a = takesAutoclosure(0) // Fine + } + for x in undefined { // expected-error {{cannot find 'undefined' in scope}} + let b: Int = x // No type error, `x` is invalid. + _ = "" as Int // expected-error {{cannot convert value of type 'String' to type 'Int' in coercion}} + } +} diff --git a/tools/SourceKit/include/SourceKit/Core/LangSupport.h b/tools/SourceKit/include/SourceKit/Core/LangSupport.h index 4b143b0f8ea8c..9929299b4659a 100644 --- a/tools/SourceKit/include/SourceKit/Core/LangSupport.h +++ b/tools/SourceKit/include/SourceKit/Core/LangSupport.h @@ -1107,6 +1107,7 @@ class LangSupport { virtual void editorOpenSwiftSourceInterface(StringRef Name, StringRef SourceName, ArrayRef Args, + bool CancelOnSubsequentRequest, SourceKitCancellationToken CancellationToken, std::shared_ptr Consumer) = 0; @@ -1216,12 +1217,14 @@ class LangSupport { virtual void findLocalRenameRanges(StringRef Filename, unsigned Line, unsigned Column, unsigned Length, ArrayRef Args, + bool CancelOnSubsequentRequest, SourceKitCancellationToken CancellationToken, CategorizedRenameRangesReceiver Receiver) = 0; virtual void semanticRefactoring(StringRef PrimaryFilePath, SemanticRefactoringInfo Info, ArrayRef Args, + bool CancelOnSubsequentRequest, SourceKitCancellationToken CancellationToken, CategorizedEditsReceiver Receiver) = 0; @@ -1240,6 +1243,7 @@ class LangSupport { StringRef PrimaryFilePath, StringRef InputBufferName, ArrayRef Args, std::optional Offset, std::optional Length, bool FullyQualified, + bool CancelOnSubsequentRequest, SourceKitCancellationToken CancellationToken, std::function &)> Receiver) = 0; diff --git a/tools/SourceKit/lib/SwiftLang/SwiftDocSupport.cpp b/tools/SourceKit/lib/SwiftLang/SwiftDocSupport.cpp index e7b48b8f502bb..855072cd64d0f 100644 --- a/tools/SourceKit/lib/SwiftLang/SwiftDocSupport.cpp +++ b/tools/SourceKit/lib/SwiftLang/SwiftDocSupport.cpp @@ -1418,7 +1418,8 @@ SwiftLangSupport::findRenameRanges(llvm::MemoryBuffer *InputBuf, void SwiftLangSupport::findLocalRenameRanges( StringRef Filename, unsigned Line, unsigned Column, unsigned Length, - ArrayRef Args, SourceKitCancellationToken CancellationToken, + ArrayRef Args, bool CancelOnSubsequentRequest, + SourceKitCancellationToken CancellationToken, CategorizedRenameRangesReceiver Receiver) { using ResultType = CancellableResult>; std::string Error; @@ -1465,8 +1466,8 @@ void SwiftLangSupport::findLocalRenameRanges( /// FIXME: When request cancellation is implemented and Xcode adopts it, /// don't use 'OncePerASTToken'. static const char OncePerASTToken = 0; - getASTManager()->processASTAsync(Invok, ASTConsumer, &OncePerASTToken, - CancellationToken, + const void *Once = CancelOnSubsequentRequest ? &OncePerASTToken : nullptr; + getASTManager()->processASTAsync(Invok, ASTConsumer, Once, CancellationToken, llvm::vfs::getRealFileSystem()); } diff --git a/tools/SourceKit/lib/SwiftLang/SwiftEditorInterfaceGen.cpp b/tools/SourceKit/lib/SwiftLang/SwiftEditorInterfaceGen.cpp index 320a74e117f85..88f2c7b41003e 100644 --- a/tools/SourceKit/lib/SwiftLang/SwiftEditorInterfaceGen.cpp +++ b/tools/SourceKit/lib/SwiftLang/SwiftEditorInterfaceGen.cpp @@ -853,6 +853,7 @@ class PrimaryFileInterfaceConsumer : public SwiftASTConsumer { void SwiftLangSupport::editorOpenSwiftSourceInterface( StringRef Name, StringRef SourceName, ArrayRef Args, + bool CancelOnSubsequentRequest, SourceKitCancellationToken CancellationToken, std::shared_ptr Consumer) { std::string Error; @@ -864,7 +865,8 @@ void SwiftLangSupport::editorOpenSwiftSourceInterface( auto AstConsumer = std::make_shared(Name, SourceName, IFaceGenContexts, Consumer, Invocation); static const char OncePerASTToken = 0; - getASTManager()->processASTAsync(Invocation, AstConsumer, &OncePerASTToken, + const void *Once = CancelOnSubsequentRequest ? &OncePerASTToken : nullptr; + getASTManager()->processASTAsync(Invocation, AstConsumer, Once, CancellationToken, llvm::vfs::getRealFileSystem()); } diff --git a/tools/SourceKit/lib/SwiftLang/SwiftLangSupport.h b/tools/SourceKit/lib/SwiftLang/SwiftLangSupport.h index 9a56d6684c440..2e3a93e5813fe 100644 --- a/tools/SourceKit/lib/SwiftLang/SwiftLangSupport.h +++ b/tools/SourceKit/lib/SwiftLang/SwiftLangSupport.h @@ -619,6 +619,7 @@ class SwiftLangSupport : public LangSupport { void editorOpenSwiftSourceInterface( StringRef Name, StringRef SourceName, ArrayRef Args, + bool CancelOnSubsequentRequest, SourceKitCancellationToken CancellationToken, std::shared_ptr Consumer) override; @@ -708,6 +709,7 @@ class SwiftLangSupport : public LangSupport { void findLocalRenameRanges(StringRef Filename, unsigned Line, unsigned Column, unsigned Length, ArrayRef Args, + bool CancelOnSubsequentRequest, SourceKitCancellationToken CancellationToken, CategorizedRenameRangesReceiver Receiver) override; @@ -723,6 +725,7 @@ class SwiftLangSupport : public LangSupport { StringRef PrimaryFilePath, StringRef InputBufferName, ArrayRef Args, std::optional Offset, std::optional Length, bool FullyQualified, + bool CancelOnSubsequentRequest, SourceKitCancellationToken CancellationToken, std::function &)> Receiver) override; @@ -730,6 +733,7 @@ class SwiftLangSupport : public LangSupport { void semanticRefactoring(StringRef PrimaryFilePath, SemanticRefactoringInfo Info, ArrayRef Args, + bool CancelOnSubsequentRequest, SourceKitCancellationToken CancellationToken, CategorizedEditsReceiver Receiver) override; diff --git a/tools/SourceKit/lib/SwiftLang/SwiftSourceDocInfo.cpp b/tools/SourceKit/lib/SwiftLang/SwiftSourceDocInfo.cpp index 258241054920b..ac24c0256dcbc 100644 --- a/tools/SourceKit/lib/SwiftLang/SwiftSourceDocInfo.cpp +++ b/tools/SourceKit/lib/SwiftLang/SwiftSourceDocInfo.cpp @@ -2776,7 +2776,8 @@ static RefactoringKind getIDERefactoringKind(SemanticRefactoringInfo Info) { void SwiftLangSupport::semanticRefactoring( StringRef PrimaryFilePath, SemanticRefactoringInfo Info, - ArrayRef Args, SourceKitCancellationToken CancellationToken, + ArrayRef Args, bool CancelOnSubsequentRequest, + SourceKitCancellationToken CancellationToken, CategorizedEditsReceiver Receiver) { std::string Error; SwiftInvocationRef Invok = @@ -2834,7 +2835,8 @@ void SwiftLangSupport::semanticRefactoring( /// FIXME: When request cancellation is implemented and Xcode adopts it, /// don't use 'OncePerASTToken'. static const char OncePerASTToken = 0; - getASTManager()->processASTAsync(Invok, std::move(Consumer), &OncePerASTToken, + const void *Once = CancelOnSubsequentRequest ? &OncePerASTToken : nullptr; + getASTManager()->processASTAsync(Invok, std::move(Consumer), Once, CancellationToken, llvm::vfs::getRealFileSystem()); } @@ -2918,6 +2920,7 @@ void SwiftLangSupport::collectVariableTypes( StringRef PrimaryFilePath, StringRef InputBufferName, ArrayRef Args, std::optional Offset, std::optional Length, bool FullyQualified, + bool CancelOnSubsequentRequest, SourceKitCancellationToken CancellationToken, std::function &)> Receiver) { std::string Error; @@ -2997,7 +3000,8 @@ void SwiftLangSupport::collectVariableTypes( /// FIXME: When request cancellation is implemented and Xcode adopts it, /// don't use 'OncePerASTToken'. static const char OncePerASTToken = 0; - getASTManager()->processASTAsync(Invok, std::move(Collector), - &OncePerASTToken, CancellationToken, + const void *Once = CancelOnSubsequentRequest ? &OncePerASTToken : nullptr; + getASTManager()->processASTAsync(Invok, std::move(Collector), Once, + CancellationToken, llvm::vfs::getRealFileSystem()); } diff --git a/tools/SourceKit/tools/sourcekitd/lib/Service/Requests.cpp b/tools/SourceKit/tools/sourcekitd/lib/Service/Requests.cpp index c3e802a5c056f..9f286f3bafdd2 100644 --- a/tools/SourceKit/tools/sourcekitd/lib/Service/Requests.cpp +++ b/tools/SourceKit/tools/sourcekitd/lib/Service/Requests.cpp @@ -331,6 +331,7 @@ editorOpenHeaderInterface(StringRef Name, StringRef HeaderName, static void editorOpenSwiftSourceInterface(StringRef Name, StringRef SourceName, ArrayRef Args, + bool CancelOnSubsequentRequest, SourceKitCancellationToken CancellationToken, ResponseReceiver Rec, bool EnableDeclarations); @@ -1053,8 +1054,13 @@ static void handleRequestEditorOpenSwiftSourceInterface( // Reporting the declarations array is off by default bool EnableDeclarations = Req.getOptionalInt64(KeyEnableDeclarations).value_or(false); + // For backwards compatibility, the default is 1. + int64_t CancelOnSubsequentRequest = 1; + Req.getInt64(KeyCancelOnSubsequentRequest, CancelOnSubsequentRequest, + /*isOptional=*/true); return editorOpenSwiftSourceInterface( - *Name, *FileName, Args, CancellationToken, Rec, EnableDeclarations); + *Name, *FileName, Args, CancelOnSubsequentRequest, CancellationToken, + Rec, EnableDeclarations); } } @@ -1705,8 +1711,15 @@ handleRequestSemanticRefactoring(const RequestDict &Req, Info.Line = Line; Info.Column = Column; Info.Length = Length; + + // For backwards compatibility, the default is 1. + int64_t CancelOnSubsequentRequest = 1; + Req.getInt64(KeyCancelOnSubsequentRequest, CancelOnSubsequentRequest, + /*isOptional=*/true); + return Lang.semanticRefactoring( - *PrimaryFilePath, Info, Args, CancellationToken, + *PrimaryFilePath, Info, Args, CancelOnSubsequentRequest, + CancellationToken, [Rec](const RequestResult> &Result) { Rec(createCategorizedEditsResponse(Result)); }); @@ -1782,9 +1795,15 @@ handleRequestCollectVariableType(const RequestDict &Req, [](int64_t v) -> unsigned { return v; }); int64_t FullyQualified = false; Req.getInt64(KeyFullyQualified, FullyQualified, /*isOptional=*/true); + + // For backwards compatibility, the default is 1. + int64_t CancelOnSubsequentRequest = 1; + Req.getInt64(KeyCancelOnSubsequentRequest, CancelOnSubsequentRequest, + /*isOptional=*/true); + return Lang.collectVariableTypes( *PrimaryFilePath, InputBufferName, Args, Offset, Length, FullyQualified, - CancellationToken, + CancelOnSubsequentRequest, CancellationToken, [Rec](const RequestResult &Result) { reportVariableTypeInfo(Result, Rec); }); @@ -1814,9 +1833,15 @@ handleRequestFindLocalRenameRanges(const RequestDict &Req, return Rec(createErrorRequestInvalid("'key.column' is required")); Req.getInt64(KeyLength, Length, /*isOptional=*/true); + // For backwards compatibility, the default is 1. + int64_t CancelOnSubsequentRequest = 1; + Req.getInt64(KeyCancelOnSubsequentRequest, CancelOnSubsequentRequest, + /*isOptional=*/true); + LangSupport &Lang = getGlobalContext().getSwiftLangSupport(); return Lang.findLocalRenameRanges( - *PrimaryFilePath, Line, Column, Length, Args, CancellationToken, + *PrimaryFilePath, Line, Column, Length, Args, CancelOnSubsequentRequest, + CancellationToken, [Rec](const CancellableResult> &Result) { Rec(createCategorizedRenameRangesResponse(Result)); @@ -3686,6 +3711,7 @@ static sourcekitd_response_t editorOpenInterface( static void editorOpenSwiftSourceInterface(StringRef Name, StringRef HeaderName, ArrayRef Args, + bool CancelOnSubsequentRequest, SourceKitCancellationToken CancellationToken, ResponseReceiver Rec, bool EnableDeclarations) { SKEditorConsumerOptions Opts; @@ -3694,8 +3720,9 @@ editorOpenSwiftSourceInterface(StringRef Name, StringRef HeaderName, Opts.EnableDeclarations = EnableDeclarations; auto EditC = std::make_shared(Rec, Opts); LangSupport &Lang = getGlobalContext().getSwiftLangSupport(); - Lang.editorOpenSwiftSourceInterface(Name, HeaderName, Args, CancellationToken, - EditC); + Lang.editorOpenSwiftSourceInterface(Name, HeaderName, Args, + CancelOnSubsequentRequest, + CancellationToken, EditC); } static void diff --git a/tools/swift-inspect/Sources/swift-inspect/Cleanup.swift b/tools/swift-inspect/Sources/swift-inspect/Cleanup.swift new file mode 100644 index 0000000000000..dfc54bfaed7fd --- /dev/null +++ b/tools/swift-inspect/Sources/swift-inspect/Cleanup.swift @@ -0,0 +1,48 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2025 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 +// +//===----------------------------------------------------------------------===// + +/// A helper struct that manages the cleanup of some external resource. +/// The value is stored as an Optional, but presented as a non-optional. +/// Accessing the value before one has been set is a runtime error. The cleanup +/// function is called on the value if one has been set, when setting a new +/// value or when the struct is destroyed. +struct Cleanup: ~Copyable { + /// The underlying Optional storage for the value. + private var _value: T? + + /// The wrapped value. A value must be set before any value is read here. + var value: T { + get { + _value! + } + set { + if let _value { + cleanup(_value) + } + _value = newValue + } + } + + /// The function used to clean up the resource held by this struct. + let cleanup: (T) -> Void + + init(cleanup: @escaping (T) -> Void) { + self._value = nil + self.cleanup = cleanup + } + + deinit { + if let _value { + cleanup(_value) + } + } +} diff --git a/tools/swift-inspect/Sources/swift-inspect/DarwinRemoteProcess.swift b/tools/swift-inspect/Sources/swift-inspect/DarwinRemoteProcess.swift index e86b0e47b31fc..59b71ff7617cc 100644 --- a/tools/swift-inspect/Sources/swift-inspect/DarwinRemoteProcess.swift +++ b/tools/swift-inspect/Sources/swift-inspect/DarwinRemoteProcess.swift @@ -19,13 +19,25 @@ internal final class DarwinRemoteProcess: RemoteProcess { public typealias ProcessIdentifier = pid_t public typealias ProcessHandle = task_t - private var task: task_t + private var task = Cleanup { + // task_stop_peeking does nothing if we didn't task_start_peeking first, so + // we can call it unconditionally. + task_stop_peeking($0) + mach_port_deallocate(mach_task_self_, $0) + } + internal var processIdentifier: ProcessIdentifier internal lazy var processName = getProcessName(processId: processIdentifier) ?? "" - public var process: ProcessHandle { task } - public private(set) var context: SwiftReflectionContextRef! - private var symbolicator: CSSymbolicatorRef + public var process: ProcessHandle { task.value } + private var _context = Cleanup { + swift_reflection_destroyReflectionContext($0) + } + public var context: SwiftReflectionContextRef! { _context.value } + + private var symbolicator = Cleanup { + CSRelease($0) + } private var swiftCore: CSTypeRef private let swiftConcurrency: CSTypeRef @@ -72,7 +84,7 @@ internal final class DarwinRemoteProcess: RemoteProcess { } func read(address: swift_addr_t, size: Int) -> UnsafeRawPointer? { - return task_peek(task, address, mach_vm_size_t(size)) + return task_peek(task.value, address, mach_vm_size_t(size)) } func getAddr(symbolName: String) -> swift_addr_t { @@ -98,7 +110,7 @@ internal final class DarwinRemoteProcess: RemoteProcess { static var GetStringLength: GetStringLengthFunction { return { (context, address) in let process: DarwinRemoteProcess = DarwinRemoteProcess.fromOpaque(context!) - if let str = task_peek_string(process.task, address) { + if let str = task_peek_string(process.task.value, address) { return UInt64(strlen(str)) } return 0 @@ -119,18 +131,19 @@ internal final class DarwinRemoteProcess: RemoteProcess { init?(processId: ProcessIdentifier, forkCorpse: Bool) { processIdentifier = processId - var task: task_t = task_t() - let taskResult = task_for_pid(mach_task_self_, processId, &task) + var processTask: task_t = task_t() + let taskResult = task_for_pid(mach_task_self_, processId, &processTask) guard taskResult == KERN_SUCCESS else { print("unable to get task for pid \(processId): \(String(cString: mach_error_string(taskResult))) \(hex: taskResult)", to: &Std.err) return nil } + self.task.value = processTask // Consult with VMUProcInfo to determine if we should force forkCorpse. let forceForkCorpse: Bool if let procInfoClass = getVMUProcInfoClass() { - let procInfo = procInfoClass.init(task: task) + let procInfo = procInfoClass.init(task: self.task.value) forceForkCorpse = procInfo.shouldAnalyzeWithCorpse } else { // Default to not forcing forkCorpse. @@ -141,11 +154,9 @@ internal final class DarwinRemoteProcess: RemoteProcess { var corpse = task_t() let maxRetry = 6 for retry in 0.. (module: String?, symbol: String?) { let symbol = - CSSymbolicatorGetSymbolWithAddressAtTime(self.symbolicator, address, kCSNow) + CSSymbolicatorGetSymbolWithAddressAtTime(self.symbolicator.value, address, kCSNow) let module = CSSymbolGetSymbolOwner(symbol) return (CSSymbolOwnerGetName(module), CSSymbolGetName(symbol)) @@ -206,7 +210,7 @@ internal final class DarwinRemoteProcess: RemoteProcess { internal func iterateHeap(_ body: (swift_addr_t, UInt64) -> Void) { withoutActuallyEscaping(body) { withUnsafePointer(to: $0) { - task_enumerate_malloc_blocks(self.task, + task_enumerate_malloc_blocks(self.task.value, UnsafeMutableRawPointer(mutating: $0), CUnsignedInt(MALLOC_PTR_IN_USE_RANGE_TYPE), { (task, context, type, ranges, count) in @@ -264,14 +268,14 @@ extension DarwinRemoteProcess { } private func getThreadInfos() -> [ThreadInfo] { - guard let threads = PortList(task: self.task) else { + guard let threads = PortList(task: self.task.value) else { return [] } - return threads.compactMap { - guard let info = getThreadInfo(thread: $0) else { + return threads.compactMap { t -> ThreadInfo? in + guard let info = getThreadInfo(thread: t) else { return nil } - guard let kernelObj = getKernelObject(task: mach_task_self_, port: $0) else { + guard let kernelObj = getKernelObject(task: mach_task_self_, port: t) else { return nil } return ThreadInfo(threadID: info.thread_id, @@ -328,7 +332,7 @@ extension DarwinRemoteProcess { } internal func getThreadID(remotePort: thread_t) -> UInt64? { - guard let remoteThreadObj = getKernelObject(task: self.task, port: remotePort) else { + guard let remoteThreadObj = getKernelObject(task: self.task.value, port: remotePort) else { return nil } return threadInfos.first{ $0.kernelObject == remoteThreadObj }?.threadID diff --git a/tools/swift-inspect/Sources/swift-inspect/Process.swift b/tools/swift-inspect/Sources/swift-inspect/Process.swift index 9317f5d0957b2..f0d41fe27a2cb 100644 --- a/tools/swift-inspect/Sources/swift-inspect/Process.swift +++ b/tools/swift-inspect/Sources/swift-inspect/Process.swift @@ -80,7 +80,7 @@ internal func getAllProcesses(options: UniversalOptions) -> [ProcessIdentifier]? } let newCount = bufferSize / kinfo_stride if count > newCount { - buffer.dropLast(count - newCount) + buffer.removeLast(count - newCount) } let sorted = buffer.sorted { first, second in first.kp_proc.p_pid > second.kp_proc.p_pid diff --git a/utils/build-presets.ini b/utils/build-presets.ini index eb1ccada75147..4961b3fbadc92 100644 --- a/utils/build-presets.ini +++ b/utils/build-presets.ini @@ -424,6 +424,8 @@ mixin-preset=buildbot_incremental_base # on Foundation, so that is built as well. On OS X, Foundation is built as part # of the XCTest Xcode project. xctest +swift-testing +swift-testing-macros build-swift-stdlib-unittest-extra @@ -441,6 +443,8 @@ skip-test-foundation release assertions xctest +swift-testing +swift-testing-macros test skip-test-cmark @@ -625,6 +629,8 @@ swiftformat swift-driver indexstore-db sourcekit-lsp +swift-testing +swift-testing-macros # Failing to build in CI: rdar://78408440 # swift-inspect install-llvm @@ -635,6 +641,8 @@ install-swiftpm install-swiftsyntax install-swift-driver install-swiftformat +install-swift-testing +install-swift-testing-macros # We need to build the unittest extras so we can test build-swift-stdlib-unittest-extra @@ -671,6 +679,10 @@ skip-test-llbuild enable-new-runtime-build +# Escalate certain C++ warnings to errors for Swift. +extra-swift-cmake-options= + -DCMAKE_CXX_FLAGS="-Werror=unused" + [preset: buildbot_incremental,tools=RA,stdlib=RD,smoketest=macosx,flto] mixin-preset=buildbot_incremental,tools=RA,stdlib=RD,smoketest=macosx build-subdir=buildbot_incremental @@ -936,9 +948,6 @@ mixin-preset= skip-test-swiftdocc -# to allow to build under aarch64 -llvm-build-compiler-rt-with-use-runtime=0 - [preset: buildbot_linux,release_foundation_tests] mixin-preset=buildbot_linux @@ -1134,6 +1143,8 @@ lldb foundation swiftpm swift-driver +swift-testing +swift-testing-macros xctest build-subdir=buildbot_linux @@ -1147,6 +1158,8 @@ install-foundation install-swiftpm install-swift-driver install-swiftsyntax +install-swift-testing +install-swift-testing-macros install-xctest install-prefix=/usr swift-install-components=autolink-driver;compiler;clang-builtin-headers;libexec;stdlib;swift-remote-mirror;sdk-overlay;dev @@ -3030,8 +3043,12 @@ build-subdir=compat_linux foundation libdispatch xctest +swift-testing +swift-testing-macros install-foundation install-libdispatch +install-swift-testing +install-swift-testing-macros install-xctest swift-install-components=autolink-driver;compiler;clang-builtin-headers;stdlib;libexec;swift-remote-mirror;sdk-overlay;license @@ -3224,6 +3241,8 @@ skip-early-swift-driver llbuild xctest +swift-testing +swift-testing-macros swiftpm swift-include-tests=0 @@ -3248,4 +3267,6 @@ install-foundation install-libdispatch install-llbuild install-swiftpm +install-swift-testing +install-swift-testing-macros install-xctest diff --git a/utils/embedded-test-support/libc.c b/utils/embedded-test-support/libc.c index b502cfbc5585f..04dd19c25b8a4 100644 --- a/utils/embedded-test-support/libc.c +++ b/utils/embedded-test-support/libc.c @@ -81,7 +81,7 @@ int memcmp(const void *s1, const void *s2, size_t n) { __attribute__((used)) void *memmove(void *dst, const void *src, size_t n) { - if ((uintptr_t)dst > (uintptr_t)src) { + if ((uintptr_t)dst < (uintptr_t)src) { for (int i = 0; i < n; i++) { ((char *)dst)[i] = ((char *)src)[i]; } diff --git a/utils/swift_build_support/swift_build_support/products/llvm.py b/utils/swift_build_support/swift_build_support/products/llvm.py index fad5efa812503..c5371269f534e 100644 --- a/utils/swift_build_support/swift_build_support/products/llvm.py +++ b/utils/swift_build_support/swift_build_support/products/llvm.py @@ -242,7 +242,9 @@ def build(self, host_target): llvm_cmake_options.define('INTERNAL_INSTALL_PREFIX', 'local') if host_target.startswith('linux'): - toolchain_file = self.generate_linux_toolchain_file(platform, arch) + toolchain_file = self.generate_linux_toolchain_file( + platform, arch, + crosscompiling=self.is_cross_compile_target(host_target)) llvm_cmake_options.define('CMAKE_TOOLCHAIN_FILE:PATH', toolchain_file) if not self.is_release(): # On Linux build LLVM and subprojects with -gsplit-dwarf which is more @@ -309,12 +311,26 @@ def build(self, host_target): if host_target.startswith('linux'): # This preserves the behaviour we had when using # LLVM_BUILD_EXTERNAL COMPILER_RT -- - # that is, having the linker not complaing if symbols used + # that is, having the linker not complaining if symbols used # by TSan are undefined (namely the ones for Blocks Runtime) # In the long term, we want to remove this and # build Blocks Runtime before LLVM - llvm_cmake_options.define( - 'SANITIZER_COMMON_LINK_FLAGS:STRING', '-Wl,-z,undefs') + if ("-DCLANG_DEFAULT_LINKER=gold" in llvm_cmake_options + or "-DCLANG_DEFAULT_LINKER:STRING=gold" in llvm_cmake_options): + print("Assuming just built clang will use a gold linker -- " + "if that's not the case, please adjust the value of " + "`SANITIZER_COMMON_LINK_FLAGS` in `extra-llvm-cmake-options`", + flush=True) + llvm_cmake_options.define( + 'SANITIZER_COMMON_LINK_FLAGS:STRING', + '-Wl,--unresolved-symbols,ignore-in-object-files') + else: + print("Assuming just built clang will use a non gold linker -- " + "if that's not the case, please adjust the value of " + "`SANITIZER_COMMON_LINK_FLAGS` in `extra-llvm-cmake-options`", + flush=True) + llvm_cmake_options.define( + 'SANITIZER_COMMON_LINK_FLAGS:STRING', '-Wl,-z,undefs') builtins_runtimes_target_for_darwin = f'{arch}-apple-darwin' if system() == "Darwin": diff --git a/utils/swift_build_support/swift_build_support/products/product.py b/utils/swift_build_support/swift_build_support/products/product.py index 8e675f228a29f..274b60373058b 100644 --- a/utils/swift_build_support/swift_build_support/products/product.py +++ b/utils/swift_build_support/swift_build_support/products/product.py @@ -389,7 +389,7 @@ def get_linux_target(self, platform, arch): sysroot_arch, vendor, abi = self.get_linux_target_components(arch) return '{}-{}-linux-{}'.format(sysroot_arch, vendor, abi) - def generate_linux_toolchain_file(self, platform, arch): + def generate_linux_toolchain_file(self, platform, arch, crosscompiling=True): """ Generates a new CMake tolchain file that specifies Linux as a target platform. @@ -402,8 +402,9 @@ def generate_linux_toolchain_file(self, platform, arch): toolchain_args = {} - toolchain_args['CMAKE_SYSTEM_NAME'] = 'Linux' - toolchain_args['CMAKE_SYSTEM_PROCESSOR'] = arch + if crosscompiling: + toolchain_args['CMAKE_SYSTEM_NAME'] = 'Linux' + toolchain_args['CMAKE_SYSTEM_PROCESSOR'] = arch # We only set the actual sysroot if we are actually cross # compiling. This is important since otherwise cmake seems to change the diff --git a/validation-test/IDE/stress_tester_issues_fixed/pr-81028.swift b/validation-test/IDE/stress_tester_issues_fixed/pr-81028.swift new file mode 100644 index 0000000000000..b168fc6642c5e --- /dev/null +++ b/validation-test/IDE/stress_tester_issues_fixed/pr-81028.swift @@ -0,0 +1,9 @@ +// RUN: %batch-code-completion + +// Make sure we don't crash. +func foo(xs: [[Int]], ys: [Int]) { + for x in ys { + _ = xs.map{ $0.filter{ $0 == x } #^COMPLETE^# } + // COMPLETE: Begin completions + } +} diff --git a/validation-test/SILOptimizer/rdar139666145.swift b/validation-test/SILOptimizer/rdar139666145.swift new file mode 100644 index 0000000000000..fb07277f2c5d0 --- /dev/null +++ b/validation-test/SILOptimizer/rdar139666145.swift @@ -0,0 +1,11 @@ +// RUN: %target-build-swift %s + +struct Box { var value: T } + +func modify(_ string: inout String) {} + +func tryConsume() { + var box = Box(value: "") + modify(&box.value) + print(consume box) +}