Commit Graph

830 Commits

Author SHA1 Message Date
Erik Eckstein
46035305aa Optimizer: improve simplification of alloc_stack
* Reimplement most of the logic in Swift as an Instruction simplification and remove the old code from SILCombine
* support more cases of existential archetype replacements:

For example:
```
  %0 = alloc_stack $any P
  %1 = init_existential_addr %0, $T
  use %1
```
is transformed to
```
  %0 = alloc_stack $T
  use %0
```

Also, if the alloc_stack is already an opened existential and the concrete type is known,
replace it as well:
```
  %0 = metatype $@thick T.Type
  %1 = init_existential_metatype %0, $@thick any P.Type
  %2 = open_existential_metatype %1 : $@thick any P.Type to $@thick (@opened("X", P) Self).Type
  ...
  %3 = alloc_stack $@opened("X", any P) Self
  use %3
```
is transformed to
```
  ...
  %3 = alloc_stack $T
  use %3
```
2025-03-07 15:59:34 +01:00
Erik Eckstein
5572c832e1 SILOptimizer: replace existential archetypes with concrete types in witness_method instructions 2025-03-07 15:59:34 +01:00
Erik Eckstein
71de3d90e0 Optimizer: replace existential archetypes with concrete types in apply instructions
If an apply uses an existential archetype (`@opened("...")`) and the concrete type is known, replace the existential archetype with the concrete type
  1. in the apply's substitution map
  2. in the arguments, e.g. by inserting address casts
For example:
```
  %5 = apply %1<@opend("...")>(%2) : <τ_0_0> (τ_0_0) -> ()
```
->
```
  %4 = unchecked_addr_cast %2 to $*ConcreteType
  %5 = apply %1<ConcreteType>(%4) : <τ_0_0> (τ_0_0) -> ()
```
2025-03-07 15:59:34 +01:00
Erik Eckstein
5016e35880 Optimizer: add two small utilities for instructions
* `func Instruction.dominatesInSameBlock(_ otherInst: Instruction) -> Bool`
* `var Instruction.concreteTypeOfDependentExistentialArchetype`
2025-03-07 15:59:34 +01:00
Erik Eckstein
810064b7dc Cleanup and additions to AST and SIL Type/CanonicalType
* factor out common methods of AST Type/CanonicalType into a `TypeProperties` protocol.
* add more APIs to AST Type/CanoncialType.
* move `MetatypeRepresentation` from SIL.Type to AST.Type and implement it with a swift enum.
* let `Builder.createMetatype` get a CanonicalType as instance type, because the instance type must not be a lowered type.
2025-03-07 15:59:33 +01:00
Erik Eckstein
35097b5a71 Optimizer: simplify unconditional_checked_cast to existential metatypes.
Replace `unconditional_checked_cast` to an existential metatype with an `init_existential_metatype`, it the source is a conforming type.
Note that init_existential_metatype is better than unconditional_checked_cast because it does not need to do any runtime casting.
2025-03-07 15:59:33 +01:00
Erik Eckstein
48db89031a SIL: be more tolerant when a user is deleted during use-list iteration.
Check if an operand's instruction has been deleted in `UseList.next()`.
This allows to delete an instruction, which has two uses of a value, during use-list iteration.
2025-03-07 15:59:32 +01:00
Meghana Gupta
87dcb65b4a Fix copy-to-borrow optimization's end_borrow insertion
allLifetimeEndingInstructions collects insertion points for end_borrows,
and can end up having duplicate entries in the case of enums with non payloaded cases.

Unique the entries so we don't end up with multiple end_borrows

Fixes rdar://146212574
2025-03-06 11:53:38 -08:00
Andrew Trick
b3f401d346 LifetimeDependenceScopeFixup: handle indirect yields & fix bugs
Handle coroutines that yield an address. Fix bugs involving extension of
multiple nested scopes that depend on multiple coroutine operands.
2025-03-05 02:12:21 -08:00
Andrew Trick
fa64a362a2 Add -Xfrontend -enable-address-dependencies
Temporary option to bootstrap '@'_addressable enforcement.

