Commit Graph

9293 Commits

Author SHA1 Message Date
Gábor Horváth
40bea13e68 [6.2][cxx-interop] Delay lowering unowned convention until ownership elimination
Explanation: Unowned result conventions do not work well with OSSA. Retain the
result right after the call when we come out of OSSA so we can treat the
returned value as if it was owned when we do optimizations.

This fix a miscompilation due to the DestroyAddrHoisting pass hoisting destroys
above copies with unowned sources. When the destroyed object was the last
reference to the pointed memory the copy is happening too late resulting in
a use after free.

Issues: rdar://160462854
Original PRs: #84612
Risk: We change where retaining of the unowned return values
happen in the optimization pipeline. It is hard to anticipate all the
possible effects but it should make the optimizer more correct.
Testing: Added a compiler test.
Reviewers: @eeckstein, @atrick
2025-10-08 18:57:54 +01:00
John McCall
2bd4c8c0ac At the SIL level, allow synchronous functions to be nonisolated(nonsending). 2025-09-11 21:51:44 -04:00
John McCall
6f376c2468 Fix SILGen's computation of default argument generator isolation 2025-09-11 21:51:36 -04:00
Egor Zhdan
8178aa8b65 [cxx-interop] Pass foreign reference types with correct level of indirection
When calling a C++ function that takes a reference to a pointer to a foreign reference type, Swift would previously pass a pointer to the foreign reference type as an argument (instead of a reference to a pointer), which resulted in invalid memory accesses.

This was observed when using `std::vector<ImmortalRef*>::push_back`.

rdar://150791778
(cherry picked from commit 0a766e59ce)
2025-09-03 20:42:06 +01:00
Nate Chandler
5798e71baf [MemoryLifetimeVerifier] Permit leaks in dead-ends 2025-08-28 05:47:40 -07:00
Nate Chandler
c7c0cb03d2 [SIL] Fix visitAccessedAddress @ end_borrow
`end_borrow` instructions may end the scopes introduced by `load_borrow`
or `store_borrow` instructions, or those introduced by `begin_borrow`
whose operand's guaranteed root includes a `load_borrow`.

Previously, such scope ending instructions which end the scope
associated with a borrowing load or store were not regarded as accessing
the loaded-from or stored-to address.  One consequence of this is that
they were not regarded as accessing pointers and thus not as deinit
barriers; that in turn resulted in `destroy_addr`s being hoisted into
such borrow scopes.

Here this is fixed by regarding such `end_borrow`s to access the
loaded-from or stored-to address of the scope-introducing `load_borrow`
or `store_borrow` respectively.

rdar://157772187
2025-08-13 16:48:58 -07:00
Michael Gottesman
e73396bc8a [sil] Add the ability to mark a function with isolation just so we can write more concurrency tests in SIL.
Specifically, we write a string out like:

sil [isolation "$REPRESENTATION OF ISOLATION"] @function : $@convention(thin) ...

The idea is that by using a string, we avoid parsing issues of the isolation and
have flexibility. I left in the way we put isolation into the comment above
functions so I did not break any tests that rely on it. I also made it so that
we only accept this with sil tests that pass in the flag
"sil-print-function-isolation-info". I am going to for the next release put in a
full real implementation of this that allows for actor isolation to become a
true first class citizen in SIL. But for now this at least lets us write tests
in the short term.

Since this is temporary and behind a flag, I did not add support for
serialization since this is just for writing textual SIL tests.

(cherry picked from commit ee3027c2ca)

Conflicts:
	lib/SIL/Parser/ParseSIL.cpp
2025-07-15 17:12:01 -07:00
Joe Groff
79b59f1977 Lower imported C structs and unions as addressable-for-dependencies.
C code is highly likely to want to use pointers as references between dependent
structs, and we would like to be able to readily map these to lifetime-dependent
Swift values. Making C types addressable-for-dependencies ensures that any function
producing a dependency on such a value receives a stable in-memory address for that
value, allowing borrows and inout accesses to always be representable as pointers.

