Commit Graph

1324 Commits

Author SHA1 Message Date
Nadav Rotem
1891de29a4 Teach getCalleeFunction to work with FullApplySite, that wraps TryApply and Apply instructions. NFC.
Swift SVN r27329
2015-04-15 21:22:48 +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
Michael Gottesman
898f11f48f [g-arc-opts] Teach ARC how to recognize StrongEntrance of RC caused by @owned return values.
<rdar://problem/20368790>

Swift SVN r26999
2015-04-05 02:39:45 +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
Mark Lacey
2659b4bcde Add DenseMapInfo for ApplySite and FullApplySite.
Swift SVN r26892
2015-04-02 20:22:07 +00:00
Michael Gottesman
2c1aed9b27 [cow] Teach uniqueness check hoisting how to ignore guaranteed calls to ArraySemantic functions.
We ignore calls to ArraySemantic functions when we hoist uniqueness checks. With
+0 self, this is disrupted by the release that now is in the caller instead of
the callee.

This patch fixes that problem by teaching COWArrayOpts about "guaranteed call
sequences". This is the following pattern:

retain(x)
... nothing that decrements reference counts ...
call f1(@guaranteed_self x)
... nothing that decrements or uses ref counts ...
call f2(@guaranteed_self x)
... nothing that decrements or uses ref counts ...
...
... nothing that decrements or uses ref counts ...
call f$(n-1)(@guaranteed_self x)
... nothing that decrements or uses ref counts ...
call fn(@guaranteed_self x)
... nothing that uses ref counts ...
release(x)

This pattern is created when there are a bunch of guaranteed calls together in a
row (which seems to happen at the "semantic" SIL level). We pattern match the
sequence and then verify that all of the calls are semantic calls. If the
verification succeeds, we can hoist the uniqueness check.

rdar://20340699

Swift SVN r26835
2015-04-01 23:30:03 +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
Michael Gottesman
07d5537bf9 Add SILInstruction::moveAfter(SILInstruction *).
I am going to use this in a subsequent SILCodeMotion change.

Swift SVN r26669
2015-03-28 02:47:05 +00:00
John McCall
1ffb87bb1f Implement a 'throw' instruction in SIL.
Swift SVN r26668
2015-03-28 02:00:20 +00:00
Michael Gottesman
0688dbf607 [rcid] Teach RCIdentityAnalaysis::getRCUses() how to ignore certain uses that are inert from its perspective.
This includes:

1. Extract instructions which extracts a trivial part of an aggregate that has
one RCIdentity.
2. Instructions which take a pointer out of ARC's control by converting it to a
trivial type. This is safe to do since we can assume that the object that is
convered is alive when the conversion happens. So assuming that we can
conservatively find all RC users, we will have at least one RC user that
post dominates the use (since otherwise we would be touching a dangling
pointer). We leave it to the user of the pass to determine what is safe to do
with this information. Potentially in the future it might make sense to return
this information as well so that a user can use that information directly.

rdar://20305817

Swift SVN r26583
2015-03-26 07:19:41 +00:00
Roman Levenstein
332af2a892 Introduce a base class for ApplyInst and PartialApplyInst.
The new base class ApplyInstBase contains APIs that are common for ApplyInst and PartialApplyInst. It allows such optimization passes like generic specializer to treat both instructions in the same way whenever it is possible. Before this change, one had to duplicate and adjust a lot of implementation code in such passes, because ApplyInst and PartialApplyInst were not related to each other in any form.

The existing clients of both classes can continue using the usual APIs. No changes are required. Only new clients, which want to treat ApplyInst and PartialApplyInst in a uniform way, may do so. One of such new clients is the generic specializer, whose adjusted implementation will be submitted in the following commit.

Swift SVN r26581
2015-03-26 06:41:28 +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
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
Arnold Schwaighofer
faeaea890e Add a convenience hasSemantics api to ApplyInst.
Swift SVN r26239
2015-03-17 23:27:18 +00:00
Joe Groff
fdde2a8e99 SIL: Add instructions for boxed existential operations.
Parsing and serialization for {Alloc,Open,Dealloc}ExistentialBox instructions to represent operations on ErrorType boxes.

Swift SVN r26145
2015-03-15 03:32:37 +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
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
Arnold Schwaighofer
360981a794 Add an API to SILInstruction to get the self argument operand.
Swift SVN r25617
2015-02-27 22:07:38 +00:00
Michael Gottesman
6f8b468cb6 Change switches and selects to use NullablePtr<EnumElementDecl> instead of EnumElementDecl * when their API explicitly requires the user to check for nullptr. NFC.
This is just good to do and hopefully will help prevent people from forgetting
to check in the future by annotating the API explicitly as returning a
potentially nullptr.

