Commit Graph

2822 Commits

Author SHA1 Message Date
John McCall
64d020ec45 [NFC] Introduce a convenience specialization of CanTypeVisitor that
forwards the paired nominal type methods to common implementations.
2025-09-05 14:02:36 -04:00
Erik Eckstein
8e86b5ce3b Optimizer: add a preserveGenericSignature flag to FunctionPassContext.createSpecializedFunctionDeclaration 2025-09-04 08:15:46 +02:00
Erik Eckstein
45b1a21e74 Optimizer: make ModulePassContext.specialize() also available in FunctionPassContext and add two argument flags
add `convertIndirectToDirect` and `isMandatory`
2025-09-04 08:15:45 +02:00
Erik Eckstein
1a4bd76f95 Mangling: add specialization mangling for more complex constant propagated function arguments
So far, constant propagated arguments could only be builtin literals.
Now we support arbitrary structs (with constant arguments), e.g. `Int`.
This requires a small addition in the mangling scheme for function specializations.
Also, the de-mangling tree now looks a bit different to support a "tree" of structs and literals.
2025-09-04 08:15:44 +02:00
Erik Eckstein
bc244d1122 SIL: move the FunctionBuilderTy template argument from TypeSubstCloner to remapParentFunction 2025-09-04 08:15:44 +02:00
Janat Baig
f21eb5375e Merge branch 'main' into temp-branch 2025-09-02 20:23:25 -04:00
Jakub Florek
eae7864370 Merge pull request #83988 from MAJKFL/new-sil-licm-pass-copy
New SIL LICM pass
2025-09-01 10:28:17 +01:00
Michael Gottesman
6d20c74c3e Merge pull request #83903 from gottesmm/rdar152454571
[rbi] Teach RegionIsolation how to properly error when 'inout sending' params are returned.
2025-08-29 14:56:58 -07:00
Jakub Florek
e3140e0ae0 Add new generalized cloner. 2025-08-28 20:57:57 +01:00
Erik Eckstein
87e7250750 Optimizer: fix an ownership violation when duplicating loops
If a guaranteed value is used in a dead-end exit block and the enclosing value is _not_ destroyed in this block, we end up missing the enclosing value as phi-argument after duplicating the loop.
TODO: once we have complete lifetimes we can remove this check again.

rdar://159125605
2025-08-28 18:40:54 +02:00
Michael Gottesman
8745ab00de [rbi] Teach RegionIsolation how to properly error when 'inout sending' params are returned.
We want 'inout sending' parameters to have the semantics that not only are they
disconnected on return from the function but additionally they are guaranteed to
be in their own disconnected region on return. This implies that we must emit
errors when an 'inout sending' parameter or any element that is in the same
region as the current value within an 'inout sending' parameter is
returned. This commit contains a new diagnostic for RegionIsolation that adds
specific logic for detecting and emitting errors in these situations.

To implement this, we introduce 3 new diagnostics with each individual
diagnostic being slightly different to reflect the various ways that this error
can come up in source:

* Returning 'inout sending' directly:

```swift
func returnInOutSendingDirectly(_ x: inout sending NonSendableKlass) -> NonSendableKlass {
  return x // expected-warning {{cannot return 'inout sending' parameter 'x' from global function 'returnInOutSendingDirectly'}}
  // expected-note @-1 {{returning 'x' risks concurrent access since caller assumes that 'x' and the result of global function 'returnInOutSendingDirectly' can be safely sent to different isolation domains}}
}
```

* Returning a value in the same region as an 'inout sending' parameter. E.x.:

```swift
func returnInOutSendingRegionVar(_ x: inout sending NonSendableKlass) -> NonSendableKlass {
  var y = x
  y = x
  return y // expected-warning {{cannot return 'y' from global function 'returnInOutSendingRegionVar'}}
  // expected-note @-1 {{returning 'y' risks concurrent access to 'inout sending' parameter 'x' since the caller assumes that 'x' and the result of global function 'returnInOutSendingRegionVar' can be safely sent to different isolation domains}}
}
```

* Returning the result of a function or computed property that is in the same
region as the 'inout parameter'.

