Commit Graph

727 Commits

Author SHA1 Message Date
Arnold Schwaighofer
b994bf3191 Add support for _specialize(exported: true, ...)
This attribute allows to define a pre-specialized entry point of a
generic function in a library.

The following definition provides a pre-specialized entry point for
`genericFunc(_:)` for the parameter type `Int` that clients of the
library can call.

```
@_specialize(exported: true, where T == Int)
public func genericFunc<T>(_ t: T) { ... }
```

Pre-specializations of internal `@inlinable` functions are allowed.

```
@usableFromInline
internal struct GenericThing<T> {
  @_specialize(exported: true, where T == Int)
  @inlinable
  internal func genericMethod(_ t: T) {
  }
}
```

There is syntax to pre-specialize a method from a different module.

```
import ModuleDefiningGenericFunc

@_specialize(exported: true, target: genericFunc(_:), where T == Double)
func prespecialize_genericFunc(_ t: T) { fatalError("dont call") }

```

Specially marked extensions allow for pre-specialization of internal
methods accross module boundries (respecting `@inlinable` and
`@usableFromInline`).

```
import ModuleDefiningGenericThing
public struct Something {}

@_specializeExtension
extension GenericThing {
  @_specialize(exported: true, target: genericMethod(_:), where T == Something)
  func prespecialize_genericMethod(_ t: T) { fatalError("dont call") }
}
```

