Commit Graph

48 Commits

Author SHA1 Message Date
Nate Chandler
5d14610043 [SILOptimizer] Preserve arg attrs at cloning.
Arguments are copied into new cloned functions in a number of places.
Wherever that happens, be sure to transfer the attributes as well.
2022-09-26 16:55:50 -07:00
Pavel Yaskevich
41a4ceae15 [Distributed] SILOpt: Make sure that ad-hoc function does not get eliminated as unused 2022-04-18 16:53:47 -07:00
zoecarver
036361d1e4 [cxx-interop] Add SIL function representation cxx_method; Support extending C++ types.
There are three major changes here:
    1. The addition of "SILFunctionTypeRepresentation::CXXMethod".
    2. C++ methods are imported with their members *last*. Then the arguments are switched when emitting the IR for an application of the function.
    3. Clang decls are now marked as foreign witnesses.

These are all steps towards being able to have C++ protocol conformance.
2022-01-06 14:26:47 -08:00
Pavel Yaskevich
4860f90fd7 [SIL] Add new flag to SILFunction - IsDistributed
Determines whether given SILFunction represents a distributed
method or its thunk.
2021-12-17 10:52:52 -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
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
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
Michael Gottesman
6049ce629c [fso] Do not try to specialize pseudo-generic functions today.
This is just fixing an assert violation. I also needed to add support for
target-sil-opt(mock-sdk: ...) so I added support to lit for that here.

<rdar://problem/62262811>
2020-05-21 15:48:55 -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
Andrew Trick
80d502c8ef Move the FSO bailout to the beginning of the pass.
This way we catch the DeadFunctionArgs optimization too, which is a
separate sub-pass.
2020-03-17 23:35:02 -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
Michael Gottesman
df47eb2c1f [sil] Use SILNodes.def to define ARGKIND##ArrayRef instead of hard coding names.
I also changed all of the places that vended these to use SILNodes.def as well
so that when new argument kinds are added, things just work.
2019-12-02 14:39:02 -08:00
Arnold Schwaighofer
8aaa7b4dc1 SILOptimizer: Pipe through TypeExpansionContext 2019-11-11 14:21:52 -08:00
Brent Royal-Gordon
17169fc1fe Merge pull request #27950 from brentdax/dumpster-fire
[NFC] Standardize dump() methods in frontend
2019-10-31 20:36:26 -07:00
Brent Royal-Gordon
99faa033fc [NFC] Standardize dump() methods in frontend
By convention, most structs and classes in the Swift compiler include a `dump()` method which prints debugging information. This method is meant to be called only from the debugger, but this means they’re often unused and may be eliminated from optimized binaries. On the other hand, some parts of the compiler call `dump()` methods directly despite them being intended as a pure debugging aid. clang supports attributes which can be used to avoid these problems, but they’re used very inconsistently across the compiler.

This commit adds `SWIFT_DEBUG_DUMP` and `SWIFT_DEBUG_DUMPER(<name>(<params>))` macros to declare `dump()` methods with the appropriate set of attributes and adopts this macro throughout the frontend. It does not pervasively adopt this macro in SILGen, SILOptimizer, or IRGen; these components use `dump()` methods in a different way where they’re frequently called from debugging code. Nor does it adopt it in runtime components like swiftRuntime and swiftReflection, because I’m a bit worried about size.

Despite the large number of files and lines affected, this change is NFC.
2019-10-31 18:37:42 -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
Andrew Trick
bddc69c8a6 Organize SILOptimizer/Utils headers. Remove Local.h.
The XXOptUtils.h convention is already established and parallels
the SIL/XXUtils convention.

New:
- InstOptUtils.h
- CFGOptUtils.h
- BasicBlockOptUtils.h
- ValueLifetime.h

Removed:
- Local.h
- Two conflicting CFG.h files

This reorganization is helpful before I introduce more
utilities for block cloning similar to SinkAddressProjections.

Move the control flow utilies out of Local.h, which was an
unreadable, unprincipled mess. Rename it to InstOptUtils.h, and
confine it to small APIs for working with individual instructions.
These are the optimizer's additions to /SIL/InstUtils.h.

Rename CFG.h to CFGOptUtils.h and remove the one in /Analysis. Now
there is only SIL/CFG.h, resolving the naming conflict within the
swift project (this has always been a problem for source tools). Limit
this header to low-level APIs for working with branches and CFG edges.

Add BasicBlockOptUtils.h for block level transforms (it makes me sad
that I can't use BBOptUtils.h, but SIL already has
BasicBlockUtils.h). These are larger APIs for cloning or removing
whole blocks.
2019-10-02 11:34:54 -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
Nate Chandler
9567bd4341 [SILOptimizer] Alter FSO arg explosion heuristic.
The new rule is that an argument will be exploded if one of the
following sets of conditions hold:

