Commit Graph

60 Commits

Author SHA1 Message Date
Meghana Gupta
4561658799 Avoid creating unoptimizable copies in CSE
CSE uses OSSA rauw which creates copies and copies that are created to optimize
across borrow scopes are unoptimizable. This PR avoids this situation for now.
2025-02-19 11:20:43 -08:00
Meghana Gupta
2c256180ce Add new utility swift::areUsesWithinValueLifetime 2025-01-10 16:15:50 -08:00
Erik Eckstein
48b913af4b Optimizer: make the hasOwnershipOperandsOrResults utility available in OwnershipOptUtils 2025-01-02 10:42:01 +01:00
Erik Eckstein
09a5a4487a Optimizer: add a utility to replaces phis with the unique incoming values if all incoming values are the same
This is needed after running the SSAUpdater for an existing OSSA value, because the updater can
insert unnecessary phis in the middle of the original liverange which breaks up the original
liverange into smaller ones:

```
   %1 = def_of_owned_value
   %2 = begin_borrow %1
   ...
   br bb2(%1)
 bb2(%3 : @owned $T): // inserted by SSAUpdater
   ...
   end_borrow %2      // use after end-of-lifetime!
   destroy_value %3
```

It's not needed to run this utility if SSAUpdater is used to create a _new_ OSSA liverange.
2024-12-12 08:57:57 +01:00
Erik Eckstein
51e3e5ed80 Optimizer: rename BorrowArgumentsUpdater -> GuaranteedPhiUpdater
NFC
2024-11-12 09:26:59 +01:00
Erik Eckstein
8462459f07 Optimizer: re-compute the re-borrow flags of phi arguments in updateAllBorrowArguments and updateBorrowArguments 2024-11-12 09:26:59 +01:00
Erik Eckstein
6b8c6a3c3b SIL: rename updateBorrowedFrom to updateBorrowArguments
NFC
2024-11-12 09:26:58 +01:00
Erik Eckstein
e14c1d1f62 SIL, Optimizer: update and handle borrowed-from instructions
Compute, update and handle borrowed-from instruction in various utilities and passes.
Also, used borrowed-from to simplify `gatherBorrowIntroducers` and `gatherEnclosingValues`.
Replace those utilities by `Value.getBorrowIntroducers` and `Value.getEnclosingValues`, which return a lazily computed Sequence of borrowed/enclosing values.
2024-04-10 13:38:10 +02:00
Ben Barham
ef8825bfe6 Migrate llvm::Optional to std::optional
LLVM has removed llvm::Optional, move over to std::optional. Also
clang-format to fix up all the renamed #includes.
2024-02-21 11:20:06 -08:00
Evan Wilde
f3ff561c6f [NFC] add llvm namespace to Optional and None
This is phase-1 of switching from llvm::Optional to std::optional in the
next rebranch. llvm::Optional was removed from upstream LLVM, so we need
to migrate off rather soon. On Darwin, std::optional, and llvm::Optional
have the same layout, so we don't need to be as concerned about ABI
beyond the name mangling. `llvm::Optional` is only returned from one
function in
```
getStandardTypeSubst(StringRef TypeName,
                     bool allowConcurrencyManglings);
```
It's the return value, so it should not impact the mangling of the
function, and the layout is the same as `std::optional`, so it should be
mostly okay. This function doesn't appear to have users, and the ABI was
already broken 2 years ago for concurrency and no one seemed to notice
so this should be "okay".

I'm doing the migration incrementally so that folks working on main can
cherry-pick back to the release/5.9 branch. Once 5.9 is done and locked
away, then we can go through and finish the replacement. Since `None`
and `Optional` show up in contexts where they are not `llvm::None` and
`llvm::Optional`, I'm preparing the work now by going through and
removing the namespace unwrapping and making the `llvm` namespace
explicit. This should make it fairly mechanical to go through and
replace llvm::Optional with std::optional, and llvm::None with
std::nullopt. It's also a change that can be brought onto the
release/5.9 with minimal impact. This should be an NFC change.
2023-06-27 09:03:52 -07:00
Andrew Trick
91c4efea95 Move the LoadOperation abstraction to InstructionUtils.h
This is a fundamental abstraction over loads. It was in
OwnershipOptUtils because load_borrow happens to be restricted by
OSSA. Passes should not include OwnershipOptUtils just because they
work with loads.
2023-05-15 15:20:57 -07:00
Nate Chandler
f952b0cc7e [PrunedLiveness] Removed invalidate.
The method doesn't do what clients expect.
2023-05-02 11:51:53 -07:00
Andrew Trick
ae64ff5cb0 Rename PrunedLiveness.clear() to invalidate()
Because SILBitfield cannot be cleared.
2023-03-22 01:36:48 -07:00
Andrew Trick
15796e3ff9 PrunedLiveness: add a SILFunction argument
So that liveness can migrate to using a SILBitfield.
2023-03-22 01:36:48 -07:00
Andrew Trick
13e1aa4467 Add OwnershipLiveness utilities
Encapsulate all the complexity of reborrows and guaranteed phi in 3
ownership liveness interfaces:

