Commit Graph

373 Commits

Author SHA1 Message Date
Alexis Laferrière
256226d35e [Serialization] Fix isUserAccessible serialization on functions only 2020-08-20 16:32:46 -07:00
Alexis Laferrière
2f7e0d496f Revert "Revert "[Serialization] Serialize isUserAccessible on functions""
This reverts commit bf25a01701.
2020-08-20 16:23:57 -07:00
Nate Chandler
9b8828848d [SIL] Add SILFunctionType flag for async. 2020-08-19 11:29:58 -07:00
Alexis Laferrière
bf25a01701 Revert "[Serialization] Serialize isUserAccessible on functions"
This reverts commit f523c88754.
2020-08-18 09:31:32 -07:00
Slava Pestov
b07a17efed Merge branch 'master' into objc-protocols-have-a-layout-constraint 2020-08-14 18:02:01 -04:00
Alexis Laferrière
f523c88754 [Serialization] Serialize the isUserAccessible bit on functions
rdar://problem/53891642
SR-7460
2020-08-14 09:50:31 -07:00
Slava Pestov
92bc89b78f GSB: Add an inferred AnyObject constraint to @objc protocol requirement signatures
This simplifies GenericSignatureImpl::requiresClass(), which no longer
has to look through the conformances of the equivalence class.
2020-08-13 00:23:47 -04:00
Yuta Saito
0ce2810144 [Serialization] Serialize subclassScope to keep linkage
subclassScope was always set as NotApplicable when deserialized but we
need to serialize and deserialize it to keep correct linkage when using
SIB

```swift
open class Visitor {
    public func visit() {
        visitExprImpl()
    }
    @_optimize(none)
    private func visitExprImpl() {
    }
}
```

In this case, `visitExprImpl` is private but subclassScope is External.
So it should be lowered as an external function at LLVM IR level.

But once it's serialized into SIB, subclassScope of `visitExprImpl` was
deserialized as NotApplicable because it was not serialized. This
mismatch makes `visitExprImpl` lowered as an internal function at LLVM
IR level.

So `subclassScope` should be serialized.
2020-08-08 14:28:12 +09:00
Erik Eckstein
755f6aa2e4 AST, SIL: Remove UTF16 encoding from StringLiteralExpr and StringLiteralInst
The UTF16 encoding is not used (anymore). I think it became obsolete with the switch to the UTF8 String representation.
2020-08-06 19:09:09 +02:00
Nate Chandler
6b28c2fe89 [SIL] Add flag to SILFunction to indicate async.
Includes boilerplate to parse and print as well as to serialize and
deserialize.
2020-08-05 16:22:48 -07:00
Doug Gregor
f6e9f352f0 [Concurrency] Add async to the Swift type system.
Add `async` to the type system. `async` can be written as part of a
function type or function declaration, following the parameter list, e.g.,

  func doSomeWork() async { ... }

`async` functions are distinct from non-`async` functions and there
are no conversions amongst them. At present, `async` functions do not
*do* anything, but this commit fully supports them as a distinct kind
of function throughout:

* Parsing of `async`
* AST representation of `async` in declarations and types
* Syntactic type representation of `async`
* (De-/re-)mangling of function types involving 'async'
* Runtime type representation and reconstruction of function types
involving `async`.
* Dynamic casting restrictions for `async` function types
* (De-)serialization of `async` function types
* Disabling overriding, witness matching, and conversions with
differing `async`
2020-07-27 18:18:03 -07:00
Michael Gottesman
d2f986739c Merge pull request #32940 from gottesmm/pr-8414ddbc369ed5bb8c0622162de920b962426cf1
[ast] Rename VarPattern -> BindingPattern.
2020-07-18 20:47:21 -07:00
Michael Gottesman
092edd6621 [ast] Rename VarPattern -> BindingPattern.
VarPattern is today used to implement both 'let' and 'var' pattern bindings, so
today is already misleading. The reason why the name Var was chosen was done b/c
it is meant to represent a pattern that performs 'variable binding'. Given that
I am going to add a new 'inout' pattern binding to this, it makes sense to
give it now a better fitting name before I make things more confusing.
2020-07-16 18:56:01 -07:00
Brent Royal-Gordon
9a838bb654 Differentiate between Swift 5 and “Swift 6” #file
In -swift-version 5 and earlier, #file will continue to be a synonym for #filePath; in a future -swift-version (“Swift 6 mode”), it will become a synonym for #fileID. #file in libraries will be interpreted according to the language mode the library was compiled in, not the language mode its client uses.

