Commit Graph

405 Commits

Author SHA1 Message Date
Slava Pestov
e1f0f02480 SILGen: Three-parameter re-abstraction thunks
Right now, re-abstraction thunks are set up to convert values
as follows, where L is type lowering:

- OrigToSubst: L(origType, substType) -> L(substType)
- SubstToOrig: L(substType) -> L(origType, substType)

This assumes there's no AST-level type conversion, because
when we visit a type in contravariant position, we flip the
direction of the transform but we're still converting *to*
substType -- which will now equal to the type of the input,
not the type of the expected result!

This caused several problems:

- VTable thunk generation had a bunch of special logic to
  compute a substOverrideType, and wrap the thunk result
  in an optional, duplicating work done in the transform

- Witness thunk generation similarly had to handle the case
  of upcasting to a base class to call the witness, and
  casting the result of materializeForSet back to the right
  type for properties defined on the base.

  Now the materializeForSet cast sequence is a bit longer,
  we unpack the returned tuple and do a convert_function
  on the function, then pack it again -- before we would
  unchecked_ref_cast the tuple, which is technically
  incorrect since the tuple is not a ref, but IRGen didn't
  seem to care...

To handle the conversions correctly, we add a third AST type
parameter to a transform, named inputType. Now, transforms
perform these conversions:

- OrigToSubst: L(origType, inputType) -> L(substType)
- SubstToOrig: L(inputType) -> L(origType, substType)

When we flip the direction of the transform while visiting
types in contravariant position, we also swap substType with
inputType.

Note that this is similar to how bridging thunks work, for
the same reason -- bridging thunks convert between AST types.

This is mostly just a nice cleanup that fixes some obscure
corner cases for now, but this functionality will be used
in a subsequent patch.

Swift SVN r31486
2015-08-26 09:15:29 +00:00
Slava Pestov
7a2018ef52 SILGen: fix conversions from @convention(c) to @convention({thick,block})
Also clean up some code and add some tests for FunctionConversionExpr,
which will be very important in subsequent patches.

Swift SVN r31400
2015-08-22 03:17:02 +00:00
Slava Pestov
e416bfbc4e SILGen: Refactor code for existentials
We need to be able to introduce and eliminate existentials inside
reabstraction thunks, so make this logic independent of RValue
and Expr emission.

NFC for now.

Swift SVN r31375
2015-08-21 02:26:57 +00:00
Slava Pestov
9b74a4b0d6 SILGen: Fix memory leak when sub-expression of ErasureExpr throws
If we didn't initialize the existential, we have to emit a cleanup
because we may have allocated a buffer on the heap to store the value.

Factor out the TakeExistentialCleanup that appears in a few places,
rename it to DeinitExistentialCleanup and add support for deallocating
boxed existentials.

Then, use a special Initialization subclass to keep track of the
state of the memory in emit{AddressOnly,Boxed}Erasure().

Swift SVN r31259
2015-08-16 16:45:44 +00:00
John McCall
0c39ec02fa Don't use materializeForSet when accessing properties or
subscripts defined in protocol extensions.

The right condition for this is really direct uses of the
default implementation; right now, that just means all
direct uses of something from a protocol extension.

Fixes rdar://22109071.

Swift SVN r31228
2015-08-13 21:49:14 +00:00
John McCall
7e81f7e129 Fix a number of bugs with the new materializeForSet SILGen,
including one which triggered only for non-subscripts and
a number which triggered with different cases of classes.

Swift SVN r31198
2015-08-13 01:52:17 +00:00
Slava Pestov
48fe3e1c9b SILGen: Fix static computed properties in protocol extensions
We need to keep the AST formal type of the base around when building up
lvalues.

When the getter or setter involves an accessor call, we would use the
lowered type of the self argument to form the call. However, it might be
at the wrong level of abstraction, causing a @thin -vs- @thick metatype
mismatch. Using the formal type instead allows SILGenApply logic to emit
a thin to thick metatype conversion if necessary.

Fixes <rdar://problem/21358641>.

Swift SVN r30913
2015-08-01 07:21:25 +00:00
Doug Gregor
07135ac4e9 Handle initializer delegation in a protocol extension with a class-bound Self.
When extending a protocol where the 'Self' type is a subclass of some
known class type, initializers within the protocol extension can
delegate to required initializers of that superclass bound. Correctly
adjust the 'self' we produce in SILGen to the superclass type.

Fixes rdar://problem/21370992.

