Commit Graph

173 Commits

Author SHA1 Message Date
Erik Eckstein
ef306ca9e0 SILOptimizer: fix some missing header file include directives
NFC
2021-05-26 21:57:54 +02:00
Michael Gottesman
7b55cbc669 [sil-optimizer] Make InstructionDeleter and related APIs to use an InstModCallback instead of a notification callback.
I recently have been running into the issue that many of these APIs perform the
deletion operation themselves and notify the caller it is going to delete
instead of allowing the caller to specify how the instruction is deleted. This
causes interesting semantic issues (see the loop in deleteInstruction I
simplified) and breaks composition since many parts of the optimizer use
InstModCallbacks for this purpose.

To fix this, I added a notify will be deleted construct to InstModCallback. In a
similar way to the rest of it, if the notify is not set, we do not call any code
implying that we should have good predictable performance in loops since we will
always skip the function call.

I also changed InstModCallback::deleteInst() to notify before deleting so we
have a default safe behavior. All previous use sites of this API do not care
about being notified and the only new use sites of this API are in
InstructionDeleter that perform special notification behavior (it notifies for
certain sets of instructions it is going to delete before it deletes any of
them). To work around this, I added a bool to deleteInst to control this
behavior and defaulted to notifying. This should ensure that all other use sites
still compose correctly.
2021-04-26 16:37:43 -07:00
Erik Eckstein
6ec788ff09 SIL: remove the SILOpenedArchetypesTracker
Instead, put the archetype->instrution map into SIlModule.

SILOpenedArchetypesTracker tried to maintain and reconstruct the mapping locally, e.g. during a use of SILBuilder.
Having a "global" map in SILModule makes the whole logic _much_ simpler.

I'm wondering why we didn't do this in the first place.

This requires that opened archetypes must be unique in a module - which makes sense. This was the case anyway, except for keypath accessors (which I fixed in the previous commit) and in some sil test files.
2021-04-14 08:36:10 +02:00
Slava Pestov
7ccc41a7b7 SIL: Preliminary support for 'apply [noasync]' calls
Refactor SILGen's ApplyOptions into an OptionSet, add a
DoesNotAwait flag to go with DoesNotThrow, and sink it
all down into SILInstruction.h.

Then, replace the isNonThrowing() flag in ApplyInst and
BeginApplyInst with getApplyOptions(), and plumb it
through to TryApplyInst as well.

Set the flag when SILGen emits a sync call to a reasync
function.

When set, this disables the SIL verifier check against
calling async functions from sync functions.

Finally, this allows us to add end-to-end tests for
rdar://problem/71098795.
2021-03-04 22:41:46 -05:00
Andrew Trick
ba9f52071b OSSA: simplify-cfg support for trivial block arguments.
Enable most simplify-cfg optimizations as long as the block arguments
have trivial types. Enable most simplify CFG unit tests cases.

This massively reduces the size of the CFG during OSSA passes.

Test cases that aren't supported in OSSA yet have been moved to a
separate test file for disabled OSSA tests,

Full simplify-cfg support is currently blocked on OSSA utilities which
I haven't checked in yet.
2021-02-23 22:47:59 -08:00
Andrew Trick
0c09d42447 Comment OSSA APIs makeNewValueAvailable & endLifetimeAtLeakingBlocks 2021-02-23 16:54:37 -08:00
Erik Eckstein
542a378436 SIL: add FunctionRefInst::getReferencedFunction()
If we know that we have a FunctionRefInst (and not another variant of FunctionRefBaseInst), we know that getting the referenced function will not be null (in contrast to FunctionRefBaseInst::getReferencedFunctionOrNull).