Swift SVN r25364
2015-02-18 02:11:57 +00:00
Arnold Schwaighofer
650b4021f2 ApplyInst: Add asserts to make sure we do have a self argument
Swift SVN r25031
2015-02-06 01:23:42 +00:00
Arnold Schwaighofer
d1ec4772b4 ApplyInst: Add API to get an argument operand as a reference
This is similar to UnaryInstructionBase's getOperandRef(). Sometimes, we want to
store a pointer to an operand in a temporary data structure such as a visited
set.

Swift SVN r24958
2015-02-04 16:39:12 +00:00
Michael Gottesman
359d67274e [closure-spec] Add support for propagating thin_to_thick_function closures.
<rdar://problem/18995320>

Swift SVN r24770
2015-01-28 01:36:38 +00:00
Michael Gottesman
3b5e703d68 [g-arc-opts] Teach the ARC Optimizer how to understand @guaranteed parameters directly.
Swift SVN r24602
2015-01-21 14:52:37 +00:00
Dmitri Hrybenko
94541a5ced Revert "Change select* instructions so that all of them have the same tail allocated"
This reverts commit r24159 because it breaks building the stdandard
library.

Swift SVN r24161
2014-12-28 08:04:45 +00:00
Michael Gottesman
a6bd0cce0f Change select* instructions so that all of them have the same tail allocated
memory layout and add a SelectInst API that allows for one to access select inst
operands when one does not care about what the cases actually are.

Previously select_enum, select_enum_addr had the following memory layout:

  [operands], [cases]

In constrast, select_value had the following layout:

  [operand1, case1, operand2, case 2, ...]

The layout for select_value makes it impossible to just visit operands in a
generic way via a higher level API. This is an important operation for many
analyses such as AA on select insts.

This commit does the following:

1. Adds a new abstract parent class for all select instructions called
SelectInst.
2. Adds a new templated implementation parent class that inherits from
SelectInst called SelectInstBase. This handles the complete implementation of
select for all types by templating on CaseTy.
3. Changes SelectEnumAddrInst, SelectEnumInst, SelectValueInst to be thin
classes that inherit from the appropriately specialized SelectInstBase.

I left in SelectEnumInstBase for now as a subclass of SelectInstBase and parent
class of SelectEnum{,Addr}Inst since it provides specific enum APIs that are
used all over the compiler. All of these methods have equivalent methods on
SelectInstBase. I just want to leave them for a later commit so that this commit
stays small.

Swift SVN r24159
2014-12-27 05:33:18 +00:00
Andrew Trick
d84feff62b Add a changeBranchTarget helper.
I refactored, generalized, and cleaned up an existing helper.

I also removed hard-coded assumptions about successor indices.
There's no point giving CondBranch a true/false API if we don't respect it.

Swift SVN r24001
2014-12-18 01:26:45 +00:00
Andrew Trick
0899d2a2bc Resolve a visual name conflict.
Swift SVN r24000
2014-12-18 01:26:43 +00:00
John McCall
5c8fbc704c Add SIL instructions to convert between thin functions
and raw pointers.

Swift SVN r23992
2014-12-17 22:23:15 +00:00
Michael Gottesman
c0b5b94cfc Move SelectValueInst to where the rest of the Select*Inst instructions are, not next to the switch instructions. NFC.
Swift SVN r23934
2014-12-15 05:22:40 +00:00
John McCall
169e4fe319 Add Builtin.UnsafeValueBuffer, which provides opaque
storage for arbitrary values.

A buffer doesn't provide any way to identify the type of
value it stores, and so it cannot be copied, moved, or
destroyed independently; thus it's not available as a
first-class type in Swift, which is why I've labelled
it Unsafe.  But it does allow an efficient means of
opaquely preserving information between two cooperating
functions.  This will be useful for the adjustments I
need to make to materializeForSet to support safe
addressors.

I considered making this a SIL type category instead,
like $@value_buffer T.  This is an attractive idea because
it's generally better-typed.  The disadvantages are that:
- it would need its own address_to_pointer equivalents and
- alloc_stack doesn't know what type will be stored in
  any particular buffer, so there still needs to be
  something opaque.

This representation is a bit gross, but it'll do.

Swift SVN r23903
2014-12-13 01:27:12 +00:00
John McCall
3b4e0d307e Intrinsic support for pinning.
Using the intrinsics is obnoxious because I needed them
to return Builtin.NativeObject?, but there's no reasonable
way to safely generate optional types from Builtins.cpp.
Ugh.

Dave and I also decided that there's no need for
swift_tryPin to allow a null object.