Once all the SILGen cases are handled, we won't need this option.
2025-03-03 16:21:48 -08:00
Andrew Trick
1b51aa8829 LifetimeDependenceScopeFixup: extend store_borrow scopes
This is require to handle '@'_addressable arguments on the caller side.
2025-03-03 16:21:48 -08:00
Andrew Trick
3019c843be LifetimeDependence: allow dependence on the store_borrow address
Previously, the dependence was on the stored value, but that is incorrect for
'@'_addressable parameters.
2025-03-03 11:56:37 -08:00
Andrew Trick
af878cc9af LifetimeDependenceInsertion: support '@'_addressable parameters 2025-03-03 11:56:37 -08:00
Andrew Trick
bc6200e592 SwiftCompilerSources: bridge '@'_addressable dependencies 2025-03-03 11:56:37 -08:00
Andrew Trick
6e75813a9b OwnershipLiveness fix: support visitInnerUses
DestroyHoisting is using this utility. This requires complete liveness. But we
can't rely on complete liveness because complete lifetimes is not
enabled. Instead, we use a visitInnerUses flag to try to ignore borrow
scopes. That flag was never properly implemented. Make an attempt here.
2025-02-26 02:54:37 -08:00
Andrew Trick
2542515b69 OwnershipLiveness.swift fix: don't ignore trivial types
interiorPointerUse is dealing with addresses, so the memory still needs to be
alive regardless of the type.
2025-02-26 02:33:13 -08:00
Andrew Trick
e280c52825 Fix DestroyHoisting: don't ignore pointer escapes.
A pointer escape means the liveness is incomplete. Don't hoist destroys with
incomplete liveness.
2025-02-26 02:13:05 -08:00
Andrew Trick
747b1ac28a Fix OwnershipLivenes.swift visitInnerBorrowUses
Always visit the use even if it is the beginning of an inner borrow. This
provides a "better" liveness result in the case of dead borrows and gives the
client a chance to see/intercept all uses.
2025-02-26 01:42:19 -08:00
Andrew Trick
0f728f0514 Fix BorrowingInstruction.visitEndBorrows to handle borrowed-from
For borrowed-from of a reborrow, the value is the block argument. So we need to
look through the borrowed-from user.
2025-02-26 01:40:42 -08:00
Andrew Trick
353bef7904 Fix DestroyHoisting to visit all interior uses.
Set the visitInnerUses flag. This is only a quick, partial fix.

InteriorUseWalker does not generate complete liveness for two reasons

1. pointer escapes. The client must always check for escapes before assuming
complete liveness.

2. dead end blocks. Until we have complete OSSA lifetimes, the algorithm for
handling nested borrows is incorrect. The visitInnerUses flag works around this
problem, but it isn't well tested and I'm not sure it's properly records escapes yet.
2025-02-26 00:40:12 -08:00
Andrew Trick
38137c5383 OwnershipLiveness.swift: add comments
and rename visitOwnedDependentUses
2025-02-26 00:39:25 -08:00
Andrew Trick
406afc7202 SwiftCompilerSources: Fix InteriorUseWalker with visitInnerUses.
Add support to all kinds of borrowing instructions so we visit all their inner uses.
2025-02-26 00:38:18 -08:00
Andrew Trick
8decfa4910 Add BorrowingInstruction.innerValue 2025-02-26 00:37:20 -08:00
Andrew Trick
083ab98818 Simplify OwnershipLiveness.swift, remove reborrowingUse.
Remove complexity around reborrows. They no longer need special treatment.
2025-02-25 23:36:14 -08:00
Andrew Trick
b854ab18c1 OwnershipUseVisitor.visitInnerBorrowUses: support dependent values
Add liveness support for dependent values: borrowed-from & mark_dependence so
they aren't reported as unknown uses.
2025-02-25 23:08:55 -08:00
Andrew Trick
907097421b Add BorrowingInstruction.dependentValue and .scopedValue
This consolidates the rules for borrow scopes so we can simplify interior liveness.
2025-02-25 23:08:55 -08:00
Andrew Trick
5864004c4e SwiftCompilerSources: remove adjacent phis from InteriorUseWalker.
The extra complexity for traversing phis is not needed now that it handles
borrowed-from instructions. Remove the redundant logic because it complicates
the liveness algorithm and generates confusing results.
2025-02-25 23:08:54 -08:00
Andrew Trick
5a1a487d14 Fix InteriorUseWalker to handle dependent lifetimes as inner scopes
Inner scopes must all be reported because the walker assumes they are
complete. It is up to the client to either complete them or recursively follow
them.
2025-02-25 23:08:54 -08:00
Andrew Trick
7f6962adff Fix OwnershipUseVisitor.dependentUse()
Check if the forwarded value is trivial, not the base value. Presumably, we
won't call this visitor at all if the base is trivial.

Record a dependent non-Escapable values as a pointer-escape. InteriorUseWalker
does not handle lifetime dependencies. That requires
LifetimeDependenceDefUseWalker.
2025-02-25 23:08:54 -08:00
Andrew Trick
f1792d80b3 Fix BorrowingOperand.visitScopeEndingUses
Only return false if the visitor returns false. Clients were ignoring the
result.

If the BorrowingOperand does not create a borrow scope, call visitUnknownUse
instead.

