Merge pull request #21970 from jrose-apple/5.0-layout-is-french-for-exit

[5.0] Test that newer libobjcs let the Swift runtime set up a class's layout
diff --git a/include/swift/AST/Decl.h b/include/swift/AST/Decl.h
index 206dcd9..f1df095 100644
--- a/include/swift/AST/Decl.h
+++ b/include/swift/AST/Decl.h
@@ -488,7 +488,7 @@
     HasLazyConformances : 1
   );
 
-  SWIFT_INLINE_BITFIELD_FULL(ProtocolDecl, NominalTypeDecl, 1+1+1+1+1+1+1+2+8+16,
+  SWIFT_INLINE_BITFIELD_FULL(ProtocolDecl, NominalTypeDecl, 1+1+1+1+1+1+1+2+1+8+16,
     /// Whether the \c RequiresClass bit is valid.
     RequiresClassValid : 1,
 
@@ -514,6 +514,9 @@
     /// The stage of the circularity check for this protocol.
     Circularity : 2,
 
+    /// Whether we've computed the inherited protocols list yet.
+    InheritedProtocolsValid : 1,
+
     : NumPadBits,
 
     /// If this is a compiler-known protocol, this will be a KnownProtocolKind
@@ -3892,15 +3895,7 @@
 class ProtocolDecl final : public NominalTypeDecl {
   SourceLoc ProtocolLoc;
 
-  /// The generic signature representing exactly the new requirements introduced
-  /// by this protocol.
-  const Requirement *RequirementSignature = nullptr;
-
-  bool requiresClassSlow();
-
-  bool existentialConformsToSelfSlow();
-
-  bool existentialTypeSupportedSlow(LazyResolver *resolver);
+  ArrayRef<ProtocolDecl *> InheritedProtocols;
 
   struct {
     /// The superclass decl and a bit to indicate whether the
@@ -3912,6 +3907,18 @@
     llvm::PointerIntPair<Type, 1, bool> SuperclassType;
   } LazySemanticInfo;
 
+  /// The generic signature representing exactly the new requirements introduced
+  /// by this protocol.
+  const Requirement *RequirementSignature = nullptr;
+
+  bool requiresClassSlow();
+
+  bool existentialConformsToSelfSlow();
+
+  bool existentialTypeSupportedSlow(LazyResolver *resolver);
+
+  ArrayRef<ProtocolDecl *> getInheritedProtocolsSlow();
+
   friend class SuperclassDeclRequest;
   friend class SuperclassTypeRequest;
   friend class TypeChecker;
@@ -3924,7 +3931,12 @@
   using Decl::getASTContext;
 
   /// Retrieve the set of protocols inherited from this protocol.
-  llvm::TinyPtrVector<ProtocolDecl *> getInheritedProtocols() const;
+  ArrayRef<ProtocolDecl *> getInheritedProtocols() const {
+    if (Bits.ProtocolDecl.InheritedProtocolsValid)
+      return InheritedProtocols;
+
+    return const_cast<ProtocolDecl *>(this)->getInheritedProtocolsSlow();
+  }
 
   /// Determine whether this protocol has a superclass.
   bool hasSuperclass() const { return (bool)getSuperclassDecl(); }
diff --git a/lib/AST/Decl.cpp b/lib/AST/Decl.cpp
index 19f5f7e..3741c08 100644
--- a/lib/AST/Decl.cpp
+++ b/lib/AST/Decl.cpp
@@ -3856,16 +3856,19 @@
   Bits.ProtocolDecl.ExistentialConformsToSelf = false;
   Bits.ProtocolDecl.Circularity
     = static_cast<unsigned>(CircularityCheck::Unchecked);
+  Bits.ProtocolDecl.InheritedProtocolsValid = 0;
   Bits.ProtocolDecl.NumRequirementsInSignature = 0;
   Bits.ProtocolDecl.HasMissingRequirements = false;
   Bits.ProtocolDecl.KnownProtocol = 0;
-  setTrailingWhereClause(TrailingWhere);
+    setTrailingWhereClause(TrailingWhere);
 }
 
-llvm::TinyPtrVector<ProtocolDecl *>
-ProtocolDecl::getInheritedProtocols() const {
-  llvm::TinyPtrVector<ProtocolDecl *> result;
-  SmallPtrSet<const ProtocolDecl *, 4> known;
+ArrayRef<ProtocolDecl *>
+ProtocolDecl::getInheritedProtocolsSlow() {
+  Bits.ProtocolDecl.InheritedProtocolsValid = true;
+
+  llvm::SmallVector<ProtocolDecl *, 2> result;
+  SmallPtrSet<const ProtocolDecl *, 2> known;
   known.insert(this);
   bool anyObject = false;
   for (const auto found :
@@ -3877,7 +3880,9 @@
     }
   }
 
-  return result;
+  auto &ctx = getASTContext();
+  InheritedProtocols = ctx.AllocateCopy(result);
+  return InheritedProtocols;
 }
 
 llvm::TinyPtrVector<AssociatedTypeDecl *>
diff --git a/lib/AST/NameLookup.cpp b/lib/AST/NameLookup.cpp
index 61a8866..cb6bc3a 100644
--- a/lib/AST/NameLookup.cpp
+++ b/lib/AST/NameLookup.cpp
@@ -590,6 +590,14 @@
   auto *extDecl = decl.dyn_cast<ExtensionDecl *>();
 
   DeclContext *dc = protoDecl ? (DeclContext *)protoDecl : (DeclContext *)extDecl;
+
+  // A protocol or extension 'where' clause can reference associated types of
+  // the protocol itself, so we have to start unqualified lookup from 'dc'.
+  //
+  // However, the right hand side of a 'Self' conformance constraint must be
+  // resolved before unqualified lookup into 'dc' can work, so we make an
+  // exception here and begin lookup from the parent context instead.
+  auto *lookupDC = dc->getParent();
   auto requirements = protoDecl ? protoDecl->getTrailingWhereClause()
                                 : extDecl->getTrailingWhereClause();
 
@@ -619,7 +627,7 @@
     // Resolve the right-hand side.
     DirectlyReferencedTypeDecls rhsDecls;
     if (auto typeRepr = req.getConstraintRepr()) {
-      rhsDecls = directReferencesForTypeRepr(evaluator, ctx, typeRepr, dc);
+      rhsDecls = directReferencesForTypeRepr(evaluator, ctx, typeRepr, lookupDC);
     } else if (Type type = req.getConstraint()) {
       rhsDecls = directReferencesForType(type);
     }
diff --git a/lib/Sema/TypeCheckError.cpp b/lib/Sema/TypeCheckError.cpp
index a967828..20ead77 100644
--- a/lib/Sema/TypeCheckError.cpp
+++ b/lib/Sema/TypeCheckError.cpp
@@ -155,6 +155,11 @@
       }
     }
     
