Commit Graph

2864 Commits

Author SHA1 Message Date
Joe Groff
73ed03c827 Merge pull request #73380 from jckarter/mark-captured-no-implicit-copy-parameters
Consistently mark `borrowing` and `consuming` parameters for move-only checking when captured.
2024-05-02 08:56:10 -07:00
nate-chandler
d5aafbcdad Merge pull request #73368 from nate-chandler/lifetime-completion/20240501/1
[NFC] LifetimeCompletion: Clarified API and documentation.
2024-05-01 18:02:46 -07:00
Joe Groff
90e1ecb864 Consistently mark borrowing and consuming parameters for move-only checking when captured.
When a `borrowing` or `consuming` parameter is captured by a closure,
we emit references to the binding within the closure as if it is non-implicitly
copyable, but we didn't mark the bindings inside the closure for move-only
checking to ensure the uses were correct, so improper consumes would go
undiagnosed and lead to assertion failures, compiler crashes, and/or
miscompiles. Fixes rdar://127382105
2024-05-01 13:41:28 -07:00
Nate Chandler
5383df755a [NFC] LifetimeCompletion: Clarify modes.
Completion is done along a boundary, either the availability or the
liveness boundary.  Represent which with a type.  Update docs and names.
2024-05-01 08:57:01 -07:00
Nate Chandler
7009a18cc4 [MoveOnlyAddressChecker] Don't complete phis.
After 874971c40d, before running address
checking, all lifetimes in the function are completed.  That doesn't
quite work because lifetime completion expects not to encounter
reborrows or their adjacent phis.
2024-04-30 16:52:01 -07:00
Nate Chandler
5307ac666e [SIL] Permit end_borrow(begin_apply). 2024-04-25 17:03:41 -07:00
Michael Gottesman
9ce43d5a98 [region-isolation] Suppress non-Sendable region isolation errors appropriately when the type is imported by using @preconcurrency import.
This translates the rules for @preconcurrency import from SE-0337 into the
region isolation world. Specifically if a module is compiled without strict
concurrency checking and imported with @preconcurrency:

1. All types from that module that are implicitly non-Sendable have diagnostics
suppressed in swift 5 and swift 6.

2. All types from that module that are explicitly non-Sendable emit warnings in
both swift 5 and swift 6.

rdar://126804052
2024-04-23 22:26:07 -05:00
Michael Gottesman
c4f7076baf [region-isolation] When RegionIsolation is enabled, delay the preconcurrency import not used diagnostic to the SIL pipeline.
The reason why I am doing this is that I am going to be adding support for
preconcurrency imports to TransferNonSendable. That implies that we can have
preconcurrency import suppression in the SIL pipeline and thus that emitting the
diagnostic in Sema is too early.

To do this, I introduced a new module pass called
DiagnoseUnnecessaryPreconcurrencyImports that runs after the SILFunction pass
TransferNonSendable. The reason why I use a module pass is to ensure that
TransferNonSendable has run on all functions before we attempt to emit these
diagnostics. Then in that pass, we iterate over all of the modules functions and
construct a uniqued array of SourceFiles for these functions. Then we iterate
over the uniqued SourceFiles and use the already constructed Sema machinery to
emit the diagnostic using the source files.

rdar://126928265
2024-04-23 12:42:43 -05:00
nate-chandler
a354528321 Merge pull request #73155 from nate-chandler/lifetime-completion/20240419/1
[LifetimeCompletion] Don't destroy alloc_boxes.
2024-04-22 11:33:36 -07:00
Nate Chandler
5881ea43e7 [DI] Fix unfailable throw during super init.
When deallocating a partially allocated class in the trapping branch of
an unfailable cast, cast back down to the subclass which is being
partially deallocated before emitting the dealloc partial ref
instruction.
2024-04-21 20:56:39 -07:00
Nate Chandler
46ccdd6176 [NFC] DI: Used already existing local variable.
Rather than repeating the same expression that already defines it.
2024-04-19 16:57:20 -07:00
Nate Chandler
3e2d1d0e4c [MoveOnlyAddressChecker] Complete lifetimes first.
It relies on complete lifetimes for its analysis.  So if there are any
instructions to check, complete all lifetimes in the function first.
2024-04-19 14:47:35 -07:00
Nate Chandler
f174729a35 [MoveOnlyAddressChecker] OK destroy(pai[onstack])
A destroy_value of an on-stack partial apply isn't actually a consuming
use, so don't treat it as one.
2024-04-19 12:37:34 -07:00
Nate Chandler
23e7c36c5f [NoncopyablePartialConsumption] Ungate feature.
Remove all checks for the feature flag.  It's on all the time.
2024-04-19 12:37:34 -07:00
Michael Gottesman
bfa910dcb1 Merge pull request #72959 from gottesmm/tns-upstream-2
[region-isolation] Do not look through begin_borrow or move_value if they are marked as a var_decl.
2024-04-17 17:42:19 -07:00
Michael Gottesman
51ef67d7df [variable-name-utils] Refactor inferName/inferNameAndRoot helpers onto VariableNameInferrer.
I have been using these in TransferNonSendable and they are useful in terms of
reducing the amount of code that one has to type to use this API. I am going to
need to use it in SILIsolationInfo, so it makes sense to move it into
SILOptimizer/Utils.