Swift SVN r23824
2014-12-10 00:52:48 +00:00
Chris Lattner
811735657f comment fix, NFC.
Swift SVN r23822
2014-12-10 00:11:40 +00:00
Manman Ren
16cc4dfa65 Revert r23713
Swift SVN r23739
2014-12-05 18:41:27 +00:00
Mark Lacey
f80f9325b0 Fix 80-column violation.
Swift SVN r23721
2014-12-05 04:43:36 +00:00
Manman Ren
d0068877f5 [PGO] Add SILMetadata for branch weights.
SILMetadata is the base class with a single enum member (MDKind).
SILBranchNode is the derived class with additional members:
  unsigned NumOperands
  an array of uint32_t

A static member function SILBranchNode::get is implemented to get or create
SILBranchNode. All SILMetadata created are uniqued and saved in SILModule's
member variable:
  llvm::FoldingSet<SILMetadata> Metadatas

Usage of SILMetadta by SILInstruction is captured in SILModule's member variable:
  llvm::DenseMap<const SILInstruction *, SILMetadata *> MetadataStore
This is similar to LLVM's Metadata. Another option is to add a SILMetadata* to
SILInstruction. The disadvantage is the waste of space when we don't have PGO on.

This commit also enables parsing and printing of SILMetadata.

We add keyword sil_metadata to define SILMetadata:
  sil_metadata !0 = {"branch_weights", 3, 5}

For parsing, we add a map in SILModule
  llvm::DenseMap<unsigned, SILMetadata *> NumberedMetadata
that maps from ID to SILMetadata* to help matching usage of "!id" in SILFunction
with definition of "!id" in sil_metadata section.

For printing, we assign IDs to SILMetadata at SILModule scope, we then pass in
an optional argument of
  llvm::DenseMap<const SILMetadata *, unsigned> *MetadataMap
to SILFunction::print in order to get the ID of SILMetadata used in
SILInstruction.

Post-commit review will be appreciated.

rdar://18269754


Swift SVN r23713
2014-12-05 01:47:11 +00:00
John McCall
dd07c8ca10 Add 'mark_dependence', which indicates that an address
or pointer depends on another for validity in a
non-obvious way.

Also, document some basic value-propagation rules
based roughly on the optimization rules for ARC.

Swift SVN r23695
2014-12-04 22:38:09 +00:00
Arnold Schwaighofer
c322b3592d Add a data dependence between opened existential values and method_inst that 'use' them.
Before this patch there was no dependence visible to the optimizer between a
open_existential and the witness_method allowing the optimizer to reorder the
two instruction. The dependence was implicit in the opened archetype but this
is not a concept model by the SIL optimizer.

  %2 = open_existential %0 : $*FooProto to $*@opened("...") FooProto
  %3 = witness_method $@opened("...") FooProto,
                      #FooProto.bar!1 : $@cc(...)
  %4 = apply %3<...>(%2)

This patch changes the SIL representation such that witness_methods on opened
archetypes take the open_existential (or the producer of the opened existential)
as an operand preventing the optimizer from reordering them.

  %2 = open_existential %0 : $*FooProto to $*@opened("...") FooProto
  %3 = witness_method $@opened("...") FooProto,
                      #FooProto.bar!1,
                      %2 : $*@opened("...") FooProto : $@cc(...)
  %4 = apply %3<...>(%2)

rdar://18984526

Swift SVN r23438
2014-11-19 17:22:22 +00:00
Michael Gottesman
fae31cbaa2 [dead-object-elim] Add SILInstruction::mayTrap(), change SILInstruction::mayHaveSideEffects() to call it, and change dead object elimination to call mayHaveSideEffects().
Note that I did not change any actual memory behavior. That will come via a
later cleanup phase. Since this is a correctness fix I wanted to only make
things more conservative.

rdar://18568601

Swift SVN r23311
2014-11-14 00:05:15 +00:00
Roman Levenstein
3910c25da1 Minor re-factoring: Move the logic to decide if a given instruction can be (easily) duplicated into SILInstruction. So far it was mainly used by jump-threading related optimizations. But it could be generally useful, or at least generally important, to optimizations that want to duplicate code.
Swift SVN r23213
2014-11-10 23:15:07 +00:00
Erik Eckstein
da9f08aec8 Replace the default-entry with a corresponding case-entry in select_enum[ _addr], if possible.
This is exactly the same thing as I did for switch_enum.



