Merge pull request #12269 from linux-on-ibm-z/swift-4.0-branch-s390x-test

[4.0] Update test case for s390x
diff --git a/CMakeLists.txt b/CMakeLists.txt
index dbd3855..f89847b 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -108,7 +108,7 @@
 # SWIFT_VERSION is deliberately /not/ cached so that an existing build directory
 # can be reused when a new version of Swift comes out (assuming the user hasn't
 # manually set it as part of their own CMake configuration).
-set(SWIFT_VERSION "4.0.1")
+set(SWIFT_VERSION "4.0.2")
 
 set(SWIFT_VENDOR "" CACHE STRING
     "The vendor name of the Swift compiler")
diff --git a/lib/Basic/Statistic.cpp b/lib/Basic/Statistic.cpp
index 7b1d14d..09d663d 100644
--- a/lib/Basic/Statistic.cpp
+++ b/lib/Basic/Statistic.cpp
@@ -87,8 +87,10 @@
   if (InputName.empty()) {
     InputName = "all";
   }
+  // Dispose of path prefix, which might make composite name too long.
+  InputName = path::filename(InputName);
   if (OptType.empty()) {
-    InputName = "Onone";
+    OptType = "Onone";
   }
   if (!OutputType.empty() && OutputType.front() == '.') {
     OutputType = OutputType.substr(1);
diff --git a/lib/IDE/CodeCompletion.cpp b/lib/IDE/CodeCompletion.cpp
index 292c561..ed2f647 100644
--- a/lib/IDE/CodeCompletion.cpp
+++ b/lib/IDE/CodeCompletion.cpp
@@ -1537,7 +1537,7 @@
   case CodeCompletionLiteralKind::NilLiteral:
     return KnownProtocolKind::ExpressibleByNilLiteral;
   case CodeCompletionLiteralKind::StringLiteral:
-    return KnownProtocolKind::ExpressibleByStringLiteral;
+    return KnownProtocolKind::ExpressibleByUnicodeScalarLiteral;
   case CodeCompletionLiteralKind::Tuple:
     llvm_unreachable("no such protocol kind");
   }