rdar://153648393
2025-07-07 08:46:43 -07:00
Jamie
11525cabf8 [SILOptimizer]: slow OSSA lifetime canonicalization mitigation
OSSA lifetime canonicalization can take a very long time in certain
cases in which there are large basic blocks. to mitigate this, add logic
to skip walking the liveness boundary for extending liveness to dead
ends when there aren't any dead ends in the function.

Updates `DeadEndBlocks` with a new `isEmpty` method and cache to
determine if there are any dead-end blocks in a given function.

(cherry picked from commit 1f3f830fc7)
2025-06-22 18:08:06 -05:00
nate-chandler
4051ea2e78 Merge pull request #82044 from nate-chandler/cherrypick/release/6.2/rdar152580661
6.2: [TypeLowering] Record pack used in aggregate signature.
2025-06-06 14:53:18 -07:00
Nate Chandler
d8c6f9817c [TypeLowering] Record pack used in aggregate sig.
Every `LowerType::visit*` function eventually calls through to a
`LowerType::handle*` function.  After
https://github.com/swiftlang/swift/pull/81581, every
`LowerType::handle*` needs to set the `hasPack` flag based on the
passed-in type by calling `mergeHasPack`.  Add the missing call in the
`handleAggregateByProperties` function.

rdar://152580661
2025-06-05 17:45:14 -07:00
Pavel Yaskevich
608a37ad04 Merge pull request #81997 from xedin/using-for-default-isolation-in-file-context-6.2
[6.2][AST/Sema] SE-0478: Implement using declaration under an experimental flag
2025-06-05 00:44:21 -07:00
Pavel Yaskevich
d057429e9a [AST] Add new declaration - using
Initially this declaration is going to be used to determine
per-file default actor isolation i.e. `using @MainActor` and
`using nonisolated` but it could be extended to support other
file-global settings in the future.

(cherry picked from commit aabfebec03)
2025-06-04 13:16:55 -07:00
Konrad `ktoso` Malawski
284487cc27 Merge pull request #81831 from ktoso/pick-irgen-mangling-fix-distributed 2025-06-05 05:06:52 +09:00
Konrad 'ktoso' Malawski
9c023a2577 [Distributed] print distributed(_thunk) in SILPrinter 2025-06-04 21:07:06 +09:00
Nate Chandler
ef7ee7c825 [Gardening] Tweaked comments. 2025-06-03 15:54:11 -07:00
nate-chandler
57651963f1 Merge pull request #81875 from nate-chandler/cherrypick/release/6.2/rdar152195094
6.2: [DestroyAddrHoisting] Don't destructure NE aggs.
2025-05-30 21:06:59 -07:00
Nate Chandler
c3671aaa4f [DestroyAddrHoisting] Don't destructure NC aggs.
When hoisting destroys of aggregates, an attempt is made to fold the
destroys of individual fields into the foregoing instructions.  If the
aggregate is noncopyable, this transformation is illegal.
2025-05-30 13:27:45 -07:00
Nate Chandler
bb28bd756c [DestroyAddrHoisting] Don't destructure NE aggs.
When hoisting destroys of aggregates, an attempt is made to fold the
destroys of individual fields into the foregoing instructions.  If the
aggregate is nonescapable, this transformation is illegal.

rdar://152195094
2025-05-30 13:27:45 -07:00
Nate Chandler
c894bdffab [NFC] SIL: This utility takes a func not a module.
In preparation to use the function in the implementation.
2025-05-30 13:27:45 -07:00
Joe Groff
5ca6ad9d5e SILGen: Emit property descriptors for conditionally Copyable and Escapable types.
Key paths can't reference non-escapable or non-copyable storage declarations,
so we don't need to refer to them resiliently, and can elide their property
descriptors.