Swift SVN r30584
2015-07-24 18:22:43 +00:00
Doug Gregor
f00e5bc6ab Allow a variadic parameter anywhere in the parameter list.
Requiring a variadic parameter to come at the end of the parameter
list is an old restriction that makes no sense nowadays, and which we
had all thought we had already lifted. It made variadic parameters
unusable with trailing closures or defaulted arguments, and made our
new print() design unimplementable.

Remove this restriction, replacing it with a less onerous and slightly
less silly restriction that we not have more than one variadic
parameter in a given parameter clause. Fixes rdar://problem/20127197.

Swift SVN r30542
2015-07-23 18:45:29 +00:00
Slava Pestov
35e55940ca SILGen: Fix miscompile if witness is a property defined in base class
Fixes <rdar://problem/21375219>.

Swift SVN r29901
2015-07-02 21:31:07 +00:00
Slava Pestov
7b2aa2c0a2 SILGen: Fix lvalue reabstraction
We didn't have any tests exercising SubstToOrigComponent and in
fact it was broken. Fix emitInOut() to remove a level of inout
from the origParam abstraction pattern and add some tests.

Fixes <rdar://problem/20985062>.

Swift SVN r29644
2015-06-24 22:27:54 +00:00
Slava Pestov
a64d505a98 SILGen: Fix some problems when generating delegating init calls
- If delegating to an initializing constructor for a value type,
  the ApplyInst takes an @out parameter for Self, instead of
  returning Self like with references. Fix the def-use traversal
  to handle that instead of crashing.

- When calling an allocating constructor, the formal type is
  the instance type because Sema constructs the constructor call
  as if it were an initializing constructor. This causes us to
  fail to re-abstract a @thin metatype to @thick. Fix this to
  use the correct metatype type for allocating constructors.

Fixes <rdar://problem/20945954>.

Swift SVN r29555
2015-06-22 22:26:17 +00:00
Slava Pestov
7319a97ab4 Sema: Rewrite witness method calls as ApplyExpr + DeclRefExpr
Special-casing these as MemberRefExprs created an asymmetry
where unbound archetype instance methods (<T : P> T.f) could
not be represented. Treating class and protocol methods
uniformly also eliminates a handful of special cases around
MemberRefExpr.

SILGen's RValue and call emission peepholes now have to know
about DeclRefExprs that point to protocol methods.

Finally, generalize the diagnostic for partially applied
mutating methods to any partially applied function with an
inout parameter, since this is not supported.

Fixes <rdar://problem/20564672>.

Swift SVN r29298
2015-06-04 15:57:58 +00:00
Joe Groff
96638e3028 SILGen: Properly type reabstracted overrides in calls and witness thunks.
Fixes most of rdar://problem/20874966, though curry thunks are still broken (filed as rdar://problem/21167978).

Swift SVN r29160
2015-05-30 00:41:55 +00:00
John McCall
af25b38029 Teach SILFunctionType substitution to handle foreign error conventions.
Normally, ObjC methods are never generic, but this comes up
with protocol methods.

rdar://21051021

Swift SVN r28900
2015-05-22 01:23:04 +00:00
John McCall
26a9a4d1e5 SILGen for 'rethrows'. WIP; committed to get broader testing
of an assertion.

Swift SVN r28733
2015-05-19 00:54:32 +00:00
John McCall
f0f8787b0f Generalize the 'transparent' flag passed around to
various emitApply routines.  NFC.

Swift SVN r28720
2015-05-18 20:30:12 +00:00
Slava Pestov
2098c60131 SIL: Generate emitRawApply()'s @guaranteed cleanups with CleanupLocation
These used a RegularLocation because the mechanism is different from
the usual Cleanup stuff, which is tied to a specific scope.

Using a CleanupLocation prevents unreachable code diagnostics from
complaining if we call a @noreturn with guaranteed.

If we diagnose while emitting one of the cleanups, the diagnostic will
point to the end of the apply expression rather than the start, but I
don't think that matters.

Swift SVN r28690
2015-05-18 00:26:19 +00:00
John McCall
312a9c1f6e Clean up correctly if a variadic argument throws.
rdar://20942603

Swift SVN r28622
2015-05-15 08:20:36 +00:00
Joe Groff
a32b14e0a8 SILGen: Don't try to witness-dispatch extension inits that delegate to other extension inits.
Fixes rdar://problem/20841699.

Swift SVN r28263
2015-05-07 14:38:34 +00:00
John McCall
36c605f7dc Remove ScalarToTupleExpr in favor of a flag on TupleShuffleExpr.
Also, implement in-place initialization through tuple shuffles.

