Commit Graph

91 Commits

Author SHA1 Message Date
Doug Gregor
7088022eef [Standard library] Eliminate ABI-only rethrows versions from Embedded
Where we have rethrowing versions of functions that have typed-throws
counterparts that are only retained for ABI compatibility, wrap them
in `#if !$Embedded` so they aren't compiled into the Embedded version
of the standard library. This eliminates warnings about this code,
which cannot actually be used with arbitrary errors anyway.
2025-09-17 13:09:49 -07:00
Guillaume Lessard
bc22bcd820 [stdlib] remove TODOs
These TODOs aren’t particularly actionable. What we really want is a way to define `_overrideLifetime()` in a not-unsafe way, and that will probably be a `Builtin` operation.
2025-05-06 15:19:32 -07:00
Guillaume Lessard
e0cfb31fcd [stdlib] make _overrideLifetime functions public
These are discussed in the lifetime annotations pitch: https://github.com/swiftlang/swift-evolution/pull/2750

Addresses rdar://150400414
2025-04-30 15:54:41 -07:00
Meghana Gupta
ef1e94577f Revert "Merge pull request #80540 from swiftlang/revert-80452-lifetimeinout"
This reverts commit 6eaa07a880, reversing
changes made to e75ee3f4cf.
2025-04-04 09:50:13 -07:00
Artem Chikin
39e1791b67 Revert "Add support for inout lifetime dependence" 2025-04-04 09:00:09 -07:00
Meghana Gupta
f4a980d62d Update stdlib 2025-04-03 17:32:09 -07:00
Guillaume Lessard
c9b1ab8c42 Merge pull request #79650 from glessard/rdar138440979-MutableSpan
[SE-0467] MutableSpan, with mutableSpan properties to Array, ArraySlice and ContiguousArray.
2025-03-28 17:59:47 -07:00
Guillaume Lessard
30a3eaec4f [stdlib] add MutableSpan and MutableRawSpan 2025-03-27 13:30:13 -07:00
Karoy Lorentey
fb3455eccf [stdlib] Generalize withExtendedLifetime; add extendLifetime 2025-03-24 12:15:42 -07:00
Andrew Trick
c6116be7b5 Update stdlib source with explicit @lifetime(copy self) 2025-03-19 11:59:04 -07:00
Doug Gregor
22eecacc35 Adopt unsafe annotations throughout the standard library 2025-02-26 14:28:01 -08:00
Guillaume Lessard
d4ae6b0ce8 [gardening] move String.withCString to String.swift
- it has been at an unexpected location for unremembered reasons.
2025-01-09 22:16:58 -08:00
Andrew Trick
0b7a9dd441 Make _overrideLifetime transparent. It is a compiler intrinsic. 2024-12-11 22:02:57 -08:00
Andrew Trick
b08caffc37 Rename _unsafeLifetime to @unsafe _overrideLifetime and reformat.
Also, fix the _overrideLifetime doc comments.
2024-12-11 22:02:57 -08:00
Andrew Trick
df655e8fc2 [stdlib] Add unsafeLifetime APIs
Unsafely discard any lifetime dependence on the `dependent` argument. Return
a value identical to `dependent` with a new lifetime dependence on the
`borrows` argument.

