Commit Graph

396 Commits

Author SHA1 Message Date
Arnold Schwaighofer
33f4f57cc4 SILGen: Add TypeExpansionContext to SILGen 2019-11-11 14:21:52 -08:00
Robert Widmann
8a69f886ad Merge pull request #27955 from AnthonyLatsis/bracestmt_cleanup
NFC: Solidify and tidy up the BraceStmt interface
2019-10-31 13:48:40 -07:00
Anthony Latsis
6325915b4b NFC: Solidify and tidy up the BraceStmt interface 2019-10-30 16:43:59 +03:00
Michael Gottesman
26a734e58e [sil] Rename ValueOwnershipKind::{Any,None} 2019-10-25 10:28:25 -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
Joe Groff
7adfc52447 SILGen: Emit bb args for shared loadable case bindings that come after address-only ones.
Looks like a think-o; even if we see an address-only binding in a shared pattern block, we still
expect bb args in the lowered basic block for anything that comes after it. rdar://problem/53956564
2019-08-06 15:09:01 -07:00
Saleem Abdulrasool
731c31f9a5 MSVC: litter the code with llvm_unreachable (NFC)
Add `llvm_unreachable` to mark covered switches which MSVC does not
analyze correctly and believes that there exists a path through the
function without a return value.
2019-06-01 19:02:46 -07:00
Michael Gottesman
adcfda6f6d [silgenpattern] When binding values, use a ManagedValue instead of an RValue to avoid implicitly exploding tuples.
In SILGenPattern, we need to be able to unforward cleanups when we explode
tuples. Thus we can't use RValue in SILGenPattern since it may implicitly
explode tuples (which without modifying RValue itself we can not
unforward). This patch removes a specific RValue usage that we can replace with
the use of a ManagedValue instead.

rdar://49903264
2019-05-16 12:41:08 -07:00
Slava Pestov
16d5716e71 SIL: Use the best resilience expansion when lowering types
This is a large patch; I couldn't split it up further while still
keeping things working. There are four things being changed at
once here:

- Places that call SILType::isAddressOnly()/isLoadable() now call
  the SILFunction overload and not the SILModule one.

- SILFunction's overloads of getTypeLowering() and getLoweredType()
  now pass the function's resilience expansion down, instead of
  hardcoding ResilienceExpansion::Minimal.

- Various other places with '// FIXME: Expansion' now use a better
  resilience expansion.

- A few tests were updated to reflect SILGen's improved code
  generation, and some new tests are added to cover more code paths
  that previously were uncovered and only manifested themselves as
  standard library build failures while I was working on this change.
2019-04-26 22:47:59 -04:00
Michael Gottesman
14d39c0cf9 [silgenpattern] Fix ownership error which could result in a use-after-free.
Specifically, in order to generate runtime errors when we do not handle an enum
appropriately, we form a metatype from the input of the switch. The problem is
that by the time we get to the leaf of the emission tree where this metatype is
created, the input of the switch may have already been consumed. This means
creating the metatype could be a use after free.

This patch fixes the problem by emitting the value_metatype after we emit the
subject of the switch, but before we emit the switch itself.

rdar://49562761
2019-04-10 08:48:27 -07:00
Michael Gottesman
564b4fc11a [silgenpattern] Fix some stack-use-after-free errors caused by iterating over an Optional<ArrayRef<T>>.
Specifically the bad pattern was:

```
   for (auto *vd : *caseStmt->getCaseBodyVariables()) { ... }
```

The problem is that the optional is not lifetime extended over the for loop. To
work around this, I changed the API of CaseStmt's getCaseBodyVariable methods to
never return the inner Optional<MutableArrayRef<T>>. Now we have the following 3
methods (ignoring const differences):

1. CaseStmt::hasCaseBodyVariables().

2. CaseStmt::getCaseBodyVariables(). Asserts if the case body variable array was
   never specified.

