Commit Graph

66 Commits

Author SHA1 Message Date
Tim Kientzle
1d961ba22d Add #include "swift/Basic/Assertions.h" to a lot of source files
Although I don't plan to bring over new assertions wholesale
into the current qualification branch, it's entirely possible
that various minor changes in main will use the new assertions;
having this basic support in the release branch will simplify that.
(This is why I'm adding the includes as a separate pass from
rewriting the individual assertions)
2024-06-05 19:37:30 -07:00
Michael Gottesman
11f0ff6e32 [sil] Ensure that all SILValues have a parent function by making it so that SILUndef is uniqued at the function instead of module level.
For years, optimizer engineers have been hitting a common bug caused by passes
assuming all SILValues have a parent function only to be surprised by SILUndef.
Generally we see SILUndef not that often so we see this come up later in
testing. This patch eliminates that problem by making SILUndef uniqued at the
function level instead of the module level. This ensures that it makes sense for
SILUndef to have a parent function, eliminating this possibility since we can
define an API to get its parent function.

rdar://123484595
2024-02-27 13:14:47 -08: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
543063ef0e [silgen] Make ManagedValue::forUnmanaged private and change users to use other more specific APIs.
I have been doing this over the past couple of days in preparation for changing
ManagedValue to specify the type of scope its cleanup is connected to.
2023-08-19 14:11:44 -07:00
Evan Wilde
250082df25 [NFC] Reformat all the LLVMs
Reformatting everything now that we have `llvm` namespaces. I've
separated this from the main commit to help manage merge-conflicts and
for making it a bit easier to read the mega-patch.
2023-06-27 09:03:52 -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
Erik Eckstein
ab1b343dad use new llvm::Optional API
`getValue` -> `value`
`getValueOr` -> `value_or`
`hasValue` -> `has_value`
`map` -> `transform`

The old API will be deprecated in the rebranch.
To avoid merge conflicts, use the new API already in the main branch.

rdar://102362022
2022-11-21 19:44:24 +01:00
Josh Soref
9a6bf46c0f Spelling silgen
* actually
* arbitrary
* cargo-culted
* clazz
* constrained
* continuation
* coordinator
* coroutine
* derivative
* destroyer
* given
* have
* imported
* initialization
* items
* necessarily
* occurring
* omitting
* overridden
* parameter
* possible
* predecessor
* preparation
* resilience
* should
* struct
* that
* the
* throwing
* unexpectedly
* uniqueness
* using
* value
* villain

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>
2022-11-09 21:44:17 -05:00
Holly Borla
6cee193fc0 [Type System] When explicit existential types are enabled, wrap Error
in ExistentialType for the type of error values.
2022-01-13 19:30:44 -08:00
Andrew Trick
8f53a927b0 SILGen OSSA support for switch_enum/checked_cast_br, related cleanup
Use APIs for creating terminator results that handle forwarding
ownership consistently.

Add ManagedValue::forForwardedRValue(SILValue) to handle cleanups
consistently based on ownership forwarding.

Add SILGenBuilder::createForwardedTermResult(SILType type) for
creating termator results with the correct ownership and cleanups.

Add SILGenBuilder::createTermResult(SILType type, ValueOwnershipKind
ownership) that handles cleanup based on terminator result ownership.

Add SILGenBuilder::createOptionalSomeResult(SwitchEnumInst) so a lot
of code doesn't need to deal with unwrapping Optional types,
terminator results, and ownership rules.

Replace the existing "phi" APIs with a single
SILGenBuilder::createPhi(SILType, ValueOwnershipKind) that handles
cleanup based on phi ownership.

Phis and terminator results are fundamentally different and need to be handled differently everywhere. Remove the confusion where terminator results were generated with a "phi argument" API.
2021-09-07 22:50:46 -07:00
Nate Chandler
1ae317dd88 [SILGen] Handle foreign funcs with error and async conventions.
Previously, SILGen assumed that a foreign function could either have a
foreign async convention or a foreign error convention, but if it had
both, the error would be subsumed into the completion.  That resulted in
failures to emit code for async calls of functions like