```swift
func returnInOutSendingViaHelper(_ x: inout sending NonSendableKlass) -> NonSendableKlass {
  let y = x
  return useNonSendableKlassAndReturn(y) // expected-warning {{cannot return result of global function 'useNonSendableKlassAndReturn' from global function 'returnInOutSendingViaHelper'}}
  // expected-note @-1 {{returning result of global function 'useNonSendableKlassAndReturn' risks concurrent access to 'inout sending' parameter 'x' since the caller assumes that 'x' and the result of global function 'returnInOutSendingViaHelper' can be safely sent to different isolation domains}}
}
```

Additionally, I had to introduce a specific variant for each of these
diagnostics for cases where due to us being in a method, we are actually in our
caller causing the 'inout sending' parameter to be in the same region as an
actor isolated value:

* Returning 'inout sending' directly:

```swift
extension MyActor {
  func returnInOutSendingDirectly(_ x: inout sending NonSendableKlass) -> NonSendableKlass {
    return x // expected-warning {{cannot return 'inout sending' parameter 'x' from instance method 'returnInOutSendingDirectly'}}
    // expected-note @-1 {{returning 'x' risks concurrent access since caller assumes that 'x' is not actor-isolated and the result of instance method 'returnInOutSendingDirectly' is 'self'-isolated}}
  }
}
```

* Returning a value in the same region as an 'inout sending' parameter. E.x.:

```swift
extension MyActor {
  func returnInOutSendingRegionLet(_ x: inout sending NonSendableKlass) -> NonSendableKlass {
    let y = x
    return y // expected-warning {{cannot return 'y' from instance method 'returnInOutSendingRegionLet'}}
    // expected-note @-1 {{returning 'y' risks concurrent access to 'inout sending' parameter 'x' since the caller assumes that 'x' is not actor-isolated and the result of instance method 'returnInOutSendingRegionLet' is 'self'-isolated}}
  }
}
```

* Returning the result of a function or computed property that is in the same region as the 'inout parameter'.

```swift
extension MyActor {
  func returnInOutSendingViaHelper(_ x: inout sending NonSendableKlass) -> NonSendableKlass {
    let y = x
    return useNonSendableKlassAndReturn(y) // expected-warning {{cannot return result of global function 'useNonSendableKlassAndReturn' from instance method 'returnInOutSendingViaHelper'; this is an error in the Swift 6 language mode}}
    // expected-note @-1 {{returning result of global function 'useNonSendableKlassAndReturn' risks concurrent access to 'inout sending' parameter 'x' since the caller assumes that 'x' is not actor-isolated and the result of instance method 'returnInOutSendingViaHelper' is 'self'-isolated}}
  }
}
```

To implement this, I used two different approaches depending on whether or not
the returned value was generic or not.

* Concrete

In the case where we had a concrete value, I was able to in simple cases emit
diagnostics based off of the values returned by the return inst. In cases where
we phied together results due to multiple results in the same function, we
determine which of the incoming phied values caused the error by grabbing the
exit partition information of each of the incoming value predecessors and seeing
if an InOutSendingAtFunctionExit would emit an error.

* Generic

In the case of generic code, it is a little more interesting since the result is
a value stored in an our parameter instead of being a value directly returned by
a return inst. To work around this, I use PrunedLiveness to determine the last
values stored into the out parameter in the function to avoid having to do a
full dataflow. Then I take the exit blocks where we assign each of those values
and run the same check as we do in the direct phi case to emit the appropriate
error.

