Commit Graph

159 Commits

Author SHA1 Message Date
Erik Eckstein
c15f76f316 SILCloner: correctly map function argument types in cloneFunction
and remove the now unused `SILBasicBlock::cloneArgumentList`
2025-09-04 08:15:45 +02:00
Shubham Sandeep Rastogi
b016c742c6 Add dump overloads to print debug info for SIL.
This patch adds dump overload methods to SILInstruction, SILBasicBlock,
SILFunction, and SILModule that prints the debug information as well.
2025-03-26 10:47:45 -07:00
Yuta Saito
84bfaf5f7e [SIL] Explicitly use uint64_t for maxBitfieldID
The `maxBitfieldID` was defined as `size_t` and used to assert
bitfield ID values. The `currentBitfieldID` of `SILFunction` is
defined as `uint64_t`, so we should consistently use `uint64_t`
for `maxBitfieldID` as well for 32-bit platforms.
2025-02-13 02:04:54 +00:00
Saleem Abdulrasool
a3b60ed0f3 SIL: avoid truncation warnings on Windows (NFCI)
`enum` is a signed integer type on some platforms. The return value of
`std::numeric_limits<T>::max()` is a `size_t` which is unsigned. Further
manipulation retains the unsigned-ness until the assignment which
results in truncation. Change the type to a `constexpr` constant
definition and remove the `enum` type along with a type conversion to an
explicitly unsigned integral type.
2024-12-09 08:29:23 -08:00
Erik Eckstein
44cd8d71d5 SIL: remove some const from decl arguments in SILBasicBlock and SILArgument APIs
It's not needed and would just introduce some const_casts.
2024-10-02 07:10:28 +02:00
Michael Gottesman
2e08d6110d Fix SILBasicBlock::{dump,print}ID so that they are available in no-asserts but just print out NOASSERTS instead of a debug id. 2024-08-09 11:10:37 -07:00
Slava Pestov
a1462ef184 SIL: Promote removeDeadBlock() from SILOptimizer to a method on SILBasicBlock 2024-05-21 13:52:58 -04:00
Erik Eckstein
7afa419dd4 SIL: improve inline bitfields in SILNode, SILBasicBlock and Operand
* Let the customBits and lastInitializedBitfieldID share a single uint64_t. This increases the number of available bits in SILNode and Operand from 8 to 20. Also, it simplifies the Operand class because no PointerIntPairs are used anymore to store the operand pointer fields.
* Instead make the "deleted" flag a separate bool field in SILNode (instead of encoding it with the sign of lastInitializedBitfieldID). Another simplification
* Enable important invariant checks also in release builds by using `require` instead of `assert`. Not catching such errors in release builds would be a disaster.
* Let the Swift optimization passes use all the available bits and not only a fixed amount of 8 (SILNode) and 16 (SILBasicBlock).
2024-03-21 15:52:39 +01: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
Michael Gottesman
a2604dcafa [region-isolation] Ensure that we error if we access a Sendable field of a non-Sendable typed var and the var is captured in a closure
If the var is captured in a closure before it is transferred, it is not safe to
access the Sendable field since we may race on accessing the field with an
assignment to the field in another concurrency domain.

rdar://115124361
2023-12-01 13:53:56 -08:00
Nate Chandler
d8312122eb [SIL] NFC: Improved block id printing. 2023-10-04 16:48:06 -07:00
Nate Chandler
61984e015e [SIL] Add utils to visit prev/next insts.
For instructions at the back of a block, visiting the subsequent
instructions means visiting the instructions at the front of every
successor.  For instructions at the front of a block, visiting the prior
instructions means visiting the instructions at the back of every
predecessor.
2023-09-25 18:49:29 -07: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
Nate Chandler
7c1e5ec1d1 [SIL] NFC: Added debug printing of block ids. 2023-06-23 10:16:53 -07:00
Meghana Gupta
1dc713e2f7 Add new flags "reborrow" and "escaping" to SILArgument.
"reborrow" flag on the SILArgument avoids transitive walk over the phi operandsi
to determine if it is a reborrow in multiple utilities.
SIL transforms must keep the flag up-to-date by calling SILArgument::setReborrow.
SILVerifier checks to ensure the flag is not invalidated.

Currently "escaping" is not used anywhere.
2023-05-11 12:31:37 -07:00
Erik Eckstein
1c844ed29f SIL: remove dangerous SILBasicBlock APIs
`isSuccessorBlock` and `isPredecessorBlock` are dangerous because they can easily lead to quadratic behavior.
Fortunately they are not used anywhere (except in one place for verification, which I rewrote).
2023-03-08 12:20:52 +01:00
Erik Eckstein
0523dbee9d SILBitFields: don't set bitfields of deleted nodes 2023-01-16 16:16:51 +01:00
eeckstein
cb6737269d Merge pull request #62480 from eeckstein/instruction-iteration
SIL: simplify deleting instructions while iterating over instructions.
2022-12-13 10:45:06 +01:00
Andrew Trick
f9861ec9c0 Add APIs for terminator results that forward ownership.
Add TermInst::forwardedOperand.