LinerLiveness, InteriorLiveness, and ExtendedLiveness.
2023-02-10 09:39:18 -08:00
Allan Shortlidge
4f8d33ffb5 SILOptimizer: Break circular dependency with SIL library by moving extendStoreBorrow(). 2022-10-27 15:29:37 -07:00
Andrew Trick
04aa16f97d OSSA: CheckedCastBrJumpThreading: support using RAUW utility.
Begin adding support for OSSA to checked-cast jump-threading based on
the new ownership utilities.

TODO:

Finish migrating to the new utilities in OwnershipOptUtils.

Ensure full unit test coverage.
2022-10-22 21:57:47 -07:00
Andrew Trick
40e03ef782 Update passes to use SSAPrunedLiveness or MultiDefPrunedLiveness 2022-10-04 13:27:47 -07:00
Andrew Trick
ca503b54b7 Redesign PrunedLiveness APIs, introducing live ranges
First restore the basic PrunedLiveness abstraction to its original
intention. Move code outside of the basic abstraction that polutes the
abstraction and is fundamentally wrong from the perspective of the
liveness abstraction.

Most clients need to reason about live ranges, including the def
points, not just liveness based on use points. Add a PrunedLiveRange
layer of types that understand where the live range is
defined. Knowing where the live range is defined (the kill set) helps
reliably check that arbitrary points are within the boundary. This
way, the client doesn't need to be manage this on its own. We can also
support holes in the live range for non-SSA liveness. This makes it
safe and correct for the way liveness is now being used. This layer
safety handles:

- multiple defs
- instructions that are both uses and defs
- dead values
- unreachable code
- self-loops

So it's no longer the client's responsibility to check these things!

Add SSAPrunedLiveness and MultiDefPrunedLiveness to safely handle each
situation.

Split code that I can't figure out into
DiagnosticPrunedLiveness. Hopefully it will be deleted soon.
2022-10-04 13:27:44 -07:00
Josh Soref
730b16c569 Spelling siloptimizer
* access
* accessed
* accesses
* accessor
* acquiring
* across
* activated
* additive
* address
* addresses'
* aggregated
* analysis
* and
* appropriately
* archetype
* argument
* associated
* availability
* barriers
* because
* been
* beginning
* belongs
* beneficial
* blocks
* borrow
* builtin
* cannot
* canonical
* canonicalize
* clazz
* cleanup
* coalesceable
* coalesced
* comparisons
* completely
* component
* computed
* concrete
* conjunction
* conservatively
* constituent
* construct
* consuming
* containing
* covered
* creates
* critical
* dataflow
* declaration
* defined
* defining
* definition
* deinitialization
* deliberately
* dependencies
* dependent
* deserialized
* destroy
* deterministic
* deterministically
* devirtualizes
* diagnostic
* diagnostics
* differentiation
* disable
* discipline
* dominate
* dominates
* don't
* element
* eliminate
* eliminating
* elimination
* embedded
* encounter
* epilogue
* epsilon
* escape
* escaping
* essential
* evaluating
* evaluation
* evaluator
* executing
* existential
* existentials
* explicit
* expression
* extended
* extension
* extract
* for
* from
* function
* generic
* guarantee
* guaranteed
* happened
* heuristic
* however
* identifiable
* immediately
* implementation
* improper
* include
* infinite
* initialize
* initialized
* initializer
* inside
* instruction
* interference
* interferes
* interleaved
* internal
* intersection
* intractable
* intrinsic
* invalidates
* irreducible
* irrelevant
* language
* lifetime
* literal
* looks
* materialize
* meaning
* mergeable
* might
* mimics
* modification
* modifies
* multiple
* mutating
* necessarily
* necessary
* needsmultiplecopies
* nonetheless
* nothing
* occurred
* occurs
* optimization
* optimizing
* original
* outside
* overflow
* overlapping
* overridden
* owned
* ownership
* parallel
* parameter
* paths
* patterns
* pipeline
* plottable
* possible
* potentially
* practically
* preamble
* precede
* preceding
* predecessor
* preferable
* preparation
* probably
* projection
* properties
* property
* protocol
* reabstraction
* reachable
* recognized
* recursive
* recursively
* redundant
* reentrancy
* referenced
* registry
* reinitialization
* reload
* represent
* requires
* response
* responsible
* retrieving
* returned
* returning
* returns
* rewriting
* rewritten
* sample
* scenarios
* scope
* should
* sideeffects
* similar
* simplify
* simplifycfg
* somewhat
* spaghetti
* specialization
* specializations
* specialized
* specially
* statistically
* substitute
* substitution
* succeeds
* successful
* successfully
* successor
* superfluous
* surprisingly
* suspension
* swift
* targeted
* that
* that our
* the
* therefore
* this
* those
* threshold
* through
* transform
* transformation
* truncated
* ultimate
* unchecked
* uninitialized
* unlikely
* unmanaged
* unoptimized key
* updataflow
* usefulness
* utilities
* villain
* whenever
* writes

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>
2022-10-03 18:31:33 -04:00
Michael Gottesman
1e6187c4f4 [sil] Update all usages of old API SILValue::getOwnershipKind() in favor of new ValueBase::getOwnershipKind().
Andy some time ago already created the new API but didn't go through and update
the old occurences. I did that in this PR and then deprecated the old API. The
tree is clean, so I could just remove it, but I decided to be nicer to
downstream people by deprecating it first.
2022-07-26 11:46:23 -07:00
Andrew Trick
1c8f142a73 OwnershipOptUtils - computeGuaranteedBoundary 2022-02-16 12:23:01 -08:00
Nate Chandler
f8bcfe2328 [RAUW] Allow RAUWing some lexical values.
RAUWing a lexical value with a non-lexical value is illegal because it
would result in the value's lifetime being shortened without regard to
deinit barriers.  RAUWing _with_ a lexical value is LEGAL so long as
doing so doesn't extend its lifetime.
2022-02-10 16:28:41 -08:00
Andrew Trick
0b95286ddb Add LoadOperation::getLoadInst for readability at the use sites.
And minor implementation cleanup.
2021-12-13 21:35:14 -08:00
Andrew Trick
c86d112891 Update #include for InstructionDeleter.h 2021-11-18 11:38:08 -08:00
Meghana Gupta
e9df26803b Add new api makeGuaranteedValueAvailable 2021-11-01 14:03:22 -07:00
Andrew Trick
652ff78412 OSSA RAUW helper redesign - split prepareReplacement() vs. perform()
Required to fix SILCombine.

