Commit Graph

354 Commits

Author SHA1 Message Date
Nate Chandler
9b8828848d [SIL] Add SILFunctionType flag for async. 2020-08-19 11:29:58 -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
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
Anthony Latsis
9fd1aa5d59 [NFC] Pre- increment and decrement where possible 2020-06-01 15:39:29 +03: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
Slava Pestov
9ec80df97e SIL: Remove curried SILDeclRefs 2020-03-19 02:20:21 -04: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
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
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
Varun Gandhi
29cc1b6195 Revert "[AST] Store Clang type in SILFunctionType for @convention(c) functions."
This reverts commit 5f45820755.
2020-01-22 09:04:52 -08:00
Varun Gandhi
5f45820755 [AST] Store Clang type in SILFunctionType for @convention(c) functions. 2020-01-17 16:22:39 -08:00
Slava Pestov
47df8a1257 SILGen: Fix assert when bridging no-payload enum case to Any
It's possible for a value of a non-trivial type to have no cleanup,
if the value was constructed from a no-payload enum case. Tweak
the assert to check the value's ownership instead of checking the
type.

Fixes <https://bugs.swift.org/browse/SR-12000>, <rdar://problem/58455443>.
2020-01-14 15:31:02 -05:00
Joe Groff
0926d2380b SIL: Sink GenericContextScope into IRGen.
All the context dependencies in SIL type lowering have been eradicated, but IRGen's
type info lowering is still context-dependent and doesn't systemically pass generic
contexts around. Sink GenericContextScope bookkeeping entirely into IRGen for now.
2019-12-02 12:20:05 -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
Joe Groff
dc0f770364 remove todo warnings, oops 2019-10-26 10:49:47 -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
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
75f4625bee AST: Peel off ClangModuleLoader.h from ASTContext.h 2019-09-03 22:39:35 -04:00
Slava Pestov
2dbeeb0d3f AST: Make SubstFlags::UseErrorType the default behavior
We've fixed a number of bugs recently where callers did not expect
to get a null Type out of subst(). This occurs particularly often
in SourceKit, where the input AST is often invalid and the types
resulting from substitution are mostly used for display.

Let's fix all these potential problems in one fell swoop by changing
subst() to always return a Type, possibly one containing ErrorTypes.

Only a couple of places depended on the old behavior, and they were
easy enough to change from checking for a null Type to checking if
the result responds with true to hasError().

Also while we're at it, simplify a few call sites of subst().
2019-08-22 01:07:50 -04:00
Slava Pestov
4c499fd4ac AST: Stop passing around LazyResolvers in various places 2019-07-06 00:43:22 -04:00
Slava Pestov
fb8bd3a056 Merge pull request #24267 from slavapestov/unused-conformances
Remove per-SourceFile "used conformances" lists
2019-04-26 18:10:28 -04:00
Slava Pestov
472787bab7 SIL: isNonThrowing parameter of SILBuilder::create{Begin,}Apply() defaults to false
Also remove the overload of createApply() that does not take a SubstitutionMap.
It accomplishes nothing except creating ambiguity.
2019-04-25 22:27:38 -04:00
Saleem Abdulrasool
83b290438c Windows: bridge BOOL to Bool
This allows the conversion of the Windows `BOOL` type to be converted to
`Bool` implicitly.  The implicit bridging allows for a more ergonomic
use of the native Windows APIs in Swift.

Due to the ambiguity between the Objective C `BOOL` and the Windows
`BOOL`, we must manually map the `BOOL` type to the appropriate type.
This required lifting the mapping entry for `ObjCBool` from the mapped
types XMACRO definition into the inline definition in the importer.

Take the opportunity to simplify the mapping code.

Adjust the standard library usage of the `BOOL` type which is now
eclipsed by the new `WindowsBool` type, preferring to use `Bool`
whenever possible.