Swift SVN r28227
2015-05-06 23:44:26 +00:00
Joe Groff
e2962ed213 SILGen: Implement recursive local function references.
Instead of immediately creating closures for local function declarations and treating them directly as capturable values, break function captures down and transitively capture the storage necessary to invoke the captured functions. Change the way SILGen emits calls to closures and local functions so that it treats the capture list as the first curry level of an invocation, so that full applications of closure literals or nested functions don't require a partial apply at all. This allows references among local functions with captures to work within the existing confines of partial_apply, and also has the nice benefit that circular references would work without creating reference cycles (though Sema unfortunately rejects them; something we arguably ought to fix.)

This fixes rdar://problem/11266246 and improves codegen of local functions. Full applications of functions, or immediate applications of closure literals like { }(), now never need to allocate a closure.

Swift SVN r28112
2015-05-04 05:33:55 +00:00
John McCall
58b5e1dc0f Implement error handling in protocol witness and
reabstraction thunks.

rdar://20782111

Swift SVN r28075
2015-05-02 04:37:30 +00:00
Joe Groff
384ae282c7 SILGen: Emit @objc protocol extension initializers.
In @objc protocols, the initializing entry point is witnessed (as an -init method) rather than the allocating entry point, so the extension initializer needs to allocate the object and delegate to the initializing constructor.

Swift SVN r27940
2015-04-29 23:01:50 +00:00
Joe Groff
6de9d84b1f SILGen: Handle initializers in protocol extensions.
For the most part, this just involves spot fixes to make sure protocol inits follow the same paths as value type initializers would, with the extra wrinkle that we have to ensure we forward the correct metatype from the delegating initializer to the delegatee, in case the initializer is invoked with a different dynamic type from the static Self type. This should handle non-@objc delegations; @objc will need some additional work.

Swift SVN r27900
2015-04-29 02:40:30 +00:00
Chris Lattner
caeca69466 fix <rdar://problem/19086357> SILGen crashes reabstracting default argument closure in members
When emitting default arguments for a parameter, emitApplyOfDefaultArgGenerator
was trying to reconstruct the original type by looking at the decl that it came
from.  However, it doesn't know the number of curry levels already applied, so it
was wrong in the case of default arguments on methods and initializers (which already
have self applied).

Fix this by having the caller pass this information in, since it knows the original
type.

While we're at it, remove the code for handling default arguments from the general 
SILGenExpr logic.  Default arguments in tuples are no longer a general thing, they 
are only valid in argument lists.



Swift SVN r27800
2015-04-27 04:29:32 +00:00
John McCall
d84a95f325 Handle foreign error conventions in foreign-to-native thunks.
Swift SVN r27737
2015-04-26 00:12:52 +00:00
Michael Gottesman
11622986a0 [+0 self] Teach SILGen how to avoid emitting an extra rr pair on self when calling a dynamic dispatch method on a let.
The main thing that this patch does is work around a shortcoming of
SILGenApply namely that we in certain cases emit self before we know
what the callee is. We work around this by emitting self at +0 assuming
that the callee does pass self at +0 and set a flag. After we know what
the callee is, if the flag is set, we emit an extra retain for self.

rdar://15729033

Swift SVN r27553
2015-04-22 03:02:05 +00:00
Michael Gottesman
b8a913e034 Standardize capitalization of fields of SILGenApply to SILGen standard conventions.
Swift SVN r27552
2015-04-22 03:02:02 +00:00
Joe Groff
3f38d75006 SILGen: Currying of 'super.method' calls.
Keep track of a second set of "direct method reference" curry thunks that don't end in a dynamic dispatch in order to properly implement a partial application such as 'let foo = super.foo'. Fixes rdar://problem/20598526.

Swift SVN r27538
2015-04-21 22:56:03 +00:00
Michael Gottesman
7f366fc664 Standardize the variable names of Callee the other way. Sorry about that John!
Swift SVN r27509
2015-04-20 23:49:21 +00:00
Michael Gottesman
baacff1a36 Change some class member names to match SILGen library member capitalization name style. NFC.
Swift SVN r27507
2015-04-20 23:35:39 +00:00
Michael Gottesman
ffe698ddaa Remove trailing whitespace. NFC.
Swift SVN r27506
2015-04-20 23:35:37 +00:00
John McCall
a67452c72c SILGen for throwing foreign errors out of @objc thunks.
Also, create a new file specifically for the foreign-error
code.

