Commit Graph

174 Commits

Author SHA1 Message Date
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
Erik Eckstein
756c7f9c49 SILOptimizer: fix a compile time problem in the inliner
When inlining many functions in a very large basic block, the splitting of the block at the call sites is quadratic, when traversing in forward order.
Traversing backwards, fixes the problem.

rdar://problem/56268570
2020-04-07 15:00:48 +02:00
Andrew Trick
ab14c432c3 Emit inlining diagnostics as debug messages.
So -debug-only=sil-inliner is useful.
2020-03-18 11:24:11 -07:00
Michael Gottesman
e3f2bb74d2 [inliner] Add a new Inliner that only inlines AlwaysInline functions (but do not put it in the pass pipeline).
We need this anyways for -Onone and I want to do some experiments with running
this very early so I can expose more of the stdlib (modulo inlining) to the new
ownership optimizing passes.

I also changed how the inliner handles inlining around OSSA by changing it to
check early that if the caller is in ossa, then we only inline if all of the
callees that the caller calls are in ossa. The intention is to hopefully avoid
weird swings in code-size/perf due to the inliner heuristic's calculation being
artificially manipulated due to some callees not being available to inline (due
to this difference) when others are already available.
2020-03-10 19:53:18 -07:00
Erik Eckstein
2f6c9f3a28 Reinstate "Inliner: inline generic thunks which return a partial_apply.""
This reinstates commit 92a764d9f6.

rdar://problem/59061452
2020-02-25 17:49:50 +01:00
Erik Eckstein
92a764d9f6 Revert "Inliner: inline generic thunks which return a partial_apply."
This reverts commit 66474ed5a2.

The original commit triggers a crash in IRGen: rdar://problem/59456064
Reverting for now until the IRGen issue is fixed.
2020-02-14 13:48:04 +01:00
Erik Eckstein
66474ed5a2 Inliner: inline generic thunks which return a partial_apply.
The returned partial_apply of a thunk is most likely being optimized away if inlined.
Because some thunks cannot be specialized (e.g. if an opened existential is in the subsitution list), inline such thunks also in case they are generic.

https://bugs.swift.org/browse/SR-12115
rdar://problem/59061452
2020-02-12 09:36:12 +01:00
Erik Eckstein
40e5955193 SILOptimizer: rename needUpdateStackNesting (and similar) -> invalidatedStackNesting
NFC
2020-02-11 18:26:04 +01:00
zoecarver
2ca448b23d Address review comments
* add namespace
* fix block comment style
* SEMA_ATTR -> SEMANTICS_ATTR
* error when SEMANTICS_ATTR isn't defined
2019-11-02 21:58:26 -07:00
zoecarver
9c1a614efb Fix based on review comments 2019-11-02 13:07:20 -07:00
zoecarver
d4129d8659 Add def file for semantics attributes and use constants instead of cstring literals 2019-11-02 11:36:13 -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
Erik Eckstein
d07593b352 PerformanceInliner: enable generic inlining of co-routines
Co-routines are so expensive (e.g. Array.subscript.read) that it makes sense to enable generic inlining of co-routines.
This will speed up array iteration (e.g. for elem in array { }) in a generic context significantly.
Another example is ManagedBuffer.header.read, which gets much faster.
In both cases, the speedup is mainly because there is no malloc happening anymore.

https://bugs.swift.org/browse/SR-11231
rdar://problem/53777612
2019-09-09 19:18:31 +02: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
Ravi Kandhadai
bed34d65ad [SIL Inlining] Extract out a reusable code snippet in PerformanceInliner
into a utility function in SILInliner.
2019-05-03 15:00:41 -07:00
Andrew Trick
a461faf16b Fix a PerformanceInliner crash caused by a null callee signature.
This is an obvious drive-by fix. It will crash when building
Foundation after I commit changes to the pipeline. My attempts at
creating a unit test were unsuccessful because it depends on some
interaction between inlining and specialization heuristics.
2019-03-21 15:13:12 -07:00
Michael Gottesman
d0ca07b444 [perf-inliner] Do not inline non-ossa funcs into ossa transparent funcs.
This is a temporary restriction for this round of ownership work until I update
the perf pipeline for ownership.
2019-02-11 14:42:46 -08:00
Joe Shajrawi
6236fd5ffd Fix typo in PerformanceInliner 2019-02-05 14:51:26 -08:00
Erik Eckstein
767ad5e70a Inliner: fix a stack nesting problem when inlining coroutines
Beside fixing the compiler crash, this change also improves the stack-nesting correction mechanisms in the inliners:

* Instead of trying to correct the nesting after each inlining of a callee, correct the nesting once when inlining is finished for a caller function.
This fixes a potential compile time problem, because StackNesting iterates over the whole function.
In worst case this can lead to quadratic behavior in case many begin_apply instructions with overlapping stack locations are inlined.

