Commit Graph

63 Commits

Author SHA1 Message Date
Doug Gregor
1a1f79c0de Introduce safety checkin for ConcurrentValue conformance.
Introduce checking of ConcurrentValue conformances:
- For structs, check that each stored property conforms to ConcurrentValue
- For enums, check that each associated value conforms to ConcurrentValue
- For classes, check that each stored property is immutable and conforms
  to ConcurrentValue

Because all of the stored properties / associated values need to be
visible for this check to work, limit ConcurrentValue conformances to
be in the same source file as the type definition.

This checking can be disabled by conforming to a new marker protocol,
UnsafeConcurrentValue, that refines ConcurrentValue.
UnsafeConcurrentValue otherwise his no specific meaning. This allows
both "I know what I'm doing" for types that manage concurrent access
themselves as well as enabling retroactive conformance, both of which
are fundamentally unsafe but also quite necessary.

The bulk of this change ended up being to the standard library, because
all conformances of standard library types to the ConcurrentValue
protocol needed to be sunk down into the standard library so they
would benefit from the checking above. There were numerous little
mistakes in the initial pass through the stsandard library types that
have now been corrected.
2021-02-04 03:45:09 -08:00
Matt Zanchelli
be13b470aa Fix typos
becuase -> because
preceeds -> precedes
initalizer -> initializer
intialize -> initialize
libary -> library
notfication -> notification
reciever -> receiver
collecton -> collection
exlcusive -> exclusive
techincal -> technical
compatability -> compatibility
setps -> steps
accomodate -> accommodate
brakcet -> bracket
fraciton -> fraction
programm -> program
concequently -> consequently
ecoding -> encoding
timeIntervalforSelfEnd -> timeIntervalForSelfEnd
2020-12-21 18:44:03 -05:00
Karoy Lorentey
184367ca8f [stdlib] Fix Array.append(contentsOf:) for arguments of type NSArray
Due to a couple of unfortunate circumstances, appending an NSArray instance to an Array instance does not actually append any elements.

The cause is https://github.com/apple/swift/pull/29220, which accidentally optimized away the actual loop that appends the elements in this particular case. (And only this particular case, which is why this wasn’t detected by the test suite.)

When the argument to `Array.append(contentsOf:)` is of type NSArray, the `newElements is [Element]` expression is compiled into a runtime check that returns true, eliminating the subsequent loop over the remaining items of the iterator. Sadly, NSArray.underestimatedCount` currently returns 0, so the earlier _copyContents call is a noop, so no elements get added to `self` at all.

Turning the `is` test into a direct equality check between the metatype instances resolves the issue.
2020-10-24 18:17:52 -07:00
Valeriy Van
cdba663d80 Fixes example snippets in Array.swift considering endianness 2020-09-29 02:00:24 +02:00
Xiaodi Wu
502258e6a1 Merge pull request #33610 from valeriyvan/Array-snippet
Fixes example snippet in Array.swift adding missing parameter label
2020-09-04 14:32:08 -04:00
Valeriy Van
9d08f164ca Fixes example snippet in Array.swift adding missing parameter label 2020-08-30 19:19:05 +02:00
Valeriy Van
84928c611d Fixes example snippet in Array.swift
Uses URL instead of NSURL, otherwise example deson't compile
2020-08-24 13:43:25 +02:00
Erik Eckstein
71a642e51b stdlib, SIL optimizer: use the SIL copy-on-write representation in the Array types.
Use the new builtins for COW representation in Array, ContiguousArray and ArraySlice.
The basic idea is to strictly separate code which mutates an array buffer from code which reads from an array.
The concept is explained in more detail in docs/SIL.rst, section "Copy-on-Write Representation".

The main change is to use beginCOWMutation() instead of isUniquelyReferenced() and insert endCOWMutation() at the end of all mutating functions. Also, reading from the array buffer must be done differently, depending on if the buffer is in a mutable or immutable state.

All the required invariants are enforced by runtime checks - but only in an assert-build of the library: a bit in the buffer object side-table indicates if the buffer is mutable or not.

Along with the library changes, also two optimizations needed to be updated: COWArrayOpt and ObjectOutliner.
2020-06-08 15:02:22 +02:00
Erik Eckstein
68728dcb7d stdlib: move the new-buffer creation function from Array to ArrayBuffer
This has two advantages:
1. It does not force the Array in memory (to pass it as inout self to the non-inlinable _createNewBuffer).
2. The new _consumeAndCreateNew is annotated to consume self. This helps to reduce unnecessary retains/releases.

The change applies for Array and ContiguousArray.
2020-05-29 08:46:54 +02:00
Alex Martini
bc5f0153fa Match docs to current behavior.
Confirmed this change on using the swift-5.2-DEVELOPMENT-SNAPSHOT-2020-01-22-a
toolchain, Apple Swift version 5.2-dev (Swift d3f0448a4c).

Fixes rdar://problem/58717942
2020-03-05 11:17:55 -08:00
Erik Eckstein
172c72b95a stdlib: add a shortcut for Array.append(contentsOf:) in case the argument is an Array, too.
This additional check lets the optimizer eliminate most of the append-code in specializations where the appended sequence is also an Array.
For example, when "adding" arrays, e.g. arr += other_arr
2020-01-15 15:27:25 +01:00
Arnold Schwaighofer
1386af04a2 Revert "stdlib: Add custom .first to Array"
This reverts commit 3e932c075d.

The compiler does not support @_alwaysEmitIntoClient properties
specially wrt property descriptors. The revert commit would introduce an
ABI incompatability when a keypath to Array.first is formed:

    let greetings = ["hello", "hola"]
    let count = greetings[keyPath: \[String].first?.count]

Runmning on an older runtime would lead to linker errors against $sSa5firstxSgvpMV
the property descriptor for Array.first.

rdar://58484319
2020-01-13 13:07:00 -08:00
Erik Eckstein
dfc5b06819 stdlib: annotate Array's remove functions with semantic attributes.
All mutating Array functions must be annotated with semantics, because otherwise some high level optimizations get confused.
The semantic attributes prevent inlining those functions in high-level-sil.
This is need so that the optimizer sees that the Array is taken as inout and can reason that it's modified.

This restriction is not needed anymore when we’ll have COW representation in SIL.

rdar://problem/58478089
2020-01-10 17:09:47 +01:00
Erik Eckstein
60a0718922 stdlib: simplify Array/ContiguousArray's withUnsafeMutableBufferPointer and withUnsafeMutableBufferPointer
Again, to reduce code size
2020-01-09 16:17:38 +01:00
Erik Eckstein
bda8af0958 stdlib: simplify Array/ContiguousArray's append(contentsOf:)
Instead of calling ArrayBuffer's _arrayAppendSequence, inline the code. This saves some code size.
2020-01-09 16:17:38 +01:00
Erik Eckstein
88a9ebb9f8 stdlib: Don't request additional capacity in Array/ContiguousArray's remove.
Just copy the buffer if it's not unique.
This also implies that if there is a copy-on-write in remove, "shrink" the capacity of the new buffer to the required amount of elements (instead of copying the capacity of the original buffer).
2020-01-09 16:17:38 +01:00
Erik Eckstein
ea3b6a02af stdlib: rewrite Array/ContiguousArray logic for reserving capacity and creating a new buffer.
Share more code and avoid the large generic functions of ArrayProtocol.
The result is a significant code size win.
2020-01-09 16:17:38 +01:00
Erik Eckstein
3e932c075d stdlib: Add custom .first to Array
This makes Array.first much small and more efficient.
Without this, Array.first compiled down to RandomAccessCollection.first, which ended up in pretty unefficient code.

rdar://problem/46291397
2019-11-27 09:55:27 +01:00
Julian Lettner
381dcc24fc [TSan] Do not report benign race on _swiftEmptyArrayStorage
A previous commit [1] identified and fixed a benign race on
`_swiftEmptyArrayStorage`.  Unfortunately, we have some code duplication
and the fix was not applied to all the necessary places.  Essentially,
we need to ensure that the "empty array storage" object that backs many
"array like types" is never written to.

I tried to improve the test to capture this, however, it is very
finicky.  Currently, it does not go red on my system even when I remove
the check to avoid the benign race in Release mode.

Relevant classes: Array, ArraySlice, ContiguousArray, ArrayBuffer,
ContiguousArrayBuffer, SliceBuffer.

[1] b9b4c789f3

rdar://55161564
2019-10-21 11:22:25 -07:00
Alex Martini
f040edaa85 Typo fix: of of -> of
rdar://problem/54218099
2019-08-21 10:40:18 -07:00
Paul Hudson
06f82a53b5 Replaced the majority of ' : ' with ': '. 2019-07-18 20:46:07 +01:00
Ben Cohen
e9d4687e31 De-underscore @frozen, apply it to structs (#24185)
* De-underscore @frozen for enums

* Add @frozen for structs, deprecate @_fixed_layout for them

* Switch usage from _fixed_layout to frozen
2019-05-30 17:55:37 -07:00
Turushan Aktay
c61691919b Fix documentation typos. 2019-05-26 14:17:45 +02:00
David Smith
39745a1e5e Merge pull request #21627 from kubamracek/fix-data-race-on-emptyarraystorage
Fix a data race on _swiftEmptyArrayStorage reported by TSan
2019-03-28 17:38:21 -07:00
Nate Cook
b6bb9d2f8c [stdlib] Make unsafe array initializer public (#23134)
[stdlib] Make unsafe array initializer public

This implements SE-0245. The public versions of this initializer call
into the existing, underscored version, which avoids the need for
availability constraints.
2019-03-23 13:18:10 -05:00
Ravi Kandhadai
6c662f7a6c [stdlib][Semantics annotation] Add ".empty" suffix to the semantics attribute of
array.init() and add semantics annotation to the compiler-intrinsic:
Array._allocateUninitializedArray
2019-03-05 17:09:34 -08:00
Andrew Trick
6d3397337d Fix performance of array initialization from a generic sequence.
This fixes a major perform bug involving array initialization from any
contiguously stored collection.	 This is not a recent regression. This fix
results in a 10,000X speedup (that's 4 zeros) for this code path:

func initializeFromSlice(_ a: [Int]) -> [Int] {
  return Array<Int>(a[...])
}

A benchmark is included.
2019-02-11 19:41:45 -08:00
Kuba Mracek
b9b4c789f3 Fix a data race on _swiftEmptyArrayStorage reported by TSan. Array.append(contentsOf) used to write a 0 into _buffer.count causing a race. 2019-01-03 17:26:18 -08:00
Ben Cohen
ad50a39b12 [stdlib] Add withContiguous{Mutable}StorageIfAvailable (#21092)
* Add MutableCollection.withContiguousMutableStorageIfAvailable

* Add withContiguousMutableStorageIfAvailable impls

* Add tests on concrete types

* Add Sequence.withContiguousStorageIfAvailable

* Implement withContiguousStorageIfAvailable in concrete types
2018-12-07 10:01:18 -08:00
Mark Lacey
2c15dc2d1c Merge pull request #20625 from rudkx/designated-types-array
[ConstraintSystem] Add Array as a designated type for `+` and `+=`.
2018-11-16 15:28:34 -08:00
Mark Lacey
d3b660d907 [stdlib] Remove FIXMEs from Array extension. 2018-11-16 11:03:55 -08:00
Mark Lacey
d7cf830842 [ConstraintSystem] Add Array as a designated type for + and +=.
Also add overloads for these operators to an extension of Array.

This allows us to typecheck array concatenation quickly with
designated type support enabled and the remaining type checker hacks
disabled.
2018-11-15 21:42:33 -08:00
Ben Cohen
1673c12d78 [stdlib] Replace "sanityCheck" with "internalInvariant" (#20616)
* Replace "sanityCheck" with "internalInvariant"
2018-11-15 20:50:22 -08:00
Karoy Lorentey
ee17e975ca [stdlib] Make protocol _NSArrayCore internal
These shadow protocols don’t add any real type safety, and exposing them in the ABI seems unnecessary.
2018-11-15 09:54:25 +00:00
Maxim Moiseev
cbf83ac04f [NFC][stdlib] Add FIXME markers to simplify audit 2018-11-14 11:58:42 -08:00
Slava Pestov
f6c2caf64b stdlib: Add @inlinable to @inline(__always) declarations
These should be audited since some might not actually need to be
@inlinable, but for now:

- Anything public and @inline(__always) is now also @inlinable
- Anything @usableFromInline and @inline(__always) is now @inlinable
2018-11-13 15:15:07 -05:00
Ben Cohen
ed64e7bdfc reorder a __consuming func 2018-10-04 06:38:58 -07:00
Ben Cohen
9ce2143335 Additional ownership annotations 2018-10-03 19:10:22 -07:00
Ben Cohen
6cc6f4f182 Underscore @usableFromInlinable symbols (#19686) 2018-10-03 12:01:28 -07:00
Ben Cohen
098a8919c4 Remove redundant implementations of !=(Equatable,Equatable) 2018-09-25 15:24:23 -07:00
swift-ci
aca00505d9 Merge pull request #19496 from lorentey/hashing-consuming-audit 2018-09-25 11:27:59 -07:00
Karoy Lorentey
7058f48f37 [stdlib][NFC] Cosmetics 2018-09-25 16:58:12 +01:00
Ben Cohen
df995de0d6 [stdlib] Make KeyValuePairs fully inlinable (#19502)
* Move KVP into its own Swift file. Make it fully inlineable.

* Make _makeCollectionDescription an extension. Add KeyValue equivalent.
2018-09-24 17:46:32 -07:00
Karoy Lorentey
6cef0beff9 Merge pull request #19495 from lorentey/simplify-rawHashValue
[stdlib] Finalize one-shot hashing interface
2018-09-24 21:44:36 +01:00
Karoy Lorentey
c3bc84e680 [stdlib] Set, Dictionary: __consuming/__owned audit
Add __consuming and __owned to Set and Dictionary members where applicable.

Ignore compiler intrinsics for casting for now — their ARC behavior is covered by unit tests that need to be updated.
2018-09-24 13:46:40 +01:00
Karoy Lorentey
6d81663716 [stdlib] Make Hashable._rawHashValue(seed:) safer and more convenient
- Don’t expose the raw execution seed to _rawHashValue.
- Change the type of _rawHashValue’s seed from (UInt64,UInt64) to a single Int. Working with a pair of UInt64s is unwieldy, and overkill in practice. Int as a seed also integrates nicely with Int as a hash value.
- Remove _HasherCore._generateSeed(). Instead, simply call finalize() on a copy of the hasher to get a seed suitable for _rawHashValue.
- Update Set and Dictionary to store a single Int as the seed value.

Note that this doesn’t affect the core hasher, which still mixes in the actual 128-bit execution seed during its initialization. To reduce the potential of confusion, use the name “rawSeed” to refer to an actual 128-bit seed value.
2018-09-24 13:30:05 +01:00
Mike Ash
49c3547449 Merge remote-tracking branch 'origin/master' into rename-conflicting-classes-and-methods 2018-09-21 15:52:38 -04:00
Ben Cohen
ae6f5dd604 [stdlib] Add consuming/owned annotations to Collection implementations (#19360)
* Add consuming/owned annotations to Collection implementations

* Update SILOptimizer tests

* Fix access_marker_verify test

* XFAIL reconstruct_type_from_mangled_name
2018-09-21 12:06:56 -07:00
Mike Ash
798edb9d0e [Runtime][Stdlib][Overlays] Rename various Objective-C classes and methods that would conflict when loading old Swift libraries into a process alongside ABI-stable libraries.
rdar://problem/35768222
2018-09-13 16:55:10 -04:00
Ben Cohen
b4a23adcf0 [stdlib] Update Array.subscript to use _modify (#19154)
* Switch Array to use subscript _modify

* Add _modify to ContiguousArray

* XFAIL linux failing test
2018-09-07 10:36:58 -07:00