Implement this behavior, tied to a frontend flag instead of a language version. We do so by splitting the old `MagicIdentifierLiteralExprKind::File` into two separate cases, `FileIDSpelledAsFile` and `FilePathSpelledAsFile`, and propagating this distinction throughout the AST. This seems cleaner than looking up the setting for the module the declaration belongs to every time we see `File`.

This doesn’t handle module interfaces yet; we’ll take care of those in a separate commit.
2020-07-13 14:06:55 -07:00
Brent Royal-Gordon
0e569f5d9e Add support for #fileID
This temporarily breaks -enable-experimental-concise-pound-file.

fixup adding #fileID
2020-07-13 14:05:13 -07:00
Dan Zheng
bf47403162 [AutoDiff] Serialize and print @derivative and @transpose accessor kind. (#32839)
Serialize and print the optional accessor kind in `@derivative` and `@transpose`
attributes.

Resolves TF-1293.
2020-07-12 15:04:49 -07:00
Michael Gottesman
5e36ae1c7c [sil] Add a forwarding cast called unchecked_value_cast.
Today unchecked_bitwise_cast returns a value with ObjCUnowned ownership. This is
important to do since the instruction can truncate memory meaning we want to
treat it as a new object that must be copied before use.

This means that in OSSA we do not have a purely ossa forwarding unchecked
layout-compatible assuming cast. This role is filled by unchecked_value_cast.
2020-07-09 21:14:32 -07:00
Erik Eckstein
211bd71588 SIL: increase the module version number
I forgot to do that in 67605553df, which introduces the new base_addr_for_offset instruction.
2020-07-01 18:24:35 +02:00
Erik Eckstein
fce7fdc3da SIL: serialization of initializers of global variables.
This is needed for cross-module optimization: it enables constant folding of global let variables which are defined in another module.
2020-06-22 16:49:26 +02:00
Joe Groff
04c8f0df42 IRGen: Don't reify internal vtable entries that are marked overridden.
Private and internal classes shouldn't have ABI constraints on their concrete vtable layout, so if methods
don't have overrides in practice, we can elide their vtable entries.
2020-06-12 11:59:24 -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
Joe Groff
564c1a5eec Add a [nonoverridden] kind for SILVTable entries.
This will let us track class methods that must exist for pass ordering, interface, or ABI reasons, but which can
be given more efficient runtime representation because they have no overrides.
2020-06-01 12:24:18 -07:00
Hamish Knight
912baa8a8b [Serialization] Use direct operator lookup for xrefs
We don't need to look at re-exports when resolving
cross references. Luckily the old lookup logic
didn't, but the new logic will. Therefore switch
it over to calling the appropriate request for a
direct operator lookup. In addition, return a
deserialization error instead of silently
returning nullptr if the lookup fails.
2020-05-18 14:33:42 -07:00
Erik Eckstein
f5a8f600ea SIL: new instructions for copy-on-write support
* a new [immutable] attribute on ref_element_addr and ref_tail_addr
* new instructions: begin_cow_mutation and end_cow_mutation

These new instructions are intended to be used for the stdlib's COW containers, e.g. Array.
They allow more aggressive optimizations, especially for Array.
2020-05-14 08:39:54 +02:00
Robert Widmann
72807bf284 [NFC] Don't Serialize Pattern::isImplicit 2020-05-01 16:30:00 -07:00
Nate Chandler
df99de804d Added executable entry-point via @main type.
When a type (class, enum, or struct) is annotated @main, it is required
to provide a function with the following signature:

  static func main() -> ()

That function will be called when the executable the type is defined
within is launched.
2020-04-17 09:53:46 -07:00
Xi Ge
c1e1cbad85 AST: teach getOpaqueResultTypeDecl() to get result for serialized AST
TBD was missing several opaque type descriptor symbols. The root causes
are: (1) the AST API called by TBD doesn't return opaque type decl if
the decl is from a serialized AST; and (2) the access level of opaque
type decl isn't serialized so TBD considers them as internal.

This change fixes both.

rdar://61833970
2020-04-16 22:16:23 -07:00
Slava Pestov
41ccedc999 AST: Fix opaque type mangling used by type reconstruction
Make sure we mangle opaque types using the same settings as the
debugger mangling (with OptimizeProtocolNames = false) to ensure
that we can reconstruct those names again.
2020-04-10 15:05:54 -04:00
Suyash Srijan
724f8c23db [Typechecker] Implement SE-0268 Refine didSet Semantics (#26632) 2020-04-09 01:23:15 +01:00
Dan Zheng
28315487dc [AutoDiff upstream] Serialize derivative function configurations. (#30672)
Serialize derivative function configurations per module.

`@differentiable` and `@derivative` attributes register derivatives for
`AbstractFunctionDecl`s for a particular "derivative function configuration":
parameter indices and dervative generic signature.

To find `@derivative` functions registered in other Swift modules, derivative
function configurations must be serialized per module. When configurations for
a `AbstractFunctionDecl` are requested, all configurations from imported
modules are deserialized. This module serialization technique has precedent: it
is used for protocol conformances (e.g. extension declarations for a nominal
type) and Obj-C members for a class type.

Add `AbstractFunctionDecl::getDerivativeFunctionConfigurations` entry point
for accessing derivative function configurations.

In the differentiation transform: use
`AbstractFunctionDecl::getDerivativeFunctionConfigurations` to implement
`findMinimalDerivativeConfiguration` for canonical derivative function
configuration lookup, replacing `getMinimalASTDifferentiableAttr`.

Resolves TF-1100.
2020-03-27 06:40:27 -07:00
ematejska
75691d641e [AutoDiff upstream] Add linear function SIL instructions (#30638)
Add `linear_function` and `linear_function_extract` instructions.

`linear_function` creates a `@differentiable(linear)` function-typed value from
an original function operand and a transpose function operand (optional).

`linear_function_extract` extracts either the original or transpose function
value from a `@differentiable(linear)` function.

Resolves TF-1142 and TF-1143.
2020-03-26 09:41:14 -07:00
marcrasi
1be86adbfc [AutoDiff] forbid derivative registration using @differentiable (#30001)
Delete `@differentiable` attribute `jvp:` and `vjp:` arguments for derivative
registration. `@derivative` attribute is now the canonical way to register
derivatives.

Resolves TF-1001.
2020-03-24 00:41:27 -07:00
Dan Zheng
62f6686da4 Merge pull request #30579 from dan-zheng/autodiff-upstream-sil
[AutoDiff upstream] [SIL] Add differentiable function instructions.
2020-03-23 12:18:19 -07:00
Hamish Knight
a502246f34 [AST] Add OperatorFixity
Use this instead of DeclKind in a few places.
2020-03-23 09:17:58 -07:00
Dan Zheng
cc7e9fc39e [AutoDiff upstream] [SIL] Add differentiable function instructions.
Add `differentiable_function` and `differentiable_function_extract`
instructions.

`differentiable_function` creates a `@differentiable` function-typed
value from an original function operand and derivative function operands
(optional).

`differentiable_function_extract` extracts either the original or
derivative function value from a `@differentiable` function.

The differentiation transform canonicalizes `differentiable_function`
instructions, filling in derivative function operands if missing.

Resolves TF-1139 and TF-1140.
2020-03-22 23:53:43 -07:00
Slava Pestov
9ec80df97e SIL: Remove curried SILDeclRefs 2020-03-19 02:20:21 -04:00
Erik Eckstein
ae93e60072 SIL: add a lazy_property_getter flag to SILFunction
It is set on getter-functions for lazy properties.
2020-03-13 09:49:55 +01:00
Alexis Laferrière
884222e083 [Serialization] Bump swiftmodule version number
rdar://problem/60350100
2020-03-12 12:04:34 -07: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
Holly Borla
6bc15293fc [Serialization] Bump the module format version number for serialization
of typeEraser.
2020-02-28 16:46:25 -08:00
Joe Groff
eecc2173d2 Bump module format version 2020-02-24 12:14:21 -08:00
Alexis Laferrière
6a5a858408 [SPI] Serialize SPI attributes on imports 2020-02-19 14:17:14 -08:00
Alexis Laferrière
d5969a9f3a [AST] Intro SPI attribute for access control and imports 2020-02-19 14:17:08 -08:00
Michael Gottesman
1fb56db502 [ownership] Implement movable guaranteed scopes in ossa.
This patch implements movable guaranteed scopes in ossa. This pattern is
currently not generated anywhere in the compiler, but my hope is to begin
emitting these in SemanticARCOpts. The idea is that these model true phi nodes
and thus can be used to fuse multiple guaranteed scopes into one using br
instructions. This is treated similarly to how owned instructions are forwarded
through /all/ terminators. This will enable us to use the SILSSAUpdater with
guaranteed arguments as well as enable the expression of sets of borrow scopes
that minimally jointly-dominate a guaranteed argument. This will enable us to
express +0 merge points like the following:

```
bb1:
  %0a = begin_borrow %0 : $Klass
  br bb3(%0a : $Klass)

bb2:
  %1a = load_borrow %1 : $*Klass
  br bb3(%1a : $Klass)

bb3(%2 : @guaranteed $Klass)
  ...
  end_borrow %2 : $Klass
```

I describe below what the semantics of guaranteed block arguments were
previously, what they are now, and a little bit of interesting things from a
semantic perspective around implicit sub-scope users.

Before this patch in ossa, guaranteed block arguments had two different sets of
semantics:

1. Given a checked_cast_br or a switch_enum, the guaranteed block argument was
   treated like a forwarding instruction. As such, the guaranteed argument's did
   not require an end_borrow and its uses were validated as part of the use list
   of the switch_enum/checked_cast_br operand's borrow introducer. It also was
   not classified as a BorrowScopeValueIntroducer since it was not introducing a
   new scope.

2. Given any other predecessor terminator, we treated the guaranteed argument as
   a complete sub-scope of its incoming values. Thus we required the guaranteed
   argument to have its lifetime eneded by an end_borrow and that all incoming
   values of the guaranteed argument to come from a borrow introducer whose set
   of jointly post-dominating end_borrows also jointly post-dominates the set of
   end_borrows associated with the guaranteed argument itself. Consider the
   following example:

```
bb0:
  %1 = begin_borrow %foo : $Foo   // (1)
  %2 = begin_borrow %foo2 : $Foo2 // (2)
  cond_br ..., bb1, bb2

bb1:
  br bb3(%1 : $Foo)

bb2:
  br bb3(%2 : $Foo)

bb3(%3 : @guaranteed $Foo)
  ...
  end_borrow %3 : $Foo            // (3)
  end_borrow %2 : $Foo            // (4)
  end_borrow %1 : $Foo            // (5)
  ...
```

Notice how due to SSA, (1) and (2) must dominate (4) and (5) and thus must
dominate bb3, preventing the borrows from existing within bb1, bb2.

This dominance property is actively harmful to expressivity in SIL since it
means that guaranteed arguments can not be used to express (without contortion)
sil code patterns where an argument is jointly-dominated by a minimal set of
guaranteed incoming values. For instance, consider the following SIL example:

```
bb0:
  cond_br ..., bb1, bb2

bb1:
  %0 = load [copy] %globalAddr : $Foo
  br bb3(%0 : $Foo)

bb2:
  %1 = copy_value %guaranteedFunctionArg : $Foo
  br bb3(%1 : $Foo):

bb3(%2 : @owned $Foo):
  apply %useFoo(%2)
  destroy_value %2 : $Foo
```

As a quick proof: Assume the previous rules for guaranteed arguments. Then to
promote the load [copy] -> load_borrow and the copy_value to a begin_borrow, we
would need to place an end_borrow in bb3. But neither bb1 or bb2 dominates bb3,
so we would violate SSA dominance rules.

To enable SIL to express this pattern, we introduce a third rule for terminator
in ossa that applies only to branch insts. All other branches that obeyed the
previous rules (cond_br), still follow the old rule. This is not on purpose, I
am just being incremental and changing things as I need to. Specifically,
guaranteed arguments whose incoming values are defined by branch instructions
now act as a move on guaranteed values. The intuition here is that these
arguments are acting as true phis in an SSA sense and thus are just new names
for the incoming values. This implies since it is just a new name (not a
semantic change) that the guaranteed incoming value's guaranteed scopes should
be fused into one scope. The natural way to model this is by treating branch
insts as consuming guaranteed values. This then lets us express the example
above without using copies as follows:

```
bb0:
  cond_br ..., bb1, bb2

bb1:
  %0 = load_borrow %globalAddr : $Foo
  br bb3(%0 : $Foo) // consumes %0 and acts as %0's end_borrow.

bb2:
  // We need to introduce a new begin_borrow here since function
  // arguments are required to never be consumed.
  %1 = begin_borrow %guaranteedFunctionArg : $Foo
  br bb3(%1 : $Foo) // consumes %1 and acts as %1's end_borrow

// %2 continues the guaranteed scope of %0, %1. This time fused with one name.
bb3(%2 : @guaranteed $Foo):
  apply %useFoo(%2)
  // End the lifetime of %2 (which implicitly ends the lifetime of %0, %1).
  end_borrow %2 : $Foo
  ...
```

The main complication for users is that now when attempting to discover the set
of implicit users on an owned or guaranteed value caused by their usage as an
argument of a borrow introducer like begin_borrow. For those who are unaware, a
begin_borrow places an implicit requirement on its parent value that the parent
value is alive for the entire part of the CFG where this begin_borrow is
live. Previously, one could just look for the end_borrows of the
begin_borrow. Now one must additionally look for consuming branch insts. This is
because the original value that is being borrowed from must be alive over the
entire web of guaranteed values. That is the entire web of guaranteed values act
as a liveness requirement on the begin_borrow's operand.

The way this is implemented is given a use that we are validating, if the use is
a BorrowScopeOperand (1), we see if the borrow scope operand consumes the given
guaranteed scope and forwards it into a borrow scope introducer. If so, we add
the list of consuming uses of the borrow scope introducer to the worklist to
visit and then iterate.

In order to avoid working with cycles, for now, the ownership verifier bans
liveness requiring uses that have cycles in them. This still allows us to have
loop carried guaranteed values.

(1) A BorrowScopeOperand is a concept that represents an operand to a SIL
instruction that begins a guaranteed scope of some sort. All BorrowScopeOperand
are thus at a minimum able to compute a compile time the static region in which
they implicitly use their operands. NOTE: We do not require the scope to be
represented as a SILValue in the same function.

We achieve some nice benefit by introducing this. Specifically:

1. We can optimize the pattern I mentioned above. This is a common pattern in
   many frameworks that want to return a default object if a computation fails
   (with the default object usually being some sort of global or static
   var). This will let us optimize that case when the global is a let global.

2. The SSA Updater can now be used with guaranteed values without needing to
   introduce extra copies. This will enable predictable mem opts to introduce
   less copies and for semantic arc opts to optimize the remaining copies that
   PMO exposes but does not insert itself.

rdar://56720519
2020-02-17 00:29:49 -08:00
Dan Zheng
a49428ca7c [AutoDiff upstream] Add differentiability_witness_function instruction. (#29765)
The `differentiability_witness_function` instruction looks up a
differentiability witness function (JVP, VJP, or transpose) for a referenced
function via SIL differentiability witnesses.

Add round-trip parsing/serialization and IRGen tests.

Notes:
- Differentiability witnesses for linear functions require more support.
  `differentiability_witness_function [transpose]` instructions do not yet
  have IRGen.
- Nothing currently generates `differentiability_witness_function` instructions.
  The differentiation transform does, but it hasn't been upstreamed yet.

Resolves TF-1141.
2020-02-13 16:55:46 -08:00
Holly Borla
24826e01bd Merge pull request #29775 from hborla/parse-type-eraser-attribute
[Parse] Add an attribute for typeEraser.
2020-02-12 09:58:14 -08:00
Holly Borla
ffba71b889 [Parse] Add an attribute for typeEraser.
This will be used for compiler-driven type erasure for dynamic
replacement of functions with an opaque return type. For now, just
parse the attribute and ignore it.
2020-02-11 17:30:21 -08:00
Michael Gottesman
67e57f3083 [master-rebranch] Running into some weird module version issues on master-rebranch. Bumping the module version just in case. 2020-02-09 19:11:35 -08:00
Robert Widmann
f56fee839b [ModuleInterface] Pass Through Flags for Nested Types Tables
When a swift module is generated from a swift interface file, we must
remember to setup the nested types tables. Plumb the flag down from the
frontend options.

In the future, we must remove the ability to turn this off. There's
literally zero reason to have this be a configuration option anymore.

Resolves rdar://59202687 and its many, many dupes.
2020-02-07 14:37:03 -08:00