rdar://152454571
2025-08-25 14:57:44 -07:00
Arnold Schwaighofer
2fd904808c ConstantTracker: Look through mark_dependence instructions
An interposed mark_dependence should not block the heuristic that adds a
benefit when inlining a function that takes a closure argument.
2025-08-25 13:57:23 -07:00
Janat Baig
798c0f51a4 Merge branch 'main' into temp-branch 2025-08-23 11:11:04 -04:00
JanBaig
52895fefc3 [SIL] Remove AssignByWrapper references from SIL passes 2025-08-22 23:20:53 -04:00
nate-chandler
d1637af144 Merge pull request #83789 from nate-chandler/nfc/20250818/1
[NFC] Renamed three SIL utilities.
2025-08-20 13:25:04 -07:00
Nate Chandler
5da38cb04b [NFC] OSSACanonicalizeGuaranteed: Renamed. 2025-08-18 09:45:27 -07:00
Nate Chandler
8f1d6616af [NFC] OSSACanonicalizeOwned: Renamed. 2025-08-18 09:45:21 -07:00
Nate Chandler
aa85694237 [NFC] OSSACompleteLifetime: Renamed. 2025-08-18 09:45:19 -07:00
Andrew Trick
1cb6ab5359 Merge pull request #83763 from atrick/fix-dce-struct-deinit
SIL: fix miscompiles of non-Copyable struct/enum with deinits
2025-08-17 12:33:45 -07:00
Andrew Trick
9d40198c0f SIL: fix miscompiles of non-Copyable struct/enum with deinits
The SIL optimizer has fundamental bugs that result in dropping non-Copyable
struct & enum the deinitializers.

Fix this by

1. correctly representing the ownership of struct & enum values that are
   initialized from trivial values.

2. checking move-only types before deleting forwarding instructions.

These bugs block other bug fixes. They are exposed by other unrelated SIL
optimizations to SIL. I'm sure its possible to expose the bugs with source-level
tests, but the current order of inlining and deinit devirtualization has been
hiding the bugs and complicates reproduction.
2025-08-15 15:03:50 -07:00
Nate Chandler
017f003147 [OSSA] Fix borrowCopyOverGuaranteedUsers dead-ends.
The utility was computing the boundary of the `copy_value` with the
`end_borrow`s as users.  But there may not be any `end_borrow`s thanks
to dead-ends.  Instead, consider both guaranteed users and any
`end_borrow`s.

Fixes a miscompile in CSE.

rdar://158353230
2025-08-14 17:05:26 -07:00
Nate Chandler
1fe65b0e3d [NFC] Deleted two unused functions. 2025-08-14 16:15:43 -07:00
Anthony Latsis
bbd84429a0 Merge pull request #83400 from swiftlang/jepa-main
Address `llvm::PointerUnion::{is,get}` deprecations
2025-07-30 17:19:58 +01:00
Andrew Trick
648722eecd Merge pull request #83403 from atrick/fix-ossa-rauw
Fix OSSA RAUW utility for move_value that changes ownership.
2025-07-30 07:22:38 -07:00
Andrew Trick
0597fd927f Merge pull request #83390 from atrick/fix-trackifdead
Fix assertion in InstructionDeleter::trackIfDead.
2025-07-29 14:57:01 -07:00
Andrew Trick
05fcf5fbbc Fix OSSA RAUW utility for move_value that changes ownership.
CSE "looks through" ownership operations, which can lead to problematic substitutions. This fix cleans up owned operands even when the newly substituted value has no ownership.

For example:

    %0 = enum $Optional<Interface>, #Optional.none!enumelt
    %1 = move_value [lexical] %0
    %2 = enum $Optional<Interface>, #Optional.none!enumelt
    %3 = struct $EndpointCommon (%2)
    %4 = struct $EndpointCommon (%1)

CSE combines the two .none enums:

    %0 = enum $Optional<Interface>, #Optional.none!enumelt
    %2 = enum $Optional<Interface>, #Optional.none!enumelt

Then combines the two structs:

    %3 = struct $EndpointCommon (%2)
    %4 = struct $EndpointCommon (%1)

Leaving a dead move_value:

    %1 = move_value [lexical] %0

which is invalid OSSA. Now, when replacing the owned struct, we add destroys for its operands.

Fixes rdar://156431548 Error! Found a leaked owned value that was never consumed.
2025-07-29 11:18:10 -07:00
Anthony Latsis
fec049e5e4 Address llvm::PointerUnion::{is,get} deprecations
These were deprecated in
https://github.com/llvm/llvm-project/pull/122623.
2025-07-29 18:37:48 +01:00
Andrew Trick
c1e0a1d999 Fix assertion in InstructionDeleter::trackIfDead.
This assertion was triggering when deleting scope-ending operations whose
operand had been replaced with an undef:

   end_borrow undef

Related to rdar://156431548

