Commit Graph

566 Commits

Author SHA1 Message Date
Arnold Schwaighofer
d6d79c66aa Merge two fields into a PointerUnion in SILDeclRef to save space 2020-10-12 09:19:29 -07:00
Nate Chandler
94b5f76654 Revert "[SIL] Add SILFunctionType flag for async."
This reverts commit 9b8828848d.
2020-08-25 13:37:26 -07:00
Nate Chandler
9b8828848d [SIL] Add SILFunctionType flag for async. 2020-08-19 11:29:58 -07:00
Varun Gandhi
29188e3fe7 [AST] Update equality for ExtInfo to take Clang types into account.
In the future, we will remove the UseClangFunctionTypes language option, but we
temporarily need the scaffolding for equality checks to be consistent in all
places.
2020-07-31 13:55:55 -07:00
Varun Gandhi
f219e58ada [NFC] Refactor ExtInfo to use a builder-pattern based API.
Since the two ExtInfos share a common ClangTypeInfo, and C++ doesn't let us
forward declare nested classes, we need to hoist out AnyFunctionType::ExtInfo
and SILFunctionType::ExtInfo to the top-level.

We also add some convenience APIs on (AST|SIL)ExtInfo for frequently used
withXYZ methods. Note that all non-default construction still goes through the
builder's build() method.