diff --git a/lib/IRGen/Fulfillment.cpp b/lib/IRGen/Fulfillment.cpp
index 449acb8..ac4c6a9 100644
--- a/lib/IRGen/Fulfillment.cpp
+++ b/lib/IRGen/Fulfillment.cpp
@@ -222,6 +222,11 @@
                                                unsigned source,
                                                MetadataPath &&path,
                                          const InterestingKeysCallback &keys) {
+  // We can't use an objective-c parent type as we don't populate the parent
+  // type correctly.
+  if (type->getDecl()->hasClangNode())
+    return false;
+
   // Nominal types add no generic arguments themselves, but they
   // may have the arguments of their parents.
   return searchParentTypeMetadata(IGM, type->getDecl(), type.getParent(),
diff --git a/lib/IRGen/GenCall.cpp b/lib/IRGen/GenCall.cpp
index fac359e..551acbf 100644
--- a/lib/IRGen/GenCall.cpp
+++ b/lib/IRGen/GenCall.cpp
@@ -1082,11 +1082,12 @@
     return metatype->getRepresentation() != MetatypeRepresentation::Thin;
   }
 
-  // Classes and class-bounded archetypes.
+  // Classes and class-bounded archetypes or ObjC existentials.
   // No need to apply this to existentials.
   // The direct check for SubstitutableType works because only
   // class-bounded generic types can be passed directly.
-  if (type->mayHaveSuperclass() || isa<SubstitutableType>(type)) {
+  if (type->mayHaveSuperclass() || isa<SubstitutableType>(type) ||
+      type->isObjCExistentialType()) {
     return true;
   }
 
diff --git a/lib/IRGen/IRGen.cpp b/lib/IRGen/IRGen.cpp
index e86bb7a..05d2a6f 100644
--- a/lib/IRGen/IRGen.cpp
+++ b/lib/IRGen/IRGen.cpp
@@ -15,11 +15,10 @@
 //===----------------------------------------------------------------------===//
 
 #define DEBUG_TYPE "irgen"
-#include "swift/Subsystems.h"
+#include "IRGenModule.h"
 #include "swift/AST/DiagnosticsIRGen.h"
 #include "swift/AST/IRGenOptions.h"
 #include "swift/AST/LinkLibrary.h"
-#include "swift/SIL/SILModule.h"
 #include "swift/Basic/Defer.h"
 #include "swift/Basic/Dwarf.h"
 #include "swift/Basic/Platform.h"
@@ -29,44 +28,46 @@
 #include "swift/ClangImporter/ClangImporter.h"
 #include "swift/IRGen/IRGenPublic.h"
 #include "swift/IRGen/IRGenSILPasses.h"
-#include "swift/LLVMPasses/PassesFwd.h"
 #include "swift/LLVMPasses/Passes.h"
-#include "swift/SILOptimizer/PassManager/Passes.h"
+#include "swift/LLVMPasses/PassesFwd.h"
+#include "swift/SIL/SILModule.h"
 #include "swift/SILOptimizer/PassManager/PassManager.h"
 #include "swift/SILOptimizer/PassManager/PassPipeline.h"
+#include "swift/SILOptimizer/PassManager/Passes.h"
+#include "swift/Subsystems.h"
 #include "clang/Basic/TargetInfo.h"
-#include "llvm/Bitcode/BitcodeWriterPass.h"
+#include "llvm/ADT/StringSet.h"
+#include "llvm/Analysis/AliasAnalysis.h"
 #include "llvm/Bitcode/BitcodeWriter.h"
+#include "llvm/Bitcode/BitcodeWriterPass.h"
 #include "llvm/CodeGen/BasicTTIImpl.h"
 #include "llvm/IR/Constants.h"
 #include "llvm/IR/DataLayout.h"
 #include "llvm/IR/IRPrintingPasses.h"
-#include "llvm/IR/LegacyPassManager.h"
 #include "llvm/IR/LLVMContext.h"
+#include "llvm/IR/LegacyPassManager.h"
 #include "llvm/IR/Module.h"
 #include "llvm/IR/ValueSymbolTable.h"
 #include "llvm/IR/Verifier.h"
 #include "llvm/Linker/Linker.h"
 #include "llvm/MC/SubtargetFeature.h"
+#include "llvm/Object/ObjectFile.h"
+#include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/FormattedStream.h"
-#include "llvm/Support/TargetRegistry.h"
-#include "llvm/Support/Path.h"
-#include "llvm/Support/Mutex.h"
 #include "llvm/Support/MD5.h"
-#include "llvm/ADT/StringSet.h"
-#include "llvm/Analysis/AliasAnalysis.h"
+#include "llvm/Support/Mutex.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/TargetRegistry.h"
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/Target/TargetSubtargetInfo.h"
-#include "llvm/Transforms/Instrumentation.h"
 #include "llvm/Transforms/IPO.h"
 #include "llvm/Transforms/IPO/AlwaysInliner.h"
 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
+#include "llvm/Transforms/Instrumentation.h"
 #include "llvm/Transforms/ObjCARC.h"
-#include "llvm/Object/ObjectFile.h"
-#include "IRGenModule.h"
 
 #include <thread>
 
@@ -74,6 +75,10 @@
 using namespace irgen;
 using namespace llvm;
 
+static cl::opt<bool> DisableObjCARCContract(
+    "disable-objc-arc-contract", cl::Hidden,
+    cl::desc("Disable running objc arc contract for testing purposes"));
+
 namespace {
 // We need this to access IRGenOptions from extension functions
 class PassManagerBuilderWrapper : public PassManagerBuilder {
@@ -441,6 +446,13 @@
 
   legacy::PassManager EmitPasses;
 
+  // Make sure we do ARC contraction under optimization.  We don't
+  // rely on any other LLVM ARC transformations, but we do need ARC
+  // contraction to add the objc_retainAutoreleasedReturnValue
+  // assembly markers and remove clang.arc.used.
+  if (Opts.Optimize && !DisableObjCARCContract)
+    EmitPasses.add(createObjCARCContractPass());
+
   // Set up the final emission passes.
   switch (Opts.OutputKind) {
   case IRGenOutputKind::Module:
@@ -461,13 +473,6 @@
     EmitPasses.add(createTargetTransformInfoWrapperPass(
         TargetMachine->getTargetIRAnalysis()));
 
-    // Make sure we do ARC contraction under optimization.  We don't
-    // rely on any other LLVM ARC transformations, but we do need ARC
-    // contraction to add the objc_retainAutoreleasedReturnValue
-    // assembly markers.
-    if (Opts.Optimize)
-      EmitPasses.add(createObjCARCContractPass());
-
     bool fail = TargetMachine->addPassesToEmitFile(EmitPasses, *RawOS,
                                                    FileType, !Opts.Verify);
     if (fail) {
diff --git a/lib/SILOptimizer/SILCombiner/SILCombinerApplyVisitors.cpp b/lib/SILOptimizer/SILCombiner/SILCombinerApplyVisitors.cpp
index 29b50e9..d4a74e5 100644
--- a/lib/SILOptimizer/SILCombiner/SILCombinerApplyVisitors.cpp
+++ b/lib/SILOptimizer/SILCombiner/SILCombinerApplyVisitors.cpp
@@ -956,8 +956,20 @@
 
   // Propagate the concrete type into a callee-operand, which is a
   // witness_method instruction.
-  auto PropagateIntoOperand = [this, &WMI, &AI](CanType ConcreteType,
-                                           ProtocolConformanceRef Conformance) {
+  auto PropagateIntoOperand = [this, &WMI, &AI](
+      CanType ConcreteType, ProtocolConformanceRef Conformance) {
+    if (ConcreteType == WMI->getLookupType() &&
+        Conformance == WMI->getConformance()) {
+      // If we create a new instruction that’s the same as the old one we’ll
+      // cause an infinite loop:
+      // NewWMI will be added to the Builder’s tracker list.
+      // SILCombine, in turn, uses the tracker list to populate the worklist
+      // As such, if we don’t remove the witness method later on in the pass, we
+      // are stuck:
+      // We will re-create the same instruction and re-populate the worklist
+      // with it
+      return;
+    }
     // Keep around the dependence on the open instruction unless we've
     // actually eliminated the use.
     auto *NewWMI = Builder.createWitnessMethod(WMI->getLoc(),
@@ -970,7 +982,7 @@
     MutableArrayRef<Operand> Operands = AI.getInstruction()->getAllOperands();
     for (auto &Op : Operands) {
       if (Op.get() == WMI)
-         Op.set(NewWMI); 
+        Op.set(NewWMI);
     }
     if (WMI->use_empty())
       eraseInstFromFunction(*WMI);
diff --git a/lib/Sema/CSApply.cpp b/lib/Sema/CSApply.cpp
index e84e714..f370cc9 100644
--- a/lib/Sema/CSApply.cpp
+++ b/lib/Sema/CSApply.cpp
@@ -4172,9 +4172,14 @@
           
           auto dc = subscript->getInnermostDeclContext();
           SmallVector<Substitution, 4> subs;
+          SubstitutionMap subMap;
+          auto indexType = subscript->getIndicesInterfaceType();
+
           if (auto sig = dc->getGenericSignatureOfContext()) {
             // Compute substitutions to refer to the member.
             solution.computeSubstitutions(sig, locator, subs);
+            subMap = sig->getSubstitutionMap(subs);
+            indexType = indexType.subst(subMap);
           }
           
           auto resolvedTy = foundDecl->openedType->castTo<AnyFunctionType>()
@@ -4183,9 +4188,13 @@
           
           auto ref = ConcreteDeclRef(cs.getASTContext(), subscript, subs);
           
+          // Coerce the indices to the type the subscript expects.
+          auto indexExpr = coerceToType(origComponent.getIndexExpr(),
+                                        indexType,
+                                        locator);
+          
           component = KeyPathExpr::Component
-            ::forSubscriptWithPrebuiltIndexExpr(ref,
-                                            origComponent.getIndexExpr(),
+            ::forSubscriptWithPrebuiltIndexExpr(ref, indexExpr,
                                             origComponent.getSubscriptLabels(),
                                             resolvedTy,
                                             origComponent.getLoc(),
diff --git a/stdlib/public/SDK/Foundation/Data.swift b/stdlib/public/SDK/Foundation/Data.swift
index 5398567..b8dfff3 100644
--- a/stdlib/public/SDK/Foundation/Data.swift
+++ b/stdlib/public/SDK/Foundation/Data.swift
@@ -1926,27 +1926,11 @@
 
 extension Data : Codable {
     public init(from decoder: Decoder) throws {
-        // FIXME: This is a hook for bypassing a conditional conformance implementation to apply a strategy (see SR-5206). Remove this once conditional conformance is available.
-        do {
-            let singleValueContainer = try decoder.singleValueContainer()
-            if let decoder = singleValueContainer as? _JSONDecoder {
-                switch decoder.options.dataDecodingStrategy {
-                case .deferredToData:
-                    break /* fall back to default implementation below; this would recurse */
-
-                default:
-                    // _JSONDecoder has a hook for Datas; this won't recurse since we're not going to defer back to Data in _JSONDecoder.
-                    self = try singleValueContainer.decode(Data.self)
-                    return
-                }
-            }
-        } catch { /* fall back to default implementation below */ }
-
         var container = try decoder.unkeyedContainer()
         
         // It's more efficient to pre-allocate the buffer if we can.
         if let count = container.count {
-            self = Data(count: count)
+            self.init(count: count)
             
             // Loop only until count, not while !container.isAtEnd, in case count is underestimated (this is misbehavior) and we haven't allocated enough space.
             // We don't want to write past the end of what we allocated.
@@ -1955,7 +1939,7 @@
                 self[i] = byte
             }
         } else {
-            self = Data()
+            self.init()
         }
         
         while !container.isAtEnd {
@@ -1965,21 +1949,6 @@
     }
     
     public func encode(to encoder: Encoder) throws {
-        // FIXME: This is a hook for bypassing a conditional conformance implementation to apply a strategy (see SR-5206). Remove this once conditional conformance is available.
-        // We are allowed to request this container as long as we don't encode anything through it when we need the unkeyed container below.
-        var singleValueContainer = encoder.singleValueContainer()
-        if let encoder = singleValueContainer as? _JSONEncoder {
-            switch encoder.options.dataEncodingStrategy {
-            case .deferredToData:
-                break /* fall back to default implementation below; this would recurse */
-
-            default:
-                // _JSONEncoder has a hook for Datas; this won't recurse since we're not going to defer back to Data in _JSONEncoder.
-                try singleValueContainer.encode(self)
-                return
-            }
-        }
-
         var container = encoder.unkeyedContainer()
         
         // Since enumerateBytes does not rethrow, we need to catch the error, stow it away, and rethrow if we stopped.
diff --git a/stdlib/public/SDK/Foundation/Date.swift b/stdlib/public/SDK/Foundation/Date.swift
index 05dd9d9..c179f30 100644
--- a/stdlib/public/SDK/Foundation/Date.swift
+++ b/stdlib/public/SDK/Foundation/Date.swift
@@ -287,40 +287,13 @@
 
 extension Date : Codable {
     public init(from decoder: Decoder) throws {
-        // FIXME: This is a hook for bypassing a conditional conformance implementation to apply a strategy (see SR-5206). Remove this once conditional conformance is available.
         let container = try decoder.singleValueContainer()
-        if let decoder = container as? _JSONDecoder {
-            switch decoder.options.dateDecodingStrategy {
-            case .deferredToDate:
-                break /* fall back to default implementation below; this would recurse */
-
-            default:
-                // _JSONDecoder has a hook for Dates; this won't recurse since we're not going to defer back to Date in _JSONDecoder.
-                self = try container.decode(Date.self)
-                return
-            }
-        }
-
         let timestamp = try container.decode(Double.self)
-        self = Date(timeIntervalSinceReferenceDate: timestamp)
+        self.init(timeIntervalSinceReferenceDate: timestamp)
     }
 
     public func encode(to encoder: Encoder) throws {
-        // FIXME: This is a hook for bypassing a conditional conformance implementation to apply a strategy (see SR-5206). Remove this once conditional conformance is available.
-        // We are allowed to request this container as long as we don't encode anything through it when we need the keyed container below.
         var container = encoder.singleValueContainer()
-        if let encoder = container as? _JSONEncoder {
-            switch encoder.options.dateEncodingStrategy {
-            case .deferredToDate:
-                break /* fall back to default implementation below; this would recurse */
-
-            default:
-                // _JSONEncoder has a hook for Dates; this won't recurse since we're not going to defer back to Date in _JSONEncoder.
-                try container.encode(self)
-                return
-            }
-        }
-
         try container.encode(self.timeIntervalSinceReferenceDate)
     }
 }
diff --git a/stdlib/public/SDK/Foundation/Decimal.swift b/stdlib/public/SDK/Foundation/Decimal.swift
index 4bf2c9b..23c276b 100644
--- a/stdlib/public/SDK/Foundation/Decimal.swift
+++ b/stdlib/public/SDK/Foundation/Decimal.swift
@@ -471,17 +471,6 @@
     }
 
     public init(from decoder: Decoder) throws {
-        // FIXME: This is a hook for bypassing a conditional conformance implementation to apply a strategy (see SR-5206). Remove this once conditional conformance is available.
-        do {
-            // We are allowed to request this container as long as we don't decode anything through it when we need the keyed container below.
-            let singleValueContainer = try decoder.singleValueContainer()
-            if singleValueContainer is _JSONDecoder {
-                // _JSONDecoder has a hook for Decimals; this won't recurse since we're not going to defer to Decimal in _JSONDecoder.
-                self  = try singleValueContainer.decode(Decimal.self)
-                return
-            }
-        } catch { /* Fall back to default implementation below. */ }
-
         let container = try decoder.container(keyedBy: CodingKeys.self)
         let exponent = try container.decode(CInt.self, forKey: .exponent)
         let length = try container.decode(CUnsignedInt.self, forKey: .length)
@@ -509,15 +498,6 @@
     }
 
     public func encode(to encoder: Encoder) throws {
-        // FIXME: This is a hook for bypassing a conditional conformance implementation to apply a strategy (see SR-5206). Remove this once conditional conformance is available.
-        // We are allowed to request this container as long as we don't encode anything through it when we need the keyed container below.
-        var singleValueContainer = encoder.singleValueContainer()
-        if singleValueContainer is _JSONEncoder {
-            // _JSONEncoder has a hook for Decimals; this won't recurse since we're not going to defer to Decimal in _JSONEncoder.
-            try singleValueContainer.encode(self)
-            return
-        }
-
         var container = encoder.container(keyedBy: CodingKeys.self)
         try container.encode(_exponent, forKey: .exponent)
         try container.encode(_length, forKey: .length)
diff --git a/stdlib/public/SDK/Foundation/JSONEncoder.swift b/stdlib/public/SDK/Foundation/JSONEncoder.swift
index 825735d..8b10376 100644
--- a/stdlib/public/SDK/Foundation/JSONEncoder.swift
+++ b/stdlib/public/SDK/Foundation/JSONEncoder.swift
@@ -99,7 +99,7 @@
     open var userInfo: [CodingUserInfoKey : Any] = [:]
 
     /// Options set on the top-level encoder to pass down the encoding hierarchy.
-    internal struct _Options {
+    fileprivate struct _Options {
         let dateEncodingStrategy: DateEncodingStrategy
         let dataEncodingStrategy: DataEncodingStrategy
         let nonConformingFloatEncodingStrategy: NonConformingFloatEncodingStrategy
@@ -155,14 +155,14 @@
 
 // MARK: - _JSONEncoder
 
-internal class _JSONEncoder : Encoder {
+fileprivate class _JSONEncoder : Encoder {
     // MARK: Properties
 
     /// The encoder's storage.
     fileprivate var storage: _JSONEncodingStorage
 
     /// Options set on the top-level encoder.
-    internal let options: JSONEncoder._Options
+    fileprivate let options: JSONEncoder._Options
 
     /// The path to the current point in encoding.
     public var codingPath: [CodingKey]
@@ -827,7 +827,7 @@
     open var userInfo: [CodingUserInfoKey : Any] = [:]
 
     /// Options set on the top-level encoder to pass down the decoding hierarchy.
-    internal struct _Options {
+    fileprivate struct _Options {
         let dateDecodingStrategy: DateDecodingStrategy
         let dataDecodingStrategy: DataDecodingStrategy
         let nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy
@@ -871,14 +871,14 @@
 
 // MARK: - _JSONDecoder
 
-internal class _JSONDecoder : Decoder {
+fileprivate class _JSONDecoder : Decoder {
     // MARK: Properties
 
     /// The decoder's storage.
     fileprivate var storage: _JSONDecodingStorage
 
     /// Options set on the top-level decoder.
-    internal let options: JSONDecoder._Options
+    fileprivate let options: JSONDecoder._Options
 
     /// The path to the current point in encoding.
     fileprivate(set) public var codingPath: [CodingKey]
diff --git a/stdlib/public/SDK/Foundation/NSStringAPI.swift b/stdlib/public/SDK/Foundation/NSStringAPI.swift
index c23bdbd..5746850 100644
--- a/stdlib/public/SDK/Foundation/NSStringAPI.swift
+++ b/stdlib/public/SDK/Foundation/NSStringAPI.swift
@@ -30,12 +30,6 @@
   return result
 }
 
-func _toNSRange(_ r: Range<String.Index>) -> NSRange {
-  return NSRange(
-    location: r.lowerBound.encodedOffset,
-    length: r.upperBound.encodedOffset - r.lowerBound.encodedOffset)
-}
-
 // We only need this for UnsafeMutablePointer, but there's not currently a way
 // to write that constraint.
 extension Optional {
@@ -417,10 +411,26 @@
     return self._ephemeralString as NSString
   }
 
+  // self can be a Substring so we need to subtract/add this offset when
+  // passing _ns to the Foundation APIs. Will be 0 if self is String.
+  @_inlineable
+  @_versioned
+  internal var _substringOffset: Int {
+    return self.startIndex.encodedOffset
+  }
+
   /// Return an `Index` corresponding to the given offset in our UTF-16
   /// representation.
   func _index(_ utf16Index: Int) -> Index {
-    return Index(encodedOffset: utf16Index)
+    return Index(encodedOffset: utf16Index + _substringOffset)
+  }
+
+  @_inlineable
+  @_versioned
+  internal func _toRelativeNSRange(_ r: Range<String.Index>) -> NSRange {
+    return NSRange(
+      location: r.lowerBound.encodedOffset - _substringOffset,
+      length: r.upperBound.encodedOffset - r.lowerBound.encodedOffset)
   }
 
   /// Return a `Range<Index>` corresponding to the given `NSRange` of
@@ -581,7 +591,7 @@
     return locale != nil ? _ns.compare(
       aString,
       options: mask,
-      range: _toNSRange(
+      range: _toRelativeNSRange(
         range ?? startIndex..<endIndex
       ),
       locale: locale
@@ -590,7 +600,7 @@
     : range != nil ? _ns.compare(
       aString,
       options: mask,
-      range: _toNSRange(range!)
+      range: _toRelativeNSRange(range!)
     )
 
     : !mask.isEmpty ? _ns.compare(aString, options: mask)
@@ -1008,7 +1018,7 @@
     T : StringProtocol, R : RangeExpression
   >(in range: R, with replacement: T) -> String where R.Bound == Index {
     return _ns.replacingCharacters(
-      in: _toNSRange(range.relative(to: self)),
+      in: _toRelativeNSRange(range.relative(to: self)),
       with: replacement._ephemeralString)
   }
 
@@ -1041,7 +1051,7 @@
       of: target,
       with: replacement,
       options: options,
-      range: _toNSRange(
+      range: _toRelativeNSRange(
         searchRange ?? startIndex..<endIndex
       )
     )
@@ -1163,7 +1173,7 @@
   ) where R.Bound == Index {
     let range = range.relative(to: self)
     _ns.enumerateLinguisticTags(
-      in: _toNSRange(range),
+      in: _toRelativeNSRange(range),
       scheme: tagScheme._ephemeralString,
       options: opts,
       orthography: orthography != nil ? orthography! : nil
@@ -1227,7 +1237,7 @@
     ) -> Void
   ) where R.Bound == Index {
     _ns.enumerateSubstrings(
-      in: _toNSRange(range.relative(to: self)), options: opts) {
+      in: _toRelativeNSRange(range.relative(to: self)), options: opts) {
       var stop_ = false
 
       body($0,
@@ -1300,7 +1310,7 @@
         usedLength: usedBufferCount,
         encoding: encoding.rawValue,
         options: options,
-        range: _toNSRange(range.relative(to: self)),
+        range: _toRelativeNSRange(range.relative(to: self)),
         remaining: $0)
     }
   }
@@ -1327,7 +1337,7 @@
           contentsEnd in self._ns.getLineStart(
             start, end: end,
             contentsEnd: contentsEnd,
-            for: _toNSRange(range.relative(to: self)))
+            for: _toRelativeNSRange(range.relative(to: self)))
         }
       }
     }
@@ -1355,7 +1365,7 @@
           contentsEnd in self._ns.getParagraphStart(
             start, end: end,
             contentsEnd: contentsEnd,
-            for: _toNSRange(range.relative(to: self)))
+            for: _toRelativeNSRange(range.relative(to: self)))
         }
       }
     }
@@ -1382,7 +1392,8 @@
   public func lineRange<
     R : RangeExpression
   >(for aRange: R) -> Range<Index> where R.Bound == Index {
-    return _range(_ns.lineRange(for: _toNSRange(aRange.relative(to: self))))
+    return _range(_ns.lineRange(
+      for: _toRelativeNSRange(aRange.relative(to: self))))
   }
 
   // - (NSArray *)
@@ -1406,7 +1417,7 @@
     var nsTokenRanges: NSArray?
     let result = tokenRanges._withNilOrAddress(of: &nsTokenRanges) {
       self._ns.linguisticTags(
-        in: _toNSRange(range.relative(to: self)),
+        in: _toRelativeNSRange(range.relative(to: self)),
         scheme: tagScheme._ephemeralString,
         options: opts,
         orthography: orthography,
@@ -1430,7 +1441,7 @@
     R : RangeExpression
   >(for aRange: R) -> Range<Index> where R.Bound == Index {
     return _range(
-      _ns.paragraphRange(for: _toNSRange(aRange.relative(to: self))))
+      _ns.paragraphRange(for: _toRelativeNSRange(aRange.relative(to: self))))
   }
 
   // - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet
@@ -1456,7 +1467,7 @@
       _ns.rangeOfCharacter(
         from: aSet,
         options: mask,
-        range: _toNSRange(
+        range: _toRelativeNSRange(
           aRange ?? startIndex..<endIndex
         )
       )
@@ -1487,7 +1498,7 @@
     // and output ranges due (if nothing else) to locale changes
     return _range(
       _ns.rangeOfComposedCharacterSequences(
-        for: _toNSRange(range.relative(to: self))))
+        for: _toRelativeNSRange(range.relative(to: self))))
   }
 
   // - (NSRange)rangeOfString:(NSString *)aString
@@ -1522,13 +1533,13 @@
       locale != nil ? _ns.range(
         of: aString,
         options: mask,
-        range: _toNSRange(
+        range: _toRelativeNSRange(
           searchRange ?? startIndex..<endIndex
         ),
         locale: locale
       )
       : searchRange != nil ? _ns.range(
-        of: aString, options: mask, range: _toNSRange(searchRange!)
+        of: aString, options: mask, range: _toRelativeNSRange(searchRange!)
       )
       : !mask.isEmpty ? _ns.range(of: aString, options: mask)
       : _ns.range(of: aString)
@@ -1637,7 +1648,7 @@
   @available(swift, deprecated: 4.0,
     message: "Please use String slicing subscript.")
   public func substring(with aRange: Range<Index>) -> String {
-    return _ns.substring(with: _toNSRange(aRange))
+    return _ns.substring(with: _toRelativeNSRange(aRange))
   }
 }
 
diff --git a/stdlib/public/SDK/Foundation/URL.swift b/stdlib/public/SDK/Foundation/URL.swift
index 262efa7..3799dba 100644
--- a/stdlib/public/SDK/Foundation/URL.swift
+++ b/stdlib/public/SDK/Foundation/URL.swift
@@ -1214,17 +1214,6 @@
     }
 
     public init(from decoder: Decoder) throws {
-        // FIXME: This is a hook for bypassing a conditional conformance implementation to apply a strategy (see SR-5206). Remove this once conditional conformance is available.
-        do {
-            // We are allowed to request this container as long as we don't decode anything through it when we need the keyed container below.
-            let singleValueContainer = try decoder.singleValueContainer()
-            if singleValueContainer is _JSONDecoder {
-                // _JSONDecoder has a hook for URLs; this won't recurse since we're not going to defer back to URL in _JSONDecoder.
-                self = try singleValueContainer.decode(URL.self)
-                return
-            }
-        } catch { /* Fall back to default implementation below. */ }
-
         let container = try decoder.container(keyedBy: CodingKeys.self)
         let relative = try container.decode(String.self, forKey: .relative)
         let base = try container.decodeIfPresent(URL.self, forKey: .base)
@@ -1238,15 +1227,6 @@
     }
 
     public func encode(to encoder: Encoder) throws {
-        // FIXME: This is a hook for bypassing a conditional conformance implementation to apply a strategy (see SR-5206). Remove this once conditional conformance is available.
-        // We are allowed to request this container as long as we don't encode anything through it when we need the keyed container below.
-        var singleValueContainer = encoder.singleValueContainer()
-        if singleValueContainer is _JSONEncoder {
-            // _JSONEncoder has a hook for URLs; this won't recurse since we're not going to defer back to URL in _JSONEncoder.
-            try singleValueContainer.encode(self)
-            return
-        }
-
         var container = encoder.container(keyedBy: CodingKeys.self)
         try container.encode(self.relativeString, forKey: .relative)
         if let base = self.baseURL {
diff --git a/stdlib/public/core/Codable.swift b/stdlib/public/core/Codable.swift
index e8cb748..6ba72e4 100644
--- a/stdlib/public/core/Codable.swift
+++ b/stdlib/public/core/Codable.swift
@@ -3974,6 +3974,34 @@
     }
 }
 
+// Temporary resolution for SR-5206.
+// 
+// The following two extension on Encodable and Decodable are used below to provide static type information where we don't have any yet.
+// The wrapped contents of the below generic types have to expose their Encodable/Decodable conformance via an existential cast/their metatype.
+// Since those are dynamic types without static type guarantees, we cannot call generic methods taking those arguments, e.g.
+// 
+//   try container.encode((someElement as! Encodable))
+// 
+// One way around this is to get elements to encode into `superEncoder`s and decode from `superDecoder`s because those interfaces are available via the existentials/metatypes.
+// However, this direct encoding/decoding never gives containers a chance to intercept and do something custom on types.
+// 
+// If we instead expose this custom private functionality of writing to/reading from containers directly, the containers do get this chance.
+
+// FIXME: Remove when conditional conformance is available.
+extension Encodable {
+    fileprivate func __encode(to container: inout SingleValueEncodingContainer) throws { try container.encode(self) }
+    fileprivate func __encode(to container: inout UnkeyedEncodingContainer)     throws { try container.encode(self) }
+    fileprivate func __encode<Key>(to container: inout KeyedEncodingContainer<Key>, forKey key: Key) throws { try container.encode(self, forKey: key) }
+}
+
+// FIXME: Remove when conditional conformance is available.
+extension Decodable {
+    // Since we cannot call these __init, we'll give the parameter a '__'.
+    fileprivate init(__from container: SingleValueDecodingContainer)   throws { self = try container.decode(Self.self) }
+    fileprivate init(__from container: inout UnkeyedDecodingContainer) throws { self = try container.decode(Self.self) }
+    fileprivate init<Key>(__from container: KeyedDecodingContainer<Key>, forKey key: Key) throws { self = try container.decode(Self.self, forKey: key) }
+}
+
 // FIXME: Uncomment when conditional conformance is available.
 extension Optional : Encodable /* where Wrapped : Encodable */ {
     public func encode(to encoder: Encoder) throws {
@@ -3982,7 +4010,7 @@
         var container = encoder.singleValueContainer()
         switch self {
         case .none: try container.encodeNil()
-        case .some(let wrapped): try (wrapped as! Encodable).encode(to: encoder)
+        case .some(let wrapped): try (wrapped as! Encodable).__encode(to: &container)
         }
     }
 }
@@ -3996,7 +4024,7 @@
         let container = try decoder.singleValueContainer()
         if !container.decodeNil() {
             let metaType = (Wrapped.self as! Decodable.Type)
-            let element = try metaType.init(from: decoder)
+            let element = try metaType.init(__from: container)
             self = .some(element as! Wrapped)
         }
     }
@@ -4009,10 +4037,7 @@
 
         var container = encoder.unkeyedContainer()
         for element in self {
-            // superEncoder appends an empty element and wraps an Encoder around it.
-            // This is normally appropriate for encoding super, but this is really what we want to do.
-            let subencoder = container.superEncoder()
-            try (element as! Encodable).encode(to: subencoder)
+            try (element as! Encodable).__encode(to: &container)
         }
     }
 }
@@ -4026,10 +4051,7 @@
         let metaType = (Element.self as! Decodable.Type)
         var container = try decoder.unkeyedContainer()
         while !container.isAtEnd {
-            // superDecoder fetches the next element as a container and wraps a Decoder around it.
-            // This is normally appropriate for decoding super, but this is really what we want to do.
-            let subdecoder = try container.superDecoder()
-            let element = try metaType.init(from: subdecoder)
+            let element = try metaType.init(__from: &container)
             self.append(element as! Element)
         }
     }
@@ -4041,10 +4063,7 @@
 
         var container = encoder.unkeyedContainer()
         for element in self {
-            // superEncoder appends an empty element and wraps an Encoder around it.
-            // This is normally appropriate for encoding super, but this is really what we want to do.
-            let subencoder = container.superEncoder()
-            try (element as! Encodable).encode(to: subencoder)
+            try (element as! Encodable).__encode(to: &container)
         }
     }
 }
@@ -4058,10 +4077,7 @@
         let metaType = (Element.self as! Decodable.Type)
         var container = try decoder.unkeyedContainer()
         while !container.isAtEnd {
-            // superDecoder fetches the next element as a container and wraps a Decoder around it.
-            // This is normally appropriate for decoding super, but this is really what we want to do.
-            let subdecoder = try container.superDecoder()
-            let element = try metaType.init(from: subdecoder)
+            let element = try metaType.init(__from: &container)
             self.insert(element as! Element)
         }
     }
@@ -4093,29 +4109,22 @@
             var container = encoder.container(keyedBy: _DictionaryCodingKey.self)
             for (key, value) in self {
                 let codingKey = _DictionaryCodingKey(stringValue: key as! String)!
-                let valueEncoder = container.superEncoder(forKey: codingKey)
-                try (value as! Encodable).encode(to: valueEncoder)
+                try (value as! Encodable).__encode(to: &container, forKey: codingKey)
             }
         } else if Key.self == Int.self {
             // Since the keys are already Ints, we can use them as keys directly.
             var container = encoder.container(keyedBy: _DictionaryCodingKey.self)
             for (key, value) in self {
                 let codingKey = _DictionaryCodingKey(intValue: key as! Int)!
-                let valueEncoder = container.superEncoder(forKey: codingKey)
-                try (value as! Encodable).encode(to: valueEncoder)
+                try (value as! Encodable).__encode(to: &container, forKey: codingKey)
             }
         } else {
             // Keys are Encodable but not Strings or Ints, so we cannot arbitrarily convert to keys.
             // We can encode as an array of alternating key-value pairs, though.
             var container = encoder.unkeyedContainer()
             for (key, value) in self {
-                // superEncoder appends an empty element and wraps an Encoder around it.
-                // This is normally appropriate for encoding super, but this is really what we want to do.
-                let keyEncoder = container.superEncoder()
-                try (key as! Encodable).encode(to: keyEncoder)
-
-                let valueEncoder = container.superEncoder()
-                try (value as! Encodable).encode(to: valueEncoder)
+                try (key as! Encodable).__encode(to: &container)
+                try (value as! Encodable).__encode(to: &container)
             }
         }
     }
@@ -4133,8 +4142,7 @@
             let container = try decoder.container(keyedBy: _DictionaryCodingKey.self)
             let valueMetaType = Value.self as! Decodable.Type
             for key in container.allKeys {
-                let valueDecoder = try container.superDecoder(forKey: key)
-                let value = try valueMetaType.init(from: valueDecoder)
+                let value = try valueMetaType.init(__from: container, forKey: key)
                 self[key.stringValue as! Key] = (value as! Value)
             }
         } else if Key.self == Int.self {
@@ -4153,8 +4161,7 @@
                                                                            debugDescription: "Expected Int key but found String key instead."))
                 }
 