Add SILArgument::forwardedTerminatorResultOperand. This API will be
moved into a proper TerminatorResult abstraction.

Remove getSingleTerminatorOperand, which could be misused because it's
not necessarilly forwarding ownership.

Remove the isTransformationTerminator API, which is not useful or well
defined.

Rewrite several instances of complex logic to handle block arguments
with the simple terminator result API. This defines away potential
bugs where we don't detect casts that perform implicit conversion.

Replace uses of the SILPhiArgument type and code that explicitly
handle block arguments. Control flow is irrelevant in these
situations. SILPhiArgument needs to be deleted ASAP. Instead, use
simple APIs like SILArgument::isTerminatorResult(). Eventually this
will be replaced by a TerminatorResult type.
2022-12-12 12:37:35 -08:00
Erik Eckstein
c180d1363e SIL: simplify deleting instruction while iterating over instructions.
Add `deletableInstructions()` and `reverseDeletableInstructions()` in SILBasicBlock.
It allows deleting instructions while iterating over all instructions of the block.
This is a replacement for `InstructionDeleter::updatingRange()`.
It's a simpler implementation than the existing `UpdatingListIterator` and `UpdatingInstructionIteratorRegistry`, because it just needs to keep the prev/next pointers for "deleted" instructions instead of the iterator-registration machinery.
It's also safer, because it doesn't require to delete instructions via a specific instance of an InstructionDeleter (which can be missed easily).
2022-12-12 19:08:54 +01:00
Erik Eckstein
05a63c70c5 SIL: change way how a SILInstruction is marked as deleted
Instead of setting the parent pointer to null, set the `lastInitializedBitfieldID` to -1.
This allows to keep the parent block information, even when an instruction is removed from it's list.
2022-12-12 19:06:00 +01:00
Erik Eckstein
2ca9a3b9ce SIL: fix APIs for (re)moving instructions
Instructions can only be moved and erased, but never _removed_ from a block.
2022-12-12 19:05:59 +01:00
Erik Eckstein
0eacaabfef SIL: add SILArgument::isErased()
Similar to SILInstruction, it's now possible to check if an argument was erased from a SILBasicBlock.
2022-11-11 07:58:51 +01:00
Andrew Trick
ecc4474095 Define critical SILInstruction and SILBasicBlock getters inline.
It makes no sense to operate on the block's instruction list without
also including SILBasicBlock.h anyway. Similarly, it doesn't make
sense to query the entry block without including SILFunction.h.

Now we can call these simple getters in critical-path loops assuming
they are as cheap as a load. I was avoiding calling these in critical
path code, which resulted in less readability and consistency across
the code base.
2022-09-25 20:31:26 -07:00
Erik Eckstein
6760dc420c SIL: add a utility which can manage per-value and per-instruction bitfields and flags efficiently.
It's used to implement `InstructionSet` and `ValueSet`: sets of SILValues and SILInstructions.
Just like `BasicBlockSet` for basic blocks, the set is implemented by setting bits directly in SILNode.
This is super efficient because insertion and deletion to/from the set are basic bit operations.

The cost is an additional word in SILNode. But this is basically negligible: it just adds ~0.7% of memory used for SILInstructions.
In my experiments, I didn't see any relevant changes in memory consumption or compile time.
2022-07-13 14:27:50 +02:00
Nate Chandler
a9fe8735e5 [Gardening] Addressed typo. 2022-05-21 12:56:50 -07:00
Rintaro Ishizaki
7486cd1c21 [SwiftCompiler] Move common bridging facilities to 'Basic'
A preparation for AST/DiagnosticEngine bridging
2022-02-20 22:06:39 -08:00
Andrew Trick
83b01d8ebe Improve the SILPhiArgument API
This subclass of SILArgument should be eliminated--it's not always a
phi, and whether it is a "phi argument" has nothing whatsoever to do
with the opcode. That is a property of a value's uses, not a property of the
value.

Until then, provide a logical and useful API within the type. This
often avoids the need to explicitly cast to a SILPhiArgument type and
avoids a lot of boilerplate in code that deals with phis.

Note: PhiOperand and PhiValue are improved abstractions on top of this
API. But the SILArgument-level API is still an important bridge
between SILArgument and other phi abstractions.
2022-02-15 13:28:46 -08:00
Nate Chandler
45afec6e0a [SIL] Added SILBasicBlock::hasPhi. 2022-02-14 17:12:47 -08:00
Konrad `ktoso` Malawski
d96cb1dbaf [SIL] Allow giving debug names to SILBasicBlocks 2022-02-01 14:35:03 +09:00
Erik Eckstein
8080465e77 libswift: basic SIL and SIL bridging
This is the initial version of a buildable SIL definition in libswift.
It defines an initial set of SIL classes, like Function, BasicBlock, Instruction, Argument, and a few instruction classes.
The interface between C++ and SIL is a bridging layer, implemented in C.
It contains all the required bridging data structures used to access various SIL data structures.
2021-06-09 11:28:57 +02:00
Erik Eckstein
24799e1526 SIL: defer instruction deletion to the end of a pass run.
When an instruction is "deleted" from the SIL, it is put into the SILModule::scheduledForDeletion list.
The instructions in this list are eventually deleted for real in SILModule::flushDeletedInsts(), which is called by the pass manager after each pass run.
In other words: instruction deletion is deferred to the end of a pass.