This is required to enable lifetime enforcement in the standard library
build.
2024-12-11 22:02:57 -08:00
Stephen Canon
a4c20e043b Add borrowing _withUnprotectedUnsafePointer (#76446)
* Add non-inout `_withUnprotectedUnsafePointer`

For withUnsafePointer we have both an inout and a borrowing form, allowing it to be used with immutable values. Add a parallel form for the unprotected variant.

* Update LifetimeManager.swift
2024-09-16 14:11:34 -04:00
Allan Shortlidge
20d97556ae stdlib: Remove #if $TypedThrows guards.
https://github.com/swiftlang/swift/pull/72612 can be reverted because it is no
longer necessary for the interface of the stdlib to be compatible with
compilers without `$TypedThrows` support.
2024-07-08 16:52:52 -07:00
Karoy Lorentey
ab51f1630c [stdlib] API additions for basic noncopyable primitives
- Add `exchange(_:with:)`
- Add `Optional.take()`
- Add `Unsafe[Mutable]BufferPointer.extracting(_:)`
- Finish generalizing `withExtendedLifetime`
- Radically simplify the implementation of `swap(_:_:)`
2024-06-07 14:09:53 -07:00
Kuba (Brecka) Mracek
545c2434c0 Merge pull request #70446 from kubamracek/embedded-string
[embedded] Port Swift.String to embedded Swift
2024-05-26 12:59:01 -07:00
Kuba Mracek
7ae20b7039 [embedded] Port Swift.String to embedded Swift 2024-05-08 11:11:37 -07:00
Nate Chandler
06921cfe84 [SIL] Hollow out Builtin.copy, deprecate _copy.
The copy operator has been implemented and doesn't use it.  Remove
`Builtin.copy` and `_copy` as much as currently possible.

Source compatibility requires that `_copy` remain in the stdlib.  It is
deprecated here and just uses the copy operator.

Handling old swiftinterfaces requires that `Builtin.copy` be defined.
Redefine it here as a passthrough--SILGen machinery will produce the
necessary copy_addr.

rdar://127502242
2024-05-03 15:56:25 -07:00
Allan Shortlidge
7fc2179c31 stdlib: Fix more typed throws and non-copyable generics condfails.
There were two categories of problem for older compilers that consume the
stdlib `.swiftinterface`:

- The `case .some(borrowing x)` syntax isn't accepted; use `_borrowing`
- Various functions that addopted `~Copyable` generic constraints conflict with
  the `@usableFromInline` ABI stubs that were left in to preserve compatibility
  when the functions are printed with `~Copyable` constraints stripped. The stubs
  need to have different names to get out of the way.

Resolves rdar://127132742
2024-04-26 16:37:09 -07:00
Karoy Lorentey
153c001b15 [stdlib] Undo typed throws on withExtendedLifetime
https://github.com/apple/swift/pull/73045 has uncovered a compiler crash with existing code of this form:

       try withExtendedLifetime(statement) { // 💥silgen crash
            do {
                try dbPool.close()
                XCTFail("Expected Error")
            } catch DatabaseError.SQLITE_BUSY { }
        }

This patterns can happen with any of the newly typed throwing entry points, but the source compat suite only seems to have caught this with `withExtendedLifetime`; let’s see if we can get away with only rolling back this one.
2024-04-16 17:10:24 -07:00
Karoy Lorentey
cafc99369b [stdlib] Round out ~Copyable generalizations in stdlib primitives
- `Optional.map`, `.flatMap`: Allow noncopyable results. Implement typed throws.

- `Result.map`, `.flatMap`: Allow noncopyable types for the new success.
- `Result.flatMapError`: Generalize for noncopyable Success.

- `Unsafe[Mutable][Buffer]Pointer.withMemoryRebound`: Alllow typed throws.
- `Unsafe[Mutable]BufferPointer: Generalize CustomDebugStringConvertible conformance for noncopyable `Element`s.

- `OpaquePointer.init(_: UnsafeMutablePointer)`, `.init(_: UnsafeMutablePointer?)`: Allow noncopyable pointee types.

- `ManagedBuffer.withUnsafeMutablePointerToHeader`, `.withUnsafeMutablePointerToElements`, `.withUnsafeMutablePointers`: Generalize for typed throws and noncopyable return types. Avoid `@_preInverseGenerics`.
- `ManagedBufferPointer`: Ditto.

- `withExtendedLifetime`: Use typed throws. Stop using `@_preInverseGenerics`.

rdar://117753275
2024-04-16 01:15:33 -07:00
Allan Shortlidge
a1dacc12d7 stdlib: Make typed throws ABI placeholders properly @usableFromInline.
Functions that are used in public `@inlinable` function bodies can't be marked
`@_spi` nor can they be made obsolete. Also, they must retain `rethrows` so
that use of these entry points from other `rethrows` functions is accepted.

Builds on https://github.com/apple/swift/pull/72365. Once we no longer have to
support pre-`$TypedThrows` compilers, all of this can be reverted.

Part of rdar://125138945
2024-03-27 14:57:56 -07:00
Karoy Lorentey
2d23ab3226 [stdlib] withUnsafePointer: Spell out Error conformance on E 2024-03-18 11:03:49 -07:00
Karoy Lorentey
d70f197c24 [stdlib] Update SwiftStdlibLegacyABI convention to use @available(swift, obsoleted: 1)
Using version `2` here is just weird for no reason.
2024-03-18 11:03:49 -07:00
Karoy Lorentey
3507a0cf8c [stdlib] Add support for noncopyables to withUnsafePointer(to:) family 2024-03-18 11:03:49 -07:00
Karoy Lorentey
285c3d3744 [stdlib] Add support for noncopyables to withExtendedLifetime(of:) family 2024-03-18 11:03:49 -07:00
Guillaume Lessard
d4abcde64a Merge pull request #72233 from glessard/toplevel-withUUMP-typed-throws
[stdlib] convert `_withUnprotectedUnsafeMutablePointer()` to typed throws
2024-03-12 14:39:46 -07:00
Guillaume Lessard
0ccfa42957 [stdlib] convert _withUnprotectedUnsafeMutablePointer() to typed throws 2024-03-11 11:34:01 -07:00
Guillaume Lessard
78273b2390 Merge pull request #72089 from glessard/toplevel-withUMP-typed-throws
[stdlib] convert `withUnsafeMutablePointer()` to typed throws
2024-03-08 13:52:23 -08:00
Guillaume Lessard
82ae264b69 [stdlib] convert withUnsafeMutablePointer() to typed throws 2024-03-05 02:48:41 -08:00
Guillaume Lessard
d3cd4985d1 [stdlib] convert withUnsafePointer() to typed throws 2024-03-05 02:31:23 -08:00
Kuba Mracek
6d2de26691 Adopt typed throws in one withUnsafePointer() API 2024-01-17 14:19:16 -08:00
Kuba Mracek
a565d1ab85 [embedded] Make embedded print() not depend on untyped throwing and allocations 2024-01-13 21:35:37 +01:00
Kuba Mracek
ae2e903574 [embedded] Build an initial embedded Swift standard library
This isn't a "complete" port of the standard library for embedded Swift, but
something that should serve as a starting point for further iterations on the
stdlib.

- General CMake logic for building a library as ".swiftmodule only" (ONLY_SWIFTMODULE).
- CMake logic in stdlib/public/core/CMakeLists.txt to start building the embedded stdlib for a handful of hardcoded target triples.
- Lots of annotations throughout the standard library to make types, functions, protocols unavailable in embedded Swift (@_unavailableInEmbedded).
- Mainly this is about stdlib functionality that relies on existentials, type erasure, metatypes, reflection, string interpolations.
- We rely on function body removal of unavailable functions to eliminate the actual problematic SIL code (existentials).
- Many .swift files are not included in the compilation of embedded stdlib at all, to simplify the scope of the annotations.
- EmbeddedStubs.swift is used to stub out (as unavailable and fatalError'd) the missing functionality.
2023-09-16 12:38:46 -07:00
Erik Eckstein
0f8dd3a551 stdlib: opt out of stack protection in places where there can't be buffer overflows.
We trust the internal implementation of the stdlib to not cause any unintentional buffer overflows.
In such cases we can use the "unprotected" address-to-pointer conversions.
This avoids inserting stack protections where it's not needed.
2022-09-08 08:42:25 +02:00
Erik Eckstein
ba135dc493 stdlib: add underscored "withUnprotected..Pointer" functions
Those functions work the same way as their "unprotected" counterparts, except that they don't trigger stack protection for the pointers.

* `_withUnprotectedUnsafeMutablePointer`
* `_withUnprotectedUnsafePointer`
* `_withUnprotectedUnsafeBytes` (two times)
2022-09-08 08:42:25 +02:00
Michael Gottesman
366e7ae64d [move-keyword] Remove the old stdlib entrypoint. 2022-08-08 12:50:42 -07:00
Michael Gottesman
3a5049fa15 [stdlib] Mark _move as public.
Just a thinko on my part.
2021-10-29 15:37:46 -07:00
Michael Gottesman
f9122a79b7 [moveOnly] Implement a new _copy function that performs an explicit copy value.
The key thing is that the move checker will not consider the explicit copy value
to be a copy_value that can be rewritten, ensuring that any uses of the result
of the explicit copy_value (consuming or other wise) are not checked.

Similar to the _move operator I recently introduced, this is a transparent
function so we can perform one level of specialization and thus at least be
generic over all concrete types.
2021-10-29 15:37:46 -07:00
Michael Gottesman
114789707c [moveOnly] Implement a semi-generic _move function that can be used on non-generic, non-existential values.
This patch introduces a new stdlib function called _move:

```Swift
  @_alwaysEmitIntoClient
  @_transparent
  @_semantics("lifetimemanagement.move")
  public func _move<T>(_ value: __owned T) -> T {
  #if $ExperimentalMoveOnly
    Builtin.move(value)
  #else
    value
  #endif
  }
```

It is a first attempt at creating a "move" function for Swift, albeit a skleton
one since we do not yet perform the "no use after move" analysis. But this at
leasts gets the skeleton into place so we can built the analysis on top of it
and churn tree in a manageable way. Thus in its current incarnation, all it does
is take in an __owned +1 parameter and returns it after moving it through
Builtin.move.

Given that we want to use an OSSA based analysis for our "no use after move"
analysis and we do not have opaque values yet, we can not supporting moving
generic values since they are address only. This has stymied us in the past from
creating this function. With the implementation in this PR via a bit of
cleverness, we are now able to support this as a generic function over all
concrete types by being a little clever.

The trick is that when we transparent inline _move (to get the builtin), we
perform one level of specialization causing the inlined Builtin.move to be of a
loadable type. If after transparent inlining, we inline builtin "move" into a
context where it is still address only, we emit a diagnostic telling the user
that they applied move to a generic or existential and that this is not yet
supported.

The reason why we are taking this approach is that we wish to use this to
implement a new (as yet unwritten) diagnostic pass that verifies that _move
(even for non-trivial copyable values) ends the lifetime of the value. This will
ensure that one can write the following code to reliably end the lifetime of a
let binding in Swift:

```Swift
  let x = Klass()
  let _ = _move(x)
  // hypotheticalUse(x)
```

Without the diagnostic pass, if one were to write another hypothetical use of x
after the _move, the compiler would copy x to at least hypotheticalUse(x)
meaning the lifetime of x would not end at the _move, =><=.

So to implement this diagnostic pass, we want to use the OSSA infrastructure and
that only works on objects! So how do we square this circle: by taking advantage
of the mandatory SIL optimzier pipeline! Specifically we take advantage of the
following:

1. Mandatory Inlining and Predictable Dead Allocation Elimination run before any
   of the move only diagnostic passes that we run.

2. Mandatory Inlining is able to specialize a callee a single level when it
   inlines code. One can take advantage of this to even at -Onone to
   monomorphosize code.

and then note that _move is such a simple function that predictable dead
allocation elimination is able to without issue eliminate the extra alloc_stack
that appear in the caller after inlining without issue. So we (as the tests
show) get SIL that for concrete types looks exactly like we just had run a
move_value for that specific type as an object since we promote away the
stores/loads in favor of object operations when we eliminate the allocation.

In order to prevent any issue with this being used in a context where multiple
specializations may occur, I made the inliner emit a diagnostic if it inlines
_move into a function that applies it to an address only value. The diagnostic
is emitted at the source location where the function call occurs so it is easy
to find, e.x.:

```
func addressOnlyMove<T>(t: T) -> T {
    _move(t) // expected-error {{move() used on a generic or existential value}}
}

moveonly_builtin_generic_failure.swift:12:5: error: move() used on a generic or existential value
    _move(t)
    ^
```

To eliminate any potential ABI impact, if someone calls _move in a way that
causes it to be used in a context where the transparent inliner will not inline
it, I taught IRGen that Builtin.move is equivalent to a take from src -> dst and
marked _move as always emit into client (AEIC). I also took advantage of the
feature flag I added in the previous commit in order to prevent any cond_fails
from exposing Builtin.move in the stdlib. If one does not pass in the flag
-enable-experimental-move-only then the function just returns the value without
calling Builtin.move, so we are safe.

rdar://83957028
2021-10-27 19:36:49 -07:00
Michael Ilseman
d5da6fdbfd [String] More comparison speedups and cleanup 2018-11-04 10:42:41 -08:00
Michael Ilseman
4ab45dfe20 [String] Drop in initial UTF-8 String prototype
This is a giant squashing of a lot of individual changes prototyping a
switch of String in Swift 5 to be natively encoded as UTF-8. It
includes what's necessary for a functional prototype, dropping some
history, but still leaves plenty of history available for future
commits.

My apologies to anyone trying to do code archeology between this
commit and the one prior. This was the lesser of evils.
2018-11-04 10:42:40 -08:00
Ben Cohen
a6952decab [stdlib] Remove inlineable annotation from transparent functions (#17800)
* Remove inlineable annotation from transparent functions
2018-07-07 08:47:02 -07:00
Nate Cook
7a4e0a32f6 [stdlib] Revise documentation
This includes various revisions to the APIs landing in Swift 4.2, including:
- Random and other randomness APIs
- Hashable changes
- MemoryLayout.offset(of:)
2018-05-18 11:31:54 -05:00
Slava Pestov
28ce9204fe stdlib: More SE-0193 updates 2018-04-24 21:21:22 -07:00
Joe Groff
62771a0c9d stdlib: Add withUnsafeBytes(of:) and withUnsafePointer(to:) for immutable arguments.
Since the functions produce pointers with tightly-scoped lifetimes there's no formal reason these have to only work on `inout` things.  Now that arguments can be +0, we can even do this without copying values that we already have at +0.
2018-04-18 09:13:45 -07:00
Slava Pestov
e1f50b2d36 SE-0193: Rename @_inlineable to @inlinable, @_versioned to @usableFromInline 2018-03-30 21:55:30 -07:00