Divide the logic into smaller pieces. This allows passes to check for
replaceability before generating the replacement value.

Preparation for simplifying OSSA utilities into smaller logical
components making them flexibile and allowing improvements to be
staged in.
2021-10-18 09:01:15 -07:00
Andrew Trick
4a85e187ca Eliminate unused and incomplete OSSA logic. 2021-10-18 09:01:15 -07:00
Andrew Trick
8062e408ea Migrate to OwnershipLifetimeExtender API: borrowCopyOverScope etc.
Preparation for rewriting non-trivial terminators and generalizing
support for guaranteed phis.

Add guaranteedUsePoints to the RAUW context. This will replace ALL
existing context book-keeping once the old code is deleted.

Introduce a borrowCopyOverScope entry point to handle extending
lifetime over a BorrowedValue. This simply uses the
BorrowedLifetimeExtender.

Introduce higher-level APIs:
- borrowOverValue to extened over a guaranteedValue
- borrowOverSingleUse to extened over a single guaranteed use

These replace both createPlusZeroBorrow and createPlusOneBorrow.

Update RAUW-ctor, RAUW::handleUnowned, and replaceAddressUses to use
the new API.

Restructure RAUW::canFixUpOwnershipForRAUW. Simply use
findInnerTransitiveGuaranteedUses.

Replace RAUW::handleGuaranteed and rewriteReborrows with
OLE::borrowOverValue.

Use the BorrowedLifetimeExtender utility to handle all situations
correctly.

TODO: createPlusOneBorrow can be completely removed, and a massive
amount of confusing/incomplete code can be deleted in a follow-up
commit.
2021-10-18 09:01:15 -07:00
Andrew Trick
850426514a Merge pull request #39761 from atrick/fix-accessopt
Fix AccessEnforcementOpts for OSSA
2021-10-15 00:14:23 -07:00
Andrew Trick
4b592c09d8 Add OSSA utilities for extending lifetimes and borrow scopes
Without introducing any new borrow scopes or owned lifetimes.

Top-level APIs:
- extendOwnedLifetime()
- extendLocalBorrow()

New utilitiy: GuaranteedOwnershipExtension.