* Because we are doing it only once for a caller, we can remove the complex logic for checking if it is necessary.
We can just do it unconditionally in case any coroutine gets inlined.
The inliners iterate over all instruction of a function anyway, so this does not increase the computational complexity (StackNesting is roughly linear with the number of instructions).

rdar://problem/47615442
2019-02-01 08:32:19 -08:00
Joe Shajrawi
18e9256e94 [PerformanceInliner] Reduce the code size impact of the exclusivity heuristic 2019-01-15 16:19:31 -08:00
Joe Shajrawi
5195e792e9 [Exclusivity] Change the exclusivity checks inline heuristic threshold 2019-01-04 14:05:23 -08:00
Adrian Prantl
ff63eaea6f Remove \brief commands from doxygen comments.
We've been running doxygen with the autobrief option for a couple of
years now. This makes the \brief markers into our comments
redundant. Since they are a visual distraction and we don't want to
encourage more \brief markers in new code either, this patch removes
them all.

Patch produced by

      for i in $(git grep -l '\\brief'); do perl -pi -e 's/\\brief //g' $i & done
2018-12-04 15:45:04 -08:00
John McCall
91a7c7635e Merge pull request #20415 from rjmccall/stdlib-borrowed-storage
Use @_borrowed on a few declarations in the stdlib and overlays
2018-11-28 21:29:27 -05:00
Andrew Trick
9c46b2a053 Fix block merging after inlining to help avoid quadratic inlining.
A recent SILCloner rewrite removed a special case hack for single
basic block callee functions:

commit c6865c0dff
Merge: 76e6c4157e 9e440d13a6
Author: Andrew Trick <atrick@apple.com>
Date:   Thu Oct 11 14:23:32 2018

    Merge pull request #19786 from atrick/silcloner-cleanup

    SILCloner and SILInliner rewrite.

Instead, the new inliner simply merges trivial unconditional branches
after inlining the return block. This way, the CFG is always in
canonical state after inlining. This is more robust, and avoids
interfering with subsequent SIL passes when non-single-block callees
are inlined.

The problem is that inlining a series of calls within a large block
could result in interleaved block splitting and merging operations,
which is quadratic in the block size. This showed up when inlining the
tens of thousands of array subscript calls emitted for a large array
initialization.

The first half of the fix is to simply defer block merging until all
calls are inlined. We can't expect SimplifyCFG to run immediately
after inlining, nor would we want to do that, *especially* for
mandatory inlining. This fix instead exposes block merging as a
trivial utility.

Note: by eliminating some unconditional branches, this change could
reduce the number of debug locations emitted. This does not
fundamentally change any debug information guarantee, and I was unable
to observe any behavior difference in the debugger.
2018-11-26 09:41:28 -08:00
Michael Gottesman
6decec6c90 [inliner] Treat inline_always as meaning truly inline_always even in situations where we have large caller CFGs.
Currently if a caller is > 400 blocks, the inliner bails out of finding
inlinable targets. This is incorrect behavior for inline always functions. In
such cases, we should continue inlining inline always functions and skip any
functions that are not inline always.

rdar://45976860
2018-11-14 18:17:06 -08:00
John McCall
d339eab30c Don't apply the -Osize heuristic when inlining coroutines.
This is a performance hack: inlining a coroutine can promote heap
allocations of the frame to stack allocations, which is valuable
out of proportion to the normal weight.  There are surely more
principled ways of getting this effect, though.
2018-11-08 12:19:24 -05:00
swift-ci
b0389af92e Merge pull request #19894 from shajrawi/inline_exclusivity 2018-10-16 14:08:19 -07:00
Joe Shajrawi
2dc1015279 [Exclusivity] Make the performance inliner aware of exclusivity checks 2018-10-16 13:06:36 -07:00
Andrew Trick
bd28b0ea1b SILCloner and SILInliner rewrite.
Mostly functionally neutral:
- may fix latent bugs.
- may reduce useless basic blocks after inlining.

This rewrite encapsulates the cloner's internal state, providing a
clean API for the CRTP subclasses. The subclasses are rewritten to use
the exposed API and extension points. This makes it much easier to
understand, work with, and extend SIL cloners, which are central to
many optimization passes. Basic SIL invariants are now clearly
expressed and enforced. There is no longer a intricate dance between
multiple levels of subclasses operating on underlying low-level data
structures. All of the logic needed to keep the original SIL in a
consistent state is contained within the SILCloner itself. Subclasses
only need to be responsible for their own modifications.

The immediate motiviation is to make CFG updates self-contained so
that SIL remains in a valid state. This will allow the removal of
critical edge splitting hacks and will allow general SIL utilities to
take advantage of the fact that we don't allow critical edges.

This rewrite establishes a simple principal that should be followed
everywhere: aside from the primitive mutation APIs on SIL data types,
each SIL utility is responsibile for leaving SIL in a valid state and
the logic for doing so should exist in one central location.