```
- (BOOL)minimalWithError:(NSError* _Nullable*)error
         completionHandler:(void (^ _Nonnull)(void))completionHandler;
```

Here, SILGen gains the ability to emit such functions.  To enable that,
a few changes were required when both conventions are present:
- a separate argument for each convention is used
- the ResultPlan is a ForeignErrorResultPlan nesting a
  ForeignAsyncResultPlan
- the continuation is always of the form UnsafeContinuation<_, Error>
  regardless of whether the completion handler takes an error
- the foreign error block fills the continuation with the error that was
  passed by reference out of the ObjC method call
- the foreign error block branches to the block containing the await
  instruction

rdar://80704984
2021-08-03 18:36:15 -07:00
Erik Eckstein
ec64f2a255 SILLocation: replace CleanupLocation::get(loc) with CleanupLocation(loc)
No need to have a static get function - the constructor can be used directly.
NFC
2021-01-29 20:28:21 +01: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
Kita, Maksim
149331d024 [SILGen]: SR-11803. Inject "willThrow" hooks after foreign error propagation. 2019-11-23 20:03:43 +03:00
Arnold Schwaighofer
33f4f57cc4 SILGen: Add TypeExpansionContext to SILGen 2019-11-11 14:21:52 -08:00
Slava Pestov
83c90b6b2a AST: Turn NominalTypeDecl::getStoredProperties() into a request
This improves on the previous situation:

- The request ensures that the backing storage for lazy properties
  and property wrappers gets synthesized first; previously it was
  only somewhat guaranteed by callers.

- Instead of returning a range this just returns an ArrayRef,
  which simplifies clients.

- Indexing into the ArrayRef is O(1), which addresses some FIXMEs
  in the SIL optimizer.
2019-07-16 16:38:38 -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
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
Michael Gottesman
d57a88af0d [gardening] Rename references to SILPHIArgument => SILPhiArgument. 2018-09-25 22:23:34 -07:00
John McCall
6d4c724101 Distinguish different kinds of l-value reads in SILGen.
This is NFC for now, but I plan to build on this to (1) immediately
remove some unnecessary materialization and loads of the base value
and (2) to allow clients to load a borrowed value.
2018-08-30 19:42:53 -04:00
David Zarzycki
8c0c55539f [SIL] NFC: Rename misleading getSwiftRValueType() to getASTType()
Reference storage types are not RValues. Also, use more SILType helper
methods to avoid line wrap.
2018-05-04 08:14:38 -04:00
Slava Pestov
28d24f8f38 SIL: Remove redundant utility method and rename another one 2018-04-03 18:14:40 -07:00
Michael Gottesman
e567bc9028 [+0-all-args] Enable +0 normal arguments.
rdar://34222540
2018-03-19 20:25:31 -07:00
Mark Lacey
b4b66bc8e8 Replace getAnyOptionalObjectType with getOptionalObjectType. 2018-02-05 23:59:00 -08:00
Michael Gottesman
798bff756a [silgen] Rename SavedInsertionPoint => SILGenSavedInsertionPoint.
This rename makes since since:

1. This is SILGen specific functionality.
2. In the next commit I am going to be adding a SIL SavedInsertionPoint class. I
want to make sure the two can not be confused.
2017-11-08 10:40:39 -08:00
Michael Gottesman
e035c93ed9 [silgen][gardening] More gen => SGF. 2017-08-10 21:42:21 -07:00
John McCall
c0b3bf1711 Suppress access enforcement when an l-value is converted to a pointer
just for pointer identity.

The current technique for deciding whether that's the case is *extremely*
hacky and need to be replaced with an attribute, but I'm reluctant to
take that on so late in the schedule.  The hack is terrible but not too
hard to back out in the future.  Anyone who names a method like this just
to get the magic behavior knows well that they are not on the side of
righteousness.