This is a simple utility to determine whether new uses can be added to
an existing guaranteed value. It reports the kind of transformation
needed and performs the transformation if requested. If transformation
is needed, it simply calls one of the two top-level APIs.
2021-10-14 13:53:37 -07:00
Andrew Trick
7d6118f1a1 Add RAUW requiresCopyBorrowAndClone() check
The client needs to be able to check if any instructions may be cloned
to produce valid OSSA during RAUW.
2021-10-13 21:55:43 -07:00
Andrew Trick
49ce69226f Add OwnershipReplaceSingleUseHelper destructor 2021-10-13 10:57:16 -07:00
Andrew Trick
091532de04 Add a destructor to OwnershipRAUWHelper.
It's supposed to cleanup its context whenever it's invalidated. This
just makes sure the cleanup happens even if it transformation is never
performed.
2021-10-13 10:57:16 -07:00
Andrew Trick
5ac273d2b0 OwnershipOptUtils API comments. Document assumed preconditions. 2021-10-13 10:57:15 -07:00
Andrew Trick
4cdcc14885 Prepare OwnershipRAUWHelper support for terminator results.
The 'oldValue' can now be a terminator result instead of a
SingleValueInstruction.
2021-10-13 10:57:15 -07:00
Andrew Trick
d61732969a Make hasValidRAUWOwnership a static member of OwnershipRAUWHelper
Allow quickly checking for valid OSSA value substitution independent
from information about the value's lifetime or scope. Make it a static
member to allow this to check to be done outside of the RAUW
utility. e.g. from SimplifyCFG.
2021-10-13 10:57:15 -07:00
Andrew Trick
a2b6f7cb3b Fix comment typos 2021-10-13 10:57:15 -07:00
Andrew Trick
8ba105f5cb Use AddressOwnership in OSSA RAUW. Improves optimization.
This mainly simplifies the utility, but also improves optimization as
a side effect.

Update OSSA RAUW after replacing BorrowedAddress with AddressOwnership.

InteriorPointer is no longer needed. This simplifies the fixup
context. Eventually the fixup context will be very lightweight. This
is just the first step.
2021-10-07 15:48:25 -07:00
Andrew Trick
5928958fd1 NFC: Remove an unused JointPostDominanceSetComputer forward decl. 2021-10-03 19:49:57 -07:00
Andrew Trick
ffb7ecc1f7 Add a BorrowedLifetimeExtender utility.
Handle SSA update (phi creation) when extending an owned lifetime over
a borrowed lifetime.

This is a layer of logic above BorrowedValue but below
OwnershipLifetimeExtender and other higher-level utilities.
2021-09-17 20:09:58 -07:00
Meghana Gupta
d40c915489 Fix ownership rauw to not leave behind stale ownership fixup context
Ownership rauw uses a shared ownership fixup context to maintain state.
When ownership rauw fails, due to some invalid condition, we leave
behind stale data in this shared ownership fixup context.
This stale context can indvertantly affect the next rauw on addresses.
In addition to setting the ownership fixup context to nullptr, we
should also clear it so that it's internal data structures are
cleared.
2021-08-12 16:46:20 -07:00
Michael Gottesman
5019e1578f [ownership] Refactor out the composition type LoadOperation from CanonicalizeInstruction into OwnershipOptUtils.
This API is useful when writing compiler code that needs to handle ossa/non-ossa
as well as load_borrow/load while in OSSA. I am going to use this in
SILMem2Reg.
2021-04-14 11:43:20 -07:00
Andrew Trick
e9d0b08706 Add utilities to support OSSA update after running SSAUpdater.
This directly adds support to BasicBlockCloner for updating OSSA.

It also adds a much more general-purpose GuaranteedPhiBorrowFixup
utility which can be used for more complicated SSA updates, in which
multiple phis need to be created. More generally, it handles adding
nested borrow scopes for guaranteed phis even when that phi is used by
other guaranteed phis.
2021-03-18 00:14:13 -07:00
Andrew Trick
dd525d02e7 Add requiresOSSACleanup API. 2021-02-23 22:47:59 -08:00
Michael Gottesman
b16f340595 Merge pull request #35684 from eeckstein/fix-find-jpds
SIL: fix problems in findJointPostDominatingSet and some refactoring
2021-02-02 14:18:22 -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
Andrew Trick
b3e76ae8e5 Add PhiOperand and PhiValue types.
This is necessitated by the SILArgument representation. It has the
tragic property that adding unrelated phis invalidates existing
phis. Therefore, the optimizer can't do book-keeping of phi values by
refering directly to SILValues or Operands. Instead, it must only
refer to SILBasicBlocks and argument indices.
2021-02-01 20:15:05 -08: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
Meghana Gupta
3e330abf44 Fix use-after-free in ownership rauw
Instead of saving BorrowingOperand on the context save the SILBasicBlock
and index of the terminator operand.
This avoids the use-after-free in eliminateReborrowsOfRecursiveBorrows.
Previously, eliminateReborrowsOfRecursiveBorrows called helper
insertOwnedBaseValueAlongBranchEdge, which can delete a branch
instruction (reborrow) that could have been cached in
recursiveReborrows.
2021-01-26 20:21:16 -08:00