+    // Constructor delegation.
+    if (auto otherCtorDeclRef = dyn_cast<OtherConstructorDeclRefExpr>(fn)) {
+      return AbstractFunction(otherCtorDeclRef->getDecl());
+    }
+
     // Normal function references.
     if (auto declRef = dyn_cast<DeclRefExpr>(fn)) {
       ValueDecl *decl = declRef->getDecl();
diff --git a/stdlib/public/SDK/Foundation/JSONEncoder.swift b/stdlib/public/SDK/Foundation/JSONEncoder.swift
index e5811a0..d871160 100644
--- a/stdlib/public/SDK/Foundation/JSONEncoder.swift
+++ b/stdlib/public/SDK/Foundation/JSONEncoder.swift
@@ -53,9 +53,9 @@
 /// `JSONEncoder` facilitates the encoding of `Encodable` values into JSON.
 // NOTE: older overlays had Foundation.JSONEncoder as the ObjC name.
 // The two must coexist, so it was renamed. The old name must not be
-// used in the new runtime. _TtC10Foundation12_JSONEncoder is the
-// mangled name for Foundation._JSONEncoder.
-@_objcRuntimeName(_TtC10Foundation12_JSONEncoder)
+// used in the new runtime. _TtC10Foundation13__JSONEncoder is the
+// mangled name for Foundation.__JSONEncoder.
+@_objcRuntimeName(_TtC10Foundation13__JSONEncoder)
 open class JSONEncoder {
     // MARK: Options
 
@@ -1017,9 +1017,9 @@
 /// `JSONDecoder` facilitates the decoding of JSON into semantic `Decodable` types.
 // NOTE: older overlays had Foundation.JSONDecoder as the ObjC name.
 // The two must coexist, so it was renamed. The old name must not be
-// used in the new runtime. _TtC10Foundation12_JSONDecoder is the
-// mangled name for Foundation._JSONDecoder.
-@_objcRuntimeName(_TtC10Foundation12_JSONDecoder)
+// used in the new runtime. _TtC10Foundation13__JSONDecoder is the
+// mangled name for Foundation.__JSONDecoder.
+@_objcRuntimeName(_TtC10Foundation13__JSONDecoder)
 open class JSONDecoder {
     // MARK: Options
 
@@ -1190,7 +1190,7 @@
             throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: error))
         }
 
-        let decoder = _JSONDecoder(referencing: topLevel, options: self.options)
+        let decoder = __JSONDecoder(referencing: topLevel, options: self.options)
         guard let value = try decoder.unbox(topLevel, as: type) else {
             throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: [], debugDescription: "The given data did not contain a top-level value."))
         }
@@ -1199,9 +1199,12 @@
     }
 }
 
-// MARK: - _JSONDecoder
+// MARK: - __JSONDecoder
 