rdar://33265254
2017-07-21 23:40:04 -04:00
John McCall
7f22faf968 Substantially rework how SILGen handles bridging as part of laying the
ground work for the syntactic bridging peephole.

- Pass source and dest formal types to the bridging routines in addition
  to the dest lowered type.  The dest lowered type is still necessary
  in order to handle non-standard abstraction patterns for the dest type.

- Change bridging abstraction patterns to store bridged formal types
  instead of the formal type.

- Improve how SIL type lowering deals with import-as-member patterns.

- Fix some AST bugs where inadequate information was being stored in
  various expressions.

- Introduce the idea of a converting SGFContext and use it to regularize
  the existing id-as-Any conversion peephole.

- Improve various places in SILGen to emit directly into contexts.
2017-07-11 12:45:13 -04:00
Michael Gottesman
9747214e92 [silgen] Refactor WritebackScope functionality into a new FormalEvaluationScope.
As per John, WritebackScope was always an unfortunate name. Generally these
scopes are meant for formal evaluations of inout parameters. The cases that I am
interested in generalizing them to be used for are borrows of the base of a
class that will then be used as an lvalue.

This also eliminates the out of line vector of lvalue writebacks.

rdar://29791263
2017-02-14 13:15:23 -08:00
Michael Gottesman
ea1f804207 [semantic-sil] Eliminate ValueOwnershipKind::Any from SILPHIArguments in Semantic SIL.
Most of this involved sprinkling ValueOwnershipKind::Owned in many places. In
some of these places, I am sure I was too cavalier and I expect some of them to
be trivial. The verifier will help me to track those down.

On the other hand, I do expect there to be some places where we are willing to
accept guaranteed+trivial or owned+trivial. In those cases, I am going to
provide an aggregate ValueOwnershipKind that will then tell SILArgument that it
should disambiguate using the type. This will eliminate the ackwardness from
such code.

I am going to use a verifier to fix such cases.

This commit also begins the serialization of ValueOwnershipKind of arguments,
but does not implement parsing of value ownership kinds. That and undef are the
last places that we still use ValueOwnershipKind::Any.

rdar://29791263
2017-01-10 20:05:23 -08:00
practicalswift
6d1ae2a39c [gardening] 2016 → 2017 2017-01-06 16:41:22 +01:00
Michael Gottesman
4e8ff35df5 [semantic-sil] Add ValueOwnershipKind field to SILPHIArgument and split Argument creation methods into one for SILPHIArgument and another for SILFunctionArgument.
We preserve the current behavior of assuming Any ownership always and use
default arguments to hide this change most of the time. There are asserts now in
the SILBasicBlock::{create,replace,insert}{PHI,Function}Argument to ensure that
the people can only create SILFunctionArguments in entry blocks and
SILPHIArguments in non-entry blocks. This will ensure that the code in tree
maintains the API distinction even if we are not using the full distinction in
between the two.

Once the verifier is finished being upstreamed, I am going to audit the
createPHIArgument cases for the proper ownership. This is b/c I will be able to
use the verifier to properly debug the code. At that point, I will also start
serializing/printing/parsing the ownershipkind of SILPHIArguments, but lets take
things one step at a time and move incrementally.

In the process, I also discovered a CSE bug. I am not sure how it ever worked.
Basically we replace an argument with a new argument type but return the uses of
the old argument to refer to the old argument instead of a new argument.

