Commit Graph

156 Commits

Author SHA1 Message Date
Joe Groff
4e3f665cc8 Merge pull request #76688 from jckarter/atomic-layout
IRGen: Set a "not bitwise borrowable" bit in value witnesses for `@_rawLayout` types.
2024-09-25 08:09:56 -10:00
Joe Groff
57a56e5804 IRGen: Set a "not bitwise borrowable" bit in value witnesses for @_rawLayout types.
For types like `Atomic` and `Mutex`, we want to know that even though they are
technically bitwise-takable, they differ from other bitwise-takable types until
this point because they are not also "bitwise-borrowable"; while borrowed,
they are pinned in memory, so they cannot be passed by value as a borrowed
parameter, unlike copyable bitwise-takable types. Add a bit to the value witness
table flags to record this.

Note that this patch does not include any accompanying runtime support for
propagating the flag into runtime-instantiated type metadata. There isn't yet
any runtime functionality that varies based on this flag, so that can
be implemented separately.

rdar://136396806
2024-09-24 19:08:50 -07:00
Kuba Mracek
6b9a3051e3 [embedded] Introduce class-bound existentials into Embedded Swift
Motivated by need for protocol-based dynamic dispatch, which hasn't been possible in Embedded Swift due to a full ban on existentials. This lifts that restriction but only for class-bound existentials: Class-bound existentials are already (even in desktop Swift) much more lightweight than full existentials, as they don't need type metadata, their containers are typically 2 words only (reference + wtable pointer), don't incur copies (only retains+releases).

Included in this PR:
[x] Non-generic class-bound existentials, executable tests for those.
[x] Extension methods on protocols and using those from a class-bound existential.
[x] RuntimeEffects now differentiate between Existential and ExistentialClassBound.
[x] PerformanceDiagnostics don't flag ExistentialClassBound in Embedded Swift.
[x] WTables are generated in IRGen when needed.

Left for follow-up PRs:
[ ] Generic classes support
2024-09-19 07:49:50 -07:00
Arnold Schwaighofer
bbcc3054d7 Merge pull request #75967 from aschwaighofer/non_copyable_deinit_private_field
IRGen: We cannot call destroy through metadata of private types of non-copyable fields
2024-08-26 11:27:12 -07:00
Arnold Schwaighofer
ad6f6dec6e IRGen: We cannot call destroy through metadata of private types of non-copyable fields
So call the destroy on the closing type instead.

Amends the concepts areFieldsABIAccessible/isABIAccessible to take metadata
accessibility of non-copyable types into account.

rdar://133990500
2024-08-21 11:22:30 -07:00
Slava Pestov
0c2f28fd3d AST: Remove GenericSignature parameter from OpenedArchetypeType::get() 2024-08-20 12:15:27 -04:00
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
Erik Eckstein
1b1d5ed020 IRGen: support the @sensitive attribute
Call `swift_clearSensitive` after destroying or taking "sensitive" struct types.

Also, support calling C-functions with "sensitive" parameters or return values. In SIL, sensitive types are address-only and so are sensitive parameters/return values.
Though, (small) sensitive C-structs are passed directly to/from C-functions. We need re-abstract such parameter and return values for C-functions.
2024-04-09 12:01:11 +02:00
Slava Pestov
788aa5498a IRGen: Don't attempt to outline value operations on existentials that contain local archetypes
Fixes rdar://problem/118437883.
2024-04-05 17:40:01 -04:00
Nate Chandler
3f6bd9d3e1 [NFC] IRGen: Store SILType in metadata collector. 2024-03-01 21:01:49 -08:00
Ben Barham
f292ec9784 Use the new template deduction guides rather than makeArrayRef
LLVM has removed `make*ArrayRef`, migrate all references to their
constructor equivalent.
2024-02-23 20:04:51 -08:00
Nate Chandler
f3b9dec880 [IRGen] Collect nc deinit metadata for outlining.
Some outlined functions call deinits for noncopyable values.  These
deinits require the metadata for the full type.

Teach the OutliningMetadataCollector to collect the metadata for these
types, when the new needsDeinit flag is set.

