Commit Graph

145 Commits

Author SHA1 Message Date
Roman Levenstein
3721ee9c87 [sil-combine] Fix a bug in the peephole apply{partial_apply(x,y)}(z) -> apply(z,x,y)
The existing implementation of this peephole was miscompiling when some arguments of a partial_apply were alloc_stack, because some of they could be dead before the apply which uses the partial_apply. To fix this problem I had to re-factor the implementation. Earlier we were looking for an apply first and then for a partial_apply it uses. With this patch, we do it the other way around: we fist look for a partial_apply and then peephole all apply instructions referring to it in one go. To solve the problem with "prematurely" dead alloc_stack arguments, we introduce new temporaries with a longer lifetime and copy the original arguments into them.

The test-cases are extended with more complex examples, including usage of existentials.

This fixes the compile-time crasher in test/Interpreter/currying_generics.swift

rdar://20868728

Swift SVN r28570
2015-05-14 17:21:18 +00:00
Andrew Trick
313c30ad58 Prohibit specialization on DynamicSelf type.
Fixes <rdar://problem/20044992> Swift: Generic functions called from
class methods with type parameter inferred to Self compiles, breaks
type system under optimization

If we don't prohibit specialization then we silently miscompile by
assuming a base class instead of the dynamic type.

It is unclear to me why GenericFunctionType did not inherit any
recursive type properties from it's arguments and result. However, it
I think it makes sense to propagate DynamicSelfType into
GenericFunctionType so I've broke with convention here.

Swift SVN r28541
2015-05-13 23:36:17 +00:00
Arnold Schwaighofer
2d14ab95b3 Don't use Shared linkage for specialized stdlib_binary_only functions
We don't serialize their bodies because we only want them in the stdlib dylib.
Marking them Shared changes their visibility to hidden and the linker gets angry
when it tries to link their symbol in another object.

rdar://20907669

Swift SVN r28536
2015-05-13 21:49:06 +00:00
Roman Levenstein
0857b69d4a [sil-combine] Bail earlier, if emitSuccessfulScalarUnconditionalCast cannot be applied.
Fixes a compile time crasher when the whole test-suite is compiled with -O.

Swift SVN r28516
2015-05-13 17:50:36 +00:00
Roman Levenstein
a444f78cdf [sil-combine] Fix a verifier assertion triggered by compiling the objc_bridge_cast.swift test with -O
If the target ObjC type of a bridged cast is not the exact type being expected, but one of its superclasses, perform an upcast (e.g. upcast NSArray to NSObject).

rdar://20869055

Swift SVN r28319
2015-05-08 17:55:38 +00:00
Roman Levenstein
e0684ecc11 [sil-combine] Make cast optimiser less fragile
- The cast optimiser was asserting if it could not find the _forceBridgeFromObjectiveC implementations in the Foundation module (where all stdlib bridged types reside). Now it checks the module being compiled as well.
- If a bridging function cannot be found, don't assert and bail out instead. After all, it is just an optimization and even if it cannot be applied, we should not crash.

This makes Swift :: 1_stdlib/ArrayBridge.swift compile with -O.

rdar://20845536

Swift SVN r28295
2015-05-07 22:24:48 +00:00
Michael Gottesman
9006fca42b Rename SILBuilder::emitDestroyAddr => SILBuilder::emitDestroyAddrAndFold.
Now it matches SILBuilder::emit{StrongRelease,ReleaseValue}AndFold which perform
the same operation but on object types.

Swift SVN r27806
2015-04-27 17:29:50 +00:00
Michael Gottesman
a3aa89d4c4 Remove Callback from SILBuilder and instead rename
emit{StrongRelease,ReleaseValue} => emit{StrongRelease,ReleaseValue}AndFold.
Then introduce a new method emit{StrongRelease,ReleaseValue} that returns a
PointerUnion containing the increment to be deleted if it exists. This obviates
the need for the callback.

