Commit Graph

103 Commits

Author SHA1 Message Date
Kavon Farvardin
814fb42554 fix nested suspension issue with objc async calls
when two objc async functions are composed with each other,
i.e., f(g()), then the clean-ups for g() would get emitted
at an unexpected time, namely, during the suspension for
the call to f(). This means that using a clean-up to emit
the executor-hop breadcrumb was incorrect. The hop could
appear between a get_async continuation and its matching
await_continuation, which is an unsupported nested suspension.

This commit fixes that by removing the use of the breadcrumb
clean-up in favor of providing that breadcrumb directly to
the result plan, so that it may be emitted later on when the
result plan sees fit.

Fixes rdar://91502776
2022-05-02 18:20:59 -07:00
Joe Groff
1e2bda9ea0 Extensions to SILBoxType to represent captures.
- Add a `[reflection]` bit to `alloc_box` instructions, to indicate that a box
  should be allocated with reflection metadata attached.
- Add a `@captures_generics` attribute to SILLayouts, to indicate a type layout
  that captures the generic arguments it's substituted with, meaning it can
  recreate the generic environment without additional ABI-level arguments, like
  a generic partial application can.
2022-04-21 12:51:46 -07:00
Nate Chandler
4aff98ffb5 [SILGen] Use opaque AP for ObjC-async returns.
Previously, the AbstractionPattern that was used for the value
"returned" (i.e. via a completion handler) from ObjC mostly (but not
quite always) was "type".

The generated completion handler correctly (because this is required in
order to call _resumeUnsafeContinuation) reabstracted the block (e.g.
from @convention(block) to @substituted <T> () -> @out T for <()>).  The
callee of the ObjC function, however, loaded the function from the block
as if it were not reabstracted (e.g. () -> ()).

On most platforms, that happened to work.  On arm64e, that difference in
types caused in a difference in pointer signing, resulting in a failure
at runtime.

rdar://85526879
rdar://85526916
2022-04-20 10:42:45 -07:00
Doug Gregor
52dba175a7 Opened existential types aren't always ExistentialType.
As with many other places in the frontend, grab the constraint type
when from an existential type when we have one.
2022-02-18 11:22:57 -08:00
Anthony Latsis
91bd2b1803 AST: Remove OpenedArchetypeType::getOpenedExistentialType()
Clients can explicitly ask for the opened existential type on the archetype's generic environment,
or use `getExistentialType` to obtain a specific archetype's upper bounds.
2022-02-04 16:22:50 +03:00
Anthony Latsis
60c85b0108 SILGen: Handle nested opened archetypes and add tests 2022-02-02 02:10:05 +03:00
Holly Borla
d146b69ccc Merge pull request #40666 from hborla/explicit-existential-fixes
[SE-0335] Enable explicit existential types.
2022-01-14 16:38:14 -08:00
Holly Borla
6cee193fc0 [Type System] When explicit existential types are enabled, wrap Error
in ExistentialType for the type of error values.
2022-01-13 19:30:44 -08:00
Nate Chandler
4bac557ff3 [SILGen] Added borrow scopes to alloc_boxes.
Because AllocBoxToStack is not able to transform every alloc_box into an
alloc_stack, it's necessary to add begin_borrow [lexical] to every
alloc_box in order to provide lexical scopes for those alloc_boxes which
will not be transformed into alloc_stacks.
2022-01-13 13:32:35 -08:00
Robert Widmann
22405cefea Plumb the "Is Type Sequence" Bit Through the Surface AST 2021-11-08 13:48:30 -08:00
Andrew Trick
8f53a927b0 SILGen OSSA support for switch_enum/checked_cast_br, related cleanup
Use APIs for creating terminator results that handle forwarding
ownership consistently.

Add ManagedValue::forForwardedRValue(SILValue) to handle cleanups
consistently based on ownership forwarding.

Add SILGenBuilder::createForwardedTermResult(SILType type) for
creating termator results with the correct ownership and cleanups.

Add SILGenBuilder::createTermResult(SILType type, ValueOwnershipKind
ownership) that handles cleanup based on terminator result ownership.

Add SILGenBuilder::createOptionalSomeResult(SwitchEnumInst) so a lot
of code doesn't need to deal with unwrapping Optional types,
terminator results, and ownership rules.

Replace the existing "phi" APIs with a single
SILGenBuilder::createPhi(SILType, ValueOwnershipKind) that handles
cleanup based on phi ownership.

Phis and terminator results are fundamentally different and need to be handled differently everywhere. Remove the confusion where terminator results were generated with a "phi argument" API.
2021-09-07 22:50:46 -07:00
Nate Chandler
1ae317dd88 [SILGen] Handle foreign funcs with error and async conventions.
Previously, SILGen assumed that a foreign function could either have a
foreign async convention or a foreign error convention, but if it had
both, the error would be subsumed into the completion.  That resulted in
failures to emit code for async calls of functions like

