diff --git a/stdlib/private/SwiftPrivateLibcExtras/SwiftPrivateLibcExtras.swift b/stdlib/private/SwiftPrivateLibcExtras/SwiftPrivateLibcExtras.swift index cbcd1f0bef9..72d322c2a46 100644 --- a/stdlib/private/SwiftPrivateLibcExtras/SwiftPrivateLibcExtras.swift +++ b/stdlib/private/SwiftPrivateLibcExtras/SwiftPrivateLibcExtras.swift @@ -97,11 +97,17 @@ public func _stdlib_select( let readAddr = readfds.baseAddress let writeAddr = writefds.baseAddress let errorAddr = errorfds.baseAddress + func asFdSetPtr( + _ p: UnsafeMutablePointer? + ) -> UnsafeMutablePointer? { + return UnsafeMutableRawPointer(p)? + .assumingMemoryBound(to: fd_set.self) + } return select( _stdlib_FD_SETSIZE, - UnsafeMutablePointer(readAddr), - UnsafeMutablePointer(writeAddr), - UnsafeMutablePointer(errorAddr), + asFdSetPtr(readAddr), + asFdSetPtr(writeAddr), + asFdSetPtr(errorAddr), timeout) } } diff --git a/stdlib/private/SwiftPrivatePthreadExtras/SwiftPrivatePthreadExtras.swift b/stdlib/private/SwiftPrivatePthreadExtras/SwiftPrivatePthreadExtras.swift index f3a9bbaa845..53167c4badb 100644 --- a/stdlib/private/SwiftPrivatePthreadExtras/SwiftPrivatePthreadExtras.swift +++ b/stdlib/private/SwiftPrivatePthreadExtras/SwiftPrivatePthreadExtras.swift @@ -113,7 +113,8 @@ public class _stdlib_Barrier { var _pthreadBarrier: _stdlib_pthread_barrier_t var _pthreadBarrierPtr: UnsafeMutablePointer<_stdlib_pthread_barrier_t> { - return UnsafeMutablePointer(_getUnsafePointerToStoredProperties(self)) + return _getUnsafePointerToStoredProperties(self) + .assumingMemoryBound(to: _stdlib_pthread_barrier_t.self) } public init(threadCount: Int) { diff --git a/stdlib/public/SDK/Dispatch/Data.swift b/stdlib/public/SDK/Dispatch/Data.swift index a3338193220..3557d3b15c0 100644 --- a/stdlib/public/SDK/Dispatch/Data.swift +++ b/stdlib/public/SDK/Dispatch/Data.swift @@ -114,10 +114,12 @@ public struct DispatchData : RandomAccessCollection, _ObjectiveCBridgeable { /// /// - parameter buffer: The buffer of bytes to append. The size is calculated from `SourceType` and `buffer.count`. public mutating func append(_ buffer : UnsafeBufferPointer) { - self.append(UnsafePointer(buffer.baseAddress!), count: buffer.count * sizeof(SourceType.self)) + buffer.baseAddress!.withMemoryRebound(to: UInt8.self, capacity: buffer.count * strideof(SourceType.self)) { + self.append($0, count: buffer.count * sizeof(SourceType.self)) + } } - private func _copyBytesHelper(to pointer: UnsafeMutablePointer, from range: CountableRange) { + private func _copyBytesHelper(to pointer: UnsafeMutableRawPointer, from range: CountableRange) { var copiedCount = 0 __dispatch_data_apply(__wrapped) { (data: __DispatchData, offset: Int, ptr: UnsafeRawPointer, size: Int) in let limit = Swift.min((range.endIndex - range.startIndex) - copiedCount, size) @@ -172,8 +174,7 @@ public struct DispatchData : RandomAccessCollection, _ObjectiveCBridgeable { guard !copyRange.isEmpty else { return 0 } - let pointer : UnsafeMutablePointer = UnsafeMutablePointer(buffer.baseAddress!) - _copyBytesHelper(to: pointer, from: copyRange) + _copyBytesHelper(to: buffer.baseAddress!, from: copyRange) return copyRange.count } diff --git a/stdlib/public/SDK/Foundation/Data.swift b/stdlib/public/SDK/Foundation/Data.swift index 648aa2a2ac4..be1037708e9 100644 --- a/stdlib/public/SDK/Foundation/Data.swift +++ b/stdlib/public/SDK/Foundation/Data.swift @@ -314,7 +314,7 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl _mapUnmanaged { $0.getBytes(pointer, length: count) } } - private func _copyBytesHelper(to pointer: UnsafeMutablePointer, from range: NSRange) { + private func _copyBytesHelper(to pointer: UnsafeMutableRawPointer, from range: NSRange) { _mapUnmanaged { $0.getBytes(pointer, range: range) } } @@ -355,8 +355,7 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl guard !copyRange.isEmpty else { return 0 } let nsRange = NSMakeRange(copyRange.lowerBound, copyRange.upperBound - copyRange.lowerBound) - let pointer : UnsafeMutablePointer = UnsafeMutablePointer(buffer.baseAddress!) - _copyBytesHelper(to: pointer, from: nsRange) + _copyBytesHelper(to: buffer.baseAddress!, from: nsRange) return copyRange.count } diff --git a/stdlib/public/SDK/Foundation/NSStringAPI.swift b/stdlib/public/SDK/Foundation/NSStringAPI.swift index 9b5a728617f..07e6bc6d8f2 100644 --- a/stdlib/public/SDK/Foundation/NSStringAPI.swift +++ b/stdlib/public/SDK/Foundation/NSStringAPI.swift @@ -387,12 +387,10 @@ extension String { outputArray in // FIXME: completePath(...) is incorrectly annotated as requiring // non-optional output parameters. rdar://problem/25494184 - let outputNonOptionalName = AutoreleasingUnsafeMutablePointer( - UnsafeMutablePointer(outputName) - ) - let outputNonOptionalArray = AutoreleasingUnsafeMutablePointer( - UnsafeMutablePointer(outputArray) - ) + let outputNonOptionalName = unsafeBitCast( + outputName, to: AutoreleasingUnsafeMutablePointer.self) + let outputNonOptionalArray = unsafeBitCast( + outputArray, to: AutoreleasingUnsafeMutablePointer.self) return self._ns.completePath( into: outputNonOptionalName, caseSensitive: caseSensitive, @@ -505,7 +503,7 @@ extension String { var stop_ = false body(line: line, stop: &stop_) if stop_ { - UnsafeMutablePointer(stop).pointee = true + stop.pointee = true } } } @@ -541,7 +539,7 @@ extension String { var stop_ = false body($0, self._range($1), self._range($2), &stop_) if stop_ { - UnsafeMutablePointer($3).pointee = true + $3.pointee = true } } } @@ -823,7 +821,7 @@ extension String { freeWhenDone flag: Bool ) { self = NSString( - charactersNoCopy: UnsafeMutablePointer(utf16CodeUnitsNoCopy), + charactersNoCopy: UnsafeMutablePointer(mutating: utf16CodeUnitsNoCopy), length: count, freeWhenDone: flag) as String } diff --git a/stdlib/public/SDK/SceneKit/SceneKit.swift b/stdlib/public/SDK/SceneKit/SceneKit.swift index 90c012e7cb9..b2dca2f471c 100644 --- a/stdlib/public/SDK/SceneKit/SceneKit.swift +++ b/stdlib/public/SDK/SceneKit/SceneKit.swift @@ -170,7 +170,7 @@ extension SCNGeometryElement { fatalError("Expected constant number of indices per primitive") } self.init( - data: Data(bytes: UnsafePointer(indices), count: indexCount * sizeof(IndexType.self)), + data: Data(bytes: indices, count: indexCount * sizeof(IndexType.self)), primitiveType: primitiveType, primitiveCount: primitiveCount, bytesPerIndex: sizeof(IndexType.self)) diff --git a/stdlib/public/SwiftShims/RuntimeStubs.h b/stdlib/public/SwiftShims/RuntimeStubs.h index f96c9d93cdd..ad580381dbc 100644 --- a/stdlib/public/SwiftShims/RuntimeStubs.h +++ b/stdlib/public/SwiftShims/RuntimeStubs.h @@ -29,7 +29,7 @@ SWIFT_BEGIN_NULLABILITY_ANNOTATIONS SWIFT_RUNTIME_STDLIB_INTERFACE __swift_ssize_t -swift_stdlib_readLine_stdin(char * _Nullable * _Nonnull LinePtr); +swift_stdlib_readLine_stdin(unsigned char * _Nullable * _Nonnull LinePtr); SWIFT_RUNTIME_STDLIB_INTERFACE char * _Nullable * _Nonnull diff --git a/stdlib/public/SwiftShims/UnicodeShims.h b/stdlib/public/SwiftShims/UnicodeShims.h index 9a69865bb88..f53bb92da66 100644 --- a/stdlib/public/SwiftShims/UnicodeShims.h +++ b/stdlib/public/SwiftShims/UnicodeShims.h @@ -66,16 +66,16 @@ _swift_stdlib_unicode_compare_utf16_utf16(const __swift_uint16_t *Left, SWIFT_RUNTIME_STDLIB_INTERFACE __attribute__((__pure__)) __swift_int32_t -_swift_stdlib_unicode_compare_utf8_utf16(const char *Left, +_swift_stdlib_unicode_compare_utf8_utf16(const unsigned char *Left, __swift_int32_t LeftLength, const __swift_uint16_t *Right, __swift_int32_t RightLength); SWIFT_RUNTIME_STDLIB_INTERFACE __attribute__((__pure__)) __swift_int32_t -_swift_stdlib_unicode_compare_utf8_utf8(const char *Left, +_swift_stdlib_unicode_compare_utf8_utf8(const unsigned char *Left, __swift_int32_t LeftLength, - const char *Right, + const unsigned char *Right, __swift_int32_t RightLength); SWIFT_RUNTIME_STDLIB_INTERFACE @@ -84,7 +84,8 @@ _swift_stdlib_unicode_hash(const __swift_uint16_t *Str, __swift_int32_t Length); SWIFT_RUNTIME_STDLIB_INTERFACE __attribute__((__pure__)) __swift_intptr_t -_swift_stdlib_unicode_hash_ascii(const char *Str, __swift_int32_t Length); +_swift_stdlib_unicode_hash_ascii(const unsigned char *Str, + __swift_int32_t Length); SWIFT_RUNTIME_STDLIB_INTERFACE __swift_int32_t _swift_stdlib_unicode_strToUpper( diff --git a/stdlib/public/core/ArrayBuffer.swift b/stdlib/public/core/ArrayBuffer.swift index 2d26672a2ac..84dd3c952e8 100644 --- a/stdlib/public/core/ArrayBuffer.swift +++ b/stdlib/public/core/ArrayBuffer.swift @@ -204,7 +204,8 @@ extension _ArrayBuffer { location: bounds.lowerBound, length: bounds.upperBound - bounds.lowerBound) - let buffer = UnsafeMutablePointer(target) + let buffer = UnsafeMutableRawPointer(target).assumingMemoryBound( + to: AnyObject.self) // Copies the references out of the NSArray without retaining them nonNative.getObjects(buffer, range: nsSubRange) @@ -242,9 +243,11 @@ extension _ArrayBuffer { cocoa.contiguousStorage(Range(self.indices)) if let cocoaStorageBaseAddress = cocoaStorageBaseAddress { + let basePtr = UnsafeMutableRawPointer(cocoaStorageBaseAddress) + .assumingMemoryBound(to: Element.self) return _SliceBuffer( owner: nonNative, - subscriptBaseAddress: UnsafeMutablePointer(cocoaStorageBaseAddress), + subscriptBaseAddress: basePtr, indices: bounds, hasNativeBuffer: false) } @@ -255,7 +258,8 @@ extension _ArrayBuffer { // Tell Cocoa to copy the objects into our storage cocoa.buffer.getObjects( - UnsafeMutablePointer(result.firstElementAddress), + UnsafeMutableRawPointer(result.firstElementAddress) + .assumingMemoryBound(to: AnyObject.self), range: _SwiftNSRange(location: bounds.lowerBound, length: boundsCount)) return _SliceBuffer(result, shiftedToStartIndex: bounds.lowerBound) diff --git a/stdlib/public/core/BridgeObjectiveC.swift b/stdlib/public/core/BridgeObjectiveC.swift index 3bb74d8fa89..b292a0145c6 100644 --- a/stdlib/public/core/BridgeObjectiveC.swift +++ b/stdlib/public/core/BridgeObjectiveC.swift @@ -355,7 +355,7 @@ public struct AutoreleasingUnsafeMutablePointer /// Retrieve the value the pointer points to. @_transparent get { // We can do a strong load normally. - return UnsafeMutablePointer(self).pointee + return unsafeBitCast(self, to: UnsafeMutablePointer.self).pointee } /// Set the value the pointer points to, copying over the previous value. /// @@ -402,6 +402,9 @@ public struct AutoreleasingUnsafeMutablePointer /// This is inherently unsafe; UnsafeMutablePointer assumes the /// referenced memory has +1 strong ownership semantics, whereas /// AutoreleasingUnsafeMutablePointer implies +0 semantics. + /// + /// - Warning: Accessing `pointee` as a type that is unrelated to + /// the underlying memory's bound type is undefined. @_transparent public init(_ from: UnsafeMutablePointer) { self._rawValue = from._rawValue @@ -414,6 +417,9 @@ public struct AutoreleasingUnsafeMutablePointer /// This is inherently unsafe; UnsafeMutablePointer assumes the /// referenced memory has +1 strong ownership semantics, whereas /// AutoreleasingUnsafeMutablePointer implies +0 semantics. + /// + /// - Warning: Accessing `pointee` as a type that is unrelated to + /// the underlying memory's bound type is undefined. @_transparent public init?(_ from: UnsafeMutablePointer?) { guard let unwrapped = from else { return nil } @@ -424,6 +430,9 @@ public struct AutoreleasingUnsafeMutablePointer /// /// This is inherently unsafe because UnsafePointers do not imply /// mutability. + /// + /// - Warning: Accessing `pointee` as a type that is unrelated to + /// the underlying memory's bound type is undefined. @_transparent init(_ from: UnsafePointer) { self._rawValue = from._rawValue @@ -435,6 +444,9 @@ public struct AutoreleasingUnsafeMutablePointer /// /// This is inherently unsafe because UnsafePointers do not imply /// mutability. + /// + /// - Warning: Accessing `pointee` as a type that is unrelated to + /// the underlying memory's bound type is undefined. @_transparent init?(_ from: UnsafePointer?) { guard let unwrapped = from else { return nil } @@ -442,6 +454,40 @@ public struct AutoreleasingUnsafeMutablePointer } } +extension UnsafeMutableRawPointer { + /// Convert from `AutoreleasingUnsafeMutablePointer`. + @_transparent + public init(_ other: AutoreleasingUnsafeMutablePointer) { + _rawValue = other._rawValue + } + + /// Convert other `AutoreleasingUnsafeMutablePointer`. + /// + /// Returns nil if `other` is nil. + @_transparent + public init?(_ other: AutoreleasingUnsafeMutablePointer?) { + guard let unwrapped = other else { return nil } + self.init(unwrapped) + } +} + +extension UnsafeRawPointer { + /// Convert other `AutoreleasingUnsafeMutablePointer`. + @_transparent + public init(_ other: AutoreleasingUnsafeMutablePointer) { + _rawValue = other._rawValue + } + + /// Convert other `AutoreleasingUnsafeMutablePointer`. + /// + /// Returns nil if `other` is nil. + @_transparent + public init?(_ other: AutoreleasingUnsafeMutablePointer?) { + guard let unwrapped = other else { return nil } + self.init(unwrapped) + } +} + extension AutoreleasingUnsafeMutablePointer : CustomDebugStringConvertible { /// A textual representation of `self`, suitable for debugging. public var debugDescription: String { diff --git a/stdlib/public/core/Builtin.swift b/stdlib/public/core/Builtin.swift index fe185810b00..ad75068d2eb 100644 --- a/stdlib/public/core/Builtin.swift +++ b/stdlib/public/core/Builtin.swift @@ -88,9 +88,11 @@ internal func _roundUp(_ offset: Int, toAlignment alignment: Int) -> Int { return Int(_roundUpImpl(UInt(bitPattern: offset), toAlignment: alignment)) } +// This function takes a raw pointer and returns a typed pointer. It implicitly +// assumes that memory at the returned pointer is bound to `Destination` type. @_versioned -internal func _roundUp( - _ pointer: UnsafeMutablePointer, +internal func _roundUp( + _ pointer: UnsafeMutableRawPointer, toAlignmentOf destinationType: DestinationType.Type ) -> UnsafeMutablePointer { // Note: unsafe unwrap is safe because this operation can only increase the @@ -245,11 +247,11 @@ public func unsafeDowncast(_ x: AnyObject, to: T.Type) -> T { @inline(__always) public func _getUnsafePointerToStoredProperties(_ x: AnyObject) - -> UnsafeMutablePointer { + -> UnsafeMutableRawPointer { let storedPropertyOffset = _roundUp( sizeof(_HeapObject.self), toAlignment: alignof(Optional.self)) - return UnsafeMutablePointer(Builtin.bridgeToRawPointer(x)) + + return UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(x)) + storedPropertyOffset } diff --git a/stdlib/public/core/CocoaArray.swift b/stdlib/public/core/CocoaArray.swift index b67a65bfa4b..fc8f8829220 100644 --- a/stdlib/public/core/CocoaArray.swift +++ b/stdlib/public/core/CocoaArray.swift @@ -66,7 +66,8 @@ internal struct _CocoaArrayWrapper : RandomAccessCollection { } return contiguousCount >= subRange.upperBound - ? UnsafeMutablePointer(enumerationState.itemsPtr!) + ? UnsafeMutableRawPointer(enumerationState.itemsPtr!) + .assumingMemoryBound(to: AnyObject.self) + subRange.lowerBound : nil } diff --git a/stdlib/public/core/ContiguousArrayBuffer.swift b/stdlib/public/core/ContiguousArrayBuffer.swift index 3f372d27c08..251967a9532 100644 --- a/stdlib/public/core/ContiguousArrayBuffer.swift +++ b/stdlib/public/core/ContiguousArrayBuffer.swift @@ -115,7 +115,8 @@ final class _ContiguousArrayStorage : _ContiguousArrayStorage1 { ) rethrows { if _isBridgedVerbatimToObjectiveC(Element.self) { let count = __manager.header.count - let elements = UnsafePointer(__manager._elementPointer) + let elements = UnsafeMutableRawPointer(__manager._elementPointer) + .assumingMemoryBound(to: AnyObject.self) defer { _fixLifetime(__manager) } try body(UnsafeBufferPointer(start: elements, count: count)) } diff --git a/stdlib/public/core/FloatingPointParsing.swift.gyb b/stdlib/public/core/FloatingPointParsing.swift.gyb index 6e30d94afe3..351c9d0d2be 100644 --- a/stdlib/public/core/FloatingPointParsing.swift.gyb +++ b/stdlib/public/core/FloatingPointParsing.swift.gyb @@ -57,10 +57,9 @@ extension ${Self} : LosslessStringConvertible { func parseNTBS(_ chars: UnsafePointer) -> (${Self}, Int) { var result: ${Self} = 0 let endPtr = withUnsafeMutablePointer(to: &result) { - _swift_stdlib_strto${cFuncSuffix2[bits]}_clocale( - chars, UnsafeMutablePointer($0)) + _swift_stdlib_strto${cFuncSuffix2[bits]}_clocale(chars, $0) } - return (result, endPtr == nil ? 0 : UnsafePointer(endPtr!) - chars) + return (result, endPtr == nil ? 0 : endPtr! - chars) } let (result, n) = text.withCString(parseNTBS) diff --git a/stdlib/public/core/HashedCollections.swift.gyb b/stdlib/public/core/HashedCollections.swift.gyb index fa4e58015df..5871b2ba3b2 100644 --- a/stdlib/public/core/HashedCollections.swift.gyb +++ b/stdlib/public/core/HashedCollections.swift.gyb @@ -2584,7 +2584,7 @@ final internal class _Native${Self}StorageImpl<${TypeParameters}> : _UnsafeBitMap.sizeInWords(forSizeInBits: _body.capacity), strideof(UInt.self)) let start = - UnsafeMutablePointer(_initializedHashtableEntriesBitMapStorage) + UnsafeMutableRawPointer(_initializedHashtableEntriesBitMapStorage) + bitMapSizeInBytes return _roundUp(start, toAlignmentOf: Key.self) } @@ -2593,7 +2593,7 @@ final internal class _Native${Self}StorageImpl<${TypeParameters}> : // This API is unsafe and needs a `_fixLifetime` in the caller. internal var _values: UnsafeMutablePointer { let keysSizeInBytes = _unsafeMultiply(_body.capacity, strideof(Key.self)) - let start = UnsafeMutablePointer(_keys) + keysSizeInBytes + let start = UnsafeMutableRawPointer(_keys) + keysSizeInBytes return _roundUp(start, toAlignmentOf: Value.self) } %end @@ -3359,7 +3359,8 @@ final internal class _Native${Self}StorageOwner<${TypeParametersDecl}> /// Returns the pointer to the stored property, which contains bridged /// ${Self} elements. internal var _heapBufferBridgedPtr: UnsafeMutablePointer { - return UnsafeMutablePointer(_getUnsafePointerToStoredProperties(self)) + return _getUnsafePointerToStoredProperties(self).assumingMemoryBound( + to: Optional.self) } /// The storage for bridged ${Self} elements, if present. @@ -4754,12 +4755,14 @@ final internal class _Cocoa${Self}Iterator : IteratorProtocol { internal var _fastEnumerationStatePtr: UnsafeMutablePointer<_SwiftNSFastEnumerationState> { - return UnsafeMutablePointer(_getUnsafePointerToStoredProperties(self)) + return _getUnsafePointerToStoredProperties(self).assumingMemoryBound( + to: _SwiftNSFastEnumerationState.self) } internal var _fastEnumerationStackBufPtr: UnsafeMutablePointer<_CocoaFastEnumerationStackBuf> { - return UnsafeMutablePointer(_fastEnumerationStatePtr + 1) + return UnsafeMutableRawPointer(_fastEnumerationStatePtr + 1) + .assumingMemoryBound(to: _CocoaFastEnumerationStackBuf.self) } // These members have to be word-sized integers, they cannot be limited to @@ -4788,7 +4791,8 @@ final internal class _Cocoa${Self}Iterator : IteratorProtocol { // state struct. itemCount = cocoa${Self}.countByEnumerating( with: _fastEnumerationStatePtr, - objects: UnsafeMutablePointer(_fastEnumerationStackBufPtr), + objects: UnsafeMutableRawPointer(_fastEnumerationStackBufPtr) + .assumingMemoryBound(to: AnyObject.self), count: stackBufCount) if itemCount == 0 { itemIndex = -1 @@ -4796,8 +4800,9 @@ final internal class _Cocoa${Self}Iterator : IteratorProtocol { } itemIndex = 0 } - let itemsPtrUP: UnsafeMutablePointer = - UnsafeMutablePointer(_fastEnumerationState.itemsPtr!) + let itemsPtrUP = + UnsafeMutableRawPointer(_fastEnumerationState.itemsPtr!) + .assumingMemoryBound(to: AnyObject.self) let itemsPtr = _UnmanagedAnyObjectArray(itemsPtrUP) let key: AnyObject = itemsPtr[itemIndex] itemIndex += 1 diff --git a/stdlib/public/core/HeapBuffer.swift b/stdlib/public/core/HeapBuffer.swift index 6a5e4d4e326..5244a4b4275 100644 --- a/stdlib/public/core/HeapBuffer.swift +++ b/stdlib/public/core/HeapBuffer.swift @@ -92,19 +92,20 @@ struct _HeapBuffer : Equatable { : (heapAlign < elementAlign ? elementAlign : heapAlign)) } - internal var _address: UnsafeMutablePointer { - return UnsafeMutablePointer( + internal var _address: UnsafeMutableRawPointer { + return UnsafeMutableRawPointer( Builtin.bridgeToRawPointer(self._nativeObject)) } internal var _value: UnsafeMutablePointer { - return UnsafeMutablePointer( - _HeapBuffer._valueOffset() + _address) + return (_HeapBuffer._valueOffset() + _address).assumingMemoryBound( + to: Value.self) } public // @testable var baseAddress: UnsafeMutablePointer { - return UnsafeMutablePointer(_HeapBuffer._elementOffset() + _address) + return (_HeapBuffer._elementOffset() + _address).assumingMemoryBound( + to: Element.self) } internal func _allocatedSize() -> Int { diff --git a/stdlib/public/core/InputStream.swift b/stdlib/public/core/InputStream.swift index 2386680b956..0dc48b9f6d4 100644 --- a/stdlib/public/core/InputStream.swift +++ b/stdlib/public/core/InputStream.swift @@ -22,7 +22,7 @@ import SwiftShims /// Standard input is interpreted as `UTF-8`. Invalid bytes /// will be replaced by Unicode [replacement characters](http://en.wikipedia.org/wiki/Specials_(Unicode_block)#Replacement_character). public func readLine(strippingNewline: Bool = true) -> String? { - var linePtrVar: UnsafeMutablePointer? = nil + var linePtrVar: UnsafeMutablePointer? = nil var readBytes = swift_stdlib_readLine_stdin(&linePtrVar) if readBytes == -1 { return nil @@ -41,8 +41,8 @@ public func readLine(strippingNewline: Bool = true) -> String? { // Recognize Unicode newlines in readLine() // // Recognize only LF and CR+LF combinations for now. - let cr = CChar(UInt8(ascii: "\r")) - let lf = CChar(UInt8(ascii: "\n")) + let cr = UInt8(ascii: "\r") + let lf = UInt8(ascii: "\n") if readBytes == 1 && linePtr[0] == lf { return "" } @@ -61,7 +61,7 @@ public func readLine(strippingNewline: Bool = true) -> String? { } let result = String._fromCodeUnitSequenceWithRepair(UTF8.self, input: UnsafeMutableBufferPointer( - start: UnsafeMutablePointer(linePtr), + start: linePtr, count: readBytes)).0 _swift_stdlib_free(linePtr) return result diff --git a/stdlib/public/core/ManagedBuffer.swift b/stdlib/public/core/ManagedBuffer.swift index 7526bb1a2cd..358d3402213 100644 --- a/stdlib/public/core/ManagedBuffer.swift +++ b/stdlib/public/core/ManagedBuffer.swift @@ -395,8 +395,8 @@ public struct ManagedBufferPointer : Equatable { } /// The address of this instance in a convenient pointer-to-bytes form - internal var _address: UnsafePointer { - return UnsafePointer(Builtin.bridgeToRawPointer(_nativeBuffer)) + internal var _address: UnsafeMutableRawPointer { + return UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_nativeBuffer)) } /// Offset from the allocated storage for `self` to the stored `Header` @@ -412,7 +412,8 @@ public struct ManagedBufferPointer : Equatable { /// guarantee it doesn't dangle internal var _headerPointer: UnsafeMutablePointer
{ _onFastPath() - return UnsafeMutablePointer(_address + _My._headerOffset) + return (_address + _My._headerOffset).assumingMemoryBound( + to: Header.self) } /// An **unmanaged** pointer to the storage for `Element`s. Not @@ -420,7 +421,8 @@ public struct ManagedBufferPointer : Equatable { /// dangle. internal var _elementPointer: UnsafeMutablePointer { _onFastPath() - return UnsafeMutablePointer(_address + _My._elementOffset) + return (_address + _My._elementOffset).assumingMemoryBound( + to: Element.self) } /// Offset from the allocated storage for `self` to the `Element` storage diff --git a/stdlib/public/core/Runtime.swift.gyb b/stdlib/public/core/Runtime.swift.gyb index f3c43ab3559..435d5b98cf8 100644 --- a/stdlib/public/core/Runtime.swift.gyb +++ b/stdlib/public/core/Runtime.swift.gyb @@ -120,10 +120,11 @@ func _stdlib_atomicCompareExchangeStrongInt${bits}( object target: UnsafeMutablePointer, expected: UnsafeMutablePointer, desired: Int${bits}) -> Bool { - return _stdlib_atomicCompareExchangeStrongUInt${bits}( - object: UnsafeMutablePointer(target), - expected: UnsafeMutablePointer(expected), - desired: UInt${bits}(bitPattern: desired)) + + let (oldValue, won) = Builtin.cmpxchg_seqcst_seqcst_Int${bits}( + target._rawValue, expected.pointee._value, desired._value) + expected.pointee._value = oldValue + return Bool(won) } @_transparent @@ -138,9 +139,8 @@ func _swift_stdlib_atomicStoreUInt${bits}( func _swift_stdlib_atomicStoreInt${bits}( object target: UnsafeMutablePointer, desired: Int${bits}) { - return _swift_stdlib_atomicStoreUInt${bits}( - object: UnsafeMutablePointer(target), - desired: UInt${bits}(bitPattern: desired)) + + Builtin.atomicstore_seqcst_Int${bits}(target._rawValue, desired._value) } public // @testable @@ -153,9 +153,9 @@ func _swift_stdlib_atomicLoadUInt${bits}( func _swift_stdlib_atomicLoadInt${bits}( object target: UnsafeMutablePointer) -> Int${bits} { - return Int${bits}(bitPattern: - _swift_stdlib_atomicLoadUInt${bits}( - object: UnsafeMutablePointer(target))) + + let value = Builtin.atomicload_seqcst_Int${bits}(target._rawValue) + return Int${bits}(value) } % for operation in ['Add', 'And', 'Or', 'Xor']: @@ -176,10 +176,11 @@ func _swift_stdlib_atomicFetch${operation}UInt${bits}( func _swift_stdlib_atomicFetch${operation}Int${bits}( object target: UnsafeMutablePointer, operand: Int${bits}) -> Int${bits} { - return Int${bits}(bitPattern: - _swift_stdlib_atomicFetch${operation}UInt${bits}( - object: UnsafeMutablePointer(target), - operand: UInt${bits}(bitPattern: operand))) + + let value = Builtin.atomicrmw_${operation.lower()}_seqcst_Int${bits}( + target._rawValue, operand._value) + + return Int${bits}(value) } % end @@ -190,29 +191,23 @@ func _stdlib_atomicCompareExchangeStrongInt( expected: UnsafeMutablePointer, desired: Int) -> Bool { #if arch(i386) || arch(arm) - return _stdlib_atomicCompareExchangeStrongUInt32( - object: UnsafeMutablePointer(target), - expected: UnsafeMutablePointer(expected), - desired: UInt32(bitPattern: Int32(desired))) + let (oldValue, won) = Builtin.cmpxchg_seqcst_seqcst_Int32( + target._rawValue, expected.pointee._value, desired._value) #elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x) - return _stdlib_atomicCompareExchangeStrongUInt64( - object: UnsafeMutablePointer(target), - expected: UnsafeMutablePointer(expected), - desired: UInt64(bitPattern: Int64(desired))) + let (oldValue, won) = Builtin.cmpxchg_seqcst_seqcst_Int64( + target._rawValue, expected.pointee._value, desired._value) #endif + expected.pointee._value = oldValue + return Bool(won) } func _swift_stdlib_atomicStoreInt( object target: UnsafeMutablePointer, desired: Int) { #if arch(i386) || arch(arm) - return _swift_stdlib_atomicStoreUInt32( - object: UnsafeMutablePointer(target), - desired: UInt32(bitPattern: Int32(desired))) + Builtin.atomicstore_seqcst_Int32(target._rawValue, desired._value) #elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x) - return _swift_stdlib_atomicStoreUInt64( - object: UnsafeMutablePointer(target), - desired: UInt64(bitPattern: Int64(desired))) + Builtin.atomicstore_seqcst_Int64(target._rawValue, desired._value) #endif } @@ -220,13 +215,11 @@ func _swift_stdlib_atomicStoreInt( public func _swift_stdlib_atomicLoadInt( object target: UnsafeMutablePointer) -> Int { #if arch(i386) || arch(arm) - return Int(Int32(bitPattern: - _swift_stdlib_atomicLoadUInt32( - object: UnsafeMutablePointer(target)))) + let value = Builtin.atomicload_seqcst_Int32(target._rawValue) + return Int(value) #elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x) - return Int(Int64(bitPattern: - _swift_stdlib_atomicLoadUInt64( - object: UnsafeMutablePointer(target)))) + let value = Builtin.atomicload_seqcst_Int64(target._rawValue) + return Int(value) #endif } @@ -245,7 +238,7 @@ func _stdlib_atomicLoadARCRef( object target: UnsafeMutablePointer ) -> AnyObject? { let result = _swift_stdlib_atomicLoadPtrImpl( - object: UnsafeMutablePointer(target)) + object: unsafeBitCast(target, to: UnsafeMutablePointer.self)) if let unwrapped = result { return Unmanaged.fromOpaque( UnsafePointer(unwrapped)).takeUnretainedValue() @@ -261,12 +254,12 @@ public func _swift_stdlib_atomicFetch${operation}Int( #if arch(i386) || arch(arm) return Int(Int32(bitPattern: _swift_stdlib_atomicFetch${operation}UInt32( - object: UnsafeMutablePointer(target), + object: unsafeBitCast(target, to: UnsafeMutablePointer.self), operand: UInt32(bitPattern: Int32(operand))))) #elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x) return Int(Int64(bitPattern: _swift_stdlib_atomicFetch${operation}UInt64( - object: UnsafeMutablePointer(target), + object: unsafeBitCast(target, to: UnsafeMutablePointer.self), operand: UInt64(bitPattern: Int64(operand))))) #endif } @@ -276,7 +269,8 @@ public final class _stdlib_AtomicInt { var _value: Int var _valuePtr: UnsafeMutablePointer { - return UnsafeMutablePointer(_getUnsafePointerToStoredProperties(self)) + return _getUnsafePointerToStoredProperties(self).assumingMemoryBound( + to: Int.self) } public init(_ value: Int = 0) { @@ -321,23 +315,34 @@ public final class _stdlib_AtomicInt { /// A 32 byte buffer. internal struct _Buffer32 { - internal var _x0: UInt64 = 0 - internal var _x1: UInt64 = 0 - internal var _x2: UInt64 = 0 - internal var _x3: UInt64 = 0 +% for i in range(32): + internal var _x${i}: UInt8 = 0 +% end + + mutating func withBytes( + _ body: @noescape (UnsafeMutablePointer) throws -> Result + ) rethrows -> Result + { + return try withUnsafeMutablePointer(to: &self) { + try body(UnsafeMutableRawPointer($0).assumingMemoryBound(to: UInt8.self)) + } + } } /// A 72 byte buffer. internal struct _Buffer72 { - internal var _x0: UInt64 = 0 - internal var _x1: UInt64 = 0 - internal var _x2: UInt64 = 0 - internal var _x3: UInt64 = 0 - internal var _x4: UInt64 = 0 - internal var _x5: UInt64 = 0 - internal var _x6: UInt64 = 0 - internal var _x7: UInt64 = 0 - internal var _x8: UInt64 = 0 +% for i in range(72): + internal var _x${i}: UInt8 = 0 +% end + + mutating func withBytes( + _ body: @noescape (UnsafeMutablePointer) throws -> Result + ) rethrows -> Result + { + return try withUnsafeMutablePointer(to: &self) { + try body(UnsafeMutableRawPointer($0).assumingMemoryBound(to: UInt8.self)) + } + } } % for bits in [ 32, 64, 80 ]: @@ -381,14 +386,11 @@ func _float${bits}ToString(_ value: Float${bits}, debug: Bool) -> String { _sanityCheck(sizeof(_Buffer72.self) == 72) var buffer = _Buffer32() - return withUnsafeMutablePointer(to: &buffer) { - (bufferPtr) in - let bufferUTF8Ptr = UnsafeMutablePointer(bufferPtr) - let actualLength = _float${bits}ToStringImpl(bufferUTF8Ptr, 32, value, debug) + return buffer.withBytes { (bufferPtr) in + let actualLength = _float${bits}ToStringImpl(bufferPtr, 32, value, debug) return String._fromWellFormedCodeUnitSequence( UTF8.self, - input: UnsafeBufferPointer( - start: bufferUTF8Ptr, count: Int(actualLength))) + input: UnsafeBufferPointer(start: bufferPtr, count: Int(actualLength))) } } @@ -410,27 +412,21 @@ func _int64ToString( ) -> String { if radix >= 10 { var buffer = _Buffer32() - return withUnsafeMutablePointer(to: &buffer) { - (bufferPtr) in - let bufferUTF8Ptr = UnsafeMutablePointer(bufferPtr) - let actualLength = - _int64ToStringImpl(bufferUTF8Ptr, 32, value, radix, uppercase) + return buffer.withBytes { (bufferPtr) in + let actualLength + = _int64ToStringImpl(bufferPtr, 32, value, radix, uppercase) return String._fromWellFormedCodeUnitSequence( UTF8.self, - input: UnsafeBufferPointer( - start: bufferUTF8Ptr, count: Int(actualLength))) + input: UnsafeBufferPointer(start: bufferPtr, count: Int(actualLength))) } } else { var buffer = _Buffer72() - return withUnsafeMutablePointer(to: &buffer) { - (bufferPtr) in - let bufferUTF8Ptr = UnsafeMutablePointer(bufferPtr) - let actualLength = - _int64ToStringImpl(bufferUTF8Ptr, 72, value, radix, uppercase) + return buffer.withBytes { (bufferPtr) in + let actualLength + = _int64ToStringImpl(bufferPtr, 72, value, radix, uppercase) return String._fromWellFormedCodeUnitSequence( UTF8.self, - input: UnsafeBufferPointer( - start: bufferUTF8Ptr, count: Int(actualLength))) + input: UnsafeBufferPointer(start: bufferPtr, count: Int(actualLength))) } } } @@ -447,27 +443,21 @@ func _uint64ToString( ) -> String { if radix >= 10 { var buffer = _Buffer32() - return withUnsafeMutablePointer(to: &buffer) { - (bufferPtr) in - let bufferUTF8Ptr = UnsafeMutablePointer(bufferPtr) - let actualLength = - _uint64ToStringImpl(bufferUTF8Ptr, 32, value, radix, uppercase) + return buffer.withBytes { (bufferPtr) in + let actualLength + = _uint64ToStringImpl(bufferPtr, 32, value, radix, uppercase) return String._fromWellFormedCodeUnitSequence( UTF8.self, - input: UnsafeBufferPointer( - start: bufferUTF8Ptr, count: Int(actualLength))) + input: UnsafeBufferPointer(start: bufferPtr, count: Int(actualLength))) } } else { var buffer = _Buffer72() - return withUnsafeMutablePointer(to: &buffer) { - (bufferPtr) in - let bufferUTF8Ptr = UnsafeMutablePointer(bufferPtr) - let actualLength = - _uint64ToStringImpl(bufferUTF8Ptr, 72, value, radix, uppercase) + return buffer.withBytes { (bufferPtr) in + let actualLength + = _uint64ToStringImpl(bufferPtr, 72, value, radix, uppercase) return String._fromWellFormedCodeUnitSequence( UTF8.self, - input: UnsafeBufferPointer( - start: bufferUTF8Ptr, count: Int(actualLength))) + input: UnsafeBufferPointer(start: bufferPtr, count: Int(actualLength))) } } } diff --git a/stdlib/public/core/String.swift b/stdlib/public/core/String.swift index b46c9d8cad7..7ef274864c5 100644 --- a/stdlib/public/core/String.swift +++ b/stdlib/public/core/String.swift @@ -584,28 +584,20 @@ extension String { #else switch (_core.isASCII, rhs._core.isASCII) { case (true, false): - let lhsPtr = UnsafePointer(_core.startASCII) - let rhsPtr = UnsafePointer(rhs._core.startUTF16) - return Int(_swift_stdlib_unicode_compare_utf8_utf16( - lhsPtr, Int32(_core.count), rhsPtr, Int32(rhs._core.count))) + _core.startASCII, Int32(_core.count), + rhs._core.startUTF16, Int32(rhs._core.count))) case (false, true): // Just invert it and recurse for this case. return -rhs._compareDeterministicUnicodeCollation(self) case (false, false): - let lhsPtr = UnsafePointer(_core.startUTF16) - let rhsPtr = UnsafePointer(rhs._core.startUTF16) - return Int(_swift_stdlib_unicode_compare_utf16_utf16( - lhsPtr, Int32(_core.count), - rhsPtr, Int32(rhs._core.count))) + _core.startUTF16, Int32(_core.count), + rhs._core.startUTF16, Int32(rhs._core.count))) case (true, true): - let lhsPtr = UnsafePointer(_core.startASCII) - let rhsPtr = UnsafePointer(rhs._core.startASCII) - return Int(_swift_stdlib_unicode_compare_utf8_utf8( - lhsPtr, Int32(_core.count), - rhsPtr, Int32(rhs._core.count))) + _core.startASCII, Int32(_core.count), + rhs._core.startASCII, Int32(rhs._core.count))) } #endif } @@ -699,15 +691,10 @@ extension String : Hashable { } #else if self._core.isASCII { - return _core.startASCII.withMemoryRebound( - to: CChar.self, capacity: _core.count) { - _swift_stdlib_unicode_hash_ascii($0, Int32(_core.count)) - } + return _swift_stdlib_unicode_hash_ascii( + _core.startASCII, Int32(_core.count)) } else { - return _core.startUTF16.withMemoryRebound( - to: UInt16.self, capacity: _core.count) { - _swift_stdlib_unicode_hash($0, Int32(_core.count)) - } + return _swift_stdlib_unicode_hash(_core.startUTF16, Int32(_core.count)) } #endif } @@ -822,9 +809,12 @@ internal func _nativeUnicodeLowercaseString(_ str: String) -> String { var buffer = _StringBuffer( capacity: str._core.count, initialSize: str._core.count, elementWidth: 2) - // Try to write it out to the same length. + // Allocation of a StringBuffer requires binding the memory to the correct + // encoding type. let dest = buffer.start.bindMemory( to: UTF16.CodeUnit.self, capacity: str._core.count) + + // Try to write it out to the same length. let z = _swift_stdlib_unicode_strToLower( dest, Int32(str._core.count), str._core.startUTF16, Int32(str._core.count)) @@ -847,9 +837,12 @@ internal func _nativeUnicodeUppercaseString(_ str: String) -> String { var buffer = _StringBuffer( capacity: str._core.count, initialSize: str._core.count, elementWidth: 2) - // Try to write it out to the same length. + // Allocation of a StringBuffer requires binding the memory to the correct + // encoding type. let dest = buffer.start.bindMemory( to: UTF16.CodeUnit.self, capacity: str._core.count) + + // Try to write it out to the same length. let z = _swift_stdlib_unicode_strToUpper( dest, Int32(str._core.count), str._core.startUTF16, Int32(str._core.count)) diff --git a/stdlib/public/core/StringBridge.swift b/stdlib/public/core/StringBridge.swift index f55fe4ea935..6f3f816016e 100644 --- a/stdlib/public/core/StringBridge.swift +++ b/stdlib/public/core/StringBridge.swift @@ -40,7 +40,7 @@ public // @testable func _stdlib_binary_CFStringGetCharactersPtr( _ source: _CocoaString ) -> UnsafeMutablePointer? { - return UnsafeMutablePointer(_swift_stdlib_CFStringGetCharactersPtr(source)) + return UnsafeMutablePointer(mutating: _swift_stdlib_CFStringGetCharactersPtr(source)) } /// Bridges `source` to `Swift.String`, assuming that `source` has non-ASCII diff --git a/stdlib/public/core/StringBuffer.swift b/stdlib/public/core/StringBuffer.swift index a890b248a2a..c3a294a1b07 100644 --- a/stdlib/public/core/StringBuffer.swift +++ b/stdlib/public/core/StringBuffer.swift @@ -241,7 +241,8 @@ public struct _StringBuffer { // } // &StringBufferIVars.usedEnd - let usedEndPhysicalPtr = _PointerToPointer(_storage._value) + let usedEndPhysicalPtr = UnsafeMutableRawPointer(_storage._value) + .assumingMemoryBound(to: Optional.self) // Create a temp var to hold the exchanged `expected` value. var expected : UnsafeRawPointer? = bounds.upperBound if _stdlib_atomicCompareExchangeStrongPtr( diff --git a/stdlib/public/core/SwiftNativeNSArray.swift b/stdlib/public/core/SwiftNativeNSArray.swift index 333e9a18344..9ca385a1d90 100644 --- a/stdlib/public/core/SwiftNativeNSArray.swift +++ b/stdlib/public/core/SwiftNativeNSArray.swift @@ -138,7 +138,8 @@ extension _SwiftNativeNSArrayWithContiguousStorage : _NSArrayCore { internal let _nativeStorage: _ContiguousArrayStorageBase internal var _heapBufferBridgedPtr: UnsafeMutablePointer { - return UnsafeMutablePointer(_getUnsafePointerToStoredProperties(self)) + return _getUnsafePointerToStoredProperties(self).assumingMemoryBound( + to: Optional.self) } internal typealias HeapBufferStorage = _HeapBufferStorage diff --git a/stdlib/public/core/Unicode.swift b/stdlib/public/core/Unicode.swift index 73cb626062f..5fc1829030a 100644 --- a/stdlib/public/core/Unicode.swift +++ b/stdlib/public/core/Unicode.swift @@ -427,7 +427,9 @@ public struct UTF8 : UnicodeCodec { } public static func _nullCodeUnitOffset(in input: UnsafePointer) -> Int { - return Int(_swift_stdlib_strlen(UnsafePointer(input))) + // Relying on a permissive memory model in C. + let cstr = unsafeBitCast(input, to: UnsafePointer.self) + return Int(_swift_stdlib_strlen(cstr)) } // Support parsing C strings as-if they are UTF8 strings. public static func _nullCodeUnitOffset(in input: UnsafePointer) -> Int { diff --git a/stdlib/public/core/UnsafePointer.swift.gyb b/stdlib/public/core/UnsafePointer.swift.gyb index b263f3f928a..a507bc58f7c 100644 --- a/stdlib/public/core/UnsafePointer.swift.gyb +++ b/stdlib/public/core/UnsafePointer.swift.gyb @@ -69,6 +69,8 @@ public struct ${Self} } /// Construct ${a_Self} with a given pattern of bits. + /// + /// Returns nil if `bitPattern` is zero. @_transparent public init?(bitPattern: UInt) { if bitPattern == 0 { return nil } @@ -121,6 +123,25 @@ public struct ${Self} self.init(unwrapped) } +% if mutable: + /// Convert from `UnsafePointer` to `UnsafeMutablePointer` of the same + /// `Pointee`. + @_transparent + public init(mutating other: UnsafePointer) { + self._rawValue = other._rawValue + } + + /// Convert from `UnsafePointer` to `UnsafeMutablePointer` of the same + /// `Pointee`. + /// + /// Returns nil if `bitPattern` is zero. + @_transparent + public init?(mutating other: UnsafePointer?) { + guard let unwrapped = other else { return nil } + self.init(mutating: unwrapped) + } +% end + % if mutable: /// Allocate and point at uninitialized aligned memory for `count` /// instances of `Pointee`. diff --git a/stdlib/public/core/UnsafeRawPointer.swift.gyb b/stdlib/public/core/UnsafeRawPointer.swift.gyb index 28570535e8d..6da5250352d 100644 --- a/stdlib/public/core/UnsafeRawPointer.swift.gyb +++ b/stdlib/public/core/UnsafeRawPointer.swift.gyb @@ -27,13 +27,21 @@ public struct Unsafe${Mutable}RawPointer : Strideable, Hashable, _Pointer { /// Implements conformance to the public protocol `_Pointer`. public let _rawValue: Builtin.RawPointer - // Construct ${a_Self} from another ${a_Self}. - // FIXME: Why is this necessary? + /// Construct ${a_Self} from another ${a_Self}. @_transparent public init(_ other: Unsafe${Mutable}RawPointer) { self = other } + /// Construct ${a_Self} from another ${a_Self}. + /// + /// Returns nil if `other` is nil. + @_transparent + public init?(_ other: Unsafe${Mutable}RawPointer?) { + guard let unwrapped = other else { return nil } + self = unwrapped + } + /// Convert a builtin raw pointer to ${a_Self}. @_transparent public init(_ _rawValue: Builtin.RawPointer) { diff --git a/stdlib/public/stubs/Stubs.cpp b/stdlib/public/stubs/Stubs.cpp index 7a803a3a604..4389e446342 100644 --- a/stdlib/public/stubs/Stubs.cpp +++ b/stdlib/public/stubs/Stubs.cpp @@ -261,14 +261,14 @@ extern "C" uint64_t swift_float80ToString(char *Buffer, size_t BufferLength, /// /// \returns Size of character data returned in \c LinePtr, or -1 /// if an error occurred, or EOF was reached. -ssize_t swift::swift_stdlib_readLine_stdin(char **LinePtr) { +ssize_t swift::swift_stdlib_readLine_stdin(unsigned char **LinePtr) { #if defined(_MSC_VER) if (LinePtr == nullptr) return -1; ssize_t Capacity = 0; ssize_t Pos = 0; - char *ReadBuf = nullptr; + unsigned char *ReadBuf = nullptr; _lock_file(stdin); @@ -285,7 +285,8 @@ ssize_t swift::swift_stdlib_readLine_stdin(char **LinePtr) { if (Capacity - Pos <= 1) { // Capacity changes to 128, 128*2, 128*4, 128*8, ... Capacity = Capacity ? Capacity * 2 : 128; - char *NextReadBuf = static_cast(realloc(ReadBuf, Capacity)); + char *NextReadBuf = + static_cast(realloc(ReadBuf, Capacity)); if (NextReadBuf == nullptr) { if (ReadBuf) free(ReadBuf); @@ -308,7 +309,7 @@ ssize_t swift::swift_stdlib_readLine_stdin(char **LinePtr) { return Pos; #else size_t Capacity = 0; - return getline(LinePtr, &Capacity, stdin); + return getline((char **)LinePtr, &Capacity, stdin); #endif } diff --git a/stdlib/public/stubs/UnicodeNormalization.cpp b/stdlib/public/stubs/UnicodeNormalization.cpp index fe34c875fd5..84ff51a0214 100644 --- a/stdlib/public/stubs/UnicodeNormalization.cpp +++ b/stdlib/public/stubs/UnicodeNormalization.cpp @@ -153,7 +153,7 @@ swift::_swift_stdlib_unicode_compare_utf16_utf16(const uint16_t *LeftString, /// ==0 the strings are equal according to their collation. /// >0 the left string is greater than the right string. int32_t -swift::_swift_stdlib_unicode_compare_utf8_utf16(const char *LeftString, +swift::_swift_stdlib_unicode_compare_utf8_utf16(const unsigned char *LeftString, int32_t LeftLength, const uint16_t *RightString, int32_t RightLength) { @@ -183,9 +183,9 @@ swift::_swift_stdlib_unicode_compare_utf8_utf16(const char *LeftString, /// ==0 the strings are equal according to their collation. /// >0 the left string is greater than the right string. int32_t -swift::_swift_stdlib_unicode_compare_utf8_utf8(const char *LeftString, +swift::_swift_stdlib_unicode_compare_utf8_utf8(const unsigned char *LeftString, int32_t LeftLength, - const char *RightString, + const unsigned char *RightString, int32_t RightLength) { UCharIterator LeftIterator; UCharIterator RightIterator; @@ -266,7 +266,7 @@ swift::_swift_stdlib_unicode_hash(const uint16_t *Str, int32_t Length) { return hashFinish(HashState); } -intptr_t swift::_swift_stdlib_unicode_hash_ascii(const char *Str, +intptr_t swift::_swift_stdlib_unicode_hash_ascii(const unsigned char *Str, int32_t Length) { const ASCIICollation *Table = ASCIICollation::getTable(); intptr_t HashState = HASH_SEED; diff --git a/test/1_stdlib/BridgeNonVerbatim.swift b/test/1_stdlib/BridgeNonVerbatim.swift index 12d5cd0d562..9400740325c 100644 --- a/test/1_stdlib/BridgeNonVerbatim.swift +++ b/test/1_stdlib/BridgeNonVerbatim.swift @@ -88,9 +88,9 @@ func testScope() { objects.withUnsafeMutableBufferPointer { // FIXME: Can't elide signature and use $0 here (buf: inout UnsafeMutableBufferPointer) -> () in - nsx.getObjects( - UnsafeMutablePointer(buf.baseAddress!), - range: _SwiftNSRange(location: 1, length: 2)) + let objPtr = UnsafeMutableRawPointer(buf.baseAddress!).bindMemory( + to: AnyObject.self, capacity: 2) + nsx.getObjects(objPtr, range: _SwiftNSRange(location: 1, length: 2)) } // CHECK-NEXT: getObjects yields them at +0: true diff --git a/test/1_stdlib/NSStringAPI.swift b/test/1_stdlib/NSStringAPI.swift index 148573c318b..55e5fb65886 100644 --- a/test/1_stdlib/NSStringAPI.swift +++ b/test/1_stdlib/NSStringAPI.swift @@ -204,7 +204,9 @@ NSStringAPIs.test("init(utf8String:)") { i += 1 } up[i] = 0 - expectOptionalEqual(s, String(utf8String: UnsafePointer(up))) + let cstr = UnsafeMutableRawPointer(up) + .bindMemory(to: CChar.self, capacity: 100) + expectOptionalEqual(s, String(utf8String: cstr)) up.deallocate(capacity: 100) } diff --git a/test/1_stdlib/StringAPI.swift b/test/1_stdlib/StringAPI.swift index 5e63afd7a4c..1d3250d25d7 100644 --- a/test/1_stdlib/StringAPI.swift +++ b/test/1_stdlib/StringAPI.swift @@ -325,19 +325,19 @@ StringTests.test("CompareStringsWithUnpairedSurrogates") var CStringTests = TestSuite("CStringTests") -func getNullCString() -> UnsafeMutablePointer? { +func getNullUTF8() -> UnsafeMutablePointer? { return nil } -func getASCIICString() -> (UnsafeMutablePointer, dealloc: () -> ()) { - let up = UnsafeMutablePointer.allocate(capacity: 100) +func getASCIIUTF8() -> (UnsafeMutablePointer, dealloc: () -> ()) { + let up = UnsafeMutablePointer.allocate(capacity: 100) up[0] = 0x61 up[1] = 0x62 up[2] = 0 return (up, { up.deallocate(capacity: 100) }) } -func getNonASCIICString() -> (UnsafeMutablePointer, dealloc: () -> ()) { +func getNonASCIIUTF8() -> (UnsafeMutablePointer, dealloc: () -> ()) { let up = UnsafeMutablePointer.allocate(capacity: 100) up[0] = 0xd0 up[1] = 0xb0 @@ -348,7 +348,7 @@ func getNonASCIICString() -> (UnsafeMutablePointer, dealloc: () -> ()) { } func getIllFormedUTF8String1( -) -> (UnsafeMutablePointer, dealloc: () -> ()) { +) -> (UnsafeMutablePointer, dealloc: () -> ()) { let up = UnsafeMutablePointer.allocate(capacity: 100) up[0] = 0x41 up[1] = 0xed @@ -360,7 +360,7 @@ func getIllFormedUTF8String1( } func getIllFormedUTF8String2( -) -> (UnsafeMutablePointer, dealloc: () -> ()) { +) -> (UnsafeMutablePointer, dealloc: () -> ()) { let up = UnsafeMutablePointer.allocate(capacity: 100) up[0] = 0x41 up[0] = 0x41 @@ -376,7 +376,7 @@ func asCCharArray(_ a: [UInt8]) -> [CChar] { return a.map { CChar(bitPattern: $0) } } -func getCStringLength(_ cString: UnsafePointer) -> Int { +func getUTF8Length(_ cString: UnsafePointer) -> Int { var length = 0 while cString[length] != 0 { length += 1 @@ -384,13 +384,13 @@ func getCStringLength(_ cString: UnsafePointer) -> Int { return length } -func bindAsUTF8(_ cString: UnsafePointer) -> UnsafePointer { - return UnsafeRawPointer(cString).bindMemory(to: UInt8.self, - capacity: getCStringLength(cString)) +func bindAsCChar(_ utf8: UnsafePointer) -> UnsafePointer { + return UnsafeRawPointer(utf8).bindMemory(to: CChar.self, + capacity: getUTF8Length(utf8)) } -func expectEqualCString(_ lhs: UnsafePointer, - _ rhs: UnsafePointer) { +func expectEqualCString(_ lhs: UnsafePointer, + _ rhs: UnsafePointer) { var index = 0 while lhs[index] != 0 { @@ -400,18 +400,18 @@ func expectEqualCString(_ lhs: UnsafePointer, expectEqual(0, rhs[index]) } -func expectEqualCString(_ lhs: UnsafePointer, - _ rhs: ContiguousArray) { +func expectEqualCString(_ lhs: UnsafePointer, + _ rhs: ContiguousArray) { rhs.withUnsafeBufferPointer { expectEqualCString(lhs, $0.baseAddress!) } } -func expectEqualCString(_ lhs: UnsafePointer, - _ rhs: ContiguousArray) { +func expectEqualCString(_ lhs: UnsafePointer, + _ rhs: ContiguousArray) { rhs.withUnsafeBufferPointer { $0.baseAddress!.withMemoryRebound( - to: CChar.self, capacity: rhs.count) { + to: UInt8.self, capacity: rhs.count) { expectEqualCString(lhs, $0) } } @@ -419,36 +419,36 @@ func expectEqualCString(_ lhs: UnsafePointer, CStringTests.test("String.init(validatingUTF8:)") { do { - let (s, dealloc) = getASCIICString() - expectOptionalEqual("ab", String(validatingUTF8: s)) + let (s, dealloc) = getASCIIUTF8() + expectOptionalEqual("ab", String(validatingUTF8: bindAsCChar(s))) dealloc() } do { - let (s, dealloc) = getNonASCIICString() - expectOptionalEqual("аб", String(validatingUTF8: s)) + let (s, dealloc) = getNonASCIIUTF8() + expectOptionalEqual("аб", String(validatingUTF8: bindAsCChar(s))) dealloc() } do { let (s, dealloc) = getIllFormedUTF8String1() - expectEmpty(String(validatingUTF8: s)) + expectEmpty(String(validatingUTF8: bindAsCChar(s))) dealloc() } } CStringTests.test("String(cString:)") { do { - let (s, dealloc) = getASCIICString() + let (s, dealloc) = getASCIIUTF8() let result = String(cString: s) expectEqual("ab", result) - let su = bindAsUTF8(s) + let su = bindAsCChar(s) expectEqual("ab", String(cString: su)) dealloc() } do { - let (s, dealloc) = getNonASCIICString() + let (s, dealloc) = getNonASCIIUTF8() let result = String(cString: s) expectEqual("аб", result) - let su = bindAsUTF8(s) + let su = bindAsCChar(s) expectEqual("аб", String(cString: su)) dealloc() } @@ -456,7 +456,7 @@ CStringTests.test("String(cString:)") { let (s, dealloc) = getIllFormedUTF8String1() let result = String(cString: s) expectEqual("\u{41}\u{fffd}\u{fffd}\u{fffd}\u{41}", result) - let su = bindAsUTF8(s) + let su = bindAsCChar(s) expectEqual("\u{41}\u{fffd}\u{fffd}\u{fffd}\u{41}", String(cString: su)) dealloc() } @@ -464,14 +464,14 @@ CStringTests.test("String(cString:)") { CStringTests.test("String.decodeCString") { do { - let s = getNullCString() - let result = String.decodeCString(UnsafePointer(s), as: UTF8.self) + let s = getNullUTF8() + let result = String.decodeCString(s, as: UTF8.self) expectEmpty(result) } do { // repairing let (s, dealloc) = getIllFormedUTF8String1() if let (result, repairsMade) = String.decodeCString( - UnsafePointer(s), as: UTF8.self, repairingInvalidCodeUnits: true) { + s, as: UTF8.self, repairingInvalidCodeUnits: true) { expectOptionalEqual("\u{41}\u{fffd}\u{fffd}\u{fffd}\u{41}", result) expectTrue(repairsMade) } else { @@ -482,7 +482,7 @@ CStringTests.test("String.decodeCString") { do { // non repairing let (s, dealloc) = getIllFormedUTF8String1() let result = String.decodeCString( - UnsafePointer(s), as: UTF8.self, repairingInvalidCodeUnits: false) + s, as: UTF8.self, repairingInvalidCodeUnits: false) expectEmpty(result) dealloc() } @@ -490,13 +490,13 @@ CStringTests.test("String.decodeCString") { CStringTests.test("String.utf8CString") { do { - let (cstr, dealloc) = getASCIICString() + let (cstr, dealloc) = getASCIIUTF8() let str = String(cString: cstr) expectEqualCString(cstr, str.utf8CString) dealloc() } do { - let (cstr, dealloc) = getNonASCIICString() + let (cstr, dealloc) = getNonASCIIUTF8() let str = String(cString: cstr) expectEqualCString(cstr, str.utf8CString) dealloc() diff --git a/test/1_stdlib/TestUUID.swift b/test/1_stdlib/TestUUID.swift index 31ac9f6c775..7a69f124a8f 100644 --- a/test/1_stdlib/TestUUID.swift +++ b/test/1_stdlib/TestUUID.swift @@ -75,7 +75,7 @@ class TestUUID : TestUUIDSuper { var bytes: [UInt8] = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] let valFromBytes = bytes.withUnsafeMutableBufferPointer { buffer -> UUID in ref.getBytes(buffer.baseAddress) - return UUID(uuid: UnsafePointer(buffer.baseAddress!).pointee) + return UUID(uuid: UnsafeRawPointer(buffer.baseAddress!).load(as: uuid_t.self)) } let valFromStr = UUID(uuidString: ref.uuidString) expectEqual(ref.uuidString, valFromRef.uuidString) diff --git a/test/Constraints/lvalues.swift b/test/Constraints/lvalues.swift index 4352b412de3..cf193d7b85b 100644 --- a/test/Constraints/lvalues.swift +++ b/test/Constraints/lvalues.swift @@ -179,7 +179,7 @@ func rdar19835413() { f1(&a[i]) f1(&a[0]) f1(pi) - f1(UnsafeMutablePointer(pi)) + f1(pi) } } diff --git a/test/Interpreter/SDK/archiving_generic_swift_class.swift b/test/Interpreter/SDK/archiving_generic_swift_class.swift index 05166168d01..2d071fbc1af 100644 --- a/test/Interpreter/SDK/archiving_generic_swift_class.swift +++ b/test/Interpreter/SDK/archiving_generic_swift_class.swift @@ -70,10 +70,11 @@ func driver() { } // Spawn the archiver process. + let str: StaticString = "-archive" + let optStr = UnsafeMutableRawPointer(mutating: str.utf8Start).bindMemory( + to: CChar.self, capacity: str.utf8CodeUnitCount) let archiverArgv: [UnsafeMutablePointer?] = [ - CommandLine.unsafeArgv[0], - UnsafeMutablePointer(("-archive" as StaticString).utf8Start), - nil + CommandLine.unsafeArgv[0], optStr, nil ] guard posix_spawn(&archiver, CommandLine.unsafeArgv[0], &archiverActions, nil, @@ -99,11 +100,12 @@ func driver() { } // Spawn the unarchiver process. + let str = "-unarchive" as StaticString + let optStr = UnsafeMutableRawPointer(mutating: str.utf8Start).bindMemory( + to: CChar.self, capacity: str.utf8CodeUnitCount) var unarchiver: pid_t = 0 let unarchiverArgv: [UnsafeMutablePointer?] = [ - CommandLine.unsafeArgv[0], - UnsafeMutablePointer(("-unarchive" as StaticString).utf8Start), - nil + CommandLine.unsafeArgv[0], optStr, nil ] guard posix_spawn(&unarchiver, CommandLine.unsafeArgv[0], &unarchiverActions, nil, diff --git a/test/Interpreter/SDK/objc_inner_pointer.swift b/test/Interpreter/SDK/objc_inner_pointer.swift index dca84734ae7..288a74ebb27 100644 --- a/test/Interpreter/SDK/objc_inner_pointer.swift +++ b/test/Interpreter/SDK/objc_inner_pointer.swift @@ -28,7 +28,7 @@ autoreleasepool { repeat { let data = NSData(bytes: [2, 3, 5, 7] as [UInt8], length: 4) hangCanary(data) - bytes = UnsafeMutablePointer(data.bytes.assumingMemoryBound(to: UInt8.self)) + bytes = UnsafeMutablePointer(mutating: data.bytes.assumingMemoryBound(to: UInt8.self)) } while false // CHECK-NOT: died print(bytes[0]) // CHECK: 2 print(bytes[1]) // CHECK-NEXT: 3 @@ -44,7 +44,7 @@ autoreleasepool { let data = NSData(bytes: [11, 13, 17, 19] as [UInt8], length: 4) hangCanary(data) let dataAsAny: AnyObject = data - bytes = UnsafeMutablePointer(dataAsAny.bytes!.assumingMemoryBound(to: UInt8.self)) + bytes = UnsafeMutablePointer(mutating: dataAsAny.bytes!.assumingMemoryBound(to: UInt8.self)) } while false // CHECK-NOT: died print(bytes[0]) // CHECK: 11 print(bytes[1]) // CHECK-NEXT: 13 diff --git a/test/Parse/pointer_conversion.swift.gyb b/test/Parse/pointer_conversion.swift.gyb index f8715e151f6..c9df34b6d73 100644 --- a/test/Parse/pointer_conversion.swift.gyb +++ b/test/Parse/pointer_conversion.swift.gyb @@ -259,10 +259,6 @@ func stringArguments(_ s: String) { } -func pointerConstructor(_ x: UnsafeMutablePointer) -> UnsafeMutablePointer { - return UnsafeMutablePointer(x) -} - func optionality(_ op: UnsafeMutablePointer?) { takesMutableVoidPointer(op) % if not suffix: @@ -286,10 +282,10 @@ func genericPointerArithmetic(_ x: UnsafeMutablePointer, i: Int, t: T) -> p.initialize(to: t) } -func passPointerToClosure(_ f: (UnsafeMutablePointer) -> Int) -> Int { } +func passPointerToClosure(_ f: (UnsafeMutablePointer) -> Int) -> Int { } -func pointerInClosure(_ f: (UnsafeMutablePointer) -> Int) -> Int { - return passPointerToClosure { f(UnsafeMutablePointer($0)) } +func pointerInClosure(_ f: (UnsafePointer) -> Int) -> Int { + return passPointerToClosure { f($0) } } struct NotEquatable {} diff --git a/test/decl/subscript/addressors.swift b/test/decl/subscript/addressors.swift index 41145928f35..9689f08d566 100644 --- a/test/decl/subscript/addressors.swift +++ b/test/decl/subscript/addressors.swift @@ -72,7 +72,7 @@ struct AddressorAndGet { subscript(index: Int) -> Int { unsafeAddress { // expected-error {{subscript cannot provide both 'address' and a getter}} - return UnsafePointer(base) + return base } get { return base.get() @@ -85,7 +85,7 @@ struct AddressorAndSet { subscript(index: Int) -> Int { unsafeAddress { - return UnsafePointer(base) + return base } set { // expected-error {{subscript cannot provide both 'address' and a setter; use an ordinary getter instead}} } diff --git a/validation-test/stdlib/AtomicInt.swift b/validation-test/stdlib/AtomicInt.swift index b828a3fee31..ef803deb488 100644 --- a/validation-test/stdlib/AtomicInt.swift +++ b/validation-test/stdlib/AtomicInt.swift @@ -704,7 +704,8 @@ struct AtomicInitializeARCRefRaceTest : RaceTestWithPerTrialData { var _atomicReference: AnyObject? = nil var atomicReferencePtr: UnsafeMutablePointer { - return UnsafeMutablePointer(_getUnsafePointerToStoredProperties(self)) + return _getUnsafePointerToStoredProperties(self).assumingMemoryBound( + to: Optional.self) } init() {} diff --git a/validation-test/stdlib/CoreAudio.swift b/validation-test/stdlib/CoreAudio.swift index 477683e7ed2..de7049dfcb0 100644 --- a/validation-test/stdlib/CoreAudio.swift +++ b/validation-test/stdlib/CoreAudio.swift @@ -106,25 +106,25 @@ CoreAudioTestSuite.test( } CoreAudioTestSuite.test("AudioBufferList.sizeInBytes(maximumBuffers: Int)") { - expectEqual(ablHeaderSize + strideof(AudioBuffer), + expectEqual(ablHeaderSize + strideof(AudioBuffer.self), AudioBufferList.sizeInBytes(maximumBuffers: 1)) - expectEqual(ablHeaderSize + 16 * strideof(AudioBuffer), + expectEqual(ablHeaderSize + 16 * strideof(AudioBuffer.self), AudioBufferList.sizeInBytes(maximumBuffers: 16)) } CoreAudioTestSuite.test("AudioBufferList.sizeInBytes(maximumBuffers: Int)/trap/count<0") { expectCrashLater() - AudioBufferList.sizeInBytes(maximumBuffers: -1) + _ = AudioBufferList.sizeInBytes(maximumBuffers: -1) } CoreAudioTestSuite.test("AudioBufferList.sizeInBytes(maximumBuffers: Int)/trap/count==0") { expectCrashLater() - AudioBufferList.sizeInBytes(maximumBuffers: -1) + _ = AudioBufferList.sizeInBytes(maximumBuffers: -1) } CoreAudioTestSuite.test("AudioBufferList.sizeInBytes(maximumBuffers: Int)/trap/overflow") { expectCrashLater() - AudioBufferList.sizeInBytes(maximumBuffers: Int.max) + _ = AudioBufferList.sizeInBytes(maximumBuffers: Int.max) } CoreAudioTestSuite.test("AudioBufferList.allocate(maximumBuffers: Int)") { @@ -142,17 +142,17 @@ CoreAudioTestSuite.test("AudioBufferList.allocate(maximumBuffers: Int)") { CoreAudioTestSuite.test("AudioBufferList.allocate(maximumBuffers: Int)/trap/count==0") { expectCrashLater() - AudioBufferList.allocate(maximumBuffers: 0) + _ = AudioBufferList.allocate(maximumBuffers: 0) } CoreAudioTestSuite.test("AudioBufferList.allocate(maximumBuffers: Int)/trap/count<0") { expectCrashLater() - AudioBufferList.allocate(maximumBuffers: -1) + _ = AudioBufferList.allocate(maximumBuffers: -1) } CoreAudioTestSuite.test("AudioBufferList.allocate(maximumBuffers: Int)/trap/overflow") { expectCrashLater() - AudioBufferList.allocate(maximumBuffers: Int.max) + _ = AudioBufferList.allocate(maximumBuffers: Int.max) } CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer/AssociatedTypes") { @@ -201,28 +201,36 @@ CoreAudioTestSuite.test( CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer.count") { let sizeInBytes = AudioBufferList.sizeInBytes(maximumBuffers: 16) - let ablPtr = UnsafeMutablePointer( - UnsafeMutablePointer.allocate(capacity: sizeInBytes)) + let rawPtr = UnsafeMutableRawPointer.allocate( + bytes: sizeInBytes, alignedTo: alignof(AudioBufferList.self)) + let ablPtr = rawPtr.bindMemory(to: AudioBufferList.self, + capacity: sizeInBytes / strideof(AudioBufferList.self)) // It is important that 'ablPtrWrapper' is a 'let'. We are verifying that // the 'count' property has a nonmutating setter. let ablPtrWrapper = UnsafeMutableAudioBufferListPointer(ablPtr) // Test getter. - UnsafeMutablePointer(ablPtr).pointee = 0x1234_5678 + rawPtr.storeBytes(of: 0x1234_5678, as: UInt32.self) expectEqual(0x1234_5678, ablPtrWrapper.count) // Test setter. ablPtrWrapper.count = 0x7765_4321 - expectEqual(0x7765_4321, UnsafeMutablePointer(ablPtr).pointee) + expectEqual(0x7765_4321, rawPtr.load(as: UInt32.self)) - ablPtr.deallocate(capacity: sizeInBytes) + rawPtr.deallocate( + bytes: sizeInBytes, alignedTo: alignof(AudioBufferList.self)) } CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer.subscript(_: Int)") { let sizeInBytes = AudioBufferList.sizeInBytes(maximumBuffers: 16) - let ablPtr = UnsafeMutablePointer( - UnsafeMutablePointer.allocate(capacity: sizeInBytes)) + + let rawPtr = UnsafeMutableRawPointer.allocate( + bytes: sizeInBytes, alignedTo: 1) + + let ablPtr = rawPtr.bindMemory( + to: AudioBufferList.self, + capacity: sizeInBytes / sizeof(AudioBufferList.self)) // It is important that 'ablPtrWrapper' is a 'let'. We are verifying that // the subscript has a nonmutating setter. @@ -234,9 +242,9 @@ CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer.subscript(_: Int)") mNumberChannels: 2, mDataByteSize: 1024, mData: UnsafeMutableRawPointer(bitPattern: 0x1234_5678)) - UnsafeMutablePointer( - UnsafeMutablePointer(ablPtr) + ablHeaderSize - ).pointee = audioBuffer + let bufPtr = (rawPtr + ablHeaderSize).assumingMemoryBound( + to: AudioBuffer.self) + bufPtr.pointee = audioBuffer ablPtrWrapper.count = 1 expectEqual(2, ablPtrWrapper[0].mNumberChannels) @@ -253,8 +261,8 @@ CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer.subscript(_: Int)") ablPtrWrapper.count = 2 ablPtrWrapper[1] = audioBuffer - let audioBufferPtr = UnsafeMutablePointer( - UnsafeMutablePointer(ablPtr) + ablHeaderSize) + 1 + let audioBufferPtr = (rawPtr + ablHeaderSize).assumingMemoryBound( + to: AudioBuffer.self) + 1 expectEqual(5, audioBufferPtr.pointee.mNumberChannels) expectEqual(256, audioBufferPtr.pointee.mDataByteSize) expectEqual(audioBuffer.mData, audioBufferPtr.pointee.mData) diff --git a/validation-test/stdlib/NewArray.swift.gyb b/validation-test/stdlib/NewArray.swift.gyb index c4e8d875e77..ce993c650fd 100644 --- a/validation-test/stdlib/NewArray.swift.gyb +++ b/validation-test/stdlib/NewArray.swift.gyb @@ -190,7 +190,10 @@ func nsArrayOfStrings() -> Array { let src: ContiguousArray = ["foo", "bar", "baz"] return src.withUnsafeBufferPointer { - let ns = NSArray(objects: UnsafePointer($0.baseAddress!), count: $0.count) + let ns = NSArray( + objects: unsafeBitCast($0.baseAddress!, + to: UnsafeMutablePointer.self), + count: $0.count) return ns as! [NSString] } } diff --git a/validation-test/stdlib/Prototypes/PersistentVector.swift.gyb b/validation-test/stdlib/Prototypes/PersistentVector.swift.gyb index a9558356e2f..18773002127 100644 --- a/validation-test/stdlib/Prototypes/PersistentVector.swift.gyb +++ b/validation-test/stdlib/Prototypes/PersistentVector.swift.gyb @@ -104,20 +104,16 @@ import SwiftShims // func allocBytes(count: Int, alignment: Int) - -> UnsafeMutablePointer { - return UnsafeMutablePointer( - Builtin.allocRaw(count._builtinWordValue, alignment._builtinWordValue)) + -> UnsafeMutableRawPointer { + return UnsafeMutableRawPointer.allocate(bytes: count, alignedTo: alignment) } func deallocBytes( - _ pointer: UnsafeMutablePointer, + _ pointer: UnsafeMutableRawPointer, byteCount: Int, alignment: Int ) { - Builtin.deallocRaw( - pointer._rawValue, - byteCount._builtinWordValue, - alignment._builtinWordValue) + pointer.deallocate(bytes: byteCount, alignedTo: alignment) } func _swift_stdlib_atomicStoreInt( @@ -125,7 +121,7 @@ func _swift_stdlib_atomicStoreInt( desired: Int) { #if arch(x86_64) return _swift_stdlib_atomicStoreUInt64( - object: UnsafeMutablePointer(target), + object: unsafeBitCast(target, to: UnsafeMutablePointer.self), desired: UInt64(UInt(bitPattern: desired))) #endif } @@ -357,10 +353,10 @@ struct _PVSparseVectorNodePointer return _valueVectorOffset(layout: layout) + _valueVectorSize(layout: layout) } - var _nodePointer: UnsafeMutablePointer + var _nodePointer: UnsafeMutableRawPointer var _referenceCountPointer: UnsafeMutablePointer { - return UnsafeMutablePointer(_nodePointer) + return _nodePointer.assumingMemoryBound(to: Int.self) } var layoutParameters: _PVSparseVectorNodeLayoutParameters { @@ -403,23 +399,23 @@ struct _PVSparseVectorNodePointer var childNodePopulationBitmap: _Int32Bitmap { unsafeAddress { - return UnsafePointer( - _nodePointer + _Self._childNodePopulationBitmapOffset) + return UnsafePointer((_nodePointer + _Self._childNodePopulationBitmapOffset) + .assumingMemoryBound(to: _Int32Bitmap.self)) } nonmutating unsafeMutableAddress { - return UnsafeMutablePointer( - _nodePointer + _Self._childNodePopulationBitmapOffset) + return (_nodePointer + _Self._childNodePopulationBitmapOffset) + .assumingMemoryBound(to: _Int32Bitmap.self) } } var keyPopulationBitmap: _Int32Bitmap { unsafeAddress { - return UnsafePointer( - _nodePointer + _Self._keyPopulationBitmapOffset) + return UnsafePointer((_nodePointer + _Self._keyPopulationBitmapOffset) + .assumingMemoryBound(to: _Int32Bitmap.self)) } nonmutating unsafeMutableAddress { - return UnsafeMutablePointer( - _nodePointer + _Self._keyPopulationBitmapOffset) + return (_nodePointer + _Self._keyPopulationBitmapOffset) + .assumingMemoryBound(to: _Int32Bitmap.self) } } @@ -432,8 +428,8 @@ struct _PVSparseVectorNodePointer } var _childNodeVector: UnsafeMutablePointer<_PVAnyNodePointer?> { - return UnsafeMutablePointer( - _nodePointer + _Self._childNodeVectorOffset) + return (_nodePointer + _Self._childNodeVectorOffset) + .assumingMemoryBound(to: Optional<_PVAnyNodePointer>.self) } var childNodes: UnsafeMutableBufferPointer<_PVAnyNodePointer?> { @@ -444,17 +440,17 @@ struct _PVSparseVectorNodePointer func _keyVector(layout: _PVSparseVectorNodeLayoutParameters) -> UnsafeMutablePointer { - return UnsafeMutablePointer( - _nodePointer + _Self._keyVectorOffset(layout: layout)) + return (_nodePointer + _Self._keyVectorOffset(layout: layout)) + .assumingMemoryBound(to: Key.self) } func _valueVector(layout: _PVSparseVectorNodeLayoutParameters) -> UnsafeMutablePointer { - return UnsafeMutablePointer( - _nodePointer + _Self._valueVectorOffset(layout: layout)) + return (_nodePointer + _Self._valueVectorOffset(layout: layout)) + .assumingMemoryBound(to: Value.self) } - init(_nodePointer: UnsafeMutablePointer) { + init(_nodePointer: UnsafeMutableRawPointer) { self._nodePointer = _nodePointer } @@ -1025,10 +1021,10 @@ struct _PVArrayNodePointer return _valueArrayOffset + _valueArraySize } - var _nodePointer: UnsafeMutablePointer + var _nodePointer: UnsafeMutableRawPointer var _referenceCountPointer: UnsafeMutablePointer { - return UnsafeMutablePointer(_nodePointer) + return _nodePointer.assumingMemoryBound(to: Int.self) } func retain() { @@ -1049,14 +1045,14 @@ struct _PVArrayNodePointer func dealloc() { for i in childNodePopulationBitmap.setBitIndices { - UnsafeMutablePointer<_PVAnyNodePointer>( - _childNodeOrKeyArray + _Self._childNodeOrKeyStride * i) + (_childNodeOrKeyArray + _Self._childNodeOrKeyStride * i) + .assumingMemoryBound(to: _PVAnyNodePointer.self) .pointee.release() } if !_isPOD(Key.self) { for i in keyPopulationBitmap.setBitIndices { - UnsafeMutablePointer( - _childNodeOrKeyArray + _Self._childNodeOrKeyStride * i) + (_childNodeOrKeyArray + _Self._childNodeOrKeyStride * i) + .assumingMemoryBound(to: Key.self) .deinitialize() } } @@ -1076,23 +1072,23 @@ struct _PVArrayNodePointer var childNodePopulationBitmap: _Int32Bitmap { unsafeAddress { - return UnsafePointer( - _nodePointer + _Self._childNodePopulationBitmapOffset) + return UnsafePointer((_nodePointer + _Self._childNodePopulationBitmapOffset) + .assumingMemoryBound(to: _Int32Bitmap.self)) } nonmutating unsafeMutableAddress { - return UnsafeMutablePointer( - _nodePointer + _Self._childNodePopulationBitmapOffset) + return (_nodePointer + _Self._childNodePopulationBitmapOffset) + .assumingMemoryBound(to: _Int32Bitmap.self) } } var keyPopulationBitmap: _Int32Bitmap { unsafeAddress { - return UnsafePointer( - _nodePointer + _Self._keyPopulationBitmapOffset) + return UnsafePointer((_nodePointer + _Self._keyPopulationBitmapOffset) + .assumingMemoryBound(to: _Int32Bitmap.self)) } nonmutating unsafeMutableAddress { - return UnsafeMutablePointer( - _nodePointer + _Self._keyPopulationBitmapOffset) + return (_nodePointer + _Self._keyPopulationBitmapOffset) + .assumingMemoryBound(to: _Int32Bitmap.self) } } @@ -1104,17 +1100,16 @@ struct _PVArrayNodePointer return keyPopulationBitmap.setBitCount } - var _childNodeOrKeyArray: UnsafeMutablePointer { - return UnsafeMutablePointer( - _nodePointer + _Self._childNodeOrKeyArrayOffset) + var _childNodeOrKeyArray: UnsafeMutableRawPointer { + return _nodePointer + _Self._childNodeOrKeyArrayOffset } var _valueArray: UnsafeMutablePointer { - return UnsafeMutablePointer( - _nodePointer + _Self._valueArrayOffset) + return (_nodePointer + _Self._valueArrayOffset) + .assumingMemoryBound(to: Value.self) } - init(_nodePointer: UnsafeMutablePointer) { + init(_nodePointer: UnsafeMutableRawPointer) { self._nodePointer = _nodePointer } @@ -1138,9 +1133,8 @@ struct _PVArrayNodePointer precondition(!childNodePopulationBitmap[i]) // sanity check precondition(!keyPopulationBitmap[i]) // sanity check - UnsafeMutablePointer( - _childNodeOrKeyArray + _Self._childNodeOrKeyStride * i) - .initialize(to: key) + (_childNodeOrKeyArray + _Self._childNodeOrKeyStride * i) + .initializeMemory(as: Key.self, to: key) (_valueArray + i).initialize(to: value) keyPopulationBitmap[i] = true @@ -1242,10 +1236,10 @@ struct _PVCollisionNodePointer return _valueArrayOffset(layout: layout) + _valueArraySize(layout: layout) } - var _nodePointer: UnsafeMutablePointer + var _nodePointer: UnsafeMutableRawPointer var _referenceCountPointer: UnsafeMutablePointer { - return UnsafeMutablePointer(_nodePointer) + return _nodePointer.assumingMemoryBound(to: Int.self) } var layoutParameters: _PVCollisionNodePointerLayoutParameters { @@ -1284,25 +1278,27 @@ struct _PVCollisionNodePointer var keyCount: Int { unsafeAddress { - return UnsafePointer(_nodePointer + _Self._countOffset) + return UnsafePointer((_nodePointer + _Self._countOffset) + .assumingMemoryBound(to: Int.self)) } nonmutating unsafeMutableAddress { - return UnsafeMutablePointer(_nodePointer + _Self._countOffset) + return (_nodePointer + _Self._countOffset) + .assumingMemoryBound(to: Int.self) } } var _keyArray: UnsafeMutablePointer { - return UnsafeMutablePointer( - _nodePointer + _Self._keyArrayOffset) + return (_nodePointer + _Self._keyArrayOffset) + .assumingMemoryBound(to: Key.self) } func _valueArray(layout: _PVCollisionNodePointerLayoutParameters) -> UnsafeMutablePointer { - return UnsafeMutablePointer( - _nodePointer + _Self._valueArrayOffset(layout: layout)) + return (_nodePointer + _Self._valueArrayOffset(layout: layout)) + .assumingMemoryBound(to: Value.self) } - init(_nodePointer: UnsafeMutablePointer) { + init(_nodePointer: UnsafeMutableRawPointer) { self._nodePointer = _nodePointer } @@ -1486,9 +1482,9 @@ struct _PVCollisionNodePointer struct _PVAnyNodePointer : CustomReflectable, Equatable { - let taggedPointer: UnsafeMutablePointer + let taggedPointer: UnsafeMutableRawPointer - init(taggedPointer: UnsafeMutablePointer) { + init(taggedPointer: UnsafeMutableRawPointer) { self.taggedPointer = taggedPointer } @@ -1501,14 +1497,14 @@ struct _PVAnyNodePointer init(_ arrayNode: _PVArrayNodePointer) { precondition( Int(bitPattern: arrayNode._nodePointer) & 0x3 == 0) // sanity check - self.taggedPointer = UnsafeMutablePointer(bitPattern: + self.taggedPointer = UnsafeMutableRawPointer(bitPattern: Int(bitPattern: arrayNode._nodePointer) | 1)! } init(_ collisionNode: _PVCollisionNodePointer) { precondition( Int(bitPattern: collisionNode._nodePointer) & 0x3 == 0) // sanity check - self.taggedPointer = UnsafeMutablePointer(bitPattern: + self.taggedPointer = UnsafeMutableRawPointer(bitPattern: Int(bitPattern: collisionNode._nodePointer) | 2)! } @@ -1516,13 +1512,13 @@ struct _PVAnyNodePointer return Int(bitPattern: taggedPointer) & 0x3 } - var _untaggedPointer: UnsafeMutablePointer { - return UnsafeMutablePointer(bitPattern: + var _untaggedPointer: UnsafeMutableRawPointer { + return UnsafeMutableRawPointer(bitPattern: Int(bitPattern: taggedPointer) & ~0x3)! } var _referenceCountPointer: UnsafeMutablePointer { - return UnsafeMutablePointer(_untaggedPointer) + return _untaggedPointer.assumingMemoryBound(to: Int.self) } var asSparseVectorNode: _PVSparseVectorNodePointer {