NFCI.
2024-04-11 15:41:18 -07:00
Michael Gottesman
c9fe8ff935 [region-isolation] Eliminate unnecessary using TrackableValueID = Element.
Having two artificial typedefs for the same wrapped value is just confusing.
Better to just have one and make the code simpler to understand.
2024-04-11 15:41:18 -07:00
Erik Eckstein
89b38d1d70 DiagnoseUnreachable: consider borrowed-from instructions when deleting block arguments
Fixes a crash when propagating guaranteed phi arguments.
rdar://126274522
2024-04-11 18:46:22 +02:00
Michael Gottesman
df4fb64ea1 Merge pull request #72955 from gottesmm/rdar126170014
[region-isolation] Include the region -> transferring operand map in the dataflow convergence.
2024-04-10 17:20:55 -07:00
eeckstein
e871ae40c5 Merge pull request #71176 from eeckstein/borrowed-from-instruction
SIL: add the borrowed-from instruction
2024-04-10 19:33:12 +02:00
Michael Gottesman
ca8179aa7c [region-isolation] Track operand info in a separate map rather than inline in a TransferringOperand data structure.
This is backing out an approach that I thought would be superior, but ended up
causing problems.

Originally, we mapped a region number to an immutable pointer set containing
Operand * where the region was tranferred. This worked great for a time... until
I began to need to propagate other information from the transferring code in the
analysis to the actual diagnostic emitter.

To be able to do that, my thought was to make a wrapper type around Operand
called TransferringOperand that contained the operand and the other information
I needed. This seemed to provide me what I wanted but I later found that since
the immutable pointer set was tracking TransferringOperands which were always
newly wrapped with an Operand *, we actually always created new pointer
sets. This is of course wasteful from a memory perspective, but also prevents me
from tracking transferring operand sets during the dataflow since we would never
converge.

In this commit, I fix that issue by again tracking just an Operand * in the
TransferringOperandSet and instead map each operand to a state structure which
we merge dataflow state into whenever we visit it. This provides us with
everything we need to in the next commit to including a region -> transferring
operand set equality check in our dataflow equations and always converge.
2024-04-10 10:30:10 -07:00
Joe Groff
e06ff61312 Merge pull request #72577 from jckarter/enable-borrowing-switch-backend
Use the `BorrowingSwitch` implementation for all noncopyable switches.
2024-04-10 07:38:12 -07:00
Erik Eckstein
e14c1d1f62 SIL, Optimizer: update and handle borrowed-from instructions
Compute, update and handle borrowed-from instruction in various utilities and passes.
Also, used borrowed-from to simplify `gatherBorrowIntroducers` and `gatherEnclosingValues`.
Replace those utilities by `Value.getBorrowIntroducers` and `Value.getEnclosingValues`, which return a lazily computed Sequence of borrowed/enclosing values.
2024-04-10 13:38:10 +02:00
Erik Eckstein
ac4bc89c9a SIL: add the borrowed-from instruction.
It declares from which enclosing values a guaranteed phi argument is borrowed from.
2024-04-10 13:38:10 +02:00
Joe Groff
5ad260315b Use the BorrowingSwitch implementation for all noncopyable switches.
It works well enough now that it should be an acceptable replacement for both
borrowing and consuming switches that works in more correct situations than the
previous implementation. This does however expose a few known issues that I'll
try to fix in follow ups:

