use local funcs to implement `defer`, this also fixes several
bugs with that feature, such as it breaking in nonisolated
functions when a default isolation is in effect in the source file.
Change how we compute isolation of local funcs. The rule here is
supposed to be that non-`@Sendable` local funcs are isolated the
same as their enclosing context. Unlike closure expressions, this
is unconditional: in instance-isolated functions, the isolation
does not depend on whether `self` is captured. But the computation
was wrong: it didn't translate global actor isolation between
contexts, it didn't turn parameter isolation into capture isolation,
and it fell through for several other kinds of parent isolation,
causing the compiler to try to apply default isolation instead.
I've extracted the logic from the closure expression path into a
common function and used it for both paths.
The capture computation logic was forcing a capture of the
enclosing isolation in local funcs, but only for async functions.
Presumably this was conditional because async functions need the
isolation for actor hops, but sync functions don't really need it.
However, this was causing crashes with `-enable-actor-data-race-checks`.
(I didn't investigate whether it also failed with the similar
assertion we do with preconcurrency.) For now, I've switched this
to capture the isolated instance unconditionally. If we need to
be more conservative by either only capturing when data-race checks
are enabled or disabling the checks when the isolation isn't captured,
we can look into that.
Fix a bug in capture isolation checking. We were ignoring captures
of nonisolated declarations in order to implement the rule that
permits `nonisolated(unsafe)` variables to be captured in
non-sendable closures. This check needs to only apply to variables!
The isolation of a local func has nothing to do with its sendability
as a capture.
That fix exposed a problem where we were being unnecessarily
restrictive with generic local func declarations because we didn't
consider them to have sendable type. This was true even if the
genericity was purely from being declared in a generic context,
but it doesn't matter, they ought to be sendable regardless.
Finally, fix a handful of bugs where global actor types were not
remapped properly in SILGen.
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
Previously, we handled cases where we had an actual SILDeclRef constant (e.x.:
an actual function ref), but we did not handle cases where we did not have a
constant but instead just had a FunctionTypeIsolation. We now handle that
correctly.
Right now it is basically a version of nonisolated beyond a few simple cases
like constructors/destructors where we are pretty sure we want to not support
this.
This is part of my bringup strategy for changing nonisolated/unspecified to be
caller isolation inheriting.
Before this change in the following code, we would say that message is isolated to the actor instead of the global actor isolation of the actor's method:
```swift
class Message { ... }
actor MessageHolder {
@MainActor func hold(_ message: Message) { ... }
}
@MainActor
func sendMessage() async {
let messageHolder = MessageHolder()
let message = Message()
// We identified messageHolder.hold as being MessageHolder isolated
// instead of main actor isolated.
messageHolder.hold(message)
Task { @MainActor in print(message) }
}
```
I also used this as an opportunity to simplify the logic in this part of the
code. Specifically, I had made it so that multiple interesting cases were
handled in the same conditional statement in a manner that it made it hard to
know which cases were actually being handled and why it was correct. Now I split
that into two separate if statements with comments that make it clear what we
are actually trying to pattern match against.
rdar://130980933
This occurs when working with ActorIsolation in SIL.
This lets us avoid needing to depend on the AST for getting ActorIsolation for
self parameters. Now, we can just create the actor isolation we need based off
of the decl that we have.
The code is based off of forActorInstanceSelf(ValueDecl *decl) along the path
where it just creates isolation based off of the decl's nominal type decl (which
is equivalent to what we are trying to do here).
Specifically, I made it so that when one calls dump(), we put in a newline
afterwards so we get a nice easy to read msg in the debugger. I also defined
dumpForDiagnostics() to make it easy to dump out in the debugger how the
ActorIsolation will show up in the diagnostics.
This enables one to use ActorIsolation in a FoldingSetNode. I also fixed the
hash combine of the type to contain state.silParsed (which I think was an
oversight).
Now that we actually know the region that non transferrable things belong to, we
can use this information to give a better diagnostic here.
A really nice effect of this is that we now emit that actor isolated parameters
are actually actor isolated instead of task isolated.
values.
Teach ActorIsolation that a `nil` isolated argument is statically nonisolated,
and a reference to GlobalActor.shared statically has global actor isolation.
This change also models arbitrary actor instance isolation using VarDecls
when possible, which allows comparing two ActorIsolation values that may
represent different actor instances. Previously, ActorIsolation was
modeled only by storing the nominal actor type and the parameter index,
so the actor isolation value for two different actors was considered
to be equal. Now, the nominal actor type is only used for isolated `self`
in cases where there is no implicit self parameter decl, such as for
stored properties.
a VarDecl or Expr.
This generalization exposed a bug where distributed actor isolation checking
was skipped in some cases, including for the isolated call in `whenLocal`.
The `whenLocal` implementation violated distributed actor isolation because
despite the `__isLocal` dynamic check, the `self` value passed to the `body`
function argument is still not statically local. To workaround this, I
applied the `_local` modifier explicitly to `self` before the call, which
also necessitated allowing `_local` to be written explicitly in the Distributed
library.
`@GlobalActor(unsafe)` and `@preconcurrency @GlobalActor` mean the same
thing, but there were two different representations in the actor isolation
checker. Standardize on the preconcurrency representation.
Some notes:
This is not emitted by SILGen. This is just intended to be used so I can write
SIL test cases for transfer non sendable. I did this by adding an
ActorIsolationCrossing field to all FullApplySites rather than adding it into
the type system on a callee. The reason that this makes sense from a modeling
perspective is that an actor isolation crossing is a caller concept since it is
describing a difference in between the caller's and callee's isolation. As a
bonus it makes this a less viral change.
For simplicity, I made it so that the isolation is represented as an optional
modifier on the instructions:
apply [callee_isolation=XXXX] [caller_isolation=XXXX]
where XXXX is a printed representation of the actor isolation.
When neither callee or caller isolation is specified then the
ApplyIsolationCrossing is std::nullopt. If only one is specified, we make the
other one ActorIsolation::Unspecified.
This required me to move ActorIsolationCrossing from AST/Expr.h ->
AST/ActorIsolation.h to work around compilation issues... Arguably that is where
it should exist anyways so it made sense.
rdar://118521597
Now that there's only one call-site of `safeToDropGlobalActor`, it doesn't
need to be exposed in the ActorIsolation header, and it doesn't need to
avoid `warnUntilSwiftVersion` to match constraint system diagnostics.
The `@MainActor` global actor constraint on a declaration does not carry an
inherent ABI impact and therefore use of this constraint should not be limited
to OS versions where Swift concurrency is available.
Resolves rdar://105610970
It's ok to drop the global-actor qualifier `@G` from a function's type if:
- the cast is happening in a context isolated to global-actor `G`
- the function value will not be `@Sendable`
- the function value is not `async`
It's primarily safe to drop the attribute because we're already in the
same isolation domain. So it's OK to simply drop the global-actor
if we prevent the value from later leaving that isolation domain.
This means we no longer need to warn about code like this:
```
@MainActor func doIt(_ x: [Int], _ f: @MainActor (Int) -> ()) {
x.forEach(f)
// warning: converting function value of type '@MainActor (Int) -> ()' to '(Int) throws -> Void' loses global actor 'MainActor'
}
```
NOTE: this implementation is a bit gross in that the constraint solver
might emit false warnings about casts it introduced that are actually
safe. This is mainly because closure isolation is only fully determined
after constraint solving. See the FIXME's for more details.
resolves rdar://94462333
When we get rid of `LeaveClosureBodiesUnchecked` we no longer save closure types to the AST and thus also don’t save their actor isolation to the AST. Hence, we need to extract types and actor isolations of parent closures from the constraint system solution instead of the AST. This prepares `ActorIsolationChecker` to take custom functions to determine the type of an expression or the actor isolation of a closure.
A function can be actor instance-isolated to one of its parameters.
Make sure that this is reflected in ActorIsolation, so such a function
doesn't get a different actor isolation.
[Distributed] generic and inner test; without one edge case
[Distributed] fix distributed_thunk test; unsure about those extra hops, could remove later
[Distributed] Remove type pretending in getSILFunctionType; it is not needed
It seems our constant replacement in the earlier phases is enough, and
we don't need this trick at all.
[Distributed] Use thunk when calling cross-actor on DA protocols
Start collapsing the several implementations of actor isolation checking
into a single place that determines what it means to reference a declaration
from a given context, potentially supplying an instance for an actor. This
is partly cleanup, and partly staging for the implementation of the
Sendable restrictions introduced in SE-0338. The result of this check
falls into one of three categories:
* Reference occurs within the same concurrency domain (actor/task)
* Reference leaves an actor context to a nonisolated context (SE-0338)
* Reference enters the context of the actor, which might require a
combination of implicit async, implicit throws, and a "distributed" check.
Throughout this change I've sought to maintain the existing semantics,
even where I believe they are incorrect. The changes to the test cases
are not semantic changes, but reflect the unification of some
diagnostic paths that changed the diagnostic text but not when or how
those diagnostics are produced. Additionally, SE-0338 has not yet been
implemented, although this refactoring makes it easier to implement
SE-0338.
Use this new actor isolation checking scheme to implement the most
common actor-isolation check, which occurs when accessing a member of
an instance.
With the clarification in SE-0338, revise the definition of "may
execute concurrently with" to always be false when we're accessing a
value from a same-actor-isolated inner context.
Fixes rdar://82004833.
When a closure is not properly actor-isolated, but we know that we inferred its isolation from a `@preconcurrency` declaration, we now emit the errors as warnings in Swift 5 mode to avoid breaking source compatibility if the isolation was added retroactively.
The distributed case is distinguishable from the non-distributed case
based on the actor type itself for those rare cases where we care. The
vast majority of code is simplified by treating this identically to
`ActorInstance`.
Flow-isolation is a diagnostic SIL pass that finds
unsafe accesses to properties in initializers and
deinitializers that cannot gain isolation to otherwise
protect those accesses from concurrent modifications.
See SE-327 for more details about how and why it exists.
This commit includes changes and features like:
- The removal of the escaping-use restriction
- Flow-isolation that works properly with `defer` statements
- Flow-isolation with an emphasis on helpful diagnostics.
It also includes known issues like:
- Local / nonescaping functions are not analyzed by
flow-isolation, despite it being technically possible.
The main challenge in supporting it efficiently is that
such functions do not have a single exit-point, like
a `defer`. In particular, arbitrary functions can throw
so there are points where nonisolation should _not_ flow
out of the function at a call-site in the initializer, etc.
- The implementation of the flow-isolation pass is not
particularly memory efficient; it relies on BitDataflow
even though the particular flow problem is simple.
So, a more efficient implementation would be specialized for
this particular problem, etc.
There are also some changes to the Swift language itself: defer
will respect its context when deciding its property access kind.
Previously, a defer in an initializer would always access a stored
property through its accessor methods, instead of doing so directly
like its enclosing function might. This inconsistency is unfortunate,
so for Swift 6+ we make this consistent. For Swift 5, only a defer
in a function that is a member of the following kinds of types
will gain this consistency:
- an actor type
- any nominal type that is actor-isolated, excluding UnsafeGlobalActor.
These types are still rather new, so there is much less of a chance of
breaking expected behaviors around defer. In particular, the danger is
that users are relying on the behavior of defer triggering a property
observer within an init or deinit, when it would not be triggering it
without the defer.