Swift SVN r27347
2015-04-16 05:16:54 +00:00
John McCall
156a4c7ed0 SILGen for calls under foreign error conventions. WIP.
Swift SVN r27270
2015-04-14 02:35:54 +00:00
Doug Gregor
997136962e Always open existential types in the type checker.
Consistently open all references into existentials into
opened-existential archetypes within the constraint solver. Then,
during constraint application, use OpenExistentialExprs to record in
the AST where an existential is opened into an archetype, then use
that archetype throughout the subexpression. This simplifies the
overall representation, since we don't end up with a mix of operations
on existentials and operations on archetypes; it's all archetypes,
which tend to have better support down the line in SILGen already.

Start simplifying the code in SILGen by taking away the existential
paths that are no longer needed. I suspect there are more
simplifications to be had here.

The rules for placing OpenExistentialExprs are still a bit ad hoc;
this will get cleaned up later so that we can centralize that
information. Indeed, the one regression in the compiler-crasher suite
is because we're not closing out an open existential along an error
path.

Swift SVN r27230
2015-04-11 03:20:22 +00:00
John McCall
79cc258f65 Lower 'throws' to an error result.
Swift SVN r27108
2015-04-08 00:09:29 +00:00
Joe Groff
ad0d20c07a Fold "AbstractCC" into SILFunctionType::Representation.
These aren't really orthogonal concerns--you'll never have a @thick @cc(objc_method), or an @objc_block @cc(witness_method)--and we have gross decision trees all over the codebase that try to hopscotch between the subset of combinations that make sense. Stop the madness by eliminating AbstractCC and folding its states into SILFunctionTypeRepresentation. This cleans up a ton of code across the compiler.

I couldn't quite eliminate AbstractCC's information from AST function types, since SIL type lowering transiently created AnyFunctionTypes with AbstractCCs set, even though these never occur at the source level. To accommodate type lowering, allow AnyFunctionType::ExtInfo to carry a SILFunctionTypeRepresentation, and arrange for the overlapping representations to share raw values.

In order to avoid disturbing test output, AST and SILFunctionTypes are still printed and parsed using the existing @thin/@thick/@objc_block and @cc() attributes, which is kind of gross, but lets me stage in the real source-breaking change separately.

Swift SVN r27095
2015-04-07 21:59:39 +00:00
Joe Groff
4821f594bb SIL: Separate SILFunctionType::Representation and ExtInfo from AST FunctionTypes.
The set of attributes that make sense at the AST level is increasingly divergent from those at the SIL level, so it doesn't really make sense for these to be the same. It'll also help prevent us from accidental unwanted propagation of attributes from the AST to SIL, which has caused bugs in the past. For staging purposes, start off with SILFunctionType's versions exactly the same as the FunctionType versions, which necessitates some ugly glue code but minimizes the potential disruption.

Swift SVN r27022
2015-04-05 17:04:55 +00:00
John McCall
dc4b8ff2c2 Incorporate an optional Clang type into AbstractionPattern.
This is necessary for correctly dealing with non-standard
ownership conventions in secondary positions, and it should
also help with non-injective type imports (like BOOL/_Bool).
But right now we aren't doing much with it.

Swift SVN r26954
2015-04-03 21:39:31 +00:00
Chris Lattner
79ed57f9f2 standardize naming of tuples and tuple patterns on "elements".
Previously some parts of the compiler referred to them as "fields",
and most referred to them as "elements".  Use the more generic 'elements'
nomenclature because that's what we refer to other things in the compiler
(e.g. the elements of a bracestmt).

At the same time, make the API better by providing "getElement" consistently
and using it, instead of getElements()[i].

NFC.



Swift SVN r26894
2015-04-02 20:23:49 +00:00
Joe Pamer
eee40fc53f Add basic parsing, sema and mangling support for throwing function types. Next up, metadata and serialization support, as well as more tests.
Swift SVN r26767
2015-03-31 18:55:19 +00:00
Joe Groff
751724c3fa SILGen: Special-case NSError to ErrorType erasure.
We want this to be a "toll-free" adoption of the class reference without requiring a second box allocation.

