Commit Graph

293 Commits

Author SHA1 Message Date
John McCall
debc8d9ebd [NFC] Move forEachTupleElement to use a generator 2023-03-22 22:04:36 -04:00
John McCall
9ab4dc494c [NFC] Add better APIs for parallel destructuring of orig+subst types
As I've been iterating on this work, I've been gradually mulling these
over, and I think this is the way to go for now.  These should make it
a lot less cumbersome to write these kinds of traversals correctly.

The intent is to the sunset the existing expanded-components stuff
after I do a similar pass for function parameters.
2023-03-16 00:19:30 -04:00
John McCall
239777aacb Fix parameter binding for tuples containing pack expansions
More missing infrastructure.  In this case, it's really *existing*
missing infrastructure, though; we should have been imploding tuples
this way all along, given that we're doing it in the first place.

I don't like that we're doing all these extra tuple copies.  I'm not
sure yet if they're just coming out of SILGen and eliminated immediately
after in practice; maybe so.  Still, it should be obvious that they're
unnecessary.
2023-03-09 02:28:29 -05:00
John McCall
81d9e6865a Add a couple convenience APIs for working with abstraction patterns 2023-03-07 03:15:31 -05:00
John McCall
157be3420c Implement the callee side of returning a tuple containing a pack expansion.
This required quite a bit of infrastructure for emitting this kind of
tuple expression, although I'm not going to claim they really work yet;
in particular, I know the RValue constructor is going to try to explode
them, which it really shouldn't.

It also doesn't include the caller side of returns, for which I'll need
to teach ResultPlan to do the new abstraction-pattern walk.  But that's
next.
2023-03-06 04:26:18 -05:00
Kavon Farvardin
f41ed5926b implement the forget statement
Currently, this is staged in as `_forget`,
as part of SE-390. It can only be used on
`self` for a move-only type within a consuming
method or accessor. There are other rules, see
Sema for the details.

A `forget self` really just consumes self and
performs memberwise destruction of its data.
Thus, the current expansion of this statement
just reuses what we inject into the end of a
deinit.

Parsing of `forget` is "contextual".
By contextual I mean that we do lookahead to
the next token and see if it's identifier-like.
If so, then we parse it as the `forget` statement.
Otherwise, we parse it as though "forget" is an
identifier as part of some expression.

This way, we won't introduce a source break for
people who wrote code that calls a forget
function.

This should make it seamless to change it from
`_forget` to `forget` in the future.

resolves rdar://105795731
2023-02-28 21:15:17 -08:00
Hamish Knight
a40f1abaff Introduce if/switch expressions
Introduce SingleValueStmtExpr, which allows the
embedding of a statement in an expression context.
This then allows us to parse and type-check `if`
and `switch` statements as expressions, gated
behind the `IfSwitchExpression` experimental
feature for now. In the future,
SingleValueStmtExpr could also be used for e.g
`do` expressions.

For now, only single expression branches are
supported for producing a value from an
`if`/`switch` expression, and each branch is
type-checked independently. A multi-statement
branch may only appear if it ends with a `throw`,
and it may not `break`, `continue`, or `return`.

The placement of `if`/`switch` expressions is also
currently limited by a syntactic use diagnostic.
Currently they're only allowed in bindings,
assignments, throws, and returns. But this could
be lifted in the future if desired.
2023-02-01 15:30:18 +00:00
swift-ci
fd6fd76dae Merge pull request #42513 from jsoref/spelling-silgen
Spelling silgen
2022-11-09 23:28:43 -08:00
Josh Soref
9a6bf46c0f Spelling silgen
* actually
* arbitrary
* cargo-culted
* clazz
* constrained
* continuation
* coordinator
* coroutine
* derivative
* destroyer
* given
* have
* imported
* initialization
* items
* necessarily
* occurring
* omitting
* overridden
* parameter
* possible
* predecessor
* preparation
* resilience
* should
* struct
* that
* the
* throwing
* unexpectedly
* uniqueness
* using
* value
* villain

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>
2022-11-09 21:44:17 -05:00
Hamish Knight
bfa3a3f4f3 [Profiler] Avoid passing null node to loadProfilerCount
This will become an assertion failure in a future
commit.
2022-10-13 19:42:37 +01:00
Ikko Ashimine
d82d26b03f [SILGen] Fix typo in SILGenStmt.cpp
refering -> referring
2022-08-01 11:40:03 +09:00
Pavel Yaskevich
b7860ea055 [TypeChecker] Split for-in sequence into parsed and type-checked versions 2022-05-30 23:17:41 -07:00
Pavel Yaskevich
2c8bfee225 [SILGen] Unify handling of for-in and async for-in statements 2022-05-30 23:17:41 -07:00
Pavel Yaskevich
86165291aa [TypeChecker] Change the way for-in statement in type-checked
Instead of asking SILGen to build calls to `makeIterator` and
`$generator.next()`, let's synthesize and type-check them
together with the rest of for-in preamble. This greatly simplifies
interaction between Sema and SILGen for for-in statements.
2022-05-30 23:17:41 -07:00
Konrad `ktoso` Malawski
d96cb1dbaf [SIL] Allow giving debug names to SILBasicBlocks 2022-02-01 14:35:03 +09:00
Joe Groff
4d18573da0 SILGen: Continue emitting local decls after hitting a return.
Instead of short-circuiting out of emitBlockStmt if the SIL insertion point
has become unreachable (because, for instance, all paths through the function
have returned), iterate through the remaining elements and process
non-PatternBindingDecl declarations, to ensure that local functions and types
get emitted. Fixes rdar://87039628.
2022-01-10 16:16:05 -08:00
Robert Widmann
5bbd126179 Redo The Notes For "Uninhabited" Parameter Types
The use of the term 'uninhabited' does not make sense outside of formal type theoretic contexts. In Swift, we also do not use this term in a standard way - hence the term "structurally uninhabited" since we only consider products and sums eligible for the check. (Aside: We do not do exponentials because... well, Swift's type system implements Harper's "typerec" operator and as a consequence parametricity is just _not a thing_). I digress...

