Commit Graph

1196 Commits

Author SHA1 Message Date
Arnold Schwaighofer
0c882d42ce Merge pull request #85625 from aschwaighofer/wip_embedded_cast_tuples
[embedded] Allow casting to tuples and tighten the check which existentials we support in embedded with existentials
2025-12-01 08:27:43 -08:00
eeckstein
9304ce951c Merge pull request #85707 from eeckstein/embedded-witness-method-specialization
embedded: change the function representation of directly called witness methods
2025-12-01 09:36:45 +01:00
eeckstein
46c69e40c1 Merge pull request #85533 from eeckstein/fix-access-simplification
SILOptimizer: don't remove empty conflicting access scopes
2025-12-01 09:35:48 +01:00
eeckstein
c8b5df5129 Merge pull request #85647 from eeckstein/fix-embedded-cpp-classes
embedded: don't try to specialize vtables of C++ imported reference-counted classes
2025-12-01 09:35:19 +01:00
Erik Eckstein
d7b75b6819 Optimizer: register explicit-copy instruction simplifications for SILCombine
Usually `explicit_copy_addr` and `explicit_copy_value` don't survive until the first SILCombine pass run anyway.
But if they do, the simplifications need to be registered, otherwise SILCombine will complain.
2025-11-27 19:40:31 +01:00
Erik Eckstein
64dd574bea embedded: change the function representation of directly called witness methods
This is needed in Embedded Swift because the `witness_method` convention requires passing the witness table to the callee.
However, the witness table is not necessarily available.
A witness table is only generated if an existential value of a protocol is created.

This is a rare situation because only witness thunks have `witness_method` convention and those thunks are created as "transparent" functions, which means they are always inlined (after de-virtualization of a witness method call).
However, inlining - even of transparent functions - can fail for some reasons.

This change adds a new EmbeddedWitnessCallSpecialization pass:
If a function with `witness_method` convention is directly called, the function is specialized by changing the convention to `method` and the call is replaced by a call to the specialized function:

```
  %1 = function_ref @callee : $@convention(witness_method: P) (@guaranteed C) -> ()
  %2 = apply %1(%0) : $@convention(witness_method: P) (@guaranteed C) -> ()
...
sil [ossa] @callee : $@convention(witness_method: P) (@guaranteed C) -> () {
  ...
}
```
->
```
  %1 = function_ref @$e6calleeTfr9 : $@convention(method) (@guaranteed C) -> ()
  %2 = apply %1(%0) : $@convention(method) (@guaranteed C) -> ()
...
// specialized callee
sil shared [ossa] @$e6calleeTfr9 : $@convention(method) (@guaranteed C) -> () {
  ...
}
```

Fixes a compiler crash
rdar://165184147
2025-11-26 16:23:47 +01:00
Erik Eckstein
78cb4ca197 Optimizer: extract replacing an apply into a utility function ApplySite.replace(withCallTo:) 2025-11-26 16:23:47 +01:00
Erik Eckstein
17ca4d9787 Optimizer: add FunctionPassContext.mangle(withChangedRepresentation original: Function) 2025-11-26 16:23:47 +01:00
Erik Eckstein
ab2345a2ed FunctionPassContext: support setting arbitrary function type representations when creating specialized functions 2025-11-26 16:23:47 +01:00
Erik Eckstein
9a124742b0 Optimizer: add the DeadAccessScopeElimination optimization pass
It eliminates dead access scopes if they are not conflicting with other scopes.

Removes:
```
  %2 = begin_access [modify] [dynamic] %1
  ...                                       // no uses of %2
  end_access %2
```

However, dead _conflicting_ access scopes are not removed.
If a conflicting scope becomes dead because an optimization e.g. removed a load, it is still important to get an access violation at runtime.
Even a propagated value of a redundant load from a conflicting scope is undefined.

```
  %2 = begin_access [modify] [dynamic] %1
  store %x to %2
  %3 = begin_access [read] [dynamic] %1    // conflicting with %2!
  %y = load %3
  end_access %3
  end_access %2
  use(%y)
```
After redundant-load-elimination:
```
  %2 = begin_access [modify] [dynamic] %1
  store %x to %2
  %3 = begin_access [read] [dynamic] %1    // now dead, but still conflicting with %2
  end_access %3
  end_access %2
  use(%x)                                  // propagated from the store, but undefined here!
```
In this case the scope `%3` is not removed because it's important to get an access violation error at runtime before the undefined value `%x` is used.