Until we have complete lifetimes, to avoid breaking code that cannot handle dead
defs, consider a dead borrow scope to be an unknown use.
2025-02-25 23:08:54 -08:00
Andrew Trick
a4a675ee00 Remove adjacent phi handling from InteriorUseWalker.
At least the Swift utilities should rely on borrowed-from.
2025-02-25 23:08:54 -08:00
Andrew Trick
6188d29026 Handle borrowed-from in OwnershipUseVisitor.
If it is not a reborrow, then it produces a dependent value, just like
mark_dependence.
2025-02-25 23:08:54 -08:00
Andrew Trick
e22541544c Remove unused computeInterorLiveness API.
This encourages the client to check whether InteriorLivenessResult is valid or
escaping before using the instruction range.
2025-02-25 23:08:54 -08:00
Andrew Trick
fda53929c2 Add support for borrowed-from to BorrowingInstruction.
All instructions with a "Borrow" operand ownership must be valid
BorrowingInstructions.
2025-02-25 23:08:54 -08:00
Andrew Trick
6c99017588 Minor comment cleanup and code formatting.
Extracted from the functional changes for clarity.
2025-02-25 23:08:53 -08:00
Andrew Trick
75e84f1e97 Rename InteriorLiveness methods for clarity.
It was too easy to confuse the "inner" vs. "outer" value.

Use less ambigous names: visitAllUses vs visitInnerScopeUses
2025-02-25 23:08:53 -08:00
Erik Eckstein
57a236e671 InitializeStaticGlobals: support statically initializing globals which are or contain inline arrays
For example:

```
struct S {
  static let slab: Slab = [1, 2, 3, 4]
}
```

rdar://143005996
2025-02-12 22:37:49 +01:00
eeckstein
dff88f968b Merge pull request #79317 from eeckstein/remove-alloc-vector
Remove the experimental FixedArray
2025-02-12 17:03:06 +01:00
eeckstein
b6639e1782 Merge pull request #79314 from eeckstein/fix-simplify-keypath
SimplifyKeyPath: insert the correct destroy operation for an operand of a removed keypath
2025-02-12 15:18:39 +01:00
Erik Eckstein
e0b4f71af6 SIL: remove the alloc_vector instruction
It's not needed anymore, because the "FixedArray" experimental feature is replaced by inline-arrays.
2025-02-12 10:51:14 +01:00
Erik Eckstein
6407f9a0bd remove the allocVector builtin
It's not needed anymore, because the "FixedArray" experimental feature is replaced by inline-arrays.
2025-02-12 10:51:14 +01:00
Erik Eckstein
5b93eb31bf Optimizer: remove the AllocVectorLowering pass
It's not needed anymore, because the "FixedArray" experimental feature is replaced by inline-arrays.
2025-02-12 10:51:14 +01:00
Erik Eckstein
3f95ce9645 Optimizer: fix spelling of the Simplifiable protocol
Rename `Simplifyable` -> `Simplifiable`

NFC
2025-02-12 09:01:11 +01:00
Erik Eckstein
2962474b58 SimplifyKeyPath: insert the correct destroy operation for an operand of a removed keypath
If the operand is an address, we need to use `destroy_addr` and not `destroy_value`.

Fixes a compiler crash.
rdar://144662171
2025-02-12 08:35:23 +01:00
eeckstein
aa0833b0b3 Merge pull request #79110 from eeckstein/verify_mark_dependence
SIL: Fix memory behavior of mark_dependence
2025-02-11 06:39:43 +01:00
Andrew Trick
c2842e8e19 LifetimeDependenceInsertion: remove a bailout on ~Copyable
Needed to diagnose MutableSpan and OutputSpan.

For now, simply remove the bailout and TODO. The next change will introduce more
logic to force a diagnostic error in rare cases that can't be handled completely.

Fixes rdar://143584461 (Extended exclusive borrow issues with
MutableSpan and OutputSpan)
2025-02-10 09:13:27 -08:00
Andrew Trick
fa3ebb5c1e LifetimeDependence.Scope add global variable support.
This fixes functions that return @lifetime(immortal).
2025-02-10 09:11:22 -08:00
Andrew Trick
39bae0bb58 LifetimeDependenceDiagnostics: immortal dependence on global 'let' 2025-02-10 09:11:22 -08:00
Andrew Trick
c3de120ca5 LifetimeDependence: simplify and fix multiple bugs.
Functional changes:

Improved modeling of dependence on local variable scopes.

For nested modify->read accesses, only extend the read accesses.

Avoid making a read access dependent on an inout argument.
The following needs to be an error to prevent span storage from being modified:

  @lifetime(owner)
  foo(owner: inout Owner) -> Span {
    owner.span
  }

Improve usability of borrowing trivial values (UnsafePointer). Allow:

  let span = Span(buffer.baseAddress)

Ignore access scopes for trivial values.

Structural changes:

Delete the LifetimeDependenceUseDefWalker.

Encapsulate all logic for variable introducers within the LifetimeDependenceInsertion pass. Once mark_dependence instructions are inserted, no subsequent pass needs to think about the "root" of a dependence.

Fixes: rdar://142451725 (Escape analysis fails with mutations)
2025-02-10 09:11:22 -08:00
Andrew Trick
eae2f06dc7 Extend and improve AccessBase.findSingleInitializer
Return an Initializer rather than a tuple. This makes it easier and more robust
for clients to track dependencies on initialized memory.
2025-02-10 09:11:22 -08:00