This was triggered during simplify-cfg by after adding blocks to the worklist,
then later cleaning up dead instructions in the worklist blocks. I'm unable to
create a test case based on simplify-cfg because the assertion is completely
unrelated to the optimization that adds blocks to the worklist.
2025-07-29 00:22:46 -07:00
Andrew Trick
ab8091964b [NFC] add SinkAddressProjections::dump() 2025-07-29 00:10:59 -07:00
Erik Eckstein
319f49ad9f SwiftCompilerSources: move the Verifier to the SIL module 2025-07-28 14:19:11 +02:00
Erik Eckstein
e95283ba38 SwiftCompilerSources: make the testing infrastructure available in the SIL module
add `Test`, which is the SIL-equivalent of `FunctionTest`.
It's invocation closure gets a `TestContext` instead of a `FunctionContext`.

^ The commit message #2 will be skipped:

^ - test
2025-07-28 14:19:10 +02:00
Erik Eckstein
65c9828cb3 SwiftCompilerSources: move the Context protocols from the Optimizer to the SIL module
This allows to move many SIL APIs and utilities, which require a context, to the SIL module.

The SIL-part of SwiftPassInvocation is extracted into a base class SILContext which now lives in SIL.

Also: simplify the begin/end-pass functions of the SwiftPassInvocation.
2025-07-28 14:19:07 +02:00
Meghana Gupta
b90cd31d66 Fix optimization of checked_cast_addr_br to checked_cast_br 2025-07-23 17:03:13 -07:00
Allan Shortlidge
c6dad96492 Make LayoutPrespecialization a baseline feature instead of experimental.
Since LayoutPrespecialization has been enabled by default in all compiler
invocations for quite some time, it doesn't make sense for it to be treated as
experimental feature. Make it a baseline feature and remove all the
checks for it from the compiler.
2025-07-10 11:25:28 -07:00
Doug Gregor
1e87656e40 [Region analysis] Simplify logic for dynamic casts by making them less special
Extend and use SILIsolationInfo::getConformanceIsolation() for the dynamic
cast instructions.
2025-07-08 22:36:37 -07:00
Doug Gregor
0aa54a6f11 [Region isolation] Re-simplify handling of init_existential* instructions
Centralize the logic for figuring out the conformances for the various
init_existential* instructions in a SILIsolationInfo static method, and
always go through that when handling "assign" semantics. This way, we
can use CONSTANT_TRANSLATION again for these instructions, or a simpler
decision process between Assign and LookThrough.

The actually undoes a small change made earlier when we stopped looking
through `init_existential_value` instructions. Now we do when there are
no isolated conformances.
2025-07-08 22:36:37 -07:00
Doug Gregor
2f3ef58f16 [Region isolation] Factor SILIsolationInfo creation into static methods
Better match the style of SILIsolationInfo by moving the code for determining
SILIsolationInfo from conformances or dynamic casts to existentials into
static `getXYZ` methods on SILIsolationInfo.

Other than adding an assertion regarding disconnected regions, no
intended functionality change.
2025-07-08 22:36:37 -07:00
Doug Gregor
02c34bb830 [SE-0470] Track the potential introduction of isolated conformances in regions
When we introduce isolation due to a (potential) isolated conformance,
keep track of the protocol to which the conformance could be
introduced. Use this information for two reasons:

1. Downgrade the error to a warning in Swift < 7, because we are newly
diagnosing these
2. Add a note indicating where the isolated conformance could be introduced.
2025-07-08 11:18:30 -07:00
Michael Gottesman
677b897ff6 Merge pull request #82555 from gottesmm/pr-b4de2f5d58d852cd3e9e606101e1b0ff42ce6092
[nonisolated-nonsending] Make the AST not consider nonisolated(nonsending) to be an actor isolation crossing point.
2025-07-03 05:22:57 -07:00
Michael Gottesman
010fa39f31 [rbi] Use interned StringRefs for diagnostics instead of SmallString<64>.
This makes the code easier to write and also prevents any lifetime issues from a
diagnostic outliving the SmallString due to diagnostic transactions.
2025-07-02 16:50:24 -07:00
Michael Gottesman
14634b6847 [rbi] Begin tracking if a function argument is from a nonisolated(nonsending) parameter and adjust printing as appropriate.
Specifically in terms of printing, if NonisolatedNonsendingByDefault is enabled,
we print out things as nonisolated/task-isolated and @concurrent/@concurrent
task-isolated. If said feature is disabled, we print out things as
nonisolated(nonsending)/nonisolated(nonsending) task-isolated and
nonisolated/task-isolated. This ensures in the default case, diagnostics do not
change and we always print out things to match the expected meaning of
nonisolated depending on the mode.