-fileprivate class _JSONDecoder : Decoder {
+// NOTE: older overlays called this class _JSONDecoder. The two must
+// coexist without a conflicting ObjC class name, so it was renamed.
+// The old name must not be used in the new runtime.
+fileprivate class __JSONDecoder : Decoder {
     // MARK: Properties
 
     /// The decoder's storage.
@@ -1307,7 +1310,7 @@
     // MARK: Properties
 
     /// A reference to the decoder we're reading from.
-    private let decoder: _JSONDecoder
+    private let decoder: __JSONDecoder
 
     /// A reference to the container we're reading from.
     private let container: [String : Any]
@@ -1318,7 +1321,7 @@
     // MARK: - Initialization
 
     /// Initializes `self` by referencing the given decoder and container.
-    fileprivate init(referencing decoder: _JSONDecoder, wrapping container: [String : Any]) {
+    fileprivate init(referencing decoder: __JSONDecoder, wrapping container: [String : Any]) {
         self.decoder = decoder
         switch decoder.options.keyDecodingStrategy {
         case .useDefaultKeys:
@@ -1637,7 +1640,7 @@
         defer { self.decoder.codingPath.removeLast() }
 
         let value: Any = self.container[key.stringValue] ?? NSNull()
-        return _JSONDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options)
+        return __JSONDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options)
     }
 
     public func superDecoder() throws -> Decoder {
@@ -1653,7 +1656,7 @@
     // MARK: Properties
 
     /// A reference to the decoder we're reading from.
-    private let decoder: _JSONDecoder
+    private let decoder: __JSONDecoder
 
     /// A reference to the container we're reading from.
     private let container: [Any]
@@ -1667,7 +1670,7 @@
     // MARK: - Initialization
 
     /// Initializes `self` by referencing the given decoder and container.
-    fileprivate init(referencing decoder: _JSONDecoder, wrapping container: [Any]) {
+    fileprivate init(referencing decoder: __JSONDecoder, wrapping container: [Any]) {
         self.decoder = decoder
         self.container = container
         self.codingPath = decoder.codingPath
@@ -2000,11 +2003,11 @@
 
         let value = self.container[self.currentIndex]
         self.currentIndex += 1
-        return _JSONDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options)
+        return __JSONDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options)
     }
 }
 
-extension _JSONDecoder : SingleValueDecodingContainer {
+extension __JSONDecoder : SingleValueDecodingContainer {
     // MARK: SingleValueDecodingContainer Methods
 
     private func expectNonNull<T>(_ type: T.Type) throws {
@@ -2095,7 +2098,7 @@
 
 // MARK: - Concrete Value Representations
 
-extension _JSONDecoder {
+extension __JSONDecoder {
     /// Returns the given value unboxed from a container.
     fileprivate func unbox(_ value: Any, as type: Bool.Type) throws -> Bool? {
         guard !(value is NSNull) else { return nil }
diff --git a/stdlib/public/core/AtomicInt.swift.gyb b/stdlib/public/core/AtomicInt.swift.gyb
index 17d3484..62217f2 100644
--- a/stdlib/public/core/AtomicInt.swift.gyb
+++ b/stdlib/public/core/AtomicInt.swift.gyb
@@ -10,7 +10,12 @@
 //
 //===----------------------------------------------------------------------===//
 
+// NOTE: older runtimes had Swift._stdlib_AtomicInt as the ObjC name.
+// The two must coexist, so it was renamed. The old name must not be
+// used in the new runtime. _TtCs18__stdlib_AtomicInt is the mangled
+// name for Swift.__stdlib_AtomicInt
 @available(swift, deprecated: 4.2, obsoleted: 5.0)
+@_objcRuntimeName(_TtCs18__stdlib_AtomicInt)
 public final class _stdlib_AtomicInt {
   internal var _value: Int
 
diff --git a/stdlib/public/core/Builtin.swift b/stdlib/public/core/Builtin.swift
index 761df17..01b9e89 100644
--- a/stdlib/public/core/Builtin.swift
+++ b/stdlib/public/core/Builtin.swift
@@ -668,9 +668,6 @@
   return Bool(Builtin.isUnique(&object))
 }
 
-@_silgen_name("_swift_reallocObject")
-internal func _reallocObject(_ object: UnsafeMutableRawPointer, _ newSizeInBytes: Int) -> UnsafeMutableRawPointer?
-
 /// Returns `true` if `object` is uniquely referenced.
 /// This provides sanity checks on top of the Builtin.
 @_transparent
diff --git a/stdlib/public/core/ClosedRange.swift b/stdlib/public/core/ClosedRange.swift
index d2f972d..1468ab8 100644
--- a/stdlib/public/core/ClosedRange.swift
+++ b/stdlib/public/core/ClosedRange.swift
@@ -456,3 +456,26 @@
 // shorthand. TODO: Add documentation
 public typealias CountableClosedRange<Bound: Strideable> = ClosedRange<Bound>
   where Bound.Stride : SignedInteger
+
+extension ClosedRange: Decodable where Bound: Decodable {
+  public init(from decoder: Decoder) throws {
+    var container = try decoder.unkeyedContainer()
+    let lowerBound = try container.decode(Bound.self)
+    let upperBound = try container.decode(Bound.self)
+    guard lowerBound <= upperBound else {
+      throw DecodingError.dataCorrupted(
+        DecodingError.Context(
+          codingPath: decoder.codingPath,
+          debugDescription: "Cannot initialize \(ClosedRange.self) with a lowerBound (\(lowerBound)) greater than upperBound (\(upperBound))"))
+    }
+    self.init(uncheckedBounds: (lower: lowerBound, upper: upperBound))
+  }
+}
+
+extension ClosedRange: Encodable where Bound: Encodable {
+  public func encode(to encoder: Encoder) throws {
+    var container = encoder.unkeyedContainer()
+    try container.encode(self.lowerBound)
+    try container.encode(self.upperBound)
+  }
+}
diff --git a/stdlib/public/core/Codable.swift.gyb b/stdlib/public/core/Codable.swift.gyb
index ee0dd97..d33c4d1 100644
--- a/stdlib/public/core/Codable.swift.gyb
+++ b/stdlib/public/core/Codable.swift.gyb
@@ -1767,6 +1767,40 @@
   }
 }
 
+extension ContiguousArray : Encodable where Element : Encodable {
+  /// Encodes the elements of this contiguous array into the given encoder
+  /// in an unkeyed container.
+  ///
+  /// This function throws an error if any values are invalid for the given
+  /// encoder's format.
+  ///
+  /// - Parameter encoder: The encoder to write data to.
+  public func encode(to encoder: Encoder) throws {
+    var container = encoder.unkeyedContainer()
+    for element in self {
+      try container.encode(element)
+    }
+  }
+}
+
+extension ContiguousArray : Decodable where Element : Decodable {
+  /// Creates a new contiguous array by decoding from the given decoder.
+  ///
+  /// This initializer throws an error if reading from the decoder fails, or
+  /// if the data read is corrupted or otherwise invalid.
+  ///
+  /// - Parameter decoder: The decoder to read data from.
+  public init(from decoder: Decoder) throws {
+    self.init()
+
+    var container = try decoder.unkeyedContainer()
+    while !container.isAtEnd {
+      let element = try container.decode(Element.self)
+      self.append(element)
+    }
+  }
+}
+
 extension Set : Encodable where Element : Encodable {
   /// Encodes the elements of this set into the given encoder in an unkeyed
   /// container.
diff --git a/stdlib/public/core/ManagedBuffer.swift b/stdlib/public/core/ManagedBuffer.swift
index ab5b74c..67c0a8d 100644
--- a/stdlib/public/core/ManagedBuffer.swift
+++ b/stdlib/public/core/ManagedBuffer.swift
@@ -136,30 +136,6 @@
   }
 }
 
-@inline(never)
-public func tryReallocateUniquelyReferenced<Header, Element, Buffer: ManagedBuffer<Header, Element>>(
-  buffer: inout Buffer,
-  newMinimumCapacity: Int
-) -> Bool {
-  precondition(_isBitwiseTakable(Header.self))
-  precondition(_isBitwiseTakable(Element.self))
-  precondition(isKnownUniquelyReferenced(&buffer))
-
-  let newSizeInBytes = MemoryLayout<Header>.stride
-    + newMinimumCapacity * MemoryLayout<Element>.stride
-
-  return withUnsafeMutablePointer(to: &buffer) {
-    $0.withMemoryRebound(to: UnsafeMutableRawPointer.self, capacity: 1) {
-      if let reallocdObject = _reallocObject($0.pointee, newSizeInBytes) {
-        $0.pointee = reallocdObject
-        return true
-      } else {
-        return false
-      }
-    }
-  }
-}
-
 /// Contains a buffer object, and provides access to an instance of
 /// `Header` and contiguous storage for an arbitrary number of
 /// `Element` instances stored in that buffer.
diff --git a/stdlib/public/core/Range.swift b/stdlib/public/core/Range.swift
index 25bc133..d425e8f 100644
--- a/stdlib/public/core/Range.swift
+++ b/stdlib/public/core/Range.swift
@@ -405,6 +405,29 @@
   }
 }
 
+extension Range: Decodable where Bound: Decodable {
+  public init(from decoder: Decoder) throws {
+    var container = try decoder.unkeyedContainer()
+    let lowerBound = try container.decode(Bound.self)
+    let upperBound = try container.decode(Bound.self)
+    guard lowerBound <= upperBound else {
+      throw DecodingError.dataCorrupted(
+        DecodingError.Context(
+          codingPath: decoder.codingPath,
+          debugDescription: "Cannot initialize \(Range.self) with a lowerBound (\(lowerBound)) greater than upperBound (\(upperBound))"))
+    }
+    self.init(uncheckedBounds: (lower: lowerBound, upper: upperBound))
+  }
+}
+
+extension Range: Encodable where Bound: Encodable {
+  public func encode(to encoder: Encoder) throws {
+    var container = encoder.unkeyedContainer()
+    try container.encode(self.lowerBound)
+    try container.encode(self.upperBound)
+  }
+}
+
 /// A partial half-open interval up to, but not including, an upper bound.
 ///
 /// You create `PartialRangeUpTo` instances by using the prefix half-open range
@@ -447,6 +470,20 @@
   }
 }
 