- overconsumes cause verifier errors instead of raising diagnostics (rdar://125381446)
- cases with multiple pattern labels aren't yet supported (rdar://125188955)
- copyable types with the `borrowing` or `consuming` modifiers should probably use
  noncopyable pattern matching.

The `BorrowingSwitch` flag is still necessary to enable the surface-level syntax
changes (switches without `consume` and the `_borrowing` modifier, for instance).
2024-04-09 16:31:01 -07:00
Kuba (Brecka) Mracek
f36060f011 Merge pull request #72819 from kubamracek/embedded-keypath-crash
[embedded] Avoid a crash on location-less SIL functions in PerformanceDiagnostics
2024-04-08 20:09:49 -07:00
Kuba Mracek
91f4d47c7e [embedded] Add explaining comment about location-less SIL functions in PerformanceDiagnostics 2024-04-08 09:32:48 -07:00
Augusto Noronha
ddeba619d8 Use dyn_cast_or_null when casting AccessPathWithBase's base
Even though AccessPathWithBase's SILValue base is not optional, casting
it will check the underlying ValueBase, which can be null.
2024-04-04 17:50:35 -07:00
Anton Korobeynikov
c7a216058f [AutoDiff] First cut of coroutines differentiation (#71461)
This PR implements first set of changes required to support autodiff for coroutines. It mostly targeted to `_modify` accessors in standard library (and beyond), but overall implementation is quite generic.

There are some specifics of implementation and known limitations:
 - Only `@yield_once` coroutines are naturally supported
 - VJP is a coroutine itself: it yields the results *and* returns a pullback closure as a normal return. This allows us to capture values produced in resume part of a coroutine (this is required for defers and other cleanups / commits)
 - Pullback is a coroutine, we assume that coroutine cannot abort and therefore we execute the original coroutine in reverse from return via yield and then back to the entry
 - It seems there is no semantically sane way to support `_read` coroutines (as we will need to "accept" adjoints via yields), therefore only coroutines with inout yields are supported (`_modify` accessors). Pullbacks of such coroutines take adjoint buffer as input argument, yield this buffer (to accumulate adjoint values in the caller) and finally return the adjoints indirectly.
 - Coroutines (as opposed to normal functions) are not first-class values: there is no AST type for them, one cannot e.g. store them into tuples, etc. So, everywhere where AST type is required, we have to hack around.
 - As there is no AST type for coroutines, there is no way one could register custom derivative for coroutines. So far only compiler-produced derivatives are supported
 - There are lots of common things wrt normal function apply's, but still there are subtle but important differences. I tried to organize the code to enable code reuse, still it was not always possible, so some code duplication could be seen
 - The order of how pullback closures are produced in VJP is a bit different: for normal apply's VJP produces both value and pullback closure via a single nested VJP apply. This is not so anymore with coroutine VJP's: yielded values are produced at `begin_apply` site and pullback closure is available only from `end_apply`, so we need to track the order in which pullbacks are produced (and arrange consumption of the values accordingly – effectively delay them)
 - On the way some complementary changes were required in e.g. mangler / demangler

This patch covers the generation of derivatives up to SIL level, however, it is not enough as codegen of `partial_apply` of a coroutine is completely broken. The fix for this will be submitted separately as it is not directly autodiff-related.

---------

Co-authored-by: Andrew Savonichev <andrew.savonichev@gmail.com>
Co-authored-by: Richard Wei <rxwei@apple.com>
2024-04-04 17:24:55 -07:00
Meghana Gupta
0cddd69415 Merge pull request #72780 from meg-gupta/enablesilcombineossa
Enable inject_enum_addr silcombine in ossa
2024-04-03 15:59:22 -07:00
Kuba Mracek
dd9c99f27a [embedded] Avoid a crash on location-less SIL functions in PerformanceDiagnostics 2024-04-03 15:26:49 -07:00
Meghana Gupta
72a9075b8e Return index from SwitchValueInst::getUniqueCaseForDestination 2024-04-03 10:30:52 -07:00
Artem Chikin
69fdc1356c Revert "Revert "Add mandatory SIL pass implementing '@_alwaysEmitConformanceMetadata' protocol attribute"" 2024-04-03 09:29:51 -07:00
Michael Gottesman
1cf4e99454 Propagate global actor-ness of functions/closures.
I fixed a bunch of small issues around here that resulted in a bunch of radars
being fixed. Specifically:

1. I made it so that we treat function_refs that are from an actor isolated
function as actor isolated instead of sendable.

2. I made it so that autoclosures which return global actor isolated functions
are treated as producing a global actor isolated function.

3. I made it so that we properly handle SILGen code patterns produced by
Sendable GlobalActor isolated things.

rdar://125452372
rdar://121954871
rdar://121955895
rdar://122692698
2024-03-29 14:39:34 -07:00
Andrew Trick
a99ea62339 Fix MoveOnlyDiagnostics, ConsumOperator...Checkers diagnostics
Emitting a note with an invalid source location is actively
harmful. It confuses users and tools, makes it impossible to write
unit tests. In this case, the note simply says "use here", so it's
completely free of information without the source location.
2024-03-27 13:42:25 -07:00
Andrew Trick
6b776f57fb Move lifetime diagnostics after consume operator diagnostics.
This fixes bugs when ~Escapable types depended on values that are passed to 'consume'.

The consume operator diagnostics are broken when dependent values are
present. This sidesteps the problem for lifetime dependence. And we
generally want to diagnose lifetime dependence after all move-only
related diagnostics. That way, using a dependent value after consume
provides a more informative diagnostic about the dependent value and
its scope.
2024-03-27 09:13:24 -07:00
Michael Gottesman
d0d2f2d9b2 [region-isolation] Change the transfer non-transferrable value due to capture by an isolated closure diagnostic to be a named diagnostic.
rdar://125372790
2024-03-25 20:17:26 -07:00
Michael Gottesman
5e58aa64a2 [region-isolation] When emitting an error for an isolated closure use of a never transferrable value, use the dynamic isolation. Do not assume it is task isolated.
rdar://125372336
2024-03-25 20:17:26 -07:00
Kuba (Brecka) Mracek
89cd62604b Merge pull request #72472 from kubamracek/embedded-keypaths
[embedded] Compile-time (literal) KeyPaths for Embedded Swift
2024-03-25 10:58:51 -07:00
eeckstein
8cd04c26ac Merge pull request #72490 from eeckstein/fix-predictable-deadalloc-elim
PredictableMemOpt: fix a crash, caused by a wrong instruction cast
2024-03-25 17:03:46 +01:00
Michael Gottesman
7cda418d45 [region-isolation] Convert the isolation having autoclosure expr error to use a named variant.
It was pretty easy to do since I already have the name from the AST.
2024-03-23 21:17:41 -07:00
Michael Gottesman
7d07fb5a11 [region-isolation] Add a named variant of the transfer via closure capture diagnostic.
Just converting another diagnostic to its final named form.
2024-03-23 21:17:41 -07:00
Michael Gottesman
5580bb4ba7 [region-isolation] Add a named variant of the use after pass via strongly transfering parameter.
Specifically, I added a named version of the diagnostic:

 func testSimpleTransferLet() {
   let k = Klass()
-  transferArg(k) // expected-warning {{binding of non-Sendable type 'Klass' accessed after being transferred; later accesses could race}}
+  transferArg(k) // expected-warning {{transferring 'k' may cause a race}}
+  // expected-note @-1 {{'k' used after being passed as a transferring parameter}}
   useValue(k) // expected-note {{use here could race}}
 }

and I also cleaned up the typed version of the diagnostic that is used
if we fail to find a name:

 func testSimpleTransferLet() {
   let k = Klass()
-  transferArg(k) // expected-warning {{binding of non-Sendable type 'Klass' accessed after being transferred; later accesses could race}}
-  transferArg(k) // expected-warning {{value of non-Sendable type 'Klass' accessed after being transferred; later accesses could race}}
   useValue(k) // expected-note {{use here could race}}
 }

This is the 2nd to the last part of a larger effort to rework all of
the region based diagnostics to first try and use names and only go back
to the old typed diagnostics when we fail to look up a name (which should
be pretty rare, but is always possible).

At some point if I really feel confident enough with the name lookup code, I am
most likely just going to get rid of the typed diagnostic code and just emit a
compiler doesnt understand error. The user will still not be able to ship the
code but would also be told to file a bug so that we can fix the name
inference.
2024-03-23 21:17:41 -07:00
Andrew Trick
2f6c4ad90d Merge pull request #72513 from atrick/markdep_escape
SIL: Fix handling of mark_dependence [nonescaping] in several utilities
2024-03-23 09:33:28 -07:00
Konrad `ktoso` Malawski
6132386371 [Distributed] Complete handling of protocol calls and witnesses using adjusted mangling scheme (#72416) 2024-03-23 23:54:23 +09:00
Michael Gottesman
357a53ab48 [region-isolation] Clean up use after transfer error to use the dynamic isolation information of the transfered operand value in its diagnostic message.
As an example of the change:

-  // expected-note @-1 {{'x' is transferred from nonisolated caller to main actor-isolated callee. Later uses in caller could race with potential uses in callee}}
+  // expected-note @-1 {{transferring disconnected 'x' to main actor-isolated callee could cause races in between callee main actor-isolated and local nonisolated uses}}

Part of the reason I am doing this is that I am going to be ensuring that we
handle a bunch more cases and I wanted to fix this diagnostic before I added
more incaranations of it to the tests.
2024-03-22 13:12:51 -07:00
Andrew Trick
f8b5bacfd4 Fix CapturePromotion handling of mark_dependence 2024-03-22 11:51:58 -07:00
Meghana Gupta
50b358c64f Merge pull request #72359 from meg-gupta/skiphismdi
Fix utilities that may see phis of mark_dependence [nonescaping]
2024-03-21 18:28:08 -07:00
Michael Gottesman
2603c847a5 Merge pull request #72476 from gottesmm/cleanups
[region-isolation] Some cleanups in preparation for later work
2024-03-21 18:16:47 -07:00
Michael Gottesman
5b8171240d [region-isolation] Rename IsolationRegionInfo -> SILIsolationInfo.
That is really what IsolationRegionInfo is.
2024-03-21 14:16:20 -07:00