So, improve upon the old diagnostic in two ways:
1) Do away with 'uninhabited' - instead, mention that it's either an enum or a tuple with an enum in it that 'has no cases'
2) Since the SIL parameter convention flattens all tuples, point directly at the offending uninhabited element type

rdar://83600669
2021-09-27 20:17:28 -07:00
Adrian Prantl
8bb292e4d9 Enter a new debug scope for every let binding.
This fixes an ambiguity (that leads to a crash further down the pipeline) when
compiling optional unwrap bindings that bind the same variable name.

rdar://73490741
(cherry picked from commit 173c0b4657)
2021-09-17 08:41:39 -07:00
Joe Groff
fdc0e08d60 SILGen: Emit literal closures at the abstraction level of their context.
Literal closures are only ever directly referenced in the context of the expression they're written in,
so it's wasteful to emit them at their fully-substituted calling convention and then reabstract them if
they're passed directly to a generic function. Avoid this by saving the abstraction pattern of the context
before emitting the closure, and then lowering its main entry point's calling convention at that
level of abstraction. Generalize some of the prolog/epilog code to handle converting arguments and returns
to the correct representation for a different abstraction level.
2021-09-09 13:42:02 -07:00
Joe Groff
3abe16f40f Revert "SILGen: Emit literal closures at the abstraction level of their context. [take 2]" (#39228) 2021-09-09 11:53:43 -05:00
Joe Groff
43506a29a2 SILGen: Emit literal closures at the abstraction level of their context.
Literal closures are only ever directly referenced in the context of the expression they're written in,
so it's wasteful to emit them at their fully-substituted calling convention and then reabstract them if
they're passed directly to a generic function. Avoid this by saving the abstraction pattern of the context
before emitting the closure, and then lowering its main entry point's calling convention at that
level of abstraction. Generalize some of the prolog/epilog code to handle converting arguments and returns
to the correct representation for a different abstraction level.
2021-09-07 11:55:29 -07:00
Holly Borla
86e1014399 Revert " SILGen: Emit literal closures at the abstraction level of their context." 2021-08-18 09:03:23 -07:00
Joe Groff
309500d4bf SILGen: Emit literal closures at the abstraction level of their context.
Literal closures are only ever directly referenced in the context of the expression they're written in,
so it's wasteful to emit them at their fully-substituted calling convention and then reabstract them if
they're passed directly to a generic function. Avoid this by saving the abstraction pattern of the context
before emitting the closure, and then lowering its main entry point's calling convention at that
level of abstraction. Generalize some of the prolog/epilog code to handle converting arguments and returns
to the correct representation for a different abstraction level.
2021-08-16 09:39:19 -07:00
Holly Borla
bd80342a4b [SILGen] Record local auxiliary decls when a parameter is emitted, and
emit those auxiliary decls inside the function body brace statement.

This generalizes the old code to work for parameters to any kind of
function (e.g. initializers).
2021-08-12 13:56:05 -07:00
Robert Widmann
2c936fb7f6 Ignore All 'Unreachable' Decls That Don't Carry Expressions
We were just ignoring types here, but local functions don't matter. In
fact, if a local decl survives to SILGen, we only really care if it
carries some expression or statement itself - so pattern bindings are
the real stars here.

Re-resolves rdar://76269551 and SR-14449
2021-07-22 14:59:45 -07:00
Joe Groff
79fb05b362 Concurrency: Hop back to the previous executor after actor calls.
Tasks shouldn't normally hog the actor context indefinitely after making a call that's bound to
that actor, since that prevents the actor from potentially taking on other jobs it needs to
be able to address. Set up SILGen so that it saves the current executor (using a new runtime
entry point) and hops back to it after every actor call, not only ones where the caller context
is also actor-bound.

The added executor hopping here also exposed a bug in the runtime implementation while processing
DefaultActor jobs, where if an actor job returned to the processing loop having already yielded
the thread back to a generic executor, we would still attempt to make the actor give up the thread
again, corrupting its state.

rdar://71905765
2021-03-18 11:47:50 -07:00
Adrian Prantl
c4c99811e6 Fix a case where guard let bindings were not emitted in their own scope.
This is a follow-up to e9d557ae28.  The
debug_value for the guard let binding is introduced by SGF.emitStmtCondition(),
so we also need to enter the debug scope before running that function.

rdar://74538257
2021-02-19 18:11:00 -08:00
Erik Eckstein
ec64f2a255 SILLocation: replace CleanupLocation::get(loc) with CleanupLocation(loc)
No need to have a static get function - the constructor can be used directly.
NFC
2021-01-29 20:28:21 +01:00
Philippe Hausler
6e05240426 AsyncSequence and protocol conformance rethrows (#35224)
* Initial draft of async sequences

* Adjust AsyncSequence associated type requirements

* Add a draft implementation of AsyncSequence and associated functionality

* Correct merge damage and rename from GeneratorProtocol to AsyncIteratorProtocol

* Add AsyncSequence types to the cmake lists

* Add cancellation support

* [DRAFT] Implementation of protocol conformance rethrowing

* Account for ASTVerifier passes to ensure throwing and by conformance rethrowing verifies appropriately

* Remove commented out code

* OtherConstructorDeclRefExpr can also be a source of a rethrowing kind function

* Re-order the checkApply logic to account for existing throwing calculations better

* Extract rethrowing calculation into smaller functions

* Allow for closures and protocol conformances to contribute to throwing

* Add unit tests for conformance based rethrowing

* Restrict rethrowing requirements to only protocols marked with @rethrows

* Correct logic for gating of `@rethrows` and adjust the determinates to be based upon throws and not rethrows spelling

* Attempt to unify the async sequence features together

* Reorder try await to latest syntax

* revert back to the inout diagnosis

* House mutations in local scope

* Revert "House mutations in local scope"

This reverts commit d91f1b25b59fff8e4be107c808895ff3f293b394.

* Adjust for inout diagnostics and fall back to original mutation strategy

* Convert async flag to source locations and add initial try support to for await in syntax

* Fix case typo of MinMax.swift

* Adjust rethrowing tests to account for changes associated with @rethrows

* Allow parsing and diagnostics associated with try applied to for await in syntax

* Correct the code-completion for @rethrows

* Additional corrections for the code-completion for @rethrows this time for the last in the list

* Handle throwing cases of iteration of async sequences

* restore building XCTest

* First wave of feedback fixes

* Rework constraints checking for async sequence for-try-await-in checking

* Allow testing of for-await-in parsing and silgen testing and add unit tests for both

* Remove async sequence operators for now

* Back out cancellation of AsyncIteratorProtocols

* Restructure protocol conformance throws checking and cache results

* remove some stray whitespaces

* Correct some merge damage

* Ensure the throwing determinate for applying for-await-in always has a valid value and adjust the for-await-in silgen test to reflect the cancel changes

* Squelch the python linter for line length
2021-01-25 18:48:50 -08:00
Erik Eckstein
b7351780f7 SIL: move all the block-list modifying APIs to SILFunction.
... and remove SILFunction::getBlocks().

It's just a cleanup, NFC.
2021-01-14 17:35:31 +01:00
Varun Gandhi
a9c4f15677 Merge pull request #34979 from varungandhi-apple/vg-fix-silgen-for-loop
[SILGen] Branch on result of next() before conversion.
2021-01-12 14:54:11 -08:00
Varun Gandhi
02c4ad3850 [SILGen] Branch on result of next() before conversion.
Fixes SR-8688 (rdar://problem/47162940).
2021-01-12 09:09:48 -08:00
Slava Pestov
269818686a SILGen: Introduce a new debug scope for GuardStmts
A GuardStmt can shadow bindings from outer scopes, so make sure
we actually create a new debug scope here.

Note that we push the scope, but pop it when the next innermost
debug scope ends. To keep track of this I added a new bit of state
to the debug scope stack, indicating that this scope originated
from a GuardStmt.

Ideally, debug info would rely on ASTScope which is the canonical
source of truth for this information. For now, this is a spot fix.

I filed <rdar://problem/72954242> to track implementing the longer
term solution.

Fixes <rdar://problem/72900354>.
2021-01-11 22:47:41 -05:00
Michael Gottesman
c026e95cce [ownership] Extract out SILOwnershipKind from ValueOwnershipKind into its own type and rename Invalid -> Any.
This makes it easier to understand conceptually why a ValueOwnershipKind with
Any ownership is invalid and also allowed me to explicitly document the lattice
that relates ownership constraints/value ownership kinds.
2020-11-10 14:29:11 -08:00
Erik Eckstein
c5bbe516c7 [concurrency] SILGen: emit hop_to_executor instructions
Emit hop_to_executor instruction in the prolog of actor-isolated async functions and after all async calls in such functions.

rdar://problem/70299168
2020-11-04 09:57:40 +01:00
Josh Learn
45b670c740 [SR-13639][Diag] Don't diagnose local type declarations as unreachable
Local types can be used earlier within a scope than they were declared.
We currently diagnose these type declarations as unreachable when they
appear after a return, even though they may have been used prior to
the return statement. This change stops that diagnostic.

Resolves SR-13639, rdar://69845495
2020-10-29 15:53:49 -07:00
Suyash Srijan
6ef4b0db4b [SILGen] Emit unreachable code diagnostic for single expression closures with implicit returns too (#33604)
* [SILGen] Emit unreachable code diagnostics for single expression closures with implicit returns too

* [Test] Update diagnostic in test/SILGen/functions_uninhabited_param.swift
2020-09-21 21:58:14 +01:00
Slava Pestov
b9cd6caa72 SILGen: Emit hoisted declarations at the top level 2020-09-03 16:16:51 -04:00
Owen Voorhees
43e2d107e1 [SE-0276] Implement multi-pattern catch clauses
Like switch cases, a catch clause may now include a comma-
separated list of patterns. The body will be executed if any
one of those patterns is matched.

This patch replaces `CatchStmt` with `CaseStmt` as the children
of `DoCatchStmt` in the AST. This necessitates a number of changes
throughout the compiler, including:
- Parser & libsyntax support for the new syntax and AST structure
- Typechecking of multi-pattern catches, including those which
  contain bindings.
- SILGen support
- Code completion updates
- Profiler updates
- Name lookup changes
2020-04-04 09:28:26 -07:00
Doug Gregor
97b5a0d5fb [Type checker] Stop devirtualizing the reference to IteratorProtocol.next().
Rather than having the type checker look for the specific witness to
next() when type checking the for-each loop, which had the effect of
devirtualizing next() even when it shouldn't be, leave the formation
of the next() reference to SILGen. There, form it as a witness
reference, so that the SIL optimizer can choose whether to
devirtualization (or not).
2020-01-02 14:39:00 -08:00
Doug Gregor
f22a7e2880 [AST] Drop makeIterator reference from ForEachStmt.
Rather than having the type checker form the ConcreteDeclRef for
makeIterator, have SILGen do it, because it's fairly trivial.
Eliminates some redundant state from the AST.
2020-01-02 13:29:13 -08:00
Slava Pestov
4017a16684 Revert "SILGen: Simplify SILGenFunction::emitClosure()"
This change has a subtle impact on debug info emission and causes
a regression with a subsequent patch I'm about to commit.

This reverts commit 62d1adb409.
2019-12-19 23:51:53 -05:00
Robert Widmann
3e1a61f425 [NFC] Fold The Tri-State In Optional<ProtocolConformanceRef>
ProtocolConformanceRef already has an invalid state.  Drop all of the
uses of Optional<ProtocolConformanceRef> and just use
ProtocolConformanceRef::forInvalid() to represent it.  Mechanically
translate all of the callers and callsites to use this new
representation.
2019-10-29 16:55:56 -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
pschuh
7b9a51108a Bugfix for crasher SR-11269. (#26590) 2019-08-13 16:23:37 -07:00
Parker Schuh
687ff25157 Convert ForEachStmt to not use tc.callWitness().
For reference, everything else except string interpolation has been converted
not to call this method.
2019-06-28 14:20:42 -07:00
Azoy
4d2b5d4b2f emit apply 2019-03-31 11:54:03 -05:00
Robert Widmann
426fe886dc [SR-8272] Drop the last remnants of LogicValue
Removes the _getBuiltinLogicValue intrinsic in favor of an open-coded
struct_extract in SIL.  This removes Sema's last non-literal use of builtin
integer types and unblocks a bunch of cleanup.

This patch would be NFC, but it improves line information for conditional expression codegen.
2018-12-19 23:14:59 -05:00
Suyash Srijan
5587edf13e [silgen] fix brace indentation (again) 2018-11-26 21:59:55 +00:00
Suyash Srijan
59a5d71931 [silgen] run git-clang-format to fix all indentation issues 2018-11-26 21:57:44 +00:00