+extension PartialRangeUpTo: Decodable where Bound: Decodable {
+  public init(from decoder: Decoder) throws {
+    var container = try decoder.unkeyedContainer()
+    try self.init(container.decode(Bound.self))
+  }
+}
+
+extension PartialRangeUpTo: Encodable where Bound: Encodable {
+  public func encode(to encoder: Encoder) throws {
+    var container = encoder.unkeyedContainer()
+    try container.encode(self.upperBound)
+  }
+}
+
 /// A partial interval up to, and including, an upper bound.
 ///
 /// You create `PartialRangeThrough` instances by using the prefix closed range
@@ -488,6 +525,20 @@
   }
 }
 
+extension PartialRangeThrough: Decodable where Bound: Decodable {
+  public init(from decoder: Decoder) throws {
+    var container = try decoder.unkeyedContainer()
+    try self.init(container.decode(Bound.self))
+  }
+}
+
+extension PartialRangeThrough: Encodable where Bound: Encodable {
+  public func encode(to encoder: Encoder) throws {
+    var container = encoder.unkeyedContainer()
+    try container.encode(self.upperBound)
+  }
+}
+
 /// A partial interval extending upward from a lower bound.
 ///
 /// You create `PartialRangeFrom` instances by using the postfix range operator
@@ -624,6 +675,20 @@
   }
 }
 