We do not add any checks for invariants here; those will be added later.
2020-07-31 13:55:55 -07:00
Dan Zheng
b9341c8713 [AutoDiff] Fix protocol witness SILGen for @differentiable class methods. (#32639)
During protocol witness SILGen for `@differentiable` class methods,
replace the `AutoDiffDerivativeFunctionIdentifier` generic signature
with the witness thunk substitution map's generic signature.

Resolves TF-1180: vtable SIL verification error.
2020-07-01 08:34:18 -07:00
Arnold Schwaighofer
825a2a259b Mark non-foreign entry points of @objc dynamic methods in generic classes dynamically_replaceable
```
class Generic<T> {
  @objc dynamic func method() {}
}

extension Generic {
  @_dynamicReplacement(for:method())
  func replacement() {}
}
```

The standard mechanism of using Objective-C categories for dynamically
replacing @objc methods in generic classes does not work.

Instead we mark the native entry point as replaceable.

Because this affects all @objc methods in generic classes (whether there
is a replacement or not) by making the native entry point
`[dynamically_replaceable]` (regardless of optimization mode) we guard this by
the -enable-implicit-dynamic flag because we are late in the release cycle.

* Replace isNativeDynamic and isObjcDynamic by calls to shouldUse*Dispatch and
  shouldUse*Replacement
  This disambiguates between which dispatch method we should use at call
  sites and how these methods should  implement dynamic function
  replacement.

* Don't emit the method entry for @_dynamicReplacement(for:) of generic class
  methods
  There is not way to call this entry point since we can't generate an
  objective-c category for generic classes.

rdar://63679357
2020-06-09 09:23:29 -07:00
Dan Zheng
d3b6b89de6 [AutoDiff] Support multiple differentiability result indices in SIL. (#32206)
`DifferentiableFunctionInst` now stores result indices.
`SILAutoDiffIndices` now stores result indices instead of a source index.

`@differentiable` SIL function types may now have multiple differentiability
result indices and `@noDerivative` resutls.

`@differentiable` AST function types do not have `@noDerivative` results (yet),
so this functionality is not exposed to users.

Resolves TF-689 and TF-1256.

Infrastructural support for TF-983: supporting differentiation of `apply`
instructions with multiple active semantic results.
2020-06-05 16:25:17 -07:00
Anthony Latsis
9fd1aa5d59 [NFC] Pre- increment and decrement where possible 2020-06-01 15:39:29 +03:00
Dan Zheng
7fbfbc5dda [AutoDiff] Fix derivative forwarding thunk linkage. (#31726)
Make derivative forwarding thunks use original function's linkage instead of the
derivative function's, stripping external.

This is consistent with the linkage of differentiability witnesses.

Clarify AutoDiff linkage-related comments.

Resolves TF-1160: TBDGen error due to incorrect derivative thunk linkage.
2020-05-12 06:07:06 -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
Dan Zheng
29cc7fb5fb NFC: Remove SWIFT_ENABLE_TENSORFLOW comment.
Remove accidentally upstreamed marker comment.
2020-03-29 04:00:34 +00:00
marcrasi
495b571278 [AutoDiff upstream] Add @differentiable function reabstraction. (#30692)
Add SILGen logic for reabstracting `@differentiable` functions.

Resolves TF-1223.

Co-authored-by: Dan Zheng <danielzheng@google.com>
2020-03-28 12:27:14 -07:00
Dan Zheng
76ad4abd0a [AutoDiff upstream] Fill in derivative witness table/vtable thunks. (#30634)
Generate `differentiable_function` and `differentiable_function_extract` in
derivative witness table/vtable thunks.

`differentiation_function` is later canonicalized by the differentiation
transform.

Add SIL FileCheck tests.
2020-03-25 11:15:58 -07:00
Dan Zheng
723b2d2cbe [AutoDiff upstream] Add derivative function witness/vtable entry SILGen. (#30569)
`@differentiable` attribute on protocol requirements and non-final class
members now produces derivative function entries in witness tables and vtables.

This enables `witness_method` and `class_method` differentiation.

Existing type-checking rules:

- Witness declarations of `@differentiable` protocol requirements must have a
  `@differentiable` attribute with the same configuration (or a configuration
  with superset parameter indices).
  - Witness table derivative function entries are SILGen'd for `@differentiable`
    witness declarations.

- Class vtable derivative function entries are SILGen'd for non-final
  `@differentiable` class members.
  - These derivative entries can be overridden or inherited, just like other
    vtable entries.

Resolves TF-1212.
2020-03-22 16:59:01 -07:00
Dan Zheng
24445dd2e2 [AutoDiff upstream] Add differentiability witness SILGen. (#30545)
Generate SIL differentiability witnesses from `@differentiable` and
`@derivative` declaration attributes.

Add SILGen utilities for:
- Emiting differentiability witnesses.
- Creating derivative function thunks, which are used as entries in
  differentiability witnesses.

When users register a custom derivative function, it is necessary to create a
thunk with the expected derivative type computed from the original function's
type. This is important for consistent typing and consistent differentiability
witness entry mangling.

See `SILGenModule::getOrCreateCustomDerivativeThunk` documentation for details.

Resolves TF-1138.
2020-03-21 02:05:04 -07:00
Michael Gottesman
f3df836652 [ownership] Treat open_existential_box as an interior pointer producting instruction.
This means that it can only have a guaranteed object as an operandand that we
validate that all uses of the result address of open_existential_box occur only
within the lifetime of said object's borrow scope.
2020-03-15 23:21:45 -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
John McCall
07f03bd287 Use pattern substitutions to consistently abstract yields.
The design implemented in this patch is that we lower the types of accessors with pattern substitutions when lowering them against a different accessor, which happens with class overrides and protocol witnesses, and that we introduce pattern substitutions when substituting into a non-patterned coroutine type.  This seems to achieve consistent abstraction without introduce a ton of new complexity.

An earlier version of this patch tried to define witness thunks (conservatively, just for accessors) by simply applying the requirement substitutions directly to the requirement.  Conceptually that should work, but I ran into a lot of trouble with things that assumed that pattern substitutions didn't conceal significant substitution work.  for example, resolving a dependent member in a component type could find a new use of an opaque archetype when the code assumed that such types had already been substituted away.  So while I think that is definiteely a promising direction, I had to back that out in order to make the number of changes manageable for a single PR.

As part of this, I had to fix a number of little bugs here and there, some of which I just introduced.  One of these bugfixes is a place where the substitution code was trying to improperly abstract function types when substituting them in for a type parameter, and it's been in the code for a really long time, and I'm really not sure how it's never blown up before.

I'm increasingly of the opinion that invocation substitutions are not actually necessary, but that --- after we've solved the substitution issues above --- we may want the ability to build multiple levels of pattern substitution so that we can guarantee that e.g. witness thunks always have the exact component structure of the requirement before a certain level of substitution, thus allowing the witness substitutions to be easily extracted.
2020-03-10 01:26:31 -04:00
John McCall
ceff414820 Distinguish invocation and pattern substitutions on SILFunctionType.
In order to allow this, I've had to rework the syntax of substituted function types; what was previously spelled `<T> in () -> T for <X>` is now spelled `@substituted <T> () -> T for <X>`.  I think this is a nice improvement for readability, but it did require me to churn a lot of test cases.

Distinguishing the substitutions has two chief advantages over the existing representation.  First, the semantics seem quite a bit clearer at use points; the `implicit` bit was very subtle and not always obvious how to use.  More importantly, it allows the expression of generic function types that must satisfy a particular generic abstraction pattern, which was otherwise impossible to express.

As an example of the latter, consider the following protocol conformance:

```
protocol P { func foo() }
struct A<T> : P { func foo() {} }
```

The lowered signature of `P.foo` is `<Self: P> (@in_guaranteed Self) -> ()`.  Without this change, the lowered signature of `A.foo`'s witness would be `<T> (@in_guaranteed A<T>) -> ()`, which does not preserve information about the conformance substitution in any useful way.  With this change, the lowered signature of this witness could be `<T> @substituted <Self: P> (@in_guaranteed Self) -> () for <A<T>>`, which nicely preserves the exact substitutions which relate the witness to the requirement.

When we adopt this, it will both obviate the need for the special witness-table conformance field in SILFunctionType and make it far simpler for the SILOptimizer to devirtualize witness methods.  This patch does not actually take that step, however; it merely makes it possible to do so.

As another piece of unfinished business, while `SILFunctionType::substGenericArgs()` conceptually ought to simply set the given substitutions as the invocation substitutions, that would disturb a number of places that expect that method to produce an unsubstituted type.  This patch only set invocation arguments when the generic type is a substituted type, which we currently never produce in type-lowering.

My plan is to start by producing substituted function types for accessors.  Accessors are an important case because the coroutine continuation function is essentially an implicit component of the function type which the current substitution rules simply erase the intended abstraction of.  They're also used in narrower ways that should exercise less of the optimizer.
2020-03-07 16:25:59 -05:00
Joe Groff
b5c150287a SILGen: +1 function when converting for a reabstraction 2020-02-24 12:14:21 -08:00
Joe Groff
2b86330c2b SILGenPoly: Apply trivial argument conversions to return values too 2020-02-24 12:14:21 -08:00
Joe Groff
107686ecb7 SILGen: Handle function conversions in reabstraction thunks 2020-02-24 12:14:21 -08:00
Joe Groff
45e941c23a SILGen: Apply substitutions before bridging or thunking.
Even if differently-substituted function types have different value representations,
we can still share reabstraction and bridging thunks among types that are equivalent after
substitution, so handle these by generating thunks in terms of the unsubstituted type and
converting to the needed substitution form at the use site.
2020-02-24 12:14:21 -08:00
Slava Pestov
c5718d5b18 SILGen: Fix crash with function conversions involving class-constrained protocols
If a protocol has a superclass constraint, the existential type can be
upcast to the class type given by the constraint. This wasn't implemented
in the function conversion code path, leading to a crash.

Fixes <https://bugs.swift.org/browse/SR-12018> / <rdar://problem/58861162>.
2020-02-06 19:48:03 -05: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
Slava Pestov
377d22e757 SILGen: Use the correct generic environment in vtable thunks
Make sure we use the generic environment derived from the
generic signature of the vtable thunk itself, which can now
be different than the generic signature of the derived
method.

This allows vtable thunks that re-abstract generic requirements
to lower all the way through to IRGen.
2020-01-08 22:19:15 -05:00
Joe Groff
351c94dbf2 SIL: Distinguish "compatible convention" and "compatible representation" function conversions.
We want to be able to use different representations for function types with otherwise compatible
calling conventions. Distinguish these concepts in the `checkForABIDifferences` SIL APIs, so that
we correctly handle representation-only conversions, which can be handled by `convert_function`,
from full reabstractions, making sure to note that the representation-only case is not transitive
for function arguments, since a function that takes a function with a representation change needs
a thunk to change the argument's representation.
2019-12-03 11:35:48 -08:00
Joe Groff
5140174eb5 SIL: Plumb abstraction patterns through type lowering.
Lowering a SIL type should be a pure function of the formal type of a value and the
abstraction pattern it's being lowered against, but we historically did not carry
enough information in abstraction patterns to lower generic parameter types, so we
relied on a generic context signature that would be pushed and popped before lowering
interface types. This patch largely eliminates the necessity for that, by making it
so that `TypeClassifierBase` and its subclasses now take an `AbstractionPattern`
all the way down, and fixing up the visitor logic so that it derives appropriate
abstraction patterns for tuple elements, function arguments, and aggregate fields too.
This makes it so that type lowering is independent of the current generic context.
(Unfortunately, there are still places scattered across the code where we use the
current generic context in order to build abstraction patterns that we then feed
into type lowering, so we can't yet completely eliminate the concept.)

This then enables us to integrate substituted function type construction into type
lowering as well, since we can now lower a generic parameter type against an
abstraction pattern without that generic parameter having to be tied to the same
generic signature (or any generic signature at all, which in the case of a
substituted function type hasn't necessarily even been finalized yet.)
2019-12-02 12:15:56 -08:00
Arnold Schwaighofer
33f4f57cc4 SILGen: Add TypeExpansionContext to SILGen 2019-11-11 14:21:52 -08:00
Robert Widmann
b849e51768 Use operator bool to claw back some readability 2019-10-29 16:56:21 -07:00
Robert Widmann
37e82a6133 [NFC] getWitnessMethodConformanceOrNone -> getWitnessMethodConformanceOrInvalid 2019-10-29 16:56:20 -07: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
Saleem Abdulrasool
3ced35855e Merge pull request #27897 from apple/remove-todo-wip
remove todo warnings, oops
2019-10-26 13:49:06 -07:00
Joe Groff
dc0f770364 remove todo warnings, oops 2019-10-26 10:49:47 -07:00
Joe Groff
1a1d9e63f7 Merge pull request #27887 from jckarter/subst-sil-function-type-interface
SIL: Add fields to SILFunctionType for substituted function types.
2019-10-26 10:44:48 -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
Michael Gottesman
26a734e58e [sil] Rename ValueOwnershipKind::{Any,None} 2019-10-25 10:28:25 -07:00
Robert Widmann
5a8d0744c3 [NFC] Adopt TypeBase-isms for GenericSignature
Structurally prevent a number of common anti-patterns involving generic
signatures by separating the interface into GenericSignature and the
implementation into GenericSignatureBase.  In particular, this allows
the comparison operators to be deleted which forces callers to
canonicalize the signature or ask to compare pointers explicitly.
2019-09-30 14:04:36 -07:00
Slava Pestov
1e94466bcc AST: Replace GenericSignature::createGenericEnvironment() with getGenericEnvironment()
This memoizes the result, which is fine for all callers; the only
exception is open existential types where each new open existential
now explicitly gets a unique generic environment, allocated by
calling GenericEnvironment::getIncomplete().
2019-09-06 17:16:03 -04:00
Doug Gregor
0e2bb0fbe2 Prune includes of GenericSignatureBuilder.h. 2019-08-26 09:54:20 -07:00
Doug Gregor
4685f9dd0d [SILGen] Use abstract generic signature request for reabstraction thunks 2019-08-26 09:54:19 -07:00
Slava Pestov
8f22da205a Sema: Stop wrapping Self returns in protocols with DynamicSelfType 2019-06-26 01:10:11 -04:00
Slava Pestov
a31248997c SILGen: Correctly emit vtables when an override is more visible than the base
If an override B.f() is more visible than a base method A.f(), it is
possible that an override C.f() of B.f() cannot see the original method
A.f().

In this case, we would encounter linker errors if we referenced the
method descriptor or method dispatch thunk for A.f().

Make this work by treating B.f() as the least derived method in this
case, and ensuring that the vtable thunk for B.f() dispatches through
the vtable again.

Fixes <rdar://problem/48330571>, <https://bugs.swift.org/browse/SR-10648>.
2019-06-01 00:08:05 -04:00
Slava Pestov
b4487348d0 SILGen: Support vtable thunks for 'modify' accessors
When checking if a vtable override is ABI compatible with the
base class method, make sure to check yields too.

Also, add support for coroutines to vtable thunks, using code
that I've copy and pasted and tweaked from witness thunks.

(It would be nice to combine witness thunks and vtable thunks
into a single code path for 'method thunks', but that requires
some additional refactoring, so live with the copy and paste
for now).
2019-06-01 00:08:05 -04:00
Michael Gottesman
179251d167 [sil-combine] Do not perform existential type propagation on @in parameters when we have a copy of the underlying value.
Otherwise, we may get use-after-frees as in the added test.

rdar://50609145
2019-05-09 23:01:43 -07:00
Michael Gottesman
580ca729d3 [silgen] Always ensure that we have a +1 value when emitting reabstraction thunks.
The machinery assumes that it will always have a +1 value. I am attempting to do
the minimal fix here for cherry-picking purposes.

There isn't a test case with this commit since the immutable address verifier
(in the next commit) verifies that this is done correctly. The specific test
that will trip is vtable_thunks_reabstraction.swift.

rdar://50212579
2019-05-09 14:57:39 -07:00
Slava Pestov
9a1abf705a SILGen: Remove SILGenSILBuilder
This reverts commit 59cc3c1216fbb1719e5357dcef3f8b249528fc74.
2019-04-25 02:06:14 -04:00
Slava Pestov
8a74e52273 SILGen: Add post-processing pass to lazily emit ClangImproter-synthesized conformances 2019-04-25 02:05:20 -04:00
Slava Pestov
099bd8e055 SILGen: Fix withoutActuallyEscaping for DynamicSelfType
We can reuse the same logic that we have for reabstraction thunks here.
2019-04-14 20:13:49 -04:00