Swift SVN r26711
2015-03-30 04:52:41 +00:00
Doug Gregor
3d77855b31 Start allowing extensions of protocol types.
Remove the semantic restrictions that prohibited extensions of
protocol types, and start making some systematic changes so that
protocol extensions start to make sense:
  - Replace a lot of occurrences of isa<ProtocolDecl> and
    dyn_cast<ProtocolDecl> on DeclContexts to use the new
    DeclContext::isProtocolOrProtocolExtensionContext(), where we want
    that behavior to apply equally to protocols and protocol extensions.
  - Eliminate ProtocolDecl::getSelf() in favor of
    DeclContext::getProtocolSelf(), which produces the appropriate
    generic type parameter for the 'Self' of a protocol or protocol
    extension. Update all of the callers of ProtocolDecl::getSelf()
    appropriately.
  - Update extension validation to appropriately form generic
    parameter lists for protocol extensions.
  - Methods in protocol extensions always use the witnesscc calling
  convention.

At this point, we can type check and SILGen very basic definitions of
protocol extensions with methods that can call protocol requirements,
generic free functions, and other methods within the same protocol
extension.

Regresses four compiler crashers but improves three compiler
crashers... we'll call that "progress"; the four regressions all hit
the same assertion in the constraint system that will likely be
addressed as protocol extensions starts working.

Swift SVN r26579
2015-03-26 04:50:51 +00:00
John McCall
35b7db3ae1 Parsing support for error results from SILFunctionType.
Swift SVN r26566
2015-03-26 00:01:32 +00:00
Mark Lacey
1f23ff27bb Remove the transparent bit from apply instructions.
We no longer need or use it since we can always refer to the same bit on
the applied function when deciding whether to inline during mandatory
inlining.

Resolves rdar://problem/19478366.

Swift SVN r26534
2015-03-25 08:36:34 +00:00
John McCall
08d3460a19 Implement throw expressions. Untested.
Tests tomorrow for this and 'catch', I promise. :)

Swift SVN r26432
2015-03-23 08:10:15 +00:00
John McCall
ee4aa14703 Stop reordering blocks in SILBuilder::emitBlock.
This change permits SILGen to make smarter decisions about
block placement by keeping related blocks together instead
of always inserting to the end to the function.  The
flipside is that SILGen needs to be somewhat careful to
create blocks in the right order.  Counter-intuitively,
that order is the reverse of the order in which the blocks
should be laid out, since blocks created later will be
inserted before blocks created earlier.  Note, however,
that this produces the right results for recursive
emission.

To that end, adjust a couple of places in SILGen to
create blocks in properly nested order.

All of the block-order differences in the tests seem
to be desirable; several of them even had confused
comments wondering how on earth a block got injected
where it did.

Also, fix the implementation of SILBuilder::moveBlockTo,
and fix a latent bug in epilogue emission where epilogBB
was erased from its parent (deleting it) and then
queried multiple times (!).

Swift SVN r26428
2015-03-23 06:38:20 +00:00
Michael Gottesman
41747b6ce2 [+0 self] Enforce the retain/copy, call, release/destroy pattern for @guaranteed and @in_guaranteed parameters.
This means:

1. In_Guaranteed when preparing accessor base args is like @in not
   @inout. This is because @in_guaranteed parameters are immutable. We
   were not miscompiling since we were not inserting cleanups for these
   parameters. Now with 2, we perform the copy so we have the immutable
   property and then destroy_addr the result after the call.

2. If we have a guaranteed parameter, we put the destroy value right
   after the call instead of at the end of expression.

The reason 2 is necessary is that if we destroy the value at the end of
scope situations like the following cause COW to fail:

    struct Foo {
      let object: AnyObject

      var rawObject: Builtin.RawPointer {
        return Builtin.bridgeToRawPointer(object) // Psuedoname of builtin.
      }

      mutating func isUnique() -> Bool {
        return isUnique(rawObject)
      }
    }

What happens is that because Foo.isUnique is mutating, Foo is passed in
@inout. Since @inout is a guarantee related to memory, SILGen has to
increment the refcount of self to guarantee self's lifetime. Before this
patch we would have (in pseudo-sil).

    %self = load %ptr_self
    retain_value %self
    %0 = getRawObject() // guaranteed call.
    %result = isUnique(%0)
    release_value %self

This causes the COW check to always fail. There is no reason to extend
the lifetime of %self so far, guaranteed only means that the object's
lifetime is guaranteed over the call in question. So now instead, we
release after the call.

<rdar://problem/20094305>
<rdar://problem/20234910>

Swift SVN r26351
2015-03-20 07:34:51 +00:00
Joe Groff
970958c43c SILGen: Support method and property lookup on boxed existentials.
Swift SVN r26290
2015-03-19 02:10:14 +00:00