This avoids dangling instruction pointers within the run of a pass and in analysis caches.
Note that the analysis invalidation mechanism ensures that analysis caches are invalidated before flushDeletedInsts().
2021-05-26 21:57:54 +02: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
Erik Eckstein
6713c0feca SIL: a few small changes in BasicBlockData
* Instead of passing the vector type as template argument, use a SmallVector and just pass the inline size
* Increase the inline size to 32. Found by experiment, this fits 90% of all functions.
* add an API for getting data for newly created blocks.
2021-01-22 12:53:26 +01:00
Erik Eckstein
47c596d645 SIL: Use TinyPtrVector for the argument list in SILBasicBlock
A TinyPtrVector is the right choice, because ~98% of blocks have 0 or 1 arguments.
2021-01-22 10:05:09 +01:00
Erik Eckstein
2c7027da97 SIL: fix a header-file layering violation: SILArgument.h should not include SILFunction.h
"Containers" should include their "content" and not the other way round.
Also, remove some unused stuff of SILArgument.
2021-01-22 10:05:09 +01:00
Erik Eckstein
65976fd0c5 SIL: add a utility which can manage per-block bitfields and flags efficiently.
It is very efficient: no memory allocation is needed an initialization is at zero cost.
2021-01-21 21:31:41 +01:00
Erik Eckstein
273bd35061 SIL: add a utility which let's manage per-block data efficiently.
It can be used by transforms to store temporary data per basic block.
It is very efficient: only a single memory allocation is needed and no maps are used to lookup data.
2021-01-20 16:09:01 +01: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
Erik Eckstein
d824fd3440 DiagnoseInfiniteRecursion: handle invariant conditions and improve the warning message
The main change is to detect infinite recursive calls under invariant conditions. For example:

  func f() {
    if #available(macOS 10.4.4, *) {
      f()
    }
  }

or invariant conditions due to forwarded arguments:

  func f(_ x: Int) {
    if x > 0 {
      f(x)
    }
  }

Also, improve the warning message. Instead of giving a warning at the function location

  warning: all paths through this function will call itself

give a warning at the call location:

  warning: function call causes an infinite recursion

Especially in case of multiple recursive calls, it makes it easier to locate the problem.

https://bugs.swift.org/browse/SR-11842
rdar://57460599
2021-01-13 14:35:03 +01:00
Erik Eckstein
170d9e9eea SIL: Let SILGlobalVariables be destroyed.
This fixes a memory leak: instructions of the static initializer block were not be freed.

rdar://problem/66931238
2020-09-11 11:09:29 +02:00
zoecarver
db553f2f04 [NFC] Remove ostream argument from SILBasicBlock::print.
The first argument, OS, was never used in the SILBasicBlock::print method. Keeping it would be misleading.
2020-05-05 11:42:53 -07:00
Erik Eckstein
1de19a1b32 SimplifyCFG: fix a compile time problem with block merging
When merging many blocks to a single block (in the wrong order), instructions are getting moved over and over again.
This is quadratic and can result in very long compile times for large functions.
To fix this, always move the instruction to smaller block to the larger block.

rdar://problem/56268570
2020-04-10 20:10:24 +02:00
Saleem Abdulrasool
01d5652999 remove VS2015 workaround (NFC)
VS2015 had an issue with the deletion of an operator.  Since VS2017 is
the minimum version that LLVM uses, we can assume that VS2017+ is in use
(_MSC_VER >= 1910).  Clean up the now defunct workaround.
2019-12-23 11:55:10 -08: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
9ecda0c574 SIL: Plumb TypeExpansionContext through SIL 2019-11-11 14:21:52 -08:00
Jordan Rose
8b8c88e258 Improve swift::TransformRange enough to delete TransformArrayRef
We have a lot of "transform a range" types already:
llvm::mapped_iterator, swift::TransformRange and
swift::TransformIterator, and swift::ArrayRefView for static
transformations. This gets rid of one more layer without losing
any real functionality.
2019-10-02 10:23:05 -07:00
Michael Gottesman
748bf88bbe [ownership] Convert SILOptimizer/cast_folding.swift to work with ownership and fix all issues exposed. 2019-05-21 09:07:13 -07: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
Harlan
00cc011621 [SILOptimizer] Don't diagnose infinite recursion if a branch terminates the program (#19781)
* [SILOptimizer] Don't diagnose infinite recursion if a branch terminates the program

This patch augments the infinite recursion checker to not warn if a
branch terminates, but still warns if a branch calls into something with
@_semantics("programtermination_point"). This way, calling fatalError
doesn't disqualify you for the diagnostic, but calling exit does.

This also removes the warning workaround in the standard library, and
annotates the internal _assertionFailure functions as
programtermination_points, so they get this treatment too.

* Fix formatting in SILInstructions.cpp

* Re-add missing test
2018-10-09 09:46:37 -07:00