This pass considers potential conflicting access scopes in called functions.
But it does not consider potential conflicting access in callers (because it can't!).
However, optimizations, like redundant-load-elimination, can only do such transformations if the outer access scope is within the function, e.g.

```
bb0(%0 : $*T):     // an inout from a conflicting scope in the caller
  store %x to %0
  %3 = begin_access [read] [dynamic] %1
  %y = load %3     // cannot be propagated because it cannot be proved that %1 is the same address as %0
  end_access %3
```

All those checks are only done for dynamic access scopes, because they matter for runtime exclusivity checking.
Dead static scopes are removed unconditionally.
2025-11-24 14:49:45 +01:00
Erik Eckstein
fa3bfa3b10 embedded: don't try to specialize vtables of C++ imported reference-counted classes
Fixes a false compiler error

rdar://165209061
2025-11-21 16:33:49 +01:00
Arnold Schwaighofer
1b6da50ed9 Merge pull request #85602 from aschwaighofer/wip_embedded_exit_cast
[embedded] Implement swift_dynamicCast suport for casts from existential to concrete type
2025-11-20 21:01:41 -05:00
Arnold Schwaighofer
8beaad60bd [embedded] Allow casting to tuples 2025-11-20 10:03:39 -08:00
Arnold Schwaighofer
0197784625 [embedded] Tighten the check which existentials we support in embedded with existentials 2025-11-20 07:55:51 -08:00
Aidan Hall
2c9013b2a4 Merge pull request #84648 from swiftlang/users/kovdan01/ast-bridges-for-autodiff-closure-spec
Bridging: Implement bridges required for ongoing AutoDiff changes
2025-11-20 14:45:28 +00:00
Arnold Schwaighofer
3cff05d540 [embedded] Implement swift_dynamicCast suport for casts from existential to concrete type 2025-11-19 14:41:37 -08:00
Erik Eckstein
50c299e0bf LoopInvariantCodeMotion: don't reuse existing instructions in the loop pre-header
This is wrong for hoisted load instructions because we don't check for aliasing in the pre-header.
And for side-effect-free instructions it's not really necessary, because that can cleanup CSE afterwards.

Fixes a miscompile
rdar://164034503
2025-11-18 21:23:13 +01:00
Daniil Kovalev
a172134162 Address review comments 2025-11-18 01:46:49 +03:00
Yuta Saito
8748213d52 Merge pull request #85524 from kateinoigakukun/yt/fix-non-reg2mem-rle-crash 2025-11-16 23:10:20 +09:00
Yuta Saito
e259a257e6 RedundantLoadElim: Fix invalid destructure_struct emission without aggressive reg2mem
The `shouldExpand` in `OptUtils.swift` was incorrectly returning `true`
unconditionally when `useAggressiveReg2MemForCodeSize` was disabled. The
expansion might be invalid for types with addr-only types and structs
with deinit, but we didn't check them before. This could lead to invalid
`destructure_struct` instructions without `drop_deinit` being emitted.
2025-11-15 19:22:33 +00:00
Meghana Gupta
827c30f13c Merge pull request #85482 from meg-gupta/reduceendcowmutation
Avoid inserting end_cow_mutation_addr in some common cases
2025-11-13 19:07:45 -08:00
Meghana Gupta
1dc03fea25 Add early exit for Escapable and copyable types from mayHaveMutableSpan 2025-11-13 10:36:34 -08:00
Meghana Gupta
5e88f38152 Avoid inserting end_cow_mutation_addr in some common cases 2025-11-13 09:58:08 -08:00
Adrian Prantl
11356acd44 Merge pull request #85397 from adrian-prantl/163167975
[SILOptimzer] Fix a crash caused by SILCombine mishandling inlined variables
2025-11-10 18:41:07 -08:00
Meghana Gupta
e2123e1b3b Merge pull request #85362 from meg-gupta/moreborrow
Add SIL verification for borrow and mutate accessors and some other minor fixes
2025-11-10 09:04:28 -08:00
Adrian Prantl
99cf35cdce [SILOptimzer] Fix a crash caused by SILCombine mishandling inlined variables
This showed up on and off again on the source-compatibility testsuite project hummingbird.

The gist of the problem is that transformations may not rewrite the
type of an inlined instance of a variable without also createing a
deep copy of the inlined function with a different name (and e.g., a
specialization suffix). Otherwise the modified inlined variable will
cause an inconsistency when later compiler passes try to create the
abstract declaration of that inlined function as there would be
conflicting declarations for that variable.

Since SILDebugScope isn't yet available in the SwiftCompilerSources
this fix just drop these variables, but it would be absolutely
possible to preserve them by using the same mechanism that SILCloner
uses to create a deep copy of the inlined function scopes.

rdar://163167975
2025-11-07 17:06:33 -08:00
Erik Eckstein
62786b01e2 Optimizer: add the mandatory destroy hoisting pass
It hoists `destroy_value` instructions for non-lexical values.

```
  %1 = some_ownedValue
  ...
  last_use(%1)
  ... // other instructions
  destroy_value %1
```
->
```
  %1 = some_ownedValue
  ...
  last_use(%1)
  destroy_value %1    // <- moved after the last use
  ... // other instructions
```

In contrast to non-mandatory optimization passes, this is the only pass which hoists destroys over deinit-barriers.
This ensures consistent behavior in -Onone and optimized builds.
2025-11-06 21:00:44 +01:00
Erik Eckstein
eef769c83a Optimizer: when checking for lexical lifetimes look through all ownership-transitioning instructions
except `copy_value`
2025-11-06 20:26:20 +01:00
Meghana Gupta
a0eb58fa07 Handle return_borrow in a few more places in SwiftCompilerSources 2025-11-06 10:55:31 -08:00
Andrew Trick
382529c73b Merge pull request #85232 from atrick/rdar159793739-lifedep-cast
LifetimeDependenceDiagnostics: handle dynamic casting of Span<T>
2025-10-31 08:35:36 -07:00
Andrew Trick
5943d40edf LifetimeDependenceDiagnostics: handle dynamic casting of Span<T>
Add a special case for checked_cast_addr_br instruction. If it conformed to
SourceDestAddrInstruction, then the diagnostics would already have handled it
naturally, but the instruction's conditional semantics are strange enough that
such a conformance might confuse other passes.

rdar://159793739 (Using `as?` with non-escapable types emits faulty lifetime
diagnostics)
2025-10-30 23:28:25 -07:00
Andrew Trick
e11f7f1f11 LifetimeDependenceDiagnostics: diagnostic error on unknown uses
The common def-use walkers should not return .abortWalk without making a
diagnostic callback.
2025-10-30 23:28:25 -07:00
Aidan Hall
8632e58825 Create Pack Specialisation pass 2025-10-30 14:28:16 +00:00
Aidan Hall
c7af4c584e Bridging: APIs for PackSpecialization pass 2025-10-26 13:44:34 +00:00
Andrew Trick
5494a24899 Merge pull request #85076 from atrick/lifedep-reassign
Lifetimes: handle MutableSpan reassignment and 'inout' arguments
2025-10-24 09:55:34 -07:00
Andrew Trick
305d75187a LocalVariableUtils: precisely handle function live-out
Only record an outgoingArgument access when the current allocation is an
outgoing argument and the function exiting instruction is ReturnInst.