Swift SVN r27804
2015-04-27 07:29:13 +00:00
Michael Gottesman
583d7aa30a Add a delete callback to SILBuilder so that if we delete retains and releases in emitStrongRelease, emitReleaseValue, passes (like SILCombine) can update their state. Also teach the closure deletion code how to detect such a case and not send a notification message if no new instruction is created.
Swift SVN r27803
2015-04-27 05:37:09 +00:00
Michael Gottesman
d494735329 Teach capture promotion how to handle all types of partial apply arguments. We technically don't need it now but it would be technical debt to leave it unfixed.
rdar://19552593

Swift SVN r27798
2015-04-27 01:59:46 +00:00
Michael Gottesman
abb34fa1b0 Teach mandatory inlining how to use closure deletion infrastructure.
rdar://19552593

Swift SVN r27751
2015-04-26 05:11:57 +00:00
Michael Gottesman
eed6317da2 Add a callback struct to tryDeleteDeadClosure() that clients can use to be notified of instruction insertion and deletion.
rdar://19552593

Swift SVN r27749
2015-04-26 05:11:54 +00:00
Michael Gottesman
6891258151 Teach tryDeleteDeadClosure how to properly delete all types of captured arguments.
Previously, we relied on certain types not being passed in by the users of the
given function. Since I had a lot on my plate on the time and I knew it was safe
I left it in. Now I am going to be using this function in more places so it
needs to handle everything correctly.

rdar://19552593

Swift SVN r27748
2015-04-26 05:11:52 +00:00
Mark Lacey
60311dab22 Coding style clean-ups.
Remove else after return, reduce indentation, etc.

Noticed while reviewing code that uses various SILValue::strip*Casts()
functions.

Swift SVN r27574
2015-04-22 08:24:10 +00:00
Mark Lacey
1859b476d4 Further integration of inlining, devirtualization, and specialization.
This updates the performance inliner to iterate on inlining in cases
where devirtualization or specialization after the first pass of
inlining expose new opportunities for inlining. Similarly, in some cases
inlining exposes new opportunities for devirtualization, e.g. when we
inline an initializer and can now see an alloc_ref that allows us to
devirtualize some class_methods.

The implementation currently has some inefficiencies which increase the
swift compilation time for the stdlib by around 3% (this is swift-time
only, no LLVM time, so overall time does not grow by this much).

Unfortunately the (unchanged) current implementation of the core
inlining trades off improved estimates of code growth for increased
compile time, and that plays a part in why compile time increases as
much as it does. Despite this, I have some ideas on how to win some of
that time back in future patches.

Performance differences are mixed, and this will likely require some
further inliner tuning to reduce or remove some of the losses seen here
at -O. I will open radars for the losses.

Wins:
DeltaBlue                        10.2%
EditDistance                     13.8%
SwiftStructuresInsertionSort     32.6%
SwiftStructuresStack             34.9%

Losses:
PopFrontArrayGeneric            -12.7%
PrimeNum                        -19.0%
RC4                             -30.7%
Sim2DArray                      -14.6%

There were a handful of wins and losses at Onone and Ounchecked as
well. I'll review the perf testing output and open radars accordingly.

The new test case shows an example of the power of the closer
integration here. We are able to completely devirtualize and inline a
series of class_method applies (10 deep in this case, but in theory
substantially deeper) in a single pass of the inliner, whereas before we
could only do a single level per pass of inlining & devirtualization.

Swift SVN r27561
2015-04-22 04:48:13 +00:00
Nadav Rotem
32211041d2 Rename @semantics -> @_semantics.
Swift SVN r27533
2015-04-21 17:10:06 +00:00
Roman Levenstein
aa07bc3d90 Lower bridged casts always, when the outcome is not provably failing.
Even when we don't know for sure if a bridged cast would succeed, we still want to lower it to produce a more efficient code that does not performs conformance checks at run-time.

This is useful when performing casts optimizations as a guaranteed optimization.

Swift SVN r27377
2015-04-16 20:28:15 +00:00
Roman Levenstein
0f88c56b23 If a result of unconditional_checked_cast is not used, simply remove the cast.
This is useful when performing casts optimizations as a guaranteed optimization.

