Merge pull request #19483 from DougGregor/runtime-demangle-fixes

[Runtime] Fixes for demangling to metadata
diff --git a/CMakeLists.txt b/CMakeLists.txt
index f9e9891..06229f9 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -775,7 +775,10 @@
 # Should we cross-compile the standard library for Windows?
 is_sdk_requested(WINDOWS swift_build_windows)
 if(swift_build_windows AND NOT "${CMAKE_SYSTEM_NAME}" STREQUAL "Windows")
-  configure_sdk_windows(WINDOWS "Windows" "msvc" "aarch64;armv7;i686;x86_64")
+  if("${SWIFT_SDK_WINDOWS_ARCHITECTURES}" STREQUAL "")
+    set(SWIFT_SDK_WINDOWS_ARCHITECTURES aarch64;armv7;i686;x86_64)
+  endif()
+  configure_sdk_windows(WINDOWS "Windows" "msvc" "${SWIFT_SDK_WINDOWS_ARCHITECTURES}")
 endif()
 
 if("${SWIFT_SDKS}" STREQUAL "")
diff --git a/cmake/modules/AddSwift.cmake b/cmake/modules/AddSwift.cmake
index 4f97023..cfc1e80 100644
--- a/cmake/modules/AddSwift.cmake
+++ b/cmake/modules/AddSwift.cmake
@@ -132,10 +132,11 @@
   endif()
 
   if("${CFLAGS_SDK}" STREQUAL "ANDROID")
-    list(APPEND result
-      "--sysroot=${SWIFT_SDK_ANDROID_ARCH_${CFLAGS_ARCH}_PATH}"
-      # Use the linker included in the Android NDK.
-      "-B" "${SWIFT_SDK_ANDROID_ARCH_${CFLAGS_ARCH}_NDK_PREBUILT_PATH}/${SWIFT_SDK_ANDROID_ARCH_${CFLAGS_ARCH}_NDK_TRIPLE}/bin/")
+    # lld can handle targeting the android build.  However, if lld is not
+    # enabled, then fallback to the linker included in the android NDK.
+    if(NOT SWIFT_ENABLE_LLD_LINKER)
+      list(APPEND result "-B" "${SWIFT_SDK_ANDROID_ARCH_${CFLAGS_ARCH}_NDK_PREBUILT_PATH}/${SWIFT_SDK_ANDROID_ARCH_${CFLAGS_ARCH}_NDK_TRIPLE}/bin")
+    endif()
   endif()
 
   if(IS_DARWIN)
diff --git a/docs/WindowsBuild.md b/docs/WindowsBuild.md
index 5f3fa60..7193e47 100644
--- a/docs/WindowsBuild.md
+++ b/docs/WindowsBuild.md
@@ -233,12 +233,12 @@
 cmake -G "Ninja" "%swift_source_dir%/swift"^
  -DCMAKE_BUILD_TYPE=Debug^
  -DSWIFT_PATH_TO_CMARK_SOURCE="%swift_source_dir%/cmark"^
- -DSWIFT_PATH_TO_CMARK_BUILD="%swift_source_dir%/build/Ninja-RelWithDebInfoAssert/cmark-windows-amd64"^
- -DSWIFT_CMARK_LIBRARY_DIR="%swift_source_dir%/build/Ninja-RelWithDebInfoAssert/cmark-windows-amd64/src"^
+ -DSWIFT_PATH_TO_CMARK_BUILD="%swift_source_dir%/build/Ninja-DebugAssert/cmark-windows-amd64"^
+ -DSWIFT_CMARK_LIBRARY_DIR="%swift_source_dir%/build/Ninja-DebugAssert/cmark-windows-amd64/src"^
  -DSWIFT_PATH_TO_LLVM_SOURCE="%swift_source_dir%/llvm"^
- -DSWIFT_PATH_TO_LLVM_BUILD="%swift_source_dir%/build/Ninja-RelWithDebInfoAssert/llvm-windows-amd64"^
+ -DSWIFT_PATH_TO_LLVM_BUILD="%swift_source_dir%/build/Ninja-DebugAssert/llvm-windows-amd64"^
  -DSWIFT_PATH_TO_CLANG_SOURCE="%swift_source_dir%/llvm/tools/clang"^
- -DSWIFT_PATH_TO_CLANG_BUILD="%swift_source_dir%/build/Ninja-RelWithDebInfoAssert/llvm-windows-amd64"^
+ -DSWIFT_PATH_TO_CLANG_BUILD="%swift_source_dir%/build/Ninja-DebugAssert/llvm-windows-amd64"^
  -DICU_UC_INCLUDE_DIRS="%swift_source_dir%/icu/include"^
  -DICU_UC_LIBRARY_DIRS="%swift_source_dir%/icu/lib64"^
  -DICU_I18N_INCLUDE_DIRS="%swift_source_dir%/icu/include"^
diff --git a/foo.swift b/foo.swift
deleted file mode 100644
index 3624ef0..0000000
--- a/foo.swift
+++ /dev/null
@@ -1,25 +0,0 @@
-
-enum SinglePayloadGenericEnumWithDefaultMirror<T, U> {
-  case Well
-  case Faucet
-  case Pipe(T, U)
-}
-
-func foo(x: Int, y: [Int], out: (SinglePayloadGenericEnumWithDefaultMirror<Int, [Int]>) -> ()) {
-  out(.Well)
-  out(.Faucet)
-  out(.Pipe(x, y))
-}
-
-func bar<T, U>(_ x: SinglePayloadGenericEnumWithDefaultMirror<T, U>) {
-  switch x {
-  case .Well:
-    print("well")
-  case .Faucet:
-    print("faucet")
-  case .Pipe:
-    print("pipe")
-  }
-}
-
-foo(x: 1, y: [1,2,3], out: bar)
diff --git a/include/swift/AST/Decl.h b/include/swift/AST/Decl.h
index 370dcf8..09f67de 100644
--- a/include/swift/AST/Decl.h
+++ b/include/swift/AST/Decl.h
@@ -3116,6 +3116,16 @@
   /// called to make it immediately visible.
   void makeMemberVisible(ValueDecl *member);
 
+  /// Special-behaviour flags passed to lookupDirect()
+  enum class LookupDirectFlags {
+    /// Whether to avoid loading any new extension.
+    /// Used by the module loader to break recursion.
+    IgnoreNewExtensions = 1 << 0,
+    /// Whether to include @_implements members.
+    /// Used by conformance-checking to find special @_implements members.
+    IncludeAttrImplements = 1 << 1,
+  };
+
   /// Find all of the declarations with the given name within this nominal type
   /// and its extensions.
   ///
@@ -3123,11 +3133,9 @@
   /// protocols to which the nominal type conforms. Furthermore, the resulting
   /// set of declarations has not been filtered for visibility, nor have
   /// overridden declarations been removed.
-  ///
-  /// \param ignoreNewExtensions Whether to avoid loading any new extension.
-  /// Used by the module loader to break recursion.
   TinyPtrVector<ValueDecl *> lookupDirect(DeclName name,
-                                          bool ignoreNewExtensions = false);
+                                          OptionSet<LookupDirectFlags> flags =
+                                          OptionSet<LookupDirectFlags>());
 
   /// Collect the set of protocols to which this type should implicitly
   /// conform, such as AnyObject (for classes).
diff --git a/include/swift/AST/DiagnosticsModuleDiffer.def b/include/swift/AST/DiagnosticsModuleDiffer.def
index 8b7d9b4..9484f18 100644
--- a/include/swift/AST/DiagnosticsModuleDiffer.def
+++ b/include/swift/AST/DiagnosticsModuleDiffer.def
@@ -42,6 +42,8 @@
 
 ERROR(removed_decl,none,"%0 has been removed%select{| (deprecated)}1", (StringRef, bool))
 
+ERROR(removed_setter,none,"%0 has removed its setter", (StringRef))
+
 ERROR(moved_decl,none,"%0 has been moved to %1", (StringRef, StringRef))
 
 ERROR(renamed_decl,none,"%0 has been renamed to %1", (StringRef, StringRef))
@@ -62,6 +64,8 @@
 
 ERROR(conformance_added,none,"%0 has added inherited protocol %1", (StringRef, StringRef))
 
+ERROR(default_associated_type_removed,none,"%0 has removed default type %1", (StringRef, StringRef))
+
 #ifndef DIAG_NO_UNDEF
 # if defined(DIAG)
 #  undef DIAG
diff --git a/include/swift/AST/LookupKinds.h b/include/swift/AST/LookupKinds.h
index 5d735f0..71a61f5 100644
--- a/include/swift/AST/LookupKinds.h
+++ b/include/swift/AST/LookupKinds.h
@@ -57,6 +57,9 @@
   /// This lookup should only return type declarations.
   NL_OnlyTypes = 0x80,
 
+  /// Include synonyms declared with @_implements()
+  NL_IncludeAttributeImplements = 0x100,
+
   /// This lookup is known to not add any additional dependencies to the
   /// primary source file.
   ///
diff --git a/include/swift/IDE/DigesterEnums.def b/include/swift/IDE/DigesterEnums.def
index f730523..b716f2d 100644
--- a/include/swift/IDE/DigesterEnums.def
+++ b/include/swift/IDE/DigesterEnums.def
@@ -45,6 +45,8 @@
 NODE_KIND(DeclSetter, Setter)
 NODE_KIND(DeclVar, Var)
 NODE_KIND(DeclTypeAlias, TypeAlias)
+NODE_KIND(DeclAssociatedType, AssociatedType)
+NODE_KIND(DeclSubscript, Subscript)
 
 NODE_ANNOTATION(Added)
 NODE_ANNOTATION(Removed)
@@ -111,6 +113,7 @@
 KEY(enumRawTypeName)
 KEY(genericSig)
 KEY(fixedbinaryorder)
+KEY(hasSetter)
 
 KNOWN_TYPE(Optional)
 KNOWN_TYPE(ImplicitlyUnwrappedOptional)
diff --git a/include/swift/Runtime/Atomic.h b/include/swift/Runtime/Atomic.h
index 3f9c1a3..655078a 100644
--- a/include/swift/Runtime/Atomic.h
+++ b/include/swift/Runtime/Atomic.h
@@ -22,7 +22,7 @@
 // is formally UB by C++11 language rules, we should be OK because neither
 // the processor model nor the optimizer can realistically reorder our uses
 // of 'consume'.
-#if __arm64__ || __arm__
+#if defined(__arm__) || defined(_M_ARM) || defined(__arm64__) || defined(__aarch64__) || defined(_M_ARM64)
 #  define SWIFT_MEMORY_ORDER_CONSUME (std::memory_order_relaxed)
 #else
 #  define SWIFT_MEMORY_ORDER_CONSUME (std::memory_order_consume)
diff --git a/include/swift/SIL/SILArgumentArrayRef.h b/include/swift/SIL/SILArgumentArrayRef.h
new file mode 100644
index 0000000..a4d8245
--- /dev/null
+++ b/include/swift/SIL/SILArgumentArrayRef.h
@@ -0,0 +1,41 @@
+//===--- SILArgumentArrayRef.h --------------------------------------------===//
+//
+// This source file is part of the Swift.org open source project
+//
+// Copyright (c) 2014 - 2018 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
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+///
+/// A header file to ensure that we do not create a dependency cycle in between
+/// SILBasicBlock.h and SILInstruction.h.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef SWIFT_SIL_SILARGUMENTARRAYREF_H
+#define SWIFT_SIL_SILARGUMENTARRAYREF_H
+
+#include "swift/Basic/LLVM.h"
+#include "swift/Basic/STLExtras.h"
+#include "swift/Basic/TransformArrayRef.h"
+
+namespace swift {
+
+class SILArgument;
+class SILPHIArgument;
+class SILFunctionArgument;
+
+using PHIArgumentArrayRef =
+    TransformArrayRef<function_ref<SILPHIArgument *(SILArgument *)>>;
+
+using FunctionArgumentArrayRef =
+    TransformArrayRef<function_ref<SILFunctionArgument *(SILArgument *)>>;
+
+} // namespace swift
+
+#endif
diff --git a/include/swift/SIL/SILBasicBlock.h b/include/swift/SIL/SILBasicBlock.h
index d0c00ce..c7f9874 100644
--- a/include/swift/SIL/SILBasicBlock.h
+++ b/include/swift/SIL/SILBasicBlock.h
@@ -20,6 +20,7 @@
 #include "swift/Basic/Compiler.h"
 #include "swift/Basic/Range.h"
 #include "swift/Basic/TransformArrayRef.h"
+#include "swift/SIL/SILArgumentArrayRef.h"
 #include "swift/SIL/SILInstruction.h"
 
 namespace swift {
@@ -192,12 +193,15 @@
   }
 
   ArrayRef<SILArgument *> getArguments() const { return ArgumentList; }
-  using PHIArgumentArrayRefTy =
-      TransformArrayRef<SILPHIArgument *(*)(SILArgument *)>;
-  PHIArgumentArrayRefTy getPHIArguments() const;
-  using FunctionArgumentArrayRefTy =
-      TransformArrayRef<SILFunctionArgument *(*)(SILArgument *)>;
-  FunctionArgumentArrayRefTy getFunctionArguments() const;
+
+  /// Returns a transform array ref that performs llvm::cast<SILPHIArgument> on
+  /// each argument and then returns the downcasted value.
+  PHIArgumentArrayRef getPHIArguments() const;
+
+  /// Returns a transform array ref that performs
+  /// llvm::cast<SILFunctionArgument> on each argument and then returns the
+  /// downcasted value.
+  FunctionArgumentArrayRef getFunctionArguments() const;
 
   unsigned getNumArguments() const { return ArgumentList.size(); }
   const SILArgument *getArgument(unsigned i) const { return ArgumentList[i]; }
diff --git a/include/swift/SIL/SILInstruction.h b/include/swift/SIL/SILInstruction.h
index 48f17dd..4c473d0 100644
--- a/include/swift/SIL/SILInstruction.h
+++ b/include/swift/SIL/SILInstruction.h
@@ -29,6 +29,7 @@
 #include "swift/Basic/Range.h"
 #include "swift/SIL/Consumption.h"
 #include "swift/SIL/SILAllocated.h"
+#include "swift/SIL/SILArgumentArrayRef.h"
 #include "swift/SIL/SILDeclRef.h"
 #include "swift/SIL/SILFunctionConventions.h"
 #include "swift/SIL/SILLocation.h"
@@ -6605,6 +6606,14 @@
     });
   }
 
+  using SuccessorBlockArgumentsListTy =
+      TransformRange<ConstSuccessorListTy,
+                     function_ref<PHIArgumentArrayRef(const SILSuccessor &)>>;
+
+  /// Return the range of Argument arrays for each successor of this
+  /// block.
+  SuccessorBlockArgumentsListTy getSuccessorBlockArguments() const;
+
   using SuccessorBlockListTy =
       TransformRange<SuccessorListTy,
                      SILBasicBlock *(*)(const SILSuccessor &)>;
diff --git a/include/swift/Serialization/ModuleFormat.h b/include/swift/Serialization/ModuleFormat.h
index ceedb10..5fb65dd 100644
--- a/include/swift/Serialization/ModuleFormat.h
+++ b/include/swift/Serialization/ModuleFormat.h
@@ -55,7 +55,7 @@
 /// describe what change you made. The content of this comment isn't important;
 /// it just ensures a conflict if two people change the module format.
 /// Don't worry about adhering to the 80-column limit for this line.
-const uint16_t VERSION_MINOR = 448; // Last change: assoc type default is interface type
+const uint16_t VERSION_MINOR = 449; // Last change: serialize @_implements names
 
 using DeclIDField = BCFixed<31>;
 
diff --git a/lib/AST/Decl.cpp b/lib/AST/Decl.cpp
index b113b25..cecae36 100644
--- a/lib/AST/Decl.cpp
+++ b/lib/AST/Decl.cpp
@@ -3252,8 +3252,10 @@
 
 bool ClassDecl::hasMissingDesignatedInitializers() const {
   auto *mutableThis = const_cast<ClassDecl *>(this);
+  auto flags = OptionSet<LookupDirectFlags>();
+  flags |= LookupDirectFlags::IgnoreNewExtensions;
   (void)mutableThis->lookupDirect(DeclBaseName::createConstructor(),
-                                  /*ignoreNewExtensions*/true);
+                                  flags);
   return Bits.ClassDecl.HasMissingDesignatedInitializers;
 }
 
diff --git a/lib/AST/GenericSignatureBuilder.cpp b/lib/AST/GenericSignatureBuilder.cpp
index 7588277..b157b4f 100644
--- a/lib/AST/GenericSignatureBuilder.cpp
+++ b/lib/AST/GenericSignatureBuilder.cpp
@@ -2124,8 +2124,9 @@
     ProtocolDecl *proto = conforms.first;
 
     // Look for an associated type and/or concrete type with this name.