-                let valueDecoder = try container.superDecoder(forKey: key)
-                let value = try valueMetaType.init(from: valueDecoder)
+                let value = try valueMetaType.init(__from: container, forKey: key)
                 self[key.intValue! as! Key] = (value as! Value)
             }
         } else {
@@ -4172,19 +4179,14 @@
             let keyMetaType = (Key.self as! Decodable.Type)
             let valueMetaType = (Value.self as! Decodable.Type)
             while !container.isAtEnd {
-                // superDecoder fetches the next element as a container and wraps a Decoder around it.
-                // This is normally appropriate for decoding super, but this is really what we want to do.
-                let keyDecoder = try container.superDecoder()
-                let key = try keyMetaType.init(from: keyDecoder)
+                let key = try keyMetaType.init(__from: &container)
 
                 guard !container.isAtEnd else {
                     throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath,
                                                                                  debugDescription: "Unkeyed container reached end before value in key-value pair."))
                 }
 
-                let valueDecoder = try container.superDecoder()
-                let value = try valueMetaType.init(from: valueDecoder)
-
+                let value = try valueMetaType.init(__from: &container)
                 self[key as! Key] = (value as! Value)
             }
         }
diff --git a/stdlib/public/stubs/CMakeLists.txt b/stdlib/public/stubs/CMakeLists.txt
index 2013824..e041b4c 100644
--- a/stdlib/public/stubs/CMakeLists.txt
+++ b/stdlib/public/stubs/CMakeLists.txt
@@ -11,6 +11,7 @@
     FoundationHelpers.mm
     OptionalBridgingHelper.mm
     Reflection.mm