However, declarations may still be conditionally Copyable and Escapable, and
if so, then they still need a property descriptor for resilient key path
references. When a property or subscript can be used in a context where it
is fully Copyable and Escapable, emit the property descriptor in a generic
environment constrained by the necessary conditional constraints.

Fixes rdar://151628396.
2025-05-27 20:18:58 -07:00
Meghana Gupta
b91b772b01 Merge pull request #81679 from meg-gupta/fixsubstne
[6.2] Fix use-after-free on substituting function type involving conditional ~Escapable with Escapable type
2025-05-27 12:46:52 -07:00
Erik Eckstein
30e138c48b SIL: define mark_dependence_addr to read and write to its address operand
This prevents simplification and SILCombine passes to remove (alive) `mark_dependence_addr`.
The instruction is conceptually equivalent to
```
  %v = load %addr
  %d = mark_dependence %v on %base
  store %d to %addr
```

Therefore the address operand has to be defined as writing to the address.
2025-05-23 07:53:14 +02:00
Pavel Yaskevich
e12201769d [AST/Sema/SIL] Implement @_inheritActorContext(always)
- Extend `@_inheritActorContext` attribute to support optional `always` modifier.
  The new modifier will make closure context isolated even if the parameter is not
  captured by the closure.
- Implementation `@_inheritActorContext` attribute validation - it could only be
  used on parameter that have `@Sendable` or `sending` and `@isolated(any)` or
  `async` function type (downgraded to a warning until future major Swift mode
  to avoid source compatibility issues).
- Add a new language feature that guards use of `@_inheritActorContext(always)` in swift interface files
- Update `getLoweredLocalCaptures` to add an entry for isolation parameter implicitly captured by `@_inheritActorContext(always)`
- Update serialization code to store `always` modifier