Swift SVN r27376
2015-04-16 20:28:15 +00:00
Roman Levenstein
12b1e88d3f Fix a bug in a peephole for checked_cast_addr_br.
It was producing a checked_cast_add_br, which took a metatype inst as it's argument, which is simply wrong, as it is not an address type. SILVerifier was complaining about it. Now we produce an equivalent peephole, but with a correct instruction sequence, which makes SILVerifier happy.

Swift SVN r27375
2015-04-16 20:28:12 +00:00
Roman Levenstein
7fe82963f0 Bail early on casts involving unbound generic types. It is too early to optimize them.
Swift SVN r27374
2015-04-16 20:28:11 +00:00
Roman Levenstein
a8cf05343f Don't try to optimize non-addr types in simplifyCheckedCastAddrBranchInst.
Sometimes, during intermediate optimization steps, the operands of produced checked_cast_addr_br instructions do not actually have address types.
Don't try to optimize further in such cases. Let the optimizer clean-up those instructions.

Swift SVN r27373
2015-04-16 20:28:10 +00:00
Roman Levenstein
782a4120a4 If kind of the instruction was changed by the optimizeCheckedCast*BranchInst, bail.
This avoids segfaults due to de-referencing of a nullptr.

Swift SVN r27372
2015-04-16 20:28:10 +00:00
Roman Levenstein
185e96ce8c Clean-up of retain/release insertion during bridged casts optimizations.
I noticed under Instruments that the bridged casts opts produced a code that was leaking in some cases. Therefore I took the change to re-visit the code and to clean-up the logic for insertion of retains and releases.

Swift SVN r27371
2015-04-16 20:28:09 +00:00
Roman Levenstein
0b6b907a0a Do not produce an intermediate cast between the same ObjC types as it will get eliminated anyways.
When casts optimizations were lowering bridged casts from ObjC to Swift, they were producing internally an intermediate cast from an ObjC type into the expected ObjC type of a bridged cast, before converting this expected ObjC type into a Swift type. In many cases, this resulted in a useless intermediate cast where both types were the same and such a cast would be eliminated afterwards. E.g.

unconditional_checked_cast A to B  // where A is ObjC type and B is a Swift type

was lowered into:

unconditional_checked_cast A to B. _ObjectiveCType // Often useless as A is equal to B. _ObjectiveCType already.
unconditional_checked_cast B._ObjectiveCType to B

This small inefficiency is fixed now. This problem was no observable from outside the optimization pass, it just required additional processing, therefore there is no test-case.

Swift SVN r27370
2015-04-16 20:28:07 +00:00
Roman Levenstein
d1698ba1cb Use a _bridgeable suffix for newly introduced fast bridging functions. NFC.
Dave explained that stdlib usually uses the suffix notation in such cases. This change follows his advice.

Swift SVN r27177
2015-04-09 20:59:42 +00:00
Roman Levenstein
90e5f932c7 Simplify the lookup of a compiler-known library function. NFC.
Swift SVN r27157
2015-04-09 02:35:27 +00:00
Roman Levenstein
7c5717d3ad Address Joe's comments on my r27102 commit. NFC.
Swift SVN r27154
2015-04-09 01:51:59 +00:00
Roman Levenstein
2dd38eee0e [sil-combine] Teach the optimizer how to optimize bridged casts.
If a conformance to _BridgedToObjectiveC is statically known, generate a more efficient code by using the newly introduced library functions for bridging casts.
This covers the casts resulting from SIL optimizations.

Tests are included. I tried to cover most typical casts from ObjC types into Swift types and vice versa and to check that we always generate something more efficient than a checked_cast or unconditional_checked_cast. But probably even more tests should be written or generated by means of gyb files to make sure that nothing important is missing.

The plan is to make the bridged casts SIL optimization a guaranteed optimization. Once it is done, there is no need to lower the bridged casts in a special way inside Sema, because they all can be handled by the optimizer in a uniform way. This would apply to bridging of Error types too.