-    for (auto member : proto->lookupDirect(name,
-                                           /*ignoreNewExtensions=*/true)) {
+    auto flags = OptionSet<NominalTypeDecl::LookupDirectFlags>();
+    flags |= NominalTypeDecl::LookupDirectFlags::IgnoreNewExtensions;
+    for (auto member : proto->lookupDirect(name, flags)) {
       // If this is an associated type, record whether it is the best
       // associated type we've seen thus far.
       if (auto assocType = dyn_cast<AssociatedTypeDecl>(member)) {
diff --git a/lib/AST/NameLookup.cpp b/lib/AST/NameLookup.cpp
index 699a8b7..07c9d79 100644
--- a/lib/AST/NameLookup.cpp
+++ b/lib/AST/NameLookup.cpp
@@ -1339,8 +1339,11 @@
   if (!vd)
     return;
 
-  // Unnamed entities cannot be found by name lookup.
-  if (!vd->hasName())
+  // @_implements members get added under their declared name.
+  auto A = vd->getAttrs().getAttribute<ImplementsAttr>();
+
+  // Unnamed entities w/o @_implements synonyms cannot be found by name lookup.
+  if (!A && !vd->hasName())
     return;
 
   // If this declaration is already in the lookup table, don't add it
@@ -1353,6 +1356,10 @@
   // Add this declaration to the lookup set under its compound name and simple
   // name.
   vd->getFullName().addToLookupTable(Lookup, vd);
+
+  // And if given a synonym, under that name too.
+  if (A)
+    A->getMemberName().addToLookupTable(Lookup, vd);
 }
 
 void MemberLookupTable::addMembers(DeclRange members) {
@@ -1592,9 +1599,31 @@
   LookupTable.getPointer()->addMember(member);
 }
 
+
+static TinyPtrVector<ValueDecl *>
+maybeFilterOutAttrImplements(TinyPtrVector<ValueDecl *> decls,
+                             DeclName name,
+                             bool includeAttrImplements) {
+  if (includeAttrImplements)
+    return decls;
+  TinyPtrVector<ValueDecl*> result;
+  for (auto V : decls) {
+    // Filter-out any decl that doesn't have the name we're looking for
+    // (asserting as a consistency-check that such entries all have
+    // @_implements attrs for the name!)
+    if (V->getFullName().matchesRef(name)) {
+      result.push_back(V);
+    } else {
+      auto A = V->getAttrs().getAttribute<ImplementsAttr>();
+      assert(A && A->getMemberName().matchesRef(name));
+    }
+  }
+  return result;
+}
+
 TinyPtrVector<ValueDecl *> NominalTypeDecl::lookupDirect(
                                                   DeclName name,
-                                                  bool ignoreNewExtensions) {
+                                                  OptionSet<LookupDirectFlags> flags) {
   ASTContext &ctx = getASTContext();
   if (auto s = ctx.Stats) {
     ++s->getFrontendCounters().NominalTypeLookupDirectCount;
@@ -1605,6 +1634,12 @@
   bool useNamedLazyMemberLoading = (ctx.LangOpts.NamedLazyMemberLoading &&
                                     hasLazyMembers());
 
+  bool ignoreNewExtensions =
+      flags.contains(LookupDirectFlags::IgnoreNewExtensions);
+
+  bool includeAttrImplements =
+      flags.contains(LookupDirectFlags::IncludeAttrImplements);
+
   // FIXME: At present, lazy member loading conflicts with a bunch of other code
   // that appears to special-case initializers (clang-imported initializer
   // sorting, implicit initializer synthesis), so for the time being we have to
@@ -1663,7 +1698,8 @@
 
     // We found something; return it.
     if (known != LookupTable.getPointer()->end())
-      return known->second;
+      return maybeFilterOutAttrImplements(known->second, name,
+                                          includeAttrImplements);
 
     // If we have no more second chances, stop now.
     if (!useNamedLazyMemberLoading || i > 0)
@@ -2004,7 +2040,10 @@
 
     // Look for results within the current nominal type and its extensions.
     bool currentIsProtocol = isa<ProtocolDecl>(current);
-    for (auto decl : current->lookupDirect(member)) {
+    auto flags = OptionSet<NominalTypeDecl::LookupDirectFlags>();
+    if (options & NL_IncludeAttributeImplements)
+      flags |= NominalTypeDecl::LookupDirectFlags::IncludeAttrImplements;
+    for (auto decl : current->lookupDirect(member, flags)) {
       // If we're performing a type lookup, don't even attempt to validate
       // the decl if its not a type.
       if ((options & NL_OnlyTypes) && !isa<TypeDecl>(decl))
diff --git a/lib/Basic/SourceLoc.cpp b/lib/Basic/SourceLoc.cpp
index 7c5c801..a5791c3 100644
--- a/lib/Basic/SourceLoc.cpp
+++ b/lib/Basic/SourceLoc.cpp
@@ -320,11 +320,10 @@
   const char *Ptr = InputBuf->getBufferStart();
   const char *End = InputBuf->getBufferEnd();
   const char *LineStart = Ptr;
-  for (; Ptr < End; ++Ptr) {
+  --Line;
+  for (; Line && (Ptr < End); ++Ptr) {
     if (*Ptr == '\n') {
       --Line;
-      if (Line == 0)
-        break;
       LineStart = Ptr+1;
     }
   }
diff --git a/lib/ClangImporter/ClangImporter.cpp b/lib/ClangImporter/ClangImporter.cpp
index 3146a6a..fd2a7f6 100644
--- a/lib/ClangImporter/ClangImporter.cpp
+++ b/lib/ClangImporter/ClangImporter.cpp
@@ -2634,7 +2634,9 @@
       isa<StructDecl>(baseType) && !baseType->hasLazyMembers() &&
       baseType->isChildContextOf(this)) {
     auto *mutableBase = const_cast<NominalTypeDecl *>(baseType);
-    auto codeEnum = mutableBase->lookupDirect(name,/*ignoreNewExtensions*/true);
+    auto flags = OptionSet<NominalTypeDecl::LookupDirectFlags>();
+    flags |= NominalTypeDecl::LookupDirectFlags::IgnoreNewExtensions;
+    auto codeEnum = mutableBase->lookupDirect(name, flags);
     // Double-check that we actually have a good result. It's possible what we
     // found is /not/ a synthesized error struct, but just something that looks
     // like it. But if we still found a good result we should return that.
diff --git a/lib/ClangImporter/ImportDecl.cpp b/lib/ClangImporter/ImportDecl.cpp
index 1d77e3b8..1c7eb07 100644
--- a/lib/ClangImporter/ImportDecl.cpp
+++ b/lib/ClangImporter/ImportDecl.cpp
@@ -6093,9 +6093,11 @@
   SmallVector<AnyFunctionType::Param, 4> allocParams;
   bodyParams->getParams(allocParams);
 
-  bool ignoreNewExtensions = isa<ClassDecl>(dc);
+  auto flags = OptionSet<NominalTypeDecl::LookupDirectFlags>();
+  if (isa<ClassDecl>(dc))
+    flags |= NominalTypeDecl::LookupDirectFlags::IgnoreNewExtensions;
   for (auto other : ownerNominal->lookupDirect(importedName.getDeclName(),
-                                               ignoreNewExtensions)) {
+                                               flags)) {
     auto ctor = dyn_cast<ConstructorDecl>(other);
     if (!ctor || ctor->isInvalid() ||
         ctor->getAttrs().isUnavailable(Impl.SwiftContext) ||
diff --git a/lib/ClangImporter/ImportType.cpp b/lib/ClangImporter/ImportType.cpp
index 3d7628b..bfebccd 100644
--- a/lib/ClangImporter/ImportType.cpp
+++ b/lib/ClangImporter/ImportType.cpp
@@ -797,8 +797,9 @@
         if (attr->getProtocolKind() ==
             KnownProtocolKind::BridgedStoredNSError) {
           auto &ctx = nominal->getASTContext();
-          auto lookup = nominal->lookupDirect(ctx.Id_Code,
-                                              /*ignoreNewExtensions=*/true);
+          auto flags = OptionSet<NominalTypeDecl::LookupDirectFlags>();
+          flags |= NominalTypeDecl::LookupDirectFlags::IgnoreNewExtensions;
+          auto lookup = nominal->lookupDirect(ctx.Id_Code, flags);
           for (auto found : lookup) {
             if (auto codeDecl = dyn_cast<TypeDecl>(found))
               return codeDecl;
diff --git a/lib/IDE/ModuleInterfacePrinting.cpp b/lib/IDE/ModuleInterfacePrinting.cpp
index cdf9d35..b82f9b6 100644
--- a/lib/IDE/ModuleInterfacePrinting.cpp
+++ b/lib/IDE/ModuleInterfacePrinting.cpp
@@ -231,8 +231,9 @@
   if (auto nominal =
         const_cast<NominalTypeDecl *>(dyn_cast<NominalTypeDecl>(decl))) {
     auto &ctx = nominal->getASTContext();
-    for (auto code : nominal->lookupDirect(ctx.Id_Code,
-                                           /*ignoreNewExtensions=*/true)) {
+    auto flags = OptionSet<NominalTypeDecl::LookupDirectFlags>();
+    flags |= NominalTypeDecl::LookupDirectFlags::IgnoreNewExtensions;
+    for (auto code : nominal->lookupDirect(ctx.Id_Code, flags)) {
       if (auto clangDecl = code->getClangDecl())
         return clangDecl;
     }
diff --git a/lib/Parse/Lexer.cpp b/lib/Parse/Lexer.cpp
index b614aa0..c09b288 100644
--- a/lib/Parse/Lexer.cpp
+++ b/lib/Parse/Lexer.cpp
@@ -1817,6 +1817,12 @@
         // Successfully scanned the body of the expression literal.
         ++CurPtr;
         continue;
+      } else if ((*CurPtr == '\r' || *CurPtr == '\n') && IsMultilineString) {
+        // The only case we reach here is unterminated single line string in the
+        // interpolation. For better recovery, go on after emitting an error.
+        diagnose(CurPtr, diag::lex_unterminated_string);
+        wasErroneous = true;
+        continue;
       }
 
       // Being diagnosed below.
diff --git a/lib/RemoteAST/RemoteAST.cpp b/lib/RemoteAST/RemoteAST.cpp
index ef1a958..6c69919 100644
--- a/lib/RemoteAST/RemoteAST.cpp
+++ b/lib/RemoteAST/RemoteAST.cpp
@@ -402,8 +402,10 @@
     if (!base->isTypeParameter())
       return Type();
 
+    auto flags = OptionSet<NominalTypeDecl::LookupDirectFlags>();
+    flags |= NominalTypeDecl::LookupDirectFlags::IgnoreNewExtensions;
     for (auto member : protocol->lookupDirect(Ctx.getIdentifier(member),
-                                              /*ignoreNew=*/true)) {
+                                              flags)) {
       if (auto assocType = dyn_cast<AssociatedTypeDecl>(member))
         return DependentMemberType::get(base, assocType);
     }
diff --git a/lib/SIL/SILBasicBlock.cpp b/lib/SIL/SILBasicBlock.cpp
index 4ee0bdd..7d6d6b4 100644
--- a/lib/SIL/SILBasicBlock.cpp
+++ b/lib/SIL/SILBasicBlock.cpp
@@ -335,18 +335,17 @@
   return this == &*getParent()->begin();
 }
 
-SILBasicBlock::PHIArgumentArrayRefTy SILBasicBlock::getPHIArguments() const {
-  return PHIArgumentArrayRefTy(getArguments(),
-                               [](SILArgument *A) -> SILPHIArgument * {
-    return cast<SILPHIArgument>(A);
+/// Declared out of line so we can have a declaration of SILArgument.
+PHIArgumentArrayRef SILBasicBlock::getPHIArguments() const {
+  return PHIArgumentArrayRef(getArguments(), [](SILArgument *arg) {
+    return cast<SILPHIArgument>(arg);
   });
 }
 
-SILBasicBlock::FunctionArgumentArrayRefTy
-SILBasicBlock::getFunctionArguments() const {
-  return FunctionArgumentArrayRefTy(getArguments(),
-                                    [](SILArgument *A) -> SILFunctionArgument* {
-    return cast<SILFunctionArgument>(A);
+/// Declared out of line so we can have a declaration of SILArgument.
+FunctionArgumentArrayRef SILBasicBlock::getFunctionArguments() const {
+  return FunctionArgumentArrayRef(getArguments(), [](SILArgument *arg) {
+    return cast<SILFunctionArgument>(arg);
   });
 }
 
diff --git a/lib/SIL/SILInstructions.cpp b/lib/SIL/SILInstructions.cpp
index a9169af..e229692 100644
--- a/lib/SIL/SILInstructions.cpp
+++ b/lib/SIL/SILInstructions.cpp
@@ -1061,6 +1061,15 @@
   llvm_unreachable("Unhandled TermKind in switch.");
 }
 
+TermInst::SuccessorBlockArgumentsListTy
+TermInst::getSuccessorBlockArguments() const {
+  function_ref<PHIArgumentArrayRef(const SILSuccessor &)> op;
+  op = [](const SILSuccessor &succ) -> PHIArgumentArrayRef {
+    return succ.getBB()->getPHIArguments();
+  };
+  return SuccessorBlockArgumentsListTy(getSuccessors(), op);
+}
+
 YieldInst *YieldInst::create(SILDebugLocation loc,
                              ArrayRef<SILValue> yieldedValues,
                              SILBasicBlock *normalBB, SILBasicBlock *unwindBB,
diff --git a/lib/SILGen/SILGen.cpp b/lib/SILGen/SILGen.cpp
index 41cdd8b..7072316 100644
--- a/lib/SILGen/SILGen.cpp
+++ b/lib/SILGen/SILGen.cpp
@@ -214,7 +214,9 @@
   auto &ctx = getASTContext();
   FuncDecl *found = nullptr;
   DeclName name(ctx, ctx.Id_bridgeToObjectiveC, llvm::ArrayRef<Identifier>());
-  for (auto member : proto->lookupDirect(name, true)) {
+  auto flags = OptionSet<NominalTypeDecl::LookupDirectFlags>();
+  flags |= NominalTypeDecl::LookupDirectFlags::IgnoreNewExtensions;
+  for (auto member : proto->lookupDirect(name, flags)) {
     if (auto func = dyn_cast<FuncDecl>(member)) {
       found = func;
       break;
@@ -245,7 +247,9 @@
   FuncDecl *found = nullptr;
   DeclName name(ctx, ctx.getIdentifier("_unconditionallyBridgeFromObjectiveC"),
                 llvm::makeArrayRef(Identifier()));
-  for (auto member : proto->lookupDirect(name, true)) {
+  auto flags = OptionSet<NominalTypeDecl::LookupDirectFlags>();
+  flags |= NominalTypeDecl::LookupDirectFlags::IgnoreNewExtensions;
+  for (auto member : proto->lookupDirect(name, flags)) {
     if (auto func = dyn_cast<FuncDecl>(member)) {
       found = func;
       break;
@@ -275,7 +279,9 @@
   auto &ctx = getASTContext();
   AssociatedTypeDecl *found = nullptr;
   DeclName name(ctx.Id_ObjectiveCType);
-  for (auto member : proto->lookupDirect(name, true)) {
+  auto flags = OptionSet<NominalTypeDecl::LookupDirectFlags>();
+  flags |= NominalTypeDecl::LookupDirectFlags::IgnoreNewExtensions;
+  for (auto member : proto->lookupDirect(name, flags)) {
     if (auto assocType = dyn_cast<AssociatedTypeDecl>(member)) {
       found = assocType;
       break;
@@ -325,7 +331,9 @@
   // Look for _nsError.
   auto &ctx = getASTContext();
   VarDecl *found = nullptr;
-  for (auto member : proto->lookupDirect(ctx.Id_nsError, true)) {
+  auto flags = OptionSet<NominalTypeDecl::LookupDirectFlags>();
+  flags |= NominalTypeDecl::LookupDirectFlags::IgnoreNewExtensions;
+  for (auto member : proto->lookupDirect(ctx.Id_nsError, flags)) {
     if (auto var = dyn_cast<VarDecl>(member)) {
       found = var;
       break;
diff --git a/lib/SILOptimizer/Transforms/Outliner.cpp b/lib/SILOptimizer/Transforms/Outliner.cpp
index 2f7b004..410aae8 100644
--- a/lib/SILOptimizer/Transforms/Outliner.cpp
+++ b/lib/SILOptimizer/Transforms/Outliner.cpp
@@ -145,7 +145,9 @@
   FuncDecl *Requirement = nullptr;
   // bridgeToObjectiveC
   DeclName Name(Ctx, Ctx.Id_bridgeToObjectiveC, llvm::ArrayRef<Identifier>());
-  for (auto Member : Proto->lookupDirect(Name, true)) {
+  auto flags = OptionSet<NominalTypeDecl::LookupDirectFlags>();
+  flags |= NominalTypeDecl::LookupDirectFlags::IgnoreNewExtensions;
+  for (auto Member : Proto->lookupDirect(Name, flags)) {
     if (auto Func = dyn_cast<FuncDecl>(Member)) {
       Requirement = Func;
       break;
@@ -175,7 +177,9 @@
   // _unconditionallyBridgeFromObjectiveC
   DeclName Name(Ctx, Ctx.getIdentifier("_unconditionallyBridgeFromObjectiveC"),
                 llvm::makeArrayRef(Identifier()));
-  for (auto Member : Proto->lookupDirect(Name, true)) {
+  auto flags = OptionSet<NominalTypeDecl::LookupDirectFlags>();
+  flags |= NominalTypeDecl::LookupDirectFlags::IgnoreNewExtensions;
+  for (auto Member : Proto->lookupDirect(Name, flags)) {
     if (auto Func = dyn_cast<FuncDecl>(Member)) {
       Requirement = Func;
       break;
diff --git a/lib/Sema/TypeCheckDeclOverride.cpp b/lib/Sema/TypeCheckDeclOverride.cpp
index 832210d..c2315a6 100644
--- a/lib/Sema/TypeCheckDeclOverride.cpp
+++ b/lib/Sema/TypeCheckDeclOverride.cpp
@@ -1700,9 +1700,11 @@
 
     // Look for associated types with the same name.
     bool foundAny = false;
+    auto flags = OptionSet<NominalTypeDecl::LookupDirectFlags>();
+    flags |= NominalTypeDecl::LookupDirectFlags::IgnoreNewExtensions;
     for (auto member : inheritedProto->lookupDirect(
                                               assocType->getFullName(),
-                                              /*ignoreNewExtensions=*/true)) {
+                                              flags)) {
       if (auto assocType = dyn_cast<AssociatedTypeDecl>(member)) {
         overriddenAssocTypes.push_back(assocType);
         foundAny = true;
diff --git a/lib/Sema/TypeCheckNameLookup.cpp b/lib/Sema/TypeCheckNameLookup.cpp
index 656deb9..e3a2d0a 100644
--- a/lib/Sema/TypeCheckNameLookup.cpp
+++ b/lib/Sema/TypeCheckNameLookup.cpp
@@ -376,6 +376,9 @@
   if (options.contains(NameLookupFlags::ProtocolMembers))
     subOptions |= NL_ProtocolMembers;
 
+  if (options.contains(NameLookupFlags::IncludeAttributeImplements))
+    subOptions |= NL_IncludeAttributeImplements;
+
   // We handle our own overriding/shadowing filtering.
   subOptions &= ~NL_RemoveOverridden;
   subOptions &= ~NL_RemoveNonVisible;
diff --git a/lib/Sema/TypeCheckProtocol.cpp b/lib/Sema/TypeCheckProtocol.cpp
index a518deb..39476e2 100644
--- a/lib/Sema/TypeCheckProtocol.cpp
+++ b/lib/Sema/TypeCheckProtocol.cpp
@@ -867,10 +867,49 @@
   return matchWitness(tc, dc, req, witness, setup, matchTypes, finalize);
 }
 
+static bool
+witnessHasImplementsAttrForRequiredName(ValueDecl *witness,
+                                        ValueDecl *requirement) {
+  if (auto A = witness->getAttrs().getAttribute<ImplementsAttr>()) {
+    return A->getMemberName() == requirement->getFullName();
+  }
+  return false;
+}
+
+static bool
+witnessHasImplementsAttrForExactRequirement(ValueDecl *witness,
+                                            ValueDecl *requirement) {
+  assert(requirement->isProtocolRequirement());
+  auto *PD = cast<ProtocolDecl>(requirement->getDeclContext());
+  if (auto A = witness->getAttrs().getAttribute<ImplementsAttr>()) {
+    Type T = A->getProtocolType().getType();
+    if (T->castTo<ProtocolType>()->getDecl() == PD) {
+      return A->getMemberName() == requirement->getFullName();
+    }
+  }
+  return false;
+}
+
 /// \brief Determine whether one requirement match is better than the other.
 static bool isBetterMatch(TypeChecker &tc, DeclContext *dc,
+                          ValueDecl *requirement,
                           const RequirementMatch &match1,
                           const RequirementMatch &match2) {
+
+  // Special case to prefer a witness with @_implements(Foo, bar) over one without
+  // it, when the requirement was exactly for Foo.bar.
+  bool match1ImplementsAttr =
+    witnessHasImplementsAttrForExactRequirement(match1.Witness,
+                                                requirement);
+  bool match2ImplementsAttr =
+    witnessHasImplementsAttrForExactRequirement(match2.Witness,
+                                                requirement);
+  if (match1ImplementsAttr && !match2ImplementsAttr) {
+    return true;
+  } else if (!match1ImplementsAttr && match2ImplementsAttr) {
+    return false;
+  }
+
   // Check whether one declaration is better than the other.
   switch (tc.compareDeclarations(dc, match1.Witness, match2.Witness)) {
   case Comparison::Better:
@@ -894,41 +933,19 @@
 
 WitnessChecker::WitnessChecker(TypeChecker &tc, ProtocolDecl *proto,
                                Type adoptee, DeclContext *dc)
-    : TC(tc), Proto(proto), Adoptee(adoptee), DC(dc) {
-  if (auto N = DC->getSelfNominalTypeDecl()) {
-    for (auto D : N->getMembers()) {
-      if (auto V = dyn_cast<ValueDecl>(D)) {
-        if (!V->hasName())
-          continue;
-        if (auto A = V->getAttrs().getAttribute<ImplementsAttr>()) {
-          A->getMemberName().addToLookupTable(ImplementsTable, V);
-        }
-      }
-    }
-  }
-}
+    : TC(tc), Proto(proto), Adoptee(adoptee), DC(dc) {}
 
 void
 WitnessChecker::lookupValueWitnessesViaImplementsAttr(
     ValueDecl *req, SmallVector<ValueDecl *, 4> &witnesses) {
-  if (!req->isProtocolRequirement())
-    return;
-  if (!req->hasName())
-    return;
-  auto *PD = dyn_cast<ProtocolDecl>(req->getDeclContext());
-  if (!PD)
-    return;
-  auto i = ImplementsTable.find(req->getFullName());
-  if (i == ImplementsTable.end())
-    return;
-  for (auto candidate : i->second) {
-    if (auto A = candidate->getAttrs().getAttribute<ImplementsAttr>()) {
-      Type T = A->getProtocolType().getType();
-      if (auto *PT = T->getAs<ProtocolType>()) {
-        if (PT->getDecl() == PD) {
-          witnesses.push_back(candidate);
-        }
-      }
+  auto lookupOptions = defaultMemberTypeLookupOptions;
+  lookupOptions -= NameLookupFlags::PerformConformanceCheck;
+  lookupOptions |= NameLookupFlags::IncludeAttributeImplements;
+  auto candidates = TC.lookupMember(DC, Adoptee, req->getFullName(),
+                                    lookupOptions);
+  for (auto candidate : candidates) {
+    if (witnessHasImplementsAttrForExactRequirement(candidate.getValueDecl(), req)) {
+      witnesses.push_back(candidate.getValueDecl());
     }
   }
 }
@@ -936,7 +953,8 @@
 SmallVector<ValueDecl *, 4>
 WitnessChecker::lookupValueWitnesses(ValueDecl *req, bool *ignoringNames) {
   assert(!isa<AssociatedTypeDecl>(req) && "Not for lookup for type witnesses*");
-  
+  assert(req->isProtocolRequirement());
+
   SmallVector<ValueDecl *, 4> witnesses;
 
   // Do an initial check to see if there are any @_implements remappings
@@ -1113,7 +1131,7 @@
     // Find the best match.
     bestIdx = 0;
     for (unsigned i = 1, n = matches.size(); i != n; ++i) {
-      if (isBetterMatch(TC, DC, matches[i], matches[bestIdx]))
+      if (isBetterMatch(TC, DC, requirement, matches[i], matches[bestIdx]))
         bestIdx = i;
     }
 
@@ -1122,7 +1140,7 @@
       if (i == bestIdx)
         continue;
 
-      if (!isBetterMatch(TC, DC, matches[bestIdx], matches[i])) {
+      if (!isBetterMatch(TC, DC, requirement, matches[bestIdx], matches[i])) {
         isReallyBest = false;
         break;
       }
@@ -2530,15 +2548,6 @@
   }
 }
 
-static bool
-witnessHasImplementsAttrForRequirement(ValueDecl *witness,
-                                       ValueDecl *requirement) {
-  if (auto A = witness->getAttrs().getAttribute<ImplementsAttr>()) {
-    return A->getMemberName() == requirement->getFullName();
-  }
-  return false;
-}
-
 /// Determine the given witness has a same-type constraint constraining the
 /// given 'Self' type, and return the requirement that does.
 ///
@@ -2797,7 +2806,7 @@
     // If the name didn't actually line up, complain.
     if (ignoringNames &&
         requirement->getFullName() != best.Witness->getFullName() &&
-        !witnessHasImplementsAttrForRequirement(best.Witness, requirement)) {
+        !witnessHasImplementsAttrForRequiredName(best.Witness, requirement)) {
 
       diagnoseOrDefer(requirement, false,
         [witness, requirement](NormalProtocolConformance *conformance) {
@@ -4793,9 +4802,10 @@
           continue;
 
         bool valueIsType = isa<TypeDecl>(value);
+        auto flags = OptionSet<NominalTypeDecl::LookupDirectFlags>();
+        flags |= NominalTypeDecl::LookupDirectFlags::IgnoreNewExtensions;
         for (auto requirement
-                : diag.Protocol->lookupDirect(value->getFullName(),
-                                              /*ignoreNewExtensions=*/true)) {
+                : diag.Protocol->lookupDirect(value->getFullName(), flags)) {
           auto requirementIsType = isa<TypeDecl>(requirement);
           if (valueIsType != requirementIsType)
             continue;
@@ -4991,7 +5001,9 @@
     if (!proto->isObjC()) continue;
 
     Optional<ProtocolConformance *> conformance;
-    for (auto req : proto->lookupDirect(name, true)) {
+    auto flags = OptionSet<NominalTypeDecl::LookupDirectFlags>();
+    flags |= NominalTypeDecl::LookupDirectFlags::IgnoreNewExtensions;
+    for (auto req : proto->lookupDirect(name, flags)) {
       // Skip anything in a protocol extension.
       if (req->getDeclContext() != proto) continue;
 
diff --git a/lib/Sema/TypeCheckProtocolInference.cpp b/lib/Sema/TypeCheckProtocolInference.cpp
index db5b516..b5b5a7c 100644
--- a/lib/Sema/TypeCheckProtocolInference.cpp
+++ b/lib/Sema/TypeCheckProtocolInference.cpp
@@ -418,6 +418,8 @@
     auto req = dyn_cast<ValueDecl>(member);
     if (!req)
       continue;
+    if (!req->isProtocolRequirement())
+      continue;
 
     // Infer type witnesses for associated types.
     if (auto assocType = dyn_cast<AssociatedTypeDecl>(req)) {
@@ -1076,9 +1078,10 @@
         // Find an associated type with the same name in the given
         // protocol.
         AssociatedTypeDecl *foundAssocType = nullptr;
+        auto flags = OptionSet<NominalTypeDecl::LookupDirectFlags>();
+        flags |= NominalTypeDecl::LookupDirectFlags::IgnoreNewExtensions;
         for (auto result : thisProto->lookupDirect(
-                                             assocType->getName(),
-                                             /*ignoreNewExtensions=*/true)) {
+                                             assocType->getName(), flags)) {
           foundAssocType = dyn_cast<AssociatedTypeDecl>(result);
           if (foundAssocType) break;
         }
diff --git a/lib/Sema/TypeChecker.h b/lib/Sema/TypeChecker.h
index 6d13959..537a641 100644
--- a/lib/Sema/TypeChecker.h
+++ b/lib/Sema/TypeChecker.h
@@ -299,6 +299,8 @@
   /// Whether to include results from outside the innermost scope that has a
   /// result.
   IncludeOuterResults = 0x20,
+  /// Whether to consider synonyms declared through @_implements().
+  IncludeAttributeImplements = 0x40,
 };
 
 /// A set of options that control name lookup.
diff --git a/lib/Serialization/Serialization.cpp b/lib/Serialization/Serialization.cpp
index 92b07f5..66013ce 100644
--- a/lib/Serialization/Serialization.cpp
+++ b/lib/Serialization/Serialization.cpp
@@ -1814,6 +1814,16 @@
         (*memberTable)[parentID].push_back(memberID);
       }
 
+      // Same as above, but for @_implements attributes
+      if (auto A = VD->getAttrs().getAttribute<ImplementsAttr>()) {
+        std::unique_ptr<DeclMembersTable> &memberTable =
+          DeclMemberNames[A->getMemberName().getBaseName()].second;
+        if (!memberTable) {
+          memberTable = llvm::make_unique<DeclMembersTable>();
+        }
+        (*memberTable)[parentID].push_back(memberID);
+      }
+
       // Possibly add a record to ClassMembersForDynamicLookup too.
       if (isClass) {
         if (VD->canBeAccessedByDynamicLookup()) {
diff --git a/stdlib/public/SDK/Foundation/Measurement.swift b/stdlib/public/SDK/Foundation/Measurement.swift
index 320bf9e..72513aa 100644
--- a/stdlib/public/SDK/Foundation/Measurement.swift
+++ b/stdlib/public/SDK/Foundation/Measurement.swift
@@ -206,9 +206,15 @@
 
 // Implementation note: similar to NSArray, NSDictionary, etc., NSMeasurement's import as an ObjC generic type is suppressed by the importer. Eventually we will need a more general purpose mechanism to correctly import generic types.
 
+// FIXME: Remove @usableFromInline from MeasurementBridgeType once
+// rdar://problem/44662501 is fixed. (The Radar basically just says "look
+// through typealiases and inherited protocols when printing extensions".)
+
 #if DEPLOYMENT_RUNTIME_SWIFT
+@usableFromInline
 internal typealias MeasurementBridgeType = _ObjectTypeBridgeable
 #else
+@usableFromInline
 internal typealias MeasurementBridgeType = _ObjectiveCBridgeable
 #endif
 
diff --git a/stdlib/public/SwiftShims/HeapObject.h b/stdlib/public/SwiftShims/HeapObject.h
index cbc1309..97ccbc4 100644
--- a/stdlib/public/SwiftShims/HeapObject.h
+++ b/stdlib/public/SwiftShims/HeapObject.h
@@ -122,7 +122,7 @@
 #define _swift_abi_ObjCReservedLowBits                                         \
   (unsigned) SWIFT_ABI_X86_64_OBJC_NUM_RESERVED_LOW_BITS
 
-#elif defined(__arm64__)
+#elif defined(__arm64__) || defined(__aarch64__) || defined(_M_ARM64)
 
 #ifdef __APPLE__
 #define _swift_abi_LeastValidPointerValue                                      \
@@ -165,10 +165,10 @@
 #define _swift_abi_LeastValidPointerValue                                      \
   (__swift_uintptr_t) SWIFT_ABI_DEFAULT_LEAST_VALID_POINTER
 
-#if __i386__
+#if defined(__i386__)
 #define _swift_abi_SwiftSpareBitsMask                                          \
   (__swift_uintptr_t) SWIFT_ABI_I386_SWIFT_SPARE_BITS_MASK
-#elif __arm__
+#elif defined(__arm__) || defined(_M_ARM)
 #define _swift_abi_SwiftSpareBitsMask                                          \
   (__swift_uintptr_t) SWIFT_ABI_ARM_SWIFT_SPARE_BITS_MASK
 #else
diff --git a/stdlib/public/core/Algorithm.swift b/stdlib/public/core/Algorithm.swift
index a7f1c47..cbc3bfb 100644
--- a/stdlib/public/core/Algorithm.swift
+++ b/stdlib/public/core/Algorithm.swift
@@ -154,7 +154,7 @@
 extension EnumeratedSequence: Sequence {
   /// Returns an iterator over the elements of this sequence.
   @inlinable
-  public func makeIterator() -> Iterator {
+  public __consuming func makeIterator() -> Iterator {
     return Iterator(_base: _base.makeIterator())
   }
 }
diff --git a/stdlib/public/core/Array.swift b/stdlib/public/core/Array.swift
index fb99047..1849a22 100644
--- a/stdlib/public/core/Array.swift
+++ b/stdlib/public/core/Array.swift
@@ -1084,7 +1084,7 @@
   @_semantics("array.mutate_unknown")
   internal mutating func _appendElementAssumeUniqueAndCapacity(
     _ oldCount: Int,
-    newElement: Element
+    newElement: __owned Element
   ) {
     _sanityCheck(_buffer.isMutableAndUniquelyReferenced())
     _sanityCheck(_buffer.capacity >= _buffer.count + 1)
@@ -1116,7 +1116,7 @@
   ///   same array.
   @inlinable
   @_semantics("array.append_element")
-  public mutating func append(_ newElement: Element) {
+  public mutating func append(_ newElement: __owned Element) {
     _makeUniqueAndReserveCapacityIfNotUnique()
     let oldCount = _getCount()
     _reserveCapacityAssumingUniqueBuffer(oldCount: oldCount)
@@ -1141,7 +1141,7 @@
   ///   array.
   @inlinable
   @_semantics("array.append_contentsOf")
-  public mutating func append<S: Sequence>(contentsOf newElements: S)
+  public mutating func append<S: Sequence>(contentsOf newElements: __owned S)
     where S.Element == Element {
 
     let newElementsCount = newElements.underestimatedCount
@@ -1246,7 +1246,7 @@
   /// - Complexity: O(*n*), where *n* is the length of the array. If
   ///   `i == endIndex`, this method is equivalent to `append(_:)`.
   @inlinable
-  public mutating func insert(_ newElement: Element, at i: Int) {
+  public mutating func insert(_ newElement: __owned Element, at i: Int) {
     _checkIndex(i)
     self.replaceSubrange(i..<i, with: CollectionOfOne(newElement))
   }
@@ -1561,7 +1561,7 @@
   @_semantics("array.mutate_unknown")
   public mutating func replaceSubrange<C>(
     _ subrange: Range<Int>,
-    with newElements: C
+    with newElements: __owned C
   ) where C: Collection, C.Element == Element {
     _precondition(subrange.lowerBound >= self._buffer.startIndex,
       "Array replace: subrange start is negative")
diff --git a/stdlib/public/core/ArrayBuffer.swift b/stdlib/public/core/ArrayBuffer.swift
index 00183b5..94e32cb 100644
--- a/stdlib/public/core/ArrayBuffer.swift
+++ b/stdlib/public/core/ArrayBuffer.swift
@@ -43,7 +43,7 @@
   /// - Precondition: The elements actually have dynamic type `U`, and `U`
   ///   is a class or `@objc` existential.
   @inlinable
-  internal func cast<U>(toBufferOf _: U.Type) -> _ArrayBuffer<U> {
+  __consuming internal func cast<U>(toBufferOf _: U.Type) -> _ArrayBuffer<U> {
     _sanityCheck(_isClassOrObjCExistential(Element.self))
     _sanityCheck(_isClassOrObjCExistential(U.self))
     return _ArrayBuffer<U>(storage: _storage)
@@ -60,7 +60,7 @@
   /// - Precondition: `U` is a class or `@objc` existential derived from
   /// `Element`.
   @inlinable
-  internal func downcast<U>(
+  __consuming internal func downcast<U>(
     toBufferWithDeferredTypeCheckOf _: U.Type
   ) -> _ArrayBuffer<U> {
     _sanityCheck(_isClassOrObjCExistential(Element.self))
@@ -214,7 +214,7 @@
   /// just-initialized memory.
   @inlinable
   @discardableResult
-  internal func _copyContents(
+  __consuming internal func _copyContents(
     subRange bounds: Range<Int>,
     initializing target: UnsafeMutablePointer<Element>
   ) -> UnsafeMutablePointer<Element> {
diff --git a/stdlib/public/core/ArrayBufferProtocol.swift b/stdlib/public/core/ArrayBufferProtocol.swift
index d4caef1..65f82bc 100644
--- a/stdlib/public/core/ArrayBufferProtocol.swift
+++ b/stdlib/public/core/ArrayBufferProtocol.swift
@@ -30,7 +30,7 @@
   /// memory starting at `target`.  Return a pointer "past the end" of the
   /// just-initialized memory.
   @discardableResult
-  func _copyContents(
+  __consuming func _copyContents(
     subRange bounds: Range<Int>,
     initializing target: UnsafeMutablePointer<Element>
   ) -> UnsafeMutablePointer<Element>
@@ -74,7 +74,7 @@
   mutating func replaceSubrange<C>(
     _ subrange: Range<Int>,
     with newCount: Int,
-    elementsOf newValues: C
+    elementsOf newValues: __owned C
   ) where C : Collection, C.Element == Element
 
   /// Returns a `_SliceBuffer` containing the elements in `bounds`.
@@ -149,7 +149,7 @@
   internal mutating func replaceSubrange<C>(
     _ subrange: Range<Int>,
     with newCount: Int,
-    elementsOf newValues: C
+    elementsOf newValues: __owned C
   ) where C : Collection, C.Element == Element {
     _sanityCheck(startIndex == 0, "_SliceBuffer should override this function.")
     let oldCount = self.count
diff --git a/stdlib/public/core/ArrayShared.swift b/stdlib/public/core/ArrayShared.swift
index bd8ff3e..b49a802 100644
--- a/stdlib/public/core/ArrayShared.swift
+++ b/stdlib/public/core/ArrayShared.swift
@@ -88,7 +88,7 @@
   @inline(never)
   internal mutating func _arrayOutOfPlaceReplace<C: Collection>(
     _ bounds: Range<Int>,
-    with newValues: C,
+    with newValues: __owned C,
     count insertCount: Int
   ) where C.Element == Element {
 
@@ -285,7 +285,7 @@
   /// Append items from `newItems` to a buffer.
   @inlinable
   internal mutating func _arrayAppendSequence<S: Sequence>(
-    _ newItems: S
+    _ newItems: __owned S
   ) where S.Element == Element {
     
     // this function is only ever called from append(contentsOf:)
diff --git a/stdlib/public/core/ArraySlice.swift b/stdlib/public/core/ArraySlice.swift
index db6a11c..9e77894 100644
--- a/stdlib/public/core/ArraySlice.swift
+++ b/stdlib/public/core/ArraySlice.swift
@@ -903,7 +903,7 @@
   @_semantics("array.mutate_unknown")
   internal mutating func _appendElementAssumeUniqueAndCapacity(
     _ oldCount: Int,
-    newElement: Element
+    newElement: __owned Element
   ) {
     _sanityCheck(_buffer.isMutableAndUniquelyReferenced())
     _sanityCheck(_buffer.capacity >= _buffer.count + 1)
@@ -935,7 +935,7 @@
   ///   same array.
   @inlinable
   @_semantics("array.append_element")
-  public mutating func append(_ newElement: Element) {
+  public mutating func append(_ newElement: __owned Element) {
     _makeUniqueAndReserveCapacityIfNotUnique()
     let oldCount = _getCount()
     _reserveCapacityAssumingUniqueBuffer(oldCount: oldCount)
@@ -960,7 +960,7 @@
   ///   array.
   @inlinable
   @_semantics("array.append_contentsOf")
-  public mutating func append<S: Sequence>(contentsOf newElements: S)
+  public mutating func append<S: Sequence>(contentsOf newElements: __owned S)
     where S.Element == Element {
 
     let newElementsCount = newElements.underestimatedCount
@@ -1065,7 +1065,7 @@
   /// - Complexity: O(*n*), where *n* is the length of the array. If
   ///   `i == endIndex`, this method is equivalent to `append(_:)`.
   @inlinable
-  public mutating func insert(_ newElement: Element, at i: Int) {
+  public mutating func insert(_ newElement: __owned Element, at i: Int) {
     _checkIndex(i)
     self.replaceSubrange(i..<i, with: CollectionOfOne(newElement))
   }
@@ -1100,7 +1100,7 @@
   }
 
   @inlinable
-  public func _copyToContiguousArray() -> ContiguousArray<Element> {
+  public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {
     if let n = _buffer.requestNativeBuffer() {
       return ContiguousArray(_buffer: n)
     }
@@ -1260,7 +1260,7 @@
   }
 
   @inlinable
-  public func _copyContents(
+  public __consuming func _copyContents(
     initializing buffer: UnsafeMutableBufferPointer<Element>
   ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) {
 
@@ -1330,7 +1330,7 @@
   @_semantics("array.mutate_unknown")
   public mutating func replaceSubrange<C>(
     _ subrange: Range<Int>,
-    with newElements: C
+    with newElements: __owned C
   ) where C: Collection, C.Element == Element {
     _precondition(subrange.lowerBound >= _buffer.startIndex,
       "ArraySlice replace: subrange start is before the startIndex")
diff --git a/stdlib/public/core/ArrayType.swift b/stdlib/public/core/ArrayType.swift
index dfaf336..d102bc7 100644
--- a/stdlib/public/core/ArrayType.swift
+++ b/stdlib/public/core/ArrayType.swift
@@ -51,7 +51,7 @@
   /// - Complexity: O(`self.count`).
   ///
   /// - Precondition: `startIndex <= i`, `i <= endIndex`.
-  mutating func insert(_ newElement: Element, at i: Int)
+  mutating func insert(_ newElement: __owned Element, at i: Int)
 
   /// Remove and return the element at the given index.
   ///
@@ -77,7 +77,7 @@
   // efficient, we should make the default implementation coming from Sequence
   // preferred.
   @inlinable
-  public func filter(
+  public __consuming func filter(
     _ isIncluded: (Element) throws -> Bool
   ) rethrows -> [Element] {
     return try _filter(isIncluded)
diff --git a/stdlib/public/core/BidirectionalCollection.swift b/stdlib/public/core/BidirectionalCollection.swift
index 012ea66..c3c24bc 100644
--- a/stdlib/public/core/BidirectionalCollection.swift
+++ b/stdlib/public/core/BidirectionalCollection.swift
@@ -382,7 +382,7 @@
   ///   `RandomAccessCollection`; otherwise, O(*k*), where *k* is the number of
   ///   elements to drop.
   @inlinable // protocol-only
-  public func dropLast(_ k: Int) -> SubSequence {
+  public __consuming func dropLast(_ k: Int) -> SubSequence {
     _precondition(
       k >= 0, "Can't drop a negative number of elements from a collection")
     let end = index(
@@ -413,7 +413,7 @@
   ///   `RandomAccessCollection`; otherwise, O(*k*), where *k* is equal to
   ///   `maxLength`.
   @inlinable // protocol-only
-  public func suffix(_ maxLength: Int) -> SubSequence {
+  public __consuming func suffix(_ maxLength: Int) -> SubSequence {
     _precondition(
       maxLength >= 0,
       "Can't take a suffix of negative length from a collection")
diff --git a/stdlib/public/core/CharacterUnicodeScalars.swift b/stdlib/public/core/CharacterUnicodeScalars.swift
index 46aa0a5..3d3c521 100644
--- a/stdlib/public/core/CharacterUnicodeScalars.swift
+++ b/stdlib/public/core/CharacterUnicodeScalars.swift
@@ -49,7 +49,7 @@
 
 extension Character.UnicodeScalarView : Sequence {
   @inlinable // FIXME(sil-serialize-all)
-  public func makeIterator() -> Iterator {
+  public __consuming func makeIterator() -> Iterator {
     return Iterator(_base: IndexingIterator(_elements: self))
   }
 }
diff --git a/stdlib/public/core/Collection.swift b/stdlib/public/core/Collection.swift
index 308dc6a..f9dac4d 100644
--- a/stdlib/public/core/Collection.swift
+++ b/stdlib/public/core/Collection.swift
@@ -1120,7 +1120,7 @@
   /// Returns an iterator over the elements of the collection.
   @inlinable // trivial-implementation
   @inline(__always)
-  public func makeIterator() -> IndexingIterator<Self> {
+  public __consuming func makeIterator() -> IndexingIterator<Self> {
     return IndexingIterator(_elements: self)
   }
 }
@@ -1356,7 +1356,7 @@
   ///   `RandomAccessCollection`; otherwise, O(*k*), where *k* is the number of
   ///   elements to drop from the beginning of the collection.
   @inlinable
-  public func dropFirst(_ k: Int) -> SubSequence {
+  public __consuming func dropFirst(_ k: Int) -> SubSequence {
     _precondition(k >= 0, "Can't drop a negative number of elements from a collection")
     let start = index(startIndex,
       offsetBy: k, limitedBy: endIndex) ?? endIndex
@@ -1384,7 +1384,7 @@
   ///   `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length of
   ///   the collection.
   @inlinable
-  public func dropLast(_ k: Int) -> SubSequence {
+  public __consuming func dropLast(_ k: Int) -> SubSequence {
     _precondition(
       k >= 0, "Can't drop a negative number of elements from a collection")
     let amount = Swift.max(0, count - k)
@@ -1403,7 +1403,7 @@
   ///
   /// - Complexity: O(*n*), where *n* is the length of the collection.
   @inlinable
-  public func drop(
+  public __consuming func drop(
     while predicate: (Element) throws -> Bool
   ) rethrows -> SubSequence {
     var start = startIndex
@@ -1434,7 +1434,7 @@
   ///   `RandomAccessCollection`; otherwise, O(*k*), where *k* is the number of
   ///   elements to select from the beginning of the collection.
   @inlinable
-  public func prefix(_ maxLength: Int) -> SubSequence {
+  public __consuming func prefix(_ maxLength: Int) -> SubSequence {
     _precondition(
       maxLength >= 0,
       "Can't take a prefix of negative length from a collection")
@@ -1453,7 +1453,7 @@
   ///
   /// - Complexity: O(*n*), where *n* is the length of the collection.
   @inlinable
-  public func prefix(
+  public __consuming func prefix(
     while predicate: (Element) throws -> Bool
   ) rethrows -> SubSequence {
     var end = startIndex
@@ -1484,7 +1484,7 @@
   ///   `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length of
   ///   the collection.
   @inlinable
-  public func suffix(_ maxLength: Int) -> SubSequence {
+  public __consuming func suffix(_ maxLength: Int) -> SubSequence {
     _precondition(
       maxLength >= 0,
       "Can't take a suffix of negative length from a collection")
@@ -1529,7 +1529,7 @@
   ///
   /// - Complexity: O(1)
   @inlinable
-  public func prefix(upTo end: Index) -> SubSequence {
+  public __consuming func prefix(upTo end: Index) -> SubSequence {
     return self[startIndex..<end]
   }
 
@@ -1567,7 +1567,7 @@
   ///
   /// - Complexity: O(1)
   @inlinable
-  public func suffix(from start: Index) -> SubSequence {
+  public __consuming func suffix(from start: Index) -> SubSequence {
     return self[start..<endIndex]
   }
 
@@ -1601,7 +1601,7 @@
   ///
   /// - Complexity: O(1)
   @inlinable
-  public func prefix(through position: Index) -> SubSequence {
+  public __consuming func prefix(through position: Index) -> SubSequence {
     return prefix(upTo: index(after: position))
   }
 
@@ -1654,7 +1654,7 @@
   ///
   /// - Complexity: O(*n*), where *n* is the length of the collection.
   @inlinable
-  public func split(
+  public __consuming func split(
     maxSplits: Int = Int.max,
     omittingEmptySubsequences: Bool = true,
     whereSeparator isSeparator: (Element) throws -> Bool
@@ -1749,7 +1749,7 @@
   ///
   /// - Complexity: O(*n*), where *n* is the length of the collection.
   @inlinable
-  public func split(
+  public __consuming func split(
     separator: Element,
     maxSplits: Int = Int.max,
     omittingEmptySubsequences: Bool = true
diff --git a/stdlib/public/core/CollectionOfOne.swift b/stdlib/public/core/CollectionOfOne.swift
index 2192608..574d709 100644
--- a/stdlib/public/core/CollectionOfOne.swift
+++ b/stdlib/public/core/CollectionOfOne.swift
@@ -117,7 +117,7 @@
   ///
   /// - Complexity: O(1)
   @inlinable // trivial-implementation
-  public func makeIterator() -> Iterator {
+  public __consuming func makeIterator() -> Iterator {
     return Iterator(_elements: _element)
   }
 
diff --git a/stdlib/public/core/ContiguousArray.swift b/stdlib/public/core/ContiguousArray.swift
index 271b530..1dad2cc 100644
--- a/stdlib/public/core/ContiguousArray.swift
+++ b/stdlib/public/core/ContiguousArray.swift
@@ -729,7 +729,7 @@
   @_semantics("array.mutate_unknown")
   internal mutating func _appendElementAssumeUniqueAndCapacity(
     _ oldCount: Int,
-    newElement: Element
+    newElement: __owned Element
   ) {
     _sanityCheck(_buffer.isMutableAndUniquelyReferenced())
     _sanityCheck(_buffer.capacity >= _buffer.count + 1)
@@ -891,7 +891,7 @@
   /// - Complexity: O(*n*), where *n* is the length of the array. If
   ///   `i == endIndex`, this method is equivalent to `append(_:)`.
   @inlinable
-  public mutating func insert(_ newElement: Element, at i: Int) {
+  public mutating func insert(_ newElement: __owned Element, at i: Int) {
     _checkIndex(i)
     self.replaceSubrange(i..<i, with: CollectionOfOne(newElement))
   }
@@ -926,7 +926,7 @@
   }
 
   @inlinable
-  public func _copyToContiguousArray() -> ContiguousArray<Element> {
+  public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {
     if let n = _buffer.requestNativeBuffer() {
       return ContiguousArray(_buffer: n)
     }
@@ -1086,7 +1086,7 @@
   }
 
   @inlinable
-  public func _copyContents(
+  public __consuming func _copyContents(
     initializing buffer: UnsafeMutableBufferPointer<Element>
   ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) {
 
@@ -1157,7 +1157,7 @@
   @_semantics("array.mutate_unknown")
   public mutating func replaceSubrange<C>(
     _ subrange: Range<Int>,
-    with newElements: C
+    with newElements: __owned C
   ) where C: Collection, C.Element == Element {
     _precondition(subrange.lowerBound >= self._buffer.startIndex,
       "ContiguousArray replace: subrange start is negative")
diff --git a/stdlib/public/core/Dictionary.swift b/stdlib/public/core/Dictionary.swift
index 06ebe29..d22c803 100644
--- a/stdlib/public/core/Dictionary.swift
+++ b/stdlib/public/core/Dictionary.swift
@@ -588,7 +588,7 @@
   /// - Returns: A dictionary of the key-value pairs that `isIncluded` allows.
   @inlinable
   @available(swift, introduced: 4.0)
-  public func filter(
+  public __consuming func filter(
     _ isIncluded: (Element) throws -> Bool
   ) rethrows -> [Key: Value] {
     var result = Dictionary()
diff --git a/stdlib/public/core/DropWhile.swift b/stdlib/public/core/DropWhile.swift
index d8ce1d9..0eb95b4 100644
--- a/stdlib/public/core/DropWhile.swift
+++ b/stdlib/public/core/DropWhile.swift
@@ -84,7 +84,7 @@
   ///
   /// - Complexity: O(1).
   @inlinable // lazy-performance
-  public func makeIterator() -> Iterator {
+  public __consuming func makeIterator() -> Iterator {
     return Iterator(_base: _base.makeIterator(), predicate: _predicate)
   }
 }
@@ -102,7 +102,7 @@
   ///   `false` otherwise. Once `predicate` returns `false` it will not be
   ///   called again.
   @inlinable // lazy-performance
-  public func drop(
+  public __consuming func drop(
     while predicate: @escaping (Elements.Element) -> Bool
   ) -> LazyDropWhileSequence<Self.Elements> {
     return LazyDropWhileSequence(_base: self.elements, predicate: predicate)
@@ -142,7 +142,7 @@
   ///
   /// - Complexity: O(1).
   @inlinable // lazy-performance
-  public func makeIterator() -> Iterator {
+  public __consuming func makeIterator() -> Iterator {
     return Iterator(_base: _base.makeIterator(), predicate: _predicate)
   }
 }
@@ -248,7 +248,7 @@
   ///   `false` otherwise. Once `predicate` returns `false` it will not be
   ///   called again.
   @inlinable // lazy-performance
-  public func drop(
+  public __consuming func drop(
     while predicate: @escaping (Elements.Element) -> Bool
   ) -> LazyDropWhileCollection<Self.Elements> {
     return LazyDropWhileCollection(
diff --git a/stdlib/public/core/ExistentialCollection.swift.gyb b/stdlib/public/core/ExistentialCollection.swift.gyb
index 869afeb..30529ab 100644
--- a/stdlib/public/core/ExistentialCollection.swift.gyb
+++ b/stdlib/public/core/ExistentialCollection.swift.gyb
@@ -334,9 +334,9 @@
   /*
   var _indices: Indices
 
-  func prefix(upTo end: Index) -> SubSequence
+  __consuming func prefix(upTo end: Index) -> SubSequence
 
-  func suffix(from start: Index) -> SubSequence
+  __consuming func suffix(from start: Index) -> SubSequence
 
   func prefix(through position: Index) -> SubSequence
 
@@ -714,7 +714,7 @@
 %   end
   @inline(__always)
   @inlinable
-  public func makeIterator() -> Iterator {
+  public __consuming func makeIterator() -> Iterator {
     return _box._makeIterator()
   }
 
@@ -731,55 +731,55 @@
   }
 
   @inlinable
-  public func filter(
+  public __consuming func filter(
     _ isIncluded: (Element) throws -> Bool
   ) rethrows -> [Element] {
     return try _box._filter(isIncluded)
   }
 
   @inlinable
-  public func forEach(
+  public __consuming func forEach(
     _ body: (Element) throws -> Void
   ) rethrows {
     return try _box._forEach(body)
   }
 
   @inlinable
-  public func drop(
+  public __consuming func drop(
     while predicate: (Element) throws -> Bool
   ) rethrows -> Any${Kind}<Element> {
     return try Any${Kind}(_box: _box._drop(while: predicate))
   }
 
   @inlinable
-  public func dropFirst(_ n: Int) -> Any${Kind}<Element> {
+  public __consuming func dropFirst(_ n: Int) -> Any${Kind}<Element> {
     return Any${Kind}(_box: _box._dropFirst(n))
   }
 
   @inlinable
-  public func dropLast(_ n: Int) -> Any${Kind}<Element> {
+  public __consuming func dropLast(_ n: Int) -> Any${Kind}<Element> {
     return Any${Kind}(_box: _box._dropLast(n))
   }
 
   @inlinable
-  public func prefix(
+  public __consuming func prefix(
     while predicate: (Element) throws -> Bool
   ) rethrows -> Any${Kind}<Element> {
     return try Any${Kind}(_box: _box._prefix(while: predicate))
   }
 
   @inlinable
-  public func prefix(_ maxLength: Int) -> Any${Kind}<Element> {
+  public __consuming func prefix(_ maxLength: Int) -> Any${Kind}<Element> {
     return Any${Kind}(_box: _box._prefix(maxLength))
   }
 
   @inlinable
-  public func suffix(_ maxLength: Int) -> Any${Kind}<Element> {
+  public __consuming func suffix(_ maxLength: Int) -> Any${Kind}<Element> {
     return Any${Kind}(_box: _box._suffix(maxLength))
   }
 
   @inlinable
-  public func split(
+  public __consuming func split(
     maxSplits: Int = Int.max,
     omittingEmptySubsequences: Bool = true,
     whereSeparator isSeparator: (Element) throws -> Bool
diff --git a/stdlib/public/core/Filter.swift b/stdlib/public/core/Filter.swift
index c630af2..b995e8e 100644
--- a/stdlib/public/core/Filter.swift
+++ b/stdlib/public/core/Filter.swift
@@ -89,7 +89,7 @@
   ///
   /// - Complexity: O(1).
   @inlinable // lazy-performance
-  public func makeIterator() -> Iterator {
+  public __consuming func makeIterator() -> Iterator {
     return Iterator(_base: _base.makeIterator(), _predicate)
   }
 
@@ -153,7 +153,7 @@
   ///
   /// - Complexity: O(1).
   @inlinable // lazy-performance
-  public func makeIterator() -> Iterator {
+  public __consuming func makeIterator() -> Iterator {
     return Iterator(_base: _base.makeIterator(), _predicate)
   }
 
@@ -365,7 +365,7 @@
   ///   traversal step invokes `predicate` on one or more underlying
   ///   elements.
   @inlinable // lazy-performance
-  public func filter(
+  public __consuming func filter(
     _ isIncluded: @escaping (Elements.Element) -> Bool
   ) -> LazyFilterSequence<Self.Elements> {
     return LazyFilterSequence(_base: self.elements, isIncluded)
@@ -380,7 +380,7 @@
   ///   traversal step invokes `predicate` on one or more underlying
   ///   elements.
   @inlinable // lazy-performance
-  public func filter(
+  public __consuming func filter(
     _ isIncluded: @escaping (Elements.Element) -> Bool
   ) -> LazyFilterCollection<Self.Elements> {
     return LazyFilterCollection(_base: self.elements, isIncluded)
@@ -389,7 +389,7 @@
 
 extension LazyFilterSequence {
   @available(swift, introduced: 5)
-  public func filter(
+  public __consuming func filter(
     _ isIncluded: @escaping (Element) -> Bool
   ) -> LazyFilterSequence<Base> {
     return LazyFilterSequence(_base: _base) {
@@ -400,7 +400,7 @@
 
 extension LazyFilterCollection {
   @available(swift, introduced: 5)
-  public func filter(
+  public __consuming func filter(
     _ isIncluded: @escaping (Element) -> Bool
   ) -> LazyFilterCollection<Base> {
     return LazyFilterCollection(_base: _base) {
diff --git a/stdlib/public/core/Flatten.swift b/stdlib/public/core/Flatten.swift
index d9e4f5c..11c401c 100644
--- a/stdlib/public/core/Flatten.swift
+++ b/stdlib/public/core/Flatten.swift
@@ -92,7 +92,7 @@
   ///
   /// - Complexity: O(1).
   @inlinable // lazy-performance
-  public func makeIterator() -> Iterator {
+  public __consuming func makeIterator() -> Iterator {
     return Iterator(_base: _base.makeIterator())
   }
 }
@@ -122,7 +122,7 @@
   /// - Returns: A flattened view of the elements of this
   ///   sequence of sequences.
   @inlinable // lazy-performance
-  public func joined() -> FlattenSequence<Self> {
+  public __consuming func joined() -> FlattenSequence<Self> {
     return FlattenSequence(_base: self)
   }
 }
@@ -131,7 +131,7 @@
   /// Returns a lazy sequence that concatenates the elements of this sequence of
   /// sequences.
   @inlinable // lazy-performance
-  public func joined() -> LazySequence<FlattenSequence<Elements>> {
+  public __consuming func joined() -> LazySequence<FlattenSequence<Elements>> {
     return FlattenSequence(_base: elements).lazy
   }
 }
@@ -251,7 +251,7 @@
   ///
   /// - Complexity: O(1).
   @inlinable // lazy-performance
-  public func makeIterator() -> Iterator {
+  public __consuming func makeIterator() -> Iterator {
     return Iterator(_base: _base.makeIterator())
   }
 
@@ -514,7 +514,7 @@
   /// - Returns: A flattened view of the elements of this
   ///   collection of collections.
   @inlinable // lazy-performance
-  public func joined() -> FlattenCollection<Self> {
+  public __consuming func joined() -> FlattenCollection<Self> {
     return FlattenCollection(self)
   }
 }
@@ -523,7 +523,7 @@
   where Self : Collection, Element : Collection {
   /// A concatenation of the elements of `self`.
   @inlinable // lazy-performance
-  public func joined() -> LazyCollection<FlattenCollection<Elements>> {
+  public __consuming func joined() -> LazyCollection<FlattenCollection<Elements>> {
     return FlattenCollection(elements).lazy
   }
 }
diff --git a/stdlib/public/core/Join.swift b/stdlib/public/core/Join.swift
index f6001c0..d66253e 100644
--- a/stdlib/public/core/Join.swift
+++ b/stdlib/public/core/Join.swift
@@ -126,7 +126,7 @@
   ///
   /// - Complexity: O(1).
   @inlinable // lazy-performance
-  public func makeIterator() -> Iterator {
+  public __consuming func makeIterator() -> Iterator {
     return Iterator(base: _base.makeIterator(), separator: _separator)
   }
 
@@ -184,7 +184,7 @@
   ///   sequence's elements.
   /// - Returns: The joined sequence of elements.
   @inlinable // lazy-performance
-  public func joined<Separator : Sequence>(
+  public __consuming func joined<Separator : Sequence>(
     separator: Separator
   ) -> JoinedSequence<Self>
     where Separator.Element == Element.Element {
diff --git a/stdlib/public/core/LazyCollection.swift b/stdlib/public/core/LazyCollection.swift
index 6da1545..cac5fc3 100644
--- a/stdlib/public/core/LazyCollection.swift
+++ b/stdlib/public/core/LazyCollection.swift
@@ -79,7 +79,7 @@
   ///
   /// - Complexity: O(1).
   @inlinable
-  public func makeIterator() -> Iterator {
+  public __consuming func makeIterator() -> Iterator {
     return _base.makeIterator()
   }
 
diff --git a/stdlib/public/core/Map.swift b/stdlib/public/core/Map.swift
index 9ca87ec..8c2da07 100644
--- a/stdlib/public/core/Map.swift
+++ b/stdlib/public/core/Map.swift
@@ -74,7 +74,7 @@
   ///
   /// - Complexity: O(1).
   @inlinable
-  public func makeIterator() -> Iterator {
+  public __consuming func makeIterator() -> Iterator {
     return Iterator(_base: _base.makeIterator(), _transform: _transform)
   }
 
@@ -119,7 +119,7 @@
   ///
   /// - Complexity: O(1).
   @inlinable
-  public func makeIterator() -> Iterator {
+  public __consuming func makeIterator() -> Iterator {
     return Iterator(_base: _base.makeIterator(), _transform: _transform)
   }
 
diff --git a/stdlib/public/core/MigrationSupport.swift b/stdlib/public/core/MigrationSupport.swift
index b11e7c4..7d82e48 100644
--- a/stdlib/public/core/MigrationSupport.swift
+++ b/stdlib/public/core/MigrationSupport.swift
@@ -1173,7 +1173,7 @@
   }
 
   @available(swift, obsoleted: 4.0)
-  public func filter(
+  public __consuming func filter(
     _ isIncluded: (Element) throws -> Bool, obsoletedInSwift4: () = ()
   ) rethrows -> [Element] {
     var result: [Element] = []
@@ -1188,7 +1188,7 @@
 
 extension Set {
   @available(swift, obsoleted: 4.0)
-  public func filter(
+  public __consuming func filter(
     _ isIncluded: (Element) throws -> Bool, obsoletedInSwift4: () = ()
   ) rethrows -> [Element] {
     var result: [Element] = []
diff --git a/stdlib/public/core/PrefixWhile.swift b/stdlib/public/core/PrefixWhile.swift
index 3304c60..d89e5d1 100644
--- a/stdlib/public/core/PrefixWhile.swift
+++ b/stdlib/public/core/PrefixWhile.swift
@@ -75,7 +75,7 @@
   public typealias SubSequence = AnySequence<Element> // >:(
   
   @inlinable // lazy-performance
-  public func makeIterator() -> Iterator {
+  public __consuming func makeIterator() -> Iterator {
     return Iterator(_base: _base.makeIterator(), predicate: _predicate)
   }
 }
@@ -93,7 +93,7 @@
   ///   `false` otherwise. Once `predicate` returns `false` it will not be
   ///   called again.
   @inlinable // lazy-performance
-  public func prefix(
+  public __consuming func prefix(
     while predicate: @escaping (Elements.Element) -> Bool
   ) -> LazyPrefixWhileSequence<Self.Elements> {
     return LazyPrefixWhileSequence(_base: self.elements, predicate: predicate)
@@ -130,7 +130,7 @@
   public typealias Iterator = LazyPrefixWhileSequence<Base>.Iterator
   
   @inlinable // lazy-performance
-  public func makeIterator() -> Iterator {
+  public __consuming func makeIterator() -> Iterator {
     return Iterator(_base: _base.makeIterator(), predicate: _predicate)
   }
 }
@@ -304,7 +304,7 @@
   ///   or `false` otherwise. Once `predicate` returns `false` it will not be
   ///   called again.
   @inlinable // lazy-performance
-  public func prefix(
+  public __consuming func prefix(
     while predicate: @escaping (Element) -> Bool
   ) -> LazyPrefixWhileCollection<Elements> {
     return LazyPrefixWhileCollection(
diff --git a/stdlib/public/core/Range.swift b/stdlib/public/core/Range.swift
index 0643af6..25bc133 100644
--- a/stdlib/public/core/Range.swift
+++ b/stdlib/public/core/Range.swift
@@ -619,7 +619,7 @@
 
   /// Returns an iterator for this sequence.
   @inlinable
-  public func makeIterator() -> Iterator { 
+  public __consuming func makeIterator() -> Iterator { 
     return Iterator(_current: lowerBound) 
   }
 }
diff --git a/stdlib/public/core/RangeReplaceableCollection.swift b/stdlib/public/core/RangeReplaceableCollection.swift
index 64e2a15..282f7c3 100644
--- a/stdlib/public/core/RangeReplaceableCollection.swift
+++ b/stdlib/public/core/RangeReplaceableCollection.swift
@@ -109,7 +109,7 @@
   ///   equivalent to `append(contentsOf:)`.
   mutating func replaceSubrange<C>(
     _ subrange: Range<Index>,
-    with newElements: C
+    with newElements: __owned C
   ) where C : Collection, C.Element == Element
 
   /// Prepares the collection to store the specified number of elements, when
@@ -423,7 +423,7 @@
   /// - Complexity: O(1) on average, over many calls to `append(_:)` on the
   ///   same collection.
   @inlinable
-  public mutating func append(_ newElement: Element) {
+  public mutating func append(_ newElement: __owned Element) {
     insert(newElement, at: endIndex)
   }
 
@@ -445,7 +445,7 @@
   ///
   /// - Complexity: O(*m*), where *m* is the length of `newElements`.
   @inlinable
-  public mutating func append<S : Sequence>(contentsOf newElements: S)
+  public mutating func append<S : Sequence>(contentsOf newElements: __owned S)
     where S.Element == Element {
 
     let approximateCapacity = self.count +
@@ -481,7 +481,7 @@
   ///   `i == endIndex`, this method is equivalent to `append(_:)`.
   @inlinable
   public mutating func insert(
-    _ newElement: Element, at i: Index
+    _ newElement: __owned Element, at i: Index
   ) {
     replaceSubrange(i..<i, with: CollectionOfOne(newElement))
   }
@@ -513,7 +513,7 @@
   ///   is equivalent to `append(contentsOf:)`.
   @inlinable
   public mutating func insert<C : Collection>(
-    contentsOf newElements: C, at i: Index
+    contentsOf newElements: __owned C, at i: Index
   ) where C.Element == Element {
     replaceSubrange(i..<i, with: newElements)
   }
@@ -744,7 +744,7 @@
   @inlinable
   public mutating func replaceSubrange<C: Collection, R: RangeExpression>(
     _ subrange: R,
-    with newElements: C
+    with newElements: __owned C
   ) where C.Element == Element, R.Bound == Index {
     self.replaceSubrange(subrange.relative(to: self), with: newElements)
   }
@@ -1079,7 +1079,7 @@
   /// - Complexity: O(*n*), where *n* is the length of the collection.
   @inlinable
   @available(swift, introduced: 4.0)
-  public func filter(
+  public __consuming func filter(
     _ isIncluded: (Element) throws -> Bool
   ) rethrows -> Self {
     return try Self(self.lazy.filter(isIncluded))
diff --git a/stdlib/public/core/Reverse.swift b/stdlib/public/core/Reverse.swift
index b3a16c0..4c514bf 100644
--- a/stdlib/public/core/Reverse.swift
+++ b/stdlib/public/core/Reverse.swift
@@ -104,7 +104,7 @@
 
   @inlinable
   @inline(__always)
-  public func makeIterator() -> Iterator {
+  public __consuming func makeIterator() -> Iterator {
     return Iterator(_base: _base)
   }
 }
diff --git a/stdlib/public/core/Sequence.swift b/stdlib/public/core/Sequence.swift
index 2f93f50..6cd5ff0 100644
--- a/stdlib/public/core/Sequence.swift
+++ b/stdlib/public/core/Sequence.swift
@@ -637,7 +637,7 @@
 extension Sequence where Self.Iterator == Self {
   /// Returns an iterator over the elements of this sequence.
   @inlinable
-  public func makeIterator() -> Self {
+  public __consuming func makeIterator() -> Self {
     return self
   }
 }
@@ -666,7 +666,7 @@
   }
 
   @inlinable
-  internal func makeIterator() -> _DropFirstSequence<Base> {
+  __consuming internal func makeIterator() -> _DropFirstSequence<Base> {
     return self
   }
 
@@ -683,7 +683,7 @@
   }
 
   @inlinable
-  internal func dropFirst(_ k: Int) -> AnySequence<Base.Element> {
+  internal __consuming func dropFirst(_ k: Int) -> AnySequence<Base.Element> {
     // If this is already a _DropFirstSequence, we need to fold in
     // the current drop count and drop limit so no data is lost.
     //
@@ -718,7 +718,7 @@
   }
 
   @inlinable
-  internal func makeIterator() -> _PrefixSequence<Base> {
+  __consuming internal func makeIterator() -> _PrefixSequence<Base> {
     return self
   }
 
@@ -736,7 +736,7 @@
   }
 
   @inlinable
-  internal func prefix(_ maxLength: Int) -> AnySequence<Base.Element> {
+  internal __consuming func prefix(_ maxLength: Int) -> AnySequence<Base.Element> {
     return AnySequence(
       _PrefixSequence(
         _iterator: _iterator,
@@ -777,7 +777,7 @@
   }
 
   @inlinable
-  internal func makeIterator() -> _DropWhileSequence<Base> {
+  __consuming internal func makeIterator() -> _DropWhileSequence<Base> {
     return self
   }
 
@@ -793,7 +793,7 @@
   }
 
   @inlinable
-  internal func drop(
+  internal __consuming func drop(
     while predicate: (Element) throws -> Bool
   ) rethrows -> AnySequence<Element> {
     // If this is already a _DropWhileSequence, avoid multiple
@@ -867,7 +867,7 @@
   ///
   /// - Complexity: O(*n*), where *n* is the length of the sequence.
   @inlinable
-  public func filter(
+  public __consuming func filter(
     _ isIncluded: (Element) throws -> Bool
   ) rethrows -> [Element] {
     return try _filter(isIncluded)
@@ -1039,7 +1039,7 @@
   ///
   /// - Complexity: O(*n*), where *n* is the length of the sequence.
   @inlinable
-  public func split(
+  public __consuming func split(
     separator: Element,
     maxSplits: Int = Int.max,
     omittingEmptySubsequences: Bool = true
@@ -1103,7 +1103,7 @@
   ///
   /// - Complexity: O(*n*), where *n* is the length of the sequence.
   @inlinable
-  public func split(
+  public __consuming func split(
     maxSplits: Int = Int.max,
     omittingEmptySubsequences: Bool = true,
     whereSeparator isSeparator: (Element) throws -> Bool
@@ -1168,7 +1168,7 @@
   ///
   /// - Complexity: O(*n*), where *n* is the length of the sequence.
   @inlinable
-  public func suffix(_ maxLength: Int) -> AnySequence<Element> {
+  public __consuming func suffix(_ maxLength: Int) -> AnySequence<Element> {
     _precondition(maxLength >= 0, "Can't take a suffix of negative length from a sequence")
     if maxLength == 0 { return AnySequence([]) }
     // FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T>
@@ -1220,7 +1220,7 @@
   ///   where *k* is the number of elements to drop from the beginning of
   ///   the sequence.
   @inlinable
-  public func dropFirst(_ k: Int) -> AnySequence<Element> {
+  public __consuming func dropFirst(_ k: Int) -> AnySequence<Element> {
     _precondition(k >= 0, "Can't drop a negative number of elements from a sequence")
     if k == 0 { return AnySequence(self) }
     return AnySequence(_DropFirstSequence(_iterator: makeIterator(), limit: k))
@@ -1245,7 +1245,7 @@
   ///
   /// - Complexity: O(*n*), where *n* is the length of the sequence.
   @inlinable
-  public func dropLast(_ k: Int) -> AnySequence<Element> {
+  public __consuming func dropLast(_ k: Int) -> AnySequence<Element> {
     _precondition(k >= 0, "Can't drop a negative number of elements from a sequence")
     if k == 0 { return AnySequence(self) }
 
@@ -1295,7 +1295,7 @@
   /// - Complexity: O(*k*), where *k* is the number of elements to drop from
   ///   the beginning of the sequence.
   @inlinable
-  public func drop(
+  public __consuming func drop(
     while predicate: (Element) throws -> Bool
   ) rethrows -> AnySequence<Element> {
     return try AnySequence(
@@ -1322,7 +1322,7 @@
   ///
   /// - Complexity: O(1)
   @inlinable
-  public func prefix(_ maxLength: Int) -> AnySequence<Element> {
+  public __consuming func prefix(_ maxLength: Int) -> AnySequence<Element> {
     _precondition(maxLength >= 0, "Can't take a prefix of negative length from a sequence")
     if maxLength == 0 {
       return AnySequence(EmptyCollection<Element>())
@@ -1354,7 +1354,7 @@
   ///
   /// - Complexity: O(*k*), where *k* is the length of the result.
   @inlinable
-  public func prefix(
+  public __consuming func prefix(
     while predicate: (Element) throws -> Bool
   ) rethrows -> AnySequence<Element> {
     var result: [Element] = []
@@ -1390,7 +1390,7 @@
   ///
   /// - Complexity: O(1)
   @inlinable
-  public func dropFirst() -> SubSequence { return dropFirst(1) }
+  public __consuming func dropFirst() -> SubSequence { return dropFirst(1) }
 
   /// Returns a subsequence containing all but the last element of the
   /// sequence.
@@ -1411,7 +1411,7 @@
   ///
   /// - Complexity: O(*n*), where *n* is the length of the sequence.
   @inlinable
-  public func dropLast() -> SubSequence  { return dropLast(1) }
+  public __consuming func dropLast() -> SubSequence  { return dropLast(1) }
 }
 
 extension Sequence {
@@ -1423,7 +1423,7 @@
   /// - Postcondition: The `Pointee`s at `buffer[startIndex..<returned index]` are
   ///   initialized.
   @inlinable
-  public func _copyContents(
+  public __consuming func _copyContents(
     initializing buffer: UnsafeMutableBufferPointer<Element>
   ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) {
       var it = self.makeIterator()
diff --git a/stdlib/public/core/SequenceWrapper.swift b/stdlib/public/core/SequenceWrapper.swift
index 85833b2..788ad6c 100644
--- a/stdlib/public/core/SequenceWrapper.swift
+++ b/stdlib/public/core/SequenceWrapper.swift
@@ -42,7 +42,7 @@
 
 extension _SequenceWrapper where Iterator == Base.Iterator {
   @inlinable // generic-performance
-  public func makeIterator() -> Iterator {
+  public __consuming func makeIterator() -> Iterator {
     return self._base.makeIterator()
   }
   
@@ -64,7 +64,7 @@
   }
   
   @inlinable // generic-performance
-  public func filter(
+  public __consuming func filter(
     _ isIncluded: (Element) throws -> Bool
   ) rethrows -> [Element] {
     return try _base.filter(isIncluded)
@@ -83,7 +83,7 @@
   }
   
   @inlinable // generic-performance
-  public func _copyToContiguousArray()
+  public __consuming func _copyToContiguousArray()
     -> ContiguousArray<Element> {
     return _base._copyToContiguousArray()
   }
@@ -91,38 +91,38 @@
 
 extension _SequenceWrapper where SubSequence == Base.SubSequence {
   @inlinable // generic-performance
-  public func dropFirst(_ n: Int) -> SubSequence {
+  public __consuming func dropFirst(_ n: Int) -> SubSequence {
     return _base.dropFirst(n)
   }
   @inlinable // generic-performance
-  public func dropLast(_ n: Int) -> SubSequence {
+  public __consuming func dropLast(_ n: Int) -> SubSequence {
     return _base.dropLast(n)
   }
   @inlinable // generic-performance
-  public func prefix(_ maxLength: Int) -> SubSequence {
+  public __consuming func prefix(_ maxLength: Int) -> SubSequence {
     return _base.prefix(maxLength)
   }
   @inlinable // generic-performance
-  public func suffix(_ maxLength: Int) -> SubSequence {
+  public __consuming func suffix(_ maxLength: Int) -> SubSequence {
     return _base.suffix(maxLength)
   }
 
   @inlinable // generic-performance
-  public func drop(
+  public __consuming func drop(
     while predicate: (Element) throws -> Bool
   ) rethrows -> SubSequence {
     return try _base.drop(while: predicate)
   }
 
   @inlinable // generic-performance
-  public func prefix(
+  public __consuming func prefix(
     while predicate: (Element) throws -> Bool
   ) rethrows -> SubSequence {
     return try _base.prefix(while: predicate)
   }
   
   @inlinable // generic-performance
-  public func split(
+  public __consuming func split(
     maxSplits: Int, omittingEmptySubsequences: Bool,
     whereSeparator isSeparator: (Element) throws -> Bool
   ) rethrows -> [SubSequence] {
diff --git a/stdlib/public/core/Set.swift b/stdlib/public/core/Set.swift
index 8b12d17..09ee8ff 100644
--- a/stdlib/public/core/Set.swift
+++ b/stdlib/public/core/Set.swift
@@ -233,7 +233,7 @@
   /// Returns an iterator over the members of the set.
   @inlinable
   @inline(__always)
-  public func makeIterator() -> Iterator {
+  public __consuming func makeIterator() -> Iterator {
     return _variant.makeIterator()
   }
 
@@ -290,7 +290,7 @@
   /// - Returns: A set of the elements that `isIncluded` allows.
   @inlinable
   @available(swift, introduced: 4.0)
-  public func filter(
+  public __consuming func filter(
     _ isIncluded: (Element) throws -> Bool
   ) rethrows -> Set {
     var result = Set()
@@ -3074,7 +3074,7 @@
   /// - Complexity: O(1).
   @inlinable // FIXME(sil-serialize-all)
   @inline(__always)
-  internal func makeIterator() -> Set<Element>.Iterator {
+  __consuming internal func makeIterator() -> Set<Element>.Iterator {
     switch self {
     case .native(let nativeSet):
       return ._native(nativeSet.makeIterator())
@@ -3373,7 +3373,7 @@
   }
 
   @inlinable
-  internal func makeIterator() -> Iterator {
+  __consuming internal func makeIterator() -> Iterator {
     return Iterator(self)
   }
 }
@@ -3432,7 +3432,7 @@
   }
 
   @usableFromInline
-  internal func makeIterator() -> Iterator {
+  __consuming internal func makeIterator() -> Iterator {
     return Iterator(self)
   }
 }
diff --git a/stdlib/public/core/Stride.swift b/stdlib/public/core/Stride.swift
index 133c035..d501c14 100644
--- a/stdlib/public/core/Stride.swift
+++ b/stdlib/public/core/Stride.swift
@@ -273,7 +273,7 @@
   ///
   /// - Complexity: O(1).
   @inlinable
-  public func makeIterator() -> StrideToIterator<Element> {
+  public __consuming func makeIterator() -> StrideToIterator<Element> {
     return StrideToIterator(_start: _start, end: _end, stride: _stride)
   }
 
@@ -488,7 +488,7 @@
   ///
   /// - Complexity: O(1).
   @inlinable
-  public func makeIterator() -> StrideThroughIterator<Element> {
+  public __consuming func makeIterator() -> StrideThroughIterator<Element> {
     return StrideThroughIterator(_start: _start, end: _end, stride: _stride)
   }
 
diff --git a/stdlib/public/core/String.swift b/stdlib/public/core/String.swift
index ea07cde..f67b66e 100644
--- a/stdlib/public/core/String.swift
+++ b/stdlib/public/core/String.swift
@@ -938,7 +938,7 @@
 // This overload is necessary because String now conforms to
 // BidirectionalCollection, and there are other `joined` overloads that are
 // considered more specific. See Flatten.swift.gyb.
-extension BidirectionalCollection where Iterator.Element == String {
+extension BidirectionalCollection where Element == String {
   /// Returns a new string by concatenating the elements of the sequence,
   /// adding the given separator between each element.
   ///
diff --git a/stdlib/public/core/ThreadLocalStorage.swift b/stdlib/public/core/ThreadLocalStorage.swift
index ecd79d3..8bff3c8 100644
--- a/stdlib/public/core/ThreadLocalStorage.swift
+++ b/stdlib/public/core/ThreadLocalStorage.swift
@@ -38,6 +38,7 @@
   //
   // private
   internal var uBreakIterator: OpaquePointer
+  internal var uText: OpaquePointer
 
   // TODO: Consider saving two, e.g. for character-by-character comparison
 
@@ -55,8 +56,9 @@
   // TODO: unowned reference to string owner, base address, and _countAndFlags
 
   // private: Should only be called by _initializeThreadLocalStorage
-  internal init(_uBreakIterator: OpaquePointer) {
+  internal init(_uBreakIterator: OpaquePointer, _uText: OpaquePointer) {
     self.uBreakIterator = _uBreakIterator
+    self.uText = _uText
   }
 
   // Get the current thread's TLS pointer. On first call for a given thread,
@@ -104,19 +106,26 @@
 internal func _createThreadLocalStorage()
   -> UnsafeMutablePointer<_ThreadLocalStorage>
 {
-  // Create and initialize one.
+  // Allocate and initialize a UBreakIterator and UText.
   var err = __swift_stdlib_U_ZERO_ERROR
   let newUBreakIterator = __swift_stdlib_ubrk_open(
       /*type:*/ __swift_stdlib_UBRK_CHARACTER, /*locale:*/ nil,
       /*text:*/ nil, /*textLength:*/ 0, /*status:*/ &err)
   _precondition(err.isSuccess, "Unexpected ubrk_open failure")
 
+  // utext_openUTF8 needs a valid pointer, even though we won't read from it
+  var a: Int8 = 0x41
+  let newUText = __swift_stdlib_utext_openUTF8(
+      /*ut:*/ nil, /*s:*/ &a, /*len:*/ 1, /*status:*/ &err)
+
+  _precondition(err.isSuccess, "Unexpected utext_openUTF8 failure")
+
   let tlsPtr: UnsafeMutablePointer<_ThreadLocalStorage>
     = UnsafeMutablePointer<_ThreadLocalStorage>.allocate(
       capacity: 1
   )
-  tlsPtr.initialize(
-    to: _ThreadLocalStorage(_uBreakIterator: newUBreakIterator)
-  )
+  tlsPtr.initialize(to: _ThreadLocalStorage(
+    _uBreakIterator: newUBreakIterator, _uText: newUText))
+
   return tlsPtr
 }
diff --git a/stdlib/public/core/Zip.swift b/stdlib/public/core/Zip.swift
index b97fe84..731d0d2 100644
--- a/stdlib/public/core/Zip.swift
+++ b/stdlib/public/core/Zip.swift
@@ -140,7 +140,7 @@
 
   /// Returns an iterator over the elements of this sequence.
   @inlinable // generic-performance
-  public func makeIterator() -> Iterator {
+  public __consuming func makeIterator() -> Iterator {
     return Iterator(
       _sequence1.makeIterator(),
       _sequence2.makeIterator())
diff --git a/stdlib/public/runtime/HeapObject.cpp b/stdlib/public/runtime/HeapObject.cpp
index 32a9246..557931e 100644
--- a/stdlib/public/runtime/HeapObject.cpp
+++ b/stdlib/public/runtime/HeapObject.cpp
@@ -61,7 +61,7 @@
 /// Returns true if the pointer passed to a native retain or release is valid.
 /// If false, the operation should immediately return.
 static inline bool isValidPointerForNativeRetain(const void *p) {
-#if defined(__x86_64__) || defined(__arm64__)
+#if defined(__x86_64__) || defined(__arm64__) || defined(__aarch64__) || defined(_M_ARM64)
   // On these platforms, the upper half of address space is reserved for the
   // kernel, so we can assume that pointer values in this range are invalid.
   return (intptr_t)p > 0;
diff --git a/stdlib/public/runtime/SwiftObject.mm b/stdlib/public/runtime/SwiftObject.mm
index f7137bd..f92812e 100644
--- a/stdlib/public/runtime/SwiftObject.mm
+++ b/stdlib/public/runtime/SwiftObject.mm
@@ -498,7 +498,7 @@
 
 #if defined(__x86_64__)
 static uintptr_t const objectPointerIsObjCBit = 0x4000000000000000ULL;
-#elif defined(__arm64__)
+#elif defined(__arm64__) || defined(__arch64__) || defined(_M_ARM64)
 static uintptr_t const objectPointerIsObjCBit = 0x4000000000000000ULL;
 #else
 static uintptr_t const objectPointerIsObjCBit = 0x00000002U;
diff --git a/stdlib/public/runtime/WeakReference.h b/stdlib/public/runtime/WeakReference.h
index 34dd52e..a0f86e9 100644
--- a/stdlib/public/runtime/WeakReference.h
+++ b/stdlib/public/runtime/WeakReference.h
@@ -78,16 +78,16 @@
 #if !SWIFT_OBJC_INTEROP
     NativeMarkerMask  = 0,
     NativeMarkerValue = 0
-#elif __x86_64__
+#elif defined(__x86_64__)
     NativeMarkerMask  = SWIFT_ABI_X86_64_OBJC_WEAK_REFERENCE_MARKER_MASK,
     NativeMarkerValue = SWIFT_ABI_X86_64_OBJC_WEAK_REFERENCE_MARKER_VALUE
-#elif __i386__
+#elif defined(__i386__)
     NativeMarkerMask  = SWIFT_ABI_I386_OBJC_WEAK_REFERENCE_MARKER_MASK,
     NativeMarkerValue = SWIFT_ABI_I386_OBJC_WEAK_REFERENCE_MARKER_VALUE
-#elif __arm__
+#elif defined(__arm__) || defined(_M_ARM)
     NativeMarkerMask  = SWIFT_ABI_ARM_OBJC_WEAK_REFERENCE_MARKER_MASK,
     NativeMarkerValue = SWIFT_ABI_ARM_OBJC_WEAK_REFERENCE_MARKER_VALUE
-#elif __arm64__
+#elif defined(__arm64__) || defined(__aarch64__) || defined(_M_ARM64)
     NativeMarkerMask  = SWIFT_ABI_ARM64_OBJC_WEAK_REFERENCE_MARKER_MASK,
     NativeMarkerValue = SWIFT_ABI_ARM64_OBJC_WEAK_REFERENCE_MARKER_VALUE
 #else
diff --git a/stdlib/public/stubs/MathStubs.cpp b/stdlib/public/stubs/MathStubs.cpp
index 39ac393..dbafab6 100644
--- a/stdlib/public/stubs/MathStubs.cpp
+++ b/stdlib/public/stubs/MathStubs.cpp
@@ -64,7 +64,7 @@
     (defined(__linux__) && defined(__aarch64__)) || \
     (defined(__linux__) && defined(__powerpc64__)) || \
     (defined(__linux__) && defined(__s390x__)) || \
-    (defined(__ANDROID__) && defined(__arm64__))
+    (defined(__ANDROID__) && defined(__aarch64__))
 
 SWIFT_RUNTIME_STDLIB_API
 ti_int
diff --git a/test/IDE/print_type_interface.swift b/test/IDE/print_type_interface.swift
index d61f4af..a121596 100644
--- a/test/IDE/print_type_interface.swift
+++ b/test/IDE/print_type_interface.swift
@@ -71,15 +71,15 @@
 // RUN: %target-swift-ide-test -print-type-interface -usr=_TtGSaSi_ -module-name print_type_interface -source-filename %s | %FileCheck %s -check-prefix=TYPE4
 // TYPE4-DAG: public typealias Index = Int
 // TYPE4-DAG: public func min() -> Int?
-// TYPE4-DAG: public mutating func insert<C>(contentsOf newElements: C, at i: Int)
+// TYPE4-DAG: public mutating func insert<C>(contentsOf newElements: __owned C, at i: Int)
 // TYPE4-DAG: public mutating func removeFirst(_ k: Int)
-// TYPE4-DAG: public func makeIterator() -> IndexingIterator<Array<Int>>
+// TYPE4-DAG: public __consuming func makeIterator() -> IndexingIterator<Array<Int>>
 // TYPE4-NOT: public func joined
 
 // RUN: %target-swift-ide-test -print-type-interface -usr=_TtGSaSS_ -module-name print_type_interface -source-filename %s | %FileCheck %s -check-prefix=TYPE5
-// TYPE5-DAG: public func prefix(_ maxLength: Int) -> ArraySlice<String>
-// TYPE5-DAG: public func suffix(_ maxLength: Int) -> ArraySlice<String>
-// TYPE5-DAG: public func split(separator: String, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true) -> [ArraySlice<String>]
+// TYPE5-DAG: public __consuming func prefix(_ maxLength: Int) -> ArraySlice<String>
+// TYPE5-DAG: public __consuming func suffix(_ maxLength: Int) -> ArraySlice<String>
+// TYPE5-DAG: public __consuming func split(separator: String, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true) -> [ArraySlice<String>]
 // TYPE5-DAG: public func formIndex(_ i: inout Int, offsetBy distance: Int)
 // TYPE5-DAG: public func distance(from start: Int, to end: Int) -> Int
 // TYPE5-DAG: public func joined(separator: String = "") -> String
diff --git a/test/IDE/reconstruct_type_from_mangled_name.swift b/test/IDE/reconstruct_type_from_mangled_name.swift
index 5410b81..21deb14 100644
--- a/test/IDE/reconstruct_type_from_mangled_name.swift
+++ b/test/IDE/reconstruct_type_from_mangled_name.swift
@@ -1,4 +1,5 @@
 // RUN: %target-swift-ide-test -reconstruct-type -source-filename %s | %FileCheck %s -implicit-check-not="FAILURE"
+// XFAIL: *
 
 struct Mystruct1 {
 // CHECK: decl: struct Mystruct1
@@ -64,7 +65,7 @@
 
     arr1.append(1)
 // FIXME: missing append()
-// CHECK: dref: FAILURE	for 'append' usr=s:Sa6appendyyxF
+// CHECK: dref: FAILURE	for 'append' usr=s:Sa6appendyyxnF
 // CHECK: type: (inout Array<Int>) -> (Int) -> ()
 
     var arr2 : [Mystruct1]
diff --git a/test/Misc/misc_diagnostics.swift b/test/Misc/misc_diagnostics.swift
index 4176dff..5265098 100644
--- a/test/Misc/misc_diagnostics.swift
+++ b/test/Misc/misc_diagnostics.swift
@@ -90,10 +90,10 @@
 let _: String = testIS1() // expected-error {{cannot convert value of type 'Int' to specified type 'String'}}
 
 func insertA<T>(array : inout [T], elt : T) {
-  array.append(T.self); // expected-error {{cannot invoke 'append' with an argument list of type '(T.Type)'}} expected-note {{expected an argument list of type '(T)'}}
+  array.append(T.self); // expected-error {{cannot invoke 'append' with an argument list of type '(T.Type)'}} expected-note {{expected an argument list of type '(__owned T)'}}
 
   // FIXME: Kind of weird
-  array.append(T); // expected-error {{cannot invoke 'append' with an argument list of type '((T).Type)'}} expected-note {{expected an argument list of type '(T)'}}
+  array.append(T); // expected-error {{cannot invoke 'append' with an argument list of type '((T).Type)'}} expected-note {{expected an argument list of type '(__owned T)'}}
 }
 
 // <rdar://problem/17875634> can't append to array of tuples
diff --git a/test/Parse/multiline_errors.swift b/test/Parse/multiline_errors.swift
index 4fa56d0..de5c3cd 100644
--- a/test/Parse/multiline_errors.swift
+++ b/test/Parse/multiline_errors.swift
Binary files differ
diff --git a/test/Parse/string_literal_eof4.swift b/test/Parse/string_literal_eof4.swift
new file mode 100644
index 0000000..2f8f451
--- /dev/null
+++ b/test/Parse/string_literal_eof4.swift
@@ -0,0 +1,6 @@
+// RUN: %target-typecheck-verify-swift
+
+// NOTE: DO NOT add a newline at EOF.
+// expected-error@+1 {{unterminated string literal}}
+_ = """
+    foo
\ No newline at end of file
diff --git a/test/Parse/string_literal_eof5.swift b/test/Parse/string_literal_eof5.swift
new file mode 100644
index 0000000..04c359a
--- /dev/null
+++ b/test/Parse/string_literal_eof5.swift
@@ -0,0 +1,7 @@
+// RUN: %target-typecheck-verify-swift
+
+// NOTE: DO NOT add a newline at EOF.
+// expected-error@+1 {{unterminated string literal}}
+_ = """
+    foo
+    \(
diff --git a/test/Parse/string_literal_eof6.swift b/test/Parse/string_literal_eof6.swift
new file mode 100644
index 0000000..43611f4
--- /dev/null
+++ b/test/Parse/string_literal_eof6.swift
@@ -0,0 +1,7 @@
+// RUN: %target-typecheck-verify-swift
+
+// NOTE: DO NOT add a newline at EOF.
+// expected-error@+1 {{unterminated string literal}}
+_ = """
+    foo
+    \("bar
\ No newline at end of file
diff --git a/test/Parse/string_literal_eof7.swift b/test/Parse/string_literal_eof7.swift
new file mode 100644
index 0000000..8525270
--- /dev/null
+++ b/test/Parse/string_literal_eof7.swift
@@ -0,0 +1,9 @@
+// RUN: %target-typecheck-verify-swift
+
+// expected-error@+4 {{unterminated string literal}}
+// expected-error@+1 {{unterminated string literal}}
+_ = """
+    foo
+    \("bar
+    baz
+
diff --git a/test/SILOptimizer/access_marker_verify.swift b/test/SILOptimizer/access_marker_verify.swift
index cc64589..302d0fa 100644
--- a/test/SILOptimizer/access_marker_verify.swift
+++ b/test/SILOptimizer/access_marker_verify.swift
@@ -502,8 +502,8 @@
 // ----- call Array.append
 // CHECK:   alloc_stack $Int
 // CHECK:   store %{{.*}} to [trivial]
-// CHECK:   function_ref @$sSa6appendyyxF : $@convention(method) <τ_0_0> (@in_guaranteed τ_0_0, @inout Array<τ_0_0>) -> ()
-// CHECK:   apply %{{.*}}<Int>(%{{.*}}, [[TEMPARRAYADR]]) : $@convention(method) <τ_0_0> (@in_guaranteed τ_0_0, @inout Array<τ_0_0>) -> ()
+// CHECK:   function_ref @$sSa6appendyyxnF : $@convention(method) <τ_0_0> (@in τ_0_0, @inout Array<τ_0_0>) -> ()
+// CHECK:   apply %{{.*}}<Int>(%{{.*}}, [[TEMPARRAYADR]]) : $@convention(method) <τ_0_0> (@in τ_0_0, @inout Array<τ_0_0>) -> ()
 // CHECK:   [[TEMPARRAYVAL:%.*]] = load [take] [[TEMPACCESS]] : $*Optional<Array<Int>>
 // CHECK:   [[ARRAYCOPY:%.*]] = alloc_stack $Optional<Array<Int>>
 // CHECK:   store [[TEMPARRAYVAL]] to [init] [[ARRAYCOPY]] : $*Optional<Array<Int>>
diff --git a/test/SILOptimizer/array_contentof_opt.swift b/test/SILOptimizer/array_contentof_opt.swift
index bcae405..0a6ab5d 100644
--- a/test/SILOptimizer/array_contentof_opt.swift
+++ b/test/SILOptimizer/array_contentof_opt.swift
@@ -5,7 +5,7 @@
 
 // CHECK-LABEL: sil @{{.*}}testInt
 // CHECK-NOT: apply
-// CHECK:        [[F:%[0-9]+]] = function_ref @$sSa6appendyyxFSi_Tg5
+// CHECK:        [[F:%[0-9]+]] = function_ref @$sSa6appendyyxnFSi_Tg5
 // CHECK-NOT: apply
 // CHECK:        apply [[F]]
 // CHECK-NEXT:   tuple
@@ -19,7 +19,7 @@
 // CHECK:        [[FR:%[0-9]+]] = function_ref @$sSa15reserveCapacityyySiFSi_Tg5
 // CHECK-NEXT:   apply [[FR]]
 // CHECK-NOT: apply
-// CHECK:        [[F:%[0-9]+]] = function_ref @$sSa6appendyyxFSi_Tg5
+// CHECK:        [[F:%[0-9]+]] = function_ref @$sSa6appendyyxnFSi_Tg5
 // CHECK-NOT: apply
 // CHECK:        apply [[F]]
 // CHECK-NEXT:   apply [[F]]
@@ -32,7 +32,7 @@
 
 // CHECK-LABEL: sil @{{.*}}testTooManyInts
 // CHECK-NOT: apply
-// CHECK:        [[F:%[0-9]+]] = function_ref  @$sSa6append10contentsOfyqd___t7ElementQyd__RszSTRd__lFSi_SaySiGTg5
+// CHECK:        [[F:%[0-9]+]] = function_ref  @$sSa6append10contentsOfyqd__n_t7ElementQyd__RszSTRd__lFSi_SaySiGTg5Tf4gn_n
 // CHECK-NOT: apply
 // CHECK:        apply [[F]]
 // CHECK-NOT: apply
@@ -43,7 +43,7 @@
 
 // CHECK-LABEL: sil @{{.*}}testString
 // CHECK-NOT: apply
-// CHECK:        [[F:%[0-9]+]] = function_ref @$sSa6appendyyxFSS_Tg5
+// CHECK:        [[F:%[0-9]+]] = function_ref @$sSa6appendyyxnFSS_Tg5
 // CHECK-NOT: apply
 // CHECK:        apply [[F]]
 // CHECK-NOT: apply
diff --git a/test/SILOptimizer/array_element_propagation.sil b/test/SILOptimizer/array_element_propagation.sil
index 27d51e6..cdf04f6 100644
--- a/test/SILOptimizer/array_element_propagation.sil
+++ b/test/SILOptimizer/array_element_propagation.sil
@@ -310,7 +310,7 @@
 // CHECK-NEXT: [[ARR:%.*]] = apply [[ASFUN]]
 // CHECK-NEXT: [[OWNER:%.*]] = tuple_extract [[ARR]]{{.*}}, 0
 // CHECK-NOT:    apply [[ACFUN]]
-// CHECK:      [[AEFUN:%.*]] = function_ref @$sSa6appendyyxF
+// CHECK:      [[AEFUN:%.*]] = function_ref @$sSa6appendyyxnF
 // CHECK-NEXT: [[STACK:%.*]] = alloc_stack $MyInt
 // CHECK-NEXT: store %{{[0-9]+}} to [[STACK]]
 // CHECK-NEXT: apply [[AEFUN]]<MyInt>([[STACK]]
@@ -357,13 +357,12 @@
 // CHECK:      strong_retain %1 : $Hello
 // CHECK-NEXT: store %1 to %{{[0-9]+}} : $*Hello
 // CHECK-NOT:     apply
-// CHECK:      [[AEFUN:%.*]] = function_ref @$sSa6appendyyxF
+// CHECK:      [[AEFUN:%.*]] = function_ref @$sSa6appendyyxnF
 // CHECK-NEXT: strong_retain %1 : $Hello
 // CHECK-NEXT: [[STACK:%.*]] = alloc_stack $Hello
 // CHECK-NEXT: store %1 to [[STACK]]
 // CHECK-NEXT: apply [[AEFUN]]<Hello>([[STACK]], %0)
 // CHECK-NEXT: dealloc_stack [[STACK]]
-// CHECK-NEXT: strong_release %1
 // CHECK-NEXT: release_value [[OWNER]]
 // CHECK-NEXT: return
 sil @append_contentsOf_class : $@convention(thin) (@inout Array<Hello>, @owned Hello) -> @owned Hello {
diff --git a/test/SourceKit/CursorInfo/cursor_stdlib.swift b/test/SourceKit/CursorInfo/cursor_stdlib.swift
index fafb056..9d0dde3 100644
--- a/test/SourceKit/CursorInfo/cursor_stdlib.swift
+++ b/test/SourceKit/CursorInfo/cursor_stdlib.swift
@@ -49,7 +49,7 @@
 
 // RUN: %sourcekitd-test -req=cursor -pos=9:8 %s -- %s %mcp_opt -target %target-triple %clang-importer-sdk-nosource -I %t | %FileCheck -check-prefix=CHECK-REPLACEMENT2 %s
 // CHECK-REPLACEMENT2: <Group>Collection/Array</Group>
-// CHECK-REPLACEMENT2: <Declaration>{{.*}}mutating func append(_ newElement: <Type usr="s:Si">Int</Type>)</Declaration>
+// CHECK-REPLACEMENT2: <Declaration>{{.*}}mutating func append(_ newElement: __owned <Type usr="s:Si">Int</Type>)</Declaration>
 
 // RUN: %sourcekitd-test -req=cursor -pos=15:10 %s -- %s %mcp_opt -target %target-triple %clang-importer-sdk-nosource -I %t | %FileCheck -check-prefix=CHECK-REPLACEMENT3 %s
 // CHECK-REPLACEMENT3: <Group>Collection/Array</Group>
@@ -58,7 +58,7 @@
 
 // RUN: %sourcekitd-test -req=cursor -pos=18:8 %s -- %s %mcp_opt -target %target-triple %clang-importer-sdk-nosource -I %t | %FileCheck -check-prefix=CHECK-REPLACEMENT4 %s
 // CHECK-REPLACEMENT4: <Group>Collection/Array</Group>
-// CHECK-REPLACEMENT4: <Declaration>{{.*}}mutating func append(_ newElement: <Type usr="s:13cursor_stdlib2S1V">S1</Type>)</Declaration>
+// CHECK-REPLACEMENT4: <Declaration>{{.*}}mutating func append(_ newElement: __owned <Type usr="s:13cursor_stdlib2S1V">S1</Type>)</Declaration>
 
 // RUN: %sourcekitd-test -req=cursor -pos=21:10 %s -- %s %mcp_opt -target %target-triple %clang-importer-sdk-nosource -I %t | %FileCheck -check-prefix=CHECK-MODULE-GROUP1 %s
 // CHECK-MODULE-GROUP1: MODULE GROUPS BEGIN
diff --git a/test/SourceKit/Refactoring/semantic-refactoring/line-col-conversion.swift b/test/SourceKit/Refactoring/semantic-refactoring/line-col-conversion.swift
new file mode 100644
index 0000000..02aca45
--- /dev/null
+++ b/test/SourceKit/Refactoring/semantic-refactoring/line-col-conversion.swift
@@ -0,0 +1,4 @@
+// RUN: %sourcekitd-test -req=local-rename -pos=4:7 -name new_name %s -- %s
+
+var Foo: Int {
+	var missingNewlineAtEndOfFile
\ No newline at end of file
diff --git a/test/api-digester/Inputs/cake.swift b/test/api-digester/Inputs/cake.swift
index ea09c0a..ed19110 100644
--- a/test/api-digester/Inputs/cake.swift
+++ b/test/api-digester/Inputs/cake.swift
@@ -49,4 +49,14 @@
   var c = 3
 }
 
-extension Int: P1 { public func bar() {} }
\ No newline at end of file
+extension Int: P1 { public func bar() {} }
+
+public protocol ProWithAssociatedType {
+  associatedtype A
+  associatedtype B = Int
+}
+
+public protocol SubsContainer {
+  subscript(getter i: Int) -> Int { get }
+  subscript(setter i: Int) -> Int { get set }
+}
diff --git a/test/api-digester/Inputs/cake1.swift b/test/api-digester/Inputs/cake1.swift
index 9483f7b..b97041c 100644
--- a/test/api-digester/Inputs/cake1.swift
+++ b/test/api-digester/Inputs/cake1.swift
@@ -69,3 +69,17 @@
 public protocol P3: P2, P1 {}
 
 extension fixedLayoutStruct: P1 {}
+
+public protocol AssociatedTypePro {
+  associatedtype T1 = Int
+  associatedtype T2
+  associatedtype T3 = C1
+}
+
+public class RemoveSetters {
+  public var Value = 4
+  public subscript(_ idx: Int) -> Int {
+    get { return 1 }
+    set(newValue) {}
+  }
+}
diff --git a/test/api-digester/Inputs/cake2.swift b/test/api-digester/Inputs/cake2.swift
index a410da4..608ac31 100644
--- a/test/api-digester/Inputs/cake2.swift
+++ b/test/api-digester/Inputs/cake2.swift
@@ -76,3 +76,17 @@
 public protocol P4 {}
 
 extension fixedLayoutStruct: P2 {}
+
+public protocol AssociatedTypePro {
+  associatedtype T1
+  associatedtype T2
+  associatedtype T3 = C6
+}
+
+public class RemoveSetters {
+  public private(set) var Value = 4
+  public subscript(_ idx: Int) -> Int {
+    get { return 1 }
+  }
+}
+
diff --git a/test/api-digester/Outputs/Cake-abi.txt b/test/api-digester/Outputs/Cake-abi.txt
index 137ad54..6d21e40 100644
--- a/test/api-digester/Outputs/Cake-abi.txt
+++ b/test/api-digester/Outputs/Cake-abi.txt
@@ -9,6 +9,8 @@
 cake1: Constructor Somestruct2.init(_:) has been removed
 cake1: Constructor fixedLayoutStruct.init(b:a:) has been removed
 cake1: Func C4.foo() has been removed
+cake1: Subscript RemoveSetters.subscript(_:) has removed its setter
+cake1: Var RemoveSetters.Value has removed its setter
 
 /* Moved Decls */
 
@@ -17,6 +19,7 @@
 cake1: Struct Somestruct2 has been renamed to Struct NSSomestruct2
 
 /* Type Changes */
+cake1: AssociatedType AssociatedTypePro.T3 has default type change from C1 to C6
 cake1: Constructor S1.init(_:) has parameter 0 type change from Int to Double
 cake1: Func C1.foo2(_:) has parameter 0 type change from Int to () -> ()
 cake1: Func C7.foo(_:_:) has removed default argument from parameter 0
@@ -47,3 +50,6 @@
 cake1: Protocol P3 has added inherited protocol P4
 cake1: Protocol P3 has removed inherited protocol P2
 cake1: Struct fixedLayoutStruct has removed conformance to P1
+
+/* Protocol Requirement Change */
+cake1: AssociatedType AssociatedTypePro.T1 has removed default type Int
diff --git a/test/api-digester/Outputs/Cake.txt b/test/api-digester/Outputs/Cake.txt
index 70b4e29..60b7268 100644
--- a/test/api-digester/Outputs/Cake.txt
+++ b/test/api-digester/Outputs/Cake.txt
@@ -9,6 +9,8 @@
 cake1: Constructor Somestruct2.init(_:) has been removed
 cake1: Constructor fixedLayoutStruct.init(b:a:) has been removed
 cake1: Func C4.foo() has been removed
+cake1: Subscript RemoveSetters.subscript(_:) has removed its setter
+cake1: Var RemoveSetters.Value has removed its setter
 
 /* Moved Decls */
 
@@ -17,6 +19,7 @@
 cake1: Struct Somestruct2 has been renamed to Struct NSSomestruct2
 
 /* Type Changes */
+cake1: AssociatedType AssociatedTypePro.T3 has default type change from C1 to C6
 cake1: Constructor S1.init(_:) has parameter 0 type change from Int to Double
 cake1: Func C1.foo2(_:) has parameter 0 type change from Int to () -> ()
 cake1: Func C7.foo(_:_:) has removed default argument from parameter 0
@@ -33,3 +36,6 @@
 cake1: Protocol P3 has added inherited protocol P4
 cake1: Protocol P3 has removed inherited protocol P2
 cake1: Struct fixedLayoutStruct has removed conformance to P1
+
+/* Protocol Requirement Change */
+cake1: AssociatedType AssociatedTypePro.T1 has removed default type Int
diff --git a/test/api-digester/Outputs/cake-abi.json b/test/api-digester/Outputs/cake-abi.json
index 93d20c3..10b542a 100644
--- a/test/api-digester/Outputs/cake-abi.json
+++ b/test/api-digester/Outputs/cake-abi.json
@@ -808,33 +808,6 @@
                   "usr": "s:Si"
                 }
               ]
-            },
-            {
-              "kind": "Setter",
-              "name": "_",
-              "printedName": "_()",
-              "declKind": "Accessor",
-              "usr": "s:4cake17fixedLayoutStructV1b33_3D8926C30F7417F2EF9A277D0C73FBDBLLSivs",
-              "location": "",
-              "moduleName": "cake",
-              "implicit": true,
-              "mutating": true,
-              "declAttributes": [
-                "Transparent"
-              ],
-              "children": [
-                {
-                  "kind": "TypeNominal",
-                  "name": "Void",
-                  "printedName": "()"
-                },
-                {
-                  "kind": "TypeNominal",
-                  "name": "Int",
-                  "printedName": "Int",
-                  "usr": "s:Si"
-                }
-              ]
             }
           ]
         },
@@ -877,33 +850,6 @@
                   "usr": "s:Si"
                 }
               ]
-            },
-            {
-              "kind": "Setter",
-              "name": "_",
-              "printedName": "_()",
-              "declKind": "Accessor",
-              "usr": "s:4cake17fixedLayoutStructV1cSivs",
-              "location": "",
-              "moduleName": "cake",
-              "implicit": true,
-              "mutating": true,
-              "declAttributes": [
-                "Transparent"
-              ],
-              "children": [
-                {
-                  "kind": "TypeNominal",
-                  "name": "Void",
-                  "printedName": "()"
-                },
-                {
-                  "kind": "TypeNominal",
-                  "name": "Int",
-                  "printedName": "Int",
-                  "usr": "s:Si"
-                }
-              ]
             }
           ]
         },
@@ -965,6 +911,103 @@
     },
     {
       "kind": "TypeDecl",
+      "name": "ProWithAssociatedType",
+      "printedName": "ProWithAssociatedType",
+      "declKind": "Protocol",
+      "usr": "s:4cake21ProWithAssociatedTypeP",
+      "location": "",
+      "moduleName": "cake",
+      "children": [
+        {
+          "kind": "AssociatedType",
+          "name": "A",
+          "printedName": "A",
+          "declKind": "AssociatedType",
+          "usr": "s:4cake21ProWithAssociatedTypeP1AQa",
+          "location": "",
+          "moduleName": "cake"
+        },
+        {
+          "kind": "AssociatedType",
+          "name": "B",
+          "printedName": "B",
+          "declKind": "AssociatedType",
+          "usr": "s:4cake21ProWithAssociatedTypeP1BQa",
+          "location": "",
+          "moduleName": "cake",
+          "children": [
+            {
+              "kind": "TypeNominal",
+              "name": "Int",
+              "printedName": "Int",
+              "usr": "s:Si"
+            }
+          ]
+        }
+      ]
+    },
+    {
+      "kind": "TypeDecl",
+      "name": "SubsContainer",
+      "printedName": "SubsContainer",
+      "declKind": "Protocol",
+      "usr": "s:4cake13SubsContainerP",
+      "location": "",
+      "moduleName": "cake",
+      "children": [
+        {
+          "kind": "Subscript",
+          "name": "subscript",
+          "printedName": "subscript(getter:)",
+          "declKind": "Subscript",
+          "usr": "s:4cake13SubsContainerP6getterS2i_tcip",
+          "location": "",
+          "moduleName": "cake",
+          "genericSig": "<τ_0_0 where τ_0_0 : SubsContainer>",
+          "children": [
+            {
+              "kind": "TypeNominal",
+              "name": "Int",
+              "printedName": "Int",
+              "usr": "s:Si"
+            },
+            {
+              "kind": "TypeNominal",
+              "name": "Int",
+              "printedName": "Int",
+              "usr": "s:Si"
+            }
+          ]
+        },
+        {
+          "kind": "Subscript",
+          "name": "subscript",
+          "printedName": "subscript(setter:)",
+          "declKind": "Subscript",
+          "usr": "s:4cake13SubsContainerP6setterS2i_tcip",
+          "location": "",
+          "moduleName": "cake",
+          "genericSig": "<τ_0_0 where τ_0_0 : SubsContainer>",
+          "hasSetter": true,
+          "children": [
+            {
+              "kind": "TypeNominal",
+              "name": "Int",
+              "printedName": "Int",
+              "usr": "s:Si"
+            },
+            {
+              "kind": "TypeNominal",
+              "name": "Int",
+              "printedName": "Int",
+              "usr": "s:Si"
+            }
+          ]
+        }
+      ]
+    },
+    {
+      "kind": "TypeDecl",
       "name": "Int",
       "printedName": "Int",
       "declKind": "Struct",
diff --git a/test/api-digester/Outputs/cake.json b/test/api-digester/Outputs/cake.json
index cf77bae..c35c9fb 100644
--- a/test/api-digester/Outputs/cake.json
+++ b/test/api-digester/Outputs/cake.json
@@ -841,6 +841,103 @@
     },
     {
       "kind": "TypeDecl",
+      "name": "ProWithAssociatedType",
+      "printedName": "ProWithAssociatedType",
+      "declKind": "Protocol",
+      "usr": "s:4cake21ProWithAssociatedTypeP",
+      "location": "",
+      "moduleName": "cake",
+      "children": [
+        {
+          "kind": "AssociatedType",
+          "name": "A",
+          "printedName": "A",
+          "declKind": "AssociatedType",
+          "usr": "s:4cake21ProWithAssociatedTypeP1AQa",
+          "location": "",
+          "moduleName": "cake"
+        },
+        {
+          "kind": "AssociatedType",
+          "name": "B",
+          "printedName": "B",
+          "declKind": "AssociatedType",
+          "usr": "s:4cake21ProWithAssociatedTypeP1BQa",
+          "location": "",
+          "moduleName": "cake",
+          "children": [
+            {
+              "kind": "TypeNominal",
+              "name": "Int",
+              "printedName": "Int",
+              "usr": "s:Si"
+            }
+          ]
+        }
+      ]
+    },
+    {
+      "kind": "TypeDecl",
+      "name": "SubsContainer",
+      "printedName": "SubsContainer",
+      "declKind": "Protocol",
+      "usr": "s:4cake13SubsContainerP",
+      "location": "",
+      "moduleName": "cake",
+      "children": [
+        {
+          "kind": "Subscript",
+          "name": "subscript",
+          "printedName": "subscript(getter:)",
+          "declKind": "Subscript",
+          "usr": "s:4cake13SubsContainerP6getterS2i_tcip",
+          "location": "",
+          "moduleName": "cake",
+          "genericSig": "<Self where Self : SubsContainer>",
+          "children": [
+            {
+              "kind": "TypeNominal",
+              "name": "Int",
+              "printedName": "Int",
+              "usr": "s:Si"
+            },
+            {
+              "kind": "TypeNominal",
+              "name": "Int",
+              "printedName": "Int",
+              "usr": "s:Si"
+            }
+          ]
+        },
+        {
+          "kind": "Subscript",
+          "name": "subscript",
+          "printedName": "subscript(setter:)",
+          "declKind": "Subscript",
+          "usr": "s:4cake13SubsContainerP6setterS2i_tcip",
+          "location": "",
+          "moduleName": "cake",
+          "genericSig": "<Self where Self : SubsContainer>",
+          "hasSetter": true,
+          "children": [
+            {
+              "kind": "TypeNominal",
+              "name": "Int",
+              "printedName": "Int",
+              "usr": "s:Si"
+            },
+            {
+              "kind": "TypeNominal",
+              "name": "Int",
+              "printedName": "Int",
+              "usr": "s:Si"
+            }
+          ]
+        }
+      ]
+    },
+    {
+      "kind": "TypeDecl",
       "name": "Int",
       "printedName": "Int",
       "declKind": "Struct",
diff --git a/test/attr/attr_implements.swift b/test/attr/attr_implements.swift
index 5d2fd6e..5f1da10 100644
--- a/test/attr/attr_implements.swift
+++ b/test/attr/attr_implements.swift
@@ -70,3 +70,23 @@
 
 // print(s.f(x:1, y:2))
 
+
+// Next test is for rdar://43804798
+//
+// When choosing between an @_implements-provided implementation of a specific
+// protocol's witness (Equatable / Comparable in particular), we want to choose
+// the @_implements-provided one when we're looking up from a context that only
+// knows the protocol bound, and the non-@_implements-provided one when we're
+// looking up from a context that knows the full type.
+
+struct SpecificType : Equatable {
+  @_implements(Equatable, ==(_:_:))
+  static func bar(_: SpecificType, _: SpecificType) -> Bool { return true }
+  static func ==(_: SpecificType, _: SpecificType) -> Bool { return false }
+}
+
+func trueWhenJustEquatable<T: Equatable>(_ x: T) -> Bool { return x == x }
+func falseWhenSpecificType(_ x: SpecificType) -> Bool { return x == x }
+
+assert(trueWhenJustEquatable(SpecificType()))
+assert(!falseWhenSpecificType(SpecificType()))
diff --git a/test/attr/attr_implements_fp.swift b/test/attr/attr_implements_fp.swift
new file mode 100644
index 0000000..f8ae784
--- /dev/null
+++ b/test/attr/attr_implements_fp.swift
@@ -0,0 +1,116 @@
+// RUN: %empty-directory(%t)
+// RUN: echo 'main()' >%t/main.swift
+// RUN: %target-swiftc_driver -o %t/a.out %s %t/main.swift
+// RUN: %target-codesign %t/a.out
+// RUN: %target-run %t/a.out | %FileCheck %s
+// REQUIRES: executable_test
+
+// This is a more-thorough and explicit test for rdar://43804798 that uses @_implements to
+// achieve "Comparable Floating Point values are FP-like when known to be FP, Comparable-like
+// when only known to be comparable".
+
+// Could calls to the different comparison operators.
+public var comparedAsComparablesCount : Int = 0
+public var comparedAsFauxtsCount : Int = 0
+
+public protocol FauxtingPoint : Comparable {
+  static var nan: Self { get }
+  static var one: Self { get }
+  static var two: Self { get }
+}
+
+public protocol BinaryFauxtingPoint: FauxtingPoint {
+  var bitPattern: UInt8 { get }
+}
+
+public extension BinaryFauxtingPoint {
+  // This version of < will be called in a context that only knows it has a Comparable.
+  @_implements(Comparable, <(_:_:))
+  static func _ComparableLessThan(_ lhs: Fauxt, _ rhs: Fauxt) -> Bool {
+    print("compared as Comparables")
+    comparedAsComparablesCount += 1
+    return lhs.bitPattern < rhs.bitPattern
+  }
+}
+
+public enum State {
+  case Nan
+  case One
+  case Two
+}
+
+public struct Fauxt {
+  let state: State
+  init(_ s: State) {
+    state = s
+  }
+  public static var nan: Fauxt {
+    return Fauxt(State.Nan)
+  }
+  public static var one: Fauxt {
+    return Fauxt(State.One)
+  }
+  public static var two: Fauxt {
+    return Fauxt(State.Two)
+  }
+}
+
+extension Fauxt: BinaryFauxtingPoint {
+  // Requirement from BinaryFauxtingPoint
+  public var bitPattern: UInt8 {
+    switch state {
+    case .One:
+      return 1
+    case .Two:
+      return 2
+    case .Nan:
+      return 0xff
+    }
+  }
+}
+
+public extension Fauxt {
+  // This version of < will be called in a context that knows it has a Fauxt.
+  // It is inside an extension of Fauxt rather than the declaration of Fauxt
+  // itself in order to avoid a warning about near-matches with the defaulted
+  // requirement from Comparable.< up above.
+  static func <(_ lhs: Fauxt, _ rhs: Fauxt) -> Bool {
+    print("compared as Fauxts")
+    comparedAsFauxtsCount += 1
+    if lhs.state == .Nan || rhs.state == .Nan {
+      return false
+    } else {
+      return lhs.bitPattern < rhs.bitPattern
+    }
+  }
+}
+
+public func compare_Comparables<T:Comparable>(_ x: T, _ y: T) -> Bool {
+  return x < y
+}
+
+public func compare_Fauxts(_ x: Fauxt, _ y: Fauxt) -> Bool {
+  return x < y
+}
+
+public func main() {
+  assert(compare_Comparables(Fauxt.one, Fauxt.two))
+  assert(comparedAsComparablesCount == 1)
+  // CHECK: compared as Comparables
+  assert(compare_Comparables(Fauxt.one, Fauxt.nan))
+  assert(comparedAsComparablesCount == 2)
+  // CHECK: compared as Comparables
+  assert(!compare_Comparables(Fauxt.nan, Fauxt.one))
+  assert(comparedAsComparablesCount == 3)
+  // CHECK: compared as Comparables
+
+  assert(compare_Fauxts(Fauxt.one, Fauxt.two))
+  assert(comparedAsFauxtsCount == 1)
+  // CHECK: compared as Fauxts
+  assert(!compare_Fauxts(Fauxt.one, Fauxt.nan))
+  assert(comparedAsFauxtsCount == 2)
+  // CHECK: compared as Fauxts
+  assert(!compare_Fauxts(Fauxt.nan, Fauxt.one))
+  assert(comparedAsFauxtsCount == 3)
+  // CHECK: compared as Fauxts
+}
diff --git a/test/attr/attr_implements_serial.swift b/test/attr/attr_implements_serial.swift
new file mode 100644
index 0000000..b5e5583
--- /dev/null
+++ b/test/attr/attr_implements_serial.swift
@@ -0,0 +1,35 @@
+// RUN: %empty-directory(%t)
+// RUN: echo 'client()' >%t/main.swift
+// RUN: %target-swiftc_driver -module-name AttrImplFP -emit-module -emit-module-path %t/AttrImplFP.swiftmodule -emit-library -o %t/library.%target-dylib-extension %S/attr_implements_fp.swift
+// RUN: %target-swiftc_driver -I %t -o %t/a.out %s %t/main.swift %t/library.%target-dylib-extension
+// RUN: %target-codesign %t/a.out
+// RUN: %target-codesign %t/library.%target-dylib-extension
+// RUN: %target-run %t/a.out | %FileCheck %s
+// REQUIRES: executable_test
+
+// This test just checks that the lookup-table entries for @_implements are
+// also written-to and read-from serialized .swiftmodules
+
+import AttrImplFP
+
+public func client() {
+  assert(compare_Comparables(Fauxt.one, Fauxt.two))
+  assert(comparedAsComparablesCount == 1)
+  // CHECK: compared as Comparables
+  assert(compare_Comparables(Fauxt.one, Fauxt.nan))
+  assert(comparedAsComparablesCount == 2)
+  // CHECK: compared as Comparables
+  assert(!compare_Comparables(Fauxt.nan, Fauxt.one))
+  assert(comparedAsComparablesCount == 3)
+  // CHECK: compared as Comparables
+
+  assert(compare_Fauxts(Fauxt.one, Fauxt.two))
+  assert(comparedAsFauxtsCount == 1)
+  // CHECK: compared as Fauxts
+  assert(!compare_Fauxts(Fauxt.one, Fauxt.nan))
+  assert(comparedAsFauxtsCount == 2)
+  // CHECK: compared as Fauxts
+  assert(!compare_Fauxts(Fauxt.nan, Fauxt.one))
+  assert(comparedAsFauxtsCount == 3)
+  // CHECK: compared as Fauxts
+}
diff --git a/test/decl/protocol/req/associated_type_inference.swift b/test/decl/protocol/req/associated_type_inference.swift
index b00165e..8d8b92f 100644
--- a/test/decl/protocol/req/associated_type_inference.swift
+++ b/test/decl/protocol/req/associated_type_inference.swift
@@ -501,3 +501,10 @@
 struct Foo: RefinesAssocWithDefault {
 }
 
+protocol P20 {
+  associatedtype T // expected-note{{protocol requires nested type 'T'; do you want to add it?}}
+  typealias TT = T?
+}
+struct S19 : P20 {  // expected-error{{type 'S19' does not conform to protocol 'P20'}}
+  typealias TT = Int?
+}
diff --git a/tools/SourceKit/tools/sourcekitd-test/sourcekitd-test.cpp b/tools/SourceKit/tools/sourcekitd-test/sourcekitd-test.cpp
index 75275e4..17175f1 100644
--- a/tools/SourceKit/tools/sourcekitd-test/sourcekitd-test.cpp
+++ b/tools/SourceKit/tools/sourcekitd-test/sourcekitd-test.cpp
@@ -1963,11 +1963,10 @@
   const char *Ptr = InputBuf->getBufferStart();
   const char *End = InputBuf->getBufferEnd();
   const char *LineStart = Ptr;
-  for (; Ptr < End; ++Ptr) {
+  --Line;
+  for (; Line && (Ptr < End); ++Ptr) {
     if (*Ptr == '\n') {
       --Line;
-      if (Line == 0)
-        break;
       LineStart = Ptr+1;
     }
   }
diff --git a/tools/swift-api-digester/ModuleAnalyzerNodes.cpp b/tools/swift-api-digester/ModuleAnalyzerNodes.cpp
index d4f9a4d..a1e7a79 100644
--- a/tools/swift-api-digester/ModuleAnalyzerNodes.cpp
+++ b/tools/swift-api-digester/ModuleAnalyzerNodes.cpp
@@ -58,6 +58,7 @@
   StringRef EnumRawTypeName;
   TypeInitInfo TypeInfo;
   StringRef GenericSig;
+  bool HasSetter = false;
 
   SDKNodeInitInfo(SDKContext &Ctx) : Ctx(Ctx) {}
   SDKNodeInitInfo(SDKContext &Ctx, ValueDecl *VD);
@@ -130,12 +131,35 @@
 SDKNodeDeclSetter::SDKNodeDeclSetter(SDKNodeInitInfo Info):
   SDKNodeDeclAbstractFunc(Info, SDKNodeKind::DeclSetter) {}
 
+SDKNodeDeclAssociatedType::SDKNodeDeclAssociatedType(SDKNodeInitInfo Info):
+  SDKNodeDecl(Info, SDKNodeKind::DeclAssociatedType) {};
+
+SDKNodeDeclSubscript::SDKNodeDeclSubscript(SDKNodeInitInfo Info):
+  SDKNodeDeclAbstractFunc(Info, SDKNodeKind::DeclSubscript),
+  HasSetter(Info.HasSetter) {}
+
 StringRef SDKNodeDecl::getHeaderName() const {
   if (Location.empty())
     return StringRef();
   return llvm::sys::path::filename(Location.split(":").first);
 }
 
+SDKNodeDeclGetter *SDKNodeDeclVar::getGetter() const {
+  if (getChildrenCount() > 1)
+    return cast<SDKNodeDeclGetter>(childAt(1));
+  return nullptr;
+}
+
+SDKNodeDeclSetter *SDKNodeDeclVar::getSetter() const {
+  if (getChildrenCount() > 2)
+    return cast<SDKNodeDeclSetter>(childAt(2));
+  return nullptr;
+}
+
+SDKNodeType *SDKNodeDeclVar::getType() const {
+  return cast<SDKNodeType>(childAt(0));
+}
+
 NodePtr UpdatedNodesMap::findUpdateCounterpart(const SDKNode *Node) const {
   assert(Node->isAnnotatedAs(NodeAnnotation::Updated) && "Not update operation.");
   auto FoundPair = std::find_if(MapImpl.begin(), MapImpl.end(),
@@ -348,6 +372,8 @@
     case SDKNodeKind::DeclTypeAlias:
     case SDKNodeKind::DeclType:
     case SDKNodeKind::DeclVar:
+    case SDKNodeKind::DeclAssociatedType:
+    case SDKNodeKind::DeclSubscript:
       return true;
     case SDKNodeKind::Root:
     case SDKNodeKind::TypeNominal:
@@ -435,6 +461,7 @@
     case SDKNodeKind::DeclSetter:
     case SDKNodeKind::DeclGetter:
     case SDKNodeKind::DeclConstructor:
+    case SDKNodeKind::DeclSubscript:
       return true;
 
     default:
@@ -567,6 +594,9 @@
       case KeyKind::KK_implicit:
         Info.IsImplicit = true;
         break;
+      case KeyKind::KK_hasSetter:
+        Info.HasSetter = true;
+        break;
       case KeyKind::KK_ownership:
         Info.ReferenceOwnership =
             swift::ReferenceOwnership(getAsInt(Pair.getValue()));
@@ -731,6 +761,14 @@
       }
       LLVM_FALLTHROUGH;
     }
+    case SDKNodeKind::DeclAssociatedType:
+    case SDKNodeKind::DeclSubscript: {
+      auto *Left = dyn_cast<SDKNodeDeclSubscript>(this);
+      auto *Right = dyn_cast<SDKNodeDeclSubscript>(&Other);
+      if (Left && Right && Left->hasSetter() != Right->hasSetter())
+        return false;
+      LLVM_FALLTHROUGH;
+    }
     case SDKNodeKind::DeclTypeAlias: {
       auto Left = this->getAs<SDKNodeDecl>();
       auto Right = (&Other)->getAs<SDKNodeDecl>();
@@ -863,9 +901,8 @@
 
 static StringRef getPrintedName(SDKContext &Ctx, ValueDecl *VD) {
   llvm::SmallString<32> Result;
-  if (auto FD = dyn_cast<AbstractFunctionDecl>(VD)) {
-    auto DM = FD->getFullName();
-
+  DeclName DM = VD->getFullName();
+  if (isa<AbstractFunctionDecl>(VD) || isa<SubscriptDecl>(VD)) {
     if (DM.getBaseName().empty()) {
       Result.append("_");
     } else {
@@ -880,7 +917,6 @@
     Result.append(")");
     return Ctx.buffer(Result.str());
   }
-  auto DM = VD->getFullName();
   Result.append(getEscapedName(DM.getBaseName()));
   return Ctx.buffer(Result.str());
 }
@@ -1047,6 +1083,11 @@
       }
     }
   }
+
+  // Record whether a subscript has getter/setter.
+  if (auto *SD = dyn_cast<SubscriptDecl>(VD)) {
+    HasSetter = SD->getSetter();
+  }
 }
 
 SDKNode *SDKNodeInitInfo::createSDKNode(SDKNodeKind Kind) {
@@ -1238,8 +1279,10 @@
   if (auto VAD = dyn_cast<AbstractStorageDecl>(VD)) {
     if (auto Getter = VAD->getGetter())
       Var->addChild(constructFunctionNode(Ctx, Getter, SDKNodeKind::DeclGetter));
-    if (auto Setter = VAD->getSetter())
-      Var->addChild(constructFunctionNode(Ctx, Setter, SDKNodeKind::DeclSetter));
+    if (auto Setter = VAD->getSetter()) {
+      if (Setter->getFormalAccess() > AccessLevel::Internal)
+        Var->addChild(constructFunctionNode(Ctx, Setter, SDKNodeKind::DeclSetter));
+    }
   }
   return Var;
 }
@@ -1250,6 +1293,24 @@
   return Alias;
 }
 
+static SDKNode *constructAssociatedTypeNode(SDKContext &Ctx,
+                                            AssociatedTypeDecl *ATD) {
+  auto Asso = SDKNodeInitInfo(Ctx, ATD).
+    createSDKNode(SDKNodeKind::DeclAssociatedType);
+  if (auto DT = ATD->getDefaultDefinitionType()) {
+    Asso->addChild(constructTypeNode(Ctx, DT));
+  }
+  return Asso;
+}
+
+static SDKNode *constructSubscriptDeclNode(SDKContext &Ctx, SubscriptDecl *SD) {
+  auto Subs = SDKNodeInitInfo(Ctx, SD).createSDKNode(SDKNodeKind::DeclSubscript);
+  Subs->addChild(constructTypeNode(Ctx, SD->getElementInterfaceType()));
+  for (auto *Node: createParameterNodes(Ctx, SD->getIndices()))
+    Subs->addChild(Node);
+  return Subs;
+}
+
 static void addMembersToRoot(SDKContext &Ctx, SDKNode *Root,
                              IterableDeclContext *Context,
                              std::set<ExtensionDecl*> &HandledExts) {
@@ -1268,6 +1329,16 @@
       Root->addChild(constructVarNode(Ctx, EED));
     } else if (auto NTD = dyn_cast<NominalTypeDecl>(Member)) {
       Root->addChild(constructTypeDeclNode(Ctx, NTD, HandledExts));
+    } else if (auto ATD = dyn_cast<AssociatedTypeDecl>(Member)) {
+      Root->addChild(constructAssociatedTypeNode(Ctx, ATD));
+    } else if (auto SD = dyn_cast<SubscriptDecl>(Member)) {
+      Root->addChild(constructSubscriptDeclNode(Ctx, SD));
+    } else if (isa<PatternBindingDecl>(Member)) {
+      // All containing variables should have been handled.
+    } else if (isa<DestructorDecl>(Member)) {
+      // deinit has no impact.
+    } else {
+      llvm_unreachable("unhandled member decl kind.");
     }
   }
 }
@@ -1427,6 +1498,12 @@
           out.mapRequired(getKeyContent(Ctx, KeyKind::KK_selfIndex).data(),
                           Index);
         }
+        if (auto S = dyn_cast<SDKNodeDeclSubscript>(value)) {
+          if (bool hasSetter = S->hasSetter()) {
+            out.mapRequired(getKeyContent(Ctx, KeyKind::KK_hasSetter).data(),
+                            hasSetter);
+          }
+        }
       }
       if (auto *TD = dyn_cast<SDKNodeDeclType>(value)) {
         auto Super = TD->getSuperClassUsr();
diff --git a/tools/swift-api-digester/ModuleAnalyzerNodes.h b/tools/swift-api-digester/ModuleAnalyzerNodes.h
index 8835863..fb4e38d 100644
--- a/tools/swift-api-digester/ModuleAnalyzerNodes.h
+++ b/tools/swift-api-digester/ModuleAnalyzerNodes.h
@@ -207,7 +207,8 @@
 };
 
 class SDKNodeRoot;
-
+class SDKNodeDeclGetter;
+class SDKNodeDeclSetter;
 struct SDKNodeInitInfo;
 
 class SDKNode {
@@ -440,6 +441,15 @@
   static bool classof(const SDKNode *N);
 };
 
+class SDKNodeDeclAssociatedType: public SDKNodeDecl {
+public:
+  SDKNodeDeclAssociatedType(SDKNodeInitInfo Info);
+  const SDKNodeType* getDefault() const {
+    return getChildrenCount() ? getOnlyChild()->getAs<SDKNodeType>(): nullptr;
+  }
+  static bool classof(const SDKNode *N);
+};
+
 class SDKNodeDeclVar : public SDKNodeDecl {
   Optional<unsigned> FixedBinaryOrder;
 public:
@@ -447,6 +457,9 @@
   static bool classof(const SDKNode *N);
   bool hasFixedBinaryOrder() const { return FixedBinaryOrder.hasValue(); }
   unsigned getFixedBinaryOrder() const { return *FixedBinaryOrder; }
+  SDKNodeDeclGetter *getGetter() const;
+  SDKNodeDeclSetter *getSetter() const;
+  SDKNodeType *getType() const;
 };
 
 class SDKNodeDeclAbstractFunc : public SDKNodeDecl {
@@ -466,6 +479,14 @@
   static StringRef getTypeRoleDescription(SDKContext &Ctx, unsigned Index);
 };
 
+class SDKNodeDeclSubscript: public SDKNodeDeclAbstractFunc {
+  bool HasSetter;
+public:
+  SDKNodeDeclSubscript(SDKNodeInitInfo Info);
+  static bool classof(const SDKNode *N);
+  bool hasSetter() const { return HasSetter; }
+};
+
 class SDKNodeDeclFunction: public SDKNodeDeclAbstractFunc {
 public:
   SDKNodeDeclFunction(SDKNodeInitInfo Info);
diff --git a/tools/swift-api-digester/ModuleDiagsConsumer.cpp b/tools/swift-api-digester/ModuleDiagsConsumer.cpp
index cfc21aa..f570302 100644
--- a/tools/swift-api-digester/ModuleDiagsConsumer.cpp
+++ b/tools/swift-api-digester/ModuleDiagsConsumer.cpp
@@ -33,6 +33,7 @@
 static StringRef getCategoryName(uint32_t ID) {
   switch(ID) {
   case LocalDiagID::removed_decl:
+  case LocalDiagID::removed_setter:
     return "/* Removed Decls */";
   case LocalDiagID::moved_decl:
     return "/* Moved Decls */";
@@ -54,6 +55,8 @@
   case LocalDiagID::conformance_added:
   case LocalDiagID::conformance_removed:
     return "/* Protocol Conformance Change */";
+  case LocalDiagID::default_associated_type_removed:
+    return "/* Protocol Requirement Change */";
   default:
     return StringRef();
   }
diff --git a/tools/swift-api-digester/swift-api-digester.cpp b/tools/swift-api-digester/swift-api-digester.cpp
index 5cb4c3a..060aef5 100644
--- a/tools/swift-api-digester/swift-api-digester.cpp
+++ b/tools/swift-api-digester/swift-api-digester.cpp
@@ -817,6 +817,13 @@
     case NodeMatchReason::Removed:
       assert(!Right);
       Left->annotate(NodeAnnotation::Removed);
+      if (auto *LT = dyn_cast<SDKNodeType>(Left)) {
+        if (auto *AT = dyn_cast<SDKNodeDeclAssociatedType>(LT->getParent())) {
+          Ctx.getDiags().diagnose(SourceLoc(),
+                                  diag::default_associated_type_removed,
+                                  AT->getScreenInfo(), LT->getPrintedName());
+        }
+      }
       return;
     case NodeMatchReason::FuncToProperty:
     case NodeMatchReason::ModernizeEnum:
@@ -860,6 +867,17 @@
       break;
     }
 
+    case SDKNodeKind::DeclSubscript: {
+      if (auto *LS = dyn_cast<SDKNodeDeclSubscript>(Left)) {
+        auto *RS = cast<SDKNodeDeclSubscript>(Right);
+        if (LS->hasSetter() && !RS->hasSetter()) {
+          Ctx.getDiags().diagnose(SourceLoc(), diag::removed_setter,
+                                  LS->getScreenInfo());
+        }
+      }
+      LLVM_FALLTHROUGH;
+    }
+    case SDKNodeKind::DeclAssociatedType:
     case SDKNodeKind::DeclFunction:
     case SDKNodeKind::DeclSetter:
     case SDKNodeKind::DeclGetter:
@@ -877,10 +895,16 @@
     }
 
     case SDKNodeKind::DeclVar: {
-      auto LC = Left->getChildren()[0];
-      auto RC = Right->getChildren()[0];
+      auto LVar = cast<SDKNodeDeclVar>(Left);
+      auto RVar = cast<SDKNodeDeclVar>(Right);
+      auto LC = LVar->getType();
+      auto RC = RVar->getType();
       if (!(*LC == *RC))
         foundMatch(LC, RC, NodeMatchReason::Sequential);
+      if (LVar->getSetter() && !RVar->getSetter()) {
+          Ctx.getDiags().diagnose(SourceLoc(), diag::removed_setter,
+                                  LVar->getScreenInfo());
+      }
       break;
     }
     }
@@ -1732,6 +1756,10 @@
         Diags.diagnose(SourceLoc(), diag::decl_type_change, Parent->getScreenInfo(),
           Descriptor, Node->getPrintedName(), Count->getPrintedName());
       break;
+    case SDKNodeKind::DeclAssociatedType:
+      Diags.diagnose(SourceLoc(), diag::decl_type_change, Parent->getScreenInfo(),
+                     "default", Node->getPrintedName(), Count->getPrintedName());
+      break;
     default:
       break;
     }