(cherry picked from commit 04d46760bb)
(cherry picked from commit c050e8f75a)
(cherry picked from commit c0aca5384b)
(cherry picked from commit a4f6d710cf)
(cherry picked from commit 6c911f5d42)
(cherry picked from commit 17b8f7ef12)
2025-05-22 11:32:35 -07:00
Michael Gottesman
63a436ec04 Merge pull request #81615 from gottesmm/release/6.2-rdar151394209
[6.2] Fix a few issues around nonisolated(nonsending) and  protocol witness thunks/vtable thunks
2025-05-22 00:04:01 -07:00
Meghana Gupta
00dcffcd24 [6.2] Fix use-after-free on substituting function type involving conditional ~Escapable with Escapable type 2025-05-21 16:30:02 -07:00
Stephen Canon
85b304220f [6.2] Implement Builtin.select binding llvm select instruction (#81665)
Not used (yet), but needed to implement SIMD.replacing(with:where:)
idiomatically, and probably useful otherwise.

**Explanation:** Makes select available in Swift's builtin module, which
allows implementing concrete SIMD operations more efficiently.
**Risk:** Low. New builtin protected by a feature flag, currently
unused.
**Testing:** New tests added.
**Reviewers:** @eeckstein, @Azoy 
**Main branch PR:** https://github.com/swiftlang/swift/pull/81598
2025-05-21 19:14:33 -04:00
Egor Zhdan
36511a2937 Merge pull request #81674 from swiftlang/egorzhdan/6.2-silverifier-trivial-frt
🍒[cxx-interop] Relax a SILVerifier assertion for immortal reference types
2025-05-21 22:35:59 +01:00
nate-chandler
1887346228 Merge pull request #81659 from nate-chandler/cherrypick/release/6.2/rdar147207926
6.2: [TypeLowering] Record packs used in signatures.
2025-05-21 13:40:48 -07:00
Egor Zhdan
069c42159f [cxx-interop] Relax a SILVerifier assertion for immortal reference types
Immortal C++ foreign reference types get TrivialTypeLowering instead of ReferenceTypeLowering, since they do not have retain/release lifetime operations. This was tripping up an assertion in SILVerifier.

rdar://147251759 / resolves https://github.com/swiftlang/swift/issues/80065
(cherry picked from commit 2e3df1c0f3)
2025-05-21 13:06:01 +01:00
Nate Chandler
701ad64ca6 [TypeLowering] Record packs used in signatures.
To determine whether an instruction may require pack metadata, the types
of its operands are examined.

Previously, the top level type was checked for having a pack in its
signature, and the whole type was checked for having a type anywhere in
its layout (via TypeLowering).  This didn't account for the case where
the metadata was required for a resilient type which uses a pack in its
signature.

Here, during type lowering, a type having a pack in its signature is
counted towards the type having a pack.

Fixes a compiler crash.

rdar://147207926
2025-05-20 17:26:46 -07:00
Meghana Gupta
58300798ca Merge pull request #81521 from meg-gupta/disableverificationcp
[6.2] Add a new semantics attribute to disable SIL verification on a function
2025-05-19 18:01:34 -07:00
Michael Gottesman
27cf33676f [silgen] Place the correct isolation on protocol witness thunks.
We were using the isolation from the witness not from the requirement which we
are supposed to do. The witness thunk thunks the isolation from the requirement
to the witness so from an ABI perspective it should have the interface implied
by the requirement's isolation since that is what callers of the witness method
will expect.

rdar://151394209
(cherry picked from commit 39a013f807)
2025-05-19 10:33:57 -07:00
Michael Gottesman
d3145b2380 [silgen] Begin placing isolation on protocol witness thunks.
This will cause tests today to crash since even though we are placing the
isolation now, to make it easier to read, I left in the old isolation selecting
code. This code uses the witness's isolation instead of the requirement's
isolation which is incorrect since the protocol witness thunk needs to look the
requirement from an ABI perspective since the two must be substitutable. The
crash comes from the ABI verification I added in earlier commits.

(cherry picked from commit ff1cbea576)
2025-05-19 10:33:46 -07:00
Michael Gottesman
752e12bd5b [sil] Verify that witness table witnesses are ABI compatible with their requirements.
(cherry picked from commit ed1654c3cf)
2025-05-19 10:33:30 -07:00
Michael Gottesman
be412d7dd0 [gardening] Clean up SILWitnessTable::verify before I touch it.
I just renamed a few variables and eliminated a bunch of unnecessary
indentation.

Just to make it easier to review the actual functional change.

(cherry picked from commit 634435d8cf)
2025-05-19 10:33:23 -07:00
Michael Gottesman
55a0e7beac [sil] Change SILDefaultWitnessTable verification to use verificationEnabled instead of #ifndef NDEBUG to match the rest of the SILVerifier.
I think this was just an oversight. There is really no reason that this should
not match the rest of the SILVerifier w here we have moved from using #ifndef
NDEBUG to verificationEnabled checking.

(cherry picked from commit e25c664c98)
2025-05-19 10:33:18 -07:00
Michael Gottesman
1b2f943945 [gardening] Cleanup SILDefaultWitnessTable before I change it.
Just to make review easier.

(cherry picked from commit 71adae4c0c)
2025-05-19 10:33:16 -07:00
Meghana Gupta
06f681777d [6.2] Add a new semantics attribute to disable SIL verification on a function 2025-05-15 14:32:09 -07:00
Erik Eckstein
21303a5d3d SIL: Make the verifier's ImmutableAddressUseVerifier generally available
Also, make it more tolerant to instructions and builtins, which are not explicitly handled.
This avoids crashes when new instructions are added. We got lucky that this didn't happen so far.
2025-05-14 07:09:32 +02:00
Michael Gottesman
d3de4a64c9 Merge pull request #81363 from gottesmm/release/6.2-rdar150209093
[6.2][concurrency] Ensure that we treat closures that are nonisolated(nonsending) via their ActorIsolation as nonisolated(nonsending).
2025-05-09 18:43:32 -07:00
Becca Royal-Gordon
51da65bebd Make inlinability non-ABI for @abi
Inlinability doesn’t affect the mangling except in function specializations, which are applied after the fact and should never mangle in information from an ABI-only decl. That means we can simply ban these from `@abi` instead of inferring them.

Also adds some assertions to help double-check that SIL never tries to directly mangle or retrieve inlinability info from an ABI-only decl.
2025-05-08 18:27:57 -07:00
Michael Gottesman
03d8c0ae6b [concurrency] Ensure that we treat closures that are nonisolated(nonsending) via their ActorIsolation as nonisolated(nonsending).
Some notes:

1. In most cases, I think we were getting lucky with this by just inferring the
closure's isolation from its decl context. In the specific case that we were
looking at here, this was not true since we are returning from an @concurrent
async function a nonisolated(nonsending) method that closes over self. This
occurs since even when NonisolatedNonsendingByDefault we want to start importing
objc async functions as nonisolated(nonsending).

2. I also discovered that in the ActorIsolationChecker we were not visiting the
inner autoclosure meaning that we never set the ActorIsolation field on the
closure. After some discussion with @xedin about potentially visiting the
function in the ActorIsolationChecker, we came to the conclusion that this was
likely to result in source stability changes. So we put in a targeted fix just
for autoclosures in this specific case by setting their actor isolation in the
type checker.

3. Beyond adding tests to objc_async_from_swift to make sure that when
NonisolatedNonsendingByDefault is disabled we do the right thing, I noticed that
we did not have any tests that actually tested the behavior around
objc_async_from_swift when NonisolatedNonsendingByDefault is enabled. So I added
the relevant test lines so we can be sure that we get correct behavior in such a
case.

rdar://150209093
(cherry picked from commit ced96aa5cd)
2025-05-07 13:03:45 -07:00
Erik Eckstein
bb9829c89c SIL ownership verifier: don't require scope-ending instructions for unchecked_ownership_conversion
The optimizer may convert unowned blocks to guaranteed blocks for a partial_apply. This does not require any scope-ending instructions.
2025-05-06 17:57:37 +02:00
Artem Chikin
8aca9b115c Merge pull request #81146 from artemcm/ParameterizeWeakQueryForSwift-62
[6.2 🍒] Modify clang declaration weakly-imported query to use Swift's code-gen target triple
2025-05-05 09:21:44 -07:00
Erik Eckstein
bcc9753288 CastOptimizer: don't assume dynamic casts from ObjectiveC classes to unrelated classes will fail
In case of ObjectiveC classes, the runtime type can differ from its declared type.
Therefore a cast between (compile-time) unrelated classes may succeed at runtime.

rdar://149810124
2025-05-02 07:24:30 +02:00
Artem Chikin
4ac9119bf7 Modify clang declaration weakly-imported query to use Swift's code-gen target triple
Similarly to how https://github.com/swiftlang/swift/pull/70564 configures 'ClangImporter's 'CodeGenerator' using Swift's compilation target triple, we must use the versioned version of the 'isWeakImported' query to determine linkage for imported Clang symbols.
2025-05-01 10:40:10 -07:00
Meghana Gupta
cc72edb119 Introduce end_cow_mutation_addr instruction 2025-04-30 14:38:48 -07:00
Slava Pestov
e3d8e356cb Merge pull request #81080 from slavapestov/fix-rdar149353285-6.2
[6.2] SIL: Use SubstitutionMap::mapIntoTypeExpansionContext() in SILTypeSubstituter
2025-04-29 08:02:37 -04:00
Slava Pestov
88814e4fbf SIL: Use SubstitutionMap::mapIntoTypeExpansionContext() in SILTypeSubstituter
I made a mistake in 47156e006b. There was a
call to call to forAbstract() in SILTypeSubstituter that passed in the
wrong subject ype.

This call was inside SILTypeSubstituter's own implementation of replacing
opaque types with underlying types in a substitution map. This duplicates
an existing utility method in SubstitutionMap anyway, so let's just use
that instead.

Fixes rdar://149353285.
2025-04-28 11:52:41 -04:00