With this change, no run-time conformance checks are performed at run-time if conformances are statically known at compile-time.
As a result, the performance of rdar://19081345 is improved by about 15%. In the past, conformance checks in this test took 50% of its execution time, then after some improvements 15% and now it is 0%, as it should be.

Swift SVN r27102
2015-04-07 22:53:57 +00:00
Mark Lacey
fea3321f59 Update the generic specializer to maintain the call graph.
Swift SVN r27024
2015-04-05 19:27:40 +00:00
Mark Lacey
5adf76b4dd Missed one comment update.
Swift SVN r27019
2015-04-05 07:14:45 +00:00
Mark Lacey
8fad304e02 Fix a leak.
swift::clearBlockBody() in Local.cpp was popping instructions rather
than erasing them, resulting in leaking any instructions removed via
this function (which is reached via removeDeadBlock(), called throughout
SimplifyCFG).

Also tweak a couple comments and remove an assert that cannot fire.

Swift SVN r27018
2015-04-05 07:12:35 +00:00
Mark Lacey
730ef41385 Make devirtualizer clients remove old applies.
This makes it feasible for clients to maintain the call graph.

Swift SVN r26997
2015-04-05 02:27:57 +00:00
Roman Levenstein
55ea9ec0e3 [sil-combine] Minor clean-up of casts optimizations. NFC.
Add more checks and logic into emitSuccessfulIndirectUnconditionalCast and emitSuccessfulScalarUnconditionalCast, so that its clients in sil-combine can be simplified by avoiding looking into special cases.

Swift SVN r26885
2015-04-02 19:57:35 +00:00
Roman Levenstein
a7d0eb17ba [sil-combine] casts to/from existentials cannot be further simplified.
This should fix a bug in Adventure reported in rdar://20396204.

Swift SVN r26875
2015-04-02 17:20:23 +00:00
John McCall
6d8fff9c06 Parsing and basic structure of try_apply. Not yet properly
threaded into IRGen; tests to follow when that's done.

I made a preliminary effort to make the inliner do the
right thing with try_apply, but otherwise tried to avoid
touching the optimizer any more than was required by the
removal of ApplyInstBase.

Swift SVN r26747
2015-03-31 02:41:03 +00:00
Roman Levenstein
7011a5f4b4 [generic-specializer] Add support for specializing generic partial_apply instructions.
Use existing machinery of the generic specializer to produce generic specializations of closures referenced by partial_apply instructions. Thanks to the newly introduced ApplyInstBase class, the required changes in the generic specializer are very minimal.

rdar://19290942

Swift SVN r26582
2015-03-26 06:41:30 +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
Mark Lacey
2cec37e73b Use isTransparent() from the referenced function rather than the apply.
When creating a new apply, we were copying the transparent bit from the
old apply, as well as the referenced function from the old apply. We
should just use the transparent bit from that referenced function.

Swift SVN r26384
2015-03-21 02:06:15 +00:00
Roman Levenstein
f3ae8c1f52 Minor clean-up after my recent re-factoring of cast optimizations. NFC.
Swift SVN r26312
2015-03-19 20:03:44 +00:00
Roman Levenstein
848b9ab488 [sil-simplify-cfg] Fold checked_cast_br if a dynamic type of the operand is statically known from alloc_ref
Transforms :

%1 = alloc_ref $B
checked_cast_br [exact] %1 : $B to $B, bb1, bb2

into

br bb1(%1 : $B)

In case when source and destination types do no match, replace by a branch to the failure bb of the checked_cast_br.

Swift SVN r26275
2015-03-18 20:27:44 +00:00
Chris Lattner
4f708c049b fix const correctness and standardize on names for the successor list of
TerminatorInsts.  Now you can walk over the successor list of a terminator
and actually modify the SILSuccessor directly, allowing better CFG
transformations.  NFC.