3. CaseStmt::getCaseBodyVariablesOrEmptyArray(). Returns either the case body
   variables array or an empty array if we were never given any case body
   variable array.

This should prevent anyone else in the future from hitting this type of bug.

radar://49609717
2019-04-04 13:34:36 -07:00
Michael Gottesman
dc7879d48f Fix ASAN error caused by assigning/getting from the same DenseMap in one statement.
The problem would occur if after we accessed the value, we grew the DenseMap to
insert the value again. But putting in an extra auto I avoid the problem here.

rdar://49609717
2019-04-04 13:34:36 -07:00
Michael Gottesman
7b0d8455ca [ast][silgen] Wire up the case body var decls and use them in SILGenPattern emission to fix the evil fallthrough bug.
rdar://47467128
2019-04-03 23:51:06 -07:00
Michael Gottesman
7b27b4b502 [silgenpattern] Change SILGenPattern to use CaseStmt::hasFallthroughDest() instead of computing this itself.
rdar://47467128
2019-03-14 11:25:41 -07:00
Michael Gottesman
85ee550669 [silgenpattern] When we switch on an enum with an associated type that is empty, create a phi argument for it.
Previously we were handling this like we did not have any associated type. This
caused us to break the requirement in [ossa] that all switch_enum successors
associated with payloaded enums must have arguments. We still emit the empty
tuple value (or an undef tuple) if we do not have any associated type.
2019-03-12 14:59:50 -07:00
Slava Pestov
8915f96e3e SIL: Replace SILType::isTrivial(SILModule) with isTrivial(SILFunction) 2019-03-12 01:16:04 -04:00
Slava Pestov
c791c4a137 SIL: SILUndef must be aware of the resilience expansion
The ownership kind is Any for trivial types, or Owned otherwise, but
whether a type is trivial or not will soon depend on the resilience
expansion.

This means that a SILModule now uniques two SILUndefs per type instead
of one, and serialization uses two distinct sentinel IDs for this
purpose as well.

For now, the resilience expansion is not actually used here, so this
change is NFC, other than changing the module format.
2019-03-12 00:30:35 -04:00
Michael Gottesman
87604fedc7 Merge pull request #23161 from gottesmm/pr-a5f2826a8beda8910e2b0dc7efba52dce1379f8d
[silgenpattern] Only emit a shared case if we have a fallthrough/mult…
2019-03-07 17:04:07 -08:00
Michael Gottesman
6113566089 [silgenpattern] Convert two Pattern::forEachVariables() to instead use Pattern::collectVariables().
This maps more cleanly onto CaseStmt::getCaseBodyVariables() and cleans up the
diff for changing to use said method instead.
2019-03-07 12:01:48 -08:00
Michael Gottesman
9f0375e3c9 [silgenpattern] Only emit a shared case if we have a fallthrough/multiple cast items.
There was a bug here where we were emitting a shared case if we had arguments.
That is why we needed the hacked in deletion of that block when we emitted
shared blocks. I was able to replace that with an assert to make sure that we do
not regress.