+    SwiftNativeNSXXXBaseARC.m
     SwiftNativeNSXXXBase.mm.gyb)
 set(swift_stubs_unicode_normalization_sources
     UnicodeNormalization.cpp)
@@ -41,3 +42,7 @@
   LINK_FLAGS ${SWIFT_RUNTIME_CORE_LINK_FLAGS}
   INSTALL_IN_COMPONENT stdlib)
 
+if(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
+  set_property(SOURCE SwiftNativeNSXXXBaseARC.m APPEND_STRING PROPERTY COMPILE_FLAGS
+    "-fobjc-arc")
+endif()
diff --git a/stdlib/public/stubs/SwiftNativeNSXXXBase.mm.gyb b/stdlib/public/stubs/SwiftNativeNSXXXBase.mm.gyb
index d0c2675..eb061bc 100644
--- a/stdlib/public/stubs/SwiftNativeNSXXXBase.mm.gyb
+++ b/stdlib/public/stubs/SwiftNativeNSXXXBase.mm.gyb
@@ -140,25 +140,6 @@
 }
 
 SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE
-size_t
-swift_stdlib_NSStringHashValue(NSString *NS_RELEASES_ARGUMENT str,
-                               bool isASCII) {
-  size_t Result =
-      isASCII ? str.hash : str.decomposedStringWithCanonicalMapping.hash;
-
-  swift_unknownRelease(str);
-  return Result;
-}
-
-SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE
-size_t
-swift_stdlib_NSStringHashValuePointer(void *opaque, bool isASCII) {
-  NSString *str = (NSString *)opaque;
-  return isASCII ? str.hash : str.decomposedStringWithCanonicalMapping.hash;
-}
-
-
-SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE
 bool swift_stdlib_NSStringHasPrefixNFD(NSString *theString,
                                        NSString *prefix) {
   auto Length = CFStringGetLength((__bridge CFStringRef)theString);
@@ -208,22 +189,6 @@
 }
 
 SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE
-NS_RETURNS_RETAINED NSString *
-swift_stdlib_NSStringLowercaseString(NSString *NS_RELEASES_ARGUMENT str) {
-  NSString *Result = objc_retain(str.lowercaseString);
-  swift_unknownRelease(str);
-  return Result;
-}
-
-SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE
-NS_RETURNS_RETAINED NSString *
-swift_stdlib_NSStringUppercaseString(NSString *NS_RELEASES_ARGUMENT str) {
-  NSString *Result = objc_retain(str.uppercaseString);
-  swift_unknownRelease(str);
-  return Result;
-}
-
-SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE
 void swift_stdlib_CFSetGetValues(NSSet *NS_RELEASES_ARGUMENT set,
                                             const void **values) {
   CFSetGetValues((__bridge CFSetRef)set, values);
diff --git a/stdlib/public/stubs/SwiftNativeNSXXXBaseARC.m b/stdlib/public/stubs/SwiftNativeNSXXXBaseARC.m
new file mode 100644
index 0000000..28ec1b8
--- /dev/null
+++ b/stdlib/public/stubs/SwiftNativeNSXXXBaseARC.m
@@ -0,0 +1,75 @@
+//===--- SwiftNativeNSXXXBaseARC.mm - Runtime stubs that require ARC ------===//
+//
+// This source file is part of the Swift.org open source project
+//
+// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See https://swift.org/LICENSE.txt for license information
+// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
+//
+//===----------------------------------------------------------------------===//
+#include "swift/Runtime/Config.h"
+
+#if SWIFT_OBJC_INTEROP
+
+#import <Foundation/Foundation.h>
+#import <CoreFoundation/CoreFoundation.h>
+#include <objc/NSObject.h>
+#include <objc/runtime.h>
+#include <objc/objc.h>
+
+// The following two routines need to be implemented in ARC because
+// decomposedStringWithCanonicalMapping returns its result autoreleased. And we
+// want ARC to insert 'objc_retainAutoreleasedReturnValue' and the necessary
+// markers for the hand-off to facilitate the remove from autorelease pool
+// optimization such that the object is not handed into the current autorelease
+// pool which might be scoped such that repeatedly placing objects into it
+// results in unbounded memory growth.
+
+// On i386 the remove from autorelease pool optimization is foiled by the
+// decomposedStringWithCanonicalMapping implementation. Instead, we use a local
+// autorelease pool to prevent leaking of the temporary object into the callers
+// autorelease pool.
+#if defined(__i386__)
+#define AUTORELEASEPOOL @autoreleasepool
+#else
+// On other platforms we rely on the remove from autorelease pool optimization.
+#define AUTORELEASEPOOL
+#endif
+
+SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE
+size_t swift_stdlib_NSStringHashValue(NSString *NS_RELEASES_ARGUMENT str,
+                                      bool isASCII) {
+  AUTORELEASEPOOL {
+    return isASCII ? str.hash : str.decomposedStringWithCanonicalMapping.hash;
+  }
+}
+
+SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE
+size_t
+swift_stdlib_NSStringHashValuePointer(void *opaque, bool isASCII) {
+  NSString __unsafe_unretained *str =
+      (__bridge NSString __unsafe_unretained *)opaque;
+  AUTORELEASEPOOL {
+    return isASCII ? str.hash : str.decomposedStringWithCanonicalMapping.hash;
+  }
+}
+
+SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE
+NS_RETURNS_RETAINED NSString *
+swift_stdlib_NSStringLowercaseString(NSString *NS_RELEASES_ARGUMENT str) {
+  AUTORELEASEPOOL {
+    return str.lowercaseString;
+  }
+}
+
+SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE
+NS_RETURNS_RETAINED NSString *
+swift_stdlib_NSStringUppercaseString(NSString *NS_RELEASES_ARGUMENT str) {
+  AUTORELEASEPOOL {
+    return str.uppercaseString;
+  }
+}
+
+#endif
diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt
index 3828ea3..7653938 100644
--- a/test/CMakeLists.txt
+++ b/test/CMakeLists.txt
@@ -46,7 +46,7 @@
       swift-api-digester)
   if(NOT SWIFT_BUILT_STANDALONE)
     list(APPEND deps_binaries FileCheck arcmt-test c-arcmt-test c-index-test
-         clang llc llvm-cov llvm-dwarfdump llvm-link llvm-profdata not)
+         clang llc llvm-cov llvm-dwarfdump llvm-link llvm-dis llvm-profdata not)
   endif()
   if(SWIFT_BUILD_SOURCEKIT)
     list(APPEND deps_binaries sourcekitd-test complete-test)