Thanks to Jordan Rose for the suggestion to do this and a couple of
hints along the way.
2019-04-25 17:52:08 -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
a5675a8edd SILGen: Fix function conversions involving DynamicSelfType
This was partially implemented but the check looked at the lowered
types and not the AST types, and DynamicSelfType is erased at the
top level of a lowered type.

Also use the new mangling for reabstraction thunks with self, to
ensure we don't emit the same symbol with two different lowered
types.

Fixes <https://bugs.swift.org/browse/SR-10309>, <rdar://problem/49703441>.
2019-04-14 19:17:32 -04:00
Slava Pestov
18e8feac8f SILGen: Kill OpaqueValueState and clean up code for opening existentials
OpaqueValueState used to store a SILValue, so back then the IsConsumable flag
was meaningful. But now we can just check if the ManagedValue has a cleanup
or not.

Also, we were passing around an opened ArchetypeType for no good reason.
2019-03-27 17:41:40 -04:00
Slava Pestov
50b1bae51f SILGen: Tidy up some code 2019-03-13 02:21:53 -04:00
Slava Pestov
568816aa91 SILGen: Always use minimal resilience expansion for the calling convention 2019-03-12 03:06:32 -04:00
Slava Pestov
8915f96e3e SIL: Replace SILType::isTrivial(SILModule) with isTrivial(SILFunction) 2019-03-12 01:16:04 -04:00
Slava Pestov
c791c4a137 SIL: SILUndef must be aware of the resilience expansion
The ownership kind is Any for trivial types, or Owned otherwise, but
whether a type is trivial or not will soon depend on the resilience
expansion.

This means that a SILModule now uniques two SILUndefs per type instead
of one, and serialization uses two distinct sentinel IDs for this
purpose as well.