This additionally improved our code generation by eliminating a potential extra
copy when we had such a case. That is where the test updates come from.
2019-03-07 11:54:07 -08:00
Michael Gottesman
4fefea5cbf [silgenpattern] Reduce indentation and clean up code by inverting an if condition and using an early exit. 2019-03-06 12:45:03 -08:00
Michael Gottesman
99c62ea5da [silgenpattern] Extract out the large completion handler lambda into its own function.
This makes it easier to read/reason about SILGenPattern::emitSwitchStmt().
2019-03-06 12:33:58 -08:00
Michael Gottesman
c8cdc46f02 [silgenpattern] Reduce indentation by inverting a condition. 2019-03-06 11:28:05 -08:00
Michael Gottesman
0f1510bfdf Merge pull request #22723 from gottesmm/pr-4c62ddbcb693de79222f5cd1f86a2a89f0d879bd
[silgen] Eliminate more unneeded indentation by inverting an if state…
2019-02-19 16:46:20 -08:00
Michael Gottesman
c04afbd4a6 [silgen] Eliminate more unneeded indentation by inverting an if statement. 2019-02-19 15:05:14 -08:00
Michael Gottesman
7989d3f48c Merge pull request #22720 from gottesmm/pr-92e66215cb00ac99f0a42ba2235807d017811217
[silgen] Remove some unnecessary indentation from SILGenPattern::emitSwitchStmt
2019-02-19 14:59:21 -08:00
Michael Gottesman
9b9d01ea5d [silgen] Eliminate another level of indentation by inverting an if statement and using a continue. 2019-02-19 13:31:52 -08:00
Michael Gottesman
cd2fbfcd81 [silgen] Use early exits and invert an if condition to reduce indentation. 2019-02-19 13:31:52 -08:00
Michael Gottesman
0b3aba4c82 [silgen] Eliminate another level of indentation by inverting an if condition in a for loop. 2019-02-19 13:04:28 -08:00
Michael Gottesman
af40fcfe6b [silgen] Use early breaks in an if-else-if block instead of having a break at the end.
Just reducing indentation more.
2019-02-19 13:04:28 -08:00
Michael Gottesman
9570384646 [silgen] Use an early exit to reduce indentation. NFC. 2019-02-19 13:04:28 -08:00
Andrew Trick
f3f5848e29 Remove a stale UnenforcedAccess marker from SILGenPattern.
NFC unless -enable-verify-exclusivity is on.

Boxed (indirect) enum loads are not formal accesses so they should not
have access markers. For a while, we used UnenforcedAccess in this
case to signal to the verifier that this is actually a safe load. But
that isn't needed. The verifier just ignores loads from unidentified
storage instead.

There are two code paths that had this UnenforcedAccess marker. One
was cleaned up, and the other was not. So finish the cleanup and add a
unit test for both SILGen code paths.
2019-02-13 19:00:51 -08:00
Michael Gottesman
d364bb359b [silgenpattern] Fix the box handling in the old silgenpattern enum code to not pass a load_borrow payload as BorrowAlways instead of TakeAlways.
Thanks to Luiz Fernando Silva for the test case!

SR-9871
rdar://problem/47852446
2019-02-07 12:35:28 -08:00
Michael Gottesman
a53e351d37 [silgenpattern] Fix a leak in tuple pattern emission.
Today SILGenPattern maintains the following invariants:

1. All values passed into a switch must be either TakeAlways or BorrowAlways and
   loadable input values will be loaded.

2. Loadable types passed to a subtree must be loaded.

3. TakeOnSuccess can only occur with address only types and only in subtrees.

4. A TakeOnSuccess value must go through "fake borrowing"
   (i.e. forward/unforwarding) to ensure that along failing cases, we properly
   re-enable the cleanup on the aggregate. This means that TakeOnSuccess can
   never be handled as a loadable value with ownership enabled and that any
   take_on_success value since the original cleanup on the parent value was
   disabled must be at +1.

5. We use BorrowAlways instead of TakeOnSuccess for objects to express the
   notion that the object is not owned by the sub-tree.

The bug in this tuple code occured at the a place in the code where we go from
an address only parent type to a loadable subtype via TakeOnSuccess. I was
trying to follow (5) and thus I converted the subvalue to use a {load_borrow,
BorrowAlways}. The problem with this is that I lost the cleanup from the tuple
subvalue since take_on_success is just simulating +0 and thus entails having a
cleanup for each of the underlying tuple values.

The fix here was to:

* Create a cleanup for the loadable subvalue leaving it in memory. This address
  version of the subvalue we use for the purposes of unforwarding. This avoids
  (4).
* load_borrow the subvalue and pass that off to the subtree. This ensures that
  we respect (2), (3), (4).
* Unforward in the failure case the in memory subvalue.

This gives us both characteristics as well as in the future the possibility of
enforcing via the ownership verifier that the borrow ends before the
destroy_addr.

