Commit Graph

972 Commits

Author SHA1 Message Date
Michael Gottesman
1f9e30276a [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 17:25:01 -07:00
Michael Gottesman
f920aba2f9 [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.

(cherry picked from commit 010fa39f31)
2025-07-09 12:25:06 -07:00
Michael Gottesman
85fafa5b1e [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.

(cherry picked from commit 14634b6847)
2025-07-09 12:25:03 -07:00
Michael Gottesman
ca8cdc1fd7 [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.

(cherry picked from commit 4433ab8d81)
2025-07-09 12:24:17 -07:00
Michael Gottesman
0ec2527bdc [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.

(cherry picked from commit 4ce4fc4f95)
2025-07-09 12:24:17 -07:00
Doug Gregor
1d86ed5f15 [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 17:33:33 -07:00
Doug Gregor
066fa0b828 [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 17:33:33 -07:00
Doug Gregor
22ca6b98e5 [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 17:33:33 -07:00
Doug Gregor
6637960bdc [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.

(cherry picked from commit 02c34bb830)
2025-07-08 17:32:06 -07:00
Erik Eckstein
849a5e9082 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-03 13:21:27 +02: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
Michael Gottesman
da57f9665c Merge pull request #80953 from gottesmm/release/6.2-135459885
[6.2][sil-isolation-info] When determining isolation of a function arg, use its VarDecl.
2025-04-24 10:14:41 -07:00
Nate Chandler
f2a00f0fcb [OSSACanOwned] Don't dead-end extend if consumed.
When the utility is used by the ConsumeOperatorCopyableValuesChecker,
the checker guarantees that the lifetime can end at the consumes, that
there are no uses after those consumes.  In that circumstance, the
utility maintains liveness to those consumes and as far as possible
without introducing a copy everywhere else.

The lack of complete lifetimes has forced the utility to extend liveness
of values to dead-ends.  That extension, however, is in tension with the
use that the checker is putting the utility to.  If there is a dead-end
after a consume, liveness must not be maintained to that dead-end.

rdar://147586673
2025-04-22 16:49:42 -07:00
Nate Chandler
19242dffde [NFC] OSSACanOwned: Extracted predicate. 2025-04-22 16:49:42 -07:00
Nate Chandler
6b977dc43b [NFC] OSSACanOwned: Renamed field. 2025-04-22 16:49:41 -07:00
Michael Gottesman
636aa31192 [sil-isolation-info] When determining isolation of a function arg, use its VarDecl.
Otherwise, we can be inconsistent with isolations returned by other parts of the
code. Previously we were just treating it always as self + nom decl, which is
clearly wrong if a type is not self (e.x.: if it is an isolated parameter).

rdar://135459885
(cherry picked from commit 0ece31e4f6)
2025-04-21 10:57:48 -07:00
Michael Gottesman
46926720a9 [rbi] Make it so that we correctly do not error on uses of Sendable values that are projected from non-Sendable bases.
Specifically, we only do this if the base is a let or if it is a var but not
captured by reference.

rdar://149019222
(cherry picked from commit 23b6937cbc)
2025-04-15 14:58:04 -07:00
Michael Gottesman
a93e994593 [rbi] Add the ability to add flags to PartitionOp.
I am doing this so I can mark requires as being on a mutable non-Sendable base
from a Sendable value.

I also took this as an opportunity to compress the size of PartitionOp to be 24
bytes instead of 40 bytes.

(cherry picked from commit a045c9880a)
2025-04-15 14:57:57 -07:00
Michael Gottesman
ed98efa08a [rbi] Refactor getUnderlyingTrackedValue so that for addresses we return both a value and a base in certain situations.
Previously, when we saw any Sendable type and attempted to look up an underlying
tracked value, we just bailed. This caused an issue in situations like the
following where we need to emit an error:

```swift
func test() {
  var x = 5
  Task.detached { x += 1 }
  print(x)
}
```

The problem with the above example is that despite value in x being Sendable,
'x' is actually in a non-Sendable box. We are passing that non-Sendable box into
the detached task by reference causing a race against the read from the
non-Sendable box later in the function. In SE-0414, this is explicitly banned in
the section called "Accessing Sendable fields of non-Sendable types after weak
transferring". In this example, the box is the non-Sendable type and the value
stored in the box is the Sendable field.

To properly represent this, we need to change how the underlying object part of
our layering returns underlying objects and vends TrackableValues to the actual
analysis for addresses. NOTE: We leave the current behavior alone for SIL
objects.

By doing this, in situations like the above, despite have a Sendable value (the
integer), we are able to ensure that we require that the non-Sendable box
containing the integer is not used after we have sent it into the other Task
despite us not actually using the box directly.

Below I describe the representation change in more detail and describe the
various cases here. In this commit, I only change the representation and do not
actually use the new base information. I do that in the next commit to make this
change easier for others to read and review. I made sure that change was NFC by
leaving RegionAnalysis.cpp:727 returning an optional.none if the value found was
a Sendable value.

----

The way we modify the representation is that we instead of just returning a
single TrackedValue return a pair of tracked values, one for the base and one
for the "value". We return this pair in what is labeled a
"TrackableValueLookupResult":

```c++
struct TrackableValueLookupResult {
  TrackableValue value;

  std::optional<TrackableValue> base;

  TrackableValueLookupResult(TrackableValue value)
    : value(value), base() {}
  TrackableValueLookupResult(TrackableValue value, TrackableValue base)
    : value(value), base(base) {}
};
```

In the case where we are accessing a projection path out of a non-Sendable type
that contains all non-Sendable fields, we do not do anything different than we
did previously. We just walk up from use->def until we find the access path base
which we use as the representative of the leaf of the chain and return
TrackableValueLookupResult(access path base).

In the case where we are accessing a Sendable leaf type projected from a
non-Sendable base, we store the leaf type as our value and return the actual
non-Sendable base in TrackableValueLookupResult. Importantly this ensures that
even though our Sendable value will be ignored by the rest of the analysis, the
rest of the analysis will ensure that our base is required if our base is a var
that had been escaped into a closure by reference.

In the case where we are accessing a non-Sendable leaf type projected from a
Sendable type (which we may have continued to be projected subsequently out of
additional Sendable types or a non-Sendable type), we make the last type on the
projection path before the Sendable type, the value of the leaf type. We return
the eventual access path base as our underlying value base. The logic here is
that since we are dealing with access paths, our access path can only consist of
projections into a recursive value type (e.x.: struct/tuple/enum... never a
class). The minute that we hit a pointer or a class, we will no longer be along
the access path since we will be traversing a non-contiguous piece of
memory (consider a class vs the class's storage) and the traversal from use->def
will stop. Thus, we know that there are only two ways we can get a field in that
value type to be Sendable and have a non-Sendable field:

1. The struct can be @unchecked Sendable. In such a case, we want to treat the
leaf field as part of its own disconnected region.

2. The struct can be global actor isolated. In such a case, we want to treat the
leaf field as part of the global actor's region rather than whatever actor.

The reason why we return the eventual access path base as our tracked value base
is that we want to ensure that if the var value had been escaped by reference,
we can require that the var not be sent since we are going to attempt to access
state from the var in order to get the global actor guarded struct that we are
going to attempt to extract our non-Sendable leaf value out of.

(cherry picked from commit c846c2279e)
2025-04-15 14:57:47 -07:00
Andrew Trick
4608c06f78 Fix GenericSpecializer for addressable parameters.
Addressable parameters must remain indirect.

Incidentally also fixes an obvious latent bug in which all specialization was
disabled if any metatypes could not be specialized.

Fixes rdar://145687827 (Crash of inline-stored Span properties with optimizations)

(cherry picked from commit 935b5e7ea2)
2025-04-08 14:02:19 -07:00
Andrew Trick
da2894ba2c [NFC] fix a dropUnusedArguments parameter name
(cherry picked from commit 6898e33edd)
2025-04-08 14:02:18 -07:00
Artem Chikin
d484ec7c1f [Compile Time Values] Implement a mandatory SIL pass to verify '@const' values 2025-03-27 14:33:35 -07:00
Pavel Yaskevich
41c88f864a [SILOptimizer] Turn "is self-recursive" check into analysis
The body of a function has to be re-analyzed for every call
site of the function, which is very expensive and if the
body is not changed would produce the same result.

This takes about ~10% from swift-syntax overall build time
in release configuration.
2025-03-24 00:25:13 -07:00
Meghana Gupta
30a364d3f0 Merge pull request #80031 from meg-gupta/closurelifetimefixup
Fix ClosureLifetimeFixup to insert destroys at leaking blocks
2025-03-18 10:40:31 -07:00
Meghana Gupta
c528afccf2 Fix ClosureLifetimeFixup to insert destroys at leaking blocks 2025-03-14 15:48:44 -07:00
Erik Eckstein
d225c47d25 AST: rename OpenArchetypeType -> ExistentialArchetypeType
NFC
2025-03-11 20:21:46 +01:00
Nate Chandler
f1bc3b5205 [OSSACanOwned] Dead-end extend base lifetime.
Regardless of consumes of copies, if the original lexical value is not
consumed on a dead-end path, it must remain live to that dead-end.

rdar://145226757
2025-02-27 07:20:27 -08:00
Nate Chandler
5ffe092fa5 [OSSACanOwned] Extend all lifetimes to dead-ends.
Uses of borrows may occur between the borrow and a dead-end regardless
of lexicality, so always extend lifetimes to dead-ends.
2025-02-27 07:20:25 -08:00
Nate Chandler
22fdeff83c [NFC] OSSACanOwned: Record function as member. 2025-02-27 07:19:48 -08:00
Michael Gottesman
44052e5c28 [rbi] Respect nonisolated(unsafe) when assigning or merging into a sending out parameter.
rdar://143714959
2025-02-25 08:39:17 -08:00
Michael Gottesman
b286373631 [rbi] Make a confusing comment clearer.
From talking with @dgregor, it became clear that this comment was easily
interpreted as saying that AssignFresh always introduced a disconnected value...
which is not the case. Instead, AssignFresh just introduces a new value that
could have any form of isolation. The actual isolation of the value is assigned
via tryToTrackValue and eventually SILIsolationInfo::get().
2025-02-24 10:09:32 -08:00
Meghana Gupta
4561658799 Avoid creating unoptimizable copies in CSE
CSE uses OSSA rauw which creates copies and copies that are created to optimize
across borrow scopes are unoptimizable. This PR avoids this situation for now.
2025-02-19 11:20:43 -08:00
Arnold Schwaighofer
ed32270d72 Merge pull request #79191 from aschwaighofer/access_enforcement_fixes
AccessEnforcement: Fix analysis to include mayReleases as potentially executing unknown code
2025-02-10 16:57:31 -08:00
eeckstein
c4af3b3a8e Merge pull request #79186 from eeckstein/remove-predictable-memopt
Optimizer: replace PredictableMemoryAccessOptimizations with a "mandatory" redundant load elimination pass
2025-02-08 08:05:33 +01:00
Arnold Schwaighofer
7a251af60c AccessEnforcement: Fix analysis to include mayReleases as potentially
executing unknown code

This means we have to claw back some performance by recognizing harmless
releases.

Such as releases on types we known don't call a deinit with unknown
side-effects.

rdar://143497196
rdar://143141695
2025-02-07 15:10:13 -08:00
Erik Eckstein
0a011cddd8 Remove the old (and now obsolete) PredictableMemoryAccessOptimizations pass 2025-02-07 11:30:35 +01:00
Nate Chandler
c6e0480e1c [NFC] OSSACanOwned: Simplify Def definition.
It's sufficient just to have a struct with a kind and a value.  There
aren't any cases where the payload's original type benefits from being
statically preserved--they're only ever obtained as `SILValue`s.  Keep
the type safety by way of constructors.
2025-02-06 17:58:20 -08:00
Nate Chandler
2a43494a01 [Gardening] OSSACanOwned: Removed dead friend.
There's no longer a DenseMap of Defs, so no corresponding DenseMapInfo.
2025-02-06 13:16:09 -08:00
Michael Gottesman
082b824a8e [rbi] Change Region Based Isolation for closures to not use the AST and instead just use SIL.
The reason why I am doing this is that in certain cases the AST captures indices
will never actually line up with partial apply capture indices since we seem to
"smush" together closures and locally defined functions.

NOTE: The reason for the really small amount of test changes is that this change
does not change the actual output by design. The only cases I had to change were
a case where we began to emit a better diagnostic and also where I added code
coverage around _ and let _ since those require ignored_use to be implemented so
that they would be diagnosed (previously we just did not emit anything so we
couldn't emit the diagnostic at the SIL level).

rdar://142661388
2025-01-22 21:12:36 -08:00
Meghana Gupta
2c256180ce Add new utility swift::areUsesWithinValueLifetime 2025-01-10 16:15:50 -08:00
Meghana Gupta
ed0483b4ce Fix SILCombine of existential applies
Don't use previously found owned concrete values in ossa. They will consumed by
forwarding operations like init_existential_ref. Instead create an unconditional cast
of the opened existential to concrete type and use that to create a concrete apply.
2025-01-07 10:38:25 -08:00
Erik Eckstein
48b913af4b Optimizer: make the hasOwnershipOperandsOrResults utility available in OwnershipOptUtils 2025-01-02 10:42:01 +01:00
Nate Chandler
bace1a60ce [NFC] ReachableBlocks: Add ::hasUnreachableBlocks.
The method walks over the blocks of the function testing each for
reachability and returns false on the first that is not.
2024-12-18 11:25:42 -08:00
Nate Chandler
631fc4c39e [NFC] ReachableBlocks: Rename isReachable method.
It was previously `isVisited`.  And mark `visit` private, it needn't be
part of the interface for any current clients.
2024-12-18 11:25:42 -08:00
Nate Chandler
f8d782ed42 [NFC] ReachableBlocks: Extract compute method.
In preparation for adding more users.
2024-12-18 11:25:42 -08:00
Erik Eckstein
09a5a4487a Optimizer: add a utility to replaces phis with the unique incoming values if all incoming values are the same
This is needed after running the SSAUpdater for an existing OSSA value, because the updater can
insert unnecessary phis in the middle of the original liverange which breaks up the original
liverange into smaller ones:

```
   %1 = def_of_owned_value
   %2 = begin_borrow %1
   ...
   br bb2(%1)
 bb2(%3 : @owned $T): // inserted by SSAUpdater
   ...
   end_borrow %2      // use after end-of-lifetime!
   destroy_value %3
```

It's not needed to run this utility if SSAUpdater is used to create a _new_ OSSA liverange.
2024-12-12 08:57:57 +01:00
Erik Eckstein
301ab4e112 LoopRotate: remove the replace-arg-with-struct peephole optimization
This does not belong to loop-rotate and does not work with OSSA.
This peephole is covered by other optimizations.
2024-12-12 08:35:48 +01:00
nate-chandler
5637eaf3ca Merge pull request #77968 from nate-chandler/rdar139842132
[OSSACanonicalizeOwned] Record traversed defs and don't traverse copies of guaranteed values.
2024-12-06 07:00:20 -08:00
Nate Chandler
eebe9ac20a [NFC] OSSACanonicalizeOwned: Renamed found defs.
The field is no longer a worklist, just a list of discovered defs.
2024-12-05 08:29:52 -08:00
Nate Chandler
498294efa2 [NFC] OSSACanOwned: Record defs in SmallVector.
In preparation for only recording the defs once, replace the
GraphNodeWorklist of defs with a SetVector.  Preserve the current
visitation order by creating a worklist of indices to be visited.
2024-12-05 08:24:46 -08:00