+extension PartialRangeFrom: Decodable where Bound: Decodable {
+  public init(from decoder: Decoder) throws {
+    var container = try decoder.unkeyedContainer()
+    try self.init(container.decode(Bound.self))
+  }
+}
+
+extension PartialRangeFrom: Encodable where Bound: Encodable {
+  public func encode(to encoder: Encoder) throws {
+    var container = encoder.unkeyedContainer()
+    try container.encode(self.lowerBound)
+  }
+}
+
 extension Comparable {
   /// Returns a half-open range that contains its lower bound but not its upper
   /// bound.
diff --git a/stdlib/public/runtime/SwiftObject.h b/stdlib/public/runtime/SwiftObject.h
index 10e6d68..a730d51 100644
--- a/stdlib/public/runtime/SwiftObject.h
+++ b/stdlib/public/runtime/SwiftObject.h
@@ -88,11 +88,4 @@
 
 #endif
 
-namespace swift {
-
-SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_SPI
-HeapObject *_swift_reallocObject(HeapObject *obj, size_t size);
-
-}
-
 #endif
diff --git a/stdlib/public/runtime/SwiftObject.mm b/stdlib/public/runtime/SwiftObject.mm
index 14b8c53..db459da 100644
--- a/stdlib/public/runtime/SwiftObject.mm
+++ b/stdlib/public/runtime/SwiftObject.mm
@@ -82,24 +82,6 @@
 #endif
 }
 
-bool isObjCPinned(HeapObject *obj) {
-  #if SWIFT_OBJC_INTEROP
-    /* future: implement checking the relevant objc runtime bits */
-    return true;
-  #else
-    return false;
-  #endif
-}
-
-// returns non-null if realloc was successful
-SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_SPI
-HeapObject *swift::_swift_reallocObject(HeapObject *obj, size_t size) {
- if (isObjCPinned(obj) || obj->refCounts.hasSideTable()) {
-   return nullptr;
- }
- return (HeapObject *)realloc(obj, size);
-}
-
 #if SWIFT_OBJC_INTEROP
 
 /// \brief Replacement for ObjC object_isClass(), which is unavailable on
diff --git a/test/CircularReferences/protocols.swift b/test/CircularReferences/protocols.swift
new file mode 100644
index 0000000..d071907
--- /dev/null
+++ b/test/CircularReferences/protocols.swift
@@ -0,0 +1,12 @@
+// RUN: %target-typecheck-verify-swift -debug-cycles 2>&1 | %FileCheck --allow-empty %s
+
+// Verify that protocol where clause lookups don't cause cyclic dependencies.
+
+// expected-no-diagnostics
+
+class C { }
+protocol Q { }
+protocol P where Self : Q, Self : C { }
+
+// CHECK-NOT: CYCLE DETECTED
+
diff --git a/test/Syntax/Outputs/round_trip_parse_gen.swift.withkinds b/test/Syntax/Outputs/round_trip_parse_gen.swift.withkinds
index 2c1af8b..6a050fe 100644
--- a/test/Syntax/Outputs/round_trip_parse_gen.swift.withkinds
+++ b/test/Syntax/Outputs/round_trip_parse_gen.swift.withkinds
@@ -532,7 +532,7 @@
   @_implements(<ImplementsAttributeArguments><SimpleTypeIdentifier>P</SimpleTypeIdentifier>, x</ImplementsAttributeArguments>)</Attribute>
   var <PatternBinding><IdentifierPattern>y</IdentifierPattern><TypeAnnotation>: <SimpleTypeIdentifier>String</SimpleTypeIdentifier></TypeAnnotation></PatternBinding></VariableDecl></MemberDeclListItem><MemberDeclListItem><FunctionDecl><Attribute>
   @_implements(<ImplementsAttributeArguments><SimpleTypeIdentifier>P</SimpleTypeIdentifier>, g<DeclNameArguments>()</DeclNameArguments></ImplementsAttributeArguments>)</Attribute>
-  func h<FunctionSignature><ParameterClause>() </ParameterClause></FunctionSignature><CodeBlock>{}</CodeBlock></FunctionDecl></MemberDeclListItem><MemberDeclListItem><VariableDecl><Attribute>
+  func h<FunctionSignature><ParameterClause>() </ParameterClause></FunctionSignature><CodeBlock>{ <SequenceExpr><DiscardAssignmentExpr>_ </DiscardAssignmentExpr><AssignmentExpr>= </AssignmentExpr><KeyPathExpr>\<DotSelfExpr>.self </DotSelfExpr></KeyPathExpr></SequenceExpr>}</CodeBlock></FunctionDecl></MemberDeclListItem><MemberDeclListItem><VariableDecl><Attribute>
 
   @available(<AvailabilityArgument>*, </AvailabilityArgument><AvailabilityArgument><AvailabilityLabeledArgument>deprecated: <VersionTuple>1.2</VersionTuple></AvailabilityLabeledArgument>, </AvailabilityArgument><AvailabilityArgument><AvailabilityLabeledArgument>message: "ABC"</AvailabilityLabeledArgument></AvailabilityArgument>)</Attribute><DeclModifier>
   fileprivate(set) </DeclModifier>var <PatternBinding><IdentifierPattern>x</IdentifierPattern><TypeAnnotation>: <SimpleTypeIdentifier>String</SimpleTypeIdentifier></TypeAnnotation></PatternBinding></VariableDecl></MemberDeclListItem>
diff --git a/test/Syntax/round_trip_parse_gen.swift b/test/Syntax/round_trip_parse_gen.swift
index b17b017..960789c 100644
--- a/test/Syntax/round_trip_parse_gen.swift
+++ b/test/Syntax/round_trip_parse_gen.swift
@@ -532,7 +532,7 @@
   @_implements(P, x)
   var y: String
   @_implements(P, g())