I also updated the tests as appropriate/added some more tests/added to the
SendNonSendable education notes information about this.
2025-07-02 13:03:13 -07:00
Michael Gottesman
4433ab8d81 [rbi] Thread through a SILFunction into print routines so we can access LangOpts.Features so we can change how we print based off of NonisolatedNonsendingByDefault.
We do not actually use this information yet though... This is just to ease
review.
2025-07-02 12:13:52 -07:00
Michael Gottesman
4ce4fc4f95 [rbi] Wrap use ActorIsolation::printForDiagnostics with our own SILIsolationInfo::printActorIsolationForDiagnostics.
I am doing this so that I can change how we emit the diagnostics just for
SendNonSendable depending on if NonisolatedNonsendingByDefault is enabled
without touching the rest of the compiler.

This does not actually change any of the actual output though.
2025-07-02 12:13:50 -07:00
Michael Gottesman
c12c99fb73 [nonisolated-nonsending] Make the AST not consider nonisolated(nonsending) to be an actor isolation crossing point.
We were effectively working around this previously at the SIL level. This caused
us not to obey the semantics of the actual evolution proposal. As an example of
this, in the following, x should not be considered main actor isolated:

```swift
nonisolated(nonsending) func useValue<T>(_ t: T) async {}
@MainActor func test() async {
  let x = NS()
  await useValue(x)
  print(x)
}
```

we should just consider this to be a merge and since useValue does not have any
MainActor isolated parameters, x should not be main actor isolated and we should
not emit an error here.

I also fixed a separate issue where we were allowing for parameters of
nonisolated(nonsending) functions to be passed to @concurrent functions. We
cannot allow for this to happen since the nonisolated(nonsending) parameters
/could/ be actor isolated. Of course, we have lost that static information at
this point so we cannot allow for it. Given that we have the actual dynamic
actor isolation information, we could dynamically allow for the parameters to be
passed... but that is something that is speculative and is definitely outside of
the scope of this patch.

rdar://154139237
2025-07-02 12:13:29 -07:00
Erik Eckstein
606f7693d4 MandatoryPerformanceOptimizations: don't de-virtualize a generic class method call to specialized method
This results in wrong argument/return calling conventions.
First, the method call must be specialized. Only then the call can be de-virtualized.
Usually, it's done in this order anyway, because the `class_method` instruction is located before the `apply`.
But when inlining functions, the order (in the worklist) can be the other way round.

Fixes a compiler crash.
rdar://154631438
2025-07-01 09:44:47 +02:00
nate-chandler
17c1fbd5f4 Merge pull request #82313 from jamieQ/copy-prop-ossa-dead-ends-build-time-fix
[SILOptimizer]: slow OSSA lifetime canonicalization mitigation
2025-06-21 08:50:58 -07:00
Erik Eckstein
28dd6f7064 Optimizer: improve the SpecializationCloner
* add `cloneFunctionBody` without an `entryBlockArguments` argument
* remove the `swift::ClosureSpecializationCloner` from the bridging code and replace it with a more general `SpecializationCloner`
2025-06-20 08:15:02 +02:00
Erik Eckstein
d8e4e501f6 Optimizer: add some SIL modification APIs to Context
* `insertFunctionArgument`
* `BeginAccessInst.set(accessKind:)`
* `erase(function:)`
2025-06-20 08:15:01 +02:00
Erik Eckstein
de28cf04cc Optimizer: add Context. mangle(withBoxToStackPromotedArguments) 2025-06-20 08:15:01 +02:00
Erik Eckstein
bc7024edfe Optimizer: fix ModulePassContext.mangle(withDeadArguments:)
If mangled the wrong argument indices.
2025-06-20 08:15:00 +02:00