I also sprinkled some assertions liberally to maintain invariants.

rdar://47034816
2019-01-09 15:14:15 -08:00
Robert Widmann
426fe886dc [SR-8272] Drop the last remnants of LogicValue
Removes the _getBuiltinLogicValue intrinsic in favor of an open-coded
struct_extract in SIL.  This removes Sema's last non-literal use of builtin
integer types and unblocks a bunch of cleanup.

This patch would be NFC, but it improves line information for conditional expression codegen.
2018-12-19 23:14:59 -05:00
Slava Pestov
6c012b2aec AST: Remove some unnecessary LazyResolver * parameters from ASTContext methods 2018-12-07 20:39:27 -05:00
Michael Gottesman
0af0d5fddc [ownership] Replace ValueOwnershipKind::Trivial with ValueOwnershipKind::Any.
In a previous commit, I banned in the verifier any SILValue from producing
ValueOwnershipKind::Any in preparation for this.

This change arises out of discussions in between John, Andy, and I around
ValueOwnershipKind::Trivial. The specific realization was that this ownership
kind was an unnecessary conflation of the a type system idea (triviality) with
an ownership idea (@any, an ownership kind that is compatible with any other
ownership kind at value merge points and can only create). This caused the
ownership model to have to contort to handle the non-payloaded or trivial cases
of non-trivial enums. This is unnecessary if we just eliminate the any case and
in the verifier separately verify that trivial => @any (notice that we do not
verify that @any => trivial).

NOTE: This is technically an NFC intended change since I am just replacing
Trivial with Any. That is why if you look at the tests you will see that I
actually did not need to update anything except removing some @trivial ownership
since @any ownership is represented without writing @any in the parsed sil.

rdar://46294760
2018-12-04 23:01:43 -08:00
Slava Pestov
14a3a5d5a9 SILGen: Fix corner case when emitting switch over value needing reabstraction
This also exposed a bug where we use a lowered type as an AST type and
crash when emitting the '@unknown case' block. This block is unreachable
when switching over non-enum values, but its emitted anyway.

Fixes <https://bugs.swift.org/browse/SR-9159>, <rdar://problem/45962466>.
2018-11-16 00:06:32 -05:00
Michael Gottesman
b45bea8a03 [silgen] Scope conditionally emitted code by emitBoolDispatch.
rdar://45602910
2018-10-31 18:44:48 -07:00
Joe Groff
7b5e83de01 Merge pull request #19979 from mdiep/SR-8933
Fix assertion from empty switch over uninhabited enum
2018-10-29 09:46:55 -07:00
Jordan Rose
dc3ff6c22b Merge pull request #19985 from vinivendra/ast-dump-cleanup
Cleans up calls to print/dump for the AST Dumper
2018-10-24 15:22:41 -07:00
Michael Gottesman
d8243c8b9b [silgenpattern] Allow the initial switch value to be at +0 if it is loadable.
This commit allows the initial switch subject value to be emitted at +0 if we
can emit it that way. As you can imagine since we have +0 normal function
arguments this should tighten up a lot of code around switches on arguments. So
I got to delete a bunch of code in the tests. = ).

Some things to note:

1. If the switch is given a +1 value, we will still try to let it through at +1
until we hit a part of the decision tree where previously we would need to use
TakeOnSuccess. This means that +1 values that go through irrefutable patterns
like tuple splitting should still be emitted at +1.

2. If we are returned an address only type without a cleanup, we copy it and
pass it down at +1 like the old code.

3. I also elided the last ownership check in SILGenPattern in this commit. After
this, there is only 1 specialization for ownership in the swift compiler that is
in Apply emission. Thats my next target.

rdar://29791263
2018-10-23 10:25:05 -07:00
Michael Gottesman
447a11a19a [silgenpattern] Change catch emission to not be conditional on ownership verification being enabled.
We were missing the code-coverage needed to show this so I added some examples
to test/SILGen/errors.swift.