rdar://29671437
2016-12-18 14:48:35 -08:00
practicalswift
38be6125e5 [gardening] C++ gardening: Terminate namespaces, fix argument names, ...
Changes:
* Terminate all namespaces with the correct closing comment.
* Make sure argument names in comments match the corresponding parameter name.
* Remove redundant get() calls on smart pointers.
* Prefer using "override" or "final" instead of "virtual". Remove "virtual" where appropriate.
2016-12-17 00:32:42 +01:00
Michael Gottesman
96837babda Merge pull request #5920 from gottesmm/vacation_gardening
Vacation gardening
2016-11-25 09:17:21 -06:00
Michael Gottesman
bf6920650c [gardening] Drop BB from all argument related code in SILBasicBlock.
Before this commit all code relating to handling arguments in SILBasicBlock had
somewhere in the name BB. This is redundant given that the class's name is
already SILBasicBlock. This commit drops those names.

Some examples:

getBBArg() => getArgument()
BBArgList => ArgumentList
bbarg_begin() => args_begin()
2016-11-25 01:14:36 -06:00
practicalswift
797b80765f [gardening] Use the correct base URL (https://swift.org) in references to the Swift website
Remove all references to the old non-TLS enabled base URL (http://swift.org)
2016-11-20 17:36:03 +01:00
Michael Gottesman
34ec32bc14 [semantic-arc] Handle the rest of the unqualified mem opts in SILGen.
Keep in mind that these are approximations that will not impact correctness
since in all cases I ensured that the SIL will be the same after the
OwnershipModelEliminator has run. The cases that I was unsure of I commented
with SEMANTIC ARC TODO. Once we have the verifier any confusion that may have
occurred here will be dealt with.

rdar://28685236
2016-11-09 11:37:52 -08:00
Michael Gottesman
bffa7addaf [semantic-arc] Eliminate default {Load,Store}OwnershipQualification argument to SILBuilder::create{Load,Store}(...)
Today, loads and stores are treated as having @unowned(unsafe) ownership
semantics. This leaves the user to specify ownership changes on the loaded or
stored value independently of the load/store by inserting ARC operations. With
the change to Semantic SIL, this will no longer be true. Instead loads, stores
have ownership semantics that one must reason about such as copy, take, and
trivial.

This change moves us closer to that world by eliminating the default
OwnershipQualification argument from create{Load,Store}. This means that the
compiler developer cannot ignore reasoning about the ownership semantics of the
memory operation that they are creating.

Operationally, this is a NFC change since I have just gone through the compiler
and updated all places where we create loads, stores to pass in the former
default argument ({Load,Store}OwnershipQualifier::Unqualified), to
SILBuilder::create{Load,Store}(...). For now, one can just do that in situations
where one needs to create loads/stores, but over time, I am going to tighten the
semantics up via the verifier.

rdar://28685236
2016-10-30 13:07:06 -07:00
Michael Gottesman
362a556af4 [semantic-arc] SILBuilder::emit{Retain,Release}ValueOperation => SILBuilder::emit{Copy,Destroy}ValueOperation.
rdar://28851920
2016-10-25 13:12:52 -07:00
John McCall
0bdc8b2a3b Merge pull request #4689 from rjmccall/optional-abstraction
Abstract the object type of optional types
2016-09-09 10:19:36 -07:00
Jordan Rose
a335ebce80 [SILGen] Restore old logic for checking (non-)zero error results. (#4681)
Actually bridging ObjCBool to Bool is overkill for this, but moreover
it caused problems for non-boolean types that took this code
path. Just go back to the previous logic of unwrapping multiple levels
of struct; this way we can also handle wrappers around integer types
(if we ever have any).

rdar://problem/27985744
2016-09-09 09:31:59 -07:00
John McCall
34fb15e375 Abstract the object type of an optional type according to the
abstraction pattern of the type rather than always using the
most-general pattern, and erase ImplicitlyUnwrappedOptional from
the SIL type system.
2016-09-08 23:26:19 -07:00
Slava Pestov
0004bc480a IRGen: Differentiate between Swift.Bool and ObjCBool
SIL already does this where necessary, except with foreign throwing
functions; this patch changes Sema and the ClangImporter to give
them an ObjCBool foreign error result type explicitly.

This fixes a problem where calls to functions taking and returning
the C99 _Bool type were miscompiled on Mac OS X x86-64, because
IRGen was conflating the Objective-C BOOL type (which is a signed
char on some platforms) and C99 _Bool (which lowers as the LLVM
i1 type).

Fixes <rdar://problem/26506458> and <rdar://problem/27365520>.
2016-08-10 10:34:24 -07:00
Doug Gregor
823c24b355 [SE-0112] Rename ErrorProtocol to Error.
This is bullet (5) of the proposed solution in SE-0112, and the last
major piece to be implemented.
2016-07-12 10:53:52 -07:00
Jordan Rose
bc83940301 Make pointer nullability explicit using Optional.
Implements SE-0055: https://github.com/apple/swift-evolution/blob/master/proposals/0055-optional-unsafe-pointers.md

- Add NULL as an extra inhabitant of Builtin.RawPointer (currently
  hardcoded to 0 rather than being target-dependent).
- Import non-object pointers as Optional/IUO when nullable/null_unspecified
  (like everything else).
- Change the type checker's *-to-pointer conversions to handle a layer of
  optional.
- Use 'AutoreleasingUnsafeMutablePointer<NSError?>?' as the type of error
  parameters exported to Objective-C.
- Drop NilLiteralConvertible conformance for all pointer types.
- Update the standard library and then all the tests.

I've decided to leave this commit only updating existing tests; any new
tests will come in the following commits. (That may mean some additional
implementation work to follow.)

The other major piece that's missing here is migration. I'm hoping we get
a lot of that with Swift 1.1's work for optional object references, but
I still need to investigate.
2016-04-11 20:06:38 -07:00
practicalswift
66183cdbf7 [gardening] Fix unjustified spacing 2016-04-07 10:10:24 +02:00
Dmitri Gribenko
0f36bec31f Merge remote-tracking branch 'origin/master' into swift-3-api-guidelines 2016-02-18 16:41:35 -08:00
John McCall
e249fd680e Destructure result types in SIL function types.
Similarly to how we've always handled parameter types, we
now recursively expand tuples in result types and separately
determine a result convention for each result.

The most important code-generation change here is that
indirect results are now returned separately from each
other and from any direct results.  It is generally far
better, when receiving an indirect result, to receive it
as an independent result; the caller is much more likely
to be able to directly receive the result in the address
they want to initialize, rather than having to receive it
in temporary memory and then copy parts of it into the
target.

The most important conceptual change here that clients and
producers of SIL must be aware of is the new distinction
between a SILFunctionType's *parameters* and its *argument
list*.  The former is just the formal parameters, derived
purely from the parameter types of the original function;
indirect results are no longer in this list.  The latter
includes the indirect result arguments; as always, all
the indirect results strictly precede the parameters.
Apply instructions and entry block arguments follow the
argument list, not the parameter list.

A relatively minor change is that there can now be multiple
direct results, each with its own result convention.
This is a minor change because I've chosen to leave
return instructions as taking a single operand and
apply instructions as producing a single result; when
the type describes multiple results, they are implicitly
bound up in a tuple.  It might make sense to split these
up and allow e.g. return instructions to take a list
of operands; however, it's not clear what to do on the
caller side, and this would be a major change that can
be separated out from this already over-large patch.

Unsurprisingly, the most invasive changes here are in
SILGen; this requires substantial reworking of both call
emission and reabstraction.  It also proved important
to switch several SILGen operations over to work with
RValue instead of ManagedValue, since otherwise they
would be forced to spuriously "implode" buffers.
2016-02-18 01:26:28 -08:00
Max Moiseev
61c837209b Merge remote-tracking branch 'origin/master' into swift-3-api-guidelines 2016-02-04 16:13:39 -08:00
Erik Eckstein
506ab9809f SIL: remove getTyp() from SILValue 2016-01-25 15:00:49 -08:00