Commit Graph

1246 Commits

Author SHA1 Message Date
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
Joe Groff
f5676400f5 SILGen: Don't leak when opening an existential 'self' argument to an application.
Swift SVN r26289
2015-03-19 00:54:02 +00:00
Michael Gottesman
3c2216b115 [+0 self] Add the deallocating parameter convention.
The deallocating parameter convention is a new convention put on a
non-trivial parameter if the caller function guarantees to the callee
that the parameter has the deallocating bit set in its object header.

This means that retains and releases do not need to be emitted on these
parameters even though they are non-trivial. This helps to solve a bug
in +0 self and makes it trivial for the optimizer to perform
optimizations based on this property.

It is not emitted yet by SILGen and will only be put on the self
argument of Deallocator functions.

Swift SVN r26179
2015-03-16 07:51:11 +00:00
Joe Groff
962a87f444 SIL: Rename address-only existential instructions to '{init,deinit,open}_existential_addr'.
For better consistency with other address-only instruction variants, and to open the door to new exciting existential representations (such as a refcounted boxed representation for ErrorType).

Swift SVN r25902
2015-03-09 23:55:31 +00:00
Joe Groff
5629d5cdd0 SILGen: Handle scalar-to-tuple shuffles in function arguments.
Deferring to emitRValue doesn't work for inout parameters. Factor out the code for shuffling arguments in TupleShuffleExprs so we can reuse for ScalarToTuple transformations. Building what amounts to a fake TupleShuffle out of a ScalarToTuple isn't the most elegant solution, but I think it's the lowest-risk approach for the short term. Fixes rdar://problem/19814841.

Swift SVN r25290
2015-02-14 01:02:13 +00:00
Joe Groff
7d811bf1da SILGen: Load when an lvalue base is passed to a nonmutating accessor.
This shouldn't happen, but this is a low-risk workaround to fix rdar://problem/19782170.

Swift SVN r25241
2015-02-12 17:01:56 +00:00
Joe Groff
b0fabcef7b Sema: Force dynamic materializeForSet accessors to be statically dispatched.
The materializeForSet accessor for a `dynamic` property needs to dynamically invoke the getter and setter of the property in order to allow for runtime modification, so it doesn't need to be dynamically dispatched itself. If the property came from an imported ObjC class, then we can't dynamically dispatch it without polluting the selector namespace. Introduce a new 'ForcedStaticDispatch' bit and set it in order to force `dynamic` materializeForSet accessors to be statically dispatched. (They can't be `final` because it's legal to override a dynamic property.) If the property came from ObjC, register materializeForSet as an external declaration so it gets generated by SIL. Fixes rdar://problem/18706056.

Swift SVN r24930
2015-02-04 00:46:24 +00:00
Nadav Rotem
3d8e7bcf92 Fix a few warnings of unused variables in the -no-assertions build.
Swift SVN r24921
2015-02-03 19:41:10 +00:00
John McCall
bf75beeb7a Begin formal accesses on l-value arguments immediately before
the call instead of during the formal evaluation of the argument.

This is the last major chunk of the semantic changes proposed
in the accessors document.  It has two purposes, both related
to the fact that it shortens the duration of the formal access.

First, the change isolates later evaluations (as long as they
precede the call) from the formal access, preventing them from
spuriously seeing unspecified behavior.  For example::

  foo(&array[0], bar(array))

Here the value passed to bar is a proper copy of 'array',
and if bar() decides to stash it aside, any modifications
to 'array[0]' made by foo() will not spontaneously appear
in the copy.  (In contrast, if something caused a copy of
'array' during foo()'s execution, that copy would violate
our formal access rules and would therefore be allowed to
have an arbitrary value at index 0.)

Second, when a mutating access uses a pinning addressor, the
change limits the amount of arbitrary code that falls between
the pin and unpin.  For example::

  array[0] += countNodes(subtree)

Previously, we would begin the access to array[0] before the
call to countNodes().  To eliminate the pin and unpin, the
optimizer would have needed to prove that countNodes didn't
access the same array.  With this change, the call is evaluated
first, and the access instead begins immediately before the call
to +=.  Since that operator is easily inlined, it becomes
straightforward to eliminate the pin/unpin.

A number of other changes got bundled up with this in ways that
are hard to tease apart.  In particular:

  - RValueSource is now ArgumentSource and can now store LValues.

  - It is now illegal to use emitRValue to emit an l-value.

  - Call argument emission is now smart enough to emit tuple
    shuffles itself, applying abstraction patterns in reverse
    through the shuffle.  It also evaluates varargs elements
    directly into the array.

  - AllowPlusZero has been split in two.  AllowImmediatePlusZero
    is useful when you are going to immediately consume the value;
    this is good enough to avoid copies/retains when reading a 'var'.
    AllowGuaranteedPlusZero is useful when you need a stronger
    guarantee, e.g. when arbitrary code might intervene between
    evaluation and use; it's still good enough to avoid copies
    from a 'let'.  The upshot is that we're now a lot smarter
    about generally avoiding retains on lets, but we've also
    gotten properly paranoid about calling non-mutating methods
    on vars.

    (Note that you can't necessarily avoid a copy when passing
    something in a var to an @in_guaranteed parameter!  You
    first have to prove that nothing can assign to the var during
    the call.  That should be easy as long as the var hasn't
    escaped, but that does need to be proven first, so we can't
    do it in SILGen.)

Swift SVN r24709
2015-01-24 13:05:46 +00:00
John McCall
cae0f6e3db Add the ability for a owning addressor to return
a non-native owner.  This is required by Slice, which
will use an ObjC immutable array object as the owner
as long as all the elements are contiguous.

As part of this, I decided it was best to encode the
native requirement in the accessor names.  This makes
some of these accessors really long; we can revisit this
if we productize this feature.

Note that pinning addressors still require a native
owner, since pinning as a feature is specific to swift
refcounting.

Swift SVN r24420
2015-01-14 19:14:20 +00:00