diff --git a/test/IDE/complete_value_literals.swift b/test/IDE/complete_value_literals.swift
index 6f02d3e..d4363ea 100644
--- a/test/IDE/complete_value_literals.swift
+++ b/test/IDE/complete_value_literals.swift
@@ -14,6 +14,9 @@
 // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=STRING_0 | %FileCheck %s -check-prefix=STRING_0
 // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=STRING_1 | %FileCheck %s -check-prefix=STRING_1
 // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=STRING_2 | %FileCheck %s -check-prefix=STRING_2
+// RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=STRING_3 | %FileCheck %s -check-prefix=STRING_3
+// RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=STRING_4 | %FileCheck %s -check-prefix=STRING_4
+// RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=STRING_5 | %FileCheck %s -check-prefix=STRING_5
 // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=ARRAY_0 | %FileCheck %s -check-prefix=ARRAY_0
 // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=ARRAY_1 | %FileCheck %s -check-prefix=ARRAY_1
 // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=ARRAY_2 | %FileCheck %s -check-prefix=ARRAY_2
@@ -62,6 +65,13 @@
   init(extendedGraphemeClusterLiteral value: String) {}
   init(stringLiteral value: String) {}
 }
+struct MyUnicodeScalar1: ExpressibleByUnicodeScalarLiteral {
+  init(unicodeScalarLiteral value: Character) {}
+}
+struct MyCharacter1: ExpressibleByExtendedGraphemeClusterLiteral {
+  init(unicodeScalarLiteral value: Character) {}
+  init(extendedGraphemeClusterLiteral value: String) {}
+}
 struct MyArray1<Element>: ExpressibleByArrayLiteral {
   init(arrayLiteral value: Element...) {}
 }
@@ -154,6 +164,19 @@
 }
 // STRING_2: Literal[String]/None/TypeRelation[Identical]: "{#(abc)#}"[#String#];
 
+func testString3() {
+  let x: MyUnicodeScalar1 = #^STRING_3^#
+}
+// STRING_3: Literal[String]/None/TypeRelation[Identical]: "{#(abc)#}"[#MyUnicodeScalar1#];
+func testString4() {
+  let x: MyCharacter1 = #^STRING_4^#
+}
+// STRING_4: Literal[String]/None/TypeRelation[Identical]: "{#(abc)#}"[#MyCharacter1#];
+func testString5() {
+  let x: Character = #^STRING_5^#
+}
+// STRING_5: Literal[String]/None/TypeRelation[Identical]: "{#(abc)#}"[#Character#];
+
 func testArray0() {
   let x: Int = #^ARRAY_0^#
 }
diff --git a/test/IRGen/Inputs/StaticInline.h b/test/IRGen/Inputs/StaticInline.h
index 165f5b3..d0a8bbb 100644
--- a/test/IRGen/Inputs/StaticInline.h
+++ b/test/IRGen/Inputs/StaticInline.h
@@ -3,3 +3,18 @@
 static inline NSString *staticInlineFun() {
   return [[NSLocale currentLocale] localeIdentifier];
 }
+
+static inline __attribute__((ns_returns_retained))
+NSURL *_Nullable test(NSFileManager *self_, NSURL *originalItemURL,
+                      NSURL *newItemURL, NSString *_Nullable backupItemName,
+                      NSFileManagerItemReplacementOptions options,
+                      NSError **_Nullable error) {
+  NSURL *result = nil;
+  BOOL success = [self_ replaceItemAtURL:originalItemURL
+                           withItemAtURL:newItemURL
+                          backupItemName:backupItemName
+                                 options:options
+                        resultingItemURL:&result
+                                   error:error];
+  return success ? result : nil;
+}
diff --git a/test/IRGen/Inputs/usr/include/Gizmo.h b/test/IRGen/Inputs/usr/include/Gizmo.h
index c9cf43e..0ffced5 100644
--- a/test/IRGen/Inputs/usr/include/Gizmo.h
+++ b/test/IRGen/Inputs/usr/include/Gizmo.h
@@ -137,3 +137,10 @@
 };
 
 struct StructOfNSStrings useStructOfNSStringsInObjC(struct StructOfNSStrings);
+
+@interface OuterType : NSObject
+@end
+
+__attribute__((swift_name("OuterType.InnerType")))
+@interface OuterTypeInnerType : NSObject
+@end
diff --git a/test/IRGen/existentials_objc.sil b/test/IRGen/existentials_objc.sil
index d84dfb3..af2787f 100644
--- a/test/IRGen/existentials_objc.sil
+++ b/test/IRGen/existentials_objc.sil
@@ -179,3 +179,35 @@
 
   return undef : $()
 }
+
+@objc protocol ProtocolA : class {
+ @objc optional func funcA()
+}
+
+// CHECK: define swiftcc void @useObjcProtocol(%objc_object* swiftself)
+// CHECK: entry:
+// CHECK:   load i8*, i8** @"\01L_selector(funcA)"
+// CHECK:   load i8*, i8** @"\01L_selector(respondsToSelector:)"
+// CHECK:   [[TMP:%.*]] = call i1 bitcast (void ()* @objc_msgSend
+// CHECK:   br i1 [[TMP]]
+//
+// CHECK:   [[SELF:%.*]] = bitcast %objc_object* %0 to i8*
+// CHECK:   call void bitcast (void ()* @objc_msgSend to void (i8*, i8*)*)(i8* [[SELF]]
+// CHECK:   ret void
+// CHECK: }
+
+sil public @useObjcProtocol : $@convention(method) (@guaranteed ProtocolA) -> () {
+bb0(%0 : $ProtocolA):
+  dynamic_method_br %0 : $ProtocolA, #ProtocolA.funcA!1.foreign, bb1, bb2
+
+bb1(%1 : $@convention(objc_method) (ProtocolA) -> ()):
+  %3 = apply %1(%0) : $@convention(objc_method) (ProtocolA) -> ()
+  br bb3
+
+bb2:
+ br bb3
+
+bb3:
+ %4 = tuple()
+ return %4 : $()
+}
diff --git a/test/IRGen/objc_arc_contract.swift b/test/IRGen/objc_arc_contract.swift
new file mode 100644
index 0000000..6d70f88
--- /dev/null
+++ b/test/IRGen/objc_arc_contract.swift
@@ -0,0 +1,28 @@
+// Make sure that we run objc arc contract when emitting ir or bc with optimization enabled.
+
+// RUN: %empty-directory(%t)
+
+// RUN: %target-swift-frontend -import-objc-header %S/Inputs/StaticInline.h %s -emit-ir -Xllvm -disable-objc-arc-contract -parse-as-library -O | %FileCheck --check-prefix=CHECK-WITHOUT-PASS %s
+// RUN: %target-swift-frontend -import-objc-header %S/Inputs/StaticInline.h %s -emit-bc -Xllvm -disable-objc-arc-contract -parse-as-library -O -o %t/test1.bc && %llvm-dis -o - %t/test1.bc | %FileCheck --check-prefix=CHECK-WITHOUT-PASS %s
+
+// RUN: %target-swift-frontend -import-objc-header %S/Inputs/StaticInline.h %s -emit-ir -parse-as-library -O | %FileCheck --check-prefix=CHECK-WITH-PASS %s
+// RUN: %target-swift-frontend -import-objc-header %S/Inputs/StaticInline.h %s -emit-bc -parse-as-library -O -o %t/test2.bc && %llvm-dis -o - %t/test2.bc | %FileCheck --check-prefix=CHECK-WITH-PASS %s
+
+
+// REQUIRES: objc_interop
+// REQUIRES: asserts
+
+// CHECK-WITHOUT-PASS: call void (...) @clang.arc.use
+// CHECK-WITH-PASS-NOT: call void (...) @clang.arc.use
+
+import Foundation
+
+@inline(never)
+public func foo() throws {
+  let x: FileManager! = nil
+  let y = URL(string: "http://swift.org")
+  let z: URL! = nil
+  let w: String = "foo"
+  var e: NSError? = nil
+  test(x, y, z, w, .usingNewMetadataOnly, &e)
+}
diff --git a/test/IRGen/objc_types_as_members.sil b/test/IRGen/objc_types_as_members.sil
new file mode 100644
index 0000000..83a04e1
--- /dev/null
+++ b/test/IRGen/objc_types_as_members.sil
@@ -0,0 +1,27 @@
+// RUN: rm -rf %t && mkdir -p %t
+// RUN: %build-irgen-test-overlays
+// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) %s -emit-ir | %FileCheck %s
+
+// REQUIRES: objc_interop
+
+import gizmo
+
+sil @use_metatype : $@convention(thin) <T> (@thin T.Type) -> ()
+
+// CHECK-LABEL: define swiftcc void @test(%TSo9InnerTypeC* swiftself, %swift.type* %Self, i8** %SelfWitnessTable)
+// CHECK:   [[TMP:%.*]] = call %swift.type* @_T0So9OuterTypeCMa()
+// CHECK:   call swiftcc void @use_metatype(%swift.type* [[TMP]])
+// CHECK:   ret void
+
+sil @test : $@convention(witness_method) (@guaranteed OuterType.InnerType) -> () {
+bb0(%0 : $OuterType.InnerType):
+  %1 = function_ref @use_metatype : $@convention(thin) <τ_0_0> (@thin τ_0_0.Type) -> ()
+  %2 = metatype $@thin OuterType.Type
+  %3 = apply %1<OuterType>(%2) : $@convention(thin) <τ_0_0> (@thin τ_0_0.Type) -> ()
+  return %3 : $()
+}
+
+// CHECK-LABEL: define {{.*}}%swift.type* @_T0So9OuterTypeCMa()
+// CHECK:  [[TMP:%.*]] = call %objc_class* @swift_rt_swift_getInitializedObjCClass(
+// CHECK:  call %swift.type* @swift_getObjCClassMetadata(%objc_class* [[TMP]])
+// CHECK:  ret
diff --git a/test/Interpreter/Inputs/ObjCClasses/ObjCClasses.h b/test/Interpreter/Inputs/ObjCClasses/ObjCClasses.h
index 324ef03..d4d08c0 100644
--- a/test/Interpreter/Inputs/ObjCClasses/ObjCClasses.h
+++ b/test/Interpreter/Inputs/ObjCClasses/ObjCClasses.h
@@ -109,6 +109,13 @@
 - (void) shouldBeTrueCBool: (_Bool)value;
 @end
 