This includes, for example:
- Generating a valid CFG, splitting edges if needed.
- Returning a valid instruction iterator if any instructions are removed.
- Updating dominance.
- Updating SSA (block arguments).

(Dominance info and SSA properties are fundamental to SIL verification).

LoopInfo is also somewhat fundamental to SIL, and should generally be
updated, but it isn't required.

This also fixes some latent bugs related to iterator invalidation in
recursivelyDeleteTriviallyDeadInstructions and SILInliner. Note that
the SILModule deletion callback should be avoided. It can be useful as
a simple cache invalidation mechanism, but it is otherwise bug prone,
too limited to be very useful, and basically bad design. Utilities
that mutate should return a valid instruction iterator and provide
their own deletion callbacks.
2018-10-08 19:30:09 -07:00
Jordan Rose
737a405596 Add ModuleDecl::isOnoneSupportModule, and use it
A few places around the compiler were checking for this module by its
name. The implementation still checks by name, but at least that only
has to occur in one place.

(Unfortunately I can't eliminate the string constant altogether,
because the implicit import for SwiftOnoneSupport happens by name.)

No functionality change.
2018-09-06 16:05:16 -07:00
Brent Royal-Gordon
e289f4e586 [SILOptimizer] Fix overflow in inlining
When compiling benchmark/single-source/DictTest.swift, a multiplication can overflow in SILPerformanceInliner::isProfitableToInline(). Notice when the value is large enough to overflow and zero out the value it would have been subtracted from.
2018-08-29 22:53:40 -07: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
f500f007f8 [sil] Add a template parameter to TypeSubstCloner so that subclasses can inject a SILFunctionBuilder composition class.
This works around a potential circular dependence issue where TypeSubstCloner
needs access to SILOptFunctionBuilder but is in libswiftSIL.

rdar://42301529
2018-08-06 13:40:25 -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
Erik Little
863f3a19ff Rename @effects to @_effects
@effects is too low a level, and not meant for general usage outside
the standard library. Therefore it deserves to be underscored like
other such attributes.
2018-06-06 12:53:03 -04:00
Doug Gregor
911ed60a98 Eliminate dead code making use of SubstitutionList. 2018-05-11 17:37:27 -07:00
Doug Gregor
d457f1c752 [IRGen/SIL] More widespread use of SubstitutionMap. 2018-05-11 13:18:06 -07:00
Doug Gregor
09446defef Eliminate yet more SubstitutionLists from SIL in search of a steady-state 2018-05-11 13:18:06 -07:00
Slava Pestov
175b40919f AST: Fewer headers include Expr.h, Module.h, Stmt.h 2018-04-26 22:55:26 -07:00
Erik Eckstein
44aafd950c Tuning the inliner heuristics:
* allow small class methods to be inlined with -Osize
* inline pure calls: references to objects, which are initialized with constants, are considered as constant arguments
2018-01-19 11:32:37 -08:00
eeckstein
b126b62256 Revert "Optimization changes to completely fold OptionSet literals" 2018-01-18 22:05:07 -08:00
Erik Eckstein
8fb523e776 Tuning the inliner heuristics:
* allow small class methods to be inlined with -Osize
* inline pure calls: references to objects, which are initialized with constants, are considered as constant arguments
2018-01-18 18:27:17 -08:00
Adam Nemet
18a588ee46 Mention callee in missed inliner remark 2017-11-14 17:24:34 -08:00
Erik Eckstein
90c21be191 Unify the implementation of optimization mode in various option classes.
This commit is mostly refactoring.

*) Introduce a new OptimizationMode enum and use that in SILOptions and IRGenOptions
*) Allow the optimization mode also be specified for specific SILFunctions. This is not used in this commit yet and thus still a NFC.

Also, fixes a minor bug: we didn’t run mandatory IRGen passes for functions with @_semantics("optimize.sil.never")
2017-11-14 11:25:02 -08:00
Arnold Schwaighofer
56a1663c98 Merge pull request #12658 from rajbarik/master
Improve Osize
2017-10-30 07:23:49 -07:00
Raj Barik
c0b7cf0ff5 Expose UnrollThreshold and Inline_Benefit_reduction in the command line for automatic code size tuning 2017-10-27 10:30:23 -07:00
Adam Nemet
66085a8aef Save optimization remarks in an external YAML file
This brings the capability from clang to save remarks in an external YAML files.
YAML files can be viewed with tools like the opt-viewer.

Saving the remarks is activated with the new option -save-optimization-record.

Similarly to -emit-tbd, I've only added support for single-compile mode for now.
In this case the default filename is determined by
getOutputFilenameFromPathArgOrAsTopLevel, i.e. unless explicitly specified
with -save-optimization-record-path, the file is placed in the directory of the
main output file as <modulename>.opt.yaml.
2017-10-27 10:14:27 -07:00