-  func h() {}
+  func h() { _ = \.self }
 
   @available(*, deprecated: 1.2, message: "ABC")
   fileprivate(set) var x: String
diff --git a/test/api-digester/Outputs/stability-stdlib-abi.swift.expected b/test/api-digester/Outputs/stability-stdlib-abi.swift.expected
index acdca7b..50cae2d 100644
--- a/test/api-digester/Outputs/stability-stdlib-abi.swift.expected
+++ b/test/api-digester/Outputs/stability-stdlib-abi.swift.expected
@@ -42,3 +42,6 @@
 Var _NativeSet._storage has declared type change from _RawSetStorage to __RawSetStorage
 Var _RawDictionaryStorage.empty has declared type change from _EmptyDictionarySingleton to __EmptyDictionarySingleton
 Var _RawSetStorage.empty has declared type change from _EmptySetSingleton to __EmptySetSingleton
+
+Func tryReallocateUniquelyReferenced(buffer:newMinimumCapacity:) has been removed
+
diff --git a/test/api-digester/Outputs/stability-stdlib-source.swift.expected b/test/api-digester/Outputs/stability-stdlib-source.swift.expected
index 8b13789..5678bdb 100644
--- a/test/api-digester/Outputs/stability-stdlib-source.swift.expected
+++ b/test/api-digester/Outputs/stability-stdlib-source.swift.expected
@@ -1 +1 @@
-
+Func tryReallocateUniquelyReferenced(buffer:newMinimumCapacity:) has been removed
diff --git a/test/decl/func/rethrows.swift b/test/decl/func/rethrows.swift
index 86ca746..46de659 100644
--- a/test/decl/func/rethrows.swift
+++ b/test/decl/func/rethrows.swift
@@ -584,3 +584,22 @@
 }
 
 Box(unbox: 1) |> suchThat <| { $0 + 1 } // expected-warning {{result of operator '<|' is unused}}
+
+// Constructor delegation -vs- rethrows
+class RethrowingConstructor {
+  init(_ block: () throws -> ()) rethrows {
+    try block()
+  }
+
+  convenience init(bar: Int) {
+    self.init {
+      print("Foo!")
+    }
+  }
+
+  convenience init(baz: Int) throws {
+    try self.init {
+      try throwingFunc()
+    }
+  }
+}
\ No newline at end of file
diff --git a/test/stdlib/CodableTests.swift b/test/stdlib/CodableTests.swift
index b7a6a78..23dd0c8 100644
--- a/test/stdlib/CodableTests.swift
+++ b/test/stdlib/CodableTests.swift
@@ -49,7 +49,8 @@
     }
 }
 
-func expectRoundTripEquality<T : Codable>(of value: T, encode: (T) throws -> Data, decode: (Data) throws -> T, lineNumber: Int) where T : Equatable {
+func performEncodeAndDecode<T : Codable>(of value: T, encode: (T) throws -> Data, decode: (T.Type, Data) throws -> T, lineNumber: Int) -> T {
+
     let data: Data
     do {
         data = try encode(value)
@@ -57,12 +58,16 @@
         fatalError("\(#file):\(lineNumber): Unable to encode \(T.self) <\(debugDescription(value))>: \(error)")
     }
 
-    let decoded: T
     do {
-        decoded = try decode(data)
+        return try decode(T.self, data)
     } catch {
         fatalError("\(#file):\(lineNumber): Unable to decode \(T.self) <\(debugDescription(value))>: \(error)")
     }
+}
+
+func expectRoundTripEquality<T : Codable>(of value: T, encode: (T) throws -> Data, decode: (T.Type, Data) throws -> T, lineNumber: Int) where T : Equatable {
+
+    let decoded = performEncodeAndDecode(of: value, encode: encode, decode: decode, lineNumber: lineNumber)
 
     expectEqual(value, decoded, "\(#file):\(lineNumber): Decoded \(T.self) <\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
 }
@@ -77,12 +82,12 @@
         return try encoder.encode(value)
     }
 
-    let decode = { (_ data: Data) throws -> T in
+    let decode = { (_ type: T.Type, _ data: Data) throws -> T in
         let decoder = JSONDecoder()
         decoder.nonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: inf,
                                                                         negativeInfinity: negInf,
                                                                         nan: nan)
-        return try decoder.decode(T.self, from: data)
+        return try decoder.decode(type, from: data)
     }
 
     expectRoundTripEquality(of: value, encode: encode, decode: decode, lineNumber: lineNumber)
@@ -93,8 +98,8 @@
         return try PropertyListEncoder().encode(value)
     }
 
-    let decode = { (_ data: Data) throws -> T in
-        return try PropertyListDecoder().decode(T.self, from: data)
+    let decode = { (_ type: T.Type,_ data: Data) throws -> T in
+        return try PropertyListDecoder().decode(type, from: data)
     }
 
     expectRoundTripEquality(of: value, encode: encode, decode: decode, lineNumber: lineNumber)
@@ -351,6 +356,21 @@
         }
     }
 