+@interface OuterType : NSObject
+@end
+
+__attribute__((swift_name("OuterType.InnerType")))
+@interface OuterTypeInnerType : NSObject
+@property NSArray<OuterType *> *things;
+@end
 NS_ASSUME_NONNULL_END
 
 #endif
diff --git a/test/Interpreter/Inputs/ObjCClasses/ObjCClasses.m b/test/Interpreter/Inputs/ObjCClasses/ObjCClasses.m
index 49b1eae..8153b99 100644
--- a/test/Interpreter/Inputs/ObjCClasses/ObjCClasses.m
+++ b/test/Interpreter/Inputs/ObjCClasses/ObjCClasses.m
@@ -170,3 +170,22 @@
 }
 
 @end
+
+@implementation OuterType
+- (id)init {
+  if ((self = [super init]) != nil) {
+  }
+  return self;
+}
+@end
+
+@implementation OuterTypeInnerType
+
+- (id)init {
+  if ((self = [super init]) != nil) {
+    self.things = [NSArray array];
+  }
+  return self;
+}
+
+@end
diff --git a/test/Interpreter/objc_types_as_members.swift b/test/Interpreter/objc_types_as_members.swift
new file mode 100644
index 0000000..29f4eff
--- /dev/null
+++ b/test/Interpreter/objc_types_as_members.swift
@@ -0,0 +1,45 @@
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+//
+// RUN: %target-clang -fobjc-arc %S/Inputs/ObjCClasses/ObjCClasses.m -c -o %t/ObjCClasses.o
+// RUN: %target-build-swift -O -I %S/Inputs/ObjCClasses/ -Xlinker %t/ObjCClasses.o %s -o %t/a.out
+// RUN: %target-run %t/a.out
+
+// REQUIRES: executable_test
+// REQUIRES: objc_interop
+
+import ObjCClasses
+import Foundation
+
+protocol OuterProto:class {
+}
+
+protocol InnerProto : class {
+    var outerthings:[OuterProto] { get }
+}
+
+extension OuterType : OuterProto {
+}
+
+extension OuterType.InnerType: InnerProto {
+    var outerthings:[OuterProto] {
+        return self.things
+    }
+}
+
+var innerthing:InnerProto = OuterType.InnerType()
+
+@inline(never)
+func getInnerThing() -> InnerProto {
+  return innerthing
+}
+
+@inline(never)
+func dontCrash() {
+  let thing = getInnerThing()
+  let devices = thing.outerthings
+  print("Got devices: \(devices)")
+}
+
+// CHECK: Got devices: []
+dontCrash()
diff --git a/test/Misc/stats_dir_long_path_name.swift b/test/Misc/stats_dir_long_path_name.swift
new file mode 100644
index 0000000..c31f31b
--- /dev/null
+++ b/test/Misc/stats_dir_long_path_name.swift
@@ -0,0 +1,16 @@
+// REQUIRES: OS=macosx
+// RUN: rm -rf %t && mkdir -p %t
+// RUN: mkdir -p %t/very-long-directory-name-that-contains-over-128-characters-which-is-not-enough-to-be-illegal-on-its-own-but-presents
+// RUN: cp %s %t/very-long-directory-name-that-contains-over-128-characters-which-is-not-enough-to-be-illegal-on-its-own-but-presents/a-problem-when-combined-with-other-long-path-elements-and-filenames-to-exceed-256-characters-combined-because-yay-arbitrary-limits-amirite.swift
+// RUN: touch %t/main.swift
+// RUN: %target-swiftc_driver -o %t/main -module-name main -stats-output-dir %t %t/main.swift %t/very-long-directory-name-that-contains-over-128-characters-which-is-not-enough-to-be-illegal-on-its-own-but-presents/a-problem-when-combined-with-other-long-path-elements-and-filenames-to-exceed-256-characters-combined-because-yay-arbitrary-limits-amirite.swift
+// RUN: %utils/process-stats-dir.py --set-csv-baseline %t/frontend.csv %t
+// RUN: %FileCheck -input-file %t/frontend.csv %s
+
+// CHECK: {{"AST.NumSourceLines"	[1-9][0-9]*$}}
+// CHECK: {{"IRModule.NumIRFunctions"	[1-9][0-9]*$}}
+// CHECK: {{"LLVM.NumLLVMBytesOutput"	[1-9][0-9]*$}}
+
+public func foo() {
+    print("hello")
+}
diff --git a/test/Parse/ConditionalCompilation/language_version_explicit.swift b/test/Parse/ConditionalCompilation/language_version_explicit.swift
index 0edd698..5c8a782 100644
--- a/test/Parse/ConditionalCompilation/language_version_explicit.swift
+++ b/test/Parse/ConditionalCompilation/language_version_explicit.swift
@@ -21,7 +21,7 @@
   asdf asdf asdf asdf
 #endif
 
-#if swift(>=4.0.2)
+#if swift(>=4.0.3)
   // This shouldn't emit any diagnostics.
   asdf asdf asdf asdf
 #else
diff --git a/test/SILGen/keypaths.swift b/test/SILGen/keypaths.swift
index 5f425ad..7d28bd1 100644
--- a/test/SILGen/keypaths.swift
+++ b/test/SILGen/keypaths.swift
@@ -267,6 +267,13 @@
   _ = \IUOProperty.iuo!.x
 }
 
+class Bass: Hashable {
+  static func ==(_: Bass, _: Bass) -> Bool { return false }
+  var hashValue: Int { return 0 }
+}
+
+class Treble: Bass { }
+
 struct Subscripts<T> {
   subscript() -> T {
     get { fatalError() }
@@ -292,6 +299,10 @@
     get { fatalError() }
     set { fatalError() }
   }
+  subscript(bass: Bass) -> Bass {
+    get { return bass }
+    set { }
+  }
 }
 
 // CHECK-LABEL: sil hidden @{{.*}}10subscripts
@@ -321,4 +332,7 @@
   _ = \Subscripts<String>.[subGeneric: y]
 
   _ = \Subscripts<T>.[s, s].count
+
+  _ = \Subscripts<T>.[Bass()]
+  _ = \Subscripts<T>.[Treble()]
 }
diff --git a/test/SILOptimizer/sil_combine_apply.sil b/test/SILOptimizer/sil_combine_apply.sil
index cd09acd..b1bb933 100644
--- a/test/SILOptimizer/sil_combine_apply.sil
+++ b/test/SILOptimizer/sil_combine_apply.sil
@@ -343,3 +343,20 @@
   return %27 : $()
 }
 
+// CHECK-LABEL: sil @dont_replace_copied_self_in_mutating_method_call2
+sil @dont_replace_copied_self_in_mutating_method_call2 : $@convention(thin) (@thick MutatingProto.Type) -> (@out MutatingProto) {
+bb0(%0 : $*MutatingProto, %1 : $@thick MutatingProto.Type):
+  %alloc1 = alloc_stack $MutatingProto, let, name "p"
+  %openType = open_existential_metatype %1 : $@thick MutatingProto.Type to $@thick (@opened("66A6DAFC-AF78-11E7-8F3B-28CFE9213F4F") MutatingProto).Type
+  %initType =  init_existential_addr %alloc1 : $*MutatingProto, $@opened("66A6DAFC-AF78-11E7-8F3B-28CFE9213F4F") MutatingProto
+  %alloc2 = alloc_stack $MutatingProto
+  copy_addr %alloc1 to [initialization] %alloc2 : $*MutatingProto
+  %oeaddr = open_existential_addr mutable_access %alloc2 : $*MutatingProto to $*@opened("6E02DCF6-AF78-11E7-8F3B-28CFE9213F4F") MutatingProto
+  %witmethod = witness_method $@opened("66A6DAFC-AF78-11E7-8F3B-28CFE9213F4F") MutatingProto, #MutatingProto.mutatingMethod!1 : <Self where Self : MutatingProto> (inout Self) -> () -> (), %openType : $@thick (@opened("66A6DAFC-AF78-11E7-8F3B-28CFE9213F4F") MutatingProto).Type : $@convention(witness_method) <τ_0_0 where τ_0_0 : MutatingProto> (@inout τ_0_0) -> ()
+  // CHECK: apply {{%.*}}<@opened("6E02DCF6-AF78-11E7-8F3B-28CFE9213F4F") MutatingProto>({{%.*}}) : $@convention(witness_method) <τ_0_0 where τ_0_0 : MutatingProto> (@inout τ_0_0) -> () // type-defs
+  %apply = apply %witmethod<@opened("6E02DCF6-AF78-11E7-8F3B-28CFE9213F4F") MutatingProto>(%oeaddr) : $@convention(witness_method) <τ_0_0 where τ_0_0 : MutatingProto> (@inout τ_0_0) -> ()
+  dealloc_stack %alloc2 : $*MutatingProto
+  dealloc_stack %alloc1 : $*MutatingProto
+  %27 = tuple ()
+  return %27 : $()
+}
diff --git a/test/Serialization/Recovery/crash-recovery.swift b/test/Serialization/Recovery/crash-recovery.swift
index 6a17236..bd44c56 100644
--- a/test/Serialization/Recovery/crash-recovery.swift
+++ b/test/Serialization/Recovery/crash-recovery.swift
@@ -14,7 +14,7 @@
 
 // CHECK-CRASH: error: fatal error encountered while reading from module 'Lib'; please file a bug report with your project and the crash log
 // CHECK-CRASH-3-NOT: note
-// CHECK-CRASH-4: note: compiling as Swift 4.0.1, with 'Lib' built as Swift 3.2
+// CHECK-CRASH-4: note: compiling as Swift 4.0.2, with 'Lib' built as Swift 3.2
 // CHECK-CRASH-LABEL: *** DESERIALIZATION FAILURE (please include this section in any bug report) ***
 // CHECK-CRASH: could not find 'disappearingMethod()' in parent class
 // CHECK-CRASH: While loading members for 'Sub' in module 'Lib'
diff --git a/test/Serialization/Recovery/types-4-to-3.swift b/test/Serialization/Recovery/types-4-to-3.swift
index b78048e..4982204 100644
--- a/test/Serialization/Recovery/types-4-to-3.swift
+++ b/test/Serialization/Recovery/types-4-to-3.swift
@@ -16,8 +16,8 @@
 func requiresConformance(_: B_RequiresConformance<B_ConformsToProto>) {}
 func requiresConformance(_: B_RequiresConformance<C_RelyOnConformanceImpl.Assoc>) {}
 
