Commit Graph

2099 Commits

Author SHA1 Message Date
Erik Eckstein
bb3b0b2859 Optimizer: remove the old CapturePropagation pass 2025-09-04 08:15:47 +02:00
Erik Eckstein
efa9f9ebc0 Optimizer: rewrite and improve the ConstantCapturePropagation pass
(old name: CapturePropagation)

The pass is now rewritten in swift which makes the code smaller and simpler.
Compared to the old pass it has two improvements:

* It can constant propagate whole structs (and not only builtin literals). This is important for propagating "real" Swift constants which have a struct type of e.g. `Int`.
* It constant propagates keypaths even if there are other non-constant closure captures which are not propagated. This is something the old pass didn't do.

rdar://151185177
2025-09-04 08:15:46 +02: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
231042b9a8 SIL: some Cloner cleanups and improvements
* move some Cloner utilities from ContextCommon.swift directly into Cloner.swift
* add an `cloneRecursively` overload which doesn't require the `customGetCloned` closure argument
* some small cleanups
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
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
391ad21583 [rbi] Make all PartitionOpErrors noncopyable types.
I am going to be adding support to passes for emitting IsolationHistory behind a
flag. As part of this, we need to store the state of the partition that created
the error when the error is emitted. A partition stores heap memory so it makes
sense to make these types noncopyable types so we just move the heap memory
rather than copying it all over the place.
2025-08-29 15:18:55 -07: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
85aeb41bd0 Remove old LICM pass. 2025-08-28 22:57:46 +01:00
Jakub Florek
07ac8b3478 Add new loop invariant code motion. 2025-08-28 21:00:33 +01:00
Jakub Florek
3514b2b9df Bridge array semantics call and loop tree 2025-08-28 21:00:09 +01:00
Jakub Florek
bc86fe5a38 Hoist ArrayCallKind to a separate file 2025-08-28 20:50:33 +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
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
Nate Chandler
1fe65b0e3d [NFC] Deleted two unused functions. 2025-08-14 16:15:43 -07:00
Michael Gottesman
18b1fbce7a [sns] Refactor duplicate code into a helper. NFC.
The specific code path is the code used to emit errors if we assign or merge
into a sending result. I just left the code in tree in the short term to prevent
cherry-picking issues and since there wasn't a strong reason to do it at the
time. Now that we have more freedom, lets clean up this code!
2025-08-13 17:02:49 -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
0597fd927f Merge pull request #83390 from atrick/fix-trackifdead
Fix assertion in InstructionDeleter::trackIfDead.
2025-07-29 14:57:01 -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
ab8091964b [NFC] add SinkAddressProjections::dump() 2025-07-29 00:10:59 -07:00
Erik Eckstein
b38490b2e2 SwiftCompilerSources: move PhiUpdater.swift from the Optimizer to the SIL module 2025-07-28 14:19:11 +02: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
Anthony Latsis
90f9fce339 Merge pull request #82665 from swiftlang/jepa4
Bridging: Bridge some basic classes like `swift::SourceLoc` directly
2025-07-16 08:27:12 +01:00
Michael Gottesman
73e34f020b [rbi] Teach SendNonSendable how to more aggressively suppress sending errors around obfuscated Sendable functions
Specifically the type checker to work around interface types not having
isolation introduces casts into the AST that enrich the AST with isolation
information. Part of that information is Sendable. This means that we can
sometimes lose due to conversions that a function is actually Sendable. To work
around this, we today suppress those errors when they are emitted (post 6.2, we
should just change their classification as being Sendable... but I don't want to
make that change now).

This change just makes the pattern matching for these conversions handle more
cases so that transfernonsendable_closureliterals_isolationinference.swift now
passes.
2025-07-10 11:15:00 -07:00
Anthony Latsis
f131fece3f [NFC] Bridging: Rework include caveats 2025-07-10 17:58:13 +01:00
Anthony Latsis
b803861257 Bridging: Rename USED_IN_CPP_SOURCE and define it in Basic/SwiftBridging.h 2025-07-10 17:58:13 +01: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
nate-chandler
d6b5c4fb99 Merge pull request #82798 from eeckstein/fix-let-property-lowering
LetPropertyLowering: remove redundant phis after ssa-update
2025-07-08 18:07:08 -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
Erik Eckstein
1a6ad0c512 Optimizer: add var insertedPhis in SSAUpdater 2025-07-04 11:10:27 +02: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
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
6714a72256 Optimizer: re-implement and improve the AllocBoxToStack pass
This pass replaces `alloc_box` with `alloc_stack` if the box is not escaping.
The original implementation had some limitations. It could not handle cases of local functions which are called multiple times or even recursively, e.g.

```
public func foo() -> Int {
  var i = 1

  func localFunction() { i += 1 }

  localFunction()
  localFunction()
  return i
}

```

The new implementation (done in Swift) fixes this problem with a new algorithm.
It's not only more powerful, but also simpler: the new pass has less than half lines of code than the old pass.

The pass is invoked in the mandatory pipeline and later in the optimizer pipeline.
The new implementation provides a module-pass for the mandatory pipeline (whereas the "regular" pass is a function pass).
This is required because the mandatory pass needs to remove originals of specialized closures, which cannot be done from a function-pass.
In the old implementation this was done with a hack by adding a semantic attribute and deleting the function later in the pipeline.

I still kept the sources of the old pass for being able to bootstrap the compiler without a host compiler.

rdar://142756547
2025-06-20 08:15:04 +02:00
Erik Eckstein
b256bab988 fix BridgedPassContext::addFunctionToPassManagerWorklist
A new function must not be added to the pass-manager's worklist if done from a module pass.
2025-06-20 08:15:03 +02: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