Swift SVN r26140
2015-03-14 17:52:27 +00:00
Roman Levenstein
51ad2d964d Move the logic for type casts optimizations into one place.
This is mostly a re-factoring. It creates a new helper class CastOptimizer which contains all the logic for performing type casts optimizations. This logic is a copy of the current logic from sil-combine and simplify-cfg. Those passes will become clients of this new helper class.

Swift SVN r26122
2015-03-14 02:23:05 +00:00
Arnold Schwaighofer
aa24e126e4 ArraySemantic: Move to its own file in SILAnalysis
I want to use it in ARCAnalysis.

Swift SVN r25924
2015-03-10 15:20:20 +00:00
Arnold Schwaighofer
75710bf9c4 Array property functions were enabled by default
No need to conditionalize code anymore. NFC.

Swift SVN r25894
2015-03-09 22:03:06 +00:00
Arnold Schwaighofer
06f7c40c32 ArraySemanticsCall: Handle @guaranteed parameters
Also improve checking of parameter requirements.

This is needed for our move to +0 self.

radar://20039357

Swift SVN r25798
2015-03-06 03:20:47 +00:00
Arnold Schwaighofer
f7c01f2061 Nuke isReadNone function
We can now compute the same result with Inst.mayReadOrWriteMemory(). NFC.

Swift SVN r25743
2015-03-04 05:03:45 +00:00
Arnold Schwaighofer
951dc2875a Nuke isSideEffectFree
We can now compute the same result with Inst.mayHaveSideEffects(). NFC.

Swift SVN r25742
2015-03-04 05:03:44 +00:00
Arnold Schwaighofer
d6cd798de2 stdlib: Add array.props.isNative/needsElementTypeCheck calls
This enables high-level SIL optimizations to speculatively specialize loops into
'fast native swift array' loops vs standard array loops.

This commits adds two semantic calls to Arrays.swift.

   @semantics("array.props.isNative")
   func _getArrayPropertyIsNative() -> Bool

   @semantics("array.props.needsElementTypeCheck")
   func _getArrayPropertyNeedsElementTypeCheck() -> Bool

checkSubscript and getElement get extra arguments to pass in the result of above
function calls. This also allow us to communicate that an array that was made
mutable is always native. The array subscript getter is changed to use the
result of these new calls:

   public subscript(index: Int) -> Element {
     get {
       let isNative = _getArrayPropertyIsNative()
       let needsTypeCheck = _getArrayPropertyNeedsElementTypeCheck()
       _checkSubscript(index, isNative)
       return _getElement(index, isNative, needsTypeCheck)
     }
     mutableAddressWithPinnedNativeOwner {
       _makeMutableAndUniqueOrPinned()
       // When an array was made mutable we know it is a backed by a native
       // array buffer.
       _checkSubscript(index, true)
       return (_getElementAddress(index),
               Builtin.tryPin(Builtin.castToNativeObject(_buffer.owner)))
     }
   }

High-level SIL optimizations will now see a loop like this:

     func f(inout a : A[AClass]) {
         for i in 0..a.count {
           let b = a.props.isNative()
            .. += _getElement(a, i, b)
         }
     }

After proving that ‘a’ does not escape other than to known safe functions, the
optimizer hoists the array property calls out of the loop in a loop versioned
on the array property.

      func f(inout a : A[AClass]) {
        let b2 = a.props.isNative()
        if (!b2) {
          for i in 0..a.count {
             .. += _getElement(a, i, false)
          }
        } else {
          for i in 0..a.count {
            let b = a.props.isNative
            .. += _getElement(a, i, b)
          }
        }
      }

rdar://17955309

Swift SVN r25698
2015-03-03 00:45:59 +00:00
Arnold Schwaighofer
14ddfe1427 Add an API to ArraySemantic call to get the self argument as an operand.
Swift SVN r25619
2015-02-27 22:07:39 +00:00
Arnold Schwaighofer
20b1323da2 ArraySemanticsCall: Don't repeat assertions
SILInstruction::getSelfArgument already performs these.

Swift SVN r25616
2015-02-27 22:07:37 +00:00