This avoids invalid SIL where we attempt to extend end_access up to an `unwind` but
fail to actually materialize that end_access.
2025-10-23 23:34:26 -07:00
Andrew Trick
62b04caaa7 LocalVariableUtils add non-escaping closure capture support
Don't always consider an inout_aliasable argument to have
escaped. AccessEnforcementSelection has already done that analysis and left
begin_access [dynamic] artifacts if the argument has escaped in any meaningful
way. Use that information to

Essential for supporting autoclosures that call mutating methods on span-like
things. Such as UTF8Span.UnicodeScalarIterator.skipForward():

e.g. while numSkipped < n && skipForward() != 0 { ... }
2025-10-23 23:34:25 -07:00
Andrew Trick
8200a871c9 Fix LifetimeDependenceDefUseWalker to follow inout dependence
Fixes rdar://157796728 ([nonescapable] [miscompile] No diagnostic error when an
inout MutableSpan is reassigned to a different lifetime source)
2025-10-23 23:34:25 -07:00
Andrew Trick
77ee27a0e7 [NFC] LocalVariableAccessInfo.description 2025-10-23 23:34:25 -07:00
Andrew Trick
de34abe3e5 Fix LocalVariableReachableAccess to handle potential reassignment.
Define LocalAccessInfo._isFullyAssigned to mean that the access does not read
the incoming value. Then treat any assignment that isn't full as a potential read.
2025-10-23 23:34:25 -07:00
Andrew Trick
6e0eeb00e3 Fix LifetimeDependenceDefUseWalker for @inout reassignment 2025-10-23 23:34:24 -07:00
Andrew Trick
ff4d053a44 [NFC] LifetimeDependenceDefUseWalker.inoutDependence entry point
Handle cases where there's no relevant operand.
2025-10-23 23:34:24 -07:00
Andrew Trick
a0f0c108b0 [NFC] Add a new entry point for DiagnoseDependence.reportError
Allow diagnosing values that have no relevant users. Such as an @inout argument.
2025-10-23 23:34:24 -07:00
Andrew Trick
ce153a85ea [NFC] extend AddressInitializationWalker to report address reads 2025-10-23 23:34:24 -07:00
Andrew Trick
432e31612a [NFC] Extend AddressInitializationWalker.findSingleInitializer
Handle applies that reassign the lifetime of their operand vs. the value of
their operand.
2025-10-23 23:34:24 -07:00
Andrew Trick
3bb3e4d077 [NFC] Add ApplySite.parameterDependence(target:source:) 2025-10-23 23:34:23 -07:00
Erik Eckstein
6988b03c13 ClosureSpecialization: don't crash for recursive functions
Don't support self-recursive functions because that would result in mapping troubles when cloning.
2025-10-24 06:11:53 +02:00
Erik Eckstein
53f424e5f0 TempRValueOptimization: respect deinit-barriers when hoisting destroys
Fixes a mis-compile which causes a deinit to be called earlier than expected.

rdar://162299994
2025-10-23 20:45:11 +02:00
Erik Eckstein
309b93ca15 Optimizer: add the isBarrierForDestroy utility
It checks if a destroy of a type must not be moved across an instruction.
2025-10-23 20:45:11 +02:00
eeckstein
0e4dc2fe2e Merge pull request #85068 from eeckstein/fix-licm
LoopInvariantCodeMotion: don't extend "read" access scopes over memory writes to the same address
2025-10-23 07:25:38 +02:00