rdar://64993425
2020-10-12 09:19:29 -07:00
Alexis Laferrière
39ee5916bd [SIL] Don't print availability for unreachable/unavailable functions 2020-10-09 10:40:21 -07:00
Joe Groff
a664a33b52 SIL: Add instructions to represent async suspend points.
`get_async_continuation[_addr]` begins a suspend operation by accessing the continuation value that can resume
the task, which can then be used in a callback or event handler before executing `await_async_continuation` to
suspend the task.
2020-10-01 14:21:52 -07:00
Andrew Trick
5ae231eaab Rename getFieldNo() to getFieldIndex().
Do I really need to justify this?
2020-09-24 22:44:13 -07:00
Michael Gottesman
4fa57aef13 [serialization] Refactor from large SILInstruction loop, writeNoOperandLayout handler.
NFC.
2020-09-04 18:03:33 -07:00
Yuta Saito
992c383023 [Serialization] Serialize hasCReferences to keep linkage
hasCReferences is used to determine that the function is externally
available. If a function has @_cdecl and not used from anywhere in Swift
side code, it will be emitted due to its hasCReferences. But if the
attribute is not restored from sib, it won't be emitted even if it's
used externally. So we need to serialize the attribute.
2020-08-29 02:21:49 +09:00
Nate Chandler
4145ef7a12 Revert "[SIL] Add flag to SILFunction to indicate async."
This reverts commit 6b28c2fe89.
2020-08-19 11:29:16 -07:00
Slava Pestov
4b8bbf7434 Merge pull request #33279 from kateinoigakukun/katei/serialize-subclass-scope
[Serialization] Serialize subclassScope to keep linkage
2020-08-12 15:33:20 -04:00
Max Desiatov
f74502ee9d Merge pull request #33325 from kateinoigakukun/katei/sort-diff-wt-serialization
[Serialization] Serialize Differentiability WT index sorted
2020-08-12 17:10:47 +01:00
Dan Zheng
bf2ef3934d [AutoDiff] NFC: make LinearFunctionExtractInst inherit UnaryInstructionBase. (#33418)
Remove ad-hoc operand list and operand getters.
2020-08-11 22:20:58 -07: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
Yuta Saito
d913e57d84 [Serialization] Serialize Differentiability WT index sorted
When there are sil_property and sil_differentiability_witness at once,
serialized file couldn't be deserialized because it's index table is
serialized un-sortedly but deserializer assumes that contents of table
index are sorted.

This patch fixes the un-sorted serialization and adds test case to
ensure that table index contents can be deserialized
2020-08-07 08:49:26 +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
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
67605553df SIL: a new instruction 'base_addr_for_offset' for field offset calculations.
The ``base_addr_for_offset`` instruction creates a base address for offset calculations.
The result can be used by address projections, like ``struct_element_addr``, which themselves return the offset of the projected fields.
IR generation simply creates a null pointer for ``base_addr_for_offset``.
2020-07-01 15:10:08 +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
David Zarzycki
e077b6ffd9 [SIL] NFC: Make SILVTable follow C++ and LLVM best practices
1) Convert the `Entry` type to a class with getters/setters
2) Use llvm::TrailingObjects
3) Use llvm::PointerIntPair
2020-06-11 07:51:42 -04:00
David Zarzycki
017ee7bf04 [SIL] NFC: Simplify SILVTable and save 8 bytes per SILVTable
We were not using the primary benefits of an intrusive list, namely the
ability to insert or remove from the middle of the list, so let's switch
to a plain vector. This also avoids linked-list pointer chasing.
2020-06-10 07:54:23 -04: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
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
Hamish Knight
2d9b63ed11 A SILModule Always Has An Associated Context
Now that the integrated REPL has been removed,
there is always an associated decl context, and
we can assert as such.
2020-05-10 19:56:12 -07:00
Varun Gandhi
65577940d0 [NFC] Get rid of -Wrange-loop-analysis warnings. (#31324) 2020-04-27 09:47:52 -07:00
Dan Zheng
96026575c4 [AutoDiff upstream] Upstream serialization changes. (#30720)
Upstream random serialization code from tensorflow branch:
- `SerializedSILLoader::getAllDifferentiabilityWitnesses()`
- Add diff. witness serialization for functions with `inout` parameters.
- `deserializeSILFunctionType`: fix assertion for differentiability kind.
2020-03-30 12:32:16 -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
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
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
Dan Zheng
7b064a6500 [AutoDiff upstream] Add SIL differentiability witness serialization. (#29642)
SIL differentiability witnesses are a new top-level SIL construct mapping
an "original" SIL function and derivative configuration to derivative SIL
functions.

This patch adds `SILDifferentiabilityWitness` serialization/deserialization.

Resolves TF-1136.
2020-02-07 09:35:16 -08:00
Slava Pestov
53bfc767a3 SIL: Track target formal type for casts
SIL type lowering erases DynamicSelfType, so we generate
incorrect code when casting to DynamicSelfType. Fixing this
requires a fair amount of plumbing, but most of the
changes are mechanical.

Note that the textual SIL syntax for casts has changed
slightly; the target type is now a formal type without a '$',
not a SIL type.

Also, the unconditional_checked_cast_value and
checked_cast_value_br instructions now take the _source_
formal type as well, just like the *_addr forms they are
intended to replace.
2019-11-20 21:30:28 -05:00
Michael Gottesman
7ee5ad7318 [sil] Rename {,Strong}Copy{Unowned,Unmanaged}. 2019-10-26 17:03:47 -07:00
Michael Gottesman
26a734e58e [sil] Rename ValueOwnershipKind::{Any,None} 2019-10-25 10:28:25 -07:00
Slava Pestov
3a59e7c53a SIL: Serialize availability with the SIL function, not just a weak imported flag
The weak imported flag is now only set if the attribute is unconditionally
weak linked, which is the case when it or one of its parent contexts has a
@_weakLinked attribute.

To correctly handle weak linking based availability with serialized SIL
functions, we need to serialize the actual version tuple when the SIL function
was introduced. This is because the deployment target of the client app can
be older than the deployment target that the original module was built with.

Fixes <rdar://problem/52783668>.
2019-09-06 20:08:40 -04:00
Slava Pestov
2656220222 Serialization: Simplify GenericEnvironment (de-)serialization
Now that GenericSignatures store their single unique GenericEnvironment,
we can remove similar logic from deserialization to preserve identity
of GenericEnvironments.
2019-09-06 17:16:04 -04:00
Jordan Rose
c06e105bd0 [Serialization] Switch to a better hash seed for lookup tables
...fulfilling the promised audit from 0747d9a339. No intended
functionality change /other/ than the order of already-unsorted lists.
This affected a number of SIL tests that relied on deserialization
order matching the original source order; I have no idea why the old
hash logic would make that the case. If we think that's a valuable
property, we should serialize a list of functions in addition to the
iterable table. (Maybe just in SIB mode?)
2019-08-29 09:20:18 -07:00
Jordan Rose
62f947d6ba [Serialization] Drop GenericEnvironmentID for GenericSignatureID (#26862)
A generic environment is always serialized as a GenericSignature with
a lazily-recreated environment, though sometimes it has to include
extra info specifically for generic environments used by SIL. The code
that was doing this claimed a bit for disambiguating between the two,
shrinking the permitted size of a compiled module from 2^31 bits to
2^30. (The code isn't just needlessly complicated; GenericEnvironments
used to be serialized with more information.)

Rather than have two representations for GenericEnvironmentID, this
commit just drops it altogether in favor of referencing
GenericSignatures directly.  This causes a negligible file size
shrinkage for swiftmodules in addition to eliminating the problematic
disambiguation bit.

For now, the Deserialization logic will continue to cache
GenericEnvironments that are used directly by Deserialization, but
really that should probably be done at the AST level. Then we can
simplify further to ModuleFile tracking a plain list of
GenericSignatures.
2019-08-28 09:38:19 -07:00
Doug Gregor
c8ac000fbb Record specialized signature in (SIL)SpecializeAttr.
Rather than storing the set of input requirements in a
(SIL)SpecializeAttr, store the specialized generic signature. This
prevents clients from having to rebuild the same specialized generic
signature on every use.
2019-08-26 09:54:56 -07:00
Michael Gottesman
5fc1d1d349 [ownership] Define a new instruction copy_unmanaged_value.
This provides a singular instruction for convert an unmanaged value to a ref,
then strong_retain it. I expanded the definition of UNCHECKED_REF_STORAGE to
include these copy like instructions. This instruction is valid in all SIL.

The reason why I am adding this instruction is that currently when we emit an
access to an unowned (unsafe) ivar, we use an unmanaged_to_ref and a strong
retain. This can look to the optimizer like a strong retain that can potentially
be optimized. By combining the two together into a new instruction, we can avoid
this potential problem since the pattern matching will break.
2019-08-25 21:26:40 -07:00
Erik Eckstein
32c0feb577 SIL: add a [dynamic_lifetime] flag to alloc_stack and alloc_box
This flag is set by DefinitInitialization if the lifetime of the stored value is controlled dynamically.
If the flag is set, it's not (easily) possibly to statically calculate the lifetime of the stored value.
2019-08-13 09:29:05 +02:00
Joe Groff
77b012af1d SIL: Add an [exact_self_class] function attribute.
This indicates that the "self" argument to the current function is always dynamically of the exact
static base class type, allowing metadata accesses in IRGen to use the local self metadata to answer
metadata requests for the class type. Set this attribute on allocating entry points of designated
inits, which is one of the most common places where we emit redundant metadata accesses.
2019-08-08 14:03:07 -07:00
Erik Eckstein
237a3ef77f SIL: Extend cond_fail by a second operand, which is a static string literal, indicating the failure reason. 2019-07-16 12:31:10 +02:00
Brent Royal-Gordon
d5a2912a26 Revert "Better runtime failure messages (not yet enabled by default)" 2019-07-15 13:42:40 -07:00
Erik Eckstein
e2d313ef68 SIL: Extend cond_fail by a second operand, which is a static string literal, indicating the failure reason. 2019-07-12 14:03:13 +02:00
Slava Pestov
f681cbe264 SIL: Remove SILVTable::Entry::Linkage
This field would store the linkage of the original method, if it was
distinct from the linkage of a vtable thunk. It is no longer used.
2019-06-09 15:54:05 -07:00
Doug Gregor
c02ecf9859 [SE-0258] Rename to Property Wrappers 2019-05-29 22:17:50 -07:00
Arnold Schwaighofer
c187c8ac13 SIL: Replace uses of getReferencedFunction() by getReferencedFunctionOrNull() and getInitialReferencedFunction()
With the advent of dynamic_function_ref the actual callee of such a ref
my vary. Optimizations should not assume to know the content of a
function referenced by dynamic_function_ref. Introduce
getReferencedFunctionOrNull which will return null for such function
refs. And getInitialReferencedFunction to return the referenced
function.
Use as appropriate.

rdar://50959798
2019-05-26 08:58:14 -07:00
Erik Eckstein
c957c50e28 Serialization: use the mangled class name for serializing vtables.
To distinguish between classes which have the same name (but are in different contexts).
Fixes a miscompile if classes with the same name are used from a different module.

SR-10634
rdar://problem/50538534
2019-05-11 08:30:15 -07:00