```
- (BOOL)minimalWithError:(NSError* _Nullable*)error
         completionHandler:(void (^ _Nonnull)(void))completionHandler;
```

Here, SILGen gains the ability to emit such functions.  To enable that,
a few changes were required when both conventions are present:
- a separate argument for each convention is used
- the ResultPlan is a ForeignErrorResultPlan nesting a
  ForeignAsyncResultPlan
- the continuation is always of the form UnsafeContinuation<_, Error>
  regardless of whether the completion handler takes an error
- the foreign error block fills the continuation with the error that was
  passed by reference out of the ObjC method call
- the foreign error block branches to the block containing the await
  instruction

rdar://80704984
2021-08-03 18:36:15 -07:00
nate-chandler
8345174bae Merge pull request #38370 from nate-chandler/rdar79383990
[SILGen] Used formal type when bridging completion handler arguments.
2021-07-26 10:57:49 -07:00
Nate Chandler
c493632b68 [SILGen] Used type AbstractionPattern.
Previously, AbstractionPattern::getOpaque() was used for async
continuations.  That was problematic for functions like

```objc
- (void)performVoid2VoidWithCompletion:(void (^ _Nonnull)(void (^ _Nonnull)(void)))completion;
```

whose completion takes a closure.  Doing so resulted in attempting to
build a block to func thunk where one of the functions had an out
parameter.

Instead, use the AbstractionPattern(ty).

rdar://79383990
2021-07-24 14:25:27 -07:00
Nate Chandler
4cb8453d6a [SILGen] Used formal type when bridging continuation arguments.
Address a FIXME where lowered types rather than formal types were used
when converting from objc to native types which resulted in a failure to
convert block types.
2021-07-24 14:25:26 -07:00
Robert Widmann
1329f3cfbd [NFC] Lift getGenericEnvironment() into GenericSignature 2021-07-22 23:33:02 -07:00
Robert Widmann
a0615e9848 [NFC] Use GenericSIgnature::getGanonicalSignature Where Possible 2021-07-22 23:27:06 -07:00
Erik Eckstein
65a6d9a22a MemoryLifetimeVerifier: support verifying enum memory locations.
This is kind of complicated, because an enum can be trivial for one case and not trivial for another case. We need to check at which parts of the function we can prove that the enum does (or could) have a trivial case. In such a branch, it's not required in SIL to destroy the enum location.

Also, document the rules and requirements for enum memory locations in SIL.rst.

rdar://73770085
2021-02-23 08:08:34 +01:00
Joe Groff
eea3a6c27f SILGen: Handle pseudogeneric completion-handler-based async APIs.
Plumb generic signatures through the codegen for invoking foreign APIs as async, so that we
correctly handle APIs declared on ObjC lightweight generic classes. rdar://74361267
2021-02-16 16:05:04 -08:00
Jonathan Grynspan
d8f7f20c4b [Concurrency] Simplify the type story for Continuation by eliminating Throwing variants
The goal of doing this is to reduce the amount of boilerplate and repeated code w.r.t. Continuation. Having just added `resume()` in four places, I got the sense that there was a lot of common code that was being duplicated. I removed the Throwing variants of these types (they can be expressed as Continuation<T, E:Error> instead of ThrowingContinuation<E>) and I broke out a significant amount of common code between CheckedContinuation and UnsafeContinuation into an implementation-only protocol to avoid repeating it. D.R.Y.

This change resolves rdar://74154769.
2021-02-10 12:09:33 -05:00
Joe Groff
bd2a6a4892 SILGen: Handle _Nullable completion handler arguments to imported async APIs. 2020-12-11 14:11:13 -08:00
Slava Pestov
a2dbdecdab SIL: Refactor get_async_continuation[_addr] to return a RawUnsafeContinuation 2020-12-01 20:04:09 -05:00
Joe Groff
368dc0f401 SILGen: Generate bodies for completion handler block impls 2020-11-10 16:36:50 -08:00
Joe Groff
e7ec8c35af SILGen: Caller-side codegen for invoking foreign async functions
Immediately before invoking the ObjC API, get the current continuation, capture it into a block to
pass as the completion handler, and then await the continuation, whose resume/error successors
serve as the semantic return/throw result of the call. This should complete the caller-side part
of SILGen; the completion handler block implementation is however still only a stub.
2020-11-03 08:28:30 -08:00
Slava Pestov
ffc976d3d5 SILGen: Fix an unused variable warning 2020-10-29 23:07:17 -04:00
Joe Groff
7ab9e87b68 SILGen: Stub out support for invoking foreign async methods.
Allow SILGen to not crash when invoking foreign async methods by emitting
`undef` for the completion callback going into the call, and for the
results that would be channeled back through awaiting the continuation.
2020-10-27 10:22:32 -07:00
Arnold Schwaighofer
147144baa6 SIL: Thread type expansion context through to function convention apis
This became necessary after recent function type changes that keep
substituted generic function types abstract even after substitution to
correctly handle automatic opaque result type substitution.