-class Sub: Base {} // expected-error {{cannot inherit from class 'Base' (compiled with Swift 4.0.1) because it has overridable members that could not be loaded in Swift 3.2}}
-class Impl: Proto {} // expected-error {{type 'Impl' cannot conform to protocol 'Proto' (compiled with Swift 4.0.1) because it has requirements that could not be loaded in Swift 3.2}}
+class Sub: Base {} // expected-error {{cannot inherit from class 'Base' (compiled with Swift 4.0.2) because it has overridable members that could not be loaded in Swift 3.2}}
+class Impl: Proto {} // expected-error {{type 'Impl' cannot conform to protocol 'Proto' (compiled with Swift 4.0.2) because it has requirements that could not be loaded in Swift 3.2}}
 
 #else // TEST
 
diff --git a/test/expr/unary/keypath/keypath.swift b/test/expr/unary/keypath/keypath.swift
index f45b9b4..d95c2a6 100644
--- a/test/expr/unary/keypath/keypath.swift
+++ b/test/expr/unary/keypath/keypath.swift
@@ -409,6 +409,23 @@
   _ = \X.Type.b // expected-error{{cannot refer to static member}}
 }
 
+class Bass: Hashable {
+  static func ==(_: Bass, _: Bass) -> Bool { return false }
+  var hashValue: Int { return 0 }
+}
+
+class Treble: Bass { }
+
+struct BassSubscript {
+  subscript(_: Bass) -> Int { fatalError() }
+  subscript(_: @autoclosure () -> String) -> Int { fatalError() }
+}
+
+func testImplicitConversionInSubscriptIndex() {
+  _ = \BassSubscript.[Treble()]
+  _ = \BassSubscript.["hello"] // expected-error{{must be Hashable}}
+}
+
 func testSyntaxErrors() { // expected-note{{}}
   _ = \.  ; // expected-error{{expected member name following '.'}}
   _ = \.a ;
diff --git a/test/lit.cfg b/test/lit.cfg
index f29b64e..1fe45be 100644
--- a/test/lit.cfg
+++ b/test/lit.cfg
@@ -292,6 +292,7 @@
 config.llvm_cov = inferSwiftBinary('llvm-cov')
 config.filecheck = inferSwiftBinary('FileCheck')
 config.llvm_dwarfdump = inferSwiftBinary('llvm-dwarfdump')
+config.llvm_dis = inferSwiftBinary('llvm-dis')
 
 config.swift_utils = os.path.join(config.swift_src_root, 'utils')
 config.line_directive = os.path.join(config.swift_utils, 'line-directive')
@@ -378,6 +379,7 @@
 config.substitutions.append( ('%llvm-link', config.llvm_link) )
 config.substitutions.append( ('%swift-llvm-opt', config.swift_llvm_opt) )
 config.substitutions.append( ('%llvm-dwarfdump', config.llvm_dwarfdump) )
+config.substitutions.append( ('%llvm-dis', config.llvm_dis) )
 
 # This must come after all substitutions containing "%swift".
 config.substitutions.append(
@@ -450,6 +452,7 @@
 disallow('clang')
 disallow('FileCheck')
 disallow('llvm-dwarfdump')
+disallow('llvm-dis')
 
 config.substitutions.insert(0,
     ('%p',
diff --git a/test/stdlib/NSStringAPI+Substring.swift b/test/stdlib/NSStringAPI+Substring.swift
new file mode 100644
index 0000000..92c9444
--- /dev/null
+++ b/test/stdlib/NSStringAPI+Substring.swift
@@ -0,0 +1,146 @@
+// RUN: rm -rf %t ; mkdir -p %t
+// RUN: %target-build-swift %s -o %t/a.out4 -swift-version 4 && %target-run %t/a.out4
+// REQUIRES: executable_test
+
+// REQUIRES: objc_interop
+
+//
+// Tests for the NSString APIs on Substring
+//
+
+import StdlibUnittest
+
+import Foundation
+
+
+extension String {
+  func range(fromStart: Int, fromEnd: Int) -> Range<String.Index> {
+    return index(startIndex, offsetBy: fromStart) ..<
+           index(endIndex, offsetBy: fromEnd)
+  }
+  subscript(fromStart: Int, fromEnd: Int) -> SubSequence {
+    return self[range(fromStart: fromStart, fromEnd: fromEnd)]
+  }
+}
+
+var tests = TestSuite("NSStringAPIs/Substring")
+
+tests.test("range(of:)/NilRange") {
+  let ss = "aabcdd"[1, -1]
+  let range = ss.range(of: "bc")
+  expectOptionalEqual("bc", range.map { ss[$0] })
+}
+
+tests.test("range(of:)/NonNilRange") {
+  let s = "aabcdd"
+  let ss = s[1, -1]
+  let searchRange = s.range(fromStart: 2, fromEnd: -2)
+  let range = ss.range(of: "bc", range: searchRange)
+  expectOptionalEqual("bc", range.map { ss[$0] })
+}
+
+tests.test("rangeOfCharacter") {
+  let ss = "__hello__"[2, -2]
+  let range = ss.rangeOfCharacter(from: CharacterSet.alphanumerics)
+  expectOptionalEqual("h", range.map { ss[$0] })
+}
+
+tests.test("compare(_:options:range:locale:)/NilRange") {
+  let needle = "hello"
+  let haystack = "__hello__"[2, -2]
+  expectEqual(.orderedSame, haystack.compare(needle))
+}
+
+tests.test("compare(_:options:range:locale:)/NonNilRange") {
+  let needle = "hello"
+  let haystack = "__hello__"
+  let range = haystack.range(fromStart: 2, fromEnd: -2)
+  expectEqual(.orderedSame, haystack[range].compare(needle, range: range))
+}
+
+tests.test("replacingCharacters(in:with:)") {
+  let s = "__hello, world"
+  let range = s.range(fromStart: 2, fromEnd: -7)
+  let expected = "__goodbye, world"
+  let replacement = "goodbye"
+  expectEqual(expected,
+    s.replacingCharacters(in: range, with: replacement))
+  expectEqual(expected[2, 0],
+    s[2, 0].replacingCharacters(in: range, with: replacement))
+
+  expectEqual(replacement,
+    s.replacingCharacters(in: s.startIndex..., with: replacement))
+  expectEqual(replacement,
+    s.replacingCharacters(in: ..<s.endIndex, with: replacement))
+  expectEqual(expected[2, 0],
+    s[2, 0].replacingCharacters(in: range, with: replacement[...]))
+}
+
+tests.test("replacingOccurrences(of:with:options:range:)/NilRange") {
+  let s = "hello"
+
+  expectEqual("he11o", s.replacingOccurrences(of: "l", with: "1"))
+  expectEqual("he11o", s.replacingOccurrences(of: "l"[...], with: "1"))
+  expectEqual("he11o", s.replacingOccurrences(of: "l", with: "1"[...]))
+  expectEqual("he11o", s.replacingOccurrences(of: "l"[...], with: "1"[...]))
+
+  expectEqual("he11o",
+    s[...].replacingOccurrences(of: "l", with: "1"))
+  expectEqual("he11o",
+    s[...].replacingOccurrences(of: "l"[...], with: "1"))
+  expectEqual("he11o",
+    s[...].replacingOccurrences(of: "l", with: "1"[...]))
+  expectEqual("he11o",
+    s[...].replacingOccurrences(of: "l"[...], with: "1"[...]))
+}
+
+tests.test("replacingOccurrences(of:with:options:range:)/NonNilRange") {
+  let s = "hello"
+  let r = s.range(fromStart: 1, fromEnd: -2)
+
+  expectEqual("he1lo",
+    s.replacingOccurrences(of: "l", with: "1", range: r))
+  expectEqual("he1lo",
+    s.replacingOccurrences(of: "l"[...], with: "1", range: r))
+  expectEqual("he1lo",
+    s.replacingOccurrences(of: "l", with: "1"[...], range: r))
+  expectEqual("he1lo",
+    s.replacingOccurrences(of: "l"[...], with: "1"[...], range: r))
+
+  expectEqual("he1lo",
+    s[...].replacingOccurrences(of: "l", with: "1", range: r))
+  expectEqual("he1lo",
+    s[...].replacingOccurrences(of: "l"[...], with: "1", range: r))
+  expectEqual("he1lo",
+    s[...].replacingOccurrences(of: "l", with: "1"[...], range: r))
+  expectEqual("he1lo",
+    s[...].replacingOccurrences(of: "l"[...], with: "1"[...], range: r))
+
+  let ss = s[1, -1]
+  expectEqual("e1l",
+    ss.replacingOccurrences(of: "l", with: "1", range: r))
+  expectEqual("e1l",
+    ss.replacingOccurrences(of: "l"[...], with: "1", range: r))
+  expectEqual("e1l",
+    ss.replacingOccurrences(of: "l", with: "1"[...], range: r))
+  expectEqual("e1l",
+    ss.replacingOccurrences(of: "l"[...], with: "1"[...], range: r))
+}
+
+tests.test("substring(with:)") {
+  let s = "hello, world"
+  let r = s.range(fromStart: 7, fromEnd: 0)
+  expectEqual("world", s.substring(with: r))
+  expectEqual("world", s[...].substring(with: r))
+  expectEqual("world", s[1, 0].substring(with: r))
+}
+
+tests.test("substring(with:)/SubscriptEquivalence") {
+  let s = "hello, world"
+  let r = s.range(fromStart: 7, fromEnd: 0)
+  expectEqual(s[r], s.substring(with: r))
+  expectEqual(s[...][r], s[...].substring(with: r))
+  expectEqual(s[1, 0][r], s[1, 0].substring(with: r))
+}
+
+runAllTests()
diff --git a/test/stdlib/NSStringAPI.swift b/test/stdlib/NSStringAPI.swift
index 72e4376..4d7d2a7 100644
--- a/test/stdlib/NSStringAPI.swift
+++ b/test/stdlib/NSStringAPI.swift
@@ -1,4 +1,4 @@
-// RUN: %target-run-simple-swift -swift-version 3
+// RUN: %target-run-simple-swift
 // REQUIRES: executable_test
 
 // REQUIRES: objc_interop
@@ -1144,9 +1144,11 @@
       for: s.index(s.startIndex, offsetBy: 8)..<s.index(s.startIndex, offsetBy: 10))])
 }
 