Also add the new needsLayout flag.  For now, all outlined functions need
it.
2024-02-21 19:31:52 -08:00
zoecarver
349d37ab24 [embedded] Start fencing parts of IRGen that are not compatible with embedded Swift. 2023-09-06 10:48:17 -07:00
Erik Eckstein
24837b4d10 IRGen: change a few enum utility functions to be able to create enums in static initializers
Instead of passing `IRGenFunction`, pass the `IRGenModule` and the `IRBuilder`.
This makes enum creation not dependent on the presence of a function.

NFC, just refactoring.
2023-05-25 16:28:41 +02:00
Dario Rexin
97381e6411 [IRGen] Support additional single payload enum cases in layout strings (#66042)
* [IRGen] Support additional single payload enum cases in layout strings

rdar://105837101

Adds layout string support for single payload enums with simple (non-scattered) extra inhabitant patterns

* Add more test cases
2023-05-23 13:17:51 -07:00
Dario Rexin
6d031cbada [IRGen] Respect optionality of unowned(unsafe) reference properties (#65663)
* [IRGen] Respect optionality of unowned(unsafe) reference properties

rdar://108705703

When generating the type info for fields marked unowned(unsafe) of an optional reference (e.g. AnyObject?), we dropped the fact that it was optional along the way. This caused incorrect tags to be returned when on object of the type was stored in an optional itself and the unowned property contained `nil`. In those cases the outer optional appeared to be `nil` as well, even if it in fact contained a value.

* Fix additional case
2023-05-05 09:37:46 -07:00
Slava Pestov
8d8fdb7062 IRGen: Make bindArchetype() a static helper in GenExistential.cpp to discourage future use 2023-04-20 22:05:46 -04:00
Slava Pestov
5452a8955a IRGen: Fix createExistentialTypeInfo() for compositions involving ParameterizedProtocolType 2023-03-23 00:53:13 -04:00
Dario Rexin
2f8c1a402c [IRGen] Make pointers to accessor functions in layout strings relative (#64155)
* [IRGen] Make pointers to accessor functions in layout strings relative

rdar://106319336

Pointers embedded in static layout strings should always be relative, so layout strings can reside in read-only memory.

* Properly handle reference storage ownership

* Pass layout tag and metadata / type layout ppointers separately

* Layout string instantiation fully working

* Fix cases where hasLayoutString flag was not set when it should have

* Update include/swift/ABI/Metadata.h
2023-03-17 09:02:51 -07:00
Joe Groff
f8e3e4069b IRGen: Bind generic params for generic deinit call. 2023-02-27 19:28:39 -08:00
Joe Groff
03a2393a6c IRGen: Track IsCopyable through type infos.
And use the new bit to ensure we don't try to lower move-only types
with common layout value witness surrogates. Take a bit in the runtime
value witness flags to represent types that are not copyable.
2023-02-27 18:52:50 -08:00
Joe Groff
a572c3f491 IRGen: Rename internal 'POD' references to 'TriviallyDestroyable'.
Noncopyable types aren't really "POD", but the bit is still useful to track
whether a noncopyable type has a no-op destroy operation, so rename the
existing bit to be more specific within IRGen's implementation.

Don't rename it in the runtime or Builtin names yet, since doing so will
require a naming transition for compatibility.
2023-02-27 18:52:10 -08:00
Dario Rexin
a8d4d57f11 [IRGen] Generate compressed representation of value witnesses (#63813)
rdar://105837040

* WIP: Store layout string in type metadata

* WIP: More cases working

* WIP: Layout strings almost working

* Add layout string pointer to struct metadata

* Fetch bytecode layout strings from metadata in runtime

* More efficient bytecode layout

* Add support for interpreted generics in layout strings

* Layout string instantiation, take and more

* Remove duplicate information from layout strings

* Include size of previous object in next objects offset to reduce number of increments at runtime

* Add support for existentials

* Build type layout strings with StructBuilder to support target sizes and metadata pointers

* Add support for resilient types

* Properly cache layout strings in compiler

* Generic resilient types working

* Non-generic resilient types working

* Instantiate resilient type in layout when possible

* Fix a few issues around alignment and signing

* Disable generics, fix static alignment

* Fix MultiPayloadEnum size when no extra tag is necessary

* Fixes after rebase

* Cleanup

* Fix most tests

* Fix objcImplementattion and non-Darwin builds

* Fix BytecodeLayouts on non-Darwin

* Fix Linux build

* Fix sizes in linux tests

* Sign layout string pointers

* Use nullptr instead of debug value
2023-02-24 15:40:28 -08:00
Joe Groff
afa5837aeb IRGen: Use deinit to destroy move-only structs that have them.
The `deinit` takes full responsibility for destroying the value, using the
user-defined deinit body and implicitly destroying any remaining resources
not consumed during the deinit.

Remaining to do after this patch:

- Run the deinit for enums
- Pass generic arguments for generic move-only types
- Handle deinits that take their parameter indirectly
- Teach value witness layout about when types are move-only and/or have
  deinits, so that we don't attempt to give move-only types standard
  value witness tables or share box metadata with copyable payloads
2023-02-22 16:48:30 -08:00
Dario Rexin
3cf40ea504 [IRGen] Re-introduce TypeLayout strings (#62059)
* Introduce TypeLayout Strings

Layout strings encode the structure of a type into a byte string that can be
interpreted by a runtime function to achieve a destroy or copy. Rather than
generating ir for a destroy/assignWithCopy/etc, we instead generate a layout
string which encodes enough information for a called runtime function to
perform the operation for us. Value witness functions tend to be quite large,
so this allows us to replace them with a single call instead. This gives us the
option of making a codesize/runtime cost trade off.

* Added Attribute @_GenerateLayoutBytecode

This marks a type definition that should use generic bytecode based
value witnesses rather than generating the standard suite of
value witness functions. This should reduce the codesize of the binary
for a runtime interpretation of the bytecode cost.

* Statically link in implementation

Summary:
This creates a library to store the runtime functions in to deploy to
runtimes that do not implement bytecode layouts. Right now, that is
everything. Once these are added to the runtime itself, it can be used
to deploy to old runtimes.

* Implement Destroy at Runtime Using LayoutStrings

If GenerateLayoutBytecode is enabled, Create a layout string and use it
to call swift_generic_destroy

* Add Resilient type and Archetype Support for BytecodeLayouts

Add Resilient type and Archetype Support to Bytecode Layouts

* Implement Bytecode assign/init with copy/take

Implements swift_generic_initialize and swift_generic_assign to allow copying
types using bytecode based witnesses.

* Add EnumTag Support

* Add IRGen Bytecode Layouts Test

Added a test to ensure layouts are correct and getting generated

* Implement BytecodeLayouts ObjC retain/release

* Fix for Non static alignments in aligned groups

* Disable MultiEnums

MultiEnums currently have some correctness issues with non fixed multienum
types. Disabling them for now then going to attempt a correct implementation in
a follow up patch

* Fixes after merge

* More fixes

* Possible fix for native unowned

* Use TypeInfoeBasedTypeLayoutEntry for all scalars when ForceStructTypeLayouts is disabled

* Remove @_GenerateBytecodeLayout attribute

* Fix typelayout_based_value_witness.swift

Co-authored-by: Gwen Mittertreiner <gwenm@fb.com>
Co-authored-by: Gwen Mittertreiner <gwen.mittertreiner@gmail.com>
2022-11-29 21:05:22 -08: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
Arnold Schwaighofer
1264735c0c Fix emitIsUniqueCall 2022-10-05 09:23:25 -07:00
Arnold Schwaighofer
d810b0f7e4 IRGen: Pass the elementType of pointers through to operations
In preparation for moving to llvm's opaque pointer representation
replace getPointerElementType and CreateCall/CreateLoad/Store uses that
dependent on the address operand's pointer element type.

This means an `Address` carries the element type and we use
`FunctionPointer` in more places or read the function type off the
`llvm::Function`.
2022-10-03 15:27:12 -07:00
swift-ci
e720aaef9d Merge remote-tracking branch 'origin/main' into rebranch 2022-06-30 20:53:40 -07:00
Robert Widmann
dde0d8f609 Generalize the Mangling of Constrained Existential Types
Upgrade the old mangling from a list of argument types to a
list of requiremnets. For now, only same-type requirements
may actually be mangled since those are all that are available
to the surface language.

Reconstruction of existential types now consists of demangling (a list of)
base protocol(s), decoding the constraints, and converting the same-type
constraints back into a list of arguments.

rdar://96088707
2022-06-30 15:32:37 -07:00
Ben Barham
04035b43b7 [next] Temporarily use getPointerElementType
`PointerType::getElementType` has been removed entirely as part of the
opaque pointers migration. Update to `getPointerElementType` for now
until we've also migrated.
2022-05-05 16:25:10 -07:00
John McCall
5519749ade [NFC] Collect protocol decls, not type, in ExistentialLayout
Another thing that will be necessary for correctness with
compositions of parameterized protocols.
2022-04-11 22:15:16 -04:00
Robert Widmann
4efcb825f5 Unlock Opaque Types in Parameterized Protocols
Represent this in much the same way that collections do by creating an opaque value representing the source argument, and a conversion expression representing the destination argument.
2022-03-08 23:45:37 -08:00
Robert Widmann
f694bf585b Plumb GenericSignature of SIL Function Through IRGen 2022-03-08 03:09:19 -08:00
Robert Widmann
d6186c9cfb Add a DeclContext Parameter to Opened Archetype Construction
This ensures that opened archetypes always inherit any outer generic parameters from the context in which they reside. This matters because class bounds may bind generic parameters from these outer contexts, and without the outer context you can wind up with ill-formed generic environments like

<τ_0_0, where τ_0_0 : C<T>, τ_0_0 : P>

Where T is otherwise unbound because there is no entry for it among the generic parameters of the environment's associated generic signature.
2022-03-07 22:54:22 -08:00
Slava Pestov
aa67c8bf8a Parametrized => parameterized 2022-02-03 13:27:24 -05:00
Slava Pestov
e7e536705e AST: Introduce ParametrizedProtocolType 2022-01-26 00:11:38 -05:00
Holly Borla
445a856652 [Type System] Introduce a dedicated type to represent existential types.
The new type, called ExistentialType, is not yet used in type resolution.
Later, existential types written with `any` will resolve to this type, and
bare protocol names will resolve to this type depending on context.
2021-12-09 23:14:50 -08:00
Arnold Schwaighofer
5c9de9e656 Revert "Merge pull request #40356 from gmittert/TypeLayoutFixes"
This reverts commit d27e6e1e46, reversing
changes made to f2e85a2b1f.

It causes an execution time failure in
`Interpreter/struct_extra_inhabitants.swift` with

```
ninja -C swift-macosx-x86_64 check-swift-optimize
```

rdar://86054209
2021-12-06 07:49:57 -08:00
Gwen Mittertreiner
335f426c22 Fixes for TypeLayout Procol Compositions
This fixes several issues with the original Scalar Type Layouts patch:

- AddressOnly types need to be lowered to ScalarKinds that do not load when releasing.
- ClassExistentials now handle the case when the existential is an inline
  aggregation of the class pointer and witness table pointers
2021-12-01 11:20:39 -08:00
Gwen Mittertreiner
13bb43b72e Revert "Revert "Merge pull request #37116 from gmittert/Descaling""
This reverts commit 7c7dd666c6.
2021-11-30 16:19:34 -08:00
Arnold Schwaighofer
7c7dd666c6 Revert "Merge pull request #37116 from gmittert/Descaling"
This reverts commit 5ebb1b2fc6, reversing
changes made to 76260c2235.

This commit causes compiler crashes when using protocol composition
types involving objc.

Repo:

```
import Foundation

public class SomeObject : NSObject {}

public protocol ProtoA{}

public protocol SomeProtoType { }
public typealias Composition = SomeObject & SomeProtoType

public struct Thing<T: ProtoA> {
    let a: Composition
    let b: T

    init(a: Composition,
         b: T
    ) {
        self.a = a
        self.b = b
    }
}

$ swiftc -c Repo.swift -O
```

While looking at this issue I noticed that it is not correct to use a
ScalarEntry of ObjCReference (or other ScalarKind::XXXReference) for
`AddressOnly##Name##ClassExistentialTypeInfo` types. These should be
calling the IGF.emit##Name##Destroy(addr, Refcounting); functions not
objc_release.
It is probably best to use the macro facilities in a similar fashion like
lib/IRGen/GenExistential.cpp does.

rdar://85269025
2021-11-11 11:44:09 -08:00
Gwen Mittertreiner
a3ceda653f Teach TypeLayout the Different Types of References
Summary:
As part of SR-14273, the type layout infrastructure needs to be able to be able
to differentiate between types of scalars so it knows how to release/retain
appropriately. Right now, for example, to destroy a scalar, it blindly calls
into typeInfo's irgen functions which means it's not able to generate any of
the needed information for itself.

This patch adds a field to ScalarTypeLayout to allow them to know what kind of
reference they are and strings through the machinery to provide the information
to set it.

This also moves ScalarTypeLayout::destroy to use the new information.

Test Plan: ninja check-swift

Reviewers: mren, #pika_compiler

Reviewed By: mren

Subscribers: apl, phabricatorlinter

Differential Revision: https://phabricator.intern.facebook.com/D30983093

Tasks: T100580959

Tags: swift-adoption

Signature: 30983093:1632340205:3bdd3218ae86ad6b3d199cc1b504a625e3650ec0
2021-09-29 10:40:55 -07:00
Doug Gregor
71c38934d3 Fix an incorrect assertion involving existential formation.
This assertion was tripping when the existential involved a marker
protocol, because it was checking for the number of protocols rather
than the number of protocols that require witness tables. Correct the
assertion and add a test.

Fixes rdar://83020734.
2021-09-24 17:05:56 -07:00
Andrew Trick
97ec127d25 Lower and emit debug_value [poison].
OwnershipEliminator lowers destroy_value [poison] to debug_value
[poison].

IRGen overwrites all references in shadow copies with a sentinel value
in place of debug_value [poison].

Part 2/2: rdar://75012368 (-Onone compiler support for early object
deinitialization with sentinel dead references)
2021-03-12 19:33:23 -08:00
Erik Eckstein
f5a8f600ea SIL: new instructions for copy-on-write support
* a new [immutable] attribute on ref_element_addr and ref_tail_addr
* new instructions: begin_cow_mutation and end_cow_mutation

These new instructions are intended to be used for the stdlib's COW containers, e.g. Array.
They allow more aggressive optimizations, especially for Array.
2020-05-14 08:39:54 +02:00
Joe Groff
950ee3b0de IRGen: Generalize the nullable optimization for single-payload enums.
Augment the `isSingleRetainablePointer` check that allows IRGen to avoid adding branching around retain/release operations on enums that use the null pointer extra inhabitant with a more general "can value witness extra inhabitants" method on TypeInfo, which says whether a type's retain/release operations are safe to invoke on some or all of its extra inhabitants. This lets us generalize the optimization to include things like `String?` or `ClassProtocol?` which are common types with a nullable pointer in them.
2020-03-03 15:00:27 -08:00
Arnold Schwaighofer
7b65768167 IRGen: Add code to compute type layouts
rdar://51988441
2020-02-19 07:12:55 -08:00
Slava Pestov
bc1aa97e4e IRGen: Clean up types of outlined existential buffer operations
The uniquing key for these was just the number of witness tables,
but the function itself referenced the specific existential type
it was instantiated with.

Everything still worked because getOrCreateHelperFunction() would
bitcast an existing function to the correct type, and in practice
the layout of an existential type only depends on the number of
witness tables.

However on master-next, other changes were made that stripped
off the bitcasts. This would result in assertions or LLVM
verifier failures when multiple existential types were used in
a single translation unit.

Fixes <rdar://problem/54780404>.
2019-09-10 14:00:06 -04:00
Slava Pestov
d434188157 SIL: Refactor TypeConverter to not require a SILModule
This mostly requires changing various entry points to pass around a
TypeConverter instead of a SILModule. I've left behind entry points
that take a SILModule for a few methods like SILType::subst() to
avoid creating even more churn.
2019-09-06 21:50:15 -04:00