Instead of performing the opaque result type substitution as part of
substituting the generic args the underlying type will now be reified as
part of looking at the parameter/return types which happens as part of
the function convention apis.

rdar://62560867
2020-05-04 13:53:30 -07:00
John McCall
585c28d0c3 Plumb a result SILType through SILGen's emitTransformedValue.
This fixes an immediate bug with subst-to-orig conversion of
parameter functions that I'm surprised isn't otherwise tested.
More importantly, it preserves valuable information that should
let us handle a much wider variety of variant representations
that aren't necessarily expressed in the AbstractionPattern.
2020-03-12 00:23:13 -04:00
Dan Zheng
1486d6b346 NFC: Add GenericSignature::getCanonicalSignature. (#29105)
Motivation: `GenericSignatureImpl::getCanonicalSignature` crashes for
`GenericSignature` with underlying `nullptr`. This led to verbose workarounds
when computing `CanGenericSignature` from `GenericSignature`.

Solution: `GenericSignature::getCanonicalSignature` is a wrapper around
`GenericSignatureImpl::getCanonicalSignature` that returns the canonical
signature, or `nullptr` if the underlying pointer is `nullptr`.

Rewrite all verbose workarounds using `GenericSignature::getCanonicalSignature`.
2020-01-12 12:17:41 -08:00
Brent Royal-Gordon
99faa033fc [NFC] Standardize dump() methods in frontend
By convention, most structs and classes in the Swift compiler include a `dump()` method which prints debugging information. This method is meant to be called only from the debugger, but this means they’re often unused and may be eliminated from optimized binaries. On the other hand, some parts of the compiler call `dump()` methods directly despite them being intended as a pure debugging aid. clang supports attributes which can be used to avoid these problems, but they’re used very inconsistently across the compiler.

This commit adds `SWIFT_DEBUG_DUMP` and `SWIFT_DEBUG_DUMPER(<name>(<params>))` macros to declare `dump()` methods with the appropriate set of attributes and adopts this macro throughout the frontend. It does not pervasively adopt this macro in SILGen, SILOptimizer, or IRGen; these components use `dump()` methods in a different way where they’re frequently called from debugging code. Nor does it adopt it in runtime components like swiftRuntime and swiftReflection, because I’m a bit worried about size.

Despite the large number of files and lines affected, this change is NFC.
2019-10-31 18:37:42 -07:00
Joe Groff
03c7919b4a SIL: Add fields to SILFunctionType for substituted function types.
https://forums.swift.org/t/improving-the-representation-of-polymorphic-interfaces-in-sil-with-substituted-function-types/29711

This prepares SIL to be able to more accurately preserve the calling convention of
polymorphic generic interfaces by letting the type system represent "substituted function types".
We add a couple of fields to SILFunctionType to support this:

- A substitution map, accessed by `getSubstitutions()`, which maps the generic signature
  of the function to its concrete implementation. This will allow, for instance, a protocol
  witness for a requirement of type `<Self: P> (Self, ...) -> ...` for a concrete conforming
  type `Foo` to express its type as `<Self: P> (Self, ...) -> ... for <Foo>`, preserving the relation
  to the protocol interface without relying on the pile of hacks that is the `witness_method`
  protocol.

- A bool for whether the generic signature of the function is "implied" by the substitutions.
  If true, the generic signature isn't really part of the calling convention of the function.
  This will allow closure types to distinguish a closure being passed to a generic function, like
  `<T, U> in (*T, *U) -> T for <Int, String>`, from the concrete type `(*Int, *String) -> Int`,
  which will make it easier for us to differentiate the representation of those as types, for
  instance by giving them different pointer authentication discriminators to harden arm64e
  code.

This patch is currently NFC, it just introduces the new APIs and takes a first pass at updating
code to use them. Much more work will need to be done once we start exercising these new
fields.

This does bifurcate some existing APIs:

- SILFunctionType now has two accessors to get its generic signature.
  `getSubstGenericSignature` gets the generic signature that is used to apply its
  substitution map, if any. `getInvocationGenericSignature` gets the generic signature
  used to invoke the function at apply sites. These differ if the generic signature is
  implied.
- SILParameterInfo and SILResultInfo values carry the unsubstituted types of the parameters
  and results of the function. They now have two APIs to get that type. `getInterfaceType`
  returns the unsubstituted type of the generic interface, and
  `getArgumentType`/`getReturnValueType` produce the substituted type that is used at
  apply sites.
2019-10-25 13:38:51 -07:00
Joe Groff
89979137fc Push ArchetypeType's API down to subclasses.
And clean up code that conditionally works only with certain kinds of archetype along the way.
2018-12-12 19:45:40 -08:00
John McCall
6d4c724101 Distinguish different kinds of l-value reads in SILGen.
This is NFC for now, but I plan to build on this to (1) immediately
remove some unnecessary materialization and loads of the base value
and (2) to allow clients to load a borrowed value.
2018-08-30 19:42:53 -04:00
Joe Groff
7f14a3bf48 SILGen: Fix order of operations when invoking a mutating method on an existential that returns Self.
Delay allocating the result buffer for an opened Self return until right before it's needed. When a mutating method is invoked on an existential, the Self type won't be opened until late, when the formal access to the mutable value begins. Fixes rdar://problem/43507711.
2018-08-28 09:52:04 -07:00
Mark Lacey
85f25003ce Replace uses of getOptionalObjectType(bool &).
Instead, use the one that doesn't have a reference parameter.
2018-03-16 21:19:49 -07:00
Mark Lacey
d63bb3fc53 Remove most uses of OptionalTypeKind.
What remains are places where we are conflating optionality with
either nullability or failability.
2018-02-10 16:24:09 -08:00
Mark Lacey
b4b66bc8e8 Replace getAnyOptionalObjectType with getOptionalObjectType. 2018-02-05 23:59:00 -08:00
Michael Gottesman
8669d9300b [silgen] Change getAtUncurryLevel to return a ManagedValue and a CalleeTypeInfo.
This is in prepatation for splitting getAtUncurryLevel into one function that
returns the CalleeTypeInfo (which is needed early) and a later one that returns
a ManagedValue, which can occur later.

rdar://33358110
2017-08-27 09:10:32 -06:00
John McCall
7f22faf968 Substantially rework how SILGen handles bridging as part of laying the
ground work for the syntactic bridging peephole.

- Pass source and dest formal types to the bridging routines in addition
  to the dest lowered type.  The dest lowered type is still necessary
  in order to handle non-standard abstraction patterns for the dest type.

- Change bridging abstraction patterns to store bridged formal types
  instead of the formal type.

- Improve how SIL type lowering deals with import-as-member patterns.

- Fix some AST bugs where inadequate information was being stored in
  various expressions.

- Introduce the idea of a converting SGFContext and use it to regularize
  the existing id-as-Any conversion peephole.

- Improve various places in SILGen to emit directly into contexts.
2017-07-11 12:45:13 -04:00
John McCall
f4a181bc21 Various improvements to RValue. 2017-06-11 01:39:50 -04:00
John McCall
f7e73ccc48 Delay the formal accesses associated with inout-to-pointer and
array-to-pointer argument conversions until just before the call.

rdar://31781386
2017-04-25 03:54:49 -04:00
John McCall
e44f37fd8d Thread an enforcement kind through a few places. NFC. 2017-04-05 01:25:35 -04:00
John McCall
305c94fc5b Pare down the Initialization interface and allow implementations
to insert code before performing an in-place initialization.

Intended to be NFC, but some of the clients needed more rewriting
than others.
2017-03-31 18:55:09 -04:00
Michael Gottesman
89496492b2 [silgen] Fix a variable lifetime scoping issue.
rdar://31145255
2017-03-20 10:16:29 -07:00
Michael Gottesman
2e80412f5c [silgen] Move the creation of the allocation for foreignErrors when creating the result plan, so it is created early before we create any potential argument scopes.
rdar://30955427
2017-03-18 16:25:34 -07:00
Michael Gottesman
8723301205 [silgen] Move implementation of emitForeignErrorArgument into ResultPlan. 2017-03-18 16:06:58 -07:00
Michael Gottesman
a5747c4dbc [silgen] Create a ForiegnErrorInitiliazation plan as a first step towards eliminating special handling of foreign error parameters. 2017-03-18 15:57:46 -07:00
Michael Gottesman
f4f41337e3 [gardening] Change some CalleeTypeInfo '&' parameters to be 'const &' parameters. NFC. 2017-03-18 14:40:50 -07:00
Michael Gottesman
53eab13be8 [silgen] Move foreignErrorPreparation code in ResultPlanBuilder into a new buildTopLevelResult method.
I am going to be cleaning up some of the code here so that I can move the
creation of a temporary needed for foreign error handling earlier and move the
handling of the error parameter in general into ResultPlanBuilder.

Otherwise, the temporary is cleaned up when I pop a soon to be committed patch
that creates scopes around call sites.

rdar://30955427
2017-03-17 19:03:33 -07:00
Michael Gottesman
213ddd753f [silgen] Compute the ResultPlan outside of SILGenApply so that we can untangle indirect result/normal argument lifetime scopes.
rdar://30955427
2017-03-14 00:39:53 -07:00