(1) (a) Specializing the function will result in a thunk.  That is, the
        thunk that is generated cannot be inlined everywhere.
    (b) The argument has dead non-trivial leaves.
    (c) The argument has fewer than three live leaves.

(2) (a) Specializing the function will not result in a thunk.  That is,
        the thunk that is generated will be inlined everywhere and
        eliminated as dead code.
    (b) The argument has dead potentially trivial leaves.
    (c) The argument has fewer than six live leaves.

This change is based heavily on @gottesm's
https://github.com/apple/swift/pull/16756 .

rdar://problem/39957093
2019-09-24 15:59:28 -07:00
Nate Chandler
c99f12ff40 [SILOptimizer] Added option to force FSO for uncalled functions.
The new flag -sil-fso-optimize-if-not-called forced function signature
optimization to run even on functions which are not called.  Doing so is
helpful for tests to alleviate the burden of writing code to actually
call a function in whose function signature optimization we are
interested.
2019-09-20 10:12:02 -07:00
Nate Chandler
003876158c [Gardening] Made FSOEnableGenerics option static.
The command-line option for sil-fso-enable-generics was previously
visible outside the FunctionSignatureOpts translation unit.  It is not
any longer.
2019-09-20 10:08:46 -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
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
Slava Pestov
8915f96e3e SIL: Replace SILType::isTrivial(SILModule) with isTrivial(SILFunction) 2019-03-12 01:16:04 -04:00
Andrew Trick
958dd9701d Prevent FunctionSignatureOptimization from rerunning on its own thunk.
This is a bug fix that just bails out of FSO, which is exactly what we
should be doing in this case anyway.

This issue will be exposed in stdlib builds once I fix another bug in
the passmanager. Once the pass pipeline restart works as intended, we
will perform FSO on `F`, then devirtualization will discover a new
reference to `F`, causing it to be pushed back on the function pass
pipeline.
2019-02-06 13:32:27 -08:00
Michael Gottesman
23378cc16f [sil] Rename QualifiedOwnership => Ownership.
Done using Xcode's refactoring engine.
2018-12-16 15:21:52 -08:00
Arnold Schwaighofer
5f4e183302 Add [dynamically_replacable] to SILFunctions
'dynamic' functions are marked as [dynamically_replaceable].
2018-11-06 09:53:21 -08:00
Michael Gottesman
d57a88af0d [gardening] Rename references to SILPHIArgument => SILPhiArgument. 2018-09-25 22:23:34 -07:00
Michael Gottesman
03afdc5291 [caller-analysis] Reimplement CallerAnalysis ontop of findLocalApplySites.
Now the caller analysis can tell callers if it was able to find /all/ callers of
a callee.

NOTE: This does not change FSO itself yet.

rdar://41146023
2018-08-21 19:34:03 -07:00
John McCall
8613761487 Fix some edge cases when inlining coroutines.
The current inlining strategy doesn't support inlining coroutines
when there are multiple end_apply or abort_apply instructions in
the caller, so refuse to inline such cases.  Also, handle the case
where there are no yield instructions in the callee, which can
happen if e.g. the callee calls a no-return function.

I also simplified the code somewhat by removing the vestiges of the
code that tried to unify control flow with switches.

As an unrelated fix, suppress function signature optimization for
coroutines for now.
2018-08-20 19:23:11 -04:00
Michael Gottesman
f35a2a3cf8 [sil-opt] Only notify the pass manager of newly added functions in SILOptFunctionBuilder.
To do so this commit does a few different things:

1. I changed SILOptFunctionBuilder to notify the pass manager's logging
functionality when new functions are added to the module and to notify analyses
as well. NOTE: This on purpose does not put the new function on the pass manager
worklist since we do not want to by mistake introduce a large amount of
re-optimizations. Such a thing should be explicit.

2. I eliminated SILModuleTransform::notifyAddFunction. This just performed the
operations from 1. Now that SILOptFunctionBuilder performs this operation for
us, it is not needed.

3. I changed SILFunctionTransform::notifyAddFunction to just add the function to
the passmanager worklist. It does not need to notify the pass manager's logging
or analyses that a new function was added to the module since
SILOptFunctionBuilder now performs that operation. Given its reduced
functionality, I changed the name to addFunctionToPassManagerWorklist(...). The
name is a little long/verbose, but this is a feature since one should think
before getting the pass manager to rerun transforms on a function. Also, giving
it a longer name calls out the operation in the code visually, giving this
operation more prominance when reading code. NOTE: I did the rename using
Xcode's refactoring functionality!

rdar://42301529
2018-08-06 18:27:24 -07:00
Michael Gottesman
b72304415d [passmanager] Change the optimizer to use SILOptFunctionBuilder.
I am going to add the code in a bit that does the notifications. I tried to pass
down the builder instead of the pass manager. I also tried not to change the
formatting.

rdar://42301529
2018-08-05 21:21:55 -07:00
Michael Gottesman
11b24415c1 [sil-module] Create SILFunctionBuilder and hide creation/erasing functions on SILModule.
This commit does not modify those APIs or their usage. It just:

1. Moves the APIs onto SILFunctionBuilder and makes SILFunctionBuilder a friend
   of SILModule.
2. Hides the APIs on SILModule so all users need to use SILFunctionBuilder to
   create/destroy functions.

I am doing this in order to allow for adding/removing function notifications to
be enforced via the type system in the SILOptimizer. In the process of finishing
off CallerAnalysis for FSO, I discovered that we were not doing this everywhere
we need to. After considering various other options such as:

1. Verifying after all passes that the notifications were sent correctly and
   asserting. Turned out to be expensive.
2. Putting a callback in SILModule. This would add an unnecessary virtual call.

I realized that by using a builder we can:

1. Enforce that users of SILFunctionBuilder can only construct composed function
   builders by making the composed function builder's friends of
   SILFunctionBuilder (notice I did not use the word subclass, I am talking
   about a pure composition).
2. Refactor a huge amount of code in SILOpt/SILGen that involve function
   creation onto a SILGenFunctionBuilder/SILOptFunctionBuilder struct. Many of
   the SILFunction creation code in question are straight up copies of each
   other with small variations. A builder would be a great way to simplify that
   code.
3. Reduce the size of SILModule.cpp by 25% from ~30k -> ~23k making the whole
   file easier to read.

NOTE: In this commit, I do not hide the constructor of SILFunctionBuilder since
I have not created the derived builder structs yet. Once I have created those in
a subsequent commit, I will hide that constructor.

rdar://42301529
2018-07-31 10:04:03 -07:00
Bob Wilson
8e330ee344 NFC: Fix indentation around the newly renamed LLVM_DEBUG macro.
Jordan used a sed command to rename DEBUG to LLVM_DEBUG. That caused some
lines to wrap and messed up indentiation for multi-line arguments.
2018-07-21 00:56:18 -07:00
Jordan Rose
cefb0b62ba Replace old DEBUG macro with new LLVM_DEBUG
...using a sed command provided by Vedant:

$ find . -name \*.cpp -print -exec sed -i "" -E "s/ DEBUG\(/ LLVM_DEBUG(/g" {} \;
2018-07-20 14:37:26 -07:00
Mark Lacey
a5a1a63ed6 Silence a couple release build warnings about unused variables. 2018-07-12 07:52:02 -07:00
Slava Pestov
330be4a38e SILOptimizer: Remove 'unique ID' from FSO mangling 2018-07-11 15:29:45 -07:00
Adrian Prantl
fafdc510d0 Use compiler-generated location for func.-sig.-spec. thunks
Function signature specialization thunks don't have any correspondence
to code the user wrote.

rdar://problem/28859432
2018-06-27 13:14:32 -07:00
Huon Wilson
85424c0c3c [SILOptimizer] Properly disconnect the signature optimized function from a parent class.
The new function with an optimized signature _shouldn't_ have a non-trivial
classSubclassScope, even if the original function did, since the original
function (that becomes the thunk) is the symbol that serves that role.

Also part of rdar://problem/40738913
2018-06-27 12:09:14 +10:00
Huon Wilson
ed64fadb28 [SIL]/[SILOpt] Thunks and specializations shouldn't be connected to their parent class.
The "subclass scope" is meant to represent a connection to a vtable (and how
public something needs to be), for things that end up in class
vtables. Specializations and thunks are mostly internal implementation details
and do not end up there, so subclass scope is not applicable to them. This stops
the thunks and specializations being incorrectly public.

(Note, there are some thunks that _are_ public facing: if a function has its
signature optimized, the original entry point becomes a thunk, and this entry
point is what ends up in vtables etc., so needs to remain around, which means
keeping the same hacks for `private` members of an `open` class.)

Fixes rdar://problem/40738913.
2018-06-26 16:25:42 +10:00
Huon Wilson
413501b34a [SIL] Separate thunks from signature optimization from other thunks.
Signature optimization is slightly different to (most) other thunks, in that
it's taking an existing function and turning that into a thunk, rather than
creating a thunk that calls an existing function. These symbols can be public,
etc. and so need to be handled a bit different to other types of thunks.
2018-06-26 14:53:58 +10:00
Michael Gottesman
e02266d4fa [func-sig-opts][projection] All projection trees during the run on a function should share the same bump ptr allocator.
Found while reading code.
2018-06-11 20:51:26 -07:00
Michael Gottesman
bfc2dac336 [func-sig-opts] Split FunctionSignatureOpts.cpp into 3 files one for each of the operations it employs now.
This is one step along the way to splitting FSO into sub-transforms.
2018-06-04 00:49:14 -07:00
Michael Gottesman
30d4f45468 [func-sig-opts] Move FunctionSignatureOpts into the directory FunctionSignatureTransform in preparation for splitting it. 2018-06-04 00:49:14 -07:00