Commit Graph

713 Commits

Author SHA1 Message Date
Arnold Schwaighofer
13ff5abdb8 Introduce @specialized attribute
Implements SE-0460 -- the non-underscored version of @specialized.

It allows to specify "internal" (not abi affecting) specializations.

rdar://150033316
2025-05-23 13:12:47 -07:00
John Hui
c7070e73fe [NFC] [cxx-interop] Consolidate uses of findOptionSetType() helper function
Also renames it to findOptionSetEnum() to make it a bit clearer at face
value that the returned ImportedType will contain a Swift enum.

Also refactors some nearby instances of

  if (auto e = dyn_cast<ElaboratedType>(t))
      t = e->desugar();

into a helper function, desugarIfElaborated().
2025-05-19 14:10:49 -07:00
Steven Wu
3c81c1ca9f [Caching] Remove CASFS clang module implemenation
Remove the CASFS based clang module implemenation as it is not longer
used.
2025-05-14 09:35:03 -07:00
Robert Widmann
edcde7c55c [ClangImporter] Import 'swift_attr("sending")' As a Type Attribute
Previously, `__attribute__((swift_attr("sending")))` would only be
resolved when attached to declarations. This patch expands it to be
a type attribute as well, which enables it to occur in the result and
parameter positions for blocks, function pointers, and lambdas.

Resolves rdar://148435359
2025-05-07 18:19:38 +01:00
Egor Zhdan
b51cfa5c76 [cxx-interop] Remove symbolic import mode
Importing C++ class templates in symbolic mode has proven to be problematic in interaction with other compiler features, and it isn't used widely. This change removes the feature.