Swift SVN r23116
2014-11-05 12:48:11 +00:00
Roman Levenstein
03a5d72a35 Get rid of virtual functions. Use CRTP instead.
Swift SVN r23057
2014-11-01 06:34:30 +00:00
Roman Levenstein
c8d180e660 Generalize the switch_int instruction into switch_value instruction, which may switch on arguments of builtin integer types or function types. The later is required for implementing a more efficient speculative devirtualizaiton implementation. Implement lowering of switch_value into LLVM code. In case of integer operands, it reuses LLVM's switch optimizations. Support for switching on function types is not yet bullet-proof and will be refined in the subsequent patches.
rdar://18508812

Swift SVN r23042
2014-10-31 22:55:56 +00:00
Roman Levenstein
f016754ef9 Add a new select_value instruction. This instruction should be the equivalent of select_enum, just for builtin int types. Such an instruction is needed e.g. to efficiently implement conversions of Int raw values to C-like enums.
rdar://18812325

Swift SVN r23036
2014-10-31 20:44:11 +00:00
Erik Eckstein
743d6af4a4 Fix typo
Swift SVN r23004
2014-10-29 16:51:38 +00:00
Erik Eckstein
4df8f66b9a Replace the default-entry with a corresponding case-entry in switch_enum[_addr], if possible.
<rdar://problem/18709388> SimplifyCFG: Canonicalize default cases of covered switches to not use a default case




Swift SVN r23003
2014-10-29 14:56:34 +00:00
Michael Gottesman
af10399976 [rc-id] Teach RCId how to strip off StructInst, TupleInst, and TupleExtractInst.
Specifically:

1. Given a struct literal with only one stored non-trivial field, a ref count
operation on the struct is equivalent to a ref count operation on the field.

2. Given a tuple literal with only one non-trivial elt , a ref count
operation on the tuple is equivalent to a ref count operation on the elt.

3. Given a tuple_extract, if the tuple_extract is extracting the only
non-trivial element of the tuple, a ref count on the tuple_extract is equivalent
to a ref count on the original type.

rdar://18499023

Swift SVN r22902
2014-10-23 23:38:26 +00:00
Joe Groff
5a2f48e3be Add a Builtin.BridgeObject type.
This is a type that has ownership of a reference while allowing access to the
spare bits inside the pointer, but which can also safely hold an ObjC tagged pointer
reference (with no spare bits of course). It additionally blesses one
Foundation-coordinated bit with the meaning of "has swift refcounting" in order
to get a faster short-circuit to native refcounting. It supports the following
builtin operations:

- Builtin.castToBridgeObject<T>(ref: T, bits: Builtin.Word) ->
  Builtin.BridgeObject

  Creates a BridgeObject that contains the bitwise-OR of the bit patterns of
  "ref" and "bits". It is the user's responsibility to ensure "bits" doesn't
  interfere with the reference identity of the resulting value. In other words,
  it is undefined behavior unless:

    castReferenceFromBridgeObject(castToBridgeObject(ref, bits)) === ref

  This means "bits" must be zero if "ref" is a tagged pointer. If "ref" is a real
  object pointer, "bits" must not have any non-spare bits set (unless they're
  already set in the pointer value). The native discriminator bit may only be set
  if the object is Swift-refcounted.

- Builtin.castReferenceFromBridgeObject<T>(bo: Builtin.BridgeObject) -> T

  Extracts the reference from a BridgeObject.

- Builtin.castBitPatternFromBridgeObject(bo: Builtin.BridgeObject) -> Builtin.Word

  Presents the bit pattern of a BridgeObject as a Word.

BridgeObject's bits are set up as follows on the various platforms:

i386, armv7:

  No ObjC tagged pointers
  Swift native refcounting flag bit: 0x0000_0001
  Other available spare bits:        0x0000_0002

x86_64:

  Reserved for ObjC tagged pointers: 0x8000_0000_0000_0001
  Swift native refcounting flag bit: 0x0000_0000_0000_0002
  Other available spare bits:        0x7F00_0000_0000_0004

arm64:

  Reserved for ObjC tagged pointers: 0x8000_0000_0000_0000
  Swift native refcounting flag bit: 0x4000_0000_0000_0000
  Other available spare bits:        0x3F00_0000_0000_0007

TODO: BridgeObject doesn't present any extra inhabitants. It ought to at least provide null as an extra inhabitant for Optional.

Swift SVN r22880
2014-10-23 00:09:23 +00:00
Joe Groff
3f23b82e6d SIL: Rename SILGlobalAddr to GlobalAddr.
All globals are SIL globals now.

Swift SVN r22827
2014-10-18 17:08:28 +00:00
Joe Groff
ea65d1e60b SIL: Remove the builtin_function_ref instruction.
Swift SVN r22797
2014-10-16 16:18:40 +00:00
Arnold Schwaighofer
ad0e20a316 Make isa work with SwitchEnumInstBase.
Swift SVN r22755
2014-10-15 17:07:02 +00:00