rdar://29791263
2018-10-23 10:05:35 -07:00
Vinicius Vendramini
b61df445ae Cleans up calls to print/dump for the AST Dumper
The `Stmt` and `Expr` classes had both `dump` and `print` methods that behaved similarly, making it unclear what each method was for. Following a conversation in https://forums.swift.org/t/unifying-printing-logic-in-astdumper/15995/6 the `dump` methods will be used to print the S-Expression-like ASTs, and the `print` methods will be used to print the more textual ASTPrinter-based representations. The `Stmt` and `Expr` classes seem to be where this distinction was more ambiguous. These changes should fix that ambiguity.

A few other classes also have `print` methods used to print straightforward representations that are neither the S-Expressions nor ASTPrinters. These were left as they are, as they don't cause the same ambiguity.

It should be noted that the ASTPrinter implementations themselves haven't yet been finished and aren't a part of these changes.
2018-10-22 16:04:02 -03:00
Matt Diephouse
cd2daa931f Fix assertion from empty switch over uninhabited enum
Fixes SR-8933.

Swift's uninhabited checking is conservative. An enum might not be found to be uninhabited, but all of its cases might. In that case, the switch can be empty even though the type isn't known to be uninhabited.

Fix an assertion that assumed there would always be at least one case for types that aren't known to be uninhabited.
2018-10-22 06:46:46 -04:00
Michael Gottesman
b7a7b1ef3b [silgenpattern] Fix pattern emission of tuples with address only and loadable components.
The problem here was that if we had a tuple with mixed address only and loadable
components and we used take on success during pattern matching, we would load
the loadable component with a load [take] and then pass it as take on success.
Instead we load the loadable components of the tuple using a load_borrow and
make the cast consumption kind BorrowAlways.

This can not happen with enum element emission since enum element emission does
not support take_on_success so the problem can not occur there.

SR-9029
rdar://45345844
2018-10-19 14:58:45 -07:00
Michael Gottesman
7461bfa85b Merge pull request #19881 from gottesmm/pr-31405c45544e9f2663f473a0121732c940139aea
[silgenpattern] Unconditionally use the +0 code path to emit enum ele…
2018-10-16 07:48:53 -07:00
Michael Gottesman
8d7a26c711 [silgenpattern] Unconditionally use the +0 code path to emit enum element dispatch on loadable enum types
This is the enum element analogue of the tuple fixup in:
359eda52e5. Additionally as a nice fixup I can now
enable ownership verification on most of the switch code.

I ran into commit ordering issues with cleaning up the address only part of the
emitEnumElement so I included it in this commit. Specifically this was because I
realized that it was possible to get a copy_on_success with an object from this
code and I wanted to enforce the invariant that ConsumptionManagedValues only
have copy_on_success with addresses and borrow_always with objects. It was less
convoluted to just fix the address only code to fit that formulation rather than
shoe-horn the old code into the new form.

rdar://29791263
2018-10-15 20:18:13 -07:00
Michael Gottesman
c9b695d554 [silgenpattern] Delete dead code for dealing with objects from address only part of emitTupleDispatch.
Now that we know that we must have an address only type here, we can assume that
we have an address.

NFC.
2018-10-14 23:07:32 -07:00
Michael Gottesman
359eda52e5 [silgenpattern] Change all loadable types to always go through the ownership preserving tuple code.
To do this the commit does a few things:

1. If we enter the tuple dispatch code with an address that is loadable, we
always immediately perform a load_borrow and change the consumable managed value
to BorrowAlways.

2. If we have a take_on_success object, we immediately borrow. We do not want to
do with TakeOnSuccess since we want to define away the need to unforward since
unforwarding recreates a destroy on the already invalidated parent tuple object.

Notice that this code still handles TakeAlways so in simple cases where we have
a +1 value, everything still works.

Since emitTupleDispatchWithOwnership now handles only objects, I renamed it to
emitTupleObjectDispatch.

rdar://29791263
2018-10-11 15:54:02 -07:00