rdar://150528798
2025-05-02 18:43:09 +01:00
John Hui
50f5221962 [NFC] promote getOperatorName() to a non-static function (#80466) 2025-04-03 10:42:37 -04:00
Gabor Horvath
77e037d5f5 [cxx-interop] Fix invalid source range for some template instantiations
Apparently, clang will pick the source range of the canonical
declaration for template specializations. This might be in a different
buffer than the definition triggering various issues. Fortunately, Clang
also has the source locations we want, we just need to use a different
API to get them. Unfortunately, I haven't figured it out yet how to
trigger a failing test.

rdar://148250404
2025-04-01 15:18:32 +01:00
fahadnayyar
9694cc8d70 [cxx-interop] Import default public ctor of C++ foreign ref types as Swift Initializer (#79986)
Building on top of PR #79288, this update synthesizes a static factory method using the default new operator, with a call to the default constructor expression for C++ foreign reference types, and imports them as Swift initializers.

rdar://147529406
2025-03-31 20:33:53 -07:00
Hiroshi Yamauchi
42fe7d90cb Merge pull request #79926 from hjyamauchi/explicit-module-build
Propagate vfs overlays and -fbuiltin-headers-in-system-modules
2025-03-28 21:58:40 -07:00
Hiroshi Yamauchi
8312f7ad9a Propagate vfs overlays and -fbuiltin-headers-in-system-modules
This fixes explicit module builds for a hello world program on Windows
as well as the ucrt import build failure as in the included test.
2025-03-27 20:57:13 -07:00
Egor Zhdan
7c494800a7 [cxx-interop] Avoid diagnosing missing lifetime operations in symbolic mode
When importing C++ decls in symbolic mode, class templates are not instantiated, which means they might not have a destructor or a move constructor. Make sure we are not trying to diagnose those missing lifetime operations in symbolic mode.

This fixes incorrect diagnostics that were emitted during indexing at the end of compilation:
```
warning: 'import_owned' Swift attribute ignored on type 'basic_string': type is not copyable or destructible
```

As a nice side effect, this moves the logic that emits these diagnostics from the request body, which might be invoked many times, to the importer itself, which is only invoked once per C++ class.

rdar://147421710
2025-03-21 18:07:22 +00:00
Gábor Horváth
ed9eef234e Merge pull request #79324 from swiftlang/gaborh/redundant-lookups
[cxx-interop] Remove some duplicated lookups
2025-02-27 17:22:53 +00:00
John Hui
66c2e2c52b [cxx-interop] Import non-public inherited members (#79348)
This patch is follow-up work from #78942 and imports non-public members,
which were previously not being imported. Those members can be accessed
in a Swift file blessed by the SWIFT_PRIVATE_FILEID annotation.

As a consequence of this patch, we are also now importing inherited members
that are inaccessible from the derived classes, because they were declared
private, or because they were inherited via nested private inheritance. We
import them anyway but mark them unavailable, for better diagnostics and to
(somewhat) simplify the import logic for inheritance.

Because non-public base class members are now imported too, this patch
inflames an existing issue where a 'using' declaration on an inherited member
with a synthesized name (e.g., operators) produces duplicate members, leading
to miscompilation (resulting in a runtime crash). This was not previously noticed
because a 'using' declaration on a public inherited member is not usually
necessary, but is a common way to expose otherwise non-public members.
This patch puts in a workaround to prevent this from affecting the behavior
of MSVC's std::optional implementation, which uses this pattern of 'using'
a private inherited member. That will be fixed in a follow-up patch.

Follow-up work is also needed to correctly diagnose ambiguous overloads
in cases of multiple inheritance, and to account for virtual inheritance.

rdar://137764620
2025-02-25 01:03:16 -08:00
Henrik G. Olsson
957db2c959 [ClangImporter] Merge paths for std::span and __counted_by
importBoundsAttributes and importSpanAttributes are merged into a single
function named swiftify. This allows us to not have to duplicate the
effort of attaching _SwiftifyImport macros, but is also necessary to
allow importing a function with both __counted_by and std::span types.
2025-02-21 20:08:59 -08:00
fahadnayyar
d8f919778d [cxx-interop] [cxx-interop] Infer SWIFT_SHARED_REFERENCE for types inheriting from a C++ foreign reference type
rdar://97914474
2025-02-20 08:46:57 -08:00
Gabor Horvath
068815c2a3 [cxx-interop] Remove some duplicated lookups
Repeatedly lookup up a key from a dictionary can be justified whenever
the content of the dictionary might change between the lookups (so any
references into the dictionary might get invalidated). We had a couple
of instances where as far as I can tell no such modifications should
happen between two lookups with identical keys. This PR simplifies the
code to remove the extra lookups. It also removes a dictionary that was
completely unused.
2025-02-14 11:04:23 +00:00
John Hui
be73254cdc [cxx-interop] Import private members (#78942)
This commit removes the guardrails in ImportDecl.cpp:SwiftDeclConverter
that prevent it from importing non-public C++ members. It also
accordingly adjusts all code that assumes generated Swift decls should
be public. This commit does not import non-public inherited members;
that needs its own follow-up patch.

Note that Swift enforces stricter invariants about access levels than C++.
For instance, public typealiases cannot be assigned private underlying types,
and public functions cannot take or return private types. Meanwhile,
both of these patterns are supported in C++, where exposing private types
from a class's public interface is considered feature. As far as I am aware,
Swift was already importing such private-containing public decls from C++
already, but I added a test suite, access inversion, that checks and
documents this scenario, to ensure that it doesn't trip any assertions.
2025-01-30 14:50:15 -08:00
Gabor Horvath
4846c56795 [cxx-interop] Generate safe overloads for non-escapable spans
A previous PR already added support to the SwiftifyImport macro to
generate safe wrappers. This PR makes ClangImporter emit the macro to do
the transformation.
2025-01-08 11:19:35 +00:00
Henrik G. Olsson
ec8ea94fb9 Infer @PointerBounds macro from clang __counted_by parameters (#77387)
This results in an automatic wrapper function with safe pointer types
when the imported function has bounds attributes. This exercises similar
pathways as the recently added functionality for specifying macros from
swift_attr. The new functionality is guarded by the experimental
language feature SafeInteropWrappers.

rdar://97942270
2024-12-11 13:36:56 -08:00
Gábor Horváth
745d9b16be Merge pull request #77829 from swiftlang/gaborh/escapability-annotate-STL
[cxx-interop] Inject escapability for the C++ standard library
2024-12-06 15:05:17 +01:00
Gabor Horvath
9027edd430 [cxx-interop] Inject escapability for the C++ standard library
We only add conditional annotations because those do not break backward
compatibility (we might import span and similar view types as
non-escapable in the future). We inject these annotations in the
importer to make sure we have consistent behavior acress the different
standard library implementations. Once we can ship APINotes for the STL
and we have conditional escapability support in APINotes we can migrate
to that solution. But it is not possible as of today and Clang already
has precedent of injecting information for the STL with lifetimebound.

rdar://139065558
2024-12-05 16:27:34 +01:00
Doug Gregor
ac448b865b [Clang importer] Don't cache swift_attr source files that have CustomAttrs with arguments
Since we can't do a proper "deep" clone of expression nodes, cloning
such a CustomAttr is necessarily shallow. In such cases, don't cache
the swift_attr source files at all, so we get fresh attribute nodes
for each such usage.
2024-12-04 15:24:00 -08:00
Gabor Horvath
1601564342 [cxx-interop] Import rvalue references as consuming parameters
Unfortunately, importing them as is results in ambiguous call sites.
E.g., std::vector::push_back has overloads for lvalue reference and
rvalue reference and we have no way to distinguish them at the call site
in Swift. To overcome this issue, functions with rvalue reference
parameters are imported with 'consuming:' argument labels.

Note that, in general, move only types and consuming is not properly
supported in Swift yet. We do not invoke the dtor for the moved-from
objects. This is a preexisting problem that can be observed with move
only types before this PR, so the fix will be done in a separate PR.
Fortunately, for most types, the moved-from objects do not require
additional cleanups.

rdar://125816354
2024-12-02 13:09:21 +00:00
Gabor Horvath
558380f6f8 [cxx-interop] Support conditional escapability
This PR adds a variadic macro that builds a SwiftAttr string containing
the names of the template type parameters that need to be escapable for
the type to be considered escapable. It also adds logic to interpret
this annotation.

rdar://139065437
2024-11-15 14:27:54 +00:00
Doug Gregor
aa4c548c0f Clang importer: switch swift_attr attribute text cache over to be module-sensitive
We need different buffers for each imported module that has swift_attr attributes,
so cache them appropriately.
2024-11-13 21:19:39 -08:00
Gabor Horvath
86e708a39b [cxx-interop] Import more C++ source locations into Swift
Occasionally, when the Swift compiler emits a diagnostic for a construct
that was imported from C++ we get a diagnostic with unknown location.
This is a bad user experience. It is particularly bad with the
borrow-checker related diagnostics. This patch extends the source
location importing to declarations in ClangImporter. There are some
invariants enforced by the Swift compile, e.g., a source range is
comprised of two valid source locations or two invalid ones. As a
result, this patch adds approximate source locations to some separators
like braces or parens that are not maintained by Clang. Having slightly
incorrect ranges in this case is better than emitting unknown source
locations.
2024-10-30 10:58:26 +00:00
Gabor Horvath
929c0ca7d8 [cxx-interop] Introduce a safe C++ interop mode
In this mode all C++ types are imported as unsafe by default. Users
explicitly marking types are escapable or not escapable can make them
imported as safe. In the future, we also want to import unannotated
functions as unsafe and add more logic to infer types that are actually
safe, like agregates of escapable types.
2024-09-19 12:34:07 +01:00
Doug Gregor
4e7fb73b0c Provide the buffer ID for source files created for C swift_attr attributes
When rendering a swift_attr attribute for parsing, we were creating both
the backing buffer and a source file, but not providing the buffer's ID
to the source file, so we couldn't find the source code again. Fix that.

While here, also register the source file with the module, so we can
find the source file again based on location.
2024-09-16 21:45:34 -07:00
Gabor Horvath
738b4c6d8d [cxx-interop] Add a SWIFT_NONESCAPABLE attribute to the bridging header
This makes it easier to experiment with noescapable types in interop.
Moreover, we always wanted to have this annotation for completeness,
similar to SWIFT_NONCOPYABLE.
2024-09-02 14:51:27 +01:00
fahadnayyar
1d8ddc2697 [cxx-interop] Import the attributes from Clang decl for synthesized Swift decl for pointee and successor 2024-06-24 13:53:54 -07:00
Steven Wu
7a68d364f4 [Caching] Embed bridging header in binary module correctly when caching
When caching is enabled with include-tree, the bridging header PCH is
created from the include tree directly. Setup the rewriter correctly
when embedding the bridging header into swift binary module.

rdar://125719747
2024-04-15 14:46:38 -07:00
Ben Barham
1fdda023b3 Rename StringRef::endswith references to StringRef::ends_with
Missed this when doing the `startswith` renaming. `endswith` has also
been deprecated upstream (and presumably soon to be removed).
2024-04-01 10:59:16 -07:00
Dave Lee
e6a34e89ac [ClangImporter] Honor ClangTarget in getNormalInvocationArguments (#72375)
In `getNormalInvocationArguments`, use a triple that corresponds to `ClangTarget`. This 
matches the behavior of `addCommonInvocationArguments`.

rdar://124539816
2024-03-21 16:31:40 -07:00
Egor Zhdan
3e75fd207d Revert "[cxx-interop] Enable virtual function calling from Swift to C++"
This partially reverts commit 128064f3
2024-02-29 22:33:27 +00:00
Ben Barham
ef8825bfe6 Migrate llvm::Optional to std::optional
LLVM has removed llvm::Optional, move over to std::optional. Also
clang-format to fix up all the renamed #includes.
2024-02-21 11:20:06 -08:00
Becca Royal-Gordon
7aa5b7fd88 Merge pull request #71445 from beccadax/category-error 2024-02-13 11:13:48 -08:00
Becca Royal-Gordon
9bcd818fb1 [NFC] Make objcImpl request one-to-many
An @_objcImpl extension with no category name *should* implement not only the class’s main @interface, but also any class extension @interfaces. Start making this true by making ObjCInterfaceAndImplementationRequest return all of these decls as the interfaces for such an implementation.

This commit doesn’t actually change Sema or IRGen to process the extra interfaces, so it’s NFC.
2024-02-09 21:32:06 -08:00
Becca Royal-Gordon
11977682b6 [NFC] Cache objcImpl requests in ClangImporter
This reduces the memory overhead of objcImpl from one word per Decl to one bit per Decl, at the cost of making cache lookups slightly slower (but it will only be consulted once for non-objcImpl decls, which is by far the most common case).
2024-02-08 20:34:31 -08:00
Becca Royal-Gordon
6e44517af0 [NFC] Make insertMembersAndAlternates more specific
This will help when ClangImporter::Impl::loadNamedMembers() starts having to handle a lot more import-as-members names, but it’s NFC in this commit.
2024-02-01 12:41:42 -08:00
Artem Chikin
e04512f55c Merge pull request #71161 from artemcm/IncrementalExplicitHeaderFixes
[Explicit Module Builds] Register Clang module dependencies' input `.h` files with the dependency tracker
2024-01-26 13:24:37 -08:00
Artem Chikin
5fdb695d6d [Explicit Module Builds] Register Clang module dependencies' input .h files with the dependency tracker
Prior to emission of `.d` and `.swiftdeps` outputs. In implicit builds such dependencies are registered during the construction of the corresponding Clang module by the ClangImporter's built-in Compiler Instance. In explicit builds, since we load pre-built PCMs directly, we do not get to do so. So instead, manually register all `.h` inputs of Clang module dependnecies.

Resolves rdar://121354886
2024-01-25 15:41:19 -08:00
Steven Wu
4fb7abc9f9 [ExplicitModule] Fix canImport lookup for swift explicit module build
Previously, canImport lookup is not completely working with explicit
module due to two issues:
* For clang modules, canImport check still do a full modulemap lookup
  which is repeated work from scanner. For caching builds, this lookup
  cannot be performed because all modulemap and search path are dropped
  after scanning.
* For swift module, if the canImport module was never actually imported
  later, this canImport check will fail during the actual compilation,
  causing different dependencies in the actual compilation.

To fix the problem, first unified the lookup method for clang and swift
module, which will only lookup the module dependencies reported by
scanner to determine if `canImport` succeed or not. Secondly, add all
the successful `canImport` check modules into the dependency of the
current module so this information can be used during actual
compilation.

Note the behavior change here is that if a module is only checked in
`canImport` but never imported still needs to be built. Comparing to
implicit module build, this can bring in additional clang modules if
they are only check inside `canImport` but should not increase work for
swift modules (where binary module needs to be on disk anyway) or the
most common usecase for `canImport` which is to check the same module
before importing.

rdar://121082031
2024-01-18 10:31:33 -08:00
Pavel Yaskevich
6a3ef05109 [ClangImporter] Augment has*Attr methods to find attributes in type positions
`SwiftAttr` can now appear in type positions and `has*Attr` methods
have to account for that when the given declaration is `ParmVarDecl`.
2024-01-15 12:20:46 -08:00
Pavel Yaskevich
a168a94f1f [ClangImporter] NFC: Transform applyTypeAttributes into getConcurrencyAttrs
It has to be reachable to declaration converter to handle attributes
associated with generic parameters.
2024-01-12 11:32:06 -08:00
Pavel Yaskevich
2e36b2cca1 [ClangImporter] Move SendableCompletionHandlers feature handling into type importer
Parameters no longer expose their attributes at their declaration,
all of the attributes are handled uniformly as type attributes.
2024-01-12 11:32:06 -08:00
Pavel Yaskevich
578f82f466 [ClangImporter] Introduce a new kind of parameter - completion handler 2024-01-12 11:32:06 -08:00
Pavel Yaskevich
41ef9b6f38 [ClangImporter] NFC: Convert CF{Un}retainedOutParaeter into ImportTypeAttr 2024-01-12 11:32:06 -08:00
Egor Zhdan
494474b021 [cxx-interop] Support C++ default arguments
This allows calling a C++ function with default arguments from Swift without having to explicitly specify the values of all arguments.

rdar://103975014
2024-01-10 16:37:42 +00:00
Puyan Lotfi
128064f31d [cxx-interop] Enable virtual function calling from Swift to C++
This is a forward-interop feature that wires up existing functionality for
synthesizing base class function calling to enable virtual function calling.
The general idea is to sythesize the pattern:

```
// C++ class:
struct S { virtual auto f() -> int { return 42; } };

// Swift User:
var s = S()
print("42: \(s.f())")

// Synthetized Swift Code:
extension S { func f() -> CInt { __synthesizedVirtualCall_f() } }

// Synthetized C/C++ Code:
auto __cxxVirtualCall_f(S *s) -> int { return s->f(); }
```

The idea here is to allow for the synthetized C++ bits from the Clang side to
handle the complexity of virtual function calling.
2023-12-04 01:55:30 -05:00
Egor Zhdan
efc008a2ca [cxx-interop] Import using decls that expose methods from private base classes
If a C++ type `Derived` inherits from `Base` privately, the public methods from `Base` should not be callable on an instance of `Derived`. However, C++ supports exposing such methods via a using declaration: `using MyPrivateBase::myPublicMethod;`.

MSVC started using this feature for `std::optional` which means Swift doesn't correctly import `var pointee: Pointee` for instantiations of `std::optional` on Windows. This prevents the automatic conformance to `CxxOptional` from being synthesized.

 rdar://114282353 / resolves https://github.com/apple/swift/issues/68068
2023-11-14 00:30:54 +00:00