For now, the resilience expansion is not actually used here, so this
change is NFC, other than changing the module format.
2019-03-12 00:30:35 -04:00
Michael Gottesman
15c03b7b0a Fix potential use-after-free in emitFuncToBlock exposed by enabling ownership verification on PrintAsObjC/blocks.swift.
If the block is guaranteed, we need to be sure to copy here. This can happen for
instance with arguments (where this was caught). I added a SILGen test that
exposes this failure since this is not an actual bug in PrintAsObjC.
2019-03-11 14:23:44 -07:00
Slava Pestov
dffa29fd0d AST: Remove a few uses of FunctionType::Param::getOldType() 2019-02-07 23:46:31 -05:00
Jordan Rose
425c190086 Restore initializing entry points for @objc convenience initializers (#21815)
This undoes some of Joe's work in 8665342 to add a guarantee: if an
@objc convenience initializer only calls other @objc initializers that
eventually call a designated initializer, it won't result in an extra
allocation. While Objective-C /allows/ returning a different object
from an initializer than the allocation you were given, doing so
doesn't play well with some very hairy implementation details of
compiled nib files (or NSCoding archives with cyclic references in
general).

This guarantee only applies to
(1) calling `self.init`
(2) where the delegated-to initializer is @objc
because convenience initializers must do dynamic dispatch when they
delegate, and Swift only stores allocating entry points for
initializers in a class's vtable. To dynamically find an initializing
entry point, ObjC dispatch must be used instead.

(It's worth noting that this patch does NOT check that the calling
initializer is a convenience initializer when deciding whether to use
ObjC dispatch for `self.init`. If we ever add peer delegation to
designated initializers, which is totally a valid feature, that should
use static dispatch and therefore should not go through objc_msgSend.)

This change doesn't /always/ result in fewer allocations; if the
delegated-to initializer ends up returning a different object after
all, the original allocation was wasted. Objective-C has the same
problem (one of the reasons why factory methods exist for things like
NSNumber and NSArray).

We do still get most of the benefits of Joe's original change. In
particular, vtables only ever contain allocating initializer entry
points, never the initializing ones, and never /both/ (which was a
thing that could happen with 'required' before).

rdar://problem/46823518
2019-01-14 13:06:50 -08:00
Slava Pestov
5ade432e6f SILGen: Emit reabtraction thunks that can capture DynamicSelfType
Fixes <https://bugs.swift.org/browse/SR-9429>.
2019-01-11 15:55:45 -05:00
Arnold Schwaighofer
cb0c53abee SIL: Remove isEscapedByUser flag on convert_escape_to_noescape instruction
It was only used for materializeForSet and is now dead code.
2019-01-04 09:21:38 -08: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
Slava Pestov
6c012b2aec AST: Remove some unnecessary LazyResolver * parameters from ASTContext methods 2018-12-07 20:39:27 -05:00
John McCall
95297f6988 Don't map Bool back to ObjCBool for SIL types in unbridged contexts.
When the Clang importer imports the components of a C function pointer
type, it generally translates foreign types into their native equivalents,
just for the convenience of Swift code working with those functions.
However, this translation must be unambiguously reversible, so (among
other things) it cannot do this when the native type is also a valid
foreign type.  Specifically, this means that the Clang importer cannot
import ObjCBool as Swift.Bool in these positions because Swift.Bool
corresponds directly to the C type _Bool.

SIL type lowering manually reverses the type-import process using
a combination of duplicated logic and an abstraction pattern which
includes information about the original Clang type that was imported.
This abstraction pattern is generally able to tell SIL type lowering
exactly what type to reverse to.  However, @convention(c) function
types may appear in positions from which it is impossible to recover
the original Clang function type; therefore the reversal must be
faithful to the proper rules.  To do this we must propagate
bridgeability just as the imported would.

This reversal system is absolutely crazy, and we should really just
- record an unbridged function type for imported declarations and
- record an unbridged function type and Clang function type for
  @convention (c) function types whenever we create them.
But for now, it's what we've got.

rdar://43656704
2018-11-30 15:23:00 -05:00
Arnold Schwaighofer
b102c7f6b4 Parser/Sema/SILGen changes for @_dynamicReplacement(for:)
Dynamic replacements are currently written in extensions as

extension ExtendedType {
  @_dynamicReplacement(for: replacedFun())
  func replacement() { }
}

The runtime implementation allows an implementation in the future where
dynamic replacements are gather in a scope and can be dynamically
enabled and disabled.

For example:

dynamic_extension_scope CollectionOfReplacements {
  extension ExtentedType {
    func replacedFun() {}
  }

  extension ExtentedType2 {
    func replacedFun() {}
  }
}

CollectionOfReplacements.enable()
CollectionOfReplacements.disable()
2018-11-06 09:58:36 -08:00
Arnold Schwaighofer
c158106329 Allow dynamic without @objc in -swift-version 5
Dynamic functions will allow replacement of their implementation at
runtime.
2018-11-06 09:53:21 -08:00
John McCall
7da688d75a Always manage subobject projections with formal-access cleanups.
To make that work, enter appropriate scopes (ArgumentScopes and
FormalEvaluationScopes) at a bunch of places.  But note that l-value
emission generally can't enter such a scope, so in generic routines
like emitOpenExistentialExpr we have to just assert that we're
already in a scope.
2018-11-03 02:14:06 -04:00
Slava Pestov
38ccddd24f Remove Swift 3 @objc behavior 2018-10-30 16:46:08 -04:00
Slava Pestov
21bcf3fdef SIL: Remove GenericEnvironment from SILConstantInfo
Most of the time we don't need it, and accessing a generic environment
on a deserialized declaration creates a GenericSignatureBuilder.
2018-09-27 09:08:43 -07:00
Slava Pestov
3b60ae153d AST: Rename AnyFunctionType::Param::getType() to getOldType() 2018-09-26 11:05:23 -07:00
Michael Gottesman
d57a88af0d [gardening] Rename references to SILPHIArgument => SILPhiArgument. 2018-09-25 22:23:34 -07:00
Joe Groff
8665342877 Merge pull request #19151 from jckarter/allocating-convenience-initializers
Dispatch initializers by their allocating entry point
2018-09-13 15:17:34 -07:00