-func toIntRange(
-  _ string: String, _ maybeRange: Range<String.Index>?
-) -> Range<Int>? {
+func toIntRange<
+  S : StringProtocol
+>(
+  _ string: S, _ maybeRange: Range<String.Index>?
+) -> Range<Int>? where S.Index == String.Index, S.IndexDistance == Int {
   guard let range = maybeRange else { return nil }
 
   return
diff --git a/test/stdlib/StringCompatibilityDiagnostics.swift b/test/stdlib/StringCompatibilityDiagnostics.swift
index a26d6e0..352c6f1 100644
--- a/test/stdlib/StringCompatibilityDiagnostics.swift
+++ b/test/stdlib/StringCompatibilityDiagnostics.swift
@@ -1,4 +1,4 @@
-// RUN: %swift -typecheck -swift-version 4 %s -verify
+// RUN: %target-swift-frontend -typecheck -swift-version 4 %s -verify
 
 func testPopFirst() {
   var str = "abc"
diff --git a/test/stdlib/StringCompatibilityDiagnostics3.swift b/test/stdlib/StringCompatibilityDiagnostics3.swift
index 325b97f..c9358ac 100644
--- a/test/stdlib/StringCompatibilityDiagnostics3.swift
+++ b/test/stdlib/StringCompatibilityDiagnostics3.swift
@@ -1,4 +1,4 @@
-// RUN: %swift -typecheck -swift-version 3 %s -verify
+// RUN: %target-swift-frontend -typecheck -swift-version 3 %s -verify
 
 func testPopFirst() {
   var str = "abc"
diff --git a/test/stdlib/StringCompatibilityDiagnostics4.swift b/test/stdlib/StringCompatibilityDiagnostics4.swift
index 13cf2a9..b5fb753 100644
--- a/test/stdlib/StringCompatibilityDiagnostics4.swift
+++ b/test/stdlib/StringCompatibilityDiagnostics4.swift
@@ -1,4 +1,4 @@
-// RUN: %swift -typecheck -swift-version 4 %s -verify
+// RUN: %target-swift-frontend -typecheck -swift-version 4 %s -verify
 
 func testPopFirst() {
   var str = "abc"
diff --git a/test/stdlib/StringMemoryTest.swift b/test/stdlib/StringMemoryTest.swift
new file mode 100644
index 0000000..68a5d24
--- /dev/null
+++ b/test/stdlib/StringMemoryTest.swift
@@ -0,0 +1,63 @@
+// RUN: %empty-directory(%t)
+// RUN: %target-build-swift -O %s -o %t/StringMemoryTest
+// RUN: %target-run %t/StringMemoryTest | %FileCheck %s
+
+// REQUIRES: optimized_stdlib
+// REQUIRES: executable_test
+// REQUIRES: objc_interop
+
+import Foundation
+
+let str = "abcdefg\u{A758}hijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz\u{A759}"
+let str2 = "abcdefg\u{A759}hijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz\u{A758}"
+
+@inline(never)
+func lookup(_ str: String, _ dict: [String: Int]) -> Bool {
+  if let _ = dict[str] {
+    return true
+  }
+  return false
+}
+
+@inline(never)
+func uppercase(_ str: String) -> String {
+      return str.uppercased()
+}
+
+@inline(never)
+func lowercase(_ str: String) -> String {
+      return str.lowercased()
+}
+
+/// Make sure the hash function does not leak.
+
+let dict = [ "foo" : 1]
+for _ in 0 ..< 10_000_000 {
+  if lookup("\u{1F1E7}\u{1F1E7}", dict) {
+    print("Found?!")
+  }
+  if uppercase(str) == "A" {
+    print("Found?!")
+  }
+  if lowercase(str2) == "A" {
+    print("Found?!")
+  }
+}
+
+// CHECK-NOT: Found?!
+// CHECK: Not found
+
+print("Not found")
+
+var usage = rusage()
+getrusage(RUSAGE_SELF, &usage)
+
+// CHECK: success
+// CHECK-NOT: failure
+
+// We should not need 50MB for this.
+if usage.ru_maxrss > 50 * 1024 * 1024 {
+  print("failure - should not need 50MB!")
+} else {
+  print("success")
+}
diff --git a/test/stdlib/runtime_autorelease_optimization.txt b/test/stdlib/runtime_autorelease_optimization.txt
new file mode 100644
index 0000000..7b10575
--- /dev/null
+++ b/test/stdlib/runtime_autorelease_optimization.txt
@@ -0,0 +1,101 @@
+// REQUIRES: objc_interop
+// RUN: otool -tvV %platform-module-dir/libswiftCore.dylib | %FileCheck %s --check-prefix=CHECK-%target-cpu
+
+// Verify the autorelease return optimization sequence.
+
+/// Test x86-64:
+
+// CHECK-x86_64-LABEL: _swift_stdlib_NSStringHashValue:
+// CHECK-x86_64-NOT: ret
+// CHECK-x86_64: movq    {{.*}}(%rip), %rsi ## Objc selector ref: decomposedStringWithCanonicalMapping
+// CHECK-x86_64: movq    {{.*}}(%rip), [[MSG:%.*]] ## Objc message: -[%rdi decomposedStringWithCanonicalMapping]
+// CHECK-x86_64: callq   *[[MSG]]
+// CHECK-x86_64: movq    %rax, %rdi
+// CHECK-x86_64: callq   {{.*}} ## symbol stub for: _objc_retainAutoreleasedReturnValue
+// CHECK-x86_64: ret
+
+
+// CHECK-x86_64-LABEL: _swift_stdlib_NSStringHashValuePointer:
+// CHECK-x86_64-NOT: ret
+// CHECK-x86_64: movq    {{.*}}(%rip), %rsi ## Objc selector ref: decomposedStringWithCanonicalMapping
+// CHECK-x86_64: movq    {{.*}}(%rip), [[MSG:%.*]] ## Objc message: -[%rdi decomposedStringWithCanonicalMapping]
+// CHECK-x86_64: callq   *[[MSG]]
+// CHECK-x86_64: movq    %rax, %rdi
+// CHECK-x86_64: callq   {{.*}} ## symbol stub for: _objc_retainAutoreleasedReturnValue
+// CHECK-x86_64: ret
+
+/// Test i386:
+
+// CHECK-i386-LABEL: _swift_stdlib_NSStringHashValue:
+// CHECK-i386-NOT: ret
+// CHECK-i386: calll   {{.*}} ## symbol stub for: _objc_msgSend
+// CHECK-i386: movl    %ebp, %ebp
+// CHECK-i386: calll   {{.*}} ## symbol stub for: _objc_retainAutoreleasedReturnValue
+// CHECK-i386: ret
+// CHECK-i386-LABEL: _swift_stdlib_NSStringHashValuePointer:
+// CHECK-i386-NOT: ret
+// CHECK-i386: calll   {{.*}} ## symbol stub for: _objc_msgSend
+// CHECK-i386: movl    %ebp, %ebp
+// CHECK-i386: calll   {{.*}} ## symbol stub for: _objc_retainAutoreleasedReturnValue
+// CHECK-i386: ret
+
+/// Test armv7:
+
+// CHECK-armv7-LABEL: _swift_stdlib_NSStringHashValue:
+// CHECK-armv7-NOT: pop {{.*}}pc{{.*}}
+// CHECK-armv7: blx     {{.*}} @ symbol stub for: _objc_msgSend
+// CHECK-armv7: mov     r7, r7
+// CHECK-armv7: blx     {{.*}} @ symbol stub for: _objc_retainAutoreleasedReturnValue
+// CHECK-armv7: pop {{.*}}pc{{.*}}
+// CHECK-armv7-LABEL: _swift_stdlib_NSStringHashValuePointer:
+// CHECK-armv7-NOT: pop {{.*}}pc{{.*}}
+// CHECK-armv7: blx     {{.*}} @ symbol stub for: _objc_msgSend
+// CHECK-armv7: mov     r7, r7
+// CHECK-armv7: blx     {{.*}} @ symbol stub for: _objc_retainAutoreleasedReturnValue
+// CHECK-armv7: pop {{.*}}pc{{.*}}
+
+/// Test armv7s:
+
+// CHECK-armv7s-LABEL: _swift_stdlib_NSStringHashValue:
+// CHECK-armv7s-NOT: pop {{.*}}pc{{.*}}
+// CHECK-armv7s: blx     {{.*}} @ symbol stub for: _objc_msgSend
+// CHECK-armv7s: mov     r7, r7
+// CHECK-armv7s: blx     {{.*}} @ symbol stub for: _objc_retainAutoreleasedReturnValue
+// CHECK-armv7s: pop {{.*}}pc{{.*}}
+// CHECK-armv7s-LABEL: _swift_stdlib_NSStringHashValuePointer:
+// CHECK-armv7s-NOT: pop {{.*}}pc{{.*}}
+// CHECK-armv7s: blx     {{.*}} @ symbol stub for: _objc_msgSend
+// CHECK-armv7s: mov     r7, r7
+// CHECK-armv7s: blx     {{.*}} @ symbol stub for: _objc_retainAutoreleasedReturnValue
+// CHECK-armv7s: pop {{.*}}pc{{.*}}
+
+
+/// Test armv7k:
+
+// CHECK-armv7k-LABEL: _swift_stdlib_NSStringHashValue:
+// CHECK-armv7k-NOT: pop {{.*}}pc{{.*}}
+// CHECK-armv7k: blx     {{.*}} @ symbol stub for: _objc_msgSend
+// CHECK-armv7k: mov     r7, r7
+// CHECK-armv7k: blx     {{.*}} @ symbol stub for: _objc_retainAutoreleasedReturnValue
+// CHECK-armv7k: pop {{.*}}pc{{.*}}
+// CHECK-armv7k-LABEL: _swift_stdlib_NSStringHashValuePointer:
+// CHECK-armv7k-NOT: pop {{.*}}pc{{.*}}
+// CHECK-armv7k: blx     {{.*}} @ symbol stub for: _objc_msgSend
+// CHECK-armv7k: mov     r7, r7
+// CHECK-armv7k: blx     {{.*}} @ symbol stub for: _objc_retainAutoreleasedReturnValue
+// CHECK-armv7k: pop {{.*}}pc{{.*}}
+
+/// Test arm64:
+
+// CHECK-arm64-LABEL: _swift_stdlib_NSStringHashValue:
+// CHECK-arm64-NOT: ret
+// CHECK-arm64: bl      {{.*}} ; Objc message: -[x0 decomposedStringWithCanonicalMapping]
+// CHECK-arm64: mov      x29, x29
+// CHECK-arm64: bl      {{.*}} ; symbol stub for: _objc_retainAutoreleasedReturnValue
+// CHECK-arm64: ret
+// CHECK-arm64-LABEL: _swift_stdlib_NSStringHashValuePointer:
+// CHECK-arm64-NOT: ret
+// CHECK-arm64: bl      {{.*}} ; Objc message: -[x0 decomposedStringWithCanonicalMapping]
+// CHECK-arm64: mov      x29, x29
+// CHECK-arm64: bl      {{.*}} ; symbol stub for: _objc_retainAutoreleasedReturnValue
+// CHECK-arm64: ret
diff --git a/utils/build-script b/utils/build-script
index d1db66d..7a21a94 100755
--- a/utils/build-script
+++ b/utils/build-script
@@ -40,7 +40,7 @@
     SWIFT_REPO_NAME,
     SWIFT_SOURCE_ROOT,
     get_all_preset_names,
-    get_preset_options,  
+    get_preset_options,
 )
 
 from swift_build_support.swift_build_support.cmake import CMake
@@ -2060,7 +2060,7 @@
         "--swift-user-visible-version",
         help="User-visible version of the embedded Swift compiler",
         type=arguments.type.swift_compiler_version,
-        default="4.0.1",
+        default="4.0.2",
         metavar="MAJOR.MINOR")
 
     parser.add_argument(