NFC
2021-02-09 19:56:43 +01:00
Meghana Gupta
ecb5d65d6d Fix lifetime of intermediate phis created by RLE
We were adjusting the lifetime of the final phi created by the
SSAUpdater. The intermediate phi's lifetime needs to be adjusted as
well.
2021-02-02 21:54:09 -08:00
Meghana Gupta
f5d47c3ba4 Fix debug location while creating instructions in RLE
The insert point may not have RegularKind debug location.
So, use an auto-generated RegularKind debug location.
2021-02-02 21:40:48 -08:00
Erik Eckstein
d33ea9f350 SIL: remove the JointPostDominanceSetComputer helper struct.
Instead make `findJointPostDominatingSet` a stand-alone function.
There is no need to keep the temporary SmallVector alive across multiple calls of findJointPostDominatingSet for the purpose of re-using malloc'ed memory. The worklist usually contains way less elements than its small size.
2021-02-02 10:20:35 +01:00
Michael Gottesman
2fad943df0 [sil-combine] Update convert_function canonicalization for ownership.
Some notes:

1. I moved the identity round-trip case to InstSimplify since that is where
   optimizations like that are.

2. I did not update in this commit the code that eliminates convert_function
   when it is only destroyed. In a subsequent commit I am going to implement
   that in a general way and apply it to all forwarding instructions.

3. I implemented eliminating convert_function with ownership only uses in a
   utility so that I can reuse it for other similar optimizations in SILCombine.
2021-01-28 12:10:16 -08:00
Erik Eckstein
e98c527319 SILOptimizer: remove the unused findApplyFromDevirtualizedResult utility function 2021-01-27 16:40:14 +01:00
Eric Miotto
8e7f9c9cbd Revert "SIL: let SingleValueInstruction only inherit from a single SILNode." 2021-01-26 10:02:24 -08:00
Erik Eckstein
5ad332f6cd SILOptimizer: remove the unused findApplyFromDevirtualizedResult utility function 2021-01-25 09:30:04 +01:00
Michael Gottesman
1e039cce38 Merge pull request #35563 from gottesmm/pr-cd7c9e97e46a0141e37f10fbfb74c094e0576ff3-followups
[ownership] cd7c9e97e4 followups
2021-01-22 19:05:12 -08:00
Michael Gottesman
f39df1d73b [sil-combine] Address comments from post-commit review of cd7c9e97e4. 2021-01-22 14:26:59 -08:00
Meghana Gupta
341facf0b3 Replace some instances of check isTrivial with check OwnershipKind::None 2021-01-21 16:27:40 -08:00
Michael Gottesman
cd7c9e97e4 [sil-combine] Fix cast optimizer based optimizations for ownership. 2021-01-20 13:19:02 -08:00
Michael Gottesman
2243ffefa4 Merge pull request #35461 from gottesmm/ossa-interior-ptr-fixup
[ownership] Implement Interior Pointer handling API for RAUWing addresses
2021-01-20 09:53:48 -08:00
Meghana Gupta
66ef200105 Enable RLE on OSSA 2021-01-17 23:39:03 -08:00
Michael Gottesman
aa38be6d98 [inst-simplify] Hide simplifyInstruction in favor of using simplifyAndReplaceAllSimplifiedUsesAndErase.
Currently all of these places in the code base perform simplifyInstruction and
then a replaceAllSimplifiedUsesAndErase(...). This is a bad pattern since:

1. simplifyInstruction assumes its result will be passed to
   replaceAllSimplifiedUsesAndErase. So by leaving these as separate things, we
   allow for users to pointlessly make this mistake.

2. I am going to implement in a subsequent commit a utility that lifetime
   extends interior pointer bases when replacing an address with an interior
   pointer derived address. To do this efficiently, I want to reuse state I
   compute during simplifyInstruction during the actual RAUW meaning that if the
   two operations are split, that is difficult without extending the API. So by
   removing this, I can make the transform and eliminate mistakes at the same
   time.
2021-01-17 20:08:24 -08:00
Michael Gottesman
1e4d3d2e97 [sil-inst-opt] Add a new utility swift::replaceSingleUse.
Given an Operand *op, this API executes op->set(newSILValue) except that:

1. If the user of op is an end scope, this API no-opts. This API is only used in
   contexts where we are rewriting uses and are not interesting in end scope
   instructions since we are moving uses from one scope to another scope.

2. If the user of op is not an end scope, but is a lifetime ending use of
   op->get(), we insert a destroy_value|end_borrow as appropriate on op->get()
   to ensure op->get()'s lifetime is still ended. We assume that if
   op->getUser() is lifetime ending, that our caller has ensured that we can end
   newValue's lifetime.