+    // MARK: - ClosedRange
+    func test_ClosedRange_JSON() {
+        let value = 0...Int.max
+        let decoded = performEncodeAndDecode(of: value, encode: { try JSONEncoder().encode($0) }, decode: { try JSONDecoder().decode($0, from: $1)  }, lineNumber: #line)
+        expectEqual(value.upperBound, decoded.upperBound, "\(#file):\(#line): Decoded ClosedRange upperBound <\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+        expectEqual(value.lowerBound, decoded.lowerBound, "\(#file):\(#line): Decoded ClosedRange lowerBound <\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+    }
+
+    func test_ClosedRange_Plist() {
+        let value = 0...Int.max
+        let decoded = performEncodeAndDecode(of: value, encode: { try PropertyListEncoder().encode($0) }, decode: { try PropertyListDecoder().decode($0, from: $1)  }, lineNumber: #line)
+        expectEqual(value.upperBound, decoded.upperBound, "\(#file):\(#line): Decoded ClosedRange upperBound <\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+        expectEqual(value.lowerBound, decoded.lowerBound, "\(#file):\(#line): Decoded ClosedRange lowerBound <\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+    }
+
     // MARK: - DateComponents
     lazy var dateComponents: Set<Calendar.Component> = [
         .era, .year, .month, .day, .hour, .minute, .second, .nanosecond,
@@ -545,6 +565,45 @@
         }
     }
 
+    // MARK: - PartialRangeFrom
+    func test_PartialRangeFrom_JSON() {
+        let value = 0...
+        let decoded = performEncodeAndDecode(of: value, encode: { try JSONEncoder().encode($0) }, decode: { try JSONDecoder().decode($0, from: $1)  }, lineNumber: #line)
+        expectEqual(value.lowerBound, decoded.lowerBound, "\(#file):\(#line): Decoded PartialRangeFrom <\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+    }
+
+    func test_PartialRangeFrom_Plist() {
+        let value = 0...
+        let decoded = performEncodeAndDecode(of: value, encode: { try PropertyListEncoder().encode($0) }, decode: { try PropertyListDecoder().decode($0, from: $1)  }, lineNumber: #line)
+        expectEqual(value.lowerBound, decoded.lowerBound, "\(#file):\(#line): Decoded PartialRangeFrom <\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+    }
+
+    // MARK: - PartialRangeThrough
+    func test_PartialRangeThrough_JSON() {
+        let value = ...Int.max
+        let decoded = performEncodeAndDecode(of: value, encode: { try JSONEncoder().encode($0) }, decode: { try JSONDecoder().decode($0, from: $1)  }, lineNumber: #line)
+        expectEqual(value.upperBound, decoded.upperBound, "\(#file):\(#line): Decoded PartialRangeThrough <\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+    }
+
+    func test_PartialRangeThrough_Plist() {
+        let value = ...Int.max
+        let decoded = performEncodeAndDecode(of: value, encode: { try PropertyListEncoder().encode($0) }, decode: { try PropertyListDecoder().decode($0, from: $1)  }, lineNumber: #line)
+        expectEqual(value.upperBound, decoded.upperBound, "\(#file):\(#line): Decoded PartialRangeThrough <\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+    }
+
+    // MARK: - PartialRangeUpTo
+    func test_PartialRangeUpTo_JSON() {
+        let value = ..<Int.max
+        let decoded = performEncodeAndDecode(of: value, encode: { try JSONEncoder().encode($0) }, decode: { try JSONDecoder().decode($0, from: $1)  }, lineNumber: #line)
+        expectEqual(value.upperBound, decoded.upperBound, "\(#file):\(#line): Decoded PartialRangeUpTo <\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+    }
+
+    func test_PartialRangeUpTo_Plist() {
+        let value = ..<Int.max
+        let decoded = performEncodeAndDecode(of: value, encode: { try PropertyListEncoder().encode($0) }, decode: { try PropertyListDecoder().decode($0, from: $1)  }, lineNumber: #line)
+        expectEqual(value.upperBound, decoded.upperBound, "\(#file):\(#line): Decoded PartialRangeUpTo <\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+    }
+
     // MARK: - PersonNameComponents
     @available(macOS 10.11, iOS 9.0, watchOS 2.0, tvOS 9.0, *)
     lazy var personNameComponentsValues: [Int : PersonNameComponents] = [
@@ -567,6 +626,21 @@
         }
     }
 
+    // MARK: - Range
+    func test_Range_JSON() {
+        let value = 0..<Int.max
+        let decoded = performEncodeAndDecode(of: value, encode: { try JSONEncoder().encode($0) }, decode: { try JSONDecoder().decode($0, from: $1)  }, lineNumber: #line)
+        expectEqual(value.upperBound, decoded.upperBound, "\(#file):\(#line): Decoded Range upperBound <\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+        expectEqual(value.lowerBound, decoded.lowerBound, "\(#file):\(#line): Decoded Range lowerBound<\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+    }
+
+    func test_Range_Plist() {
+        let value = 0..<Int.max
+        let decoded = performEncodeAndDecode(of: value, encode: { try PropertyListEncoder().encode($0) }, decode: { try PropertyListDecoder().decode($0, from: $1)  }, lineNumber: #line)
+        expectEqual(value.upperBound, decoded.upperBound, "\(#file):\(#line): Decoded Range upperBound<\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+        expectEqual(value.lowerBound, decoded.lowerBound, "\(#file):\(#line): Decoded Range lowerBound<\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+    }
+
     // MARK: - TimeZone
     lazy var timeZoneValues: [Int : TimeZone] = [
         #line : TimeZone(identifier: "America/Los_Angeles")!,
@@ -777,6 +851,8 @@
     "test_CGRect_Plist" : TestCodable.test_CGRect_Plist,
     "test_CGVector_JSON" : TestCodable.test_CGVector_JSON,
     "test_CGVector_Plist" : TestCodable.test_CGVector_Plist,
+    "test_ClosedRange_JSON" : TestCodable.test_ClosedRange_JSON,
+    "test_ClosedRange_Plist" : TestCodable.test_ClosedRange_Plist,
     "test_DateComponents_JSON" : TestCodable.test_DateComponents_JSON,
     "test_DateComponents_Plist" : TestCodable.test_DateComponents_Plist,
     "test_Decimal_JSON" : TestCodable.test_Decimal_JSON,
@@ -789,6 +865,14 @@
     "test_Locale_Plist" : TestCodable.test_Locale_Plist,
     "test_NSRange_JSON" : TestCodable.test_NSRange_JSON,
     "test_NSRange_Plist" : TestCodable.test_NSRange_Plist,
+    "test_PartialRangeFrom_JSON" : TestCodable.test_PartialRangeFrom_JSON,
+    "test_PartialRangeFrom_Plist" : TestCodable.test_PartialRangeFrom_Plist,
+    "test_PartialRangeThrough_JSON" : TestCodable.test_PartialRangeThrough_JSON,
+    "test_PartialRangeThrough_Plist" : TestCodable.test_PartialRangeThrough_Plist,
+    "test_PartialRangeUpTo_JSON" : TestCodable.test_PartialRangeUpTo_JSON,
+    "test_PartialRangeUpTo_Plist" : TestCodable.test_PartialRangeUpTo_Plist,
+    "test_Range_JSON" : TestCodable.test_Range_JSON,
+    "test_Range_Plist" : TestCodable.test_Range_Plist,
     "test_TimeZone_JSON" : TestCodable.test_TimeZone_JSON,
     "test_TimeZone_Plist" : TestCodable.test_TimeZone_Plist,
     "test_URL_JSON" : TestCodable.test_URL_JSON,
diff --git a/test/stdlib/ManagedBuffer.swift b/test/stdlib/ManagedBuffer.swift
index 8d39d3f..24d288c 100644
--- a/test/stdlib/ManagedBuffer.swift
+++ b/test/stdlib/ManagedBuffer.swift
@@ -40,7 +40,7 @@
 
 struct CountAndCapacity {
   var count: LifetimeTracked
-  var capacity: Int
+  let capacity: Int
 }
 
 // An example of ManagedBuffer, very similar to what Array will use.
@@ -96,23 +96,6 @@
     }
     self.count = count + 2
   }
-
-  class func tryGrow(_ buffer: inout TestManagedBuffer<T>, newCapacity: Int) -> Bool {
-    guard isKnownUniquelyReferenced(&buffer) else {
-      return false
-    }
-    guard newCapacity > buffer.capacity else {
-      return false
-    }
-
-    if tryReallocateUniquelyReferenced(buffer: &buffer,
-                                       newMinimumCapacity: newCapacity) {
-      buffer.header.capacity = newCapacity
-      return true
-    } else {
-      return false
-    }
-  }
 }
 
 class MyBuffer<T> {
@@ -258,35 +241,4 @@
   _fixLifetime(s2)
 }
 
-tests.test("canGrowUsingRealloc") {
-  #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
-  return // realloc currently unsupported on Darwin
-  #endif
-  func testGrow(_ buffer: inout TestManagedBuffer<LifetimeTracked>,
-                newCapacity: Int,
-                shouldSucceed: Bool = true) {
-    let s = TestManagedBuffer.tryGrow(&buffer, newCapacity: newCapacity)
-    expectEqual(s, shouldSucceed)
-    if shouldSucceed {
-      expectLE(newCapacity, buffer.myCapacity)
-      expectGE((newCapacity + 1) * 2, buffer.myCapacity)
-    }
-    repeat {
-      buffer.append(LifetimeTracked(buffer.count))
-    } while buffer.count < buffer.myCapacity - 2
-  }
-
-  var b = TestManagedBuffer<LifetimeTracked>.create(0)
-  // allow some over-allocation
-  expectLE(0, b.myCapacity)
-  expectGE(3, b.myCapacity)
-
-  testGrow(&b, newCapacity: 5)
-  testGrow(&b, newCapacity: 8)
-  testGrow(&b, newCapacity: 1000)
-  testGrow(&b, newCapacity: 16000)
-  var b2 = b
-  testGrow(&b, newCapacity: 2000, shouldSucceed: false)
-}
-
 runAllTests()
diff --git a/utils/gyb_syntax_support/ExprNodes.py b/utils/gyb_syntax_support/ExprNodes.py
index fc94746..3fba94f 100644
--- a/utils/gyb_syntax_support/ExprNodes.py
+++ b/utils/gyb_syntax_support/ExprNodes.py
@@ -309,10 +309,10 @@
                    is_optional=True),
          ]),
 
-    # dot-self-expr -> expr '.' 'self'
+    # dot-self-expr -> expr? '.' 'self'
     Node('DotSelfExpr', kind='Expr',
          children=[
-             Child('Expression', kind='Expr'),
+             Child('Expression', kind='Expr', is_optional=True),
              Child('Dot', kind='Token',
                    token_choices=[
                        'PeriodToken', 'PrefixPeriodToken'