2021-01-13 10:43:41 -08:00
Michael Gottesman
1b14b5bcee [sil] Move swift::replaceAllUsesAndErase from Analysis/SimplifyInstruction -> Utils/InstOptUtils
This is a low level API already being used in multiple places besides
InstSimplify (e.x.: Utils/OwnershipOptUtils), so it makes sense to move it into
InstOptUtil.
2021-01-13 10:43:41 -08:00
Michael Gottesman
0de00d1ce4 [sil-inst-opt] Improve performance of InstModCallbacks by eliminating indirect call along default callback path.
Specifically before this PR, if a caller did not customize a specific callback
of InstModCallbacks, we would store a static default std::function into
InstModCallbacks. This means that we always would have an indirect jump. That is
unfortunate since this code is often called in loops.

In this PR, I eliminate this problem by:

1. I made all of the actual callback std::function in InstModCallback private
   and gave them a "Func" postfix (e.x.: deleteInst -> deleteInstFunc).

2. I created public methods with the old callback names to actually call the
   callbacks. This ensured that as long as we are not escaping callbacks from
   InstModCallback, this PR would not result in the need for any source changes
   since we are changing a call of a std::function field to a call to a method.

3. I changed all of the places that were escaping inst mod's callbacks to take
   an InstModCallback. We shouldn't be doing that anyway.

4. I changed the default value of each callback in InstModCallbacks to be a
   nullptr and changed the public helper methods to check if a callback is
   null. If the callback is not null, it is called, otherwise the getter falls
   back to an inline default implementation of the operation.

All together this means that the cost of a plain InstModCallback is reduced and
one pays an indirect function cost price as one customizes it further which is
better scalability.

P.S. as a little extra thing, I added a madeChange field onto the
InstModCallback. Now that we have the helpers calling the callbacks, I can
easily insert instrumentation like this, allowing for users to pass in
InstModCallback and see if anything was RAUWed without needing to specify a
callback.
2021-01-04 12:51:55 -08:00
Meghana Gupta
8431ceb586 Support MultipleValueInstruction in swift::getInsertAfterPoint 2020-12-22 22:04:58 -08:00
Michael Gottesman
c6525fd5ac [ownership] end_borrow/destroy_value with an operand that has OwnershipKind::None are trivially dead, so make isInstructionTriviallyDead return true for those cases! 2020-12-04 16:47:40 -08: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
Michael Gottesman
642a993702 [ownership] Rename Operand::isConsumingUse() -> Operand::isLifetimeEnding().
This makes it clearer that isConsumingUse() is not an owned oriented API and
returns also for instructions that end the lifetime of guaranteed values like
end_borrow.
2020-11-08 13:23:17 -08:00
Meghana Gupta
483321c360 Enable ArrayElementValuePropagation on ownership SIL 2020-11-04 11:54:47 -08:00
Slava Pestov
360e406d3a SIL: Rename SILFunction::hasSelfMetadataParam()/getSelfMetadataArgument()
These are only for class types and are related to the usage of the
DynamicSelfType, so rename them to {has,get}DynamicSelfMetadata().
2020-10-23 21:35:11 -04:00
Meghana Gupta
0a21c4d96f Fix another use-after-free in SILCombine (#34168)
* Fix another use-after-free in SILCombine

swift::endLifetimeAtFrontier also needs to use
swift::emitDestroyOperation and delete instructions via callbacks that
can correctly remove it from the worklist that SILCombine maintains

* Add test for use-after-free in SILCombine
2020-10-06 13:37:05 -07:00
Meghana Gupta
e2a9bf2009 Fix use-after-free in SILCombine (#34145)
SILCombine maintains a worklist of instructions and deleting of instructions is valid only via callbacks that remove them from the worklist as well. It calls swift::tryDeleteDeadClosure which in turn calls SILBuilder apis like emitStrongRelease/emitReleaseValue/emitDestroyValue which can delete instructions via SILInstruction::eraseFromParent leaving behind a stale entry in SILCombine's worklist causing a crash.

This PR adds swift::emitDestroyOperation which correctly calls the appropriate InstModCallbacks on added/removed instructions. This comes from swift::releasePartialApplyCapturedArg which was handling creation of destroys with callbacks correctly.
2020-10-01 20:57:40 -07:00
Andrew Trick
5ae231eaab Rename getFieldNo() to getFieldIndex().
Do I really need to justify this?
2020-09-24 22:44:13 -07:00
Brent Royal-Gordon
dd726a0015 [NFC] Avoid repeatedly instantiating std::function 2020-09-01 12:54:55 -07:00
Erik Eckstein
63c275c45f SILOptimizer: move String concatination optimization from SILCombine/ConstantFolding to StringOptimization.
This simplifies some code and it's not required to try this optimization on every run of SILCombine and ConstantPropagation.
2020-08-04 16:16:11 +02:00
Erik Eckstein
662f03ec4c SILCombine: optimize casts of existential boxes.
Optimize the unconditional_checked_cast_addr in this pattern:

   %box = alloc_existential_box $Error, $ConcreteError
   %a = project_existential_box $ConcreteError in %b : $Error
   store %value to %a : $*ConcreteError
   %err = alloc_stack $Error
   store %box to %err : $*Error
   %dest = alloc_stack $ConcreteError
   unconditional_checked_cast_addr Error in %err : $*Error to ConcreteError in %dest : $*ConcreteError

to:
   ...
   retain_value %value : $ConcreteError
   destroy_addr %err : $*Error
   store %value to %dest $*ConcreteError

This lets the alloc_existential_box become dead and it can be removed in following optimizations.
The same optimization is also done for conditional_checked_cast_addr.

There is also an implication for debugging:
Each "throw" in the code calls the runtime function swift_willThrow. The function is used by the debugger to set a breakpoint and also add hooks.
This optimization can completely eliminate a "throw", including the runtime call.
So, with optimized code, the user might not see the program to break at a throw, whereas in the source code it is actually throwing.
On the other hand, eliminating the existential box is a significant performance win and we don't guarantee any debugging behavior for optimized code anyway. So I think this is a reasonable trade-off.
I added an option "-Xllvm -keep-will-throw-call" to keep the runtime call which can be used if someone want's to reliably break on "throw" in optimized builds.

rdar://problem/66055678
2020-07-29 21:57:51 +02:00
Suyash Srijan
acf72bdf26 [SILOptimizer] Simplify 'calleesAreStaticallyKnowable' to handle both abstract functions and enum element decls (#32968) 2020-07-20 16:44:30 +01:00
Michael Gottesman
ac3109a21d [eager-specializer] Fix for ownership and add a bunch of missing code coverage for ossa.
Specifically, we were missing a bunch of coverage around specializing guaranteed
parameters and non-trivial values in general.
2020-07-09 21:46:19 -07:00
Anthony Latsis
9fd1aa5d59 [NFC] Pre- increment and decrement where possible 2020-06-01 15:39:29 +03: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
Meghana Gupta
013387eceb Update Devirtualizer's analysis invalidation (#31284)
* Update Devirtualizer's analysis invalidation

castValueToABICompatibleType can change CFG, Devirtualizer uses this api but doesn't check if it modified the cfg
2020-04-27 18:30:33 -07:00
Michael Gottesman
c3fb485c7d [sil-combine] Refactor rewriteApplyCallee -> cloneFullApplySiteReplacingCallee and move into InstOptUtils.h.
I am going to use this in mandatory combine, and it seems like a generally
useful transformation.

I also updated the routine to construct its own SILBuilder that injects a user
passed in SILBuilderContext eliminating the bad pattern of passing in
SILBuilders.

This should be an NFC change.
2020-04-23 20:33:14 -07:00
David Zarzycki
e2c4aa13ed [SILOptimizer] Do not hardcode unowned for loadable ref storage types 2020-04-17 10:40:59 -04:00
Suyash Srijan
f724d1ff85 [SE-0280] Enum cases as protocol witnesses (#28916)
* [Typechecker] Allow enum cases without payload to witness a static get-only property with Self type protocol requirement

* [SIL] Add support for payload cases as well

* [SILGen] Clean up comment

* [Typechecker] Re-enable some previously disabled witness matching code

Also properly handle the matching in some cases

* [Test] Update typechecker tests with payload enum test cases

* [Test] Update SILGen test

* [SIL] Add two FIXME's to address soon

* [SIL] Emit the enum case constructor unconditionally when an enum case is used as a witness

Also, tweak SILDeclRef::getLinkage to update the 'limit' to 'OnDemand' if we have an enum declaration

* [SILGen] Properly handle a enum witness in addMethodImplementation

Also remove a FIXME and code added to workaround the original bug

* [TBDGen] Handle enum case witness

* [Typechecker] Fix conflicts

* [Test] Fix tests

* [AST] Fix indentation in diagnostics def file
2020-03-28 10:44:01 +00:00
Meghana Gupta
8e800e49bf Recommit #29812 with fixes (#30342) 2020-03-13 19:34:16 -07:00
Rintaro Ishizaki
ccbc26d947 Revert "Use in_guaranteed for let captures (#29812)"
This reverts commit 13b9915c6f.
2020-03-10 16:08:08 -07:00
Meghana Gupta
13b9915c6f Use in_guaranteed for let captures (#29812)
* Use in_guaranteed for let captures

With this all let values will be captured with in_guaranteed convention
by the closure. Following are the main changes :

SILGen changes:
- A new CaptureKind::Immutable is introduced, to capture let values as in_guaranteed.
- SILGen of in_guaranteed capture had to be fixed.
  in_guaranteed captures as per convention are consumed by the closure. And so SILGen should not generate a destroy_addr for an in_guaranteed capture.
  But LetValueInitialization can push Dealloc and Release states of the captured arg in the Cleanup stack, and there is no way to access the CleanupHandle and disable the emission of destroy_addr while emitting the captures in SILGenFunction::emitCaptures.
  So we now create, temporary allocation of the in_guaranteed capture iduring SILGenFunction::emitCaptures without emitting destroy_addr for it.

SILOptimizer changes:
- Handle in_guaranteed in CopyForwarding.
- Adjust dealloc_stack of in_guaranteed capture to occur after destroy_addr for on_stack closures in ClosureLifetimeFixup.

IRGen changes :
  - Since HeapLayout can be non-fixed now, make sure emitSize is used conditionally
  - Don't consider ClassPointerSource kind parameter type for fulfillments while generating code for partial apply forwarder.
    The TypeMetadata of ClassPointSource kind sources are not populated in HeapLayout's NecessaryBindings. If we have a generic parameter on the HeapLayout which can be fulfilled by a ClassPointerSource, its TypeMetaData will not be found while constructing the dtor function of the HeapLayout.
    So it is important to skip considering sources of ClassPointerSource kind, so that TypeMetadata of a dependent generic parameters gets populated in HeapLayout's NecessaryBindings.
2020-03-10 12:23:02 -07:00
Erik Eckstein
43e8b07e3f GlobalOpt: improvements for constant folding global variables
* Simplified the logic for creating static initializers and constant folding for global variables: instead of creating a getter function, directly inline the constant value into the use-sites.
* Wired up the constant folder in GlobalOpt, so that a chains for global variables can be propagated, e.g.

  let a = 1
  let b = a + 10
  let c = b + 5

* Fixed a problem where we didn't create a static initializer if a global is not used in the same module. E.g. a public let variable.
* Simplified the code in general.

rdar://problem/31515927
2020-02-26 17:35:05 +01:00
Andrew Trick
14862908ef Merge pull request #28043 from zoecarver/fix/substitution-map-composition
Devirtualize calls to protocol composition type methods
2020-02-18 09:30:07 -08:00
Michael Gottesman
ae6cd35751 [ownership] Add helper method Operand::isConsumingUse() const.
This just provides a higher level of abstraction around determining if an
operand consumes its associated value needing to touch the ownership kind
map/etc.

I also refactored parts of the code base where it made sense to use this instead
of messing with the ownership kind map itself.
2020-02-13 17:58:03 -08:00