Merge pull request #23621 from sarveshtamba/master

diff --git a/CMakeLists.txt b/CMakeLists.txt
index 8d27ca0..25bf8d5 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -409,30 +409,13 @@
   include(ClangClCompileRules)
 endif()
 
-precondition(CMAKE_SYSTEM_NAME)
-if("${CMAKE_SYSTEM_NAME}" STREQUAL "Darwin")
+if(CMAKE_SYSTEM_NAME STREQUAL Darwin OR
+    EXISTS ${SWIFT_PATH_TO_LIBDISPATCH_SOURCE})
   set(SWIFT_BUILD_SYNTAXPARSERLIB_default TRUE)
   set(SWIFT_BUILD_SOURCEKIT_default TRUE)
-elseif("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux")
-  if(EXISTS ${SWIFT_PATH_TO_LIBDISPATCH_SOURCE})
-    set(SWIFT_BUILD_SYNTAXPARSERLIB_default TRUE)
-    set(SWIFT_BUILD_SOURCEKIT_default TRUE)
-  else()
-    set(SWIFT_BUILD_SYNTAXPARSERLIB_default FALSE)
-    set(SWIFT_BUILD_SOURCEKIT_default FALSE)
-  endif()
-elseif(CMAKE_SYSTEM_NAME STREQUAL Windows)
-  if(EXISTS ${SWIFT_PATH_TO_LIBDISPATCH_SOURCE} AND
-     CMAKE_CXX_COMPILER_ID STREQUAL Clang)
-    set(SWIFT_BUILD_SYNTAXPARSERLIB_default TRUE)
-    set(SWIFT_BUILD_SOURCEKIT_default TRUE)
-  else()
-    set(SWIFT_BUILD_SYNTAXPARSERLIB_default FALSE)
-    set(SWIFT_BUILD_SOURCEKIT_default FALSE)
-  endif()
 else()
-    set(SWIFT_BUILD_SYNTAXPARSERLIB_default FALSE)
-    set(SWIFT_BUILD_SOURCEKIT_default FALSE)
+  set(SWIFT_BUILD_SYNTAXPARSERLIB_default FALSE)
+  set(SWIFT_BUILD_SOURCEKIT_default FALSE)
 endif()
 option(SWIFT_BUILD_SYNTAXPARSERLIB
     "Build the Swift Syntax Parser library"
diff --git a/cmake/modules/SwiftComponents.cmake b/cmake/modules/SwiftComponents.cmake
index fba6e55..a637e31 100644
--- a/cmake/modules/SwiftComponents.cmake
+++ b/cmake/modules/SwiftComponents.cmake
@@ -61,11 +61,12 @@
 #   Xcode;
 # * tools -- tools (other than the compiler) useful for developers writing
 #   Swift code.
+# * toolchain-tools -- a subset of tools that we will install to the OSS toolchain.
 # * testsuite-tools -- extra tools required to run the Swift testsuite.
 # * toolchain-dev-tools -- install development tools useful in a shared toolchain
 # * dev -- headers and libraries required to use Swift compiler as a library.
 set(_SWIFT_DEFINED_COMPONENTS
-  "autolink-driver;compiler;clang-builtin-headers;clang-resource-dir-symlink;clang-builtin-headers-in-clang-resource-dir;stdlib;stdlib-experimental;sdk-overlay;parser-lib;editor-integration;tools;testsuite-tools;toolchain-dev-tools;dev;license;sourcekit-xpc-service;sourcekit-inproc;swift-remote-mirror;swift-remote-mirror-headers")
+  "autolink-driver;compiler;clang-builtin-headers;clang-resource-dir-symlink;clang-builtin-headers-in-clang-resource-dir;stdlib;stdlib-experimental;sdk-overlay;parser-lib;editor-integration;tools;testsuite-tools;toolchain-tools;toolchain-dev-tools;dev;license;sourcekit-xpc-service;sourcekit-inproc;swift-remote-mirror;swift-remote-mirror-headers")
 
 # The default install components include all of the defined components, except
 # for the following exceptions.
@@ -143,6 +144,24 @@
   install(${ARGN})
 endfunction()
 
+# swift_install_in_either_component(<COMPONENT1 NAME> <COMPONENT2 NAME>
+#   <same parameters as install()>)
+#
+# Executes the specified installation actions if either one of the named
+# components is requested to be installed.
+#
+# This function accepts the same parameters as install().
+function(swift_install_in_either_component comp1 comp2)
+  foreach(component ${comp1} ${comp2})
+    precondition(component MESSAGE "Component name is required")
+    swift_is_installing_component("${component}" is_installing)
+    if(is_installing)
+      install(${ARGN})
+      return()
+    endif()
+  endforeach(component)
+endfunction()
+
 function(swift_install_symlink_component component)
   cmake_parse_arguments(
       ARG # prefix
diff --git a/cmake/modules/SwiftWindowsSupport.cmake b/cmake/modules/SwiftWindowsSupport.cmake
index fb4ebb7..1ddbf84 100644
--- a/cmake/modules/SwiftWindowsSupport.cmake
+++ b/cmake/modules/SwiftWindowsSupport.cmake
@@ -80,3 +80,28 @@
   set(UCRTVersion $ENV{UCRTVersion} CACHE STRING "")
 endfunction()
 
+# NOTE(compnerd) we use a macro here as this modifies global variables
+macro(swift_swap_compiler_if_needed target)
+  if(NOT CMAKE_C_COMPILER_ID MATCHES Clang)
+    if(CMAKE_SYSTEM_NAME STREQUAL CMAKE_HOST_SYSTEM_NAME)
+      get_target_property(CLANG_LOCATION clang LOCATION)
+      get_filename_component(CLANG_LOCATION ${CLANG_LOCATION} DIRECTORY)
+
+      if("${CMAKE_C_COMPILER_ID}" STREQUAL "MSVC" OR
+          "${CMAKE_C_SIMULATE_ID}" STREQUAL "MSVC")
+        set(CMAKE_C_COMPILER
+          ${CLANG_LOCATION}/clang-cl${CMAKE_EXECUTABLE_SUFFIX})
+        set(CMAKE_CXX_COMPILER
+          ${CLANG_LOCATION}/clang-cl${CMAKE_EXECUTABLE_SUFFIX})
+      else()
+        set(CMAKE_C_COMPILER
+          ${CLANG_LOCATION}/clang${CMAKE_EXECUTABLE_SUFFIX})
+        set(CMAKE_CXX_COMPILER
+          ${CLANG_LOCATION}/clang++${CMAKE_EXECUTABLE_SUFFIX})
+      endif()
+    else()
+      message(SEND_ERROR "${target} requires a clang based compiler")
+    endif()
+  endif()
+endmacro()
+
diff --git a/docs/WindowsBuild.md b/docs/WindowsBuild.md
index c0285e8..8c51483 100644
--- a/docs/WindowsBuild.md
+++ b/docs/WindowsBuild.md
@@ -1,35 +1,14 @@
 # Building Swift on Windows
 
-This document describes how to build Swift for Windows natively. See [the
-Windows doc](./Windows.md) for more about what is possible with Swift on
-Windows.
+Visual Studio 2017 or newer is needed to build swift on Windows.
 
-There are two supported ways to build Swift on Windows:
-
-1. Using [`clang-cl`](https://clang.llvm.org/docs/UsersManual.html#clang-cl)
-1. Using the Microsoft Visual C++ compiler (MSVC)
-
-`clang-cl` is recommended over MSVC for building Swift on Windows.
-
-Although it is possible to build the compiler and the standard library with
-MSVC and to use those built products to compile a Swift program, it won't be
-possible to run the binary without separately obtaining the Swift runtime. On
-the other hand, `clang-cl` is able to build the runtime, which makes it
-possible to build and run all the components required for Swift natively on
-Windows.
-
-clang should be 7.0 or newer. Visual Studio 2017 is needed in all cases as
-it provides some of the needed headers and libraries.
-
-## `clang-cl`
-
-### 1. Install dependencies
+## 1. Install dependencies
 1. Latest version of [Visual Studio](https://www.visualstudio.com/downloads/)
 - Make sure to include "Programming Languages|Visual C++" and "Windows and Web
   Development|Universal Windows App Development|Windows SDK" in your
   installation.
 
-### 2. Clone the repositories
+## 2. Clone the repositories
 1. Configure git to work with Unix file endings
 1. Create a folder to contain all the Swift repositories
 1. Clone `apple/swift-cmark` into a folder named `cmark`
@@ -72,7 +51,7 @@
 git clone https://gitlab.gnome.org/GNOME/libxml2.git
 ```
 
-### 3. Acquire ICU
+## 3. Acquire ICU
 1. Download ICU from [ICU Project](http://site.icu-project.org) for Windows x64 and extract the binaries.
 1. Add the `bin64` folder to your `Path` environment variable.
 
@@ -80,7 +59,7 @@
 PATH S:\icu\bin64;%PATH%
 ```
 
-### 4. Fetch SQLite3
+## 4. Fetch SQLite3
 
 ```powershell
 (New-Object System.Net.WebClient).DownloadFile("https://www.sqlite.org/2019/sqlite-amalgamation-3270200.zip", "S:\sqlite-amalgamation-3270200.zip")
@@ -88,7 +67,7 @@
 [IO.Compression.ZipFile]::ExtractToDirectory("S:\sqlite-amalgamation-3270200.zip", "S:\")
 ```
 
-### 5. Get ready
+## 5. Get ready
 - From within a **developer** command prompt (not PowerShell nor cmd, but the [Visual Studio Developer Command Prompt](https://msdn.microsoft.com/en-us/library/f35ctcxw.aspx)), execute the following command if you have an x64 PC.
 
 ```cmd
@@ -119,7 +98,7 @@
 
 Warning: Creating the above links usually requires administrator privileges. The quick and easy way to do this is to open a second developer prompt by right clicking whatever shortcut you used to open the first one, choosing Run As Administrator, and pasting the above commands into the resulting window. You can then close the privileged prompt; this is the only step which requires elevation.
 
-### 6. Build LLVM/Clang
+## 6. Build LLVM/Clang
 - This must be done from within a developer command prompt. LLVM and Clang are
   large projects, so building might take a few hours. Make sure that the build
   type for LLVM/Clang is compatbile with the build type for Swift. That is,
@@ -147,8 +126,7 @@
 ```cmd
 path S:\b\llvm\bin;%PATH%
 ```
-
-### 7. Build CMark
+## 7. Build CMark
 - This must be done from within a developer command prompt. CMark is a fairly
   small project and should only take a few minutes to build.
 ```cmd
@@ -163,7 +141,7 @@
 cmake --build "S:\b\cmark"
 ```
 
-### 8. Build Swift
+## 8. Build Swift
 - This must be done from within a developer command prompt
 - Note that Visual Studio vends a 32-bit python 2.7 installation in `C:\Python27` and a 64-bit python in `C:\Python27amd64`.  You may use either one based on your installation.
 
@@ -204,7 +182,7 @@
 cmake -G "Visual Studio 2017" -A x64 -T "host=x64"^ ...
 ```
 
-### 9. Build lldb
+## 9. Build lldb
 - This must be done from within a developer command prompt and could take hours
   depending on your system.
 ```cmd
@@ -225,7 +203,7 @@
 cmake --build S:\b\lldb
 ```
 
-### 10. Running tests on Windows
+## 10. Running tests on Windows
 
 Running the testsuite on Windows has additional external dependencies.  You must have a subset of the GNUWin32 programs installed and available in your path.  The following packages are currently required:
 
@@ -239,7 +217,7 @@
 ninja -C S:\b\swift check-swift
 ```
 
-### 11. Build swift-corelibs-libdispatch
+## 11. Build swift-corelibs-libdispatch
 
 ```cmd
 mkdir "S:\b\libdispatch"
@@ -261,7 +239,7 @@
 path S:\b\libdispatch;S:\b\libdispatch\src;%PATH%
 ```
 
-### 12. Build curl
+## 12. Build curl
 
 ```cmd
 pushd "S:\curl"
@@ -271,7 +249,7 @@
 popd
 ```
 
-### 13. Build libxml2
+## 13. Build libxml2
 
 ```cmd
 pushd "S:\libxml2\win32"
@@ -280,7 +258,7 @@
 popd
 ```
 
-### 14. Build swift-corelibs-foundation
+## 14. Build swift-corelibs-foundation
 
 ```cmd
 mkdir "S:\b\foundation"
@@ -307,7 +285,7 @@
 path S:\b\foundation;%PATH%
 ```
 
-### 15. Build swift-corelibs-xctest
+## 15. Build swift-corelibs-xctest
 
 ```cmd
 mkdir "S:\b\xctest"
@@ -332,13 +310,13 @@
 path S:\b\xctest;%PATH%
 ```
 
-### 16. Test XCTest
+## 16. Test XCTest
 
 ```cmd
 ninja -C S:\b\xctest check-xctest
 ```
 
-### 17. Rebuild Foundation
+## 17. Rebuild Foundation
 
 ```cmd
 mkdir "S:\b\foundation"
@@ -361,14 +339,14 @@
  cmake --build S:\b\foundation
 ```
 
-### 18. Test Foundation
+## 18. Test Foundation
 
 ```cmd
 cmake --build S:\b\foundation
 ninja -C S:\b\foundation test 
 ```
 
-### 19. Build SQLite3
+## 19. Build SQLite3
 
 ```cmd
 md S:\b\sqlite
@@ -381,7 +359,7 @@
 path S:\b\sqlite;%PATH%
 ```
 
-### 20. Build llbuild
+## 20. Build llbuild
 
 ```cmd
 md S:\b\llbuild
@@ -401,7 +379,7 @@
 path S:\b\llbuild;%PATH%
 ```
 
-### 21. Build swift-package-manager
+## 21. Build swift-package-manager
 
 ```cmd
 md S:\b\spm
@@ -409,7 +387,7 @@
 C:\Python27\python.exe S:\swift-package-manager\Utilities\bootstrap --foundation S:\b\foundation --libdispatch-build-dir S:\b\libdispatch --libdispatch-source-dir S:\swift-corelibs-libdispatch --llbuild-build-dir S:\b\llbuild --llbuild-source-dir S:\llbuild --sqlite-build-dir S:\b\sqlite --sqlite-source-dir S:\sqlite-amalgamation-3270200
 ```
 
-### 22. Install Swift on Windows
+## 22. Install Swift on Windows
 
 - Run ninja install:
 
diff --git a/include/swift/AST/ASTTypeIDZone.def b/include/swift/AST/ASTTypeIDZone.def
new file mode 100644
index 0000000..3a19b31
--- /dev/null
+++ b/include/swift/AST/ASTTypeIDZone.def
@@ -0,0 +1,19 @@
+//===--- ASTTypeIDZone.def - Define the AST TypeID Zone ---------*- C++ -*-===//
+//
+// This source file is part of the Swift.org open source project
+//
+// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See https://swift.org/LICENSE.txt for license information
+// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
+//
+//===----------------------------------------------------------------------===//
+//
+//  This definition file describes the types in the "AST" TypeID zone,
+//  for use with the TypeID template.
+//
+//===----------------------------------------------------------------------===//
+SWIFT_TYPEID_NAMED(NominalTypeDecl *, NominalTypeDecl)
+SWIFT_TYPEID_NAMED(VarDecl *, VarDecl)
+SWIFT_TYPEID(PropertyBehaviorTypeInfo)
diff --git a/include/swift/AST/ASTTypeIDs.h b/include/swift/AST/ASTTypeIDs.h
new file mode 100644
index 0000000..e13342c
--- /dev/null
+++ b/include/swift/AST/ASTTypeIDs.h
@@ -0,0 +1,36 @@
+//===--- ASTTypeIDs.h - AST Type Ids ----------------------------*- C++ -*-===//
+//
+// This source file is part of the Swift.org open source project
+//
+// Copyright (c) 2019 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
+//
+//===----------------------------------------------------------------------===//
+//
+//  This file defines TypeID support for AST types.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef SWIFT_AST_ASTTYPEIDS_H
+#define SWIFT_AST_ASTTYPEIDS_H
+
+#include "swift/Basic/TypeID.h"
+namespace swift {
+
+class NominalTypeDecl;
+struct PropertyBehaviorTypeInfo;
+class VarDecl;
+
+#define SWIFT_AST_TYPEID_ZONE 1
+
+// Define the AST type zone (zone 1)
+#define SWIFT_TYPEID_ZONE SWIFT_AST_TYPEID_ZONE
+#define SWIFT_TYPEID_HEADER "swift/AST/ASTTypeIDZone.def"
+#include "swift/Basic/DefineTypeIDZone.h"
+
+} // end namespace swift
+
+#endif /* SWIFT_AST_ASTTYPEIDS_H */
diff --git a/include/swift/AST/Attr.def b/include/swift/AST/Attr.def
index b36a01d..f9f0be8 100644
--- a/include/swift/AST/Attr.def
+++ b/include/swift/AST/Attr.def
@@ -390,6 +390,12 @@
 SIMPLE_DECL_ATTR(_alwaysEmitIntoClient, AlwaysEmitIntoClient,
   OnVar | OnSubscript | OnAbstractFunction | UserInaccessible,
   83)
+SIMPLE_DECL_ATTR(_implementationOnly, ImplementationOnly,
+  OnImport | UserInaccessible,
+  84)
+DECL_ATTR(_custom, Custom,
+  OnAnyDecl | UserInaccessible,
+  85)
 
 #undef TYPE_ATTR
 #undef DECL_ATTR_ALIAS
diff --git a/include/swift/AST/Attr.h b/include/swift/AST/Attr.h
index d6b3598..c9e5324 100644
--- a/include/swift/AST/Attr.h
+++ b/include/swift/AST/Attr.h
@@ -32,6 +32,7 @@
 #include "swift/AST/Ownership.h"
 #include "swift/AST/PlatformKind.h"
 #include "swift/AST/Requirement.h"
+#include "swift/AST/TrailingCallArguments.h"
 #include "swift/AST/TypeLoc.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
@@ -49,6 +50,7 @@
 class ClassDecl;
 class GenericFunctionType;
 class LazyConformanceLoader;
+class PatternBindingInitializer;
 class TrailingWhereClause;
 
 /// TypeAttributes - These are attributes that may be applied to types.
@@ -1408,6 +1410,54 @@
   }
 };
 
+/// Defines a custom attribute.
+class CustomAttr final : public DeclAttribute,
+                         public TrailingCallArguments<CustomAttr> {
+  TypeLoc type;
+  Expr *arg;
+  PatternBindingInitializer *initContext;
+
+  unsigned hasArgLabelLocs : 1;
+  unsigned numArgLabels : 16;
+
+  CustomAttr(SourceLoc atLoc, SourceRange range, TypeLoc type,
+             PatternBindingInitializer *initContext, Expr *arg,
+             ArrayRef<Identifier> argLabels, ArrayRef<SourceLoc> argLabelLocs,
+             bool implicit);
+
+public:
+  static CustomAttr *create(ASTContext &ctx, SourceLoc atLoc, TypeLoc type,
+                            bool implicit = false) {
+    return create(ctx, atLoc, type, false, nullptr, SourceLoc(), { }, { }, { },
+                  SourceLoc(), implicit);
+  }
+
+  static CustomAttr *create(ASTContext &ctx, SourceLoc atLoc, TypeLoc type,
+                            bool hasInitializer,
+                            PatternBindingInitializer *initContext,
+                            SourceLoc lParenLoc,
+                            ArrayRef<Expr *> args,
+                            ArrayRef<Identifier> argLabels,
+                            ArrayRef<SourceLoc> argLabelLocs,
+                            SourceLoc rParenLoc,
+                            bool implicit = false);
+
+  unsigned getNumArguments() const { return numArgLabels; }
+  bool hasArgumentLabelLocs() const { return hasArgLabelLocs; }
+
+  TypeLoc &getTypeLoc() { return type; }
+  const TypeLoc &getTypeLoc() const { return type; }
+
+  Expr *getArg() const { return arg; }
+  void setArg(Expr *newArg) { arg = newArg; }
+
+  PatternBindingInitializer *getInitContext() const { return initContext; }
+
+  static bool classof(const DeclAttribute *DA) {
+    return DA->getKind() == DAK_Custom;
+  }
+};
+
 /// Attributes that may be applied to declarations.
 class DeclAttributes {
   /// Linked list of declaration attributes.
@@ -1584,6 +1634,8 @@
   SourceLoc getStartLoc(bool forModifiers = false) const;
 };
 
+void simple_display(llvm::raw_ostream &out, const DeclAttribute *attr);
+
 } // end namespace swift
 
 #endif
diff --git a/include/swift/AST/Decl.h b/include/swift/AST/Decl.h
index a4eeb75..095cf78 100644
--- a/include/swift/AST/Decl.h
+++ b/include/swift/AST/Decl.h
@@ -3647,6 +3647,19 @@
     Bits.ClassDecl.Circularity = static_cast<unsigned>(circularity);
   }
 
+  /// Walk this class and all of the superclasses of this class, transitively,
+  /// invoking the callback function for each class.
+  ///
+  /// \param fn The callback function that will be invoked for each superclass.
+  /// It can return \c Continue to continue the traversal. Returning
+  /// \c SkipChildren halts the search and returns \c false, while returning
+  /// \c Stop halts the search and returns \c true.
+  ///
+  /// \returns \c true if \c fn returned \c Stop for any class, \c false
+  /// otherwise.
+  bool walkSuperclasses(
+      llvm::function_ref<TypeWalker::Action(ClassDecl *)> fn) const;
+
   //// Whether this class requires all of its stored properties to
   //// have initializers in the class definition.
   bool requiresStoredPropertyInits() const { 
@@ -3975,8 +3988,8 @@
   /// a protocol having nested types (ObjC protocols).
   llvm::TinyPtrVector<AssociatedTypeDecl *> getAssociatedTypeMembers() const;
 
-  /// Walk all of the protocols inherited by this protocol, transitively,
-  /// invoking the callback function for each protocol.
+  /// Walk this protocol and all of the protocols inherited by this protocol,
+  /// transitively, invoking the callback function for each protocol.
   ///
   /// \param fn The callback function that will be invoked for each inherited
   /// protocol. It can return \c Continue to continue the traversal,
diff --git a/include/swift/AST/DiagnosticsSema.def b/include/swift/AST/DiagnosticsSema.def
index 56c2d0e..69815cb 100644
--- a/include/swift/AST/DiagnosticsSema.def
+++ b/include/swift/AST/DiagnosticsSema.def
@@ -765,6 +765,9 @@
 ERROR(module_not_compiled_for_private_import,none,
       "module %0 was not compiled for private import", (Identifier))
 
+ERROR(import_implementation_cannot_be_exported,none,
+      "module %0 cannot be both exported and implementation-only", (Identifier))
+
 
 // Operator decls
 ERROR(ambiguous_operator_decls,none,
@@ -1101,6 +1104,9 @@
 ERROR(attribute_requires_single_argument,none,
       "'%0' requires a function with one argument", (StringRef))
 
+ERROR(nominal_type_not_attribute,none,
+      "%0 %1 cannot be used as an attribute", (DescriptiveDeclKind, DeclName))
+
 ERROR(mutating_invalid_global_scope,none, "%0 is only valid on methods",
       (SelfAccessKind))
 ERROR(mutating_invalid_classes,none, "%0 isn't valid on methods in "
diff --git a/include/swift/AST/Expr.h b/include/swift/AST/Expr.h
index 3beb297..61dfba7 100644
--- a/include/swift/AST/Expr.h
+++ b/include/swift/AST/Expr.h
@@ -22,6 +22,7 @@
 #include "swift/AST/DeclNameLoc.h"
 #include "swift/AST/FunctionRefKind.h"
 #include "swift/AST/ProtocolConformanceRef.h"
+#include "swift/AST/TrailingCallArguments.h"
 #include "swift/AST/TypeAlignments.h"
 #include "swift/AST/TypeLoc.h"
 #include "swift/AST/TypeRepr.h"
@@ -295,19 +296,6 @@
     NumElements : 16
   );
 
-  SWIFT_INLINE_BITFIELD_FULL(ArgumentShuffleExpr, ImplicitConversionExpr, 2+16+16+16,
-    TypeImpact : 2,
-    : NumPadBits,
-    NumCallerDefaultArgs : 16,
-    /// This contains an entry for each element in the Expr type.  Each element
-    /// specifies which index from the SubExpr that the destination element gets.
-    /// If the element value is DefaultInitialize, then the destination value
-    /// gets the default initializer for that tuple element value.
-    NumElementMappings : 16,
-    /// The arguments that are packed into the variadic element.
-    NumVariadicArgs : 16
-  );
-
   SWIFT_INLINE_BITFIELD(ForceValueExpr, Expr, 1,
     ForcedIUO : 1
   );
@@ -570,105 +558,6 @@
   }
 };
 
-/// Helper class to capture trailing call argument labels and related
-/// information, for expression nodes that involve argument labels, trailing
-/// closures, etc.
-template<typename Derived>
-class TrailingCallArguments
-    : private llvm::TrailingObjects<Derived, Identifier, SourceLoc> {
-  // We need to friend TrailingObjects twice here to work around an MSVC bug.
-  // If we have two functions of the same name with the parameter
-  // typename TrailingObjectsIdentifier::template OverloadToken<T> where T is
-  // different for each function, then MSVC reports a "member function already
-  // defined or declared" error, which is incorrect.
-  using TrailingObjectsIdentifier = llvm::TrailingObjects<Derived, Identifier>;
-  friend TrailingObjectsIdentifier;
-
-  using TrailingObjects = llvm::TrailingObjects<Derived, Identifier, SourceLoc>;
-  friend TrailingObjects;
-
-  Derived &asDerived() {
-    return *static_cast<Derived *>(this);
-  }
-
-  const Derived &asDerived() const {
-    return *static_cast<const Derived *>(this);
-  }
-
-  size_t numTrailingObjects(
-      typename TrailingObjectsIdentifier::template OverloadToken<Identifier>)
-      const {
-    return asDerived().getNumArguments();
-  }
-
-  size_t numTrailingObjects(
-      typename TrailingObjectsIdentifier::template OverloadToken<SourceLoc>)
-      const {
-    return asDerived().hasArgumentLabelLocs() ? asDerived().getNumArguments()
-                                              : 0;
-  }
-
-  /// Retrieve the buffer containing the argument labels.
-  MutableArrayRef<Identifier> getArgumentLabelsBuffer() {
-    return { this->template getTrailingObjects<Identifier>(),
-             asDerived().getNumArguments() };
-  }
-
-  /// Retrieve the buffer containing the argument label locations.
-  MutableArrayRef<SourceLoc> getArgumentLabelLocsBuffer() {
-    if (!asDerived().hasArgumentLabelLocs())
-      return { };
-    
-    return { this->template getTrailingObjects<SourceLoc>(),
-             asDerived().getNumArguments() };
-  }
-
-protected:
-  /// Determine the total size to allocate.
-  static size_t totalSizeToAlloc(ArrayRef<Identifier> argLabels,
-                                 ArrayRef<SourceLoc> argLabelLocs,
-                                 bool hasTrailingClosure) {
-    return TrailingObjects::template totalSizeToAlloc<Identifier, SourceLoc>(
-        argLabels.size(), argLabelLocs.size());
-  }
-
-  /// Initialize the actual call arguments.
-  void initializeCallArguments(ArrayRef<Identifier> argLabels,
-                               ArrayRef<SourceLoc> argLabelLocs,
-                               bool hasTrailingClosure) {
-    if (!argLabels.empty()) {
-      std::uninitialized_copy(argLabels.begin(), argLabels.end(),
-                              this->template getTrailingObjects<Identifier>());
-    }
-    
-    if (!argLabelLocs.empty())
-      std::uninitialized_copy(argLabelLocs.begin(), argLabelLocs.end(),
-                              this->template getTrailingObjects<SourceLoc>());
-  }
-
-public:
-  /// Retrieve the argument labels provided at the call site.
-  ArrayRef<Identifier> getArgumentLabels() const {
-    return { this->template getTrailingObjects<Identifier>(),
-             asDerived().getNumArguments() };
-  }
-
-  /// Retrieve the buffer containing the argument label locations.
-  ArrayRef<SourceLoc> getArgumentLabelLocs() const {
-    if (!asDerived().hasArgumentLabelLocs())
-      return { };
-    
-    return { this->template getTrailingObjects<SourceLoc>(),
-             asDerived().getNumArguments() };
-  }
-
-  /// Retrieve the location of the ith argument label.
-  SourceLoc getArgumentLabelLoc(unsigned i) const {
-    auto locs = getArgumentLabelLocs();
-    return i < locs.size() ? locs[i] : SourceLoc();
-  }
-};
-
 /// ErrorExpr - Represents a semantically erroneous subexpression in the AST,
 /// typically this will have an ErrorType.
 class ErrorExpr : public Expr {
@@ -2206,6 +2095,7 @@
 class CollectionExpr : public Expr {
   SourceLoc LBracketLoc;
   SourceLoc RBracketLoc;
+  ConcreteDeclRef Initializer;
 
   Expr *SemanticExpr = nullptr;
 
@@ -2282,6 +2172,14 @@
            e->getKind() <= ExprKind::Last_CollectionExpr;
   }
 
+  /// Retrieve the initializer that will be used to construct the 'array'
+  /// literal from the result of the initializer.
+  ConcreteDeclRef getInitializer() const { return Initializer; }
+
+  /// Set the initializer that will be used to construct the 'array' literal.
+  void setInitializer(ConcreteDeclRef initializer) {
+    Initializer = initializer;
+  }
 };
  
 /// An array literal expression [a, b, c].
@@ -2312,6 +2210,8 @@
   static bool classof(const Expr *e) {
     return e->getKind() == ExprKind::Array;
   }
+
+  Type getElementType();
 };
 
 /// A dictionary literal expression [a : x, b : y, c : z].
@@ -3009,157 +2909,6 @@
   }
 };
 
-/// ArgumentShuffleExpr - This represents a "complex" argument list of an
-/// ApplyExpr, with default arguments or varargs.
-///
-/// If hasScalarSource() is true, the subexpression should be treated
-/// as if it were implicitly injected into a single-element tuple
-/// type.  Otherwise, the subexpression is known to have a tuple type.
-class ArgumentShuffleExpr final : public ImplicitConversionExpr,
-    private llvm::TrailingObjects<ArgumentShuffleExpr, Expr *, int, unsigned> {
-  friend TrailingObjects;
-
-  size_t numTrailingObjects(OverloadToken<Expr *>) const {
-    return Bits.ArgumentShuffleExpr.NumCallerDefaultArgs;
-  }
-  size_t numTrailingObjects(OverloadToken<int>) const {
-    return Bits.ArgumentShuffleExpr.NumElementMappings;
-  }
-  size_t numTrailingObjects(OverloadToken<unsigned>) const {
-    return Bits.ArgumentShuffleExpr.NumVariadicArgs;
-  }
-
-public:
-  enum : int {
-    /// The element mapping value indicating that a field of the destination
-    /// tuple should be default-initialized.
-    DefaultInitialize = -1,
-    /// The element mapping is part of the variadic field.
-    Variadic = -2,
-    /// The element mapping value indicating that the field of the
-    /// destination tuple should be default-initialized with an expression
-    /// provided by the caller.
-    /// FIXME: Yet another indication that ArgumentShuffleExpr uses the wrong
-    /// formulation.
-    CallerDefaultInitialize = -3
-  };
-
-  enum TypeImpact {
-    /// The source value is a tuple which is destructured and modified to
-    /// create the result, which is a tuple.
-    ///
-    /// Example: (x: Int) => (x: Int, y: Int = 0).
-    TupleToTuple,
-
-    /// The source value is a tuple which is destructured and modified to
-    /// create the result, which is a scalar because it has one element and
-    /// no labels.
-    ///
-    /// Example: () -> (_: Int = 0)
-    /// Another example: (Int, Int) => (_: Int...)
-    TupleToScalar,
-
-    /// The source value is an individual value (possibly one with tuple
-    /// type) which is inserted into a particular position in the result,
-    /// which is a tuple.
-    ///
-    /// Example: (Int) -> (_: Int, y: Int = 0)
-    ScalarToTuple
-
-    // (ArgumentShuffleExpr are never created for a scalar-to-scalar conversion.)
-  };
-
-private:
-  /// If we're doing a varargs shuffle, this is the array type to build.
-  Type VarargsArrayTy;
-
-  /// If there are any default arguments, the owning function
-  /// declaration.
-  ConcreteDeclRef DefaultArgsOwner;
-
-  ArgumentShuffleExpr(Expr *subExpr, ArrayRef<int> elementMapping,
-                      TypeImpact typeImpact,
-                      ConcreteDeclRef defaultArgsOwner,
-                      ArrayRef<unsigned> VariadicArgs,
-                      Type VarargsArrayTy,
-                      ArrayRef<Expr *> CallerDefaultArgs,
-                      Type ty)
-    : ImplicitConversionExpr(ExprKind::ArgumentShuffle, subExpr, ty),
-      VarargsArrayTy(VarargsArrayTy), DefaultArgsOwner(defaultArgsOwner) {
-    Bits.ArgumentShuffleExpr.TypeImpact = typeImpact;
-    Bits.ArgumentShuffleExpr.NumCallerDefaultArgs = CallerDefaultArgs.size();
-    Bits.ArgumentShuffleExpr.NumElementMappings = elementMapping.size();
-    Bits.ArgumentShuffleExpr.NumVariadicArgs = VariadicArgs.size();
-    std::uninitialized_copy(CallerDefaultArgs.begin(), CallerDefaultArgs.end(),
-                            getTrailingObjects<Expr*>());
-    std::uninitialized_copy(elementMapping.begin(), elementMapping.end(),
-                            getTrailingObjects<int>());
-    std::uninitialized_copy(VariadicArgs.begin(), VariadicArgs.end(),
-                            getTrailingObjects<unsigned>());
-  }
-
-public:
-  static ArgumentShuffleExpr *create(ASTContext &ctx, Expr *subExpr,
-                                     ArrayRef<int> elementMapping,
-                                     TypeImpact typeImpact,
-                                     ConcreteDeclRef defaultArgsOwner,
-                                     ArrayRef<unsigned> VariadicArgs,
-                                     Type VarargsArrayTy,
-                                     ArrayRef<Expr *> CallerDefaultArgs,
-                                     Type ty);
-
-  ArrayRef<int> getElementMapping() const {
-    return {getTrailingObjects<int>(),
-            static_cast<size_t>(Bits.ArgumentShuffleExpr.NumElementMappings)};
-  }
-
-  /// What is the type impact of this shuffle?
-  TypeImpact getTypeImpact() const {
-    return TypeImpact(Bits.ArgumentShuffleExpr.TypeImpact);
-  }
-
-  bool isSourceScalar() const {
-    return getTypeImpact() == ScalarToTuple;
-  }
-
-  bool isResultScalar() const {
-    return getTypeImpact() == TupleToScalar;
-  }
-
-  Type getVarargsArrayType() const {
-    assert(!VarargsArrayTy.isNull());
-    return VarargsArrayTy;
-  }
-  Type getVarargsArrayTypeOrNull() const {
-    return VarargsArrayTy;
-  }
-
-  /// Retrieve the argument indices for the variadic arguments.
-  ArrayRef<unsigned> getVariadicArgs() const {
-    return {getTrailingObjects<unsigned>(),
-            static_cast<size_t>(Bits.ArgumentShuffleExpr.NumVariadicArgs)};
-  }
-
-  /// Retrieve the owner of the default arguments.
-  ConcreteDeclRef getDefaultArgsOwner() const { return DefaultArgsOwner; }
-
-  /// Retrieve the caller-defaulted arguments.
-  ArrayRef<Expr *> getCallerDefaultArgs() const {
-    return {getTrailingObjects<Expr*>(),
-            static_cast<size_t>(Bits.ArgumentShuffleExpr.NumCallerDefaultArgs)};
-  }
-
-  /// Retrieve the caller-defaulted arguments.
-  MutableArrayRef<Expr *> getCallerDefaultArgs() {
-    return {getTrailingObjects<Expr*>(),
-            static_cast<size_t>(Bits.ArgumentShuffleExpr.NumCallerDefaultArgs)};
-  }
-
-  static bool classof(const Expr *E) {
-    return E->getKind() == ExprKind::ArgumentShuffle;
-  }
-};
-
 /// LoadExpr - Turn an l-value into an r-value by performing a "load"
 /// operation.  This operation may actually be a logical operation,
 /// i.e. one implemented using a call to a potentially user-defined
@@ -4010,7 +3759,7 @@
 /// Opaque value expressions occur when a particular value within the AST
 /// needs to be re-used without being re-evaluated or for a value that is
 /// a placeholder. OpaqueValueExpr nodes are introduced by some other AST
-/// node (say, a \c DynamicMemberRefExpr) and can only be used within the
+/// node (say, an \c OpenExistentialExpr) and can only be used within the
 /// subexpressions of that AST node.
 class OpaqueValueExpr : public Expr {
   SourceLoc Loc;
@@ -4026,6 +3775,82 @@
   }
 };
 
+/// An expression referring to a default argument left unspecified at the
+/// call site.
+///
+/// A DefaultArgumentExpr must only appear as a direct child of a
+/// ParenExpr or a TupleExpr that is itself a call argument.
+class DefaultArgumentExpr final : public Expr {
+  /// The owning declaration.
+  ConcreteDeclRef DefaultArgsOwner;
+
+  /// The caller parameter index.
+  unsigned ParamIndex;
+
+  /// The source location of the argument list.
+  SourceLoc Loc;
+
+public:
+  explicit DefaultArgumentExpr(ConcreteDeclRef defaultArgsOwner, unsigned paramIndex,
+                               SourceLoc loc, Type Ty)
+    : Expr(ExprKind::DefaultArgument, /*Implicit=*/true, Ty),
+      DefaultArgsOwner(defaultArgsOwner), ParamIndex(paramIndex), Loc(loc) { }
+
+  SourceRange getSourceRange() const {
+    return Loc;
+  }
+
+  ConcreteDeclRef getDefaultArgsOwner() const {
+    return DefaultArgsOwner;
+  }
+
+  unsigned getParamIndex() const {
+    return ParamIndex;
+  }
+
+  static bool classof(const Expr *E) {
+    return E->getKind() == ExprKind::DefaultArgument;
+  }
+};
+
+/// An expression referring to a caller-side default argument left unspecified
+/// at the call site.
+///
+/// A CallerDefaultArgumentExpr must only appear as a direct child of a
+/// ParenExpr or a TupleExpr that is itself a call argument.
+///
+/// FIXME: This only exists to distinguish caller default arguments from arguments
+/// that were specified at the call site. Once we remove SanitizeExpr, we can remove
+/// this hack too.
+class CallerDefaultArgumentExpr final : public Expr {
+  /// The expression that is evaluated to produce the default argument value.
+  Expr *SubExpr;
+
+  /// The source location of the argument list.
+  SourceLoc Loc;
+
+public:
+  explicit CallerDefaultArgumentExpr(Expr *subExpr, SourceLoc loc, Type Ty)
+    : Expr(ExprKind::CallerDefaultArgument, /*Implicit=*/true, Ty),
+      SubExpr(subExpr), Loc(loc) { }
+
+  SourceRange getSourceRange() const {
+    return Loc;
+  }
+
+  Expr *getSubExpr() const {
+    return SubExpr;
+  }
+
+  void setSubExpr(Expr *subExpr) {
+    SubExpr = subExpr;
+  }
+
+  static bool classof(const Expr *E) {
+    return E->getKind() == ExprKind::CallerDefaultArgument;
+  }
+};
+
 /// ApplyExpr - Superclass of various function calls, which apply an argument to
 /// a function to get a result.
 class ApplyExpr : public Expr {
@@ -4036,8 +3861,7 @@
   llvm::PointerIntPair<Expr *, 1, bool> ArgAndIsSuper;
   
   /// Returns true if \c e could be used as the call's argument. For most \c ApplyExpr
-  /// subclasses, this means it is a \c ParenExpr, \c TupleExpr, or 
-  /// \c ArgumentShuffleExpr.
+  /// subclasses, this means it is a \c ParenExpr or \c TupleExpr.
   bool validateArg(Expr *e) const;
 
 protected:
@@ -4101,7 +3925,7 @@
            E->getKind() <= ExprKind::Last_ApplyExpr;
   }
 };
-  
+
 /// CallExpr - Application of an argument to a function, which occurs
 /// syntactically through juxtaposition with a TupleExpr whose
 /// leading '(' is unspaced.
@@ -5417,7 +5241,7 @@
   else if (isa<BinaryExpr>(this))
     return isa<TupleExpr>(e);
   else
-    return isa<ParenExpr>(e) || isa<TupleExpr>(e) || isa<ArgumentShuffleExpr>(e);
+    return isa<ParenExpr>(e) || isa<TupleExpr>(e);
 }
 
 inline Expr *const *CollectionExpr::getTrailingObjectsPointer() const {
@@ -5437,7 +5261,27 @@
 }
 
 #undef SWIFT_FORWARD_SOURCE_LOCS_TO
-  
+
+/// Pack the argument information into a single argument, to match the
+/// representation expected by the AST.
+///
+/// \param argLabels The argument labels, which might be updated by this
+/// function.
+///
+/// \param argLabelLocs The argument label locations, which might be updated by
+/// this function.
+Expr *packSingleArgument(ASTContext &ctx, SourceLoc lParenLoc,
+                         ArrayRef<Expr *> args,
+                         ArrayRef<Identifier> &argLabels,
+                         ArrayRef<SourceLoc> &argLabelLocs,
+                         SourceLoc rParenLoc,
+                         Expr *trailingClosure, bool implicit,
+                         SmallVectorImpl<Identifier> &argLabelsScratch,
+                         SmallVectorImpl<SourceLoc> &argLabelLocsScratch,
+                         llvm::function_ref<Type(const Expr *)> getType =
+                              [](const Expr *E) -> Type {
+                                return E->getType();
+                              });
 } // end namespace swift
 
 #endif
diff --git a/include/swift/AST/ExprNodes.def b/include/swift/AST/ExprNodes.def
index c5d6866..7c5225c 100644
--- a/include/swift/AST/ExprNodes.def
+++ b/include/swift/AST/ExprNodes.def
@@ -126,6 +126,8 @@
 EXPR(DynamicType, Expr)
 EXPR(RebindSelfInConstructor, Expr)
 EXPR(OpaqueValue, Expr)
+EXPR(DefaultArgument, Expr)
+EXPR(CallerDefaultArgument, Expr)
 EXPR(BindOptional, Expr)
 EXPR(OptionalEvaluation, Expr)
 EXPR(ForceValue, Expr)
@@ -144,7 +146,6 @@
 ABSTRACT_EXPR(ImplicitConversion, Expr)
   EXPR(Load, ImplicitConversionExpr)
   EXPR(DestructureTuple, ImplicitConversionExpr)
-  EXPR(ArgumentShuffle, ImplicitConversionExpr)
   EXPR(UnresolvedTypeConversion, ImplicitConversionExpr)
   EXPR(FunctionConversion, ImplicitConversionExpr)
   EXPR(CovariantFunctionConversion, ImplicitConversionExpr)
diff --git a/include/swift/AST/Module.h b/include/swift/AST/Module.h
index abab16b..35a96b8 100644
--- a/include/swift/AST/Module.h
+++ b/include/swift/AST/Module.h
@@ -419,18 +419,23 @@
          SmallVectorImpl<AbstractFunctionDecl *> &results) const;
 
   /// \sa getImportedModules
-  enum class ImportFilter {
-    All,
-    Public,
-    Private
+  enum class ImportFilterKind {
+    /// Include imports declared with `@_exported`.
+    Public = 1 << 0,
+    /// Include "regular" imports with no special annotation.
+    Private = 1 << 1,
+    /// Include imports declared with `@_implementationOnly`.
+    ImplementationOnly = 1 << 2
   };
+  /// \sa getImportedModules
+  using ImportFilter = OptionSet<ImportFilterKind>;
 
   /// Looks up which modules are imported by this module.
   ///
   /// \p filter controls whether public, private, or any imports are included
   /// in this list.
   void getImportedModules(SmallVectorImpl<ImportedModule> &imports,
-                          ImportFilter filter = ImportFilter::Public) const;
+                          ImportFilter filter = ImportFilterKind::Public) const;
 
   /// Looks up which modules are imported by this module, ignoring any that
   /// won't contain top-level decls.
@@ -758,7 +763,7 @@
   /// \see ModuleDecl::getImportedModulesForLookup
   virtual void getImportedModulesForLookup(
       SmallVectorImpl<ModuleDecl::ImportedModule> &imports) const {
-    return getImportedModules(imports, ModuleDecl::ImportFilter::Public);
+    return getImportedModules(imports, ModuleDecl::ImportFilterKind::Public);
   }
 
   /// Generates the list of libraries needed to link this file, based on its
@@ -891,23 +896,29 @@
     /// This source file has access to private declarations in the imported
     /// module.
     PrivateImport = 0x4,
+
+    /// The imported module is an implementation detail of this file and should
+    /// not be required to be present if the main module is ever imported
+    /// elsewhere.
+    ///
+    /// Mutually exclusive with Exported.
+    ImplementationOnly = 0x8
   };
 
   /// \see ImportFlags
   using ImportOptions = OptionSet<ImportFlags>;
 
-  typedef std::pair<ImportOptions, StringRef> ImportOptionsAndFilename;
-
   struct ImportedModuleDesc {
     ModuleDecl::ImportedModule module;
     ImportOptions importOptions;
     StringRef filename;
 
-    ImportedModuleDesc(ModuleDecl::ImportedModule module, ImportOptions options)
-        : module(module), importOptions(options) {}
     ImportedModuleDesc(ModuleDecl::ImportedModule module, ImportOptions options,
-                       StringRef filename)
-        : module(module), importOptions(options), filename(filename) {}
+                       StringRef filename = {})
+        : module(module), importOptions(options), filename(filename) {
+      assert(!(importOptions.contains(ImportFlags::Exported) &&
+               importOptions.contains(ImportFlags::ImplementationOnly)));
+    }
   };
 
 private:
diff --git a/include/swift/AST/NameLookupRequests.h b/include/swift/AST/NameLookupRequests.h
index 5f7177a..1c68cbd 100644
--- a/include/swift/AST/NameLookupRequests.h
+++ b/include/swift/AST/NameLookupRequests.h
@@ -17,6 +17,7 @@
 #define SWIFT_NAME_LOOKUP_REQUESTS_H
 
 #include "swift/AST/SimpleRequest.h"
+#include "swift/AST/ASTTypeIDs.h"
 #include "swift/Basic/Statistic.h"
 #include "llvm/ADT/TinyPtrVector.h"
 
@@ -238,6 +239,33 @@
   void noteCycleStep(DiagnosticEngine &diags) const;
 };
 
+/// Request the nominal type declaration to which the given custom attribute
+/// refers.
+class CustomAttrNominalRequest :
+    public SimpleRequest<CustomAttrNominalRequest,
+                         CacheKind::Cached,
+                         NominalTypeDecl *,
+                         CustomAttr *,
+                         DeclContext *> {
+public:
+  using SimpleRequest::SimpleRequest;
+
+private:
+  friend SimpleRequest;
+
+  // Evaluation.
+  llvm::Expected<NominalTypeDecl *>
+  evaluate(Evaluator &evaluator, CustomAttr *attr, DeclContext *dc) const;
+
+public:
+  // Caching
+  bool isCached() const { return true; }
+
+  // Cycle handling
+  void diagnoseCycle(DiagnosticEngine &diags) const;
+  void noteCycleStep(DiagnosticEngine &diags) const;
+};
+
 /// The zone number for name-lookup requests.
 #define SWIFT_NAME_LOOKUP_REQUESTS_TYPEID_ZONE 9
 
diff --git a/include/swift/AST/NameLookupTypeIDZone.def b/include/swift/AST/NameLookupTypeIDZone.def
index d00cfbc..1d380d2 100644
--- a/include/swift/AST/NameLookupTypeIDZone.def
+++ b/include/swift/AST/NameLookupTypeIDZone.def
@@ -20,3 +20,4 @@
 SWIFT_TYPEID(ExtendedNominalRequest)
 SWIFT_TYPEID(SelfBoundsFromWhereClauseRequest)
 SWIFT_TYPEID(TypeDeclsFromWhereClauseRequest)
+SWIFT_TYPEID(CustomAttrNominalRequest)
diff --git a/include/swift/AST/TrailingCallArguments.h b/include/swift/AST/TrailingCallArguments.h
new file mode 100644
index 0000000..5279421
--- /dev/null
+++ b/include/swift/AST/TrailingCallArguments.h
@@ -0,0 +1,130 @@
+//===--- TrailingCallArguments.h - Trailing Call Arguments ------*- C++ -*-===//
+//
+// This source file is part of the Swift.org open source project
+//
+// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See https://swift.org/LICENSE.txt for license information
+// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
+//
+//===----------------------------------------------------------------------===//
+//
+//  This file defines the TrailingCallArguments template, which is used
+//  to tail-allocate the names and source locations of argument labels in a
+//  call.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef SWIFT_AST_TRAILINGCALLARGUMENTS_H
+#define SWIFT_AST_TRAILINGCALLARGUMENTS_H
+
+#include "swift/AST/Identifier.h"
+#include "swift/Basic/SourceLoc.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/Support/TrailingObjects.h"
+
+namespace swift {
+
+/// Helper class to capture trailing call argument labels and related
+/// information, for expression nodes that involve argument labels, trailing
+/// closures, etc.
+template<typename Derived>
+class TrailingCallArguments
+    : private llvm::TrailingObjects<Derived, Identifier, SourceLoc> {
+  // We need to friend TrailingObjects twice here to work around an MSVC bug.
+  // If we have two functions of the same name with the parameter
+  // typename TrailingObjectsIdentifier::template OverloadToken<T> where T is
+  // different for each function, then MSVC reports a "member function already
+  // defined or declared" error, which is incorrect.
+  using TrailingObjectsIdentifier = llvm::TrailingObjects<Derived, Identifier>;
+  friend TrailingObjectsIdentifier;
+
+  using TrailingObjects = llvm::TrailingObjects<Derived, Identifier, SourceLoc>;
+  friend TrailingObjects;
+
+  Derived &asDerived() {
+    return *static_cast<Derived *>(this);
+  }
+
+  const Derived &asDerived() const {
+    return *static_cast<const Derived *>(this);
+  }
+
+  size_t numTrailingObjects(
+      typename TrailingObjectsIdentifier::template OverloadToken<Identifier>)
+      const {
+    return asDerived().getNumArguments();
+  }
+
+  size_t numTrailingObjects(
+      typename TrailingObjectsIdentifier::template OverloadToken<SourceLoc>)
+      const {
+    return asDerived().hasArgumentLabelLocs() ? asDerived().getNumArguments()
+                                              : 0;
+  }
+
+  /// Retrieve the buffer containing the argument labels.
+  MutableArrayRef<Identifier> getArgumentLabelsBuffer() {
+    return { this->template getTrailingObjects<Identifier>(),
+             asDerived().getNumArguments() };
+  }
+
+  /// Retrieve the buffer containing the argument label locations.
+  MutableArrayRef<SourceLoc> getArgumentLabelLocsBuffer() {
+    if (!asDerived().hasArgumentLabelLocs())
+      return { };
+
+    return { this->template getTrailingObjects<SourceLoc>(),
+             asDerived().getNumArguments() };
+  }
+
+protected:
+  /// Determine the total size to allocate.
+  static size_t totalSizeToAlloc(ArrayRef<Identifier> argLabels,
+                                 ArrayRef<SourceLoc> argLabelLocs,
+                                 bool hasTrailingClosure) {
+    return TrailingObjects::template totalSizeToAlloc<Identifier, SourceLoc>(
+        argLabels.size(), argLabelLocs.size());
+  }
+
+  /// Initialize the actual call arguments.
+  void initializeCallArguments(ArrayRef<Identifier> argLabels,
+                               ArrayRef<SourceLoc> argLabelLocs,
+                               bool hasTrailingClosure) {
+    if (!argLabels.empty()) {
+      std::uninitialized_copy(argLabels.begin(), argLabels.end(),
+                              this->template getTrailingObjects<Identifier>());
+    }
+
+    if (!argLabelLocs.empty())
+      std::uninitialized_copy(argLabelLocs.begin(), argLabelLocs.end(),
+                              this->template getTrailingObjects<SourceLoc>());
+  }
+
+public:
+  /// Retrieve the argument labels provided at the call site.
+  ArrayRef<Identifier> getArgumentLabels() const {
+    return { this->template getTrailingObjects<Identifier>(),
+             asDerived().getNumArguments() };
+  }
+
+  /// Retrieve the buffer containing the argument label locations.
+  ArrayRef<SourceLoc> getArgumentLabelLocs() const {
+    if (!asDerived().hasArgumentLabelLocs())
+      return { };
+
+    return { this->template getTrailingObjects<SourceLoc>(),
+             asDerived().getNumArguments() };
+  }
+
+  /// Retrieve the location of the ith argument label.
+  SourceLoc getArgumentLabelLoc(unsigned i) const {
+    auto locs = getArgumentLabelLocs();
+    return i < locs.size() ? locs[i] : SourceLoc();
+  }
+};
+
+} // end namespace swift
+
+#endif /* SWIFT_AST_TRAILINGCALLARGUMENTS_H */
diff --git a/include/swift/Basic/OptionSet.h b/include/swift/Basic/OptionSet.h
index 69bb319..0edab18 100644
--- a/include/swift/Basic/OptionSet.h
+++ b/include/swift/Basic/OptionSet.h
@@ -87,6 +87,15 @@
     return !static_cast<bool>(set - *this);
   }
 
+  /// Check if this option set contains the exact same options as the given set.
+  bool containsOnly(OptionSet set) {
+    return Storage == set.Storage;
+  }
+
+  // '==' and '!=' are deliberately not defined because they provide a pitfall
+  // where someone might use '==' but really want 'contains'. If you actually
+  // want '==' behavior, use 'containsOnly'.
+
   /// Produce the union of two option sets.
   friend OptionSet operator|(OptionSet lhs, OptionSet rhs) {
     return OptionSet(lhs.Storage | rhs.Storage);
@@ -114,7 +123,7 @@
     return OptionSet(lhs.Storage & ~rhs.Storage);
   }
 
-  /// Produce the intersection of two option sets.
+  /// Produce the difference of two option sets.
   friend OptionSet &operator-=(OptionSet &lhs, OptionSet rhs) {
     lhs.Storage &= ~rhs.Storage;
     return lhs;
diff --git a/include/swift/Basic/Sanitizers.def b/include/swift/Basic/Sanitizers.def
new file mode 100644
index 0000000..73c5ba9
--- /dev/null
+++ b/include/swift/Basic/Sanitizers.def
@@ -0,0 +1,28 @@
+//===--- Sanitizers.def - Swift Sanitizers ß----------------------*- C++ -*-===//
+//
+// This source file is part of the Swift.org open source project
+//
+// Copyright (c) 2014 - 2019 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
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the sanitizers supported by Swift.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef SANITIZER
+#error "Define SANITIZER prior to including this file!"
+#endif
+
+// SANITIZER(enum_bit, kind, name, file)
+
+SANITIZER(0, Address,   address,    asan)
+SANITIZER(1, Thread,    thread,     tsan)
+SANITIZER(2, Undefined, undefined,  ubsan)
+SANITIZER(3, Fuzzer,    fuzzer,     fuzzer)
+
+#undef SANITIZER
diff --git a/include/swift/Basic/Sanitizers.h b/include/swift/Basic/Sanitizers.h
index b86718e..4efced2 100644
--- a/include/swift/Basic/Sanitizers.h
+++ b/include/swift/Basic/Sanitizers.h
@@ -17,10 +17,8 @@
 
 // Enabling bitwise masking.
 enum class SanitizerKind : unsigned {
-  Address = 1 << 1,
-  Thread = 1 << 2,
-  Fuzzer = 1 << 3,
-  Undefined = 1 << 4
+  #define SANITIZER(enum_bit, kind, name, file) kind = (1 << enum_bit),
+  #include "Sanitizers.def"
 };
 
 } // end namespace swift
diff --git a/include/swift/Basic/Statistic.h b/include/swift/Basic/Statistic.h
index bc623bc..a3901f1 100644
--- a/include/swift/Basic/Statistic.h
+++ b/include/swift/Basic/Statistic.h
@@ -140,6 +140,7 @@
 private:
   bool currentProcessExitStatusSet;
   int currentProcessExitStatus;
+  long maxChildRSS = 0;
   SmallString<128> StatsFilename;
   SmallString<128> TraceFilename;
   SmallString<128> ProfileDirname;
@@ -192,6 +193,8 @@
   void flushTracesAndProfiles();
   void noteCurrentProcessExitStatus(int);
   void saveAnyFrontendStatsEvents(FrontendStatsTracer const &T, bool IsEntry);
+  void recordJobMaxRSS(long rss);
+  int64_t getChildrenMaxResidentSetSize();
 };
 
 // This is a non-nested type just to make it less work to write at call sites.
diff --git a/include/swift/Basic/TaskQueue.h b/include/swift/Basic/TaskQueue.h
index 9c5fa5c..30b1397 100644
--- a/include/swift/Basic/TaskQueue.h
+++ b/include/swift/Basic/TaskQueue.h
@@ -96,6 +96,7 @@
 #if defined(HAVE_GETRUSAGE) && !defined(__HAIKU__)
   TaskProcessInformation(ProcessId Pid, struct rusage Usage);
 #endif // defined(HAVE_GETRUSAGE) && !defined(__HAIKU__)
+  Optional<ResourceUsage> getResourceUsage() { return ProcessUsage; }
   virtual ~TaskProcessInformation() = default;
   virtual void provideMapping(json::Output &out);
 };
diff --git a/include/swift/Remote/FailureKinds.def b/include/swift/Remote/FailureKinds.def
index 96860af..a3afa5c 100644
--- a/include/swift/Remote/FailureKinds.def
+++ b/include/swift/Remote/FailureKinds.def
@@ -27,4 +27,7 @@
 FAILURE(CouldNotResolveTypeDecl,
         "could not resolve a type with mangled name '%0'", (String))
 
+FAILURE(NotFixedLayout,
+        "query cannot be determined for a type with no fixed layout", ())
+
 #undef FAILURE
diff --git a/include/swift/Sema/IDETypeChecking.h b/include/swift/Sema/IDETypeChecking.h
index f10b06b..e1d7bcc 100644
--- a/include/swift/Sema/IDETypeChecking.h
+++ b/include/swift/Sema/IDETypeChecking.h
@@ -202,6 +202,25 @@
   /// the decl context.
   bool resolveProtocolNames(DeclContext *DC, ArrayRef<const char *> names,
                             llvm::MapVector<ProtocolDecl*, StringRef> &result);
+
+  /// FIXME: All of the below goes away once CallExpr directly stores its
+  /// arguments.
+
+  /// Return value for getOriginalArgumentList().
+  struct OriginalArgumentList {
+    SmallVector<Expr *, 4> args;
+    SmallVector<Identifier, 4> labels;
+    SmallVector<SourceLoc, 4> labelLocs;
+    SourceLoc lParenLoc;
+    SourceLoc rParenLoc;
+    bool hasTrailingClosure = false;
+  };
+
+  /// When applying a solution to a constraint system, the type checker rewrites
+  /// argument lists of calls to insert default arguments and collect varargs.
+  /// Sometimes for diagnostics we want to work on the original argument list as
+  /// written by the user; this performs the reverse transformation.
+  OriginalArgumentList getOriginalArgumentList(Expr *expr);
 }
 
 #endif
diff --git a/include/swift/Serialization/ModuleFile.h b/include/swift/Serialization/ModuleFile.h
index 59febe9..42a3a67 100644
--- a/include/swift/Serialization/ModuleFile.h
+++ b/include/swift/Serialization/ModuleFile.h
@@ -135,27 +135,48 @@
     const StringRef RawPath;
 
   private:
-    unsigned IsExported : 1;
+    using ImportFilterKind = ModuleDecl::ImportFilterKind;
+    const unsigned RawImportControl : 2;
     const unsigned IsHeader : 1;
     const unsigned IsScoped : 1;
 
-    Dependency(StringRef path, bool isHeader, bool exported, bool isScoped)
-      : RawPath(path), IsExported(exported), IsHeader(isHeader),
-        IsScoped(isScoped) {}
+    static unsigned rawControlFromKind(ImportFilterKind importKind) {
+      return llvm::countTrailingZeros(static_cast<unsigned>(importKind));
+    }
+    ImportFilterKind getImportControl() const {
+      return static_cast<ImportFilterKind>(1 << RawImportControl);
+    }
+
+    Dependency(StringRef path, bool isHeader, ImportFilterKind importControl,
+               bool isScoped)
+      : RawPath(path), RawImportControl(rawControlFromKind(importControl)),
+        IsHeader(isHeader), IsScoped(isScoped) {
+      assert(llvm::countPopulation(static_cast<unsigned>(importControl)) == 1 &&
+             "must be a particular filter option, not a bitset");
+      assert(getImportControl() == importControl && "not enough bits");
+    }
 
   public:
-    Dependency(StringRef path, bool exported, bool isScoped)
-      : Dependency(path, false, exported, isScoped) {}
+    Dependency(StringRef path, ImportFilterKind importControl, bool isScoped)
+      : Dependency(path, false, importControl, isScoped) {}
 
     static Dependency forHeader(StringRef headerPath, bool exported) {
-      return Dependency(headerPath, true, exported, false);
+      auto importControl = exported ? ImportFilterKind::Public
+                                    : ImportFilterKind::Private;
+      return Dependency(headerPath, true, importControl, false);
     }
 
     bool isLoaded() const {
       return Import.second != nullptr;
     }
 
-    bool isExported() const { return IsExported; }
+    bool isExported() const {
+      return getImportControl() == ImportFilterKind::Public;
+    }
+    bool isImplementationOnly() const {
+      return getImportControl() == ImportFilterKind::ImplementationOnly;
+    }
+
     bool isHeader() const { return IsHeader; }
     bool isScoped() const { return IsScoped; }
 
@@ -638,11 +659,26 @@
   // Out of line to avoid instantiation OnDiskChainedHashTable here.
   ~ModuleFile();
 
-  /// Associates this module file with an AST module.
+  /// Associates this module file with the AST node representing it.
   ///
-  /// Returns any error that occurred during association, including validation
-  /// that the module file is compatible with the module it's being loaded as.
-  Status associateWithFileContext(FileUnit *file, SourceLoc diagLoc);
+  /// Checks that the file is compatible with the AST module it's being loaded
+  /// into, loads any dependencies needed to understand the module, and updates
+  /// the ASTContext and ClangImporter with search paths and other information
+  /// from the module.
+  ///
+  /// \param file The FileUnit that represents this file's place in the AST.
+  /// \param diagLoc A location used for diagnostics that occur during loading.
+  /// This does not include diagnostics about \e this file failing to load,
+  /// but rather other things that might be imported as part of bringing the
+  /// file into the AST.
+  /// \param treatAsPartialModule If true, processes implementation-only
+  /// information instead of assuming the client won't need it and shouldn't
+  /// see it.
+  ///
+  /// \returns any error that occurred during association, such as being
+  /// compiled for a different OS.
+  Status associateWithFileContext(FileUnit *file, SourceLoc diagLoc,
+                                  bool treatAsPartialModule);
 
   /// Checks whether this module can be used.
   Status getStatus() const {
diff --git a/include/swift/Serialization/ModuleFormat.h b/include/swift/Serialization/ModuleFormat.h
index 7582501..9eee6c0 100644
--- a/include/swift/Serialization/ModuleFormat.h
+++ b/include/swift/Serialization/ModuleFormat.h
@@ -52,7 +52,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 SWIFTMODULE_VERSION_MINOR = 479; // stored property default arg
+const uint16_t SWIFTMODULE_VERSION_MINOR = 481; // Last change: custom attrs
 
 using DeclIDField = BCFixed<31>;
 
@@ -452,6 +452,8 @@
   /// TODO: Float, string, char, etc.
 };
 
+using EnumElementRawValueKindField = BCFixed<4>;
+
 // These IDs must \em not be renumbered or reordered without incrementing
 // the module version.
 enum class ResilienceExpansion : uint8_t {
@@ -459,7 +461,17 @@
   Maximal,
 };
 
-using EnumElementRawValueKindField = BCFixed<4>;
+// These IDs must \em not be renumbered or reordered without incrementing
+// the module version.
+enum class ImportControl : uint8_t {
+  /// `import FooKit`
+  Normal = 0,
+  /// `@_exported import FooKit`
+  Exported,
+  /// `@_uncheckedImplementationOnly import FooKit`
+  ImplementationOnly
+};
+using ImportControlField = BCFixed<2>;
 
 /// The various types of blocks that can occur within a serialized Swift
 /// module.
@@ -636,8 +648,8 @@
 
   using ImportedModuleLayout = BCRecordLayout<
     IMPORTED_MODULE,
-    BCFixed<1>, // exported?
-    BCFixed<1>, // scoped?
+    ImportControlField, // import kind
+    BCFixed<1>,         // scoped?
     BCBlob // module name, with submodule path pieces separated by \0s.
            // If the 'scoped' flag is set, the final path piece is an access
            // path within the module.
@@ -1598,6 +1610,12 @@
     BCArray<IdentifierIDField>
   >;
 
+  using CustomDeclAttrLayout = BCRecordLayout<
+    Custom_DECL_ATTR,
+    BCFixed<1>,  // implicit flag
+    TypeIDField // type referenced by this custom attribute
+  >;
+
 }
 
 /// Returns the encoding kind for the given decl.
diff --git a/include/swift/Serialization/SerializedModuleLoader.h b/include/swift/Serialization/SerializedModuleLoader.h
index 3af6cfc..65dd96d 100644
--- a/include/swift/Serialization/SerializedModuleLoader.h
+++ b/include/swift/Serialization/SerializedModuleLoader.h
@@ -94,7 +94,7 @@
   FileUnit *loadAST(ModuleDecl &M, Optional<SourceLoc> diagLoc,
                     std::unique_ptr<llvm::MemoryBuffer> moduleInputBuffer,
                     std::unique_ptr<llvm::MemoryBuffer> moduleDocInputBuffer,
-                    bool isFramework = false);
+                    bool isFramework, bool treatAsPartialModule);
 
   /// Check whether the module with a given name can be imported without
   /// importing it.
diff --git a/lib/AST/ASTDumper.cpp b/lib/AST/ASTDumper.cpp
index 62e5ddf..2ecc190 100644
--- a/lib/AST/ASTDumper.cpp
+++ b/lib/AST/ASTDumper.cpp
@@ -2068,6 +2068,8 @@
   }
   void visitArrayExpr(ArrayExpr *E) {
     printCommon(E, "array_expr");
+    PrintWithColorRAII(OS, LiteralValueColor) << " initializer=";
+    E->getInitializer().dump(PrintWithColorRAII(OS, LiteralValueColor).getOS());
     for (auto elt : E->getElements()) {
       OS << '\n';
       printRec(elt);
@@ -2154,42 +2156,6 @@
     printRec(E->getResultExpr());
     PrintWithColorRAII(OS, ParenthesisColor) << ')';
   }
-  void visitArgumentShuffleExpr(ArgumentShuffleExpr *E) {
-    printCommon(E, "argument_shuffle_expr");
-    switch (E->getTypeImpact()) {
-    case ArgumentShuffleExpr::ScalarToTuple:
-      OS << " scalar_to_tuple";
-      break;
-    case ArgumentShuffleExpr::TupleToTuple:
-      OS << " tuple_to_tuple";
-      break;
-    case ArgumentShuffleExpr::TupleToScalar:
-      OS << " tuple_to_scalar";
-      break;
-    }
-    OS << " elements=[";
-    for (unsigned i = 0, e = E->getElementMapping().size(); i != e; ++i) {
-      if (i) OS << ", ";
-      OS << E->getElementMapping()[i];
-    }
-    OS << "]";
-    OS << " variadic_sources=[";
-    interleave(E->getVariadicArgs(),
-               [&](unsigned source) {
-                 OS << source;
-               },
-               [&] { OS << ", "; });
-    OS << "]";
-
-    if (auto defaultArgsOwner = E->getDefaultArgsOwner()) {
-      OS << " default_args_owner=";
-      defaultArgsOwner.dump(OS);
-    }
-
-    OS << "\n";
-    printRec(E->getSubExpr());
-    PrintWithColorRAII(OS, ParenthesisColor) << ')';
-  }
   void visitUnresolvedTypeConversionExpr(UnresolvedTypeConversionExpr *E) {
     printCommon(E, "unresolvedtype_conversion_expr") << '\n';
     printRec(E->getSubExpr());
@@ -2452,6 +2418,20 @@
     PrintWithColorRAII(OS, ParenthesisColor) << ')';
   }
 
+  void visitDefaultArgumentExpr(DefaultArgumentExpr *E) {
+    printCommon(E, "default_argument_expr");
+    OS << " default_args_owner=";
+    E->getDefaultArgsOwner().dump(OS);
+    OS << " param=" << E->getParamIndex();
+    PrintWithColorRAII(OS, ParenthesisColor) << ')';
+  }
+
+  void visitCallerDefaultArgumentExpr(CallerDefaultArgumentExpr *E) {
+    printCommon(E, "caller_default_argument_expr");
+    printRec(E->getSubExpr());
+    PrintWithColorRAII(OS, ParenthesisColor) << ')';
+  }
+
   void printArgumentLabels(ArrayRef<Identifier> argLabels) {
     PrintWithColorRAII(OS, ArgumentsColor) << " arg_labels=";
     for (auto label : argLabels) {
diff --git a/lib/AST/ASTPrinter.cpp b/lib/AST/ASTPrinter.cpp
index 6a36595..b43538c 100644
--- a/lib/AST/ASTPrinter.cpp
+++ b/lib/AST/ASTPrinter.cpp
@@ -2781,8 +2781,13 @@
                                       ->castTo<AnyFunctionType>()
                                       ->getParams();
     }
+
+    // @escaping is not valid in enum element position, even though the
+    // attribute is implicitly added. Ignore it when printing the parameters.
+    Options.ExcludeAttrList.push_back(TAK_escaping);
     printParameterList(PL, params,
                        /*isAPINameByDefault*/true);
+    Options.ExcludeAttrList.pop_back();
   }
 
   auto *raw = elt->getRawValueExpr();
@@ -3375,7 +3380,11 @@
     if (!Options.FullyQualifiedTypesIfAmbiguous)
       return false;
 
-    Decl *D = T->getAnyGeneric();
+    Decl *D;
+    if (auto *TAT = dyn_cast<TypeAliasType>(T))
+      D = TAT->getDecl();
+    else
+      D = T->getAnyGeneric();
 
     // If we cannot find the declaration, be extra careful and print
     // the type qualified.
@@ -3507,6 +3516,8 @@
     if (auto parent = T->getParent()) {
       visit(parent);
       Printer << ".";
+    } else if (shouldPrintFullyQualified(T)) {
+      printModuleContext(T);
     }
 
     printTypeDeclName(T);
@@ -4024,6 +4035,10 @@
   }
 
   void visitProtocolType(ProtocolType *T) {
+    if (shouldPrintFullyQualified(T)) {
+      printModuleContext(T);
+    }
+
     printTypeDeclName(T);
   }
 
diff --git a/lib/AST/ASTVerifier.cpp b/lib/AST/ASTVerifier.cpp
index 1248b28..695ee77 100644
--- a/lib/AST/ASTVerifier.cpp
+++ b/lib/AST/ASTVerifier.cpp
@@ -1729,12 +1729,6 @@
         }
       };
 
-      // If we have an argument shuffle, strip it off. We want to visit the
-      // underlying paren or tuple expr.
-      if (auto *ArgShuffle = dyn_cast<ArgumentShuffleExpr>(Arg)) {
-        Arg = ArgShuffle->getSubExpr();
-      }
-
       if (auto *ParentExprArg = dyn_cast<ParenExpr>(Arg)) {
         return handleSubExpr(ParentExprArg->getSubExpr());
       }
@@ -2039,66 +2033,7 @@
 
       verifyCheckedBase(E);
     }
-    
-    void verifyChecked(ArgumentShuffleExpr *E) {
-      PrettyStackTraceExpr debugStack(Ctx, "verifying ArgumentShuffleExpr", E);
 
-      auto getSubElementType = [&](unsigned i) {
-        if (E->isSourceScalar()) {
-          assert(i == 0);
-          return E->getSubExpr()->getType();
-        } else {
-          return (E->getSubExpr()->getType()->castTo<TupleType>()
-                   ->getElementType(i));
-        }
-      };
-
-      /// Retrieve the ith element type from the resulting tuple type.
-      auto getOuterElementType = [&](unsigned i) -> Type {
-        if (E->isResultScalar()) {
-          assert(i == 0);
-          return E->getType()->getWithoutParens();
-        } else {
-          return E->getType()->castTo<TupleType>()->getElementType(i);
-        }
-      };
-
-      Type varargsType;
-      unsigned callerDefaultArgIndex = 0;
-      for (unsigned i = 0, e = E->getElementMapping().size(); i != e; ++i) {
-        int subElem = E->getElementMapping()[i];
-        if (subElem == ArgumentShuffleExpr::DefaultInitialize)
-          continue;
-        if (subElem == ArgumentShuffleExpr::Variadic) {
-          varargsType = (E->getType()->castTo<TupleType>()
-                          ->getElement(i).getVarargBaseTy());
-          break;
-        }
-        if (subElem == ArgumentShuffleExpr::CallerDefaultInitialize) {
-          auto init = E->getCallerDefaultArgs()[callerDefaultArgIndex++];
-          if (!getOuterElementType(i)->isEqual(init->getType())) {
-            Out << "Type mismatch in ArgumentShuffleExpr\n";
-            abort();
-          }
-          continue;
-        }
-        if (!getOuterElementType(i)->isEqual(getSubElementType(subElem))) {
-          Out << "Type mismatch in ArgumentShuffleExpr\n";
-          abort();
-        }
-      }
-      if (varargsType) {
-        for (auto sourceIdx : E->getVariadicArgs()) {
-          if (!getSubElementType(sourceIdx)->isEqual(varargsType)) {
-            Out << "Vararg type mismatch in ArgumentShuffleExpr\n";
-            abort();
-          }
-        }
-      }
-
-      verifyCheckedBase(E);
-    }
-    
     void verifyChecked(DynamicTypeExpr *E) {
       PrettyStackTraceExpr debugStack(Ctx, "verifying DynamicTypeExpr", E);
 
diff --git a/lib/AST/ASTWalker.cpp b/lib/AST/ASTWalker.cpp
index e299778..6c64e64 100644
--- a/lib/AST/ASTWalker.cpp
+++ b/lib/AST/ASTWalker.cpp
@@ -443,6 +443,17 @@
 
   Expr *visitOpaqueValueExpr(OpaqueValueExpr *E) { return E; }
 
+  Expr *visitDefaultArgumentExpr(DefaultArgumentExpr *E) { return E; }
+
+  Expr *visitCallerDefaultArgumentExpr(CallerDefaultArgumentExpr *E) {
+    if (auto subExpr = doIt(E->getSubExpr())) {
+      E->setSubExpr(subExpr);
+      return E;
+    }
+
+    return nullptr;
+  }
+
   Expr *visitInterpolatedStringLiteralExpr(InterpolatedStringLiteralExpr *E) {
     HANDLE_SEMANTIC_EXPR(E);
 
@@ -655,23 +666,6 @@
     return E;
   }
 
-  Expr *visitArgumentShuffleExpr(ArgumentShuffleExpr *E) {
-    if (Expr *E2 = doIt(E->getSubExpr())) {
-      E->setSubExpr(E2);
-    } else {
-      return nullptr;
-    }
-
-    for (auto &defaultArg : E->getCallerDefaultArgs()) {
-      if (Expr *newDefaultArg = doIt(defaultArg))
-        defaultArg = newDefaultArg;
-      else
-        return nullptr;
-    }
-
-    return E;
-  }
-
   Expr *visitTryExpr(TryExpr *E) {
     if (Expr *E2 = doIt(E->getSubExpr())) {
       E->setSubExpr(E2);
diff --git a/lib/AST/Attr.cpp b/lib/AST/Attr.cpp
index a8751e9..4541b48 100644
--- a/lib/AST/Attr.cpp
+++ b/lib/AST/Attr.cpp
@@ -18,6 +18,7 @@
 #include "swift/AST/ASTContext.h"
 #include "swift/AST/ASTPrinter.h"
 #include "swift/AST/Decl.h"
+#include "swift/AST/Expr.h"
 #include "swift/AST/GenericEnvironment.h"
 #include "swift/AST/Module.h"
 #include "swift/AST/Types.h"
@@ -618,6 +619,16 @@
     break;
   }
 
+  case DAK_Custom: {
+    Printer.printAttrName("@");
+    const TypeLoc &typeLoc = cast<CustomAttr>(this)->getTypeLoc();
+    if (auto type = typeLoc.getType())
+      type->print(Printer, Options);
+    else
+      typeLoc.getTypeRepr()->print(Printer, Options);
+    break;
+  }
+
   case DAK_Count:
     llvm_unreachable("exceed declaration attribute kinds");
 
@@ -744,6 +755,8 @@
     return "_implements";
   case DAK_ClangImporterSynthesizedType:
     return "_clangImporterSynthesizedType";
+  case DAK_Custom:
+    return "<<custom>>";
   }
   llvm_unreachable("bad DeclAttrKind");
 }
@@ -1134,3 +1147,51 @@
 TypeLoc &ImplementsAttr::getProtocolType() {
   return ProtocolType;
 }
+
+CustomAttr::CustomAttr(SourceLoc atLoc, SourceRange range, TypeLoc type,
+                       PatternBindingInitializer *initContext, Expr *arg,
+                       ArrayRef<Identifier> argLabels,
+                       ArrayRef<SourceLoc> argLabelLocs, bool implicit)
+    : DeclAttribute(DAK_Custom, atLoc, range, implicit),
+      type(type),
+      arg(arg),
+      initContext(initContext) {
+  hasArgLabelLocs = !argLabelLocs.empty();
+  numArgLabels = argLabels.size();
+  initializeCallArguments(argLabels, argLabelLocs,
+                          /*hasTrailingClosure=*/false);
+}
+
+CustomAttr *CustomAttr::create(ASTContext &ctx, SourceLoc atLoc, TypeLoc type,
+                               bool hasInitializer,
+                               PatternBindingInitializer *initContext,
+                               SourceLoc lParenLoc,
+                               ArrayRef<Expr *> args,
+                               ArrayRef<Identifier> argLabels,
+                               ArrayRef<SourceLoc> argLabelLocs,
+                               SourceLoc rParenLoc,
+                               bool implicit) {
+  SmallVector<Identifier, 2> argLabelsScratch;
+  SmallVector<SourceLoc, 2> argLabelLocsScratch;
+  Expr *arg = nullptr;
+  if (hasInitializer) {
+    arg = packSingleArgument(ctx, lParenLoc, args, argLabels, argLabelLocs,
+                             rParenLoc, nullptr, implicit, argLabelsScratch,
+                             argLabelLocsScratch);
+  }
+
+  SourceRange range(atLoc, type.getSourceRange().End);
+  if (arg)
+    range.End = arg->getEndLoc();
+
+  size_t size = totalSizeToAlloc(argLabels, argLabelLocs,
+                                 /*hasTrailingClosure=*/false);
+  void *mem = ctx.Allocate(size, alignof(CustomAttr));
+  return new (mem) CustomAttr(atLoc, range, type, initContext, arg, argLabels,
+                              argLabelLocs, implicit);
+}
+
+void swift::simple_display(llvm::raw_ostream &out, const DeclAttribute *attr) {
+  if (attr)
+    attr->print(out);
+}
diff --git a/lib/AST/Decl.cpp b/lib/AST/Decl.cpp
index 1489410..b46f8da 100644
--- a/lib/AST/Decl.cpp
+++ b/lib/AST/Decl.cpp
@@ -2226,6 +2226,10 @@
                                      bool isMethod,
                                      bool isInitializer,
                                      unsigned curryLevels) {
+  if (type->hasError()) {
+    return type;
+  }
+
   if (curryLevels == 0) {
     // In an initializer, ignore optionality.
     if (isInitializer) {
@@ -2316,7 +2320,12 @@
     if (isa<VarDecl>(this)) {
       defaultSignatureType = TupleType::getEmpty(getASTContext());
     } else {
-      defaultSignatureType = getInterfaceType()->getCanonicalType();
+      defaultSignatureType = mapSignatureFunctionType(
+          getASTContext(), getInterfaceType(),
+          /*topLevelFunction=*/true,
+          /*isMethod=*/false,
+          /*isInitializer=*/false,
+          1)->getCanonicalType();
     }
 
     // We want to curry the default signature type with the 'self' type of the
@@ -3794,6 +3803,27 @@
   return nullptr;
 }
 
+bool ClassDecl::walkSuperclasses(
+    llvm::function_ref<TypeWalker::Action(ClassDecl *)> fn) const {
+
+  SmallPtrSet<ClassDecl *, 8> seen;
+  auto *cls = const_cast<ClassDecl *>(this);
+
+  while (cls && seen.insert(cls).second) {
+    switch (fn(cls)) {
+    case TypeWalker::Action::Stop:
+      return true;
+    case TypeWalker::Action::SkipChildren:
+      return false;
+    case TypeWalker::Action::Continue:
+      cls = cls->getSuperclassDecl();
+      continue;
+    }
+  }
+
+  return false;
+}
+
 EnumCaseDecl *EnumCaseDecl::create(SourceLoc CaseLoc,
                                    ArrayRef<EnumElementDecl *> Elements,
                                    DeclContext *DC) {
diff --git a/lib/AST/Expr.cpp b/lib/AST/Expr.cpp
index 8e960f7..e4c5062 100644
--- a/lib/AST/Expr.cpp
+++ b/lib/AST/Expr.cpp
@@ -308,6 +308,9 @@
   PASS_THROUGH_REFERENCE(RebindSelfInConstructor, getSubExpr);
 
   NO_REFERENCE(OpaqueValue);
+  NO_REFERENCE(DefaultArgument);
+  NO_REFERENCE(CallerDefaultArgument);
+
   PASS_THROUGH_REFERENCE(BindOptional, getSubExpr);
   PASS_THROUGH_REFERENCE(OptionalEvaluation, getSubExpr);
   PASS_THROUGH_REFERENCE(ForceValue, getSubExpr);
@@ -323,7 +326,6 @@
   PASS_THROUGH_REFERENCE(ConstructorRefCall, getFn);
   PASS_THROUGH_REFERENCE(Load, getSubExpr);
   NO_REFERENCE(DestructureTuple);
-  NO_REFERENCE(ArgumentShuffle);
   NO_REFERENCE(UnresolvedTypeConversion);
   PASS_THROUGH_REFERENCE(FunctionConversion, getSubExpr);
   PASS_THROUGH_REFERENCE(CovariantFunctionConversion, getSubExpr);
@@ -612,6 +614,8 @@
 
   case ExprKind::RebindSelfInConstructor:
   case ExprKind::OpaqueValue:
+  case ExprKind::DefaultArgument:
+  case ExprKind::CallerDefaultArgument:
   case ExprKind::BindOptional:
   case ExprKind::OptionalEvaluation:
     return false;
@@ -638,7 +642,6 @@
 
   case ExprKind::Load:
   case ExprKind::DestructureTuple:
-  case ExprKind::ArgumentShuffle:
   case ExprKind::UnresolvedTypeConversion:
   case ExprKind::FunctionConversion:
   case ExprKind::CovariantFunctionConversion:
@@ -1089,23 +1092,16 @@
   arg->setType(TupleType::get(typeElements, ctx));
 }
 
-/// Pack the argument information into a single argument, to match the
-/// representation expected by the AST.
-///
-/// \param argLabels The argument labels, which might be updated by this
-/// function.
-///
-/// \param argLabelLocs The argument label locations, which might be updated by
-/// this function.
-static Expr *
-packSingleArgument(ASTContext &ctx, SourceLoc lParenLoc, ArrayRef<Expr *> args,
-                   ArrayRef<Identifier> &argLabels,
-                   ArrayRef<SourceLoc> &argLabelLocs, SourceLoc rParenLoc,
-                   Expr *trailingClosure, bool implicit,
-                   SmallVectorImpl<Identifier> &argLabelsScratch,
-                   SmallVectorImpl<SourceLoc> &argLabelLocsScratch,
-                   llvm::function_ref<Type(const Expr *)> getType =
-                       [](const Expr *E) -> Type { return E->getType(); }) {
+Expr *
+swift::packSingleArgument(ASTContext &ctx, SourceLoc lParenLoc,
+                          ArrayRef<Expr *> args,
+                          ArrayRef<Identifier> &argLabels,
+                          ArrayRef<SourceLoc> &argLabelLocs,
+                          SourceLoc rParenLoc,
+                          Expr *trailingClosure, bool implicit,
+                          SmallVectorImpl<Identifier> &argLabelsScratch,
+                          SmallVectorImpl<SourceLoc> &argLabelLocsScratch,
+                          llvm::function_ref<Type(const Expr *)> getType) {
   // Clear out our scratch space.
   argLabelsScratch.clear();
   argLabelLocsScratch.clear();
@@ -1343,24 +1339,6 @@
                                          srcExpr, dstExpr, ty);
 }
 
-ArgumentShuffleExpr *ArgumentShuffleExpr::create(ASTContext &ctx,
-                                                 Expr *subExpr,
-                                                 ArrayRef<int> elementMapping,
-                                                 TypeImpact typeImpact,
-                                                 ConcreteDeclRef defaultArgsOwner,
-                                                 ArrayRef<unsigned> VariadicArgs,
-                                                 Type VarargsArrayTy,
-                                                 ArrayRef<Expr *> CallerDefaultArgs,
-                                                 Type ty) {
-  auto size = totalSizeToAlloc<Expr*, int, unsigned>(CallerDefaultArgs.size(),
-                                                     elementMapping.size(),
-                                                     VariadicArgs.size());
-  auto mem = ctx.Allocate(size, alignof(ArgumentShuffleExpr));
-  return ::new(mem) ArgumentShuffleExpr(subExpr, elementMapping, typeImpact,
-                                        defaultArgsOwner, VariadicArgs,
-                                        VarargsArrayTy, CallerDefaultArgs, ty);
-}
-
 SourceRange TupleExpr::getSourceRange() const {
   SourceLoc start = SourceLoc();
   SourceLoc end = SourceLoc();
@@ -1489,6 +1467,19 @@
   return new (Mem) ArrayExpr(LBracketLoc, Elements, CommaLocs, RBracketLoc, Ty);
 }
 
+Type ArrayExpr::getElementType() {
+  auto init = getInitializer();
+  if (!init)
+    return Type();
+
+  auto *decl = cast<ConstructorDecl>(init.getDecl());
+  return decl->getMethodInterfaceType()
+      ->getAs<AnyFunctionType>()
+      ->getParams()[0]
+      .getPlainType()
+      .subst(init.getSubstitutions());
+}
+
 DictionaryExpr *DictionaryExpr::create(ASTContext &C, SourceLoc LBracketLoc,
                              ArrayRef<Expr*> Elements,
                              ArrayRef<SourceLoc> CommaLocs,
diff --git a/lib/AST/GenericSignatureBuilder.cpp b/lib/AST/GenericSignatureBuilder.cpp
index a21ac15..6be7306 100644
--- a/lib/AST/GenericSignatureBuilder.cpp
+++ b/lib/AST/GenericSignatureBuilder.cpp
@@ -6014,7 +6014,7 @@
   }
 
   // Sort the constraints, so we get a deterministic ordering of diagnostics.
-  llvm::array_pod_sort(constraints.begin(), constraints.end());
+  std::sort(constraints.begin(), constraints.end());
 
   // Find a representative constraint.
   auto representativeConstraint =
diff --git a/lib/AST/Module.cpp b/lib/AST/Module.cpp
index c138848..2012e41 100644
--- a/lib/AST/Module.cpp
+++ b/lib/AST/Module.cpp
@@ -1020,21 +1020,18 @@
 SourceFile::getImportedModules(SmallVectorImpl<ModuleDecl::ImportedModule> &modules,
                                ModuleDecl::ImportFilter filter) const {
   assert(ASTStage >= Parsed || Kind == SourceFileKind::SIL);
+  assert(filter && "no imports requested?");
   for (auto desc : Imports) {
-    switch (filter) {
-    case ModuleDecl::ImportFilter::All:
-      break;
-    case ModuleDecl::ImportFilter::Public:
-      if (!desc.importOptions.contains(ImportFlags::Exported))
-        continue;
-      break;
-    case ModuleDecl::ImportFilter::Private:
-      if (desc.importOptions.contains(ImportFlags::Exported))
-        continue;
-      break;
-    }
+    ModuleDecl::ImportFilterKind requiredKind;
+    if (desc.importOptions.contains(ImportFlags::Exported))
+      requiredKind = ModuleDecl::ImportFilterKind::Public;
+    else if (desc.importOptions.contains(ImportFlags::ImplementationOnly))
+      requiredKind = ModuleDecl::ImportFilterKind::ImplementationOnly;
+    else
+      requiredKind = ModuleDecl::ImportFilterKind::Private;
 
-    modules.push_back(desc.module);
+    if (filter.contains(requiredKind))
+      modules.push_back(desc.module);
   }
 }
 
@@ -1277,9 +1274,14 @@
   llvm::SmallSet<ImportedModule, 32, ModuleDecl::OrderImportedModules> visited;
   SmallVector<ImportedModule, 32> stack;
 
-  auto filter = respectVisibility ? ModuleDecl::ImportFilter::Public
-                                  : ModuleDecl::ImportFilter::All;
-  topLevel->getImportedModules(stack, filter);
+  ModuleDecl::ImportFilter filter = ModuleDecl::ImportFilterKind::Public;
+  if (!respectVisibility)
+    filter |= ModuleDecl::ImportFilterKind::Private;
+
+  ModuleDecl::ImportFilter topLevelFilter = filter;
+  if (!respectVisibility)
+    topLevelFilter |= ModuleDecl::ImportFilterKind::ImplementationOnly;
+  topLevel->getImportedModules(stack, topLevelFilter);
 
   // Make sure the top-level module is first; we want pre-order-ish traversal.
   AccessPathTy overridingPath;
@@ -1330,9 +1332,11 @@
 
   if (auto SF = dyn_cast<SourceFile>(this)) {
     // Handle privately visible modules as well.
-    // FIXME: Should this apply to all FileUnits?
+    ModuleDecl::ImportFilter importFilter;
+    importFilter |= ModuleDecl::ImportFilterKind::Private;
+    importFilter |= ModuleDecl::ImportFilterKind::ImplementationOnly;
     SmallVector<ModuleDecl::ImportedModule, 4> imports;
-    SF->getImportedModules(imports, ModuleDecl::ImportFilter::Private);
+    SF->getImportedModules(imports, importFilter);
     for (auto importPair : imports)
       if (!importPair.second->forAllVisibleModules(importPair.first, fn))
         return false;
diff --git a/lib/AST/NameLookup.cpp b/lib/AST/NameLookup.cpp
index 9180840..a11c888 100644
--- a/lib/AST/NameLookup.cpp
+++ b/lib/AST/NameLookup.cpp
@@ -2093,6 +2093,31 @@
   return nominalTypes.empty() ? nullptr : nominalTypes.front();
 }
 
+llvm::Expected<NominalTypeDecl *>
+CustomAttrNominalRequest::evaluate(Evaluator &evaluator,
+                                   CustomAttr *attr, DeclContext *dc) const {
+  // Find the types referenced by the custom attribute.
+  auto &ctx = dc->getASTContext();
+  TypeLoc &typeLoc = attr->getTypeLoc();
+  DirectlyReferencedTypeDecls decls;
+  if (auto typeRepr = typeLoc.getTypeRepr()) {
+    decls = directReferencesForTypeRepr(
+        evaluator, ctx, typeRepr, dc);
+  } else if (Type type = typeLoc.getType()) {
+    decls = directReferencesForType(type);
+  }
+
+  // Dig out the nominal type declarations.
+  SmallVector<ModuleDecl *, 2> modulesFound;
+  bool anyObject = false;
+  auto nominals = resolveTypeDeclsToNominal(evaluator, ctx, decls,
+                                            modulesFound, anyObject);
+  if (nominals.size() == 1 && !isa<ProtocolDecl>(nominals.front()))
+    return nominals.front();
+
+  return nullptr;
+}
+
 void swift::getDirectlyInheritedNominalTypeDecls(
     llvm::PointerUnion<TypeDecl *, ExtensionDecl *> decl,
     unsigned i,
diff --git a/lib/AST/NameLookupRequests.cpp b/lib/AST/NameLookupRequests.cpp
index 0a82db6..3016b75 100644
--- a/lib/AST/NameLookupRequests.cpp
+++ b/lib/AST/NameLookupRequests.cpp
@@ -12,6 +12,7 @@
 
 #include "swift/AST/NameLookupRequests.h"
 #include "swift/Subsystems.h"
+#include "swift/AST/ASTContext.h"
 #include "swift/AST/Evaluator.h"
 #include "swift/AST/Decl.h"
 #include "swift/AST/Module.h"
@@ -176,6 +177,20 @@
   diags.diagnose(ext, diag::circular_reference_through);
 }
 
+void CustomAttrNominalRequest::diagnoseCycle(
+    DiagnosticEngine &diags) const {
+  auto attr = std::get<0>(getStorage());
+  ASTContext &ctx = std::get<1>(getStorage())->getASTContext();
+  ctx.Diags.diagnose(attr->getLocation(), diag::circular_reference);
+}
+
+void CustomAttrNominalRequest::noteCycleStep(
+    DiagnosticEngine &diags) const {
+  auto attr = std::get<0>(getStorage());
+  ASTContext &ctx = std::get<1>(getStorage())->getASTContext();
+  ctx.Diags.diagnose(attr->getLocation(), diag::circular_reference_through);
+}
+
 // Define request evaluation functions for each of the name lookup requests.
 static AbstractRequestFunction *nameLookupRequestFunctions[] = {
 #define SWIFT_TYPEID(Name)                                    \
diff --git a/lib/AST/UnqualifiedLookup.cpp b/lib/AST/UnqualifiedLookup.cpp
index f27e670..d18b2ae 100644
--- a/lib/AST/UnqualifiedLookup.cpp
+++ b/lib/AST/UnqualifiedLookup.cpp
@@ -1044,8 +1044,12 @@
 void UnqualifiedLookupFactory::addImportedResults(DeclContext *const dc) {
   // Add private imports to the extra search list.
   SmallVector<ModuleDecl::ImportedModule, 8> extraImports;
-  if (auto FU = dyn_cast<FileUnit>(dc))
-    FU->getImportedModules(extraImports, ModuleDecl::ImportFilter::Private);
+  if (auto FU = dyn_cast<FileUnit>(dc)) {
+    ModuleDecl::ImportFilter importFilter;
+    importFilter |= ModuleDecl::ImportFilterKind::Private;
+    importFilter |= ModuleDecl::ImportFilterKind::ImplementationOnly;
+    FU->getImportedModules(extraImports, importFilter);
+  }
 
   using namespace namelookup;
   SmallVector<ValueDecl *, 8> CurModuleResults;
diff --git a/lib/Basic/Default/TaskQueue.inc b/lib/Basic/Default/TaskQueue.inc
index 1fe79b5..1085f5b 100644
--- a/lib/Basic/Default/TaskQueue.inc
+++ b/lib/Basic/Default/TaskQueue.inc
@@ -29,6 +29,12 @@
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Signals.h"
 
+#if defined(_WIN32)
+#define NOMINMAX
+#include <Windows.h>
+#include <psapi.h>
+#endif
+
 using namespace llvm::sys;
 
 namespace swift {
@@ -150,15 +156,35 @@
     // This isn't a true signal on Windows, but we'll treat it as such so that
     // we clean up after it properly
     bool crashed = ReturnCode & 0xC0000000;
+
+    FILETIME creationTime;
+    FILETIME exitTime;
+    FILETIME utimeTicks;
+    FILETIME stimeTicks;
+    PROCESS_MEMORY_COUNTERS counters = {};
+    GetProcessTimes(PI.Process, &creationTime, &exitTime, &stimeTicks,
+                    &utimeTicks);
+    // Each tick is 100ns
+    uint64_t utime =
+        ((uint64_t)utimeTicks.dwHighDateTime << 32 | utimeTicks.dwLowDateTime) /
+        10;
+    uint64_t stime =
+        ((uint64_t)stimeTicks.dwHighDateTime << 32 | stimeTicks.dwLowDateTime) /
+        10;
+    GetProcessMemoryInfo(PI.Process, &counters, sizeof(counters));
+
+    TaskProcessInformation tpi(PI.Pid, utime, stime,
+                               counters.PeakWorkingSetSize);
 #else
       // Wait() returning a return code of -2 indicates the process received
       // a signal during execution.
     bool crashed = ReturnCode == -2;
+    TaskProcessInformation tpi(PI.Pid);
 #endif
     if (crashed) {
       if (Signalled) {
         TaskFinishedResponse Response =
-            Signalled(PI.Pid, ErrMsg, stdoutContents, stderrContents, T->Context, ReturnCode, TaskProcessInformation(PI.Pid));
+            Signalled(PI.Pid, ErrMsg, stdoutContents, stderrContents, T->Context, ReturnCode, tpi);
         ContinueExecution = Response != TaskFinishedResponse::StopExecution;
       } else {
         // If we don't have a Signalled callback, unconditionally stop.
@@ -169,7 +195,7 @@
       // finished.
       if (Finished) {
         TaskFinishedResponse Response = Finished(PI.Pid, PI.ReturnCode,
-        stdoutContents, stderrContents, TaskProcessInformation(PI.Pid), T->Context);
+        stdoutContents, stderrContents, tpi, T->Context);
         ContinueExecution = Response != TaskFinishedResponse::StopExecution;
       } else if (PI.ReturnCode != 0) {
         ContinueExecution = false;
diff --git a/lib/Basic/Statistic.cpp b/lib/Basic/Statistic.cpp
index 12f77fb..90cacfc 100644
--- a/lib/Basic/Statistic.cpp
+++ b/lib/Basic/Statistic.cpp
@@ -45,6 +45,11 @@
 #ifdef HAVE_MALLOC_MALLOC_H
 #include <malloc/malloc.h>
 #endif
+#if defined(_WIN32)
+#define NOMINMAX
+#include "Windows.h"
+#include "psapi.h"
+#endif
 
 namespace swift {
 using namespace llvm;
@@ -56,26 +61,6 @@
   return false;
 }
 
-static int64_t
-getChildrenMaxResidentSetSize() {
-#if defined(HAVE_GETRUSAGE) && !defined(__HAIKU__)
-  struct rusage RU;
-  ::getrusage(RUSAGE_CHILDREN, &RU);
-  int64_t M = static_cast<int64_t>(RU.ru_maxrss);
-  if (M < 0) {
-    M = std::numeric_limits<int64_t>::max();
-  } else {
-#ifndef __APPLE__
-    // Apple systems report bytes; everything else appears to report KB.
-    M <<= 10;
-#endif
-  }
-  return M;
-#else
-  return 0;
-#endif
-}
-
 static std::string
 makeFileName(StringRef Prefix,
              StringRef ProgramName,
@@ -380,6 +365,29 @@
     EntityProfilers = make_unique<StatsProfilers>();
 }
 
+void UnifiedStatsReporter::recordJobMaxRSS(long rss) {
+  maxChildRSS = std::max(maxChildRSS, rss);
+}
+
+int64_t UnifiedStatsReporter::getChildrenMaxResidentSetSize() {
+#if defined(HAVE_GETRUSAGE) && !defined(__HAIKU__)
+  struct rusage RU;
+  ::getrusage(RUSAGE_CHILDREN, &RU);
+  int64_t M = static_cast<int64_t>(RU.ru_maxrss);
+  if (M < 0) {
+    M = std::numeric_limits<int64_t>::max();
+  } else {
+#ifndef __APPLE__
+    // Apple systems report bytes; everything else appears to report KB.
+    M <<= 10;
+#endif
+  }
+  return M;
+#else
+  return maxChildRSS;
+#endif
+}
+
 UnifiedStatsReporter::AlwaysOnDriverCounters &
 UnifiedStatsReporter::getDriverCounters()
 {
diff --git a/lib/ClangImporter/ClangImporter.cpp b/lib/ClangImporter/ClangImporter.cpp
index 2a06586..0d5bb2e 100644
--- a/lib/ClangImporter/ClangImporter.cpp
+++ b/lib/ClangImporter/ClangImporter.cpp
@@ -3203,71 +3203,43 @@
 void ClangModuleUnit::getImportedModules(
     SmallVectorImpl<ModuleDecl::ImportedModule> &imports,
     ModuleDecl::ImportFilter filter) const {
-  switch (filter) {
-  case ModuleDecl::ImportFilter::All:
-  case ModuleDecl::ImportFilter::Private:
+  // Bail out if we /only/ want ImplementationOnly imports; Clang modules never
+  // have any of these.
+  if (filter.containsOnly(ModuleDecl::ImportFilterKind::ImplementationOnly))
+    return;
+
+  if (filter.contains(ModuleDecl::ImportFilterKind::Private))
     if (auto stdlib = owner.getStdlibModule())
       imports.push_back({ModuleDecl::AccessPathTy(), stdlib});
-    break;
-  case ModuleDecl::ImportFilter::Public:
-    break;
-  }
 
   SmallVector<clang::Module *, 8> imported;
   if (!clangModule) {
     // This is the special "imported headers" module.
-    switch (filter) {
-    case ModuleDecl::ImportFilter::All:
-    case ModuleDecl::ImportFilter::Public:
+    if (filter.contains(ModuleDecl::ImportFilterKind::Public)) {
       imported.append(owner.ImportedHeaderExports.begin(),
                       owner.ImportedHeaderExports.end());
-      break;
-
-    case ModuleDecl::ImportFilter::Private:
-      break;
     }
 
   } else {
     clangModule->getExportedModules(imported);
 
-    switch (filter) {
-    case ModuleDecl::ImportFilter::All: {
-      llvm::SmallPtrSet<clang::Module *, 8> knownModules;
-      imported.append(clangModule->Imports.begin(), clangModule->Imports.end());
-      imported.erase(std::remove_if(imported.begin(), imported.end(),
-                                    [&](clang::Module *mod) -> bool {
-                                      return !knownModules.insert(mod).second;
-                                    }),
-                     imported.end());
-
-      // FIXME: The parent module isn't exactly a private import, but it is
-      // needed for link dependencies.
-      if (clangModule->Parent)
-        imported.push_back(clangModule->Parent);
-
-      break;
-    }
-
-    case ModuleDecl::ImportFilter::Private: {
+    if (filter.contains(ModuleDecl::ImportFilterKind::Private)) {
+      // Copy in any modules that are imported but not exported.
       llvm::SmallPtrSet<clang::Module *, 8> knownModules(imported.begin(),
                                                          imported.end());
-      SmallVector<clang::Module *, 8> privateImports;
-      std::copy_if(clangModule->Imports.begin(), clangModule->Imports.end(),
-                   std::back_inserter(privateImports), [&](clang::Module *mod) {
-                     return knownModules.count(mod) == 0;
-                   });
-      imported.swap(privateImports);
+      if (!filter.contains(ModuleDecl::ImportFilterKind::Public)) {
+        // Remove the exported ones now that we're done with them.
+        imported.clear();
+      }
+      llvm::copy_if(clangModule->Imports, std::back_inserter(imported),
+                    [&](clang::Module *mod) {
+                     return !knownModules.insert(mod).second;
+                    });
 
       // FIXME: The parent module isn't exactly a private import, but it is
       // needed for link dependencies.
       if (clangModule->Parent)
         imported.push_back(clangModule->Parent);
-
-      break;
-    }
-
-    case ModuleDecl::ImportFilter::Public:
-      break;
     }
   }
 
diff --git a/lib/Driver/Compilation.cpp b/lib/Driver/Compilation.cpp
index 7c59d74..8d24140 100644
--- a/lib/Driver/Compilation.cpp
+++ b/lib/Driver/Compilation.cpp
@@ -603,6 +603,10 @@
         }
       }
 
+      if (Comp.getStatsReporter() && ProcInfo.getResourceUsage().hasValue())
+        Comp.getStatsReporter()->recordJobMaxRSS(
+            ProcInfo.getResourceUsage()->Maxrss);
+
       if (isBatchJob(FinishedCmd)) {
         return unpackAndFinishBatch(ReturnCode, Output, Errors,
                                     static_cast<const BatchJob *>(FinishedCmd));
@@ -684,6 +688,11 @@
         if (TaskQueue::supportsBufferingOutput())
           llvm::errs() << Output;
       }
+
+      if (Comp.getStatsReporter() && ProcInfo.getResourceUsage().hasValue())
+        Comp.getStatsReporter()->recordJobMaxRSS(
+            ProcInfo.getResourceUsage()->Maxrss);
+
       if (!ErrorMsg.empty())
         Comp.getDiags().diagnose(SourceLoc(),
                                  diag::error_unable_to_execute_command,
diff --git a/lib/Frontend/Frontend.cpp b/lib/Frontend/Frontend.cpp
index 1491031..bf27cae 100644
--- a/lib/Frontend/Frontend.cpp
+++ b/lib/Frontend/Frontend.cpp
@@ -868,7 +868,8 @@
   for (auto &PM : PartialModules) {
     assert(PM.ModuleBuffer);
     if (!SML->loadAST(*MainModule, SourceLoc(), std::move(PM.ModuleBuffer),
-                      std::move(PM.ModuleDocBuffer)))
+                      std::move(PM.ModuleDocBuffer), /*isFramework*/false,
+                      /*treatAsPartialModule*/true))
       hadLoadError = true;
   }
 
diff --git a/lib/Frontend/ParseableInterfaceSupport.cpp b/lib/Frontend/ParseableInterfaceSupport.cpp
index ce440f9..dd023fa0 100644
--- a/lib/Frontend/ParseableInterfaceSupport.cpp
+++ b/lib/Frontend/ParseableInterfaceSupport.cpp
@@ -86,15 +86,19 @@
 static void printImports(raw_ostream &out, ModuleDecl *M) {
   // FIXME: This is very similar to what's in Serializer::writeInputBlock, but
   // it's not obvious what higher-level optimization would be factored out here.
+  ModuleDecl::ImportFilter allImportFilter;
+  allImportFilter |= ModuleDecl::ImportFilterKind::Public;
+  allImportFilter |= ModuleDecl::ImportFilterKind::Private;
+
   SmallVector<ModuleDecl::ImportedModule, 8> allImports;
-  M->getImportedModules(allImports, ModuleDecl::ImportFilter::All);
+  M->getImportedModules(allImports, allImportFilter);
   ModuleDecl::removeDuplicateImports(allImports);
   diagnoseScopedImports(M->getASTContext().Diags, allImports);
 
   // Collect the public imports as a subset so that we can mark them with
   // '@_exported'.
   SmallVector<ModuleDecl::ImportedModule, 8> publicImports;
-  M->getImportedModules(publicImports, ModuleDecl::ImportFilter::Public);
+  M->getImportedModules(publicImports, ModuleDecl::ImportFilterKind::Public);
   llvm::SmallSet<ModuleDecl::ImportedModule, 8,
                  ModuleDecl::OrderImportedModules> publicImportSet;
   publicImportSet.insert(publicImports.begin(), publicImports.end());
diff --git a/lib/FrontendTool/ImportedModules.cpp b/lib/FrontendTool/ImportedModules.cpp
index 4a6b8f7..82e3e7d 100644
--- a/lib/FrontendTool/ImportedModules.cpp
+++ b/lib/FrontendTool/ImportedModules.cpp
@@ -79,9 +79,14 @@
   StringRef implicitHeaderPath = opts.ImplicitObjCHeaderPath;
   if (!implicitHeaderPath.empty()) {
     if (!clangImporter->importBridgingHeader(implicitHeaderPath, mainModule)) {
+      ModuleDecl::ImportFilter importFilter;
+      importFilter |= ModuleDecl::ImportFilterKind::Public;
+      importFilter |= ModuleDecl::ImportFilterKind::Private;
+      importFilter |= ModuleDecl::ImportFilterKind::ImplementationOnly;
+
       SmallVector<ModuleDecl::ImportedModule, 16> imported;
       clangImporter->getImportedHeaderModule()->getImportedModules(
-          imported, ModuleDecl::ImportFilter::All);
+          imported, importFilter);
 
       for (auto IM : imported) {
         if (auto clangModule = IM.second->findUnderlyingClangModule())
diff --git a/lib/IDE/CodeCompletion.cpp b/lib/IDE/CodeCompletion.cpp
index 9ec934a..ef9a5eb 100644
--- a/lib/IDE/CodeCompletion.cpp
+++ b/lib/IDE/CodeCompletion.cpp
@@ -1707,17 +1707,23 @@
   }
 
   void collectImportedModules(llvm::StringSet<> &ImportedModules) {
+    ModuleDecl::ImportFilter ImportFilter;
+    ImportFilter |= ModuleDecl::ImportFilterKind::Public;
+    ImportFilter |= ModuleDecl::ImportFilterKind::Private;
+    ImportFilter |= ModuleDecl::ImportFilterKind::ImplementationOnly;
+
     SmallVector<ModuleDecl::ImportedModule, 16> Imported;
     SmallVector<ModuleDecl::ImportedModule, 16> FurtherImported;
     CurrDeclContext->getParentSourceFile()->getImportedModules(Imported,
-      ModuleDecl::ImportFilter::All);
+                                                               ImportFilter);
     while (!Imported.empty()) {
       ModuleDecl *MD = Imported.back().second;
       Imported.pop_back();
       if (!ImportedModules.insert(MD->getNameStr()).second)
         continue;
       FurtherImported.clear();
-      MD->getImportedModules(FurtherImported, ModuleDecl::ImportFilter::Public);
+      MD->getImportedModules(FurtherImported,
+                             ModuleDecl::ImportFilterKind::Public);
       Imported.append(FurtherImported.begin(), FurtherImported.end());
       for (auto SubMod : FurtherImported) {
         Imported.push_back(SubMod);
@@ -5331,9 +5337,13 @@
       Lookup.getToplevelCompletions(Request.OnlyTypes);
 
       // Add results for all imported modules.
+      ModuleDecl::ImportFilter ImportFilter;
+      ImportFilter |= ModuleDecl::ImportFilterKind::Public;
+      ImportFilter |= ModuleDecl::ImportFilterKind::Private;
+      ImportFilter |= ModuleDecl::ImportFilterKind::ImplementationOnly;
       SmallVector<ModuleDecl::ImportedModule, 4> Imports;
       auto *SF = CurDeclContext->getParentSourceFile();
-      SF->getImportedModules(Imports, ModuleDecl::ImportFilter::All);
+      SF->getImportedModules(Imports, ImportFilter);
 
       for (auto Imported : Imports) {
         ModuleDecl *TheModule = Imported.second;
diff --git a/lib/IDE/ExprContextAnalysis.cpp b/lib/IDE/ExprContextAnalysis.cpp
index ea20f7b..f6c8d88 100644
--- a/lib/IDE/ExprContextAnalysis.cpp
+++ b/lib/IDE/ExprContextAnalysis.cpp
@@ -311,7 +311,7 @@
 };
 
 /// Collect function (or subscript) members with the given \p name on \p baseTy.
-void collectPossibleCalleesByQualifiedLookup(
+static void collectPossibleCalleesByQualifiedLookup(
     DeclContext &DC, Type baseTy, DeclBaseName name,
     SmallVectorImpl<FunctionTypeAndDecl> &candidates) {
 
@@ -358,7 +358,7 @@
 
 /// Collect function (or subscript) members with the given \p name on
 /// \p baseExpr expression.
-void collectPossibleCalleesByQualifiedLookup(
+static void collectPossibleCalleesByQualifiedLookup(
     DeclContext &DC, Expr *baseExpr, DeclBaseName name,
     SmallVectorImpl<FunctionTypeAndDecl> &candidates) {
   ConcreteDeclRef ref = nullptr;
@@ -374,7 +374,7 @@
 }
 
 /// For the given \c callExpr, collect possible callee types and declarations.
-bool collectPossibleCalleesForApply(
+static bool collectPossibleCalleesForApply(
     DeclContext &DC, ApplyExpr *callExpr,
     SmallVectorImpl<FunctionTypeAndDecl> &candidates) {
   auto *fnExpr = callExpr->getFn();
@@ -421,7 +421,7 @@
 
 /// For the given \c subscriptExpr, collect possible callee types and
 /// declarations.
-bool collectPossibleCalleesForSubscript(
+static bool collectPossibleCalleesForSubscript(
     DeclContext &DC, SubscriptExpr *subscriptExpr,
     SmallVectorImpl<FunctionTypeAndDecl> &candidates) {
   if (subscriptExpr->hasDecl()) {
@@ -438,14 +438,11 @@
   return !candidates.empty();
 }
 
-/// Get index of \p CCExpr in \p Args. \p Args is usually a \c TupleExpr,
-/// \c ParenExpr, or a \c ArgumentShuffleExpr.
+/// Get index of \p CCExpr in \p Args. \p Args is usually a \c TupleExpr
+/// or \c ParenExpr.
 /// \returns \c true if success, \c false if \p CCExpr is not a part of \p Args.
-bool getPositionInArgs(DeclContext &DC, Expr *Args, Expr *CCExpr,
-                       unsigned &Position, bool &HasName) {
-  if (auto ASE = dyn_cast<ArgumentShuffleExpr>(Args))
-    Args = ASE->getSubExpr();
-
+static bool getPositionInArgs(DeclContext &DC, Expr *Args, Expr *CCExpr,
+                              unsigned &Position, bool &HasName) {
   if (isa<ParenExpr>(Args)) {
     HasName = false;
     Position = 0;
@@ -468,38 +465,6 @@
   return false;
 }
 
-/// Translate argument index in \p Args to parameter index.
-/// Does nothing unless \p Args is \c ArgumentShuffleExpr.
-bool translateArgIndexToParamIndex(Expr *Args, unsigned &Position,
-                                   bool &HasName) {
-  auto ASE = dyn_cast<ArgumentShuffleExpr>(Args);
-  if (!ASE)
-    return true;
-
-  auto mapping = ASE->getElementMapping();
-  for (unsigned destIdx = 0, e = mapping.size(); destIdx != e; ++destIdx) {
-    auto srcIdx = mapping[destIdx];
-    if (srcIdx == (signed)Position) {
-      Position = destIdx;
-      return true;
-    }
-    if (srcIdx == ArgumentShuffleExpr::Variadic &&
-        llvm::is_contained(ASE->getVariadicArgs(), Position)) {
-      // The arg is a part of variadic args.
-      Position = destIdx;
-      HasName = false;
-      if (auto Args = dyn_cast<TupleExpr>(ASE->getSubExpr())) {
-        // Check if the first variadiac argument has the label.
-        auto firstVarArgIdx = ASE->getVariadicArgs().front();
-        HasName = Args->getElementNameLoc(firstVarArgIdx).isValid();
-      }
-      return true;
-    }
-  }
-
-  return false;
-}
-
 /// Given an expression and its context, the analyzer tries to figure out the
 /// expected type of the expression by analyzing its context.
 class ExprContextAnalyzer {
@@ -546,8 +511,6 @@
     bool HasName;
     if (!getPositionInArgs(*DC, Arg, ParsedExpr, Position, HasName))
       return false;
-    if (!translateArgIndexToParamIndex(Arg, Position, HasName))
-      return false;
 
     // Collect possible types (or labels) at the position.
     {
@@ -588,6 +551,12 @@
       analyzeApplyExpr(Parent);
       break;
     }
+    case ExprKind::Array: {
+      if (auto type = ParsedExpr->getType()) {
+        recordPossibleType(type);
+      }
+      break;
+    }
     case ExprKind::Assign: {
       auto *AE = cast<AssignExpr>(Parent);
 
@@ -744,12 +713,13 @@
         case ExprKind::PrefixUnary:
         case ExprKind::Assign:
         case ExprKind::Subscript:
+        case ExprKind::Array:
           return true;
         case ExprKind::Tuple: {
           auto ParentE = Parent.getAsExpr();
           return !ParentE ||
                  (!isa<CallExpr>(ParentE) && !isa<SubscriptExpr>(ParentE) &&
-                  !isa<BinaryExpr>(ParentE) && !isa<ArgumentShuffleExpr>(ParentE));
+                  !isa<BinaryExpr>(ParentE));
         }
         case ExprKind::Closure: {
           // Note: we cannot use hasSingleExpressionBody, because we explicitly
diff --git a/lib/IDE/Refactoring.cpp b/lib/IDE/Refactoring.cpp
index 8712127..0100acc 100644
--- a/lib/IDE/Refactoring.cpp
+++ b/lib/IDE/Refactoring.cpp
@@ -27,6 +27,7 @@
 #include "swift/Frontend/Frontend.h"
 #include "swift/Index/Index.h"
 #include "swift/Parse/Lexer.h"
+#include "swift/Sema/IDETypeChecking.h"
 #include "swift/Subsystems.h"
 #include "clang/Rewrite/Core/RewriteBuffer.h"
 #include "llvm/ADT/StringSet.h"
@@ -2856,8 +2857,6 @@
   if (!Args)
     return nullptr;
   Expr *LastArg;
-  if (auto *ASE = dyn_cast<ArgumentShuffleExpr>(Args))
-    Args = ASE->getSubExpr();
   if (auto *PE = dyn_cast<ParenExpr>(Args)) {
     LastArg = PE->getSubExpr();
   } else {
@@ -2885,33 +2884,24 @@
   auto *CE = findTrailingClosureTarget(SM, CursorInfo);
   if (!CE)
     return true;
-  Expr *Args = CE->getArg();
-  if (auto *ASE = dyn_cast<ArgumentShuffleExpr>(Args))
-    Args = ASE->getSubExpr();
+  Expr *Arg = CE->getArg();
 
   Expr *ClosureArg = nullptr;
   Expr *PrevArg = nullptr;
-  SourceLoc LPLoc, RPLoc;
 
-  if (auto *PE = dyn_cast<ParenExpr>(Args)) {
-    ClosureArg = PE->getSubExpr();
-    LPLoc = PE->getLParenLoc();
-    RPLoc = PE->getRParenLoc();
-  } else {
-    auto *TE = cast<TupleExpr>(Args);
-    auto NumArgs = TE->getNumElements();
-    if (NumArgs == 0)
-      return true;
-    LPLoc = TE->getLParenLoc();
-    RPLoc = TE->getRParenLoc();
-    ClosureArg = TE->getElement(NumArgs - 1);
-    if (NumArgs > 1)
-      PrevArg = TE->getElement(NumArgs - 2);
-  }
+  OriginalArgumentList ArgList = getOriginalArgumentList(Arg);
+
+  auto NumArgs = ArgList.args.size();
+  if (NumArgs == 0)
+    return true;
+  ClosureArg = ArgList.args[NumArgs - 1];
+  if (NumArgs > 1)
+    PrevArg = ArgList.args[NumArgs - 2];
+
   if (auto *ICE = dyn_cast<ImplicitConversionExpr>(ClosureArg))
     ClosureArg = ICE->getSyntacticSubExpr();
 
-  if (LPLoc.isInvalid() || RPLoc.isInvalid())
+  if (ArgList.lParenLoc.isInvalid() || ArgList.rParenLoc.isInvalid())
     return true;
 
   // Replace:
@@ -2925,14 +2915,14 @@
     EditConsumer.accept(SM, PreRange, ") ");
   } else {
     CharSourceRange PreRange(
-        SM, LPLoc, ClosureArg->getStartLoc());
+        SM, ArgList.lParenLoc, ClosureArg->getStartLoc());
     EditConsumer.accept(SM, PreRange, " ");
   }
   // Remove original closing paren.
   CharSourceRange PostRange(
       SM,
       Lexer::getLocForEndOfToken(SM, ClosureArg->getEndLoc()),
-      Lexer::getLocForEndOfToken(SM, RPLoc));
+      Lexer::getLocForEndOfToken(SM, ArgList.rParenLoc));
   EditConsumer.remove(SM, PostRange);
   return false;
 }
diff --git a/lib/IRGen/GenDecl.cpp b/lib/IRGen/GenDecl.cpp
index 7cdb016..557a31f 100644
--- a/lib/IRGen/GenDecl.cpp
+++ b/lib/IRGen/GenDecl.cpp
@@ -1640,7 +1640,7 @@
 llvm::GlobalVariable *swift::irgen::createVariable(
     IRGenModule &IGM, LinkInfo &linkInfo, llvm::Type *storageType,
     Alignment alignment, DebugTypeInfo DbgTy, Optional<SILLocation> DebugLoc,
-    StringRef DebugName, bool inFixedBuffer, bool indirectForDebugInfo) {
+    StringRef DebugName, bool inFixedBuffer) {
   auto name = linkInfo.getName();
   llvm::GlobalValue *existingValue = IGM.Module.getNamedGlobal(name);
   if (existingValue) {
@@ -1674,7 +1674,7 @@
   if (IGM.DebugInfo && !DbgTy.isNull() && linkInfo.isForDefinition())
     IGM.DebugInfo->emitGlobalVariableDeclaration(
         var, DebugName.empty() ? name : DebugName, name, DbgTy,
-        var->hasInternalLinkage(), indirectForDebugInfo, DebugLoc);
+        var->hasInternalLinkage(), inFixedBuffer, DebugLoc);
 
   return var;
 }
@@ -1812,13 +1812,6 @@
   Size fixedSize;
   Alignment fixedAlignment;
   bool inFixedBuffer = false;
-  bool indirectForDebugInfo = false;
-
-  // FIXME: Remove this once LLDB has proper support for resilience.
-  bool isREPLVar = false;
-  if (auto *decl = var->getDecl())
-    if (decl->isREPLVar())
-      isREPLVar = true;
 
   if (var->isInitializedObject()) {
     assert(ti.isFixedSize(expansion));
@@ -1840,7 +1833,7 @@
     fixedAlignment = Layout->getAlignment();
     castStorageToType = cast<FixedTypeInfo>(ti).getStorageType();
     assert(fixedAlignment >= TargetInfo.HeapObjectAlignment);
-  } else if (isREPLVar || ti.isFixedSize(expansion)) {
+  } else if (ti.isFixedSize(expansion)) {
     // Allocate static storage.
     auto &fixedTI = cast<FixedTypeInfo>(ti);
     storageType = fixedTI.getStorageType();
@@ -1853,28 +1846,6 @@
     storageType = getFixedBufferTy();
     fixedSize = Size(DataLayout.getTypeAllocSize(storageType));
     fixedAlignment = Alignment(DataLayout.getABITypeAlignment(storageType));
-
-    // DebugInfo is not resilient for now, so disable resilience to figure out
-    // if lldb needs to dereference the global variable or not.
-    //
-    // FIXME: Once lldb can make use of remote mirrors to calculate layouts
-    // at runtime, this should be removed.
-    {
-      LoweringModeScope Scope(*this, TypeConverter::Mode::CompletelyFragile);
-
-      SILType loweredTy = var->getLoweredType();
-      auto &nonResilientTI = cast<FixedTypeInfo>(getTypeInfo(loweredTy));
-      auto packing = nonResilientTI.getFixedPacking(*this);
-      switch (packing) {
-      case FixedPacking::OffsetZero:
-        break;
-      case FixedPacking::Allocate:
-        indirectForDebugInfo = true;
-        break;
-      default:
-        llvm_unreachable("Bad packing");
-      }
-    }
   }
 
   // Check whether we've created the global variable already.
@@ -1916,8 +1887,7 @@
       auto DbgTy = DebugTypeInfo::getGlobal(var, storageTypeWithContainer,
                                             fixedSize, fixedAlignment);
       gvar = createVariable(*this, link, storageTypeWithContainer,
-                            fixedAlignment, DbgTy, loc, name, inFixedBuffer,
-                            indirectForDebugInfo);
+                            fixedAlignment, DbgTy, loc, name, inFixedBuffer);
     }
     /// Add a zero initializer.
     if (forDefinition)
diff --git a/lib/IRGen/GenDecl.h b/lib/IRGen/GenDecl.h
index e8e5411..22ac112 100644
--- a/lib/IRGen/GenDecl.h
+++ b/lib/IRGen/GenDecl.h
@@ -50,8 +50,7 @@
   createVariable(IRGenModule &IGM, LinkInfo &linkInfo, llvm::Type *objectType,
                  Alignment alignment, DebugTypeInfo DebugType = DebugTypeInfo(),
                  Optional<SILLocation> DebugLoc = None,
-                 StringRef DebugName = StringRef(), bool heapAllocated = false,
-                 bool indirectForDebugInfo = false);
+                 StringRef DebugName = StringRef(), bool heapAllocated = false);
 
   void disableAddressSanitizer(IRGenModule &IGM, llvm::GlobalVariable *var);
 }
diff --git a/lib/IRGen/GenEnum.cpp b/lib/IRGen/GenEnum.cpp
index c91490e..6b38536 100644
--- a/lib/IRGen/GenEnum.cpp
+++ b/lib/IRGen/GenEnum.cpp
@@ -1879,11 +1879,15 @@
       // more no-payload case than extra inhabitants in the payload. This could
       // be slightly generalized to cases where there's multiple tag bits and
       // exactly one no-payload case in the highest used tag value.
+      unsigned extraInhabitantCount = getFixedExtraInhabitantCount(IGF.IGM);
       if (!tagBits ||
-        ElementsWithNoPayload.size() != getFixedExtraInhabitantCount(IGF.IGM)+1)
-          payloadResult = payload.emitCompare(IGF,
-                                        ti.getFixedExtraInhabitantMask(IGF.IGM),
-                                        payloadTag);
+          ElementsWithNoPayload.size() != extraInhabitantCount + 1) {
+        payloadResult = payload.emitCompare(
+            IGF,
+            extraInhabitantCount == 0 ? APInt::getAllOnesValue(PayloadBitCount)
+                                      : ti.getFixedExtraInhabitantMask(IGF.IGM),
+            payloadTag);
+      }
 
       // If any tag bits are present, they must match.
       llvm::Value *tagResult = nullptr;
diff --git a/lib/IRGen/GenProto.cpp b/lib/IRGen/GenProto.cpp
index 88dd9d4..babeac6 100644
--- a/lib/IRGen/GenProto.cpp
+++ b/lib/IRGen/GenProto.cpp
@@ -619,6 +619,12 @@
       llvm::Value *metadata = getParameter(paramIndex);
       IGF.bindLocalTypeDataFromTypeMetadata(paramType, IsInexact, metadata,
                                             MetadataState::Complete);
+    } else if (metatype->getRepresentation() == MetatypeRepresentation::ObjC) {
+      paramType = metatype.getInstanceType();
+      llvm::Value *objcMetatype = getParameter(paramIndex);
+      auto *metadata = emitObjCMetadataRefForMetadata(IGF, objcMetatype);
+      IGF.bindLocalTypeDataFromTypeMetadata(paramType, IsInexact, metadata,
+                                            MetadataState::Complete);
     }
     return;
   }
diff --git a/lib/IRGen/IRGenDebugInfo.cpp b/lib/IRGen/IRGenDebugInfo.cpp
index e5b9e66..f5c745a 100644
--- a/lib/IRGen/IRGenDebugInfo.cpp
+++ b/lib/IRGen/IRGenDebugInfo.cpp
@@ -1066,6 +1066,20 @@
         llvm::dwarf::DW_LANG_Swift, nullptr, MangledName);
   }
 
+  llvm::DIType *createFixedValueBufferStruct(llvm::DIType *PointeeTy) {
+    unsigned Line = 0;
+    unsigned PtrSize = CI.getTargetInfo().getPointerWidth(0);
+    llvm::DINode::DIFlags Flags = llvm::DINode::FlagArtificial;
+    llvm::DIFile *File = MainFile;
+    llvm::DIScope *Scope = TheCU;
+    llvm::Metadata *Elements[] = {DBuilder.createMemberType(
+        Scope, "contents", File, 0, PtrSize, 0, 0, Flags, PointeeTy)};
+    return DBuilder.createStructType(
+        Scope, "$swift.fixedbuffer", File, Line, 3 * PtrSize, 0, Flags,
+        /* DerivedFrom */ nullptr, DBuilder.getOrCreateArray(Elements),
+        llvm::dwarf::DW_LANG_Swift, nullptr);
+  }
+
   llvm::DIType *createFunctionPointer(DebugTypeInfo DbgTy, llvm::DIScope *Scope,
                                       unsigned SizeInBits, unsigned AlignInBits,
                                       llvm::DINode::DIFlags Flags,
@@ -1727,9 +1741,12 @@
 
   // Get the list of imported modules (which may actually be different
   // from all ImportDecls).
+  ModuleDecl::ImportFilter ImportFilter;
+  ImportFilter |= ModuleDecl::ImportFilterKind::Public;
+  ImportFilter |= ModuleDecl::ImportFilterKind::Private;
+  ImportFilter |= ModuleDecl::ImportFilterKind::ImplementationOnly;
   SmallVector<ModuleDecl::ImportedModule, 8> ModuleWideImports;
-  IGM.getSwiftModule()->getImportedModules(ModuleWideImports,
-                                           ModuleDecl::ImportFilter::All);
+  IGM.getSwiftModule()->getImportedModules(ModuleWideImports, ImportFilter);
   for (auto M : ModuleWideImports)
     if (!ImportedModules.count(M.second))
       DBuilder.createImportedModule(MainFile, getOrCreateModule(M), MainFile,
@@ -2227,7 +2244,7 @@
 
 void IRGenDebugInfoImpl::emitGlobalVariableDeclaration(
     llvm::GlobalVariable *Var, StringRef Name, StringRef LinkageName,
-    DebugTypeInfo DbgTy, bool IsLocalToUnit, bool Indirect,
+    DebugTypeInfo DbgTy, bool IsLocalToUnit, bool InFixedBuffer,
     Optional<SILLocation> Loc) {
   if (Opts.DebugInfoLevel <= IRGenDebugInfoLevel::LineTables)
     return;
@@ -2240,6 +2257,9 @@
     // would confuse both the user and LLDB.
     return;
 
+  if (InFixedBuffer)
+    Ty = createFixedValueBufferStruct(Ty);
+
   auto L = getStartLocation(Loc);
   auto File = getOrCreateFile(L.Filename);
 
@@ -2247,9 +2267,6 @@
   llvm::DIExpression *Expr = nullptr;
   if (!Var)
     Expr = DBuilder.createConstantValueExpression(0);
-  else if (Indirect)
-    Expr =
-        DBuilder.createExpression(ArrayRef<uint64_t>(llvm::dwarf::DW_OP_deref));
   auto *GV = DBuilder.createGlobalVariableExpression(
       MainModule, Name, LinkageName, File, L.Line, Ty, IsLocalToUnit, Expr);
   if (Var)
@@ -2388,10 +2405,10 @@
 
 void IRGenDebugInfo::emitGlobalVariableDeclaration(
     llvm::GlobalVariable *Storage, StringRef Name, StringRef LinkageName,
-    DebugTypeInfo DebugType, bool IsLocalToUnit, bool Indirect,
+    DebugTypeInfo DebugType, bool IsLocalToUnit, bool InFixedBuffer,
     Optional<SILLocation> Loc) {
   static_cast<IRGenDebugInfoImpl *>(this)->emitGlobalVariableDeclaration(
-      Storage, Name, LinkageName, DebugType, IsLocalToUnit, Indirect, Loc);
+      Storage, Name, LinkageName, DebugType, IsLocalToUnit, InFixedBuffer, Loc);
 }
 
 void IRGenDebugInfo::emitTypeMetadata(IRGenFunction &IGF, llvm::Value *Metadata,
diff --git a/lib/IRGen/IRGenSIL.cpp b/lib/IRGen/IRGenSIL.cpp
index 4a8b216..b4b735b 100644
--- a/lib/IRGen/IRGenSIL.cpp
+++ b/lib/IRGen/IRGenSIL.cpp
@@ -1884,15 +1884,9 @@
 
   auto expansion = IGM.getResilienceExpansionForLayout(var);
 
-  // FIXME: Remove this once LLDB has proper support for resilience.
-  bool isREPLVar = false;
-  if (auto *decl = var->getDecl())
-    if (decl->isREPLVar())
-      isREPLVar = true;
-
   // If the global is fixed-size in all resilience domains that can see it,
   // we allocated storage for it statically, and there's nothing to do.
-  if (isREPLVar || ti.isFixedSize(expansion))
+  if (ti.isFixedSize(expansion))
     return;
 
   // Otherwise, the static storage for the global consists of a fixed-size
@@ -1920,15 +1914,9 @@
   Address addr = IGM.getAddrOfSILGlobalVariable(var, ti,
                                                 NotForDefinition);
 
-  // FIXME: Remove this once LLDB has proper support for resilience.
-  bool isREPLVar = false;
-  if (auto *decl = var->getDecl())
-    if (decl->isREPLVar())
-      isREPLVar = true;
-
   // If the global is fixed-size in all resilience domains that can see it,
   // we allocated storage for it statically, and there's nothing to do.
-  if (isREPLVar || ti.isFixedSize(expansion)) {
+  if (ti.isFixedSize(expansion)) {
     setLoweredAddress(i, addr);
     return;
   }
diff --git a/lib/Immediate/REPL.cpp b/lib/Immediate/REPL.cpp
index e424e9b..f71baeb 100644
--- a/lib/Immediate/REPL.cpp
+++ b/lib/Immediate/REPL.cpp
@@ -176,7 +176,7 @@
 
   SmallVector<ModuleDecl::ImportedModule, 8> Imports;
   MostRecentModule->getImportedModules(Imports,
-                                       ModuleDecl::ImportFilter::Private);
+                                       ModuleDecl::ImportFilterKind::Private);
   if (!Imports.empty()) {
     SmallVector<SourceFile::ImportedModuleDesc, 8> ImportsWithOptions;
     for (auto Import : Imports) {
diff --git a/lib/Index/Index.cpp b/lib/Index/Index.cpp
index c538059..6b7fbd2 100644
--- a/lib/Index/Index.cpp
+++ b/lib/Index/Index.cpp
@@ -120,11 +120,15 @@
 
   void
   getImportedModules(SmallVectorImpl<ModuleDecl::ImportedModule> &Modules) const {
+    ModuleDecl::ImportFilter ImportFilter;
+    ImportFilter |= ModuleDecl::ImportFilterKind::Public;
+    ImportFilter |= ModuleDecl::ImportFilterKind::Private;
+    ImportFilter |= ModuleDecl::ImportFilterKind::ImplementationOnly;
+
     if (auto *SF = SFOrMod.dyn_cast<SourceFile *>()) {
-      SF->getImportedModules(Modules, ModuleDecl::ImportFilter::All);
+      SF->getImportedModules(Modules, ImportFilter);
     } else {
-      SFOrMod.get<ModuleDecl *>()->getImportedModules(Modules,
-                                                  ModuleDecl::ImportFilter::All);
+      SFOrMod.get<ModuleDecl *>()->getImportedModules(Modules, ImportFilter);
     }
   }
 };
@@ -1536,8 +1540,11 @@
     return;
   }
 
+  ModuleDecl::ImportFilter ImportFilter;
+  ImportFilter |= ModuleDecl::ImportFilterKind::Public;
+  ImportFilter |= ModuleDecl::ImportFilterKind::Private;
   SmallVector<ModuleDecl::ImportedModule, 8> Imports;
-  TopMod.getImportedModules(Imports, ModuleDecl::ImportFilter::All);
+  TopMod.getImportedModules(Imports);
 
   for (auto Import : Imports) {
     collectRecursiveModuleImports(*Import.second, Visited);
diff --git a/lib/Index/IndexRecord.cpp b/lib/Index/IndexRecord.cpp
index fe27519..b2ec3ab 100644
--- a/lib/Index/IndexRecord.cpp
+++ b/lib/Index/IndexRecord.cpp
@@ -562,8 +562,11 @@
     unitWriter.addRecordFile(recordFile, FE, isSystemModule, mod);
   }
 
+  ModuleDecl::ImportFilter importFilter;
+  importFilter |= ModuleDecl::ImportFilterKind::Public;
+  importFilter |= ModuleDecl::ImportFilterKind::Private;
   SmallVector<ModuleDecl::ImportedModule, 8> imports;
-  module->getImportedModules(imports, ModuleDecl::ImportFilter::All);
+  module->getImportedModules(imports, importFilter);
   StringScratchSpace moduleNameScratch;
   addModuleDependencies(imports, indexStorePath, indexSystemModules,
                         targetTriple, clangCI, diags, unitWriter, moduleNameScratch);
@@ -597,8 +600,12 @@
     targetTriple, sysrootPath, getModuleInfoFromOpaqueModule);
 
   // Module dependencies.
+  ModuleDecl::ImportFilter importFilter;
+  importFilter |= ModuleDecl::ImportFilterKind::Public;
+  importFilter |= ModuleDecl::ImportFilterKind::Private;
+  importFilter |= ModuleDecl::ImportFilterKind::ImplementationOnly;
   SmallVector<ModuleDecl::ImportedModule, 8> imports;
-  primarySourceFile->getImportedModules(imports, ModuleDecl::ImportFilter::All);
+  primarySourceFile->getImportedModules(imports, importFilter);
   StringScratchSpace moduleNameScratch;
   addModuleDependencies(imports, indexStorePath, indexSystemModules,
                         targetTriple, clangCI, diags, unitWriter, moduleNameScratch);
diff --git a/lib/Index/IndexSymbol.cpp b/lib/Index/IndexSymbol.cpp
index bef0536..c10c28c 100644
--- a/lib/Index/IndexSymbol.cpp
+++ b/lib/Index/IndexSymbol.cpp
@@ -28,12 +28,13 @@
 static bool isUnitTestCase(const ClassDecl *D) {
   if (!D)
     return false;
-  while (auto *SuperD = D->getSuperclassDecl()) {
-    if (SuperD->getNameStr() == "XCTestCase")
-      return true;
-    D = SuperD;
-  }
-  return false;
+
+  return D->walkSuperclasses([D](ClassDecl *SuperD) {
+    if (SuperD != D && // Do not treate XCTestCase itself as a test.
+        SuperD->getNameStr() == "XCTestCase")
+      return TypeWalker::Action::Stop; // Found test; stop and return true.
+    return TypeWalker::Action::Continue;
+  });
 }
 
 static bool isUnitTest(const ValueDecl *D) {
diff --git a/lib/Option/SanitizerOptions.cpp b/lib/Option/SanitizerOptions.cpp
index 7e59996..781427f 100644
--- a/lib/Option/SanitizerOptions.cpp
+++ b/lib/Option/SanitizerOptions.cpp
@@ -31,30 +31,27 @@
 
 static StringRef toStringRef(const SanitizerKind kind) {
   switch (kind) {
-  case SanitizerKind::Address:
-    return "address";
-  case SanitizerKind::Thread:
-    return "thread";
-  case SanitizerKind::Fuzzer:
-    return "fuzzer";
-  case SanitizerKind::Undefined:
-    return "undefined";
+    #define SANITIZER(_, kind, name, file) \
+        case SanitizerKind::kind: return #name;
+    #include "swift/Basic/Sanitizers.def"
   }
-  llvm_unreachable("Unsupported sanitizer");
+  llvm_unreachable("Unknown sanitizer");
 }
 
-static const char* toFileName(const SanitizerKind kind) {
+static StringRef toFileName(const SanitizerKind kind) {
   switch (kind) {
-  case SanitizerKind::Address:
-    return "asan";
-  case SanitizerKind::Thread:
-    return "tsan";
-  case SanitizerKind::Fuzzer:
-    return "fuzzer";
-  case SanitizerKind::Undefined:
-    return "ubsan";
+    #define SANITIZER(_, kind, name, file) \
+        case SanitizerKind::kind: return #file;
+    #include "swift/Basic/Sanitizers.def"
   }
-  llvm_unreachable("Unsupported sanitizer");
+  llvm_unreachable("Unknown sanitizer");
+}
+
+static Optional<SanitizerKind> parse(const char* arg) {
+  return llvm::StringSwitch<Optional<SanitizerKind>>(arg)
+      #define SANITIZER(_, kind, name, file) .Case(#name, SanitizerKind::kind)
+      #include "swift/Basic/Sanitizers.def"
+      .Default(None);
 }
 
 llvm::SanitizerCoverageOptions swift::parseSanitizerCoverageArgValue(
@@ -133,35 +130,34 @@
   OptionSet<SanitizerKind> sanitizerSet;
 
   // Find the sanitizer kind.
-  for (int i = 0, n = A->getNumValues(); i != n; ++i) {
-    auto kind = llvm::StringSwitch<Optional<SanitizerKind>>(A->getValue(i))
-        .Case("address", SanitizerKind::Address)
-        .Case("thread", SanitizerKind::Thread)
-        .Case("fuzzer", SanitizerKind::Fuzzer)
-        .Case("undefined", SanitizerKind::Undefined)
-        .Default(None);
-    bool isShared = kind && *kind != SanitizerKind::Fuzzer;
-    if (!kind) {
+  for (const char *arg : A->getValues()) {
+    Optional<SanitizerKind> optKind = parse(arg);
+
+    // Unrecognized sanitizer option
+    if (!optKind.hasValue()) {
       Diags.diagnose(SourceLoc(), diag::error_unsupported_option_argument,
-          A->getOption().getPrefixedName(), A->getValue(i));
+          A->getOption().getPrefixedName(), arg);
+      continue;
+    }
+    SanitizerKind kind = optKind.getValue();
+
+    // Support is determined by existance of the sanitizer library.
+    auto fileName = toFileName(kind);
+    bool isShared = (kind != SanitizerKind::Fuzzer);
+    bool sanitizerSupported = sanitizerRuntimeLibExists(fileName, isShared);
+
+    // TSan is explicitly not supported for 32 bits.
+    if (kind == SanitizerKind::Thread && !Triple.isArch64Bit())
+      sanitizerSupported = false;
+
+    if (!sanitizerSupported) {
+      SmallString<128> b;
+      Diags.diagnose(SourceLoc(), diag::error_unsupported_opt_for_target,
+                      (A->getOption().getPrefixedName() + toStringRef(kind))
+                          .toStringRef(b),
+                      Triple.getTriple());
     } else {
-      // Support is determined by existance of the sanitizer library.
-      bool sanitizerSupported =
-          sanitizerRuntimeLibExists(toFileName(*kind), isShared);
-
-      // TSan is explicitly not supported for 32 bits.
-      if (*kind == SanitizerKind::Thread && !Triple.isArch64Bit())
-        sanitizerSupported = false;
-
-      if (!sanitizerSupported) {
-        SmallString<128> b;
-        Diags.diagnose(SourceLoc(), diag::error_unsupported_opt_for_target,
-                       (A->getOption().getPrefixedName() + toStringRef(*kind))
-                           .toStringRef(b),
-                       Triple.getTriple());
-      } else {
-        sanitizerSet |= *kind;
-      }
+      sanitizerSet |= kind;
     }
   }
 
@@ -191,10 +187,12 @@
 
 std::string swift::getSanitizerList(const OptionSet<SanitizerKind> &Set) {
   std::string list;
-  if (Set & SanitizerKind::Address) list += "address,";
-  if (Set & SanitizerKind::Thread) list += "thread,";
-  if (Set & SanitizerKind::Fuzzer) list += "fuzzer,";
-  if (Set & SanitizerKind::Undefined) list += "undefined,";
-  if (!list.empty()) list.pop_back(); // Remove last comma
+  #define SANITIZER(_, kind, name, file) \
+      if (Set & SanitizerKind::kind) list += #name ",";
+  #include "swift/Basic/Sanitizers.def"
+
+  if (!list.empty())
+    list.pop_back(); // Remove last comma
+
   return list;
 }
diff --git a/lib/Parse/ParseDecl.cpp b/lib/Parse/ParseDecl.cpp
index 7ac1dc4..6a3eb23 100644
--- a/lib/Parse/ParseDecl.cpp
+++ b/lib/Parse/ParseDecl.cpp
@@ -929,6 +929,7 @@
   case DAK_RestatedObjCConformance:
   case DAK_SynthesizedProtocol:
   case DAK_ClangImporterSynthesizedType:
+  case DAK_Custom:
     llvm_unreachable("virtual attributes should not be parsed "
                      "by attribute parsing code");
   case DAK_SetterAccess:
@@ -1852,8 +1853,66 @@
 
   if (TypeAttributes::getAttrKindFromString(Tok.getText()) != TAK_Count)
     diagnose(Tok, diag::type_attribute_applied_to_decl);
-  else
-    diagnose(Tok, diag::unknown_attribute, Tok.getText());
+  else if (Tok.isContextualKeyword("unknown")) {
+    diagnose(Tok, diag::unknown_attribute, "unknown");
+  } else {
+    // Parse a custom attribute.
+    auto type = parseType(diag::expected_type);
+    if (type.hasCodeCompletion() || type.isNull()) {
+      if (Tok.is(tok::l_paren))
+        skipSingle();
+
+      return true;
+    }
+
+    // Parse the optional arguments.
+    SourceLoc lParenLoc, rParenLoc;
+    SmallVector<Expr *, 2> args;
+    SmallVector<Identifier, 2> argLabels;
+    SmallVector<SourceLoc, 2> argLabelLocs;
+    Expr *trailingClosure = nullptr;
+    bool hasInitializer = false;
+
+    // If we're not in a local context, we'll need a context to parse
+    // initializers into (should we have one).  This happens for properties
+    // and global variables in libraries.
+    PatternBindingInitializer *initContext = nullptr;
+
+    if (Tok.isFollowingLParen()) {
+      SyntaxParsingContext InitCtx(SyntaxContext,
+                                   SyntaxKind::InitializerClause);
+
+      // If we have no local context to parse the initial value into, create one
+      // for the PBD we'll eventually create.  This allows us to have reasonable
+      // DeclContexts for any closures that may live inside of initializers.
+      Optional<ParseFunctionBody> initParser;
+      if (!CurDeclContext->isLocalContext()) {
+        initContext = new (Context) PatternBindingInitializer(CurDeclContext);
+        initParser.emplace(*this, initContext);
+      }
+
+      ParserStatus status = parseExprList(tok::l_paren, tok::r_paren,
+                                          /*isPostfix=*/false,
+                                          /*isExprBasic=*/true,
+                                          lParenLoc, args, argLabels,
+                                          argLabelLocs,
+                                          rParenLoc,
+                                          trailingClosure,
+                                          SyntaxKind::FunctionCallArgumentList);
+      if (status.hasCodeCompletion())
+        return true;
+
+      assert(!trailingClosure && "Cannot parse a trailing closure here");
+      hasInitializer = true;
+    }
+
+    // Form the attribute.
+    auto attr = CustomAttr::create(Context, AtLoc, type.get(), hasInitializer,
+                                   initContext, lParenLoc, args, argLabels,
+                                   argLabelLocs, rParenLoc);
+    Attributes.add(attr);
+    return false;
+  }
 
   // Recover by eating @foo(...) when foo is not known.
   consumeToken();
diff --git a/lib/RemoteAST/RemoteAST.cpp b/lib/RemoteAST/RemoteAST.cpp
index cc81231..340ae5b 100644
--- a/lib/RemoteAST/RemoteAST.cpp
+++ b/lib/RemoteAST/RemoteAST.cpp
@@ -327,15 +327,21 @@
       return fail<uint64_t>(Failure::TypeHasNoSuchMember, memberName);
 
     // Fast path: element 0 is always at offset 0.
-    if (targetIndex == 0) return uint64_t(0);
+    if (targetIndex == 0)
+      return uint64_t(0);
 
     // Create an IRGen instance.
     auto irgen = getIRGen();
-    if (!irgen) return Result<uint64_t>::emplaceFailure(Failure::Unknown);
+    if (!irgen)
+      return Result<uint64_t>::emplaceFailure(Failure::Unknown);
     auto &IGM = irgen->IGM;
-
     SILType loweredTy = IGM.getLoweredType(type);
 
+    // Only the runtime metadata knows the offsets of resilient members.
+    auto &typeInfo = IGM.getTypeInfo(loweredTy);
+    if (!isa<irgen::FixedTypeInfo>(&typeInfo))
+      return Result<uint64_t>::emplaceFailure(Failure::NotFixedLayout);
+
     // If the type has a statically fixed offset, return that.
     if (auto offset =
           irgen::getFixedTupleElementOffset(IGM, loweredTy, targetIndex))
diff --git a/lib/SILGen/ASTVisitor.h b/lib/SILGen/ASTVisitor.h
index 710f464..e98f9b7 100644
--- a/lib/SILGen/ASTVisitor.h
+++ b/lib/SILGen/ASTVisitor.h
@@ -56,8 +56,18 @@
     llvm_unreachable("expression kind should not survive to SILGen");
   }
 
+  ExprRetTy visitDefaultArgumentExpr(DefaultArgumentExpr *E, Args...AA) {
+    llvm_unreachable("DefaultArgumentExpr should not appear in this position");
+  }
+
+  ExprRetTy visitCallerDefaultArgumentExpr(CallerDefaultArgumentExpr *E, Args... AA) {
+    return static_cast<ImplClass*>(this)->visit(E->getSubExpr(),
+                                                std::forward<Args>(AA)...);
+  }
+
   ExprRetTy visitVarargExpansionExpr(VarargExpansionExpr *E, Args... AA) {
-    llvm_unreachable("vararg expansion should not appear in this position");
+    return static_cast<ImplClass*>(this)->visit(E->getSubExpr(),
+                                                std::forward<Args>(AA)...);
   }
 
   ExprRetTy visitIdentityExpr(IdentityExpr *E, Args...AA) {
diff --git a/lib/SILGen/ArgumentSource.cpp b/lib/SILGen/ArgumentSource.cpp
index e221bc5..8969b34 100644
--- a/lib/SILGen/ArgumentSource.cpp
+++ b/lib/SILGen/ArgumentSource.cpp
@@ -27,19 +27,6 @@
   return Storage.get<RValueStorage>(StoredKind).Value;
 }
 
-bool ArgumentSource::isShuffle() const {
-  switch (StoredKind) {
-  case Kind::Invalid:
-    llvm_unreachable("argument source is invalid");
-  case Kind::RValue:
-  case Kind::LValue:
-    return false;
-  case Kind::Expr:
-    return isa<ArgumentShuffleExpr>(asKnownExpr());
-  }
-  llvm_unreachable("bad kind");
-}
-
 RValue ArgumentSource::getAsRValue(SILGenFunction &SGF, SGFContext C) && {
   switch (StoredKind) {
   case Kind::Invalid:
@@ -261,9 +248,18 @@
   llvm_unreachable("bad kind");
 }
 
-void PreparedArguments::emplaceEmptyArgumentList(SILGenFunction &SGF) {
-  emplace({}, /*scalar*/ false);
-  assert(isValid());
+PreparedArguments::PreparedArguments(
+    ArrayRef<AnyFunctionType::Param> params,
+    Expr *arg) : PreparedArguments(params) {
+  if (auto *PE = dyn_cast<ParenExpr>(arg))
+    addArbitrary(PE->getSubExpr());
+  else if (auto *TE = dyn_cast<TupleExpr>(arg)) {
+    for (auto *elt : TE->getElements())
+      addArbitrary(elt);
+  } else {
+    // FIXME: All ApplyExprs should have a ParenExpr or TupleExpr as their argument
+    addArbitrary(arg);
+  }
 }
 
 PreparedArguments
@@ -271,7 +267,7 @@
   if (isNull()) return PreparedArguments();
 
   assert(isValid());
-  PreparedArguments result(getParams(), isScalar());
+  PreparedArguments result(getParams());
   for (auto &elt : Arguments) {
     assert(elt.isRValue());
     result.add(elt.getKnownRValueLocation(),
@@ -319,7 +315,7 @@
     return PreparedArguments();
 
   assert(isValid());
-  PreparedArguments result(getParams(), isScalar());
+  PreparedArguments result(getParams());
   for (auto &arg : Arguments) {
     result.Arguments.push_back(arg.copyForDiagnostics());
   }
diff --git a/lib/SILGen/ArgumentSource.h b/lib/SILGen/ArgumentSource.h
index 4f49a4a..f9e7399 100644
--- a/lib/SILGen/ArgumentSource.h
+++ b/lib/SILGen/ArgumentSource.h
@@ -172,6 +172,25 @@
   bool isRValue() const & { return StoredKind == Kind::RValue; }
   bool isLValue() const & { return StoredKind == Kind::LValue; }
 
+  bool isDefaultArg() const {
+    switch (StoredKind) {
+    case Kind::Invalid:
+      llvm_unreachable("argument source is invalid");
+    case Kind::RValue:
+    case Kind::LValue:
+      return false;
+    case Kind::Expr:
+      return isa<DefaultArgumentExpr>(asKnownExpr());
+    }
+    llvm_unreachable("bad kind");
+  }
+
+  /// Return the default argument owner and parameter index, consuming
+  /// the argument source. Will assert if this is not a default argument.
+  DefaultArgumentExpr *asKnownDefaultArg() && {
+    return cast<DefaultArgumentExpr>(std::move(*this).asKnownExpr());
+  }
+
   /// Given that this source is storing an RValue, extract and clear
   /// that value.
   RValue &&asKnownRValue(SILGenFunction &SGF) && {
@@ -240,9 +259,6 @@
                            AbstractionPattern origFormalType,
                            SILType expectedType = SILType()) &&;
 
-  /// Whether this argument source is an ArgumentShuffleExpr.
-  bool isShuffle() const;
-
   bool isObviouslyEqual(const ArgumentSource &other) const;
 
   ArgumentSource copyForDiagnostics() const;
@@ -264,25 +280,26 @@
 class PreparedArguments {
   SmallVector<AnyFunctionType::Param, 8> Params;
   std::vector<ArgumentSource> Arguments;
-  unsigned IsScalar : 1;
   unsigned IsNull : 1;
 public:
-  PreparedArguments() : IsScalar(false), IsNull(true) {}
-  PreparedArguments(ArrayRef<AnyFunctionType::Param> params, bool isScalar)
+  PreparedArguments() : IsNull(true) {}
+  explicit PreparedArguments(ArrayRef<AnyFunctionType::Param> params)
       : IsNull(true) {
-    emplace(params, isScalar);
+    emplace(params);
   }
 
+  // Decompse an argument list expression.
+  PreparedArguments(ArrayRef<AnyFunctionType::Param> params, Expr *arg);
+
   // Move-only.
   PreparedArguments(const PreparedArguments &) = delete;
   PreparedArguments &operator=(const PreparedArguments &) = delete;
 
   PreparedArguments(PreparedArguments &&other)
     : Params(std::move(other.Params)), Arguments(std::move(other.Arguments)),
-      IsScalar(other.IsScalar), IsNull(other.IsNull) {}
+      IsNull(other.IsNull) {}
   PreparedArguments &operator=(PreparedArguments &&other) {
     Params = std::move(other.Params);
-    IsScalar = other.IsScalar;
     Arguments = std::move(other.Arguments);
     IsNull = other.IsNull;
     other.IsNull = true;
@@ -297,8 +314,6 @@
   /// Returns true if this is a non-null and completed argument list.
   bool isValid() const {
     assert(!isNull());
-    if (IsScalar)
-      return Arguments.size() == 1;
     return Arguments.size() == Params.size();
   }
 
@@ -308,28 +323,18 @@
     return Params;
   }
 
-  /// Is this a single-argument list?  Note that the argument might be a tuple.
-  bool isScalar() const {
-    assert(!isNull());
-    return IsScalar;
-  }
-
   MutableArrayRef<ArgumentSource> getSources() && {
     assert(isValid());
     return Arguments;
   }
 
   /// Emplace a (probably incomplete) argument list.
-  void emplace(ArrayRef<AnyFunctionType::Param> params, bool isScalar) {
+  void emplace(ArrayRef<AnyFunctionType::Param> params) {
     assert(isNull());
     Params.append(params.begin(), params.end());
-    IsScalar = isScalar;
     IsNull = false;
   }
 
-  /// Emplace an empty argument list.
-  void emplaceEmptyArgumentList(SILGenFunction &SGF);
-
   /// Add an emitted r-value argument to this argument list.
   void add(SILLocation loc, RValue &&arg) {
     assert(!isNull());
diff --git a/lib/SILGen/RValue.h b/lib/SILGen/RValue.h
index 5f5ce85..d2defd8 100644
--- a/lib/SILGen/RValue.h
+++ b/lib/SILGen/RValue.h
@@ -308,42 +308,6 @@
   /// be returned. Otherwise, an object will be returned. So this is a
   /// convenient way to determine if an RValue needs an address.
   SILType getLoweredImplodedTupleType(SILGenFunction &SGF) const &;
-
-  /// Rewrite the type of this r-value.
-  void rewriteType(CanType newType) & {
-#ifndef NDEBUG
-    static const auto areSimilarTypes = [](CanType l, CanType r) {
-      if (l == r) return true;
-
-      // Allow function types to disagree about 'noescape'.
-      if (auto lf = dyn_cast<FunctionType>(l)) {
-        if (auto rf = dyn_cast<FunctionType>(r)) {
-          auto lParams = lf.getParams();
-          auto rParams = rf.getParams();
-          return AnyFunctionType::equalParams(lParams, rParams) &&
-                 lf.getResult() == rf.getResult() &&
-                 lf->getExtInfo().withNoEscape(false) ==
-                     rf->getExtInfo().withNoEscape(false);
-        }
-      }
-      return false;
-    };
-
-    static const auto isSingleElementTuple = [](CanType type, CanType eltType) {
-      if (auto tupleType = dyn_cast<TupleType>(type)) {
-        return tupleType->getNumElements() == 1 &&
-               areSimilarTypes(tupleType.getElementType(0), eltType);
-      }
-      return false;
-    };
-
-    // We only allow a very modest set of changes to a type.
-    assert(areSimilarTypes(newType, type) ||
-           isSingleElementTuple(newType, type) ||
-           isSingleElementTuple(type, newType));
-#endif
-    type = newType;
-  }
   
   /// Emit an equivalent value with independent ownership.
   RValue copy(SILGenFunction &SGF, SILLocation loc) const &;
diff --git a/lib/SILGen/SILGenApply.cpp b/lib/SILGen/SILGenApply.cpp
index 669e56c..3ebb47f 100644
--- a/lib/SILGen/SILGenApply.cpp
+++ b/lib/SILGen/SILGenApply.cpp
@@ -826,7 +826,10 @@
 
   /// The lvalue or rvalue representing the argument source of self.
   ArgumentSource selfParam;
+
+  /// The method type with self stripped off (NOT the type of the self value).
   Type selfType;
+
   std::vector<ApplyExpr*> callSites;
   Expr *sideEffect = nullptr;
 
@@ -1635,9 +1638,9 @@
 
 } // end anonymous namespace
 
-static RValue emitStringLiteral(SILGenFunction &SGF, Expr *E, StringRef Str,
-                                SGFContext C,
-                                StringLiteralExpr::Encoding encoding) {
+static PreparedArguments emitStringLiteral(SILGenFunction &SGF, Expr *E,
+                                           StringRef Str, SGFContext C,
+                                        StringLiteralExpr::Encoding encoding) {
   uint64_t Length;
   bool isASCII = true;
   for (unsigned char c : Str) {
@@ -1663,8 +1666,12 @@
     SILValue UnicodeScalarValue =
         SGF.B.createIntegerLiteral(E, Int32Ty,
                                    unicode::extractFirstUnicodeScalar(Str));
-    return RValue(SGF, E, Int32Ty.getASTType(),
-                  ManagedValue::forUnmanaged(UnicodeScalarValue));
+
+    AnyFunctionType::Param param(Int32Ty.getASTType());
+    PreparedArguments args(llvm::ArrayRef<AnyFunctionType::Param>{param});
+    args.add(E, RValue(SGF, E, Int32Ty.getASTType(),
+                       ManagedValue::forUnmanaged(UnicodeScalarValue)));
+    return args;
   }
   }
 
@@ -1679,20 +1686,21 @@
   auto Int1Ty = SILType::getBuiltinIntegerType(1, SGF.getASTContext());
   auto *isASCIIInst = SGF.B.createIntegerLiteral(E, Int1Ty, isASCII);
 
+
   ManagedValue EltsArray[] = {
     ManagedValue::forUnmanaged(string),
     ManagedValue::forUnmanaged(lengthInst),
     ManagedValue::forUnmanaged(isASCIIInst)
   };
 
-  TupleTypeElt TypeEltsArray[] = {
-    EltsArray[0].getType().getASTType(),
-    EltsArray[1].getType().getASTType(),
-    EltsArray[2].getType().getASTType()
+  AnyFunctionType::Param TypeEltsArray[] = {
+    AnyFunctionType::Param(EltsArray[0].getType().getASTType()),
+    AnyFunctionType::Param(EltsArray[1].getType().getASTType()),
+    AnyFunctionType::Param(EltsArray[2].getType().getASTType())
   };
 
   ArrayRef<ManagedValue> Elts;
-  ArrayRef<TupleTypeElt> TypeElts;
+  ArrayRef<AnyFunctionType::Param> TypeElts;
   switch (instEncoding) {
   case StringLiteralInst::Encoding::UTF16:
     Elts = llvm::makeArrayRef(EltsArray).slice(0, 2);
@@ -1709,9 +1717,11 @@
     llvm_unreachable("these cannot be formed here");
   }
 
-  CanType ty =
-    TupleType::get(TypeElts, SGF.getASTContext())->getCanonicalType();
-  return RValue(SGF, Elts, ty);
+  PreparedArguments args(TypeElts);
+  for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
+    args.add(E, RValue(SGF, Elts[i], CanType(TypeElts[i].getPlainType())));
+  }
+  return args;
 }
 
 /// Emit a raw apply operation, performing no additional lowering of
@@ -2591,99 +2601,7 @@
 
 namespace {
 
-/// A destination for an argument other than just "onto to the end
-/// of the arguments lists".
-///
-/// This allows us to re-use the argument expression emitter for
-/// some weird cases, like a shuffled tuple where some of the
-/// arguments are going into a varargs array.
-struct ArgSpecialDest {
-  VarargsInfo *SharedInfo;
-  unsigned Index : 31;
-  unsigned IsExpansion : 1;
-  CleanupHandle Cleanup;
-
-  ArgSpecialDest() : SharedInfo(nullptr) {}
-  explicit ArgSpecialDest(VarargsInfo &info, unsigned index, bool isExpansion)
-    : SharedInfo(&info), Index(index), IsExpansion(isExpansion) {}
-
-  // Reference semantics: need to preserve the cleanup handle.
-  ArgSpecialDest(const ArgSpecialDest &) = delete;
-  ArgSpecialDest &operator=(const ArgSpecialDest &) = delete;
-  ArgSpecialDest(ArgSpecialDest &&other)
-    : SharedInfo(other.SharedInfo), Index(other.Index),
-      IsExpansion(other.IsExpansion), Cleanup(other.Cleanup) {
-    other.SharedInfo = nullptr;
-  }
-  ArgSpecialDest &operator=(ArgSpecialDest &&other) {
-    assert(!isValid() && "overwriting valid special destination!");
-    SharedInfo = other.SharedInfo;
-    Index = other.Index;
-    IsExpansion = other.IsExpansion;
-    Cleanup = other.Cleanup;
-    other.SharedInfo = nullptr;
-    return *this;
-  }
-
-  ~ArgSpecialDest() {
-    assert(!isValid() && "failed to deactivate special dest");
-  }
-
-  /// Is this a valid special destination?
-  bool isValid() const { return SharedInfo != nullptr; }
-
-  /// Fill this special destination with a value.
-  void fill(SILGenFunction &SGF, ArgumentSource &&arg,
-            AbstractionPattern _unused_origType,
-            SILType loweredSubstParamType) {
-    assert(isValid() && "filling an invalid destination");
-
-    if (IsExpansion) {
-      auto expr = std::move(arg).asKnownExpr()->getSemanticsProvidingExpr();
-      auto array = cast<VarargExpansionExpr>(expr)->getSubExpr();
-      SharedInfo->setExpansion(Index, SGF.emitRValueAsSingleValue(array));
-      Cleanup = CleanupHandle::invalid();
-      return;
-    }
-
-    SILLocation loc = arg.getLocation();
-    auto destAddr = SharedInfo->getBaseAddress();
-    if (Index != 0) {
-      SILValue index = SGF.B.createIntegerLiteral(loc,
-                  SILType::getBuiltinWordType(SGF.getASTContext()), Index);
-      destAddr = SGF.B.createIndexAddr(loc, destAddr, index);
-    }
-
-    assert(destAddr->getType() == loweredSubstParamType.getAddressType());
-
-    auto &destTL = SharedInfo->getBaseTypeLowering();
-    Cleanup =
-        SGF.enterDormantFormalAccessTemporaryCleanup(destAddr, loc, destTL);
-
-    TemporaryInitialization init(destAddr, Cleanup);
-    std::move(arg).forwardInto(SGF, SharedInfo->getBaseAbstractionPattern(),
-                               &init, destTL);
-  }
-
-  /// Deactivate this special destination.  Must always be called
-  /// before destruction.
-  void deactivate(SILGenFunction &SGF) {
-    assert(isValid() && "deactivating an invalid destination");
-    if (Cleanup.isValid())
-      SGF.Cleanups.forwardCleanup(Cleanup);
-    SharedInfo = nullptr;
-  }
-};
-
-using ArgSpecialDestArray = MutableArrayRef<ArgSpecialDest>;
-
-class ArgumentShuffleEmitter;
-
 class ArgEmitter {
-  // TODO: Refactor out the parts of ArgEmitter needed by ArgumentShuffleEmitter
-  // into its own "context struct".
-  friend class ArgumentShuffleEmitter;
-
   SILGenFunction &SGF;
   SILFunctionTypeRepresentation Rep;
   bool IsYield;
@@ -2697,71 +2615,41 @@
   /// in order to a "hole" (a null value) in Args.
   SmallVectorImpl<DelayedArgument> &DelayedArguments;
 
-  Optional<ArgSpecialDestArray> SpecialDests;
 public:
   ArgEmitter(SILGenFunction &SGF, SILFunctionTypeRepresentation Rep,
              bool isYield, bool isForCoroutine, ClaimedParamsRef paramInfos,
              SmallVectorImpl<ManagedValue> &args,
              SmallVectorImpl<DelayedArgument> &delayedArgs,
              const Optional<ForeignErrorConvention> &foreignError,
-             ImportAsMemberStatus foreignSelf,
-             Optional<ArgSpecialDestArray> specialDests = None)
+             ImportAsMemberStatus foreignSelf)
       : SGF(SGF), Rep(Rep), IsYield(isYield), IsForCoroutine(isForCoroutine),
         ForeignError(foreignError), ForeignSelf(foreignSelf),
-        ParamInfos(paramInfos), Args(args), DelayedArguments(delayedArgs),
-        SpecialDests(specialDests) {
-    assert(!specialDests || specialDests->size() == paramInfos.size());
-  }
+        ParamInfos(paramInfos), Args(args), DelayedArguments(delayedArgs) {}
 
   // origParamType is a parameter type.
   void emitSingleArg(ArgumentSource &&arg, AbstractionPattern origParamType) {
-    emit(std::move(arg), origParamType);
-    maybeEmitForeignErrorArgument();
-  }
+    // If this is default argument, prepare to emit the default argument
+    // generator later.
+    if (arg.isDefaultArg()) {
+      auto substParamType = arg.getSubstRValueType();
+      auto defArg = std::move(arg).asKnownDefaultArg();
 
-  // origFormalType is a function type.
-  //
-  // FIXME: This is all a bunch of hacks that can be removed once "scalar"
-  // PreparedArguments goes away.
-  void emitTopLevel(ArgumentSource &&arg, AbstractionPattern origFormalType) {
-    SmallVector<AbstractionPattern, 8> origParamTypes;
-    for (unsigned i = 0, e = origFormalType.getNumFunctionParams(); i < e; ++i) {
-      origParamTypes.push_back(origFormalType.getFunctionParamType(i));
-    }
+      auto numParams = getFlattenedValueCount(origParamType,
+                                              substParamType,
+                                              ImportAsMemberStatus());
+      DelayedArguments.emplace_back(defArg,
+                                    defArg->getDefaultArgsOwner(),
+                                    defArg->getParamIndex(),
+                                    substParamType, origParamType,
+                                    claimNextParameters(numParams),
+                                    Rep);
+      Args.push_back(ManagedValue());
 
-    auto origParamType = AbstractionPattern::getTuple(origParamTypes);
-
-    if (arg.isShuffle()) {
-      auto *shuffle = cast<ArgumentShuffleExpr>(std::move(arg).asKnownExpr());
-      emitShuffle(shuffle, origParamType);
       maybeEmitForeignErrorArgument();
       return;
     }
-
-    if (arg.isLValue()) {
-      assert(origParamTypes.size() == 1);
-      emitSingleArg(std::move(arg), origParamTypes[0]);
-      return;
-    }
-
-    if (arg.isExpr()) {
-      if (origParamTypes.size() == 1) {
-        auto *e = std::move(arg).asKnownExpr();
-
-        origParamType = origParamTypes[0];
-        if (auto *paren = dyn_cast<ParenExpr>(e))
-          e = paren->getSubExpr();
-        else if (auto *tuple = dyn_cast<TupleExpr>(e)) {
-          assert(tuple->getNumElements() == 1);
-          e = tuple->getElement(0);
-        }
-
-        emitSingleArg(e, origParamType);
-        return;
-      }
-    }
-
-    emitSingleArg(std::move(arg), origParamType);
+    emit(std::move(arg), origParamType);
+    maybeEmitForeignErrorArgument();
   }
 
   // origFormalType is a function type.
@@ -2770,14 +2658,10 @@
     assert(args.isValid());
     auto argSources = std::move(args).getSources();
 
-    if (args.isScalar()) {
-      assert(argSources.size() == 1);
-      emitTopLevel(std::move(argSources[0]), origFormalType);
-    } else {
-      for (auto i : indices(argSources)) {
-        emitSingleArg(std::move(argSources[i]),
-                      origFormalType.getFunctionParamType(i));
-      }
+    maybeEmitForeignErrorArgument();
+    for (auto i : indices(argSources)) {
+      emitSingleArg(std::move(argSources[i]),
+                    origFormalType.getFunctionParamType(i));
     }
   }
 
@@ -2809,7 +2693,6 @@
     // substituted argument type by abstraction and/or bridging.
     auto paramSlice = claimNextParameters(1);
     SILParameterInfo param = paramSlice.front();
-    ArgSpecialDest *specialDest = claimNextSpecialDest();
 
     assert(arg.hasLValueType() == param.isIndirectInOut());
 
@@ -2829,7 +2712,6 @@
     // If the caller takes the argument indirectly, the argument has an
     // inout type.
     if (param.isIndirectInOut()) {
-      assert(!specialDest);
       emitInOut(std::move(arg), loweredSubstArgType, loweredSubstParamType,
                 origParamType, substArgType);
       return;
@@ -2837,26 +2719,11 @@
 
     // If this is a yield, and the yield is borrowed, emit a borrowed r-value.
     if (IsYield && param.isGuaranteed()) {
-      assert(!specialDest);
       if (tryEmitBorrowed(std::move(arg), loweredSubstArgType,
                           loweredSubstParamType, origParamType, paramSlice))
         return;
     }
 
-    // If the original type is passed indirectly, copy to memory if
-    // it's not already there.  (Note that this potentially includes
-    // conventions which pass indirectly without transferring
-    // ownership, like Itanium C++.)
-    if (specialDest) {
-      assert(param.isFormalIndirect() &&
-             "SpecialDest should imply indirect parameter");
-      // TODO: Change the way we initialize array storage in opaque mode
-      emitIndirectInto(std::move(arg), origParamType, loweredSubstParamType,
-                       *specialDest);
-      Args.push_back(ManagedValue::forInContext());
-      return;
-    }
-
      if (SGF.silConv.isSILIndirect(param)) {
       emitIndirect(std::move(arg), loweredSubstArgType, origParamType, param);
       return;
@@ -2874,16 +2741,6 @@
     return slice;
   }
 
-  /// Claim the next destination, returning a null pointer if there
-  /// is no special destination.
-  ArgSpecialDest *claimNextSpecialDest() {
-    if (!SpecialDests) return nullptr;
-    assert(!SpecialDests->empty());
-    auto dest = &SpecialDests->front();
-    SpecialDests = SpecialDests->slice(1);
-    return (dest->isValid() ? dest : nullptr);
-  }
-
   /// Emit an argument as an expanded tuple.
   void emitExpanded(ArgumentSource &&arg, AbstractionPattern origParamType) {
     assert(!arg.isLValue() && "argument is l-value but parameter is tuple?");
@@ -2941,8 +2798,6 @@
     emitExpanded({ e, SGF.emitRValue(e) }, origParamType);
   }
 
-  void emitShuffle(ArgumentShuffleExpr *shuffle, AbstractionPattern origType);
-
   void emitIndirect(ArgumentSource &&arg,
                     SILType loweredSubstArgType,
                     AbstractionPattern origParamType,
@@ -2982,13 +2837,6 @@
     Args.push_back(result);
   }
 
-  void emitIndirectInto(ArgumentSource &&arg,
-                        AbstractionPattern origType,
-                        SILType loweredSubstParamType,
-                        ArgSpecialDest &dest) {
-    dest.fill(SGF, std::move(arg), origType, loweredSubstParamType);
-  }
-
   void emitInOut(ArgumentSource &&arg,
                  SILType loweredSubstArgType, SILType loweredSubstParamType,
                  AbstractionPattern origType, CanType substType) {
@@ -3302,11 +3150,8 @@
       return;
 
     SILParameterInfo param = claimNextParameters(1).front();
-    ArgSpecialDest *specialDest = claimNextSpecialDest();
-
     assert(param.getConvention() == ParameterConvention::Direct_Unowned);
-    assert(!specialDest && "special dest for error argument?");
-    (void) param; (void) specialDest;
+    (void) param;
 
     // Leave a placeholder in the position.
     Args.push_back(ManagedValue::forInContext());
@@ -3466,437 +3311,8 @@
   // That should drain all the parameters.
   assert(params.empty());
 }
-
-struct ElementExtent {
-  /// The parameters which go into this tuple element.
-  /// This is set in the first pass.
-  ClaimedParamsRef Params;
-  /// The destination index, if any.
-  /// This is set in the first pass.
-  unsigned DestIndex : 29;
-  unsigned HasDestIndex : 1;
-  unsigned IsVarargExpansion : 1;
-#ifndef NDEBUG
-  unsigned Used : 1;
-#endif
-  /// The arguments which feed this tuple element.
-  /// This is set in the second pass.
-  ArrayRef<ManagedValue> Args;
-  /// The inout arguments which feed this tuple element.
-  /// This is set in the second pass.
-  MutableArrayRef<DelayedArgument> DelayedArgs;
-
-  ElementExtent()
-      : HasDestIndex(false)
-#ifndef NDEBUG
-        ,
-        Used(false)
-#endif
-  {
-  }
-};
-
-class ArgumentShuffleEmitter {
-  Expr *inner;
-  Expr *outer;
-  ArrayRef<TupleTypeElt> innerElts;
-  ConcreteDeclRef defaultArgsOwner;
-  ArrayRef<Expr *> callerDefaultArgs;
-  ArrayRef<int> elementMapping;
-  ArrayRef<unsigned> variadicArgs;
-  Type varargsArrayType;
-  AbstractionPattern origParamType;
-  bool isResultScalar;
-
-  TupleTypeElt singleOuterElement;
-  ArrayRef<TupleTypeElt> outerElements;
-  CanType canVarargsArrayType;
-
-  /// The original parameter type.
-  SmallVector<AbstractionPattern, 8> origInnerElts;
-  AbstractionPattern innerOrigParamType;
-  /// Flattened inner parameter sequence.
-  SmallVector<SILParameterInfo, 8> innerParams;
-  /// Extents of the inner elements.
-  SmallVector<ElementExtent, 8> innerExtents;
-  Optional<VarargsInfo> varargsInfo;
-  SmallVector<unsigned, 4> varargExpansions;
-  SILParameterInfo variadicParamInfo; // innerExtents will point at this
-  Optional<SmallVector<ArgSpecialDest, 8>> innerSpecialDests;
-
-  // Used by flattenPatternFromInnerExtendIntoInnerParams and
-  // splitInnerArgumentsCorrectly.
-  SmallVector<ManagedValue, 8> innerArgs;
-  SmallVector<DelayedArgument, 2> innerDelayedArgs;
-
-public:
-  ArgumentShuffleEmitter(ArgumentShuffleExpr *e, ArrayRef<TupleTypeElt> innerElts,
-                         AbstractionPattern origParamType)
-      : inner(e->getSubExpr()), outer(e), innerElts(innerElts),
-        defaultArgsOwner(e->getDefaultArgsOwner()),
-        callerDefaultArgs(e->getCallerDefaultArgs()),
-        elementMapping(e->getElementMapping()),
-        variadicArgs(e->getVariadicArgs()),
-        varargsArrayType(e->getVarargsArrayTypeOrNull()),
-        origParamType(origParamType), isResultScalar(e->isResultScalar()),
-        canVarargsArrayType(),
-        origInnerElts(innerElts.size(), AbstractionPattern::getInvalid()),
-        innerOrigParamType(AbstractionPattern::getInvalid()), innerParams(),
-        innerExtents(innerElts.size()), varargsInfo(), variadicParamInfo(),
-        innerSpecialDests() {
-
-    // Decompose the shuffle result.
-    CanType resultType = e->getType()->getCanonicalType();
-    if (isResultScalar) {
-      singleOuterElement = TupleTypeElt(resultType);
-      outerElements = singleOuterElement;
-    } else {
-      outerElements = cast<TupleType>(resultType)->getElements();
-    }
-
-    if (varargsArrayType)
-      canVarargsArrayType = varargsArrayType->getCanonicalType();
-  }
-
-  ArgumentShuffleEmitter(const ArgumentShuffleEmitter &) = delete;
-  ArgumentShuffleEmitter &operator=(const ArgumentShuffleEmitter &) = delete;
-  ArgumentShuffleEmitter(ArgumentShuffleEmitter &&) = delete;
-  ArgumentShuffleEmitter &operator=(ArgumentShuffleEmitter &&) = delete;
-
-  void emit(ArgEmitter &parent);
-
-private:
-  void constructInnerTupleTypeInfo(ArgEmitter &parent);
-  void flattenPatternFromInnerExtendIntoInnerParams(ArgEmitter &parent);
-  void splitInnerArgumentsCorrectly(ArgEmitter &parent);
-  void emitDefaultArgsAndFinalize(ArgEmitter &parent);
-
-  AbstractionPattern getOutputOrigElementType(unsigned index) {
-    assert(!isResultScalar || index == 0);
-    return origParamType.getTupleElementType(index);
-  }
-
-  VarargExpansionExpr *getVarargExpansion(unsigned innerIndex) {
-    Expr *expr = inner->getSemanticsProvidingExpr();
-    if (cast<ArgumentShuffleExpr>(outer)->isSourceScalar()) {
-      assert(innerIndex == 0);
-    } else {
-      auto tuple = dyn_cast<TupleExpr>(expr);
-      if (!tuple) return nullptr;
-      expr = tuple->getElement(innerIndex)->getSemanticsProvidingExpr();
-    }
-    return dyn_cast<VarargExpansionExpr>(expr);
-  }
-};
-
 } // end anonymous namespace
 
-void ArgumentShuffleEmitter::constructInnerTupleTypeInfo(ArgEmitter &parent) {
-  unsigned nextParamIndex = 0;
-  for (unsigned outerIndex : indices(outerElements)) {
-    CanType substEltType =
-        outerElements[outerIndex].getType()->getCanonicalType();
-    AbstractionPattern origEltType =
-        getOutputOrigElementType(outerIndex);
-    unsigned numParams =
-        getFlattenedValueCount(origEltType, substEltType, parent.ForeignSelf);
-
-    // Skip the foreign-error parameter.
-    assert((!parent.ForeignError ||
-            parent.ForeignError->getErrorParameterIndex() <= nextParamIndex ||
-            parent.ForeignError->getErrorParameterIndex() >=
-                nextParamIndex + numParams) &&
-           "error parameter falls within shuffled range?");
-    if (numParams && // Don't skip it twice if there's an empty tuple.
-        parent.ForeignError &&
-        parent.ForeignError->getErrorParameterIndex() == nextParamIndex) {
-      nextParamIndex++;
-    }
-
-    // Grab the parameter infos corresponding to this tuple element
-    // (but don't drop them from ParamInfos yet).
-    auto eltParams = parent.ParamInfos.slice(nextParamIndex, numParams);
-    nextParamIndex += numParams;
-
-    int innerIndex = elementMapping[outerIndex];
-    if (innerIndex >= 0) {
-#ifndef NDEBUG
-      assert(!innerExtents[innerIndex].Used && "using element twice");
-      innerExtents[innerIndex].Used = true;
-#endif
-      innerExtents[innerIndex].Params = eltParams;
-      origInnerElts[innerIndex] = origEltType;
-    } else if (innerIndex == ArgumentShuffleExpr::Variadic) {
-      auto &varargsField = outerElements[outerIndex];
-      assert(varargsField.isVararg());
-      assert(!varargsInfo.hasValue() && "already had varargs entry?");
-
-      CanType varargsEltType = CanType(varargsField.getVarargBaseTy());
-      unsigned numVarargs = variadicArgs.size();
-      assert(canVarargsArrayType == substEltType);
-
-      // Check for vararg expansions, since their presence changes our
-      // emission strategy.
-      {
-        for (auto i : indices(variadicArgs)) {
-          unsigned innerIndex = variadicArgs[i];
-          if (getVarargExpansion(innerIndex)) {
-            varargExpansions.push_back(i);
-          }
-        }
-      }
-
-      // If we don't have any vararg expansions, eagerly emit into
-      // the array value.
-      varargsInfo.emplace(emitBeginVarargs(parent.SGF, outer, varargsEltType,
-                                           canVarargsArrayType, numVarargs,
-                                           varargExpansions));
-
-      // If we have any varargs, we'll need to actually initialize
-      // the array buffer.
-      if (numVarargs) {
-        // For this, we'll need special destinations.
-        assert(!innerSpecialDests);
-        innerSpecialDests.emplace();
-
-        // Prepare the variadic "arguments" as single +1 indirect parameters
-        // with the array's desired abstraction pattern.  The vararg element
-        // type should be materializable, and the abstraction pattern should be
-        // opaque, so ArgEmitter's lowering should always generate exactly one
-        // "argument" per element even if the substituted element type is a
-        // tuple.
-        variadicParamInfo =
-          SILParameterInfo(varargsInfo->getBaseTypeLowering()
-                           .getLoweredType().getASTType(),
-                           ParameterConvention::Indirect_In);
-
-        unsigned i = 0;
-        for (unsigned innerIndex : variadicArgs) {
-          // Find out where the next varargs element is coming from.
-          assert(innerIndex >= 0 && "special source for varargs element??");
-#ifndef NDEBUG
-          assert(!innerExtents[innerIndex].Used && "using element twice");
-          innerExtents[innerIndex].Used = true;
-#endif
-
-          auto expansion = getVarargExpansion(innerIndex);
-
-          // Set the destination index.
-          innerExtents[innerIndex].HasDestIndex = true;
-          innerExtents[innerIndex].DestIndex = i++;
-          innerExtents[innerIndex].IsVarargExpansion = (expansion != nullptr);
-
-          // Use the singleton param info we prepared before.
-          innerExtents[innerIndex].Params =
-            ClaimedParamsRef(variadicParamInfo);
-
-          // Propagate the element abstraction pattern.
-          origInnerElts[innerIndex] =
-            varargsInfo->getBaseAbstractionPattern();
-        }
-      }
-    }
-  }
-}
-
-void ArgumentShuffleEmitter::flattenPatternFromInnerExtendIntoInnerParams(
-    ArgEmitter &parent) {
-  for (auto &extent : innerExtents) {
-    assert(extent.Used && "didn't use all the inner tuple elements!");
-
-    for (auto param : extent.Params) {
-      innerParams.push_back(param);
-    }
-
-    // Fill in the special destinations array.
-    if (innerSpecialDests) {
-      // Use the saved index if applicable.
-      if (extent.HasDestIndex) {
-        assert(extent.Params.size() == 1);
-        innerSpecialDests->push_back(
-            ArgSpecialDest(*varargsInfo, extent.DestIndex,
-                           extent.IsVarargExpansion));
-
-        // Otherwise, fill in with the appropriate number of invalid
-        // special dests.
-      } else {
-        // ArgSpecialDest isn't copyable, so we can't just use append.
-        for (auto &p : extent.Params) {
-          (void)p;
-          innerSpecialDests->push_back(ArgSpecialDest());
-        }
-      }
-    }
-  }
-}
-
-void ArgumentShuffleEmitter::splitInnerArgumentsCorrectly(ArgEmitter &parent) {
-  ArrayRef<ManagedValue> nextArgs = innerArgs;
-  MutableArrayRef<DelayedArgument> nextDelayedArgs = innerDelayedArgs;
-  for (auto &extent : innerExtents) {
-    auto length = extent.Params.size();
-
-    // Claim the next N inner args for this inner argument.
-    extent.Args = nextArgs.slice(0, length);
-    nextArgs = nextArgs.slice(length);
-
-    // Claim the correct number of inout arguments as well.
-    size_t numDelayed = 0;
-    for (auto arg : extent.Args) {
-      assert(!arg.isInContext() || extent.HasDestIndex);
-      if (!arg)
-        numDelayed++;
-    }
-    extent.DelayedArgs = nextDelayedArgs.slice(0, numDelayed);
-    nextDelayedArgs = nextDelayedArgs.slice(numDelayed);
-  }
-
-  assert(nextArgs.empty() && "didn't claim all args");
-  assert(nextDelayedArgs.empty() && "didn't claim all inout args");
-}
-
-void ArgumentShuffleEmitter::emitDefaultArgsAndFinalize(ArgEmitter &parent) {
-  unsigned nextCallerDefaultArg = 0;
-  for (unsigned outerIndex = 0, e = outerElements.size();
-         outerIndex != e; ++outerIndex) {
-    // If this comes from an inner element, move the appropriate
-    // inner element values over.
-    int innerIndex = elementMapping[outerIndex];
-    if (innerIndex >= 0) {
-      auto &extent = innerExtents[innerIndex];
-      auto numArgs = extent.Args.size();
-
-      parent.maybeEmitForeignErrorArgument();
-
-      // Drop N parameters off of ParamInfos.
-      parent.ParamInfos = parent.ParamInfos.slice(numArgs);
-
-      // Move the appropriate inner arguments over as outer arguments.
-      parent.Args.append(extent.Args.begin(), extent.Args.end());
-      for (auto &delayedArg : extent.DelayedArgs)
-        parent.DelayedArguments.push_back(std::move(delayedArg));
-      continue;
-    }
-
-    // If this is default initialization, prepare to emit the default argument
-    // generator later.
-    if (innerIndex == ArgumentShuffleExpr::DefaultInitialize) {
-      // Otherwise, emit the default initializer, then map that as a
-      // default argument.
-      CanType eltType = outerElements[outerIndex].getType()->getCanonicalType();
-      auto origType = getOutputOrigElementType(outerIndex);
-      
-      auto numParams = getFlattenedValueCount(origType, eltType,
-                                              ImportAsMemberStatus());
-
-      parent.DelayedArguments.emplace_back(outer, defaultArgsOwner,
-                                         outerIndex, eltType, origType,
-                                         parent.claimNextParameters(numParams),
-                                         parent.Rep);
-      parent.Args.push_back(ManagedValue());
-      continue;
-    }
-
-    // If this is caller default initialization, generate the
-    // appropriate value.
-    if (innerIndex == ArgumentShuffleExpr::CallerDefaultInitialize) {
-      auto arg = callerDefaultArgs[nextCallerDefaultArg++];
-      parent.emit(ArgumentSource(arg),
-                  getOutputOrigElementType(outerIndex));
-      continue;
-    }
-
-    // If we're supposed to create a varargs array with the rest, do so.
-    if (innerIndex == ArgumentShuffleExpr::Variadic) {
-      auto &varargsField = outerElements[outerIndex];
-      assert(varargsField.isVararg() &&
-             "Cannot initialize nonvariadic element");
-      assert(varargsInfo.hasValue());
-      (void) varargsField;
-
-      // We've successfully built the varargs array; deactivate all
-      // the special destinations.
-      if (innerSpecialDests) {
-        for (auto &dest : *innerSpecialDests) {
-          if (dest.isValid())
-            dest.deactivate(parent.SGF);
-        }
-      }
-
-      CanType eltType = outerElements[outerIndex].getType()->getCanonicalType();
-      ManagedValue varargs =
-          emitEndVarargs(parent.SGF, outer, std::move(*varargsInfo));
-      parent.emit(
-          ArgumentSource(outer, RValue(parent.SGF, outer, eltType, varargs)),
-          getOutputOrigElementType(outerIndex));
-      continue;
-    }
-
-    // That's the last special case defined so far.
-    llvm_unreachable("unexpected special case in tuple shuffle!");
-  }
-}
-
-void ArgumentShuffleEmitter::emit(ArgEmitter &parent) {
-  // We could support dest addrs here, but it can't actually happen
-  // with the current limitations on default arguments in tuples.
-  assert(!parent.SpecialDests && "shuffle nested within varargs expansion?");
-
-  // First, construct an abstraction pattern and parameter sequence
-  // which we can use to emit the inner tuple.
-  constructInnerTupleTypeInfo(parent);
-
-  // The inner abstraction pattern is opaque if we started with an
-  // opaque pattern; otherwise, it's a tuple of the de-shuffled
-  // tuple elements.
-  innerOrigParamType = origParamType;
-
-  // That "tuple" might not actually be a tuple.
-  if (innerElts.size() == 1 && !innerElts[0].hasName()) {
-    innerOrigParamType = origInnerElts[0];
-  } else {
-    innerOrigParamType = AbstractionPattern::getTuple(origInnerElts);
-  }
-
-  flattenPatternFromInnerExtendIntoInnerParams(parent);
-
-  // Emit the inner expression.
-  if (!innerParams.empty()) {
-    ArgEmitter(parent.SGF, parent.Rep, parent.IsYield, parent.IsForCoroutine,
-               ClaimedParamsRef(innerParams), innerArgs, innerDelayedArgs,
-               /*foreign error*/ None, /*foreign self*/ ImportAsMemberStatus(),
-               (innerSpecialDests ? ArgSpecialDestArray(*innerSpecialDests)
-                                  : Optional<ArgSpecialDestArray>()))
-        .emitSingleArg(ArgumentSource(inner), innerOrigParamType);
-  }
-
-  // Make a second pass to split the inner arguments correctly.
-  splitInnerArgumentsCorrectly(parent);
-
-  // Make a final pass to emit default arguments and move things into
-  // the outer arguments lists.
-  emitDefaultArgsAndFinalize(parent);
-}
-
-void ArgEmitter::emitShuffle(ArgumentShuffleExpr *E,
-                             AbstractionPattern origParamType) {
-  ArrayRef<TupleTypeElt> srcElts;
-  TupleTypeElt singletonSrcElt;
-  auto srcEltTy = E->getSubExpr()->getType()->getCanonicalType();
-  if (E->isSourceScalar()) {
-    ParameterTypeFlags flags;
-    if (E->getSubExpr()->isSemanticallyInOutExpr()) {
-      flags = flags.withInOut(true);
-    }
-    singletonSrcElt = {srcEltTy->getInOutObjectType(), Identifier(), flags};
-    srcElts = singletonSrcElt;
-  } else {
-    srcElts = cast<TupleType>(srcEltTy)->getElements();
-  }
-
-  ArgumentShuffleEmitter(E, srcElts, origParamType).emit(*this);
-}
-
 namespace {
 /// Cleanup to destroy an uninitialized box.
 class DeallocateUninitializedBox : public Cleanup {
@@ -4064,20 +3480,6 @@
   bool Throws;
 
 public:
-  CallSite(ApplyExpr *apply)
-      : Loc(apply), SubstResultType(apply->getType()->getCanonicalType()),
-        Throws(apply->throws()) {
-    Expr *arg = apply->getArg();
-
-    SmallVector<AnyFunctionType::Param, 8> params;
-    AnyFunctionType::decomposeInput(arg->getType(), params);
-
-    // FIXME: Split up the argument expression here instead of passing
-    // scalar=true.
-    Args.emplace(params, /*scalar*/true);
-    Args.addArbitrary(arg);
-  }
-
   CallSite(SILLocation loc, PreparedArguments &&args, CanType resultType,
            bool throws)
       : Loc(loc), SubstResultType(resultType), Args(std::move(args)),
@@ -4085,30 +3487,6 @@
     assert(Args.isValid());
   }
 
-  // FIXME: Remove this entry point or refactor it so that isScalar is always
-  // false.
-  CallSite(SILLocation loc, ArgumentSource &&value, bool isScalar,
-           CanType resultType, bool throws)
-      : Loc(loc), SubstResultType(resultType), Throws(throws) {
-
-    auto type = (value.hasLValueType()
-                 ? CanInOutType::get(value.getSubstRValueType())
-                 : value.getSubstRValueType());
-    SmallVector<AnyFunctionType::Param, 8> params;
-    AnyFunctionType::decomposeInput(type, params);
-    Args.emplace(params, isScalar);
-    Args.addArbitrary(std::move(value));
-    assert(Args.isValid());
-  }
-
-  CallSite(SILLocation loc, ArgumentSource &&value, bool isScalar,
-           CanAnyFunctionType fnType)
-      : CallSite(loc, std::move(value), isScalar,
-                 fnType.getResult(), fnType->throws()) {}
-
-  CallSite(SILLocation loc, PreparedArguments &&args, CanAnyFunctionType fnType)
-      : CallSite(loc, std::move(args), fnType.getResult(), fnType->throws()) {}
-
   /// Return the substituted, unlowered AST parameter types of the argument.
   ArrayRef<AnyFunctionType::Param> getParams() const { return Args.getParams(); }
 
@@ -4135,9 +3513,8 @@
   }
 
   /// Take the arguments for special processing, in place of the above.
-  ArgumentSource &&forward() && {
-    assert(Args.isScalar());
-    return std::move(std::move(Args).getSources()[0]);
+  PreparedArguments &&forward() && {
+    return std::move(Args);
   }
 };
 
@@ -4180,7 +3557,7 @@
 
   /// A factory method for decomposing the apply expr \p e into a call
   /// emission.
-  static CallEmission forApplyExpr(SILGenFunction &SGF, Expr *e);
+  static CallEmission forApplyExpr(SILGenFunction &SGF, ApplyExpr *e);
 
   /// Add a level of function application by passing in its possibly
   /// unevaluated arguments and their formal type.
@@ -4202,6 +3579,17 @@
     addCallSite(CallSite{std::forward<T>(args)...});
   }
 
+  void addSelfParam(SILLocation loc,
+                    ArgumentSource &&selfArg,
+                    AnyFunctionType::Param selfParam,
+                    CanType methodType) {
+    PreparedArguments preparedSelf(llvm::ArrayRef<AnyFunctionType::Param>{selfParam});
+    preparedSelf.addArbitrary(std::move(selfArg));
+
+    addCallSite(loc, std::move(preparedSelf), methodType,
+                /*throws*/ false);
+  }
+
   /// Is this a fully-applied enum element constructor call?
   bool isEnumElementConstructor() {
     return (callee.kind == Callee::Kind::EnumElement &&
@@ -4523,6 +3911,12 @@
   return firstLevelResult;
 }
 
+static void emitPseudoFunctionArguments(SILGenFunction &SGF,
+                                        AbstractionPattern origFnType,
+                                        CanFunctionType substFnType,
+                                        SmallVectorImpl<ManagedValue> &outVals,
+                                        PreparedArguments &&args);
+
 CallEmission::FirstLevelApplicationResult
 CallEmission::applyEnumElementConstructor(SGFContext C) {
   FirstLevelApplicationResult firstLevelResult;
@@ -4547,9 +3941,15 @@
   CanType formalResultType = firstLevelResult.formalType.getResult();
 
   // Ignore metatype argument
+  SmallVector<ManagedValue, 0> metatypeVal;
+  emitPseudoFunctionArguments(SGF,
+                              AbstractionPattern(firstLevelResult.formalType),
+                              firstLevelResult.formalType, metatypeVal,
+                              std::move(uncurriedSites[0]).forward());
+  assert(metatypeVal.size() == 1);
+
   origFormalType = origFormalType.getFunctionResultType();
   claimNextParamClause(firstLevelResult.formalType);
-  std::move(uncurriedSites[0]).forward().getAsSingleValue(SGF);
 
   // Get the payload argument.
   ArgumentSource payload;
@@ -4557,8 +3957,16 @@
     assert(uncurriedSites.size() == 2);
     SmallVector<ManagedValue, 4> argVals;
     auto resultFnType = cast<FunctionType>(formalResultType);
-    auto arg = SGF.prepareEnumPayload(element, resultFnType,
-                                      std::move(uncurriedSites[1]).forward());
+
+    emitPseudoFunctionArguments(SGF,
+                                AbstractionPattern(resultFnType),
+                                resultFnType, argVals,
+                                std::move(uncurriedSites[1]).forward());
+
+    auto payloadTy = AnyFunctionType::composeInput(SGF.getASTContext(),
+                                                  resultFnType.getParams(),
+                                                  /*canonicalVararg*/ true);
+    auto arg = RValue(SGF, argVals, payloadTy->getCanonicalType());
     payload = ArgumentSource(element, std::move(arg));
     formalResultType = firstLevelResult.formalType.getResult();
     origFormalType = origFormalType.getFunctionResultType();
@@ -4680,10 +4088,10 @@
 
     // We should be able to enforce that these arguments are
     // always still expressions.
-    Expr *argument = std::move(uncurriedSites[0]).forward().asKnownExpr();
+    PreparedArguments args = std::move(uncurriedSites[0]).forward();
     ManagedValue resultMV =
         emitter(SGF, uncurriedLoc, callee.getSubstitutions(),
-                argument, uncurriedContext);
+                std::move(args), uncurriedContext);
     firstLevelResult.value =
         RValue(SGF, uncurriedLoc, formalResultType, resultMV);
     return firstLevelResult;
@@ -4869,7 +4277,7 @@
   return std::move(result);
 }
 
-CallEmission CallEmission::forApplyExpr(SILGenFunction &SGF, Expr *e) {
+CallEmission CallEmission::forApplyExpr(SILGenFunction &SGF, ApplyExpr *e) {
   // Set up writebacks for the call(s).
   FormalEvaluationScope writebacks(SGF);
 
@@ -4889,16 +4297,32 @@
 
   // Apply 'self' if provided.
   if (apply.selfParam) {
-    emission.addCallSite(RegularLocation(e),
-                         std::move(apply.selfParam), /*scalar*/ false,
-                         apply.selfType->getCanonicalType(), /*throws*/ false);
+    AnyFunctionType::Param selfParam(
+        apply.selfParam.getSubstRValueType(),
+        Identifier(),
+        apply.selfParam.isLValue()
+          ? ParameterTypeFlags().withInOut(true)
+          : ParameterTypeFlags());
+    emission.addSelfParam(e, std::move(apply.selfParam), selfParam,
+                          apply.selfType->getCanonicalType());
   }
 
   // Apply arguments from call sites, innermost to outermost.
   for (auto site = apply.callSites.rbegin(), end = apply.callSites.rend();
        site != end;
        ++site) {
-    emission.addCallSite(*site);
+    ApplyExpr *apply = *site;
+
+    Expr *arg = apply->getArg();
+
+    SmallVector<AnyFunctionType::Param, 8> params;
+    AnyFunctionType::decomposeInput(arg->getType(), params);
+
+    PreparedArguments preparedArgs(params, arg);
+
+    emission.addCallSite(apply, std::move(preparedArgs),
+                         apply->getType()->getCanonicalType(),
+                         apply->throws());
   }
 
   return emission;
@@ -5374,7 +4798,7 @@
       });
 }
 
-RValue SILGenFunction::emitApplyExpr(Expr *e, SGFContext c) {
+RValue SILGenFunction::emitApplyExpr(ApplyExpr *e, SGFContext c) {
   CallEmission emission = CallEmission::forApplyExpr(*this, e);
   return emission.apply(c);
 }
@@ -5433,7 +4857,7 @@
 /// Emit an application of the given allocating initializer.
 RValue SILGenFunction::emitApplyAllocatingInitializer(SILLocation loc,
                                                       ConcreteDeclRef init,
-                                                      RValue &&args,
+                                                      PreparedArguments &&args,
                                                       Type overriddenSelfType,
                                                       SGFContext C) {
   ConstructorDecl *ctor = cast<ConstructorDecl>(init.getDecl());
@@ -5493,37 +4917,33 @@
 
   auto substFormalType = callee->getSubstFormalType();
 
+  // Form the call emission.
+  CallEmission emission(*this, std::move(*callee), std::move(writebackScope));
+
+  auto methodType = cast<FunctionType>(substFormalType.getResult());
+  auto resultType = methodType.getResult();
+
+  // Self metatype.
+  emission.addSelfParam(loc,
+                        ArgumentSource(loc,
+                                       RValue(*this, loc,
+                                              selfMetaVal.getType()
+                                                .getASTType(),
+                                              std::move(selfMetaVal))),
+                        substFormalType.getParams()[0],
+                        methodType);
+
+  // Arguments.
+  emission.addCallSite(loc, std::move(args), resultType, /*throws*/ false);
+
   // For an inheritable initializer, determine whether we'll need to adjust the
   // result type.
   bool requiresDowncast = false;
   if (ctor->isRequired() && overriddenSelfType) {
-    CanType substResultType = substFormalType;
-    substResultType = cast<FunctionType>(substResultType).getResult();
-    substResultType = cast<FunctionType>(substResultType).getResult();
-
-    if (!substResultType->isEqual(overriddenSelfType))
+    if (!resultType->isEqual(overriddenSelfType))
       requiresDowncast = true;
   }
 
-  // Form the call emission.
-  CallEmission emission(*this, std::move(*callee), std::move(writebackScope));
-
-  // Self metatype.
-  emission.addCallSite(loc,
-                       ArgumentSource(loc,
-                                      RValue(*this, loc,
-                                             selfMetaVal.getType()
-                                               .getASTType(),
-                                             std::move(selfMetaVal))),
-                       /*scalar*/ false,
-                       substFormalType);
-
-  // Arguments.
-  // FIXME: Rework this so that scalar=false.
-  emission.addCallSite(loc,
-                       ArgumentSource(loc, std::move(args)), /*scalar*/ true,
-                       cast<FunctionType>(substFormalType.getResult()));
-
   // Perform the call.
   RValue result = emission.apply(requiresDowncast ? SGFContext() : C);
 
@@ -5544,7 +4964,7 @@
   ConcreteDeclRef builtinInit;
   ConcreteDeclRef init;
   // Emit the raw, builtin literal arguments.
-  RValue builtinLiteralArgs;
+  PreparedArguments builtinLiteralArgs;
   if (auto stringLiteral = dyn_cast<StringLiteralExpr>(literal)) {
     builtinLiteralArgs = emitStringLiteral(*this, literal,
                                            stringLiteral->getValue(), C,
@@ -5552,7 +4972,7 @@
     builtinInit = stringLiteral->getBuiltinInitializer();
     init = stringLiteral->getInitializer();
   } else if (auto nilLiteral = dyn_cast<NilLiteralExpr>(literal)) {
-    builtinLiteralArgs = emitEmptyTupleRValue(literal, C);
+    builtinLiteralArgs.emplace({});
     builtinInit = nilLiteral->getInitializer();
   } else if (auto booleanLiteral = dyn_cast<BooleanLiteralExpr>(literal)) {
     auto i1Ty = SILType::getBuiltinIntegerType(1, getASTContext());
@@ -5560,7 +4980,8 @@
                                                 booleanLiteral->getValue());
     ManagedValue boolManaged = ManagedValue::forUnmanaged(boolValue);
     CanType ty = boolManaged.getType().getASTType()->getCanonicalType();
-    builtinLiteralArgs = RValue(*this, {boolManaged}, ty);
+    builtinLiteralArgs.emplace(AnyFunctionType::Param(ty));
+    builtinLiteralArgs.add(literal, RValue(*this, {boolManaged}, ty));
     builtinInit = booleanLiteral->getBuiltinInitializer();
     init = booleanLiteral->getInitializer();
   } else if (auto integerLiteral = dyn_cast<IntegerLiteralExpr>(literal)) {
@@ -5570,7 +4991,8 @@
             SILType::getBuiltinIntegerLiteralType(getASTContext()),
             integerLiteral->getRawValue()));
     CanType ty = integerManaged.getType().getASTType();
-    builtinLiteralArgs = RValue(*this, {integerManaged}, ty);
+    builtinLiteralArgs.emplace(AnyFunctionType::Param(ty));
+    builtinLiteralArgs.add(literal, RValue(*this, {integerManaged}, ty));
     builtinInit = integerLiteral->getBuiltinInitializer();
     init = integerLiteral->getInitializer();
   } else if (auto floatLiteral = dyn_cast<FloatLiteralExpr>(literal)) {
@@ -5581,7 +5003,8 @@
         floatLiteral->getValue()));
 
     CanType ty = floatManaged.getType().getASTType();
-    builtinLiteralArgs = RValue(*this, {floatManaged}, ty);
+    builtinLiteralArgs.emplace(AnyFunctionType::Param(ty));
+    builtinLiteralArgs.add(literal, RValue(*this, {floatManaged}, ty));
     builtinInit = floatLiteral->getBuiltinInitializer();
     init = floatLiteral->getInitializer();
   } else {
@@ -5622,10 +5045,12 @@
                     : ctx.SourceMgr.getLineAndColumn(Loc).second;
       }
 
-      auto Ty = SILType::getBuiltinIntegerLiteralType(ctx);
-      SILValue V = B.createIntegerLiteral(literal, Ty, Value);
-      builtinLiteralArgs = RValue(*this, {ManagedValue::forUnmanaged(V)},
-                                  Ty.getASTType()->getCanonicalType());
+      auto silTy = SILType::getBuiltinIntegerLiteralType(ctx);
+      auto ty = silTy.getASTType();
+      SILValue integer = B.createIntegerLiteral(literal, silTy, Value);
+      ManagedValue integerManaged = ManagedValue::forUnmanaged(integer);
+      builtinLiteralArgs.emplace(AnyFunctionType::Param(ty));
+      builtinLiteralArgs.add(literal, RValue(*this, {integerManaged}, ty));
       builtinInit = magicLiteral->getBuiltinInitializer();
       init = magicLiteral->getInitializer();
       break;
@@ -5635,20 +5060,7 @@
     }
   }
 
-  // Helper routine to add an argument label if we need one.
-  auto relabelArgument = [&](ConcreteDeclRef callee, RValue &arg) {
-    auto name = callee.getDecl()->getFullName();
-    auto argLabels = name.getArgumentNames();
-    if (argLabels.size() == 1 && !argLabels[0].empty() &&
-        !isa<TupleType>(arg.getType())) {
-      Type newType = TupleType::get({TupleTypeElt(arg.getType(), argLabels[0])},
-                                    getASTContext());
-      arg.rewriteType(newType->getCanonicalType());
-    }
-  };
-
   // Call the builtin initializer.
-  relabelArgument(builtinInit, builtinLiteralArgs);
   RValue builtinLiteral =
     emitApplyAllocatingInitializer(literal, builtinInit,
                                    std::move(builtinLiteralArgs),
@@ -5659,9 +5071,12 @@
   if (!init) return builtinLiteral;
 
   // Otherwise, perform the second initialization step.
-  relabelArgument(init, builtinLiteral);
+  auto ty = builtinLiteral.getType();
+  PreparedArguments args((AnyFunctionType::Param(ty)));
+  args.add(literal, std::move(builtinLiteral));
+
   RValue result = emitApplyAllocatingInitializer(literal, init,
-                                                 std::move(builtinLiteral),
+                                                 std::move(args),
                                                  literal->getType(), C);
   return result;
 }
@@ -6036,9 +5451,10 @@
 }
 
 static void emitPseudoFunctionArguments(SILGenFunction &SGF,
+                                        AbstractionPattern origFnType,
                                         CanFunctionType substFnType,
                                         SmallVectorImpl<ManagedValue> &outVals,
-                                        ArgumentSource &&source) {
+                                        PreparedArguments &&args) {
   auto substParams = substFnType->getParams();
 
   SmallVector<SILParameterInfo, 4> substParamTys;
@@ -6056,7 +5472,7 @@
                      argValues, delayedArgs,
                      /*foreign error*/ None, ImportAsMemberStatus());
 
-  emitter.emitTopLevel(std::move(source), AbstractionPattern(substFnType));
+  emitter.emitPreparedArgs(std::move(args), origFnType);
 
   // TODO: do something to preserve LValues in the delayed arguments?
   if (!delayedArgs.empty())
@@ -6088,12 +5504,22 @@
     substFnType = cast<FunctionType>(interfaceType
                                        ->getCanonicalType());
 
+
+  AbstractionPattern origFnType(substFnType);
+
+  // Prepare the unevaluated index expression.
   auto substParams = substFnType->getParams();
+  PreparedArguments args(substParams, indexExpr);
 
+  // Now, force it to be evaluated.
   SmallVector<ManagedValue, 4> argValues;
-  emitPseudoFunctionArguments(*this, substFnType, argValues, indexExpr);
+  emitPseudoFunctionArguments(*this, origFnType, substFnType,
+                              argValues, std::move(args));
 
-  PreparedArguments result(substParams, /*isScalar=*/false);
+  // Finally, prepare the evaluated index expression. We might be calling
+  // the getter and setter, and it is important to only evaluate the
+  // index expression once.
+  PreparedArguments result(substParams);
 
   ArrayRef<ManagedValue> remainingArgs = argValues;
   for (auto substParam : substParams) {
@@ -6109,19 +5535,6 @@
   return result;
 }
 
-RValue
-SILGenFunction::prepareEnumPayload(EnumElementDecl *element,
-                                   CanFunctionType substFnType,
-                                   ArgumentSource &&args) {
-  SmallVector<ManagedValue, 4> argValues;
-  emitPseudoFunctionArguments(*this, substFnType, argValues, std::move(args));
-
-  auto payloadTy = AnyFunctionType::composeInput(getASTContext(),
-                                                 substFnType.getParams(),
-                                                 /*canonicalVararg*/ true);
-  return RValue(*this, argValues, payloadTy->getCanonicalType());
-}
-
 SILDeclRef SILGenModule::getAccessorDeclRef(AccessorDecl *accessor) {
   return SILDeclRef(accessor, SILDeclRef::Kind::Func)
     .asForeign(requiresForeignEntryPoint(accessor));
@@ -6146,15 +5559,18 @@
   CallEmission emission(*this, std::move(getter), std::move(writebackScope));
   // Self ->
   if (hasSelf) {
-    emission.addCallSite(loc, std::move(selfValue), /*scalar*/ false,
-                         accessType);
+    emission.addSelfParam(loc, std::move(selfValue),
+                         accessType.getParams()[0],
+                         accessType.getResult());
     accessType = cast<AnyFunctionType>(accessType.getResult());
   }
   // Index or () if none.
   if (subscriptIndices.isNull())
-    subscriptIndices.emplaceEmptyArgumentList(*this);
+    subscriptIndices.emplace({});
 
-  emission.addCallSite(loc, std::move(subscriptIndices), accessType);
+  emission.addCallSite(loc, std::move(subscriptIndices),
+                       accessType.getResult(),
+                       accessType->throws());
 
   // T
   return emission.apply(c);
@@ -6179,29 +5595,27 @@
   CallEmission emission(*this, std::move(setter), std::move(writebackScope));
   // Self ->
   if (hasSelf) {
-    emission.addCallSite(loc, std::move(selfValue), /*scalar*/ false,
-                         accessType);
+    emission.addSelfParam(loc, std::move(selfValue),
+                          accessType.getParams()[0],
+                          accessType.getResult());
     accessType = cast<AnyFunctionType>(accessType.getResult());
   }
 
   // (value)  or (value, indices...)
-  PreparedArguments values(accessType->getParams(), /*scalar*/ false);
+  PreparedArguments values(accessType->getParams());
   values.addArbitrary(std::move(setValue));
 
   if (!subscriptIndices.isNull()) {
-    unsigned paramIndex = 1;
     for (auto &component : std::move(subscriptIndices).getSources()) {
-      auto param = accessType.getParams()[paramIndex++];
-      auto paramType = param.getParameterType();
-
       auto argLoc = component.getKnownRValueLocation();
       RValue &&arg = std::move(component).asKnownRValue(*this);
-      arg.rewriteType(paramType);
       values.add(argLoc, std::move(arg));
     }
   }
   assert(values.isValid());
-  emission.addCallSite(loc, std::move(values), accessType);
+  emission.addCallSite(loc, std::move(values),
+                       accessType.getResult(),
+                       accessType->throws());
   // ()
   emission.apply();
 }
@@ -6226,15 +5640,18 @@
   CallEmission emission(*this, std::move(callee), std::move(writebackScope));
   // Self ->
   if (hasSelf) {
-    emission.addCallSite(loc, std::move(selfValue), /*scalar*/ false,
-                         accessType);
+    emission.addSelfParam(loc, std::move(selfValue),
+                          accessType.getParams()[0],
+                          accessType.getResult());
     accessType = cast<AnyFunctionType>(accessType.getResult());
   }
   // Index or () if none.
   if (subscriptIndices.isNull())
-    subscriptIndices.emplaceEmptyArgumentList(*this);
+    subscriptIndices.emplace({});
 
-  emission.addCallSite(loc, std::move(subscriptIndices), accessType);
+  emission.addCallSite(loc, std::move(subscriptIndices),
+                       accessType.getResult(),
+                       accessType->throws());
 
   // Unsafe{Mutable}Pointer<T> or
   // (Unsafe{Mutable}Pointer<T>, Builtin.UnknownPointer) or
@@ -6288,15 +5705,18 @@
   CallEmission emission(*this, std::move(callee), std::move(writebackScope));
   // Self ->
   if (hasSelf) {
-    emission.addCallSite(loc, std::move(selfValue), /*scalar*/ false,
-                         accessType);
+    emission.addSelfParam(loc, std::move(selfValue),
+                          accessType.getParams()[0],
+                          accessType.getResult());
     accessType = cast<AnyFunctionType>(accessType.getResult());
   }
   // Index or () if none.
   if (subscriptIndices.isNull())
-    subscriptIndices.emplaceEmptyArgumentList(*this);
+    subscriptIndices.emplace({});
 
-  emission.addCallSite(loc, std::move(subscriptIndices), accessType);
+  emission.addCallSite(loc, std::move(subscriptIndices),
+                       accessType.getResult(),
+                       accessType->throws());
 
   auto endApplyHandle = emission.applyCoroutine(yields);
 
diff --git a/lib/SILGen/SILGenBuiltin.cpp b/lib/SILGen/SILGenBuiltin.cpp
index a5770c0..76e7cfb 100644
--- a/lib/SILGen/SILGenBuiltin.cpp
+++ b/lib/SILGen/SILGenBuiltin.cpp
@@ -12,6 +12,7 @@
 
 #include "SpecializedEmitter.h"
 
+#include "ArgumentSource.h"
 #include "Cleanup.h"
 #include "Initialization.h"
 #include "LValue.h"
@@ -30,57 +31,29 @@
 using namespace swift;
 using namespace Lowering;
 
-static bool isTrivialShuffle(ArgumentShuffleExpr *shuffle) {
-  // Each element must be mapped to the corresponding element of the input.
-  auto mapping = shuffle->getElementMapping();
-  for (auto index : indices(mapping)) {
-    if (mapping[index] < 0 || unsigned(mapping[index]) != index)
-      return false;
-  }
-  return true;
-}
-
 /// Break down an expression that's the formal argument expression to
 /// a builtin function, returning its individualized arguments.
 ///
 /// Because these are builtin operations, we can make some structural
 /// assumptions about the expression used to call them.
-static ArrayRef<Expr*> decomposeArguments(SILGenFunction &SGF,
-                                          Expr *arg,
-                                          unsigned expectedCount) {
-  assert(expectedCount >= 2);
-  assert(arg->getType()->is<TupleType>());
-  assert(arg->getType()->castTo<TupleType>()->getNumElements()
-           == expectedCount);
+static Optional<SmallVector<Expr*, 2>>
+decomposeArguments(SILGenFunction &SGF,
+                   SILLocation loc,
+                   PreparedArguments &&args,
+                   unsigned expectedCount) {
+  SmallVector<Expr*, 2> result;
+  auto sources = std::move(args).getSources();
 
-  // The use of owned parameters can trip up CSApply enough to introduce
-  // a trivial tuple shuffle here.
-  arg = arg->getSemanticsProvidingExpr();
-  if (auto shuffle = dyn_cast<ArgumentShuffleExpr>(arg)) {
-    if (isTrivialShuffle(shuffle))
-      arg = shuffle->getSubExpr();
+  if (sources.size() == expectedCount) {
+    for (auto &&source : sources)
+      result.push_back(std::move(source).asKnownExpr());
+    return result;
   }
 
-  auto tuple = dyn_cast<TupleExpr>(arg);
-  if (tuple && tuple->getElements().size() == expectedCount) {
-    return tuple->getElements();
-  }
-
-  SGF.SGM.diagnose(arg, diag::invalid_sil_builtin,
+  SGF.SGM.diagnose(loc, diag::invalid_sil_builtin,
                    "argument to builtin should be a literal tuple");
 
-  auto tupleTy = arg->getType()->castTo<TupleType>();
-
-  // This is well-typed but may cause code to be emitted redundantly.
-  auto &ctxt = SGF.getASTContext();
-  SmallVector<Expr*, 4> args;
-  for (auto index : indices(tupleTy->getElementTypes())) {
-    Expr *projection = new (ctxt) TupleElementExpr(arg, SourceLoc(),
-                                                   index, SourceLoc(),
-                                          tupleTy->getElementType(index));
-    args.push_back(projection);
-  }
-  return ctxt.AllocateCopy(args);
+  return None;
 }
 
 static ManagedValue emitBuiltinRetain(SILGenFunction &SGF,
@@ -252,9 +225,13 @@
 static ManagedValue emitBuiltinInit(SILGenFunction &SGF,
                                     SILLocation loc,
                                     SubstitutionMap substitutions,
-                                    Expr *tuple,
+                                    PreparedArguments &&preparedArgs,
                                     SGFContext C) {
-  auto args = decomposeArguments(SGF, tuple, 2);
+  auto argsOrError = decomposeArguments(SGF, loc, std::move(preparedArgs), 2);
+  if (!argsOrError)
+    return ManagedValue::forUnmanaged(SGF.emitEmptyTuple(loc));
+
+  auto args = *argsOrError;
 
   CanType formalType =
     substitutions.getReplacementTypes()[0]->getCanonicalType();
@@ -421,23 +398,29 @@
 static ManagedValue emitBuiltinAddressOf(SILGenFunction &SGF,
                                          SILLocation loc,
                                          SubstitutionMap substitutions,
-                                         Expr *argument,
+                                         PreparedArguments &&preparedArgs,
                                          SGFContext C) {
-  auto rawPointerTy = SILType::getRawPointerType(SGF.getASTContext());
+  SILType rawPointerType = SILType::getRawPointerType(SGF.getASTContext());
+
+  auto argsOrError = decomposeArguments(SGF, loc, std::move(preparedArgs), 1);
+  if (!argsOrError)
+    return SGF.emitUndef(rawPointerType);
+
+  auto argument = (*argsOrError)[0];
+
   // If the argument is inout, try forming its lvalue. This builtin only works
   // if it's trivially physically projectable.
   auto inout = cast<InOutExpr>(argument->getSemanticsProvidingExpr());
   auto lv = SGF.emitLValue(inout->getSubExpr(), SGFAccessKind::ReadWrite);
   if (!lv.isPhysical() || !lv.isLoadingPure()) {
     SGF.SGM.diagnose(argument->getLoc(), diag::non_physical_addressof);
-    return SGF.emitUndef(rawPointerTy);
+    return SGF.emitUndef(rawPointerType);
   }
   
   auto addr = SGF.emitAddressOfLValue(argument, std::move(lv))
                  .getLValueAddress();
   
   // Take the address argument and cast it to RawPointer.
-  SILType rawPointerType = SILType::getRawPointerType(SGF.F.getASTContext());
   SILValue result = SGF.B.createAddressToPointer(loc, addr,
                                                  rawPointerType);
   return ManagedValue::forUnmanaged(result);
@@ -447,9 +430,16 @@
 static ManagedValue emitBuiltinAddressOfBorrow(SILGenFunction &SGF,
                                                SILLocation loc,
                                                SubstitutionMap substitutions,
-                                               Expr *argument,
+                                               PreparedArguments &&preparedArgs,
                                                SGFContext C) {
-  auto rawPointerTy = SILType::getRawPointerType(SGF.getASTContext());
+  SILType rawPointerType = SILType::getRawPointerType(SGF.getASTContext());
+
+  auto argsOrError = decomposeArguments(SGF, loc, std::move(preparedArgs), 1);
+  if (!argsOrError)
+    return SGF.emitUndef(rawPointerType);
+
+  auto argument = (*argsOrError)[0];
+
   SILValue addr;
   // Try to borrow the argument at +0. We only support if it's
   // naturally emitted borrowed in memory.
@@ -457,13 +447,12 @@
      .getAsSingleValue(SGF, argument);
   if (!borrow.isPlusZero() || !borrow.getType().isAddress()) {
     SGF.SGM.diagnose(argument->getLoc(), diag::non_borrowed_indirect_addressof);
-    return SGF.emitUndef(rawPointerTy);
+    return SGF.emitUndef(rawPointerType);
   }
   
   addr = borrow.getValue();
   
   // Take the address argument and cast it to RawPointer.
-  SILType rawPointerType = SILType::getRawPointerType(SGF.F.getASTContext());
   SILValue result = SGF.B.createAddressToPointer(loc, addr,
                                                  rawPointerType);
   return ManagedValue::forUnmanaged(result);
diff --git a/lib/SILGen/SILGenExpr.cpp b/lib/SILGen/SILGenExpr.cpp
index c0db5ad..06e5a47 100644
--- a/lib/SILGen/SILGenExpr.cpp
+++ b/lib/SILGen/SILGenExpr.cpp
@@ -450,7 +450,6 @@
     RValue visitDynamicSubscriptExpr(DynamicSubscriptExpr *E,
                                      SGFContext C);
     RValue visitDestructureTupleExpr(DestructureTupleExpr *E, SGFContext C);
-    RValue visitArgumentShuffleExpr(ArgumentShuffleExpr *E, SGFContext C);
     RValue visitDynamicTypeExpr(DynamicTypeExpr *E, SGFContext C);
     RValue visitCaptureListExpr(CaptureListExpr *E, SGFContext C);
     RValue visitAbstractClosureExpr(AbstractClosureExpr *E, SGFContext C);
@@ -462,7 +461,8 @@
     RValue visitKeyPathExpr(KeyPathExpr *E, SGFContext C);
     RValue visitMagicIdentifierLiteralExpr(MagicIdentifierLiteralExpr *E,
                                            SGFContext C);
-    RValue visitCollectionExpr(CollectionExpr *E, SGFContext C);
+    RValue visitArrayExpr(ArrayExpr *E, SGFContext C);
+    RValue visitDictionaryExpr(DictionaryExpr *E, SGFContext C);
     RValue visitRebindSelfInConstructorExpr(RebindSelfInConstructorExpr *E,
                                             SGFContext C);
     RValue visitInjectIntoOptionalExpr(InjectIntoOptionalExpr *E, SGFContext C);
@@ -1857,26 +1857,33 @@
                                     trueCount, falseCount);
 }
 
-RValue RValueEmitter::visitIsExpr(IsExpr *E, SGFContext C) {
-  SILValue isa = emitIsa(SGF, E, E->getSubExpr(),
-                         E->getCastTypeLoc().getType(), E->getCastKind());
-
+static RValue emitBoolLiteral(SILGenFunction &SGF, SILLocation loc,
+                              SILValue builtinBool,
+                              SGFContext C) {
   // Call the Bool(_builtinBooleanLiteral:) initializer
   ASTContext &ctx = SGF.getASTContext();
   auto init = ctx.getBoolBuiltinInitDecl();
-  Type builtinArgType = BuiltinIntegerType::get(1, ctx);
-  RValue builtinArg(SGF, ManagedValue::forUnmanaged(isa),
-                    builtinArgType->getCanonicalType());
+  auto builtinArgType = CanType(BuiltinIntegerType::get(1, ctx));
+  RValue builtinArg(SGF, ManagedValue::forUnmanaged(builtinBool),
+                    builtinArgType);
+
+  PreparedArguments builtinArgs((AnyFunctionType::Param(builtinArgType)));
+  builtinArgs.add(loc, std::move(builtinArg));
+
   auto result =
-    SGF.emitApplyAllocatingInitializer(E, ConcreteDeclRef(init),
-                                       std::move(builtinArg), Type(),
+    SGF.emitApplyAllocatingInitializer(loc, ConcreteDeclRef(init),
+                                       std::move(builtinArgs), Type(),
                                        C);
   return result;
 }
+RValue RValueEmitter::visitIsExpr(IsExpr *E, SGFContext C) {
+  SILValue isa = emitIsa(SGF, E, E->getSubExpr(),
+                         E->getCastTypeLoc().getType(), E->getCastKind());
+  return emitBoolLiteral(SGF, E, isa, C);
+}
 
 RValue RValueEmitter::visitEnumIsCaseExpr(EnumIsCaseExpr *E,
                                           SGFContext C) {
-  ASTContext &ctx = SGF.getASTContext();
   // Get the enum value.
   auto subExpr = SGF.emitRValueAsSingleValue(E->getSubExpr(),
                                 SGFContext(SGFContext::AllowImmediatePlusZero));
@@ -1894,16 +1901,7 @@
                                       {{E->getEnumElement(), t}});
   }
   
-  // Call the Bool(_builtinBooleanLiteral:) initializer
-  auto init = ctx.getBoolBuiltinInitDecl();
-  Type builtinArgType = BuiltinIntegerType::get(1, ctx);
-  RValue builtinArg(SGF, ManagedValue::forUnmanaged(selected),
-                    builtinArgType->getCanonicalType());
-  auto result =
-    SGF.emitApplyAllocatingInitializer(E, ConcreteDeclRef(init),
-                                       std::move(builtinArg), Type(),
-                                       C);
-  return result;
+  return emitBoolLiteral(SGF, E, selected, C);
 }
 
 RValue RValueEmitter::visitCoerceExpr(CoerceExpr *E, SGFContext C) {
@@ -1915,20 +1913,11 @@
 
 VarargsInfo Lowering::emitBeginVarargs(SILGenFunction &SGF, SILLocation loc,
                                        CanType baseTy, CanType arrayTy,
-                                       unsigned numElements,
-                                       ArrayRef<unsigned> expansionIndices) {
+                                       unsigned numElements) {
   // Reabstract the base type against the array element type.
   auto baseAbstraction = AbstractionPattern::getOpaque();
   auto &baseTL = SGF.getTypeLowering(baseAbstraction, baseTy);
 
-  if (!expansionIndices.empty()) {
-    // An assertion is okay here for now because this is only in generated code.
-    assert(numElements == 1 &&
-           "expansion that is not the only variadic argument is unsupported");
-    return VarargsInfo(ManagedValue(), CleanupHandle::invalid(), SILValue(),
-                       baseTL, baseAbstraction, /*expansion peephole*/ true);
-  }
-
   // Allocate the array.
   SILValue numEltsVal = SGF.B.createIntegerLiteral(loc,
                              SILType::getBuiltinWordType(SGF.getASTContext()),
@@ -1954,18 +1943,11 @@
     /*isStrict*/ true,
     /*isInvariant*/ false);
 
-  return VarargsInfo(array, abortCleanup, basePtr, baseTL, baseAbstraction,
-                     /*expansion peephole*/ false);
+  return VarargsInfo(array, abortCleanup, basePtr, baseTL, baseAbstraction);
 }
 
 ManagedValue Lowering::emitEndVarargs(SILGenFunction &SGF, SILLocation loc,
                                       VarargsInfo &&varargs) {
-  if (varargs.isExpansionPeephole()) {
-    auto result = varargs.getArray();
-    assert(result);
-    return result;
-  }
-
   // Kill the abort cleanup.
   SGF.Cleanups.setCleanupState(varargs.getAbortCleanup(), CleanupState::Dead);
 
@@ -2182,11 +2164,6 @@
   return result;
 }
 
-RValue RValueEmitter::visitArgumentShuffleExpr(ArgumentShuffleExpr *E,
-                                               SGFContext C) {
-  llvm_unreachable("ArgumentShuffleExpr cannot appear in rvalue position");
-}
-
 static SILValue emitMetatypeOfDelegatingInitExclusivelyBorrowedSelf(
     SILGenFunction &SGF, SILLocation loc, DeclRefExpr *dre, SILType metaTy) {
   SGFContext ctx;
@@ -2431,7 +2408,7 @@
     indexParams.emplace_back(SGF.F.mapTypeIntoContext(elt.first));
   }
   
-  PreparedArguments indexValues(indexParams, /*scalar*/ indexes.size() == 1);
+  PreparedArguments indexValues(indexParams);
   if (indexes.empty()) {
     assert(indexValues.isValid());
     return indexValues;
@@ -3601,7 +3578,78 @@
   llvm_unreachable("Unhandled MagicIdentifierLiteralExpr in switch.");
 }
 
-RValue RValueEmitter::visitCollectionExpr(CollectionExpr *E, SGFContext C) {
+RValue RValueEmitter::visitArrayExpr(ArrayExpr *E, SGFContext C) {
+  auto loc = SILLocation(E);
+  ArgumentScope scope(SGF, loc);
+
+  // CSApply builds ArrayExprs without an initializer for the trivial case
+  // of emitting varargs.
+  CanType arrayType, elementType;
+  if (E->getInitializer()) {
+    elementType = E->getElementType()->getCanonicalType();
+    arrayType = ArraySliceType::get(elementType)->getCanonicalType();
+  } else {
+    arrayType = E->getType()->getCanonicalType();
+    auto genericType = cast<BoundGenericStructType>(arrayType);
+    assert(genericType->getDecl() == SGF.getASTContext().getArrayDecl());
+    elementType = genericType.getGenericArgs()[0];
+  }
+
+  VarargsInfo varargsInfo =
+      emitBeginVarargs(SGF, loc, elementType, arrayType,
+                       E->getNumElements());
+
+  // Cleanups for any elements that have been initialized so far.
+  SmallVector<CleanupHandle, 8> cleanups;
+
+  for (unsigned index : range(E->getNumElements())) {
+    auto destAddr = varargsInfo.getBaseAddress();
+    if (index != 0) {
+      SILValue indexValue = SGF.B.createIntegerLiteral(
+          loc, SILType::getBuiltinWordType(SGF.getASTContext()), index);
+      destAddr = SGF.B.createIndexAddr(loc, destAddr, indexValue);
+    }
+    auto &destTL = varargsInfo.getBaseTypeLowering();
+    // Create a dormant cleanup for the value in case we exit before the
+    // full array has been constructed.
+
+    CleanupHandle destCleanup = CleanupHandle::invalid();
+    if (!destTL.isTrivial()) {
+      destCleanup = SGF.enterDestroyCleanup(destAddr);
+      SGF.Cleanups.setCleanupState(destCleanup, CleanupState::Dormant);
+      cleanups.push_back(destCleanup);
+    }
+
+    TemporaryInitialization init(destAddr, destCleanup);
+
+    ArgumentSource(E->getElements()[index])
+        .forwardInto(SGF, varargsInfo.getBaseAbstractionPattern(), &init,
+                     destTL);
+  }
+
+  // Kill the per-element cleanups. The array will take ownership of them.
+  for (auto destCleanup : cleanups)
+    SGF.Cleanups.setCleanupState(destCleanup, CleanupState::Dead);
+
+  RValue array(SGF, loc, arrayType,
+             emitEndVarargs(SGF, loc, std::move(varargsInfo)));
+
+  array = scope.popPreservingValue(std::move(array));
+
+  // If we're building an array, we don't have to call the initializer;
+  // we've already built one.
+  if (arrayType->isEqual(E->getType()))
+    return array;
+
+  // Call the builtin initializer.
+  PreparedArguments args(AnyFunctionType::Param(E->getType()));
+  args.add(E, std::move(array));
+
+  return SGF.emitApplyAllocatingInitializer(
+      loc, E->getInitializer(), std::move(args), E->getType(), C);
+}
+
+RValue RValueEmitter::visitDictionaryExpr(DictionaryExpr *E, SGFContext C) {
   return visit(E->getSemanticExpr(), C);
 }
 
diff --git a/lib/SILGen/SILGenFunction.h b/lib/SILGen/SILGenFunction.h
index d70276b..84beec7 100644
--- a/lib/SILGen/SILGenFunction.h
+++ b/lib/SILGen/SILGenFunction.h
@@ -1210,10 +1210,6 @@
                                             AccessStrategy strategy,
                                             Expr *indices);
 
-  RValue prepareEnumPayload(EnumElementDecl *element,
-                            CanFunctionType substFnType,
-                            ArgumentSource &&indexExpr);
-
   ArgumentSource prepareAccessorBaseArg(SILLocation loc, ManagedValue base,
                                         CanType baseFormalType,
                                         SILDeclRef accessor);
@@ -1417,7 +1413,7 @@
   // Helpers for emitting ApplyExpr chains.
   //
 
-  RValue emitApplyExpr(Expr *e, SGFContext c);
+  RValue emitApplyExpr(ApplyExpr *e, SGFContext c);
 
   /// Emit a function application, assuming that the arguments have been
   /// lowered appropriately for the abstraction level but that the
@@ -1463,7 +1459,7 @@
                                      SGFContext ctx);
 
   RValue emitApplyAllocatingInitializer(SILLocation loc, ConcreteDeclRef init,
-                                        RValue &&args, Type overriddenSelfType,
+                                        PreparedArguments &&args, Type overriddenSelfType,
                                         SGFContext ctx);
 
   CleanupHandle emitBeginApply(SILLocation loc, ManagedValue fn,
diff --git a/lib/SILGen/SpecializedEmitter.h b/lib/SILGen/SpecializedEmitter.h
index c249b6a..7b59166 100644
--- a/lib/SILGen/SpecializedEmitter.h
+++ b/lib/SILGen/SpecializedEmitter.h
@@ -32,6 +32,7 @@
 class SGFContext;
 class SILGenFunction;
 class SILGenModule;
+class PreparedArguments;
 
 /// Some kind of specialized emitter for a builtin function.
 class SpecializedEmitter {
@@ -41,7 +42,7 @@
   using EarlyEmitter = ManagedValue (SILGenFunction &,
                                      SILLocation,
                                      SubstitutionMap,
-                                     Expr *argument,
+                                     PreparedArguments &&args,
                                      SGFContext);
 
   /// A special function for emitting a call after the arguments
diff --git a/lib/SILGen/Varargs.h b/lib/SILGen/Varargs.h
index b38df4e..334b2ba 100644
--- a/lib/SILGen/Varargs.h
+++ b/lib/SILGen/Varargs.h
@@ -35,23 +35,12 @@
   SILValue BaseAddress;
   AbstractionPattern BasePattern;
   const TypeLowering &BaseTL;
-  bool IsExpansionPeephole = false;
 public:
   VarargsInfo(ManagedValue array, CleanupHandle abortCleanup,
               SILValue baseAddress, const TypeLowering &baseTL,
-              AbstractionPattern basePattern, bool isExpansionPeephole)
+              AbstractionPattern basePattern)
     : Array(array), AbortCleanup(abortCleanup),
-      BaseAddress(baseAddress), BasePattern(basePattern), BaseTL(baseTL),
-      IsExpansionPeephole(isExpansionPeephole) {}
-
-  void setExpansion(unsigned index, ManagedValue expansion) {
-    assert(IsExpansionPeephole);
-    assert(index == 0 && "non-initial index for peephole?");
-    assert(!Array && "array already filled");
-    Array = expansion;
-  }
-
-  bool isExpansionPeephole() const { return IsExpansionPeephole; }
+      BaseAddress(baseAddress), BasePattern(basePattern), BaseTL(baseTL) {}
 
   /// Return the array value.  emitEndVarargs() is really the only
   /// function that should be accessing this directly.
@@ -75,8 +64,7 @@
 /// Begin a varargs emission sequence.
 VarargsInfo emitBeginVarargs(SILGenFunction &SGF, SILLocation loc,
                              CanType baseTy, CanType arrayTy,
-                             unsigned numElements,
-                             ArrayRef<unsigned> expansions);
+                             unsigned numElements);
 
 /// Successfully end a varargs emission sequence.
 ManagedValue emitEndVarargs(SILGenFunction &SGF, SILLocation loc,
diff --git a/lib/SILOptimizer/Utils/CastOptimizer.cpp b/lib/SILOptimizer/Utils/CastOptimizer.cpp
index 7990dc6..b3a4b74 100644
--- a/lib/SILOptimizer/Utils/CastOptimizer.cpp
+++ b/lib/SILOptimizer/Utils/CastOptimizer.cpp
@@ -79,6 +79,63 @@
 /// _conditionallyBridgeFromObjectiveC_bridgeable which converts an ObjC
 /// instance into a corresponding Swift type, conforming to
 /// _ObjectiveCBridgeable.
+///
+/// Control Flow Modification Model
+/// ===============================
+///
+/// NOTE: In the following we assume that our src type is not address only. We
+/// do not support optimizing such source types today.
+///
+/// Unconditional Casts
+/// -------------------
+///
+/// In the case of unconditional casts, we do not touch the CFG at all. We
+/// perform the following optimizations:
+///
+/// 1. If the bridged type and the src type equal, we replace the cast with the
+///    apply.
+///
+/// 2. If src is an address and bridged type has the matching object type to
+///    src, just load the value and again replace the cast with the apply.
+///
+/// 3. If src is an address and after loading still doesn't match bridged type,
+///    insert an unconditional_checked_cast before calling the apply.
+///
+/// Conditional Casts
+/// -----------------
+///
+/// In the case of a conditional const (i.e. checked_cast_addr_br), we transform
+/// the following CFG:
+///
+/// ```
+///    InstBlock (checked_cast_addr_br) -> FailureBB -> FailureSucc
+///        \
+///         \----------------------------> SuccessBB -> SuccessSucc
+/// ```
+///
+/// to a CFG of the following form:
+///
+/// ```
+///   InstBlock (checked_cast_br) -> CastFailBB -> FailureBB -> FailureSucc
+///        |                                          ^
+///        \-> CastSuccessBB (bridge call + switch) --|
+///                 |
+///                 \-> BridgeSuccessBB -> SuccessBB -> SuccessSucc
+/// ```
+///
+/// NOTE: That if the underlying src type matches the type of the underlying
+/// bridge source object, we can omit the initial checked_cast_br and just load
+/// the value + branch to the CastSuccessBB. This results instead in the
+/// following CFG:
+///
+/// ```
+///   InstBlock (br)                             FailureBB -> FailureSucc
+///        |                                          ^
+///        \-> CastSuccessBB (bridge call + switch) --|
+///                 |
+///                 \-> BridgeSuccessBB -> SuccessBB -> SuccessSucc
+/// ```
+///
 SILInstruction *
 CastOptimizer::optimizeBridgedObjCToSwiftCast(SILDynamicCastInst dynamicCast) {
   auto kind = dynamicCast.getKind();
@@ -99,6 +156,7 @@
   }
 
   SILValue src = dynamicCast.getSource();
+
   // Check if we have a source type that is address only. We do not support that
   // today.
   if (src->getType().isAddressOnly(mod)) {
@@ -134,11 +192,12 @@
   SILBuilderWithScope Builder(Inst, BuilderContext);
 
   // If this is a conditional cast:
+  //
   // We need a new fail BB in order to add a dealloc_stack to it
-  SILBasicBlock *ConvFailBB = nullptr;
+  SILBasicBlock *CastFailBB = nullptr;
   if (isConditional) {
     auto CurrInsPoint = Builder.getInsertionPoint();
-    ConvFailBB = splitBasicBlockAndBranch(Builder, &(*FailureBB->begin()),
+    CastFailBB = splitBasicBlockAndBranch(Builder, &(*FailureBB->begin()),
                                           nullptr, nullptr);
     Builder.setInsertionPoint(CurrInsPoint);
   }
@@ -176,8 +235,8 @@
       SILBasicBlock *castSuccessBB = F->createBasicBlock();
       castSuccessBB->createPhiArgument(silBridgedTy, ValueOwnershipKind::Owned);
       auto *ccbi = Builder.createCheckedCastBranch(
-          Loc, false, load, silBridgedTy, castSuccessBB, ConvFailBB);
-      splitEdge(ccbi, /* EdgeIdx to ConvFailBB */ 1);
+          Loc, false, load, silBridgedTy, castSuccessBB, CastFailBB);
+      splitEdge(ccbi, /* EdgeIdx to CastFailBB */ 1);
       Builder.setInsertionPoint(castSuccessBB);
       return {castSuccessBB->getArgument(0), ccbi};
     }
@@ -257,17 +316,17 @@
     // Load from the optional.
     auto *SomeDecl = Builder.getASTContext().getOptionalSomeDecl();
 
-    SILBasicBlock *ConvSuccessBB = Inst->getFunction()->createBasicBlock();
-    SmallVector<std::pair<EnumElementDecl *, SILBasicBlock *>, 1> CaseBBs;
-    CaseBBs.push_back(
-        std::make_pair(mod.getASTContext().getOptionalNoneDecl(), FailureBB));
-    Builder.createSwitchEnumAddr(Loc, InOutOptionalParam, ConvSuccessBB,
+    SILBasicBlock *BridgeSuccessBB = Inst->getFunction()->createBasicBlock();
+    SmallVector<std::pair<EnumElementDecl *, SILBasicBlock *>, 2> CaseBBs;
+    CaseBBs.emplace_back(mod.getASTContext().getOptionalNoneDecl(), FailureBB);
+
+    Builder.createSwitchEnumAddr(Loc, InOutOptionalParam, BridgeSuccessBB,
                                  CaseBBs);
 
     Builder.setInsertionPoint(FailureBB->begin());
     Builder.createDeallocStack(Loc, Tmp);
 
-    Builder.setInsertionPoint(ConvSuccessBB);
+    Builder.setInsertionPoint(BridgeSuccessBB);
     auto Addr = Builder.createUncheckedTakeEnumDataAddr(Loc, InOutOptionalParam,
                                                         SomeDecl);
 
diff --git a/lib/Sema/CSApply.cpp b/lib/Sema/CSApply.cpp
index b1ea21b..ca11941 100644
--- a/lib/Sema/CSApply.cpp
+++ b/lib/Sema/CSApply.cpp
@@ -2782,71 +2782,23 @@
                               ConformanceCheckFlags::InExpression);
       assert(conformance && "Type does not conform to protocol?");
 
-      // Call the witness that builds the array literal.
-      // FIXME: callWitness() may end up re-doing some work we already did
-      // to convert the array literal elements to the element type. It would
-      // be nicer to re-use them.
-
-      // FIXME: This location info is bogus.
-      Expr *typeRef = TypeExpr::createImplicitHack(expr->getLoc(), arrayTy,
-                                                   tc.Context);
-      cs.cacheExprTypes(typeRef);
-
       DeclName name(tc.Context, DeclBaseName::createConstructor(),
                     { tc.Context.Id_arrayLiteral });
 
-      // Coerce the array elements to be rvalues, so that other type-checker
-      // code that attempts to peephole the AST doesn't have to re-load the
-      // elements (and break the invariant that lvalue nodes only get their
-      // access kind set once).
-      for (auto &element : expr->getElements()) {
-        element = cs.coerceToRValue(element);
-      }
-
-      // Restructure the argument to provide the appropriate labels in the
-      // tuple.
-      SmallVector<TupleTypeElt, 4> typeElements;
-      SmallVector<Identifier, 4> names;
-      bool first = true;
-      for (auto elt : expr->getElements()) {
-        if (first) {
-          typeElements.push_back(TupleTypeElt(cs.getType(elt),
-                                              tc.Context.Id_arrayLiteral));
-          names.push_back(tc.Context.Id_arrayLiteral);
-
-          first = false;
-          continue;
-        }
-
-        typeElements.push_back(cs.getType(elt));
-        names.push_back(Identifier());
-      }
-
-      Type argType = TupleType::get(typeElements, tc.Context);
-      assert(isa<TupleType>(argType.getPointer()));
-
-      Expr *arg =
-        TupleExpr::create(tc.Context, SourceLoc(),
-                          expr->getElements(),
-                          names,
-                          { },
-                          SourceLoc(), /*HasTrailingClosure=*/false,
-                          /*Implicit=*/true,
-                          argType);
-
-      cs.cacheExprTypes(arg);
-
-      cs.setExprTypes(typeRef);
-      cs.setExprTypes(arg);
-
-      Expr *result = tc.callWitness(typeRef, dc, arrayProto, *conformance,
-                                    name, arg, diag::array_protocol_broken);
-      if (!result)
+      ConcreteDeclRef witness =
+          findNamedWitnessImpl(tc, dc, arrayTy->getRValueType(), arrayProto,
+                               name, diag::array_protocol_broken, conformance);
+      if (!witness || !isa<AbstractFunctionDecl>(witness.getDecl()))
         return nullptr;
+      expr->setInitializer(witness);
 
-      cs.cacheExprTypes(result);
+      auto elementType = expr->getElementType();
 
-      expr->setSemanticExpr(result);
+      for (auto &element : expr->getElements()) {
+        element = coerceToType(element, elementType,
+                               cs.getConstraintLocator(element));
+      }
+
       return expr;
     }
 
@@ -2993,11 +2945,7 @@
     Expr *visitVarargExpansionExpr(VarargExpansionExpr *expr) {
       simplifyExprType(expr);
 
-      auto elementTy = cs.getType(expr);
-      auto arrayTy =
-        cs.getTypeChecker().getArraySliceType(expr->getLoc(), elementTy);
-      if (!arrayTy) return expr;
-
+      auto arrayTy = cs.getType(expr);
       expr->setSubExpr(coerceToType(expr->getSubExpr(), arrayTy,
                                     cs.getConstraintLocator(expr)));
       return expr;
@@ -3015,6 +2963,14 @@
       llvm_unreachable("Already type-checked");
     }
 
+    Expr *visitDefaultArgumentExpr(DefaultArgumentExpr *expr) {
+      llvm_unreachable("Already type-checked");
+    }
+
+    Expr *visitCallerDefaultArgumentExpr(CallerDefaultArgumentExpr *expr) {
+      llvm_unreachable("Already type-checked");
+    }
+
     Expr *visitApplyExpr(ApplyExpr *expr) {
       return finishApply(expr, cs.getType(expr),
                          ConstraintLocatorBuilder(
@@ -5368,6 +5324,15 @@
   // FIXME: Eventually, we want to enforce that we have either argTuple or
   // argParen here.
 
+  SourceLoc lParenLoc, rParenLoc;
+  if (argTuple) {
+    lParenLoc = argTuple->getLParenLoc();
+    rParenLoc = argTuple->getRParenLoc();
+  } else if (argParen) {
+    lParenLoc = argParen->getLParenLoc();
+    rParenLoc = argParen->getRParenLoc();
+  }
+
   // Local function to extract the ith argument expression, which papers
   // over some of the weirdness with tuples vs. parentheses.
   auto getArg = [&](unsigned i) -> Expr * {
@@ -5381,118 +5346,133 @@
     return arg;
   };
 
-  // Local function to extract the ith argument label, which papers over some
-  // of the weirdness with tuples vs. parentheses.
-  auto getArgLabel = [&](unsigned i) -> Identifier {
+  auto getLabelLoc = [&](unsigned i) -> SourceLoc {
     if (argTuple)
-      return argTuple->getElementName(i);
+      return argTuple->getElementNameLoc(i);
 
     assert(i == 0 && "Scalar only has a single argument");
-    return Identifier();
+    return SourceLoc();
   };
 
-  SmallVector<TupleTypeElt, 4> toSugarFields;
-  SmallVector<TupleTypeElt, 4> fromTupleExprFields(
-                                 argTuple? argTuple->getNumElements() : 1);
-  SmallVector<Expr*, 4> fromTupleExpr(argTuple? argTuple->getNumElements() : 1);
-  SmallVector<unsigned, 4> variadicArgs;
-  SmallVector<Expr *, 2> callerDefaultArgs;
-  Type sliceType = nullptr;
-  SmallVector<int, 4> sources;
+  SmallVector<Expr *, 4> newArgs;
+  SmallVector<Identifier, 4> newLabels;
+  SmallVector<SourceLoc, 4> newLabelLocs;
+  SmallVector<AnyFunctionType::Param, 4> newParams;
+
   for (unsigned paramIdx = 0, numParams = parameterBindings.size();
        paramIdx != numParams; ++paramIdx) {
     // Extract the parameter.
     const auto &param = params[paramIdx];
+    newLabels.push_back(param.getLabel());
 
     // Handle variadic parameters.
     if (param.isVariadic()) {
-      // Find the appropriate injection function.
-      if (tc.requireArrayLiteralIntrinsics(arg->getStartLoc()))
-        return nullptr;
+      assert(!param.isInOut());
 
-      // Record this parameter.
-      auto paramBaseType = param.getOldType();
-      assert(sliceType.isNull() && "Multiple variadic parameters?");
-      sliceType = tc.getArraySliceType(arg->getLoc(), paramBaseType);
-      toSugarFields.push_back(
-          TupleTypeElt(sliceType, param.getLabel(), param.getParameterFlags()));
-      sources.push_back(ArgumentShuffleExpr::Variadic);
+      SmallVector<Expr *, 4> variadicArgs;
+
+      // The first argument of this vararg parameter may have had a label;
+      // save its location.
+      auto &varargIndices = parameterBindings[paramIdx];
+      if (!varargIndices.empty())
+        newLabelLocs.push_back(getLabelLoc(varargIndices[0]));
+      else
+        newLabelLocs.push_back(SourceLoc());
 
       // Convert the arguments.
-      for (auto argIdx : parameterBindings[paramIdx]) {
+      for (auto argIdx : varargIndices) {
         auto arg = getArg(argIdx);
         auto argType = cs.getType(arg);
-        variadicArgs.push_back(argIdx);
 
         // If the argument type exactly matches, this just works.
-        if (argType->isEqual(paramBaseType)) {
-          fromTupleExprFields[argIdx] = TupleTypeElt(argType,
-                                                     getArgLabel(argIdx));
-          fromTupleExpr[argIdx] = arg;
+        if (argType->isEqual(param.getPlainType())) {
+          variadicArgs.push_back(arg);
           continue;
         }
 
         // Convert the argument.
-        auto convertedArg = coerceToType(arg, paramBaseType,
+        auto convertedArg = coerceToType(arg, param.getPlainType(),
                                          getArgLocator(argIdx, paramIdx));
         if (!convertedArg)
           return nullptr;
 
         // Add the converted argument.
-        fromTupleExpr[argIdx] = convertedArg;
-        fromTupleExprFields[argIdx] = TupleTypeElt(cs.getType(convertedArg),
-                                                   getArgLabel(argIdx));
+        variadicArgs.push_back(convertedArg);
       }
 
+      SourceLoc start, end;
+      if (!variadicArgs.empty()) {
+        start = variadicArgs.front()->getStartLoc();
+        end = variadicArgs.back()->getEndLoc();
+      }
+
+      // Collect them into an ArrayExpr.
+      auto *arrayExpr = ArrayExpr::create(tc.Context,
+                                          start,
+                                          variadicArgs,
+                                          {}, end,
+                                          param.getParameterType());
+      arrayExpr->setImplicit();
+      cs.cacheType(arrayExpr);
+
+      // Wrap the ArrayExpr in a VarargExpansionExpr.
+      auto *varargExpansionExpr =
+        new (tc.Context) VarargExpansionExpr(arrayExpr,
+                                             /*implicit=*/true,
+                                             arrayExpr->getType());
+      cs.cacheType(varargExpansionExpr);
+
+      newArgs.push_back(varargExpansionExpr);
+      newParams.push_back(param);
       continue;
     }
 
-    // If we are using a default argument, handle it now.
+    // Handle default arguments.
     if (parameterBindings[paramIdx].empty()) {
-      // Create a caller-side default argument, if we need one.
       Expr *defArg;
       DefaultArgumentKind defArgKind;
       std::tie(defArg, defArgKind) = getCallerDefaultArg(cs, dc, arg->getLoc(),
                                                          callee, paramIdx);
 
-      // Note that we'll be doing a shuffle involving default arguments.
-      toSugarFields.push_back(TupleTypeElt(
-                                param.isVariadic()
-                                  ? tc.getArraySliceType(arg->getLoc(),
-                                                         param.getOldType())
-                                  : param.getOldType(),
-                                param.getLabel(),
-                                param.getParameterFlags()));
-
+      // If we have a caller-side default argument, just add the magic literal
+      // expression to our argument list.
       if (defArg) {
-        callerDefaultArgs.push_back(defArg);
-        sources.push_back(ArgumentShuffleExpr::CallerDefaultInitialize);
+        defArg =
+            new (tc.Context) CallerDefaultArgumentExpr(defArg,
+                                                       arg->getStartLoc(),
+                                                       param.getParameterType());
+
+      // Otherwise, create a call of the default argument generator.
       } else {
-        sources.push_back(ArgumentShuffleExpr::DefaultInitialize);
+        defArg =
+            new (tc.Context) DefaultArgumentExpr(callee, paramIdx,
+                                                 arg->getStartLoc(),
+                                                 param.getParameterType());
       }
+
+      cs.cacheType(defArg);
+      newArgs.push_back(defArg);
+      newParams.push_back(param);
+      newLabelLocs.push_back(SourceLoc());
       continue;
     }
 
+    // Otherwise, we have a plain old ordinary argument.
+
     // Extract the argument used to initialize this parameter.
     assert(parameterBindings[paramIdx].size() == 1);
     unsigned argIdx = parameterBindings[paramIdx].front();
     auto arg = getArg(argIdx);
     auto argType = cs.getType(arg);
 
-    // If the argument and parameter indices differ, or if the names differ,
-    // this is a shuffle.
-    sources.push_back(argIdx);
+    // Save the original label location.
+    newLabelLocs.push_back(getLabelLoc(argIdx));
 
     // If the types exactly match, this is easy.
     auto paramType = param.getOldType();
     if (argType->isEqual(paramType)) {
-      toSugarFields.push_back(
-          TupleTypeElt(param.getPlainType(), getArgLabel(argIdx),
-                       param.getParameterFlags()));
-      fromTupleExprFields[argIdx] =
-          TupleTypeElt(param.getPlainType(), getArgLabel(argIdx),
-                       param.getParameterFlags());
-      fromTupleExpr[argIdx] = arg;
+      newArgs.push_back(arg);
+      newParams.push_back(param);
       continue;
     }
 
@@ -5510,6 +5490,8 @@
     // a regular function coversion by `coerceToType`.
     if (param.isAutoClosure() && (!argType->is<FunctionType>() ||
                                   !isAutoClosureArg(arg))) {
+      assert(!param.isInOut());
+
       // If parameter is an autoclosure, we need to make sure that:
       //   - argument type is coerced to parameter result type
       //   - impilict autoclosure is created to wrap argument expression
@@ -5530,109 +5512,65 @@
     if (!convertedArg)
       return nullptr;
 
-    // Add the converted argument.
-    fromTupleExpr[argIdx] = convertedArg;
-    fromTupleExprFields[argIdx] = TupleTypeElt(
-        cs.getType(convertedArg)->getInOutObjectType(),
-        getArgLabel(argIdx), param.getParameterFlags());
-    toSugarFields.push_back(
-        TupleTypeElt(argType->getInOutObjectType(), param.getLabel(),
-                     param.getParameterFlags()));
+    newArgs.push_back(convertedArg);
+
+    // Make an effort to preserve the sugared type of the argument in the
+    // case where there was no conversion, instead of using the parameter
+    // type.
+    newParams.emplace_back(cs.getType(convertedArg)->getInOutObjectType(),
+                           param.getLabel(),
+                           param.getParameterFlags());
   }
 
-  Type argTupleType = TupleType::get(fromTupleExprFields, tc.Context);
+  assert(newArgs.size() == newParams.size());
+  assert(newArgs.size() == newLabels.size());
+  assert(newArgs.size() == newLabelLocs.size());
 
-  // Compute a new 'arg', from the bits we have.  We have three cases: the
-  // scalar case, the paren case, and the tuple literal case.
-  if (!argTuple && !argParen) {
-    assert(fromTupleExpr.size() == 1 && fromTupleExpr[0]);
-    arg = fromTupleExpr[0];
-  } else if (argParen) {
-    // If the element changed, rebuild a new ParenExpr.
-    assert(fromTupleExpr.size() == 1 && fromTupleExpr[0]);
-    if (fromTupleExpr[0] != argParen->getSubExpr()) {
-      bool argParenImplicit = argParen->isImplicit();
-      argParen =
-        cs.cacheType(new (tc.Context)
-                     ParenExpr(argParen->getLParenLoc(),
-                               fromTupleExpr[0],
-                               argParen->getRParenLoc(),
-                               argParen->hasTrailingClosure(),
-                               argTupleType));
-      if (argParenImplicit) {
-        argParen->setImplicit();
-      }
-      arg = argParen;
-    } else {
-      // coerceToType may have updated the element type of the ParenExpr in
-      // place.  If so, propagate the type out to the ParenExpr as well.
-      cs.setType(argParen, argTupleType);
-    }
-  } else {
-    assert(argTuple);
-
-    bool anyChanged = false;
-    for (unsigned i = 0, e = argTuple->getNumElements(); i != e; ++i)
-      if (fromTupleExpr[i] != argTuple->getElement(i)) {
-        anyChanged = true;
-        break;
-      }
-
-    // If anything about the TupleExpr changed, rebuild a new one.
-    Type argTupleType = TupleType::get(fromTupleExprFields, tc.Context);
-    assert(isa<TupleType>(argTupleType.getPointer()));
-
-    if (anyChanged || !cs.getType(argTuple)->isEqual(argTupleType)) {
-      auto EltNames = argTuple->getElementNames();
-      auto EltNameLocs = argTuple->getElementNameLocs();
-      argTuple =
-        cs.cacheType(TupleExpr::create(tc.Context, argTuple->getLParenLoc(),
-                                       fromTupleExpr, EltNames, EltNameLocs,
-                                       argTuple->getRParenLoc(),
-                                       argTuple->hasTrailingClosure(),
-                                       argTuple->isImplicit(),
-                                       argTupleType));
-      arg = argTuple;
-    }
+  // This is silly. SILGen gets confused if a 'self' parameter is wrapped
+  // in a ParenExpr sometimes.
+  if (!argTuple && !argParen &&
+      (params[0].getValueOwnership() == ValueOwnership::Default ||
+       params[0].getValueOwnership() == ValueOwnership::InOut)) {
+    assert(newArgs.size() == 1);
+    assert(!hasTrailingClosure);
+    return newArgs[0];
   }
 
-  // If we don't have to shuffle anything, we're done.
-  args.clear();
-  AnyFunctionType::decomposeInput(cs.getType(arg), args);
-  if (AnyFunctionType::equalParams(args, params))
-    return arg;
-
-  auto paramType = AnyFunctionType::composeInput(tc.Context, params,
+  // Rebuild the argument list, sharing as much structure as possible.
+  auto paramType = AnyFunctionType::composeInput(tc.Context, newParams,
                                                  /*canonicalVararg=*/false);
-
-  // If we came from a scalar, create a scalar-to-tuple conversion.
-  ArgumentShuffleExpr::TypeImpact typeImpact;
-  if (argTuple == nullptr) {
-    // Deal with a difference in only scalar ownership.
-    if (auto paramParenTy = dyn_cast<ParenType>(paramType.getPointer())) {
-      assert(paramParenTy->getUnderlyingType()
-              ->isEqual(cs.getType(arg)));
-      auto argParen = new (tc.Context) ParenExpr(arg->getStartLoc(),
-                                                 arg, arg->getEndLoc(), false,
-                                                 paramParenTy);
-      argParen->setImplicit();
-      return cs.cacheType(argParen);
+  if (isa<ParenType>(paramType.getPointer())) {
+    if (argParen) {
+      // We already had a ParenExpr, so replace it's sub-expression.
+      argParen->setSubExpr(newArgs[0]);
+    } else {
+      arg = new (tc.Context) ParenExpr(lParenLoc,
+                                       newArgs[0],
+                                       rParenLoc,
+                                       hasTrailingClosure);
+      arg->setImplicit();
     }
-
-    typeImpact = ArgumentShuffleExpr::ScalarToTuple;
-    assert(isa<TupleType>(paramType.getPointer()));
-  } else if (isa<TupleType>(paramType.getPointer())) {
-    typeImpact = ArgumentShuffleExpr::TupleToTuple;
   } else {
-    typeImpact = ArgumentShuffleExpr::TupleToScalar;
-    assert(isa<ParenType>(paramType.getPointer()));
+    assert(isa<TupleType>(paramType.getPointer()));
+
+    if (argTuple && newArgs.size() == argTuple->getNumElements()) {
+      // The existing TupleExpr has the right number of elements,
+      // replace them.
+      for (unsigned i = 0, e = newArgs.size(); i != e; ++i) {
+        argTuple->setElement(i, newArgs[i]);
+      }
+    } else {
+      // Build a new TupleExpr, re-using source location information.
+      arg = TupleExpr::create(tc.Context, lParenLoc,
+                              newArgs, newLabels, newLabelLocs,
+                              rParenLoc,
+                              hasTrailingClosure,
+                              /*implicit=*/true);
+    }
   }
 
-  // Create the argument shuffle.
-  return cs.cacheType(ArgumentShuffleExpr::create(tc.Context, arg, sources,
-                                                  typeImpact, callee, variadicArgs,
-                                                  sliceType, callerDefaultArgs,
-                                                  paramType));
+  arg->setType(paramType);
+  return cs.cacheType(arg);
 }
 
 static ClosureExpr *getClosureLiteralExpr(Expr *expr) {
@@ -6904,9 +6842,6 @@
           return nullptr;
         }
 
-        if (auto shuffle = dyn_cast<ArgumentShuffleExpr>(arg))
-          arg = shuffle->getSubExpr();
-
         if (auto tuple = dyn_cast<TupleExpr>(arg))
           arg = tuple->getElements()[0];
 
@@ -7107,8 +7042,7 @@
 
     // Extract all arguments.
     auto *CEA = arg;
-    if (auto *ASE = dyn_cast<ArgumentShuffleExpr>(CEA))
-      CEA = ASE->getSubExpr();
+
     // The argument is either a ParenExpr or TupleExpr.
     ArrayRef<Expr *> arguments;
 
diff --git a/lib/Sema/CSDiag.cpp b/lib/Sema/CSDiag.cpp
index fd43424..b84f5cf 100644
--- a/lib/Sema/CSDiag.cpp
+++ b/lib/Sema/CSDiag.cpp
@@ -3537,8 +3537,6 @@
               CS.getType(ArgExpr)->hasParenSugar()) &&
              "unexpected argument expression type");
       insertLoc = ArgExpr->getLoc();
-
-      // Can't be ArgumentShuffleExpr because this argExpr is not yet resolved.
     }
 
     assert(insertLoc.isValid() && "missing argument after trailing closure?");
diff --git a/lib/Sema/CSGen.cpp b/lib/Sema/CSGen.cpp
index b4a2805..61899f9 100644
--- a/lib/Sema/CSGen.cpp
+++ b/lib/Sema/CSGen.cpp
@@ -1718,7 +1718,9 @@
       for (unsigned i = 0, n = expr->getNumElements(); i != n; ++i) {
         auto *elt = expr->getElement(i);
         auto ty = CS.getType(elt);
-        auto flags = ParameterTypeFlags().withInOut(elt->isSemanticallyInOutExpr());
+        auto flags = ParameterTypeFlags()
+            .withInOut(elt->isSemanticallyInOutExpr())
+            .withVariadic(isa<VarargExpansionExpr>(elt));
         elements.push_back(TupleTypeElt(ty->getInOutObjectType(),
                                         expr->getElementName(i), flags));
       }
@@ -2438,12 +2440,7 @@
       CS.addConstraint(ConstraintKind::Conversion,
                        CS.getType(expr->getSubExpr()), array,
                        CS.getConstraintLocator(expr));
-
-      // The apparent type of the expression is the element type, as far as
-      // the type-checker is concerned.  When this becomes a real feature,
-      // we should syntactically restrict these expressions to only appear
-      // in specific positions.
-      return element;
+      return array;
     }
 
     Type visitDynamicTypeExpr(DynamicTypeExpr *expr) {
@@ -2455,7 +2452,15 @@
     }
 
     Type visitOpaqueValueExpr(OpaqueValueExpr *expr) {
-      return expr->getType();
+      llvm_unreachable("Already type checked");
+    }
+
+    Type visitDefaultArgumentExpr(DefaultArgumentExpr *expr) {
+      llvm_unreachable("Already type checked");
+    }
+
+    Type visitCallerDefaultArgumentExpr(CallerDefaultArgumentExpr *expr) {
+      llvm_unreachable("Already type checked");
     }
 
     Type visitApplyExpr(ApplyExpr *expr) {
@@ -3178,6 +3183,9 @@
   /// This is necessary because Sema fills in too much type information before
   /// the type-checker runs, causing redundant work, and for expression that
   /// have already been typechecked and may contain unhandled AST nodes.
+  ///
+  /// FIXME: Remove this one we no longer re-type check expressions during
+  /// diagnostics and code completion.
   class SanitizeExpr : public ASTWalker {
     ConstraintSystem &CS;
     TypeChecker &TC;
@@ -3259,11 +3267,70 @@
           EPE->setSemanticExpr(nullptr);
         }
 
+        // Strip default arguments and varargs from type-checked call
+        // argument lists.
+        if (isa<ParenExpr>(expr) || isa<TupleExpr>(expr)) {
+          if (shouldSanitizeArgumentList(expr))
+            expr = sanitizeArgumentList(expr);
+        }
+
         // Now, we're ready to walk into sub expressions.
         return {true, expr};
       }
     }
 
+    bool isSyntheticArgumentExpr(const Expr *expr) {
+      if (isa<DefaultArgumentExpr>(expr) ||
+          isa<CallerDefaultArgumentExpr>(expr))
+        return true;
+
+      if (auto *varargExpr = dyn_cast<VarargExpansionExpr>(expr))
+        if (isa<ArrayExpr>(varargExpr->getSubExpr()))
+          return true;
+
+      return false;
+    }
+
+    bool shouldSanitizeArgumentList(const Expr *expr) {
+      if (auto *parenExpr = dyn_cast<ParenExpr>(expr)) {
+        return isSyntheticArgumentExpr(parenExpr->getSubExpr());
+      } else if (auto *tupleExpr = dyn_cast<TupleExpr>(expr)) {
+        for (auto *arg : tupleExpr->getElements()) {
+          if (isSyntheticArgumentExpr(arg))
+            return true;
+        }
+
+        return false;
+      } else {
+        return isSyntheticArgumentExpr(expr);
+      }
+    }
+
+    Expr *sanitizeArgumentList(Expr *original) {
+      auto argList = getOriginalArgumentList(original);
+
+      if (argList.args.size() == 1 &&
+          argList.labels[0].empty() &&
+          !isa<VarargExpansionExpr>(argList.args[0])) {
+        auto *result =
+          new (TC.Context) ParenExpr(argList.lParenLoc,
+                                     argList.args[0],
+                                     argList.rParenLoc,
+                                     argList.hasTrailingClosure);
+        result->setImplicit();
+        return result;
+      }
+
+      return TupleExpr::create(TC.Context,
+                               argList.lParenLoc,
+                               argList.args,
+                               argList.labels,
+                               argList.labelLocs,
+                               argList.rParenLoc,
+                               argList.hasTrailingClosure,
+                               /*implicit=*/true);
+    }
+
     Expr *walkToExprPost(Expr *expr) override {
       if (CS.hasType(expr)) {
         Type type = CS.getType(expr);
@@ -3777,3 +3844,58 @@
   }
   return Result;
 }
+
+OriginalArgumentList
+swift::getOriginalArgumentList(Expr *expr) {
+  OriginalArgumentList result;
+
+  auto add = [&](Expr *arg, Identifier label, SourceLoc labelLoc) {
+    if (isa<DefaultArgumentExpr>(arg) ||
+        isa<CallerDefaultArgumentExpr>(arg)) {
+      return;
+    }
+
+    if (auto *varargExpr = dyn_cast<VarargExpansionExpr>(arg)) {
+      if (auto *arrayExpr = dyn_cast<ArrayExpr>(varargExpr->getSubExpr())) {
+        for (auto *elt : arrayExpr->getElements()) {
+          result.args.push_back(elt);
+          result.labels.push_back(label);
+          result.labelLocs.push_back(labelLoc);
+
+          label = Identifier();
+          labelLoc = SourceLoc();
+        }
+
+        return;
+      }
+    }
+
+    result.args.push_back(arg);
+    result.labels.push_back(label);
+    result.labelLocs.push_back(labelLoc);
+  };
+
+  if (auto *parenExpr = dyn_cast<ParenExpr>(expr)) {
+    result.lParenLoc = parenExpr->getLParenLoc();
+    result.rParenLoc = parenExpr->getRParenLoc();
+    result.hasTrailingClosure = parenExpr->hasTrailingClosure();
+    add(parenExpr->getSubExpr(), Identifier(), SourceLoc());
+  } else if (auto *tupleExpr = dyn_cast<TupleExpr>(expr)) {
+    result.lParenLoc = tupleExpr->getLParenLoc();
+    result.rParenLoc = tupleExpr->getRParenLoc();
+    result.hasTrailingClosure = tupleExpr->hasTrailingClosure();
+
+    auto args = tupleExpr->getElements();
+    auto labels = tupleExpr->getElementNames();
+    auto labelLocs = tupleExpr->getElementNameLocs();
+    for (unsigned i = 0, e = args.size(); i != e; ++i) {
+      // Implicit TupleExprs don't always store label locations.
+      add(args[i], labels[i],
+          labelLocs.empty() ? SourceLoc() : labelLocs[i]);
+    }
+  } else {
+    add(expr, Identifier(), SourceLoc());
+  }
+
+  return result;
+}
\ No newline at end of file
diff --git a/lib/Sema/CSSimplify.cpp b/lib/Sema/CSSimplify.cpp
index 8cb349f..f9ebb40 100644
--- a/lib/Sema/CSSimplify.cpp
+++ b/lib/Sema/CSSimplify.cpp
@@ -390,6 +390,13 @@
       // Record the first argument for the variadic.
       parameterBindings[paramIdx].push_back(*claimed);
 
+      // If the argument is itself variadic, we're forwarding varargs
+      // with a VarargExpansionExpr; don't collect any more arguments.
+      if (args[*claimed].isVariadic()) {
+        skipClaimedArgs();
+        return;
+      }
+
       auto currentNextArgIdx = nextArgIdx;
       {
         nextArgIdx = *claimed;
diff --git a/lib/Sema/CodeSynthesis.cpp b/lib/Sema/CodeSynthesis.cpp
index 55e7576..1770ba0 100644
--- a/lib/Sema/CodeSynthesis.cpp
+++ b/lib/Sema/CodeSynthesis.cpp
@@ -457,7 +457,8 @@
   }
   
   // A single unlabeled value is not a tuple.
-  if (args.size() == 1 && labels[0].empty()) {
+  if (args.size() == 1 && labels[0].empty() &&
+      !isa<VarargExpansionExpr>(args[0])) {
     return new (ctx) ParenExpr(SourceLoc(), args[0], SourceLoc(),
                                /*hasTrailingClosure=*/false);
   }
diff --git a/lib/Sema/ConstraintSystem.cpp b/lib/Sema/ConstraintSystem.cpp
index 91aacee..990e99a 100644
--- a/lib/Sema/ConstraintSystem.cpp
+++ b/lib/Sema/ConstraintSystem.cpp
@@ -490,47 +490,64 @@
     // info than that, unlike a typealias
   }
 
+  if (!parentTy)
+    return;
+
   // If this decl is generic, the constraints are handled when the generic
   // parameters are applied, so we don't have to handle them here (which makes
   // getting the right substitution maps easier).
-  if (decl && !decl->isGeneric()) {
-    auto extension = dyn_cast<ExtensionDecl>(decl->getDeclContext());
-    if (parentTy && extension && extension->isConstrainedExtension()) {
-      auto contextSubMap = parentTy->getContextSubstitutionMap(
-          extension->getParentModule(),
-          extension->getSelfNominalTypeDecl());
-      if (!subMap) {
-        // The substitution map wasn't set above, meaning we should grab the map
-        // for the extension itself.
-        subMap = parentTy->getContextSubstitutionMap(
-            extension->getParentModule(), extension);
-      }
+  if (!decl || decl->isGeneric())
+    return;
 
-      if (auto *signature = decl->getGenericSignature()) {
-        cs.openGenericRequirements(
-            extension, signature, /*skipProtocolSelfConstraint*/ true, locator,
-            [&](Type type) {
-              // Why do we look in two substitution maps? We have to use the
-              // context substitution map to find types, because we need to
-              // avoid thinking about them when handling the constraints, or all
-              // the requirements in the signature become tautologies (if the
-              // extension has 'T == Int', subMap will map T -> Int, so the
-              // requirement becomes Int == Int no matter what the actual types
-              // are here). However, we need the conformances for the extension
-              // because the requirements might look like `T: P, T.U: Q`, where
-              // U is an associated type of protocol P.
-              return type.subst(QuerySubstitutionMap{contextSubMap},
-                                LookUpConformanceInSubstitutionMap(subMap),
-                                SubstFlags::UseErrorType);
-            });
-      }
+  // struct A<T> {
+  //   let foo: [T]
+  // }
+  //
+  // extension A : Codable where T: Codable {
+  //   enum CodingKeys: String, CodingKey {
+  //     case foo = "foo"
+  //   }
+  // }
+  //
+  // Reference to `A.CodingKeys.foo` would point to `A` as an
+  // unbound generic type. Conditional requirements would be
+  // added when `A` is "opened". Les delay this check until then.
+  if (parentTy->hasUnboundGenericType())
+    return;
+
+  auto extension = dyn_cast<ExtensionDecl>(decl->getDeclContext());
+  if (extension && extension->isConstrainedExtension()) {
+    auto contextSubMap = parentTy->getContextSubstitutionMap(
+        extension->getParentModule(), extension->getSelfNominalTypeDecl());
+    if (!subMap) {
+      // The substitution map wasn't set above, meaning we should grab the map
+      // for the extension itself.
+      subMap = parentTy->getContextSubstitutionMap(extension->getParentModule(),
+                                                   extension);
     }
 
-    // And now make sure sure the parent is okay, for things like X<T>.Y.Z.
-    if (parentTy) {
-      checkNestedTypeConstraints(cs, parentTy, locator);
+    if (auto *signature = decl->getGenericSignature()) {
+      cs.openGenericRequirements(
+          extension, signature, /*skipProtocolSelfConstraint*/ true, locator,
+          [&](Type type) {
+            // Why do we look in two substitution maps? We have to use the
+            // context substitution map to find types, because we need to
+            // avoid thinking about them when handling the constraints, or all
+            // the requirements in the signature become tautologies (if the
+            // extension has 'T == Int', subMap will map T -> Int, so the
+            // requirement becomes Int == Int no matter what the actual types
+            // are here). However, we need the conformances for the extension
+            // because the requirements might look like `T: P, T.U: Q`, where
+            // U is an associated type of protocol P.
+            return type.subst(QuerySubstitutionMap{contextSubMap},
+                              LookUpConformanceInSubstitutionMap(subMap),
+                              SubstFlags::UseErrorType);
+          });
     }
   }
+
+  // And now make sure sure the parent is okay, for things like X<T>.Y.Z.
+  checkNestedTypeConstraints(cs, parentTy, locator);
 }
 
 Type ConstraintSystem::openUnboundGenericType(
diff --git a/lib/Sema/LookupVisibleDecls.cpp b/lib/Sema/LookupVisibleDecls.cpp
index 9ecfd2b..f0395e7 100644
--- a/lib/Sema/LookupVisibleDecls.cpp
+++ b/lib/Sema/LookupVisibleDecls.cpp
@@ -968,7 +968,10 @@
         return;
       }
 
-      SF->getImportedModules(extraImports, ModuleDecl::ImportFilter::Private);
+      ModuleDecl::ImportFilter importFilter;
+      importFilter |= ModuleDecl::ImportFilterKind::Private;
+      importFilter |= ModuleDecl::ImportFilterKind::ImplementationOnly;
+      SF->getImportedModules(extraImports, importFilter);
     }
   }
 
diff --git a/lib/Sema/MiscDiagnostics.cpp b/lib/Sema/MiscDiagnostics.cpp
index c766e02..dfffc6d 100644
--- a/lib/Sema/MiscDiagnostics.cpp
+++ b/lib/Sema/MiscDiagnostics.cpp
@@ -25,6 +25,7 @@
 #include "swift/Basic/StringExtras.h"
 #include "swift/Parse/Lexer.h"
 #include "swift/Parse/Parser.h"
+#include "swift/Sema/IDETypeChecking.h"
 #include "llvm/ADT/MapVector.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/Support/SaveAndRestore.h"
@@ -145,11 +146,6 @@
       if (isa<TypeExpr>(Base))
         checkUseOfMetaTypeName(Base);
 
-      if (auto *ASE = dyn_cast<ArgumentShuffleExpr>(E)) {
-        if (CallArgs.count(ASE))
-          CallArgs.insert(ASE->getSubExpr());
-      }
-
       if (auto *SE = dyn_cast<SubscriptExpr>(E)) {
         CallArgs.insert(SE->getIndex());
 
@@ -329,11 +325,6 @@
     static void argExprVisitArguments(Expr* arg,
                                       llvm::function_ref
                                         <void(unsigned, Expr*)> fn) {
-      // The argument could be shuffled if it includes default arguments,
-      // label differences, or other exciting things like that.
-      if (auto *ASE = dyn_cast<ArgumentShuffleExpr>(arg))
-        arg = ASE->getSubExpr();
-
       // The argument is either a ParenExpr or TupleExpr.
       if (auto *TE = dyn_cast<TupleExpr>(arg)) {
         auto elts = TE->getElements();
@@ -1688,7 +1679,7 @@
 /// Diagnose an argument labeling issue, returning true if we successfully
 /// diagnosed the issue.
 bool swift::diagnoseArgumentLabelError(ASTContext &ctx,
-                                       const Expr *expr,
+                                       Expr *expr,
                                        ArrayRef<Identifier> newNames,
                                        bool isSubscript,
                                        InFlightDiagnostic *existingDiag) {
@@ -1700,56 +1691,26 @@
   };
 
   auto &diags = ctx.Diags;
-  auto tuple = dyn_cast<TupleExpr>(expr);
-  if (!tuple) {
-    if (newNames[0].empty()) {
-      // We don't know what to do with this.
-      return false;
-    }
 
-    llvm::SmallString<16> str;
-    // If the diagnostic is local, flush it before returning.
-    // This makes sure it's emitted before 'str' is destroyed.
-    SWIFT_DEFER { diagOpt.reset(); };
-
-    // This is a scalar-to-tuple conversion. Add the name. We "know"
-    // that we're inside a ParenExpr, because ParenExprs are required
-    // by the syntax and locator resolution looks through on level of
-    // them.
-
-    // Look through the paren expression, if there is one.
-    if (auto parenExpr = dyn_cast<ParenExpr>(expr))
-      expr = parenExpr->getSubExpr();
-
-    str += newNames[0].str();
-    str += ": ";
-    if (!existingDiag) {
-      diagOpt.emplace(diags.diagnose(expr->getStartLoc(),
-                                     diag::missing_argument_labels,
-                                     false, str.str().drop_back(),
-                                     isSubscript));
-    }
-    getDiag().fixItInsert(expr->getStartLoc(), str);
-    return true;
-  }
+  OriginalArgumentList argList = getOriginalArgumentList(expr);
 
   // Figure out how many extraneous, missing, and wrong labels are in
   // the call.
   unsigned numExtra = 0, numMissing = 0, numWrong = 0;
-  unsigned n = std::max(tuple->getNumElements(), (unsigned)newNames.size());
+  unsigned n = std::max(argList.args.size(), newNames.size());
 
   llvm::SmallString<16> missingBuffer;
   llvm::SmallString<16> extraBuffer;
   for (unsigned i = 0; i != n; ++i) {
     Identifier oldName;
-    if (i < tuple->getNumElements())
-      oldName = tuple->getElementName(i);
+    if (i < argList.args.size())
+      oldName = argList.labels[i];
     Identifier newName;
     if (i < newNames.size())
       newName = newNames[i];
 
     if (oldName == newName ||
-        (tuple->hasTrailingClosure() && i == tuple->getNumElements()-1))
+        (argList.hasTrailingClosure && i == argList.args.size()-1))
       continue;
 
     if (oldName.empty()) {
@@ -1774,8 +1735,8 @@
   if (!existingDiag) {
     bool plural = (numMissing + numExtra + numWrong) > 1;
     if (numWrong > 0 || (numMissing > 0 && numExtra > 0)) {
-      for (unsigned i = 0, n = tuple->getNumElements(); i != n; ++i) {
-        auto haveName = tuple->getElementName(i);
+      for (unsigned i = 0, n = argList.args.size(); i != n; ++i) {
+        auto haveName = argList.labels[i];
         if (haveName.empty())
           haveBuffer += '_';
         else
@@ -1813,19 +1774,19 @@
 
   // Emit Fix-Its to correct the names.
   auto &diag = getDiag();
-  for (unsigned i = 0, n = tuple->getNumElements(); i != n; ++i) {
-    Identifier oldName = tuple->getElementName(i);
+  for (unsigned i = 0, n = argList.args.size(); i != n; ++i) {
+    Identifier oldName = argList.labels[i];
     Identifier newName;
     if (i < newNames.size())
       newName = newNames[i];
 
-    if (oldName == newName || (i == n-1 && tuple->hasTrailingClosure()))
+    if (oldName == newName || (i == n-1 && argList.hasTrailingClosure))
       continue;
 
     if (newName.empty()) {
       // Delete the old name.
-      diag.fixItRemoveChars(tuple->getElementNameLocs()[i],
-                            tuple->getElement(i)->getStartLoc());
+      diag.fixItRemoveChars(argList.labelLocs[i],
+                            argList.args[i]->getStartLoc());
       continue;
     }
 
@@ -1840,12 +1801,12 @@
     if (oldName.empty()) {
       // Insert the name.
       newStr += ": ";
-      diag.fixItInsert(tuple->getElement(i)->getStartLoc(), newStr);
+      diag.fixItInsert(argList.args[i]->getStartLoc(), newStr);
       continue;
     }
 
     // Change the name.
-    diag.fixItReplace(tuple->getElementNameLocs()[i], newStr);
+    diag.fixItReplace(argList.labelLocs[i], newStr);
   }
 
   // If the diagnostic is local, flush it before returning.
@@ -2941,32 +2902,29 @@
                                         const CallExpr *call,
                                         Identifier closureLabel) {
   auto argsExpr = call->getArg();
-  if (auto ASE = dyn_cast<ArgumentShuffleExpr>(argsExpr))
-    argsExpr = ASE->getSubExpr();
 
   SmallString<32> replacement;
   SourceLoc lastLoc;
   SourceRange closureRange;
-  if (auto PE = dyn_cast<ParenExpr>(argsExpr)) {
-    assert(PE->hasTrailingClosure() && "must have trailing closure");
-    closureRange = PE->getSubExpr()->getSourceRange();
-    lastLoc = PE->getLParenLoc(); // e.g funcName() { 1 }
+
+  auto argList = getOriginalArgumentList(argsExpr);
+
+  assert(argList.args.size() >= 1 && "must have at least one argument");
+
+  if (argList.args.size() == 1) {
+    closureRange = argList.args[0]->getSourceRange();
+    lastLoc = argList.lParenLoc; // e.g funcName() { 1 }
     if (!lastLoc.isValid()) {
       // Bare trailing closure: e.g. funcName { 1 }
       replacement = "(";
       lastLoc = call->getFn()->getEndLoc();
     }
-  } else if (auto TE = dyn_cast<TupleExpr>(argsExpr)) {
-    // Tuple + trailing closure: e.g. funcName(x: 1) { 1 }
-    assert(TE->hasTrailingClosure() && "must have trailing closure");
-    auto numElements = TE->getNumElements();
-    assert(numElements >= 2 && "Unexpected num of elements in TupleExpr");
-    closureRange = TE->getElement(numElements - 1)->getSourceRange();
-    lastLoc = TE->getElement(numElements - 2)->getEndLoc();
-    replacement = ", ";
   } else {
-    // Can't be here.
-    return;
+    // Tuple + trailing closure: e.g. funcName(x: 1) { 1 }
+    auto numElements = argList.args.size();
+    closureRange = argList.args[numElements - 1]->getSourceRange();
+    lastLoc = argList.args[numElements - 2]->getEndLoc();
+    replacement = ", ";
   }
 
   // Add argument label of the closure.
@@ -2997,9 +2955,6 @@
       // Ignore invalid argument type. Some diagnostics are already emitted.
       if (!argsTy || argsTy->hasError()) return;
 
-      if (auto ASE = dyn_cast<ArgumentShuffleExpr>(argsExpr))
-        argsExpr = ASE->getSubExpr();
-
       SourceLoc closureLoc;
       if (auto PE = dyn_cast<ParenExpr>(argsExpr))
         closureLoc = PE->getSubExpr()->getStartLoc();
diff --git a/lib/Sema/MiscDiagnostics.h b/lib/Sema/MiscDiagnostics.h
index 358376b..5d0c443 100644
--- a/lib/Sema/MiscDiagnostics.h
+++ b/lib/Sema/MiscDiagnostics.h
@@ -65,7 +65,7 @@
 ///
 /// \returns true if the issue was diagnosed
 bool diagnoseArgumentLabelError(ASTContext &ctx,
-                                const Expr *expr,
+                                Expr *expr,
                                 ArrayRef<Identifier> newNames,
                                 bool isSubscript,
                                 InFlightDiagnostic *existingDiag = nullptr);
diff --git a/lib/Sema/NameBinding.cpp b/lib/Sema/NameBinding.cpp
index 1248f90..e063518 100644
--- a/lib/Sema/NameBinding.cpp
+++ b/lib/Sema/NameBinding.cpp
@@ -252,6 +252,18 @@
   if (privateImportAttr)
     options |= SourceFile::ImportFlags::PrivateImport;
 
+  auto *implementationOnlyAttr =
+      ID->getAttrs().getAttribute<ImplementationOnlyAttr>();
+  if (implementationOnlyAttr) {
+    if (options.contains(SourceFile::ImportFlags::Exported)) {
+      diagnose(ID, diag::import_implementation_cannot_be_exported,
+               topLevelModule->getName())
+        .fixItRemove(implementationOnlyAttr->getRangeWithAt());
+    } else {
+      options |= SourceFile::ImportFlags::ImplementationOnly;
+    }
+  }
+
   imports.push_back(SourceFile::ImportedModuleDesc(
       {ID->getDeclPath(), M}, options, privateImportFileName));
 
diff --git a/lib/Sema/PlaygroundTransform.cpp b/lib/Sema/PlaygroundTransform.cpp
index c4e6778..56566fa 100644
--- a/lib/Sema/PlaygroundTransform.cpp
+++ b/lib/Sema/PlaygroundTransform.cpp
@@ -344,10 +344,6 @@
       return dyn_cast<DeclRefExpr>(
           inout->getSubExpr()->getSemanticsProvidingExpr());
 
-      // Drill through argument shuffles, ignoring non-default-argument inouts.
-    } else if (auto shuffle = dyn_cast<ArgumentShuffleExpr>(E)) {
-      return digForInoutDeclRef(shuffle->getSubExpr());
-
       // Try to find a unique inout argument in a tuple.
     } else if (auto tuple = dyn_cast<TupleExpr>(E)) {
       DeclRefExpr *uniqueRef = nullptr;
diff --git a/lib/Sema/TypeCheckAttr.cpp b/lib/Sema/TypeCheckAttr.cpp
index 457d14a..cd3a18c 100644
--- a/lib/Sema/TypeCheckAttr.cpp
+++ b/lib/Sema/TypeCheckAttr.cpp
@@ -20,8 +20,10 @@
 #include "swift/AST/GenericSignatureBuilder.h"
 #include "swift/AST/ASTVisitor.h"
 #include "swift/AST/ClangModuleLoader.h"
+#include "swift/AST/DiagnosticsParse.h"
 #include "swift/AST/GenericEnvironment.h"
 #include "swift/AST/NameLookup.h"
+#include "swift/AST/NameLookupRequests.h"
 #include "swift/AST/ParameterList.h"
 #include "swift/AST/TypeCheckRequests.h"
 #include "swift/AST/Types.h"
@@ -87,6 +89,7 @@
   IGNORED_ATTR(ForbidSerializingReference)
   IGNORED_ATTR(Frozen)
   IGNORED_ATTR(HasStorage)
+  IGNORED_ATTR(ImplementationOnly)
   IGNORED_ATTR(Implements)
   IGNORED_ATTR(ImplicitlyUnwrappedOptional)
   IGNORED_ATTR(Infix)
@@ -122,6 +125,7 @@
   IGNORED_ATTR(WeakLinked)
   IGNORED_ATTR(DynamicReplacement)
   IGNORED_ATTR(PrivateImport)
+  IGNORED_ATTR(Custom)
 #undef IGNORED_ATTR
 
   void visitAlignmentAttr(AlignmentAttr *attr) {
@@ -744,6 +748,7 @@
     IGNORED_ATTR(Consuming)
     IGNORED_ATTR(Convenience)
     IGNORED_ATTR(Dynamic)
+    IGNORED_ATTR(DynamicReplacement)
     IGNORED_ATTR(Effects)
     IGNORED_ATTR(Exported)
     IGNORED_ATTR(ForbidSerializingReference)
@@ -752,6 +757,7 @@
     IGNORED_ATTR(IBDesignable)
     IGNORED_ATTR(IBInspectable)
     IGNORED_ATTR(IBOutlet) // checked early.
+    IGNORED_ATTR(ImplementationOnly)
     IGNORED_ATTR(ImplicitlyUnwrappedOptional)
     IGNORED_ATTR(Indirect)
     IGNORED_ATTR(Inline)
@@ -768,6 +774,7 @@
     IGNORED_ATTR(ObjCRuntimeName)
     IGNORED_ATTR(Optional)
     IGNORED_ATTR(Override)
+    IGNORED_ATTR(PrivateImport)
     IGNORED_ATTR(RawDocComment)
     IGNORED_ATTR(ReferenceOwnership)
     IGNORED_ATTR(RequiresStoredPropertyInits)
@@ -781,8 +788,6 @@
     IGNORED_ATTR(Transparent)
     IGNORED_ATTR(WarnUnqualifiedAccess)
     IGNORED_ATTR(WeakLinked)
-    IGNORED_ATTR(DynamicReplacement)
-    IGNORED_ATTR(PrivateImport)
 #undef IGNORED_ATTR
 
   void visitAvailableAttr(AvailableAttr *attr);
@@ -833,6 +838,7 @@
   void visitFrozenAttr(FrozenAttr *attr);
 
   void visitNonOverrideAttr(NonOverrideAttr *attr);
+  void visitCustomAttr(CustomAttr *attr);
 };
 } // end anonymous namespace
 
@@ -2397,6 +2403,36 @@
   }
 }
 
+void AttributeChecker::visitCustomAttr(CustomAttr *attr) {
+  auto dc = D->getInnermostDeclContext();
+
+  // Figure out which nominal declaration this custom attribute refers to.
+  auto nominal = evaluateOrDefault(
+    TC.Context.evaluator, CustomAttrNominalRequest{attr, dc}, nullptr);
+
+  // If there is no nominal type with this name, complain about this being
+  // an unknown attribute.
+  if (!nominal) {
+    std::string typeName;
+    if (auto typeRepr = attr->getTypeLoc().getTypeRepr()) {
+      llvm::raw_string_ostream out(typeName);
+      typeRepr->print(out);
+    } else {
+      typeName = attr->getTypeLoc().getType().getString();
+    }
+
+    TC.diagnose(attr->getLocation(), diag::unknown_attribute,
+                typeName);
+    attr->setInvalid();
+    return;
+  }
+
+  TC.diagnose(attr->getLocation(), diag::nominal_type_not_attribute,
+              nominal->getDescriptiveKind(), nominal->getFullName());
+  nominal->diagnose(diag::decl_declared_here, nominal->getFullName());
+  attr->setInvalid();
+}
+
 void TypeChecker::checkDeclAttributes(Decl *D) {
   AttributeChecker Checker(*this, D);
 
diff --git a/lib/Sema/TypeCheckAvailability.cpp b/lib/Sema/TypeCheckAvailability.cpp
index 24beba9..a537324 100644
--- a/lib/Sema/TypeCheckAvailability.cpp
+++ b/lib/Sema/TypeCheckAvailability.cpp
@@ -27,6 +27,7 @@
 #include "swift/Basic/StringExtras.h"
 #include "swift/Parse/Lexer.h"
 #include "swift/Parse/Parser.h"
+#include "swift/Sema/IDETypeChecking.h"
 #include "llvm/ADT/MapVector.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/Support/SaveAndRestore.h"
@@ -1544,77 +1545,68 @@
     SourceLoc removeRangeStart;
     SourceLoc removeRangeEnd;
 
-    const Expr *argExpr = call->getArg();
-    if (auto args = dyn_cast<TupleExpr>(argExpr)) {
-      size_t numElementsWithinParens = args->getNumElements();
-      numElementsWithinParens -= args->hasTrailingClosure();
-      if (selfIndex >= numElementsWithinParens)
+    auto *argExpr = call->getArg();
+    auto argList = getOriginalArgumentList(argExpr);
+
+    size_t numElementsWithinParens = argList.args.size();
+    numElementsWithinParens -= argList.hasTrailingClosure;
+    if (selfIndex >= numElementsWithinParens)
+      return;
+
+    if (parsed.IsGetter) {
+      if (numElementsWithinParens != 1)
         return;
+    } else if (parsed.IsSetter) {
+      if (numElementsWithinParens != 2)
+        return;
+    } else {
+      if (parsed.ArgumentLabels.size() != argList.args.size() - 1)
+        return;
+    }
 
-      if (parsed.IsGetter) {
-        if (numElementsWithinParens != 1)
-          return;
-      } else if (parsed.IsSetter) {
-        if (numElementsWithinParens != 2)
-          return;
+    selfExpr = argList.args[selfIndex];
+
+    if (selfIndex + 1 == numElementsWithinParens) {
+      if (selfIndex > 0) {
+        // Remove from the previous comma to the close-paren (half-open).
+        removeRangeStart = argList.args[selfIndex-1]->getEndLoc();
+        removeRangeStart = Lexer::getLocForEndOfToken(sourceMgr,
+                                                      removeRangeStart);
       } else {
-        if (parsed.ArgumentLabels.size() != args->getNumElements() - 1)
-          return;
+        // Remove from after the open paren to the close paren (half-open).
+        removeRangeStart = Lexer::getLocForEndOfToken(sourceMgr,
+                                                      argExpr->getStartLoc());
       }
 
-      selfExpr = args->getElement(selfIndex);
-
-      if (selfIndex + 1 == numElementsWithinParens) {
-        if (selfIndex > 0) {
-          // Remove from the previous comma to the close-paren (half-open).
-          removeRangeStart = args->getElement(selfIndex-1)->getEndLoc();
-          removeRangeStart = Lexer::getLocForEndOfToken(sourceMgr,
-                                                        removeRangeStart);
-        } else {
-          // Remove from after the open paren to the close paren (half-open).
-          removeRangeStart = Lexer::getLocForEndOfToken(sourceMgr,
-                                                        argExpr->getStartLoc());
-        }
-
-        // Prefer the r-paren location, so that we get the right behavior when
-        // there's a trailing closure, but handle some implicit cases too.
-        removeRangeEnd = args->getRParenLoc();
-        if (removeRangeEnd.isInvalid())
-          removeRangeEnd = args->getEndLoc();
-
-      } else {
-        // Remove from the label to the start of the next argument (half-open).
-        SourceLoc labelLoc = args->getElementNameLoc(selfIndex);
-        if (labelLoc.isValid())
-          removeRangeStart = labelLoc;
-        else
-          removeRangeStart = selfExpr->getStartLoc();
-
-        SourceLoc nextLabelLoc = args->getElementNameLoc(selfIndex + 1);
-        if (nextLabelLoc.isValid())
-          removeRangeEnd = nextLabelLoc;
-        else
-          removeRangeEnd = args->getElement(selfIndex + 1)->getStartLoc();
-      }
-
-      // Avoid later argument label fix-its for this argument.
-      if (!parsed.isPropertyAccessor()) {
-        Identifier oldLabel = args->getElementName(selfIndex);
-        StringRef oldLabelStr;
-        if (!oldLabel.empty())
-          oldLabelStr = oldLabel.str();
-        parsed.ArgumentLabels.insert(parsed.ArgumentLabels.begin() + selfIndex,
-                                     oldLabelStr);
-      }
+      // Prefer the r-paren location, so that we get the right behavior when
+      // there's a trailing closure, but handle some implicit cases too.
+      removeRangeEnd = argList.rParenLoc;
+      if (removeRangeEnd.isInvalid())
+        removeRangeEnd = argExpr->getEndLoc();
 
     } else {
-      if (selfIndex != 0 || !parsed.ArgumentLabels.empty())
-        return;
-      selfExpr = cast<ParenExpr>(argExpr)->getSubExpr();
-      // Remove from after the open paren to the close paren (half-open).
-      removeRangeStart = Lexer::getLocForEndOfToken(sourceMgr,
-                                                    argExpr->getStartLoc());
-      removeRangeEnd = argExpr->getEndLoc();
+      // Remove from the label to the start of the next argument (half-open).
+      SourceLoc labelLoc = argList.labelLocs[selfIndex];
+      if (labelLoc.isValid())
+        removeRangeStart = labelLoc;
+      else
+        removeRangeStart = selfExpr->getStartLoc();
+
+      SourceLoc nextLabelLoc = argList.labelLocs[selfIndex + 1];
+      if (nextLabelLoc.isValid())
+        removeRangeEnd = nextLabelLoc;
+      else
+        removeRangeEnd = argList.args[selfIndex + 1]->getStartLoc();
+    }
+
+    // Avoid later argument label fix-its for this argument.
+    if (!parsed.isPropertyAccessor()) {
+      Identifier oldLabel = argList.labels[selfIndex];
+      StringRef oldLabelStr;
+      if (!oldLabel.empty())
+        oldLabelStr = oldLabel.str();
+      parsed.ArgumentLabels.insert(parsed.ArgumentLabels.begin() + selfIndex,
+                                    oldLabelStr);
     }
 
     if (auto *inoutSelf = dyn_cast<InOutExpr>(selfExpr))
@@ -1698,7 +1690,9 @@
   if (!call || !isa<CallExpr>(call))
     return;
 
-  const Expr *argExpr = call->getArg();
+  auto *argExpr = call->getArg();
+  auto argList = getOriginalArgumentList(argExpr);
+
   if (parsed.IsGetter) {
     diag.fixItRemove(argExpr->getSourceRange());
     return;
@@ -1707,16 +1701,16 @@
   if (parsed.IsSetter) {
     const Expr *newValueExpr = nullptr;
 
-    if (auto args = dyn_cast<TupleExpr>(argExpr)) {
+    if (argList.args.size() >= 1) {
       size_t newValueIndex = 0;
       if (parsed.isInstanceMember()) {
         assert(parsed.SelfIndex.getValue() == 0 ||
                parsed.SelfIndex.getValue() == 1);
         newValueIndex = !parsed.SelfIndex.getValue();
       }
-      newValueExpr = args->getElement(newValueIndex);
+      newValueExpr = argList.args[newValueIndex];
     } else {
-      newValueExpr = cast<ParenExpr>(argExpr)->getSubExpr();
+      newValueExpr = argList.args[0];
     }
 
     diag.fixItReplaceChars(argExpr->getStartLoc(), newValueExpr->getStartLoc(),
@@ -1738,33 +1732,28 @@
     return labelStr.empty() ? Identifier() : ctx.getIdentifier(labelStr);
   });
 
-  if (auto args = dyn_cast<ArgumentShuffleExpr>(argExpr)) {
-    argExpr = args->getSubExpr();
+  // Coerce the `argumentLabelIDs` to the user supplied arguments.
+  // e.g:
+  //   @available(.., renamed: "new(w:x:y:z:)")
+  //   func old(a: Int, b: Int..., c: String="", d: Int=0){}
+  //   old(a: 1, b: 2, 3, 4, d: 5)
+  // coerce
+  //   argumentLabelIDs = {"w", "x", "y", "z"}
+  // to
+  //   argumentLabelIDs = {"w", "x", "", "", "z"}
+  auto I = argumentLabelIDs.begin();
 
-    // Coerce the `argumentLabelIDs` to the user supplied arguments.
-    // e.g:
-    //   @available(.., renamed: "new(w:x:y:z:)")
-    //   func old(a: Int, b: Int..., c: String="", d: Int=0){}
-    //   old(a: 1, b: 2, 3, 4, d: 5)
-    // coerce
-    //   argumentLabelIDs = {"w", "x", "y", "z"}
-    // to
-    //   argumentLabelIDs = {"w", "x", "", "", "z"}
-    auto elementMap = args->getElementMapping();
-    if (elementMap.size() != argumentLabelIDs.size()) {
-      // Mismatched lengths; give up.
+  auto updateLabelsForArg = [&](Expr *expr) {
+    if (isa<DefaultArgumentExpr>(expr) ||
+        isa<CallerDefaultArgumentExpr>(expr)) {
+      // Defaulted: remove param label of it.
+      I = argumentLabelIDs.erase(I);
       return;
     }
-    auto I = argumentLabelIDs.begin();
-    for (auto shuffleIdx : elementMap) {
-      switch (shuffleIdx) {
-      case ArgumentShuffleExpr::DefaultInitialize:
-      case ArgumentShuffleExpr::CallerDefaultInitialize:
-        // Defaulted: remove param label of it.
-        I = argumentLabelIDs.erase(I);
-        break;
-      case ArgumentShuffleExpr::Variadic: {
-        auto variadicArgsNum = args->getVariadicArgs().size();
+
+    if (auto *varargExpr = dyn_cast<VarargExpansionExpr>(expr)) {
+      if (auto *arrayExpr = dyn_cast<ArrayExpr>(varargExpr->getSubExpr())) {
+        auto variadicArgsNum = arrayExpr->getNumElements();
         if (variadicArgsNum == 0) {
           // No arguments: Remove param label of it.
           I = argumentLabelIDs.erase(I);
@@ -1772,65 +1761,42 @@
           // One argument: Just advance.
           ++I;
         } else {
+          ++I;
+
           // Two or more arguments: Insert empty labels after the first one.
-          I = argumentLabelIDs.insert(++I, --variadicArgsNum, Identifier());
+          variadicArgsNum--;
+          I = argumentLabelIDs.insert(I, variadicArgsNum, Identifier());
           I += variadicArgsNum;
         }
-        break;
-      }
-      default:
-        // Normal: Just advance.
-        assert(shuffleIdx == (I - argumentLabelIDs.begin()) &&
-               "SE-0060 guarantee");
-        ++I;
-        break;
+        return;
       }
     }
+
+    // Normal: Just advance.
+    ++I;
+  };
+
+  if (auto *parenExpr = dyn_cast<ParenExpr>(argExpr)) {
+    updateLabelsForArg(parenExpr->getSubExpr());
+  } else {
+    for (auto *arg : cast<TupleExpr>(argExpr)->getElements())
+      updateLabelsForArg(arg);
   }
 
-  if (auto args = dyn_cast<TupleExpr>(argExpr)) {
-    if (argumentLabelIDs.size() != args->getNumElements()) {
-      // Mismatched lengths; give up.
-      return;
-    }
+  if (argumentLabelIDs.size() != argList.args.size()) {
+    // Mismatched lengths; give up.
+    return;
+  }
 
-    auto argumentLabelsToCheck = llvm::makeArrayRef(argumentLabelIDs);
-    // The argument label for a trailing closure is ignored.
-    if (args->hasTrailingClosure())
-      argumentLabelsToCheck = argumentLabelsToCheck.drop_back();
+  auto argumentLabelsToCheck = llvm::makeArrayRef(argumentLabelIDs);
+  // The argument label for a trailing closure is ignored.
+  if (argList.hasTrailingClosure)
+    argumentLabelsToCheck = argumentLabelsToCheck.drop_back();
 
-    if (args->hasElementNames()) {
-      if (std::equal(argumentLabelsToCheck.begin(), argumentLabelsToCheck.end(),
-                     args->getElementNames().begin())) {
-        // Already matching.
-        return;
-      }
-
-    } else {
-      if (std::all_of(argumentLabelsToCheck.begin(),argumentLabelsToCheck.end(),
-                      std::mem_fn(&Identifier::empty))) {
-        // Already matching (as in, there are no labels).
-        return;
-      }
-    }
-
-  } else if (auto args = dyn_cast<ParenExpr>(argExpr)) {
-    if (args->hasTrailingClosure()) {
-      // The argument label for a trailing closure is ignored.
-      return;
-    }
-
-    if (argumentLabelIDs.size() != 1) {
-      // Mismatched lengths; give up.
-      return;
-    }
-
-    if (argumentLabelIDs.front().empty()) {
-      // Already matching (no labels).
-      return;
-    }
-  } else {
-    llvm_unreachable("Unexpected arg expression");
+  if (std::equal(argumentLabelsToCheck.begin(), argumentLabelsToCheck.end(),
+                 argList.labels.begin())) {
+    // Already matching.
+    return;
   }
 
   diagnoseArgumentLabelError(ctx, argExpr, argumentLabelIDs, false, &diag);
diff --git a/lib/Sema/TypeCheckDeclOverride.cpp b/lib/Sema/TypeCheckDeclOverride.cpp
index d9c6514..7b4f386 100644
--- a/lib/Sema/TypeCheckDeclOverride.cpp
+++ b/lib/Sema/TypeCheckDeclOverride.cpp
@@ -1320,6 +1320,8 @@
     UNINTERESTING_ATTR(WeakLinked)
     UNINTERESTING_ATTR(Frozen)
     UNINTERESTING_ATTR(HasInitialValue)
+    UNINTERESTING_ATTR(ImplementationOnly)
+    UNINTERESTING_ATTR(Custom)
 #undef UNINTERESTING_ATTR
 
     void visitAvailableAttr(AvailableAttr *attr) {
diff --git a/lib/Sema/TypeCheckError.cpp b/lib/Sema/TypeCheckError.cpp
index 60084c8..0fbbda4 100644
--- a/lib/Sema/TypeCheckError.cpp
+++ b/lib/Sema/TypeCheckError.cpp
@@ -679,6 +679,12 @@
   Classification classifyRethrowsArgument(Expr *arg, Type paramType) {
     arg = arg->getValueProvidingExpr();
 
+    if (isa<DefaultArgumentExpr>(arg) ||
+        isa<CallerDefaultArgumentExpr>(arg)) {
+      return classifyArgumentByType(arg->getType(),
+                                    PotentialReason::forDefaultArgument());
+    }
+
     // If this argument is `nil` literal or `.none`,
     // it doesn't cause the call to throw.
     if (auto *DSCE = dyn_cast<DotSyntaxCallExpr>(arg)) {
@@ -694,8 +700,6 @@
     if (auto paramTupleType = dyn_cast<TupleType>(paramType.getPointer())) {
       if (auto tuple = dyn_cast<TupleExpr>(arg)) {
         return classifyTupleRethrowsArgument(tuple, paramTupleType);
-      } else if (auto shuffle = dyn_cast<ArgumentShuffleExpr>(arg)) {
-        return classifyShuffleRethrowsArgument(shuffle, paramTupleType);
       }
 
       if (paramTupleType->getNumElements() != 1) {
@@ -709,7 +713,7 @@
 
       // FIXME: There's a case where we can end up with an ApplyExpr that
       // has a single-element-tuple argument type, but the argument is just
-      // a ClosureExpr and not a TupleExpr/ArgumentShuffleExpr.
+      // a ClosureExpr and not a TupleExpr.
       paramType = paramTupleType->getElementType(0);
     }
 
@@ -756,79 +760,6 @@
     return result;
   }
 
-  /// Classify an argument to a 'rethrows' function that's a tuple shuffle.
-  Classification classifyShuffleRethrowsArgument(ArgumentShuffleExpr *shuffle,
-                                                 TupleType *paramTupleType) {
-    auto reversedParamType =
-      reverseShuffleParamType(shuffle, paramTupleType);
-
-    // Classify the operand.
-    auto result = classifyRethrowsArgument(shuffle->getSubExpr(),
-                                           reversedParamType);
-
-    // Check for default arguments in the shuffle.
-    for (auto i : indices(shuffle->getElementMapping())) {
-      // If this element comes from the sub-expression, we've already
-      // analyzed it.  (Variadic arguments also end up here, which is
-      // correct for our purposes.)
-      auto elt = shuffle->getElementMapping()[i];
-      if (elt >= 0) {
-        // Ignore.
-
-      // Otherwise, it might come from a default argument.  It still
-      // might contribute to 'rethrows', but treat it as an opaque source.
-      } else if (elt == ArgumentShuffleExpr::DefaultInitialize ||
-                 elt == ArgumentShuffleExpr::CallerDefaultInitialize) {
-        result.merge(classifyArgumentByType(paramTupleType->getElementType(i),
-                                       PotentialReason::forDefaultArgument()));
-      }
-    }
-
-    return result;
-  }
-
-  /// Given a tuple shuffle and an original parameter type, construct
-  /// the type of the source of the tuple shuffle preserving as much
-  /// information as possible from the original parameter type.
-  Type reverseShuffleParamType(ArgumentShuffleExpr *shuffle,
-                               TupleType *origParamTupleType) {
-    SmallVector<TupleTypeElt, 4> origSrcElts;
-    if (shuffle->isSourceScalar()) {
-      origSrcElts.append(1, TupleTypeElt());
-    } else {
-      auto srcTupleType = shuffle->getSubExpr()->getType()->castTo<TupleType>();
-      origSrcElts.append(srcTupleType->getNumElements(), TupleTypeElt());
-    }
-
-    auto mapping = shuffle->getElementMapping();
-    for (unsigned destIndex = 0; destIndex != mapping.size(); ++destIndex) {
-      auto srcIndex = mapping[destIndex];
-      if (srcIndex >= 0) {
-        origSrcElts[srcIndex] = origParamTupleType->getElement(destIndex);
-      } else if (srcIndex == ArgumentShuffleExpr::DefaultInitialize ||
-                 srcIndex == ArgumentShuffleExpr::CallerDefaultInitialize) {
-        // Nothing interesting from the source expression.
-      } else if (srcIndex == ArgumentShuffleExpr::Variadic) {
-        // Variadic arguments never contribute to 'rethrows'.
-        // Assign the rest of the source elements parameter types that will
-        // cause the recursive walker to ignore them.
-        for (unsigned srcIndex : shuffle->getVariadicArgs()) {
-          assert(srcIndex >= 0 && "default-initialized variadic argument?");
-          origSrcElts[srcIndex] =
-            origParamTupleType->getASTContext().TheRawPointerType;
-        }
-      } else {
-        llvm_unreachable("bad source-element mapping!");
-      }
-    }
-
-    if (shuffle->isSourceScalar()) {
-      return origSrcElts[0].getType();
-    } else {
-      return TupleType::get(origSrcElts, origParamTupleType->getASTContext());
-    }
-  }
-
   /// Given the type of an argument, try to determine if it contains
   /// a throwing function in a way that is permitted to cause a
   /// 'rethrows' function to throw.
diff --git a/lib/Serialization/Deserialization.cpp b/lib/Serialization/Deserialization.cpp
index 963c239..92f360a 100644
--- a/lib/Serialization/Deserialization.cpp
+++ b/lib/Serialization/Deserialization.cpp
@@ -3753,35 +3753,35 @@
 
 Expected<Decl *>
 ModuleFile::getDeclChecked(DeclID DID) {
-  // Tag every deserialized ValueDecl coming out of getDeclChecked with its ID.
   if (DID == 0)
     return nullptr;
 
   assert(DID <= Decls.size() && "invalid decl ID");
   auto &declOrOffset = Decls[DID-1];
 
-  if (declOrOffset.isComplete())
-    return declOrOffset;
+  if (!declOrOffset.isComplete()) {
+    ++NumDeclsLoaded;
+    BCOffsetRAII restoreOffset(DeclTypeCursor);
+    DeclTypeCursor.JumpToBit(declOrOffset);
 
-  ++NumDeclsLoaded;
-  BCOffsetRAII restoreOffset(DeclTypeCursor);
-  DeclTypeCursor.JumpToBit(declOrOffset);
+    ModuleFile::DeserializingEntityRAII deserializingEntity(*this);
+    Expected<Decl *> deserialized =
+      DeclDeserializer(*this, declOrOffset).getDeclCheckedImpl();
+    if (!deserialized)
+      return deserialized;
+  }
 
-  SWIFT_DEFER {
-    if (!declOrOffset.isComplete())
-      return;
-    if (auto *IDC = dyn_cast_or_null<IterableDeclContext>(declOrOffset.get())) {
-      // Only set the DeclID on the returned Decl if it's one that was loaded
-      // and _wasn't_ one that had its DeclID set elsewhere (a followed XREF).
-      if (IDC->wasDeserialized() &&
-          static_cast<uint32_t>(IDC->getDeclID()) == 0) {
-        IDC->setDeclID(DID);
-      }
+  // Tag every deserialized ValueDecl coming out of getDeclChecked with its ID.
+  assert(declOrOffset.isComplete());
+  if (auto *IDC = dyn_cast_or_null<IterableDeclContext>(declOrOffset.get())) {
+    // Only set the DeclID on the returned Decl if it's one that was loaded
+    // and _wasn't_ one that had its DeclID set elsewhere (a followed XREF).
+    if (IDC->wasDeserialized() &&
+        static_cast<uint32_t>(IDC->getDeclID()) == 0) {
+      IDC->setDeclID(DID);
     }
-  };
-
-  ModuleFile::DeserializingEntityRAII deserializingEntity(*this);
-  return DeclDeserializer(*this, declOrOffset).getDeclCheckedImpl();
+  }
+  return declOrOffset;
 }
 
 llvm::Error DeclDeserializer::deserializeDeclAttributes() {
@@ -4011,6 +4011,24 @@
         break;
       }
 
+      case decls_block::Custom_DECL_ATTR: {
+        bool isImplicit;
+        TypeID typeID;
+        serialization::decls_block::CustomDeclAttrLayout::readRecord(
+          scratch, isImplicit, typeID);
+
+        Expected<Type> deserialized = MF.getTypeChecked(typeID);
+        if (!deserialized) {
+          MF.fatal(deserialized.takeError());
+          break;
+        }
+
+        Attr = CustomAttr::create(ctx, SourceLoc(),
+                                  TypeLoc::withoutLoc(deserialized.get()),
+                                  isImplicit);
+        break;
+      }
+
 #define SIMPLE_DECL_ATTR(NAME, CLASS, ...) \
       case decls_block::CLASS##_DECL_ATTR: { \
         bool isImplicit; \
diff --git a/lib/Serialization/ModuleFile.cpp b/lib/Serialization/ModuleFile.cpp
index 431d637..aa33d37 100644
--- a/lib/Serialization/ModuleFile.cpp
+++ b/lib/Serialization/ModuleFile.cpp
@@ -1092,6 +1092,22 @@
   return None;
 }
 
+static Optional<ModuleDecl::ImportFilterKind>
+getActualImportControl(unsigned rawValue) {
+  // We switch on the raw value rather than the enum in order to handle future
+  // values.
+  switch (rawValue) {
+  case static_cast<unsigned>(serialization::ImportControl::Normal):
+    return ModuleDecl::ImportFilterKind::Private;
+  case static_cast<unsigned>(serialization::ImportControl::Exported):
+    return ModuleDecl::ImportFilterKind::Public;
+  case static_cast<unsigned>(serialization::ImportControl::ImplementationOnly):
+    return ModuleDecl::ImportFilterKind::ImplementationOnly;
+  default:
+    return None;
+  }
+}
+
 static bool areCompatibleArchitectures(const llvm::Triple &moduleTarget,
                                        const llvm::Triple &ctxTarget) {
   if (moduleTarget.getArch() == ctxTarget.getArch())
@@ -1266,10 +1282,18 @@
         unsigned kind = cursor.readRecord(next.ID, scratch, &blobData);
         switch (kind) {
         case input_block::IMPORTED_MODULE: {
-          bool exported, scoped;
+          unsigned rawImportControl;
+          bool scoped;
           input_block::ImportedModuleLayout::readRecord(scratch,
-                                                        exported, scoped);
-          Dependencies.push_back({blobData, exported, scoped});
+                                                        rawImportControl,
+                                                        scoped);
+          auto importKind = getActualImportControl(rawImportControl);
+          if (!importKind) {
+            // We don't know how to import this dependency.
+            error();
+            return;
+          }
+          Dependencies.push_back({blobData, importKind.getValue(), scoped});
           break;
         }
         case input_block::LINK_LIBRARY: {
@@ -1436,7 +1460,8 @@
 }
 
 Status ModuleFile::associateWithFileContext(FileUnit *file,
-                                            SourceLoc diagLoc) {
+                                            SourceLoc diagLoc,
+                                            bool treatAsPartialModule) {
   PrettyStackTraceModuleFile stackEntry(*this);
 
   assert(getStatus() == Status::Valid && "invalid module file");
@@ -1489,6 +1514,17 @@
       continue;
     }
 
+    if (dependency.isImplementationOnly() &&
+        !(treatAsPartialModule || ctx.LangOpts.DebuggerSupport)) {
+      // When building normally (and not merging partial modules), we don't
+      // want to bring in the implementation-only module, because that might
+      // change the set of visible declarations. However, when debugging we
+      // want to allow getting at the internals of this module when possible,
+      // and so we'll try to reference the implementation-only module if it's
+      // available.
+      continue;
+    }
+
     StringRef modulePathStr = dependency.RawPath;
     StringRef scopePath;
     if (dependency.isScoped()) {
@@ -1516,7 +1552,8 @@
 
       // Otherwise, continue trying to load dependencies, so that we can list
       // everything that's missing.
-      missingDependency = true;
+      if (!(dependency.isImplementationOnly() && ctx.LangOpts.DebuggerSupport))
+        missingDependency = true;
       continue;
     }
 
@@ -1695,24 +1732,22 @@
   PrettyStackTraceModuleFile stackEntry(*this);
 
   for (auto &dep : Dependencies) {
-    switch (filter) {
-    case ModuleDecl::ImportFilter::All:
-      // We're including all imports.
-      break;
-
-    case ModuleDecl::ImportFilter::Private:
-      // Skip @_exported imports.
-      if (dep.isExported())
+    if (dep.isExported()) {
+      if (!filter.contains(ModuleDecl::ImportFilterKind::Public))
         continue;
 
-      break;
-
-    case ModuleDecl::ImportFilter::Public:
-      // Only include @_exported imports.
-      if (!dep.isExported())
+    } else if (dep.isImplementationOnly()) {
+      if (!filter.contains(ModuleDecl::ImportFilterKind::ImplementationOnly))
         continue;
+      if (!dep.isLoaded()) {
+        // Pretend we didn't have this import if we weren't originally asked to
+        // load it.
+        continue;
+      }
 
-      break;
+    } else {
+      if (!filter.contains(ModuleDecl::ImportFilterKind::Private))
+        continue;
     }
 
     assert(dep.isLoaded());
diff --git a/lib/Serialization/Serialization.cpp b/lib/Serialization/Serialization.cpp
index b1db428..b987866 100644
--- a/lib/Serialization/Serialization.cpp
+++ b/lib/Serialization/Serialization.cpp
@@ -1040,6 +1040,17 @@
   return dep.getModificationTime();
 }
 
+using ImportSet = llvm::SmallSet<ModuleDecl::ImportedModule, 8,
+                                 ModuleDecl::OrderImportedModules>;
+static ImportSet getImportsAsSet(const ModuleDecl *M,
+                                 ModuleDecl::ImportFilter filter) {
+  SmallVector<ModuleDecl::ImportedModule, 8> imports;
+  M->getImportedModules(imports, filter);
+  ImportSet importSet;
+  importSet.insert(imports.begin(), imports.end());
+  return importSet;
+}
+
 void Serializer::writeInputBlock(const SerializationOptions &options) {
   BCBlockRAII restoreBlock(Out, INPUT_BLOCK_ID, 4);
   input_block::ImportedModuleLayout ImportedModule(Out);
@@ -1068,17 +1079,20 @@
                         dep.getPath());
   }
 
+  ModuleDecl::ImportFilter allImportFilter;
+  allImportFilter |= ModuleDecl::ImportFilterKind::Public;
+  allImportFilter |= ModuleDecl::ImportFilterKind::Private;
+  allImportFilter |= ModuleDecl::ImportFilterKind::ImplementationOnly;
   SmallVector<ModuleDecl::ImportedModule, 8> allImports;
-  M->getImportedModules(allImports, ModuleDecl::ImportFilter::All);
+  M->getImportedModules(allImports, allImportFilter);
   ModuleDecl::removeDuplicateImports(allImports);
 
-  // Collect the public imports as a subset so that we can mark them with an
-  // extra flag.
-  SmallVector<ModuleDecl::ImportedModule, 8> publicImports;
-  M->getImportedModules(publicImports, ModuleDecl::ImportFilter::Public);
-  llvm::SmallSet<ModuleDecl::ImportedModule, 8,
-                 ModuleDecl::OrderImportedModules> publicImportSet;
-  publicImportSet.insert(publicImports.begin(), publicImports.end());
+  // Collect the public and private imports as a subset so that we can
+  // distinguish them.
+  ImportSet publicImportSet =
+      getImportsAsSet(M, ModuleDecl::ImportFilterKind::Public);
+  ImportSet privateImportSet =
+      getImportsAsSet(M, ModuleDecl::ImportFilterKind::Private);
 
   auto clangImporter =
     static_cast<ClangImporter *>(M->getASTContext().getClangModuleLoader());
@@ -1116,7 +1130,20 @@
 
     ImportPathBlob importPath;
     flattenImportPath(import, importPath);
-    ImportedModule.emit(ScratchRecord, publicImportSet.count(import),
+
+    serialization::ImportControl stableImportControl;
+    // The order of checks here is important, since a module can be imported
+    // differently in different files, and we need to record the "most visible"
+    // form here.
+    if (publicImportSet.count(import))
+      stableImportControl = ImportControl::Exported;
+    else if (privateImportSet.count(import))
+      stableImportControl = ImportControl::Normal;
+    else
+      stableImportControl = ImportControl::ImplementationOnly;
+
+    ImportedModule.emit(ScratchRecord,
+                        static_cast<uint8_t>(stableImportControl),
                         !import.first.empty(), importPath);
   }
 
@@ -2380,6 +2407,15 @@
         addDeclRef(theAttr->getReplacedFunction()), pieces.size(), pieces);
     return;
   }
+
+    case DAK_Custom: {
+      auto abbrCode = DeclTypeAbbrCodes[CustomDeclAttrLayout::Code];
+      auto theAttr = cast<CustomAttr>(DA);
+      CustomDeclAttrLayout::emitRecord(
+        Out, ScratchRecord, abbrCode, theAttr->isImplicit(),
+        addTypeRef(theAttr->getTypeLoc().getType()));
+      return;
+    }
   }
 }
 
diff --git a/lib/Serialization/SerializedModuleLoader.cpp b/lib/Serialization/SerializedModuleLoader.cpp
index 1db71e6..1d35eef 100644
--- a/lib/Serialization/SerializedModuleLoader.cpp
+++ b/lib/Serialization/SerializedModuleLoader.cpp
@@ -366,7 +366,7 @@
     ModuleDecl &M, Optional<SourceLoc> diagLoc,
     std::unique_ptr<llvm::MemoryBuffer> moduleInputBuffer,
     std::unique_ptr<llvm::MemoryBuffer> moduleDocInputBuffer,
-    bool isFramework) {
+    bool isFramework, bool treatAsPartialModule) {
   assert(moduleInputBuffer);
 
   StringRef moduleBufferID = moduleInputBuffer->getBufferIdentifier();
@@ -402,7 +402,8 @@
 
     auto diagLocOrInvalid = diagLoc.getValueOr(SourceLoc());
     loadInfo.status =
-        loadedModuleFile->associateWithFileContext(fileUnit, diagLocOrInvalid);
+        loadedModuleFile->associateWithFileContext(fileUnit, diagLocOrInvalid,
+                                                   treatAsPartialModule);
     if (loadInfo.status == serialization::Status::Valid) {
       Ctx.bumpGeneration();
       LoadedModuleFiles.emplace_back(std::move(loadedModuleFile),
@@ -487,8 +488,10 @@
         loadedModuleFile->getDependencies().begin(),
         loadedModuleFile->getDependencies().end(), std::back_inserter(missing),
         [&duplicates](const ModuleFile::Dependency &dependency) -> bool {
-          if (dependency.isLoaded() || dependency.isHeader())
+          if (dependency.isLoaded() || dependency.isHeader() ||
+              dependency.isImplementationOnly()) {
             return false;
+          }
           return duplicates.insert(dependency.RawPath).second;
         });
 
@@ -654,7 +657,8 @@
   SWIFT_DEFER { M->setHasResolvedImports(); };
 
   if (!loadAST(*M, moduleID.second, std::move(moduleInputBuffer),
-               std::move(moduleDocInputBuffer), isFramework)) {
+               std::move(moduleDocInputBuffer), isFramework,
+               /*treatAsPartialModule*/false)) {
     M->setFailedToLoad();
   }
 
@@ -703,8 +707,12 @@
 
 void SerializedASTFile::collectLinkLibrariesFromImports(
     ModuleDecl::LinkLibraryCallback callback) const {
+  ModuleDecl::ImportFilter ImportFilter;
+  ImportFilter |= ModuleDecl::ImportFilterKind::Public;
+  ImportFilter |= ModuleDecl::ImportFilterKind::Private;
+
   llvm::SmallVector<ModuleDecl::ImportedModule, 8> Imports;
-  File.getImportedModules(Imports, ModuleDecl::ImportFilter::All);
+  File.getImportedModules(Imports, ImportFilter);
 
   for (auto Import : Imports)
     Import.second->collectLinkLibraries(callback);
diff --git a/stdlib/private/StdlibUnittest/StdlibUnittest.swift b/stdlib/private/StdlibUnittest/StdlibUnittest.swift
index 5b9e637..55a89e0 100644
--- a/stdlib/private/StdlibUnittest/StdlibUnittest.swift
+++ b/stdlib/private/StdlibUnittest/StdlibUnittest.swift
@@ -103,6 +103,22 @@
   }
 }
 
+fileprivate struct AtomicBool {
+    
+    private var _value: _stdlib_AtomicInt
+    
+    init(_ b: Bool) { self._value = _stdlib_AtomicInt(b ? 1 : 0) }
+    
+    func store(_ b: Bool) { _value.store(b ? 1 : 0) }
+    
+    func load() -> Bool { return _value.load() != 0 }
+    
+    @discardableResult
+    func orAndFetch(_ b: Bool) -> Bool {
+        return _value.orAndFetch(b ? 1 : 0) != 0
+    }
+}
+
 func _printStackTrace(_ stackTrace: SourceLocStack?) {
   guard let s = stackTrace, !s.locs.isEmpty else { return }
   print("stacktrace:")
@@ -112,10 +128,8 @@
   }
 }
 
-// FIXME: these variables should be atomic, since multiple threads can call
-// `expect*()` functions.
-var _anyExpectFailed = false
-var _seenExpectCrash = false
+fileprivate var _anyExpectFailed = AtomicBool(false)
+fileprivate var _seenExpectCrash = AtomicBool(false)
 
 /// Run `body` and expect a failure to happen.
 ///
@@ -125,16 +139,16 @@
   stackTrace: SourceLocStack = SourceLocStack(),
   showFrame: Bool = true,
   file: String = #file, line: UInt = #line, invoking body: () -> Void) {
-  let startAnyExpectFailed = _anyExpectFailed
-  _anyExpectFailed = false
+  let startAnyExpectFailed = _anyExpectFailed.load()
+  _anyExpectFailed.store(false)
   body()
-  let endAnyExpectFailed = _anyExpectFailed
-  _anyExpectFailed = false
+  let endAnyExpectFailed = _anyExpectFailed.load()
+  _anyExpectFailed.store(false)
   expectTrue(
     endAnyExpectFailed, "running `body` should produce an expected failure",
     stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)
   )
-  _anyExpectFailed = _anyExpectFailed || startAnyExpectFailed
+  _anyExpectFailed.orAndFetch(startAnyExpectFailed)
 }
 
 public func identity(_ element: OpaqueValue<Int>) -> OpaqueValue<Int> {
@@ -257,7 +271,7 @@
   _ reason: String,
   trace message: String,
   stackTrace: SourceLocStack) {
-  _anyExpectFailed = true
+  _anyExpectFailed.store(true)
   stackTrace.print()
   print(reason, terminator: reason == "" ? "" : "\n")
   print(message, terminator: message == "" ? "" : "\n")
@@ -681,12 +695,12 @@
 }
 
 public func expectCrashLater(withMessage message: String = "") {
-  print("\(_stdlibUnittestStreamPrefix);expectCrash;\(_anyExpectFailed)")
+  print("\(_stdlibUnittestStreamPrefix);expectCrash;\(_anyExpectFailed.load())")
 
   var stderr = _Stderr()
   print("\(_stdlibUnittestStreamPrefix);expectCrash;\(message)", to: &stderr)
 
-  _seenExpectCrash = true
+  _seenExpectCrash.store(true)
 }
 
 public func expectCrash(withMessage message: String = "", executing: () -> Void) -> Never {
@@ -831,10 +845,10 @@
     }
 
     let testSuite = _allTestSuites[_testSuiteNameToIndex[testSuiteName]!]
-    _anyExpectFailed = false
+    _anyExpectFailed.store(false)
     testSuite._runTest(name: testName, parameter: testParameter)
 
-    print("\(_stdlibUnittestStreamPrefix);end;\(_anyExpectFailed)")
+    print("\(_stdlibUnittestStreamPrefix);end;\(_anyExpectFailed.load())")
 
     var stderr = _Stderr()
     print("\(_stdlibUnittestStreamPrefix);end", to: &stderr)
@@ -1212,25 +1226,27 @@
     if _runTestsInProcess {
       if t.stdinText != nil {
         print("The test \(fullTestName) requires stdin input and can't be run in-process, marking as failed")
-        _anyExpectFailed = true
+        _anyExpectFailed.store(true)
       } else if t.requiresOwnProcess {
         print("The test \(fullTestName) requires running in a child process and can't be run in-process, marking as failed.")
-        _anyExpectFailed = true
+        _anyExpectFailed.store(true)
       } else {
-        _anyExpectFailed = false
+        _anyExpectFailed.store(false)
         testSuite._runTest(name: t.name, parameter: testParameter)
       }
     } else {
-      (_anyExpectFailed, expectCrash, childTerminationStatus, crashStdout,
+      var anyExpectFailed = false
+      (anyExpectFailed, expectCrash, childTerminationStatus, crashStdout,
        crashStderr) =
         _runTestInChild(testSuite, t.name, parameter: testParameter)
+      _anyExpectFailed.store(anyExpectFailed)
     }
 
     // Determine if the test passed, not taking XFAILs into account.
     var testPassed = false
     switch (childTerminationStatus, expectCrash) {
     case (.none, false):
-      testPassed = !_anyExpectFailed
+      testPassed = !_anyExpectFailed.load()
 
     case (.none, true):
       testPassed = false
@@ -1241,7 +1257,7 @@
       print("the test crashed unexpectedly")
 
     case (.some, true):
-      testPassed = !_anyExpectFailed
+      testPassed = !_anyExpectFailed.load()
     }
     if testPassed && t.crashOutputMatches.count > 0 {
       // If we still think that the test passed, check if the crash
diff --git a/stdlib/public/Platform/winsdk.modulemap b/stdlib/public/Platform/winsdk.modulemap
index ac57755..5c6322e 100644
--- a/stdlib/public/Platform/winsdk.modulemap
+++ b/stdlib/public/Platform/winsdk.modulemap
@@ -18,6 +18,11 @@
   }
 
   module core {
+    module acl {
+      header "AclAPI.h"
+      export *
+    }
+
     // api-ms-win-core-errhandling-l1-1-0.dll
     module errhandling {
       header "errhandlingapi.h"
diff --git a/stdlib/public/core/Array.swift b/stdlib/public/core/Array.swift
index 55af724..22d7efa 100644
--- a/stdlib/public/core/Array.swift
+++ b/stdlib/public/core/Array.swift
@@ -1162,7 +1162,10 @@
       "newElements.underestimatedCount was an overestimate")
     // can't check for overflow as sequences can underestimate
 
-    _buffer.count += writtenCount
+    // This check prevents a data race writting to _swiftEmptyArrayStorage
+    if writtenCount > 0 {
+      _buffer.count += writtenCount
+    }
 
     if writtenUpTo == buf.endIndex {
       // there may be elements that didn't fit in the existing buffer,
diff --git a/stdlib/public/core/CTypes.swift b/stdlib/public/core/CTypes.swift
index 2a2a67b..496299f 100644
--- a/stdlib/public/core/CTypes.swift
+++ b/stdlib/public/core/CTypes.swift
@@ -87,6 +87,12 @@
 // Long Double type equivalent to Double type.
 public typealias CLongDouble = Double
 #endif
+#elseif os(Android)
+// On Android, long double is Float128 for AAPCS64, which we don't have yet in
+// Swift (SR-9072); and Double for ARMv7.
+#if arch(arm)
+public typealias CLongDouble = Double
+#endif
 #endif
 
 // FIXME: Is it actually UTF-32 on Darwin?
diff --git a/stdlib/public/core/DictionaryBuilder.swift b/stdlib/public/core/DictionaryBuilder.swift
index 0178c92..9ede429 100644
--- a/stdlib/public/core/DictionaryBuilder.swift
+++ b/stdlib/public/core/DictionaryBuilder.swift
@@ -71,6 +71,7 @@
   ///   - body: A closure that can initialize the dictionary's elements. This
   ///     closure must return the count of the initialized elements, starting at
   ///     the beginning of the buffer.
+  @_alwaysEmitIntoClient // Introduced in 5.1
   @inlinable
   public // SPI(Foundation)
   init(
@@ -90,6 +91,7 @@
 }
 
 extension _NativeDictionary {
+  @_alwaysEmitIntoClient // Introduced in 5.1
   @inlinable
   internal init(
     _unsafeUninitializedCapacity capacity: Int,
diff --git a/test/ClangImporter/Inputs/custom-modules/UnimportableMembers.h b/test/ClangImporter/Inputs/custom-modules/UnimportableMembers.h
index 9935779..287b028 100644
--- a/test/ClangImporter/Inputs/custom-modules/UnimportableMembers.h
+++ b/test/ClangImporter/Inputs/custom-modules/UnimportableMembers.h
@@ -1,54 +1,57 @@
+
+typedef __INTPTR_TYPE__ intptr_t;
+
 __attribute__((objc_root_class))
 @interface Base
 - (instancetype)init;
 @end
 
 @interface IncompleteDesignatedInitializers : Base
-- (instancetype)initFirst:(long)x __attribute__((objc_designated_initializer));
-- (instancetype)initSecond:(long)x __attribute__((objc_designated_initializer));
-- (instancetype)initMissing:(long)x, ... __attribute__((objc_designated_initializer));
-- (instancetype)initConveniently:(long)x;
+- (instancetype)initFirst:(intptr_t)x __attribute__((objc_designated_initializer));
+- (instancetype)initSecond:(intptr_t)x __attribute__((objc_designated_initializer));
+- (instancetype)initMissing:(intptr_t)x, ... __attribute__((objc_designated_initializer));
+- (instancetype)initConveniently:(intptr_t)x;
 @end
 @interface IncompleteDesignatedInitializers (CategoryConvenience)
-- (instancetype)initCategory:(long)x;
+- (instancetype)initCategory:(intptr_t)x;
 @end
 
 @interface IncompleteConvenienceInitializers : Base
-- (instancetype)initFirst:(long)x __attribute__((objc_designated_initializer));
-- (instancetype)initSecond:(long)x __attribute__((objc_designated_initializer));
-- (instancetype)initMissing:(long)x, ...;
-- (instancetype)initConveniently:(long)x;
+- (instancetype)initFirst:(intptr_t)x __attribute__((objc_designated_initializer));
+- (instancetype)initSecond:(intptr_t)x __attribute__((objc_designated_initializer));
+- (instancetype)initMissing:(intptr_t)x, ...;
+- (instancetype)initConveniently:(intptr_t)x;
 @end
 @interface IncompleteConvenienceInitializers (CategoryConvenience)
-- (instancetype)initCategory:(long)x;
+- (instancetype)initCategory:(intptr_t)x;
 @end
 
 @interface IncompleteUnknownInitializers : Base
-- (instancetype)initFirst:(long)x;
-- (instancetype)initSecond:(long)x;
-- (instancetype)initMissing:(long)x, ...;
-- (instancetype)initConveniently:(long)x;
+- (instancetype)initFirst:(intptr_t)x;
+- (instancetype)initSecond:(intptr_t)x;
+- (instancetype)initMissing:(intptr_t)x, ...;
+- (instancetype)initConveniently:(intptr_t)x;
 @end
 @interface IncompleteUnknownInitializers (CategoryConvenience)
-- (instancetype)initCategory:(long)x;
+- (instancetype)initCategory:(intptr_t)x;
 @end
 
 @interface IncompleteDesignatedInitializersWithCategory : Base
-- (instancetype)initFirst:(long)x __attribute__((objc_designated_initializer));
-- (instancetype)initMissing:(long)x, ... __attribute__((objc_designated_initializer));
-- (instancetype)initConveniently:(long)x;
+- (instancetype)initFirst:(intptr_t)x __attribute__((objc_designated_initializer));
+- (instancetype)initMissing:(intptr_t)x, ... __attribute__((objc_designated_initializer));
+- (instancetype)initConveniently:(intptr_t)x;
 @end
 @interface IncompleteDesignatedInitializersWithCategory (/*class extension*/)
-- (instancetype)initSecond:(long)x __attribute__((objc_designated_initializer));
-- (instancetype)initCategory:(long)x;
+- (instancetype)initSecond:(intptr_t)x __attribute__((objc_designated_initializer));
+- (instancetype)initCategory:(intptr_t)x;
 @end
 
 @interface DesignatedInitializerInAnotherModule : Base
-- (instancetype)initFirst:(long)x __attribute__((objc_designated_initializer));
-- (instancetype)initSecond:(long)x __attribute__((objc_designated_initializer));
-- (instancetype)initMissing:(long)x, ... __attribute__((objc_designated_initializer));
-- (instancetype)initConveniently:(long)x;
+- (instancetype)initFirst:(intptr_t)x __attribute__((objc_designated_initializer));
+- (instancetype)initSecond:(intptr_t)x __attribute__((objc_designated_initializer));
+- (instancetype)initMissing:(intptr_t)x, ... __attribute__((objc_designated_initializer));
+- (instancetype)initConveniently:(intptr_t)x;
 @end
 @interface DesignatedInitializerInAnotherModule (CategoryConvenience)
-- (instancetype)initCategory:(long)x;
+- (instancetype)initCategory:(intptr_t)x;
 @end
diff --git a/test/ClangImporter/cfuncs_parse.swift b/test/ClangImporter/cfuncs_parse.swift
index 172b7f3..6f12815 100644
--- a/test/ClangImporter/cfuncs_parse.swift
+++ b/test/ClangImporter/cfuncs_parse.swift
@@ -9,7 +9,12 @@
 }
 
 func test_cfunc2(_ i: Int) {
+#if os(Windows) && (arch(arm64) || arch(x86_64))
+  // LLP64 targets will import `long` as `Int32`
+  let f = cfunc2(Int32(i), 17)
+#else
   let f = cfunc2(i, 17)
+#endif
   _ = f as Float
   cfunc2(b:17, a:i) // expected-error{{extraneous argument labels 'b:a:' in call}}
   cfunc2(17, i) // expected-error{{cannot convert value of type 'Int' to expected argument type 'Int32'}}
@@ -58,9 +63,13 @@
   pow(1.5, 2.5)
 }
 
+#if !((os(Android) || os(Linux)) && arch(arm64))
+// long doubles in AAPCS64 are 128 bits, which is not supported by
+// Swift, so don't test this. SR-9072.
 func test_powl() {
   powl(1.5, 2.5)
 }
+#endif
 
 func test_puts(_ s: String) {
   _ = s.withCString { puts($0) + 32 };
diff --git a/test/ClangImporter/ctypes_parse.swift b/test/ClangImporter/ctypes_parse.swift
index 89701af..a01084c 100644
--- a/test/ClangImporter/ctypes_parse.swift
+++ b/test/ClangImporter/ctypes_parse.swift
@@ -28,15 +28,19 @@
   _ = b.rawValue
 }
 
+func verifyIsInt(_: inout Int) { }
+func verifyIsUInt(_: inout UInt) { }
+func verifyIsUInt64(_: inout UInt64) { }
+
 func testAnonEnum() {
   var a = AnonConst1
   a = AnonConst2
-#if arch(i386) || arch(arm)
-  _ = a as CUnsignedLongLong
+#if os(Windows)
+  verifyIsInt(&a)
+#elseif arch(i386) || arch(arm)
+  verifyIsUInt64(&a)
 #elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x)
-  _ = a as CUnsignedLong
-#else
-  __portMe()
+  verifyIsUInt(&a)
 #endif
 }
 
diff --git a/test/ClangImporter/enum-anon-sized.swift b/test/ClangImporter/enum-anon-sized.swift
new file mode 100644
index 0000000..3d63183
--- /dev/null
+++ b/test/ClangImporter/enum-anon-sized.swift
@@ -0,0 +1,35 @@
+// RUN: %target-swift-frontend -emit-ir %s -enable-objc-interop -import-objc-header %S/Inputs/enum-anon.h | %FileCheck -check-prefix=CHECK -check-prefix=CHECK-%target-runtime %s
+
+func verifyIsInt(_: inout Int) { }
+func verifyIsInt32(_: inout Int32) { }
+func verifyIsUInt32(_: inout UInt32) { }
+
+var a = Constant2
+var b = VarConstant2
+var c = SR2511().y
+
+verifyIsInt(&a)
+#if !os(Windows)
+verifyIsUInt32(&b)
+verifyIsUInt32(&c)
+#else
+verifyIsInt32(&b)
+verifyIsInt32(&c)
+#endif
+
+// CHECK: %TSo6SR2511V = type <{ %Ts5Int32V, [[ENUM_TYPE:%Ts5Int32V|%Ts6UInt32V]], %Ts5Int32V }>
+// CHECK-LABEL: define{{.*}} i32 @"$s4main6testIR1xs5Int32VSPySo6SR2511VG_tF"(
+public func testIR(x: UnsafePointer<SR2511>) -> CInt {
+  // CHECK: store i32 1, i32* getelementptr inbounds ([[ENUM_TYPE]], [[ENUM_TYPE]]* bitcast (i32* @global to [[ENUM_TYPE]]*), i32 0, i32 0), align 4
+  global = VarConstant2
+
+#if _runtime(_ObjC)
+  // CHECK-objc: store i16 1, i16* getelementptr inbounds (%Ts6UInt16V, %Ts6UInt16V* bitcast (i16* @usGlobal to %Ts6UInt16V*), i32 0, i32 0), align 2
+  usGlobal = USVarConstant2
+#endif
+
+  // Force the definition of the type above.
+  // CHECK: ret
+  return x.pointee.z
+} // CHECK-NEXT: {{^}$}}
+
diff --git a/test/ClangImporter/enum-anon.swift b/test/ClangImporter/enum-anon.swift
index 5f67977..14e2baa 100644
--- a/test/ClangImporter/enum-anon.swift
+++ b/test/ClangImporter/enum-anon.swift
@@ -1,11 +1,6 @@
 // RUN: %target-swift-frontend -typecheck %s -enable-objc-interop -import-objc-header %S/Inputs/enum-anon.h -DDIAGS -verify
-// RUN: %target-swift-frontend -emit-ir %s -enable-objc-interop -import-objc-header %S/Inputs/enum-anon.h | %FileCheck -check-prefix=CHECK -check-prefix=CHECK-%target-runtime %s
 
-#if DIAGS
 func testDiags() {
-  let _: String = Constant2 // expected-error {{cannot convert value of type 'Int' to specified type 'String'}}
-  let _: String = VarConstant2 // expected-error {{cannot convert value of type 'UInt32' to specified type 'String'}}
-
 #if _runtime(_ObjC)
   let us2 = USConstant2
 #else
@@ -20,27 +15,8 @@
 #endif
   let _: String = usVar2 // expected-error {{cannot convert value of type 'UInt16' to specified type 'String'}}
 
-  let _: String = SR2511().y // expected-error {{cannot convert value of type 'UInt32' to specified type 'String'}}
-
   // The nested anonymous enum value should still have top-level scope, because
   // that's how C works. It should also have the same type as the field (above).
-  let _: String = SR2511B // expected-error {{cannot convert value of type 'UInt32' to specified type 'String'}}
   let _: String = SR2511.SR2511B // expected-error {{type 'SR2511' has no member 'SR2511B'}}
 }
-#endif
 
-// CHECK-LABEL: %TSo6SR2511V = type <{ %Ts5Int32V, %Ts6UInt32V, %Ts5Int32V }>
-// CHECK-LABEL: define{{.*}} i32 @"$s4main6testIR1xs5Int32VSPySo6SR2511VG_tF"(
-public func testIR(x: UnsafePointer<SR2511>) -> CInt {
-  // CHECK: store i32 1, i32* getelementptr inbounds (%Ts6UInt32V, %Ts6UInt32V* bitcast (i32* @global to %Ts6UInt32V*), i32 0, i32 0), align 4
-  global = VarConstant2
-
-#if _runtime(_ObjC)
-  // CHECK-objc: store i16 1, i16* getelementptr inbounds (%Ts6UInt16V, %Ts6UInt16V* bitcast (i16* @usGlobal to %Ts6UInt16V*), i32 0, i32 0), align 2
-  usGlobal = USVarConstant2
-#endif
-
-  // Force the definition of the type above.
-  // CHECK: ret
-  return x.pointee.z
-} // CHECK-NEXT: {{^}$}}
diff --git a/test/DebugInfo/global_resilience.swift b/test/DebugInfo/global_resilience.swift
index e97e6e7..d8fba8e 100644
--- a/test/DebugInfo/global_resilience.swift
+++ b/test/DebugInfo/global_resilience.swift
@@ -22,6 +22,16 @@
 // CHECK-SAME: !dbg ![[LARGE:[0-9]+]]
 
 // CHECK: ![[SMALL]] = !DIGlobalVariableExpression(
+// CHECK-SAME:            var: ![[VAR_SMALL:[0-9]+]]
 // CHECK-SAME:            expr: !DIExpression())
+// CHECK: ![[VAR_SMALL]] = distinct !DIGlobalVariable(
+// CHECK-SAME:            type: ![[SMALL_TY:[0-9]+]]
+// CHECK: ![[SMALL_TY]] = !DICompositeType(tag: DW_TAG_structure_type,
+// CHECK-SAME:            name: "$swift.fixedbuffer", 
 // CHECK: ![[LARGE]] = !DIGlobalVariableExpression(
-// CHECK-SAME:            expr: !DIExpression(DW_OP_deref))
+// CHECK-SAME:            var: ![[VAR_LARGE:[0-9]+]]
+// CHECK-SAME:            expr: !DIExpression())
+// CHECK: ![[VAR_LARGE]] = distinct !DIGlobalVariable(
+// CHECK-SAME:            type: ![[LARGE_TY:[0-9]+]]
+// CHECK: ![[LARGE_TY]] = !DICompositeType(tag: DW_TAG_structure_type,
+// CHECK-SAME:            name: "$swift.fixedbuffer", 
diff --git a/test/Driver/sanitizers.swift b/test/Driver/sanitizers.swift
index 1f3e91c..85d3a00 100644
--- a/test/Driver/sanitizers.swift
+++ b/test/Driver/sanitizers.swift
@@ -106,7 +106,7 @@
 
 // UBSAN: -rpath @executable_path
 
-// MULTIPLE_SAN_LINUX: -fsanitize=address,fuzzer,undefined
+// MULTIPLE_SAN_LINUX: -fsanitize=address,undefined,fuzzer
 
 // BADARG: unsupported argument 'unknown' to option '-sanitize='
 // INCOMPATIBLESANITIZERS: argument '-sanitize=address' is not allowed with '-sanitize=thread'
diff --git a/test/IDE/complete_unresolved_members.swift b/test/IDE/complete_unresolved_members.swift
index affa2a1..9cc0a43 100644
--- a/test/IDE/complete_unresolved_members.swift
+++ b/test/IDE/complete_unresolved_members.swift
@@ -368,12 +368,12 @@
   return .#^UNRESOLVED_27^#
 }
 
-let TopLevelVar1 = OptionSetTaker7([.#^UNRESOLVED_28^#], Op2: [.Option4])
+let TopLevelVar1 = OptionSetTaker7([.#^UNRESOLVED_28^#], [.Option4])
 
 let TopLevelVar2 = OptionSetTaker1([.#^UNRESOLVED_29^#])
 
-let TopLevelVar3 = OptionSetTaker7([.Option1], Op2: [.#^UNRESOLVED_30^#])
-let TopLevelVar4 = OptionSetTaker7([.Option1], Op2: [.Option4, .#^UNRESOLVED_31^#])
+let TopLevelVar3 = OptionSetTaker7([.Option1], [.#^UNRESOLVED_30^#])
+let TopLevelVar4 = OptionSetTaker7([.Option1], [.Option4, .#^UNRESOLVED_31^#])
 
 let _: [SomeEnum1] = [.#^UNRESOLVED_32^#]
 let _: [SomeEnum1] = [.South, .#^UNRESOLVED_33^#]
diff --git a/test/IDE/print_swift_module.swift b/test/IDE/print_swift_module.swift
index 94d15ca..5be55e3 100644
--- a/test/IDE/print_swift_module.swift
+++ b/test/IDE/print_swift_module.swift
@@ -28,7 +28,7 @@
 // CHECK1:      /// Alias comment
 // CHECK1-NEXT: typealias Alias<T> = (T, T)
 
-// CHECK1:      public class C1 : P1 {
+// CHECK1:      public class C1 : print_swift_module.P1 {
 // CHECK1-NEXT:   /// foo1 comment from P1
 // CHECK1-NEXT:   public func foo1()
 // CHECK1-NEXT:   /// foo2 comment from C1
@@ -43,4 +43,4 @@
 // CHECK1-NEXT: }
 
 // CHECK1:      /// returnsAlias() comment
-// CHECK1-NEXT: func returnsAlias() -> Alias<Int>
+// CHECK1-NEXT: func returnsAlias() -> print_swift_module.Alias<Int>
diff --git a/test/IDE/print_synthesized_extensions.swift b/test/IDE/print_synthesized_extensions.swift
index 2cfc033..55a4267 100644
--- a/test/IDE/print_synthesized_extensions.swift
+++ b/test/IDE/print_synthesized_extensions.swift
@@ -255,7 +255,7 @@
 // CHECK4-NEXT:     <decl:Func>public func <loc>S9IntFunc()</loc></decl>
 // CHECK4-NEXT: }</synthesized>
 
-// CHECK5:      <decl:Struct>public struct <loc>S10</loc> : <ref:Protocol>P1</ref> {
+// CHECK5:      <decl:Struct>public struct <loc>S10</loc> : <ref:module>print_synthesized_extensions</ref>.<ref:Protocol>P1</ref> {
 // CHECK5-NEXT:   <decl:TypeAlias>public typealias <loc>T1</loc> = <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S9</ref><<ref:Struct>Int</ref>></decl>
 // CHECK5-NEXT: <decl:TypeAlias>public typealias <loc>T2</loc> = <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S9</ref><<ref:Struct>Int</ref>></decl>
 // CHECK5-NEXT: <decl:Func>public func <loc>f1(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S10</ref>.<ref:TypeAlias>T1</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S10</ref>.<ref:TypeAlias>T1</ref></decl>
@@ -275,7 +275,7 @@
 // CHECK7-NEXT:  <decl:Func>public func <loc>P4Func2()</loc></decl>
 // CHECK7-NEXT:  }</synthesized>
 
-// CHECK8:      <decl:Struct>public struct <loc>S4<<decl:GenericTypeParam>T</decl>></loc> : <ref:Protocol>P1</ref> {
+// CHECK8:      <decl:Struct>public struct <loc>S4<<decl:GenericTypeParam>T</decl>></loc> : <ref:module>print_synthesized_extensions</ref>.<ref:Protocol>P1</ref> {
 // CHECK8-NEXT:   <decl:TypeAlias>public typealias <loc>T1</loc> = <ref:Struct>Int</ref></decl>
 // CHECK8-NEXT:   <decl:TypeAlias>public typealias <loc>T2</loc> = <ref:Struct>Int</ref></decl>
 // CHECK8-NEXT:   <decl:Func>public func <loc>f1(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S4</ref><T>.<ref:TypeAlias>T1</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S4</ref><T>.<ref:TypeAlias>T1</ref></decl>
@@ -283,7 +283,7 @@
 // CHECK8-NEXT:   <decl:Func>public func <loc>p1IntFunc(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl>
 // CHECK8-NEXT:   }</synthesized>
 
-// CHECK9:      <decl:Struct>public struct <loc>S6<<decl:GenericTypeParam>T</decl>></loc> : <ref:Protocol>P1</ref> {
+// CHECK9:      <decl:Struct>public struct <loc>S6<<decl:GenericTypeParam>T</decl>></loc> : <ref:module>print_synthesized_extensions</ref>.<ref:Protocol>P1</ref> {
 // CHECK9-NEXT:    <decl:TypeAlias>public typealias <loc>T1</loc> = <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S5</ref></decl>
 // CHECK9-NEXT:    <decl:TypeAlias>public typealias <loc>T2</loc> = <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S5</ref></decl>
 // CHECK9-NEXT:    <decl:Func>public func <loc>f1(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S6</ref><T>.<ref:TypeAlias>T1</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S6</ref><T>.<ref:TypeAlias>T1</ref></decl>
@@ -300,7 +300,7 @@
 // CHECK10-NEXT:     <decl:Func>public func <loc>ef5(<decl:Param>t: <ref:Struct>S5</ref></decl>)</loc></decl>
 // CHECK10-NEXT: }</synthesized>
 
-// CHECK11:      <decl:Struct>public struct <loc>S12</loc> : <ref:Protocol>P5</ref> {
+// CHECK11:      <decl:Struct>public struct <loc>S12</loc> : <ref:module>print_synthesized_extensions</ref>.<ref:Protocol>P5</ref> {
 // CHECK11-NEXT:  <decl:TypeAlias>public typealias <loc>T1</loc> = <ref:Struct>Int</ref></decl>
 // CHECK11-NEXT:  <decl:Func>/// This is picked
 // CHECK11-NEXT:    public func <loc>foo1()</loc></decl></decl>
diff --git a/test/IDE/print_types.swift b/test/IDE/print_types.swift
index 579a32c..b8b7fee 100644
--- a/test/IDE/print_types.swift
+++ b/test/IDE/print_types.swift
@@ -6,7 +6,7 @@
 
 typealias MyInt = Int
 // CHECK: TypeAliasDecl '''MyInt''' MyInt.Type{{$}}
-// FULL:  TypeAliasDecl '''MyInt''' MyInt.Type{{$}}
+// FULL:  TypeAliasDecl '''MyInt''' swift_ide_test.MyInt.Type{{$}}
 
 func testVariableTypes(_ param: Int, param2: inout Double) {
 // CHECK: FuncDecl '''testVariableTypes''' (Int, inout Double) -> (){{$}}
@@ -52,7 +52,7 @@
   var typealias1 : MyInt = 42
 // CHECK: VarDecl '''typealias1''' MyInt{{$}}
 // CHECK:         IntegerLiteralExpr:[[@LINE-2]] '''42''' Int{{$}}
-// FULL:  VarDecl '''typealias1''' MyInt{{$}}
+// FULL:  VarDecl '''typealias1''' swift_ide_test.MyInt{{$}}
 // FULL:          IntegerLiteralExpr:[[@LINE-4]] '''42''' Swift.Int{{$}}
   _ = typealias1 ; typealias1 = 1
 
@@ -77,11 +77,11 @@
 
 func testFuncType3() -> Void {}
 // CHECK: FuncDecl '''testFuncType3''' () -> Void{{$}}
-// FULL:  FuncDecl '''testFuncType3''' () -> Void{{$}}
+// FULL:  FuncDecl '''testFuncType3''' () -> Swift.Void{{$}}
 
 func testFuncType4() -> MyInt {}
 // CHECK: FuncDecl '''testFuncType4''' () -> MyInt{{$}}
-// FULL:  FuncDecl '''testFuncType4''' () -> MyInt{{$}}
+// FULL:  FuncDecl '''testFuncType4''' () -> swift_ide_test.MyInt{{$}}
 
 func testFuncType5() -> (Int) {}
 // CHECK: FuncDecl '''testFuncType5''' () -> (Int){{$}}
@@ -111,7 +111,7 @@
 
 func testInGenericFunc1<A, B : FooProtocol, C : FooProtocol & BarProtocol>(_ a: A, b: B, c: C) {
 // CHECK: FuncDecl '''testInGenericFunc1''' <A, B, C where B : FooProtocol, C : BarProtocol, C : FooProtocol> (A, b: B, c: C) -> (){{$}}
-// FULL:  FuncDecl '''testInGenericFunc1''' <A, B, C where B : FooProtocol, C : BarProtocol, C : FooProtocol> (A, b: B, c: C) -> (){{$}}
+// FULL:  FuncDecl '''testInGenericFunc1''' <A, B, C where B : swift_ide_test.FooProtocol, C : swift_ide_test.BarProtocol, C : swift_ide_test.FooProtocol> (A, b: B, c: C) -> (){{$}}
 
   var a1 = a
   _ = a1; a1 = a
@@ -136,5 +136,5 @@
 
 func testInGenericFunc2<T : QuxProtocol, U : QuxProtocol>(_: T, _: U) where T.Qux == U.Qux {}
 // CHECK: FuncDecl '''testInGenericFunc2''' <T, U where T : QuxProtocol, U : QuxProtocol, T.Qux == U.Qux> (T, U) -> (){{$}}
-// FULL:  FuncDecl '''testInGenericFunc2''' <T, U where T : QuxProtocol, U : QuxProtocol, T.Qux == U.Qux> (T, U) -> (){{$}}
+// FULL:  FuncDecl '''testInGenericFunc2''' <T, U where T : swift_ide_test.QuxProtocol, U : swift_ide_test.QuxProtocol, T.Qux == U.Qux> (T, U) -> (){{$}}
 
diff --git a/test/IRGen/enum.sil b/test/IRGen/enum.sil
index d6c403e..742e319 100644
--- a/test/IRGen/enum.sil
+++ b/test/IRGen/enum.sil
@@ -474,6 +474,24 @@
   case u
 }
 
+// CHECK-32: define{{( dllexport)?}}{{( protected)?}} swiftcc i1 @select_enum([[WORD:i32]], i8)
+// CHECK-64: define{{( dllexport)?}}{{( protected)?}} swiftcc i1 @select_enum([[WORD:i64]], i8)
+// CHECK: entry:
+// CHECK:   [[TAG:%.*]] = trunc i8 %1 to i1
+// CHECK:   [[PAYLOAD:%.*]] = icmp eq [[WORD]] %0, 1
+// CHECK:   [[MATCHES:%.*]] = and i1 [[TAG]], [[PAYLOAD]]
+// CHECK:   [[RES:%.*]] = select i1 [[MATCHES]], i1 false, i1 true
+// CHECK:   ret i1 [[RES]]
+// CHECK: }
+
+sil @select_enum : $@convention(method) (SinglePayloadNoXI2) -> Builtin.Int1 {
+bb0(%0 : $SinglePayloadNoXI2):
+  %2 = integer_literal $Builtin.Int1, 0
+  %3 = integer_literal $Builtin.Int1, -1
+  %4 = select_enum %0 : $SinglePayloadNoXI2, case #SinglePayloadNoXI2.z!enumelt: %2, default %3 : $Builtin.Int1
+  return %4 : $Builtin.Int1
+}
+
 // CHECK-64: define{{( dllexport)?}}{{( protected)?}} swiftcc void @single_payload_no_xi_switch([[WORD:i64]], i8) {{.*}} {
 // CHECK-32: define{{( dllexport)?}}{{( protected)?}} swiftcc void @single_payload_no_xi_switch([[WORD:i32]], i8) {{.*}} {
 sil @single_payload_no_xi_switch : $@convention(thin) (SinglePayloadNoXI2) -> () {
diff --git a/test/IRGen/objc_generic_class_metadata.sil b/test/IRGen/objc_generic_class_metadata.sil
index 52bdff2..589838b 100644
--- a/test/IRGen/objc_generic_class_metadata.sil
+++ b/test/IRGen/objc_generic_class_metadata.sil
@@ -93,3 +93,22 @@
 // CHECK:         [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$sSo12GenericClassCMa"([[INT]] 255)
 // CHECK:         [[CLASS:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0
 // CHECK:         call swiftcc %swift.metadata_response @swift_getTupleTypeMetadata2([[INT]] %0, %swift.type* [[CLASS]], %swift.type* @"$sSiN", i8* null,
+
+class K<T> {}
+
+sil @$useMeta : $@convention(thin) <P> () -> ()
+
+// CHECK-LABEL: define void @an_objc_method(i8*, i8*)
+// CHECK:   [[C:%.*]] = bitcast i8* %0 to %objc_class*
+// CHECK:   [[M:%.*]] = call %swift.type* @swift_getObjCClassMetadata(%objc_class* [[C]])
+// CHECK:   [[M2:%.*]] = bitcast %swift.type* [[M]] to %swift.type**
+// CHECK:   [[P:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[M2]]
+// CHECK:   [[P2:%.*]] = load %swift.type*, %swift.type** [[P]]
+// CHECK:   call swiftcc void @"$useMeta"(%swift.type* [[P2]])
+// CHECK:   ret void
+sil @an_objc_method : $@convention(objc_method) <P> (@objc_metatype K<P>.Type) -> () {
+bb0(%0 :  $@objc_metatype K<P>.Type):
+  %2 = function_ref @$useMeta : $@convention(thin) <τ_0_0> () -> ()
+  %3 = apply %2<P>() : $@convention(thin) <τ_0_0 > () -> ()
+  return undef : $()
+}
diff --git a/test/Index/circular.swift b/test/Index/circular.swift
new file mode 100644
index 0000000..1c81995
--- /dev/null
+++ b/test/Index/circular.swift
@@ -0,0 +1,66 @@
+// RUN: %target-swift-ide-test -print-indexed-symbols -source-filename %s | %FileCheck %s
+
+class SelfCycle : SelfCycle {}
+// CHECK: [[@LINE-1]]:7 | class/Swift | SelfCycle | {{[^ ]*}} | Def | rel: 0
+// CHECK: [[@LINE-2]]:19 | class/Swift | SelfCycle | {{[^ ]*}} | Ref,RelBase | rel: 1
+// CHECK:   RelBase | class/Swift | SelfCycle | {{\W*}}
+
+class Cycle1_A: Cycle1_B {}
+// CHECK: [[@LINE-1]]:7 | class/Swift | Cycle1_A | {{[^ ]*}} | Def | rel: 0
+// CHECK: [[@LINE-2]]:17 | class/Swift | Cycle1_B | {{[^ ]*}} | Ref,RelBase | rel: 1
+// CHECK:   RelBase | class/Swift | Cycle1_A | {{[^ ]*}}
+class Cycle1_B: Cycle1_A {}
+// CHECK: [[@LINE-1]]:7 | class/Swift | Cycle1_B | {{[^ ]*}} | Def | rel: 0
+// CHECK: [[@LINE-2]]:17 | class/Swift | Cycle1_A | {{[^ ]*}} | Ref,RelBase | rel: 1
+// CHECK:   RelBase | class/Swift | Cycle1_B | {{[^ ]*}}
+
+class Cycle2_A: Cycle2_C {}
+// CHECK: [[@LINE-1]]:7 | class/Swift | Cycle2_A | {{[^ ]*}} | Def | rel: 0
+// CHECK: [[@LINE-2]]:17 | class/Swift | Cycle2_C | {{[^ ]*}} | Ref,RelBase | rel: 1
+// CHECK:   RelBase | class/Swift | Cycle2_A | {{[^ ]*}}
+class Cycle2_B: Cycle2_A {}
+// CHECK: [[@LINE-1]]:7 | class/Swift | Cycle2_B | {{[^ ]*}} | Def | rel: 0
+// CHECK: [[@LINE-2]]:17 | class/Swift | Cycle2_A | {{[^ ]*}} | Ref,RelBase | rel: 1
+// CHECK:   RelBase | class/Swift | Cycle2_B | {{[^ ]*}}
+class Cycle2_C: Cycle2_B {}
+// CHECK: [[@LINE-1]]:7 | class/Swift | Cycle2_C | {{[^ ]*}} | Def | rel: 0
+// CHECK: [[@LINE-2]]:17 | class/Swift | Cycle2_B | {{[^ ]*}} | Ref,RelBase | rel: 1
+// CHECK:   RelBase | class/Swift | Cycle2_C | {{[^ ]*}}
+
+class TestCase1: XCTestCase {}
+// CHECK: [[@LINE-1]]:7 | class(test)/Swift | TestCase1 | {{[^ ]*}} | Def | rel: 0
+// CHECK: [[@LINE-2]]:18 | class/Swift | XCTestCase | {{[^ ]*}} | Ref,RelBase | rel: 1
+// CHECK:   RelBase | class(test)/Swift | TestCase1 | {{[^ ]*}}
+class XCTestCase: TestCase1 {}
+// CHECK: [[@LINE-1]]:7 | class/Swift | XCTestCase | {{[^ ]*}} | Def | rel: 0
+// CHECK: [[@LINE-2]]:19 | class(test)/Swift | TestCase1 | {{[^ ]*}} | Ref,RelBase | rel: 1
+// CHECK:   RelBase | class/Swift | XCTestCase | {{[^ ]*}}
+class TestCase2: TestCase1 {}
+// CHECK: [[@LINE-1]]:7 | class(test)/Swift | TestCase2 | {{[^ ]*}} | Def | rel: 0
+// CHECK: [[@LINE-2]]:18 | class(test)/Swift | TestCase1 | {{[^ ]*}} | Ref,RelBase | rel: 1
+// CHECK:   RelBase | class(test)/Swift | TestCase2 | {{[^ ]*}}
+
+protocol SelfCycleP: SelfCycleP {}
+// CHECK: [[@LINE-1]]:10 | protocol/Swift | SelfCycleP | {{[^ ]*}} | Def | rel: 0
+// CHECK: [[@LINE-2]]:22 | protocol/Swift | SelfCycleP | {{[^ ]*}} | Ref,RelBase | rel: 1
+// CHECK:   RelBase | protocol/Swift | SelfCycleP | {{[^ ]*}}
+protocol Cycle1P_A: Cycle1P_B {}
+// CHECK: [[@LINE-1]]:10 | protocol/Swift | Cycle1P_A | {{[^ ]*}} | Def | rel: 0
+// CHECK: [[@LINE-2]]:21 | protocol/Swift | Cycle1P_B | {{[^ ]*}} | Ref,RelBase | rel: 1
+// CHECK:   RelBase | protocol/Swift | Cycle1P_A | {{[^ ]*}}
+protocol Cycle1P_B: Cycle1P_A {}
+// CHECK: [[@LINE-1]]:10 | protocol/Swift | Cycle1P_B | {{[^ ]*}} | Def | rel: 0
+// CHECK: [[@LINE-2]]:21 | protocol/Swift | Cycle1P_A | {{[^ ]*}} | Ref,RelBase | rel: 1
+// CHECK:   RelBase | protocol/Swift | Cycle1P_B | {{[^ ]*}}
+protocol Cycle2P_A: Cycle2P_C {}
+// CHECK: [[@LINE-1]]:10 | protocol/Swift | Cycle2P_A | {{[^ ]*}} | Def | rel: 0
+// CHECK: [[@LINE-2]]:21 | protocol/Swift | Cycle2P_C | {{[^ ]*}} | Ref,RelBase | rel: 1
+// CHECK:   RelBase | protocol/Swift | Cycle2P_A | {{[^ ]*}}
+protocol Cycle2P_B: Cycle2P_A {}
+// CHECK: [[@LINE-1]]:10 | protocol/Swift | Cycle2P_B | {{[^ ]*}} | Def | rel: 0
+// CHECK: [[@LINE-2]]:21 | protocol/Swift | Cycle2P_A | {{[^ ]*}} | Ref,RelBase | rel: 1
+// CHECK:   RelBase | protocol/Swift | Cycle2P_B | {{[^ ]*}}
+protocol Cycle2P_C: Cycle2P_B {}
+// CHECK: [[@LINE-1]]:10 | protocol/Swift | Cycle2P_C | {{[^ ]*}} | Def | rel: 0
+// CHECK: [[@LINE-2]]:21 | protocol/Swift | Cycle2P_B | {{[^ ]*}} | Ref,RelBase | rel: 1
+// CHECK:   RelBase | protocol/Swift | Cycle2P_C | {{[^ ]*}}
diff --git a/test/Inputs/clang-importer-sdk/usr/include/ctypes.h b/test/Inputs/clang-importer-sdk/usr/include/ctypes.h
index 6975ab0..c055b48 100644
--- a/test/Inputs/clang-importer-sdk/usr/include/ctypes.h
+++ b/test/Inputs/clang-importer-sdk/usr/include/ctypes.h
@@ -162,6 +162,10 @@
 
 // Types from stdint.h.
 #include <stdint.h>
+#if defined(_WIN32)
+typedef __INTPTR_TYPE__ intptr_t;
+typedef __UINTPTR_TYPE__ uintptr_t;
+#endif
 STDLIB_TEST(__UINT8_TYPE__, uint8_t);
 STDLIB_TEST(__UINT16_TYPE__, uint16_t);
 STDLIB_TEST(__UINT32_TYPE__, uint32_t);
diff --git a/test/Inputs/clang-importer-sdk/usr/include/macros.h b/test/Inputs/clang-importer-sdk/usr/include/macros.h
index 8f360bc..537c832 100644
--- a/test/Inputs/clang-importer-sdk/usr/include/macros.h
+++ b/test/Inputs/clang-importer-sdk/usr/include/macros.h
@@ -12,7 +12,13 @@
 #define EOF (-1)
 #define UINT32_MAX 0xFFFFFFFFU
 #define INT64_MAX 0x7FFFFFFFFFFFFFFFLL
+#if defined(_WIN32)
+// MSVC compatibility will always return a signed value when the suffix is `LL`
+// or `i64` and other targets will promote it to an unsigned type.
+#define UINT64_MAX 0xFFFFFFFFFFFFFFFFULL
+#else
 #define UINT64_MAX 0xFFFFFFFFFFFFFFFFLL
+#endif
 #define MINUS_THREE -3
 #define true 1
 #define false 0
diff --git a/test/Interpreter/arrays.swift b/test/Interpreter/arrays.swift
index 387a67b..003387c 100644
--- a/test/Interpreter/arrays.swift
+++ b/test/Interpreter/arrays.swift
@@ -161,3 +161,25 @@
 let mdaPerf = [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]]
 print(mdaPerf)
 // CHECK: {{\[}}[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]]
+
+class Deinitable {
+  deinit {
+    print("deinit called")
+  }
+}
+
+enum E : Error {
+  case error
+}
+
+func throwingFunc() throws -> Deinitable {
+  throw E.error
+}
+
+do {
+  let array = try [Deinitable(), throwingFunc()]
+} catch {
+  // CHECK: deinit called
+  // CHECK: error thrown
+  print("error thrown")
+}
\ No newline at end of file
diff --git a/test/Interpreter/repl.swift b/test/Interpreter/repl.swift
index f37d76c..1eedb45 100644
--- a/test/Interpreter/repl.swift
+++ b/test/Interpreter/repl.swift
@@ -46,22 +46,22 @@
 // Check that we handle unmatched parentheses in REPL.
 1+1)
 
-var z = 44
+var z = 46
 +z
-// CHECK: Int = 44{{$}}
+// CHECK: Int = 46{{$}}
 
-+44
-// CHECK: Int = 44{{$}}
++48
+// CHECK: Int = 48{{$}}
 
 typealias Foo = Int
 
 var f1 : Foo = 1
-var f44 : Foo = 44
+var f50 : Foo = 50
 f1 +
-  f44
-// CHECK: Foo = 45{{$}}
-+(f44)
-// CHECK: Foo = 44{{$}}
+  f50
+// CHECK: Foo = 51{{$}}
++(f50)
+// CHECK: Foo = 50{{$}}
 
 1.5
 // CHECK: Double = 1.5{{$}}
diff --git a/test/NameBinding/import-implementation-only.swift b/test/NameBinding/import-implementation-only.swift
new file mode 100644
index 0000000..e05c70c
--- /dev/null
+++ b/test/NameBinding/import-implementation-only.swift
@@ -0,0 +1,14 @@
+// RUN: %empty-directory(%t)
+// RUN: %target-swift-frontend -emit-module -o %t/abcde.swiftmodule %S/Inputs/abcde.swift
+// RUN: %target-swift-frontend -emit-module -o %t/Library.swiftmodule %s -I %t
+
+// RUN: echo 'import Library; foo()' > %t/main.swift
+// RUN: %target-swift-frontend -typecheck %t/main.swift -I %t
+
+// Delete the indirect dependency; everything should still work.
+// RUN: rm %t/abcde.swiftmodule
+// RUN: %target-swift-frontend -typecheck %t/main.swift -I %t
+
+@_implementationOnly import abcde
+
+public func foo() {}
diff --git a/test/ParseableInterface/Inputs/imports-clang-modules/NotSoSecret.h b/test/ParseableInterface/Inputs/imports-clang-modules/NotSoSecret.h
new file mode 100644
index 0000000..cf4f6ba
--- /dev/null
+++ b/test/ParseableInterface/Inputs/imports-clang-modules/NotSoSecret.h
@@ -0,0 +1 @@
+void notSoSecret(void);
diff --git a/test/ParseableInterface/Inputs/imports-clang-modules/NotSoSecret2.h b/test/ParseableInterface/Inputs/imports-clang-modules/NotSoSecret2.h
new file mode 100644
index 0000000..87b61fb
--- /dev/null
+++ b/test/ParseableInterface/Inputs/imports-clang-modules/NotSoSecret2.h
@@ -0,0 +1 @@
+void notSoSecret2(void);
diff --git a/test/ParseableInterface/Inputs/imports-clang-modules/Secret_BAD.h b/test/ParseableInterface/Inputs/imports-clang-modules/Secret_BAD.h
new file mode 100644
index 0000000..c16fc93
--- /dev/null
+++ b/test/ParseableInterface/Inputs/imports-clang-modules/Secret_BAD.h
@@ -0,0 +1 @@
+void secret(void);
diff --git a/test/ParseableInterface/Inputs/imports-clang-modules/module.modulemap b/test/ParseableInterface/Inputs/imports-clang-modules/module.modulemap
index 308d286..8289129 100644
--- a/test/ParseableInterface/Inputs/imports-clang-modules/module.modulemap
+++ b/test/ParseableInterface/Inputs/imports-clang-modules/module.modulemap
@@ -6,3 +6,8 @@
 }
 module C { header "C.h" }
 module D { header "D.h" }
+
+module Secret_BAD { header "Secret_BAD.h" }
+
+module NotSoSecret { header "NotSoSecret.h" }
+module NotSoSecret2 { header "NotSoSecret2.h" }
diff --git a/test/ParseableInterface/Inputs/imports-other.swift b/test/ParseableInterface/Inputs/imports-other.swift
index 617edff..b1a4e2c 100644
--- a/test/ParseableInterface/Inputs/imports-other.swift
+++ b/test/ParseableInterface/Inputs/imports-other.swift
@@ -1,3 +1,6 @@
 import A
 import B.B3
 import D
+
+import NotSoSecret
+@_implementationOnly import NotSoSecret2
diff --git a/test/ParseableInterface/ParseStdlib.swiftinterface b/test/ParseableInterface/ParseStdlib.swiftinterface
index 9072c2d..ba16186 100644
--- a/test/ParseableInterface/ParseStdlib.swiftinterface
+++ b/test/ParseableInterface/ParseStdlib.swiftinterface
@@ -8,5 +8,5 @@
 // RUN: %target-swift-frontend -build-module-from-parseable-interface -o %t/ParseStdlib.swiftmodule %s
 // RUN: %target-swift-ide-test -print-module -module-to-print ParseStdlib -I %t -source-filename x -print-interface | %FileCheck %s
 
-// CHECK: func test(_: Int42)
+// CHECK: func test(_: Builtin.Int42)
 public func test(_: Builtin.Int42) {}
diff --git a/test/ParseableInterface/access-filter.swift b/test/ParseableInterface/access-filter.swift
index b499dda..5b56490 100644
--- a/test/ParseableInterface/access-filter.swift
+++ b/test/ParseableInterface/access-filter.swift
@@ -197,12 +197,12 @@
   @usableFromInline internal func constrainedToInternalStruct2_BAD() {}
 }
 
-// CHECK: extension GenericStruct where T : PublicProto {{[{]$}}
+// CHECK: extension GenericStruct where T : main.PublicProto {{[{]$}}
 extension GenericStruct where T: PublicProto {
   // CHECK-NEXT: public func constrainedToPublicProto(){{$}}
   public func constrainedToPublicProto() {}
 } // CHECK-NEXT: {{^[}]$}}
-// CHECK: extension GenericStruct where T : UFIProto {{[{]$}}
+// CHECK: extension GenericStruct where T : main.UFIProto {{[{]$}}
 extension GenericStruct where T: UFIProto {
   // CHECK-NEXT: @usableFromInline{{$}}
   // CHECK-NEXT: internal func constrainedToUFIProto(){{$}}
@@ -245,12 +245,12 @@
 
 internal typealias ReallyInternalAlias_BAD = ReallyInternalAliasBase_BAD
 
-// CHECK: extension GenericStruct where T == PublicAlias {{[{]$}}
+// CHECK: extension GenericStruct where T == main.PublicAlias {{[{]$}}
 extension GenericStruct where T == PublicAlias {
   // CHECK-NEXT: public func constrainedToPublicAlias(){{$}}
   public func constrainedToPublicAlias() {}
 } // CHECK-NEXT: {{^[}]$}}
-// CHECK: extension GenericStruct where T == UFIAlias {{[{]$}}
+// CHECK: extension GenericStruct where T == main.UFIAlias {{[{]$}}
 extension GenericStruct where T == UFIAlias {
   // CHECK-NEXT: @usableFromInline{{$}}
   // CHECK-NEXT: internal func constrainedToUFIAlias(){{$}}
diff --git a/test/ParseableInterface/conformances.swift b/test/ParseableInterface/conformances.swift
index 566cf6d..f006bf9 100644
--- a/test/ParseableInterface/conformances.swift
+++ b/test/ParseableInterface/conformances.swift
@@ -33,23 +33,23 @@
 // NEGATIVE-NOT: extension conformances.A2
 public struct A2: PrivateProto, PublicProto {}
 // CHECK: public struct A3 {
-// CHECK-END: extension conformances.A3 : PublicProto {}
+// CHECK-END: extension conformances.A3 : conformances.PublicProto {}
 public struct A3: PublicProto & PrivateProto {}
 // CHECK: public struct A4 {
-// CHECK-END: extension conformances.A4 : PublicProto {}
+// CHECK-END: extension conformances.A4 : conformances.PublicProto {}
 public struct A4: PrivateProto & PublicProto {}
 
 public protocol PublicBaseProto {}
 private protocol PrivateSubProto: PublicBaseProto {}
 
 // CHECK: public struct B1 {
-// CHECK-END: extension conformances.B1 : PublicBaseProto {}
+// CHECK-END: extension conformances.B1 : conformances.PublicBaseProto {}
 public struct B1: PrivateSubProto {}
 // CHECK: public struct B2 : PublicBaseProto {
 // NEGATIVE-NOT: extension conformances.B2
 public struct B2: PublicBaseProto, PrivateSubProto {}
 // CHECK: public struct B3 {
-// CHECK-END: extension conformances.B3 : PublicBaseProto {}
+// CHECK-END: extension conformances.B3 : conformances.PublicBaseProto {}
 public struct B3: PublicBaseProto & PrivateSubProto {}
 // CHECK: public struct B4 : PublicBaseProto {
 // CHECK: extension B4 {
@@ -87,26 +87,26 @@
 public protocol ConditionallyConformed {}
 public protocol ConditionallyConformedAgain {}
 
-// CHECK-END: extension conformances.OuterGeneric : ConditionallyConformed, ConditionallyConformedAgain where T : _ConstraintThatIsNotPartOfTheAPIOfThisLibrary {}
+// CHECK-END: extension conformances.OuterGeneric : conformances.ConditionallyConformed, conformances.ConditionallyConformedAgain where T : _ConstraintThatIsNotPartOfTheAPIOfThisLibrary {}
 extension OuterGeneric: ConditionallyConformed where T: PrivateProto {}
 extension OuterGeneric: ConditionallyConformedAgain where T == PrivateProto {}
 
-// CHECK-END: extension conformances.OuterGeneric.Inner : PublicBaseProto {}
-// CHECK-END: extension conformances.OuterGeneric.Inner : ConditionallyConformed, ConditionallyConformedAgain where T : _ConstraintThatIsNotPartOfTheAPIOfThisLibrary {}
+// CHECK-END: extension conformances.OuterGeneric.Inner : conformances.PublicBaseProto {}
+// CHECK-END: extension conformances.OuterGeneric.Inner : conformances.ConditionallyConformed, conformances.ConditionallyConformedAgain where T : _ConstraintThatIsNotPartOfTheAPIOfThisLibrary {}
 extension OuterGeneric.Inner: ConditionallyConformed where T: PrivateProto {}
 extension OuterGeneric.Inner: ConditionallyConformedAgain where T == PrivateProto {}
 
 private protocol AnotherPrivateSubProto: PublicBaseProto {}
 
 // CHECK: public struct C1 {
-// CHECK-END: extension conformances.C1 : PublicBaseProto {}
+// CHECK-END: extension conformances.C1 : conformances.PublicBaseProto {}
 public struct C1: PrivateSubProto, AnotherPrivateSubProto {}
 // CHECK: public struct C2 {
-// CHECK-END: extension conformances.C2 : PublicBaseProto {}
+// CHECK-END: extension conformances.C2 : conformances.PublicBaseProto {}
 public struct C2: PrivateSubProto & AnotherPrivateSubProto {}
 // CHECK: public struct C3 {
 // CHECK: extension C3 {
-// CHECK-END: extension conformances.C3 : PublicBaseProto {}
+// CHECK-END: extension conformances.C3 : conformances.PublicBaseProto {}
 public struct C3: PrivateSubProto {}
 extension C3: AnotherPrivateSubProto {}
 
@@ -120,10 +120,10 @@
 // NEGATIVE-NOT: extension conformances.D2
 public struct D2: PrivateSubProto, PublicSubProto {}
 // CHECK: public struct D3 {
-// CHECK-END: extension conformances.D3 : PublicBaseProto, PublicSubProto {}
+// CHECK-END: extension conformances.D3 : conformances.PublicBaseProto, conformances.PublicSubProto {}
 public struct D3: PrivateSubProto & PublicSubProto {}
 // CHECK: public struct D4 {
-// CHECK-END: extension conformances.D4 : APublicSubProto, PublicBaseProto {}
+// CHECK-END: extension conformances.D4 : conformances.APublicSubProto, conformances.PublicBaseProto {}
 public struct D4: APublicSubProto & PrivateSubProto {}
 // CHECK: public struct D5 {
 // CHECK: extension D5 : PublicSubProto {
@@ -139,33 +139,33 @@
 private typealias PrivateProtoAlias = PublicProto
 
 // CHECK: public struct E1 {
-// CHECK-END: extension conformances.E1 : PublicProto {}
+// CHECK-END: extension conformances.E1 : conformances.PublicProto {}
 public struct E1: PrivateProtoAlias {}
 
 private typealias PrivateSubProtoAlias = PrivateSubProto
 
 // CHECK: public struct F1 {
-// CHECK-END: extension conformances.F1 : PublicBaseProto {}
+// CHECK-END: extension conformances.F1 : conformances.PublicBaseProto {}
 public struct F1: PrivateSubProtoAlias {}
 
 private protocol ClassConstrainedProto: PublicProto, AnyObject {}
 
 public class G1: ClassConstrainedProto {}
 // CHECK: public class G1 {
-// CHECK-END: extension conformances.G1 : PublicProto {}
+// CHECK-END: extension conformances.G1 : conformances.PublicProto {}
 
 public class Base {}
 private protocol BaseConstrainedProto: Base, PublicProto {}
 
 public class H1: Base, ClassConstrainedProto {}
 // CHECK: public class H1 : Base {
-// CHECK-END: extension conformances.H1 : PublicProto {}
+// CHECK-END: extension conformances.H1 : conformances.PublicProto {}
 
 public struct MultiGeneric<T, U, V> {}
 extension MultiGeneric: PublicProto where U: PrivateProto {}
 
 // CHECK: public struct MultiGeneric<T, U, V> {
-// CHECK-END: extension conformances.MultiGeneric : PublicProto where T : _ConstraintThatIsNotPartOfTheAPIOfThisLibrary {}
+// CHECK-END: extension conformances.MultiGeneric : conformances.PublicProto where T : _ConstraintThatIsNotPartOfTheAPIOfThisLibrary {}
 
 
 internal struct InternalImpl_BAD: PrivateSubProto {}
diff --git a/test/ParseableInterface/imports.swift b/test/ParseableInterface/imports.swift
index 337e597..e68e33d 100644
--- a/test/ParseableInterface/imports.swift
+++ b/test/ParseableInterface/imports.swift
@@ -1,12 +1,16 @@
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module -o %t/empty.swiftmodule %S/../Inputs/empty.swift
-// RUN: %target-swift-frontend -typecheck -emit-parseable-module-interface-path - %s %S/Inputs/imports-other.swift -I %S/Inputs/imports-clang-modules/ -I %t -verify | %FileCheck %s
+// RUN: %target-swift-frontend -typecheck -emit-parseable-module-interface-path - %s %S/Inputs/imports-other.swift -I %S/Inputs/imports-clang-modules/ -I %t -verify | %FileCheck -implicit-check-not BAD %s
 
 
 @_exported import empty
 import B.B2
 import func C.c // expected-warning {{scoped imports are not yet supported in parseable module interfaces}}
 import D
+@_implementationOnly import Secret_BAD
+
+@_implementationOnly import NotSoSecret
+import NotSoSecret2
 
 // CHECK-NOT: import
 // CHECK: {{^}}import A{{$}}
@@ -15,6 +19,8 @@
 // CHECK-NEXT: {{^}}import B.B3{{$}}
 // CHECK-NEXT: {{^}}import C/*.c*/{{$}}
 // CHECK-NEXT: {{^}}import D{{$}}
+// CHECK-NEXT: {{^}}import NotSoSecret{{$}}
+// CHECK-NEXT: {{^}}import NotSoSecret2{{$}}
 // CHECK-NEXT: {{^}}import Swift{{$}}
 // CHECK-NEXT: {{^}}@_exported import empty{{$}}
 // CHECK-NOT: import
diff --git a/test/ParseableInterface/inlinable-function.swift b/test/ParseableInterface/inlinable-function.swift
index f22e63d..b6b7ced 100644
--- a/test/ParseableInterface/inlinable-function.swift
+++ b/test/ParseableInterface/inlinable-function.swift
@@ -4,7 +4,10 @@
 // RUN: %target-swift-frontend -emit-module -o /dev/null -merge-modules %t/Test.swiftmodule -disable-objc-attr-requires-foundation-module -emit-parseable-module-interface-path %t/TestFromModule.swiftinterface -module-name Test
 // RUN: %FileCheck %s --check-prefix FROMMODULE --check-prefix CHECK < %t/TestFromModule.swiftinterface
 
-// CHECK: public struct Foo : Hashable {
+// FIXME: These shouldn't be different, or we'll get different output from
+// WMO and non-WMO builds.
+// FROMSOURCE-LABEL: public struct Foo : Hashable {
+// FROMMODULE-LABEL: public struct Foo : Swift.Hashable {
 public struct Foo: Hashable {
   // CHECK: public var inlinableGetPublicSet: [[INT:(Swift.)?Int]] {
   public var inlinableGetPublicSet: Int {
diff --git a/test/PlaygroundTransform/Inputs/not.py b/test/PlaygroundTransform/Inputs/not.py
new file mode 100644
index 0000000..e7fd556
--- /dev/null
+++ b/test/PlaygroundTransform/Inputs/not.py
@@ -0,0 +1,13 @@
+import shlex
+import subprocess
+import sys
+
+if len(sys.argv) < 2:
+    print("Too few args to " + sys.argv[0])
+    sys.exit(0)
+
+try:
+    subprocess.check_call(shlex.split(sys.argv[1]))
+    sys.exit(1)
+except subprocess.CalledProcessError as e:
+    sys.exit(0)
diff --git a/test/PlaygroundTransform/placeholder.swift b/test/PlaygroundTransform/placeholder.swift
index 2461f33..489ab33 100644
--- a/test/PlaygroundTransform/placeholder.swift
+++ b/test/PlaygroundTransform/placeholder.swift
@@ -3,19 +3,19 @@
 // RUN: %target-build-swift -Xfrontend -playground -Xfrontend -disable-playground-transform -o %t/main %t/main.swift
 // RUN: %target-codesign %t/main
 // RUN: %target-run %t/main | %FileCheck %s
-// RUN: ! %target-run %t/main --crash 2>&1 | %FileCheck -check-prefix=CRASH-CHECK %s
+// RUN: %{python} %S/Inputs/not.py "%target-run %t/main --crash" 2>&1 | %FileCheck -check-prefix=CRASH-CHECK %s
 // REQUIRES: executable_test
 
-// NOTE: "!" is used above instead of "not --crash" because simctl's exit
+// NOTE: not.py is used above instead of "not --crash" because simctl's exit
 // status doesn't reflect whether its child process crashed or not. So "not
 // --crash %target-run ..." always fails when testing for the iOS Simulator.
-// The more precise solution would be to use a version of 'not' cross-compiled
-// for the simulator.
+// not.py also works on win32, where ! does not.
+// Checking for ".[Ff]atal" because of d03a575279c.
 
 func f(crash crash: Bool) -> Int {
   if crash {
     return <#T#>
-    // CRASH-CHECK: fatal error: attempt to evaluate editor placeholder: file {{.*}}/main.swift, line [[@LINE-1]]
+    // CRASH-CHECK: {{[fF]}}atal error: attempt to evaluate editor placeholder: file {{.*}}/main.swift, line [[@LINE-1]]
   } else {
     return 42
   }
diff --git a/test/SILGen/literals.swift b/test/SILGen/literals.swift
index 0f8c3ba..47471cd 100644
--- a/test/SILGen/literals.swift
+++ b/test/SILGen/literals.swift
@@ -41,3 +41,217 @@
 func returnsCustomStringSubclass() -> CustomStringSubclass {
   return "hello world"
 }
+
+class TakesArrayLiteral<Element> : ExpressibleByArrayLiteral {
+  required init(arrayLiteral elements: Element...) {}
+}
+
+// CHECK-LABEL: sil hidden [ossa] @$s8literals18returnsCustomArrayAA05TakesD7LiteralCySiGyF : $@convention(thin) () -> @owned TakesArrayLiteral<Int>
+// CHECK: [[TMP:%.*]] = apply %2(%0, %1) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
+// CHECK: [[ARRAY_LENGTH:%.*]] = integer_literal $Builtin.Word, 2
+// CHECK: [[ALLOCATE_VARARGS:%.*]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
+// CHECK: [[ARR_TMP:%.*]] = apply [[ALLOCATE_VARARGS]]<Int>([[ARRAY_LENGTH]])
+// CHECK: ([[ARR:%.*]], [[ADDRESS:%.*]]) = destructure_tuple [[ARR_TMP]]
+// CHECK: [[POINTER:%.*]] = pointer_to_address [[ADDRESS]]
+// CHECK: store [[TMP:%.*]] to [trivial] [[POINTER]]
+// CHECK: [[IDX1:%.*]] = integer_literal $Builtin.Word, 1
+// CHECK: [[POINTER1:%.*]] = index_addr [[POINTER]] : $*Int, [[IDX1]] : $Builtin.Word
+// CHECK: store [[TMP:%.*]] to [trivial] [[POINTER1]]
+// CHECK: [[METATYPE:%.*]] = metatype $@thick TakesArrayLiteral<Int>.Type
+// CHECK: [[CTOR:%.*]] = class_method %15 : $@thick TakesArrayLiteral<Int>.Type, #TakesArrayLiteral.init!allocator.1 : <Element> (TakesArrayLiteral<Element>.Type) -> (Element...) -> TakesArrayLiteral<Element>, $@convention(method)
+// CHECK: [[RESULT:%.*]] = apply [[CTOR]]<Int>([[ARR]], [[METATYPE]])
+// CHECK: return [[RESULT]]
+func returnsCustomArray() -> TakesArrayLiteral<Int> {
+  // Use temporary to simplify generated_sil
+  let tmp = 77
+  return [tmp, tmp]
+}
+
+class Klass {}
+
+// CHECK-LABEL: sil hidden [ossa] @$s8literals24returnsClassElementArrayAA05TakesE7LiteralCyAA5KlassCGyF : $@convention(thin) () -> @owned TakesArrayLiteral<Klass>
+// CHECK: [[ARRAY_LENGTH:%.*]] = integer_literal $Builtin.Word, 1
+// CHECK: [[ALLOCATE_VARARGS:%.*]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
+// CHECK: [[ARR_TMP:%.*]] = apply [[ALLOCATE_VARARGS]]<Klass>([[ARRAY_LENGTH]])
+// CHECK: ([[ARR:%.*]], [[ADDRESS:%.*]]) = destructure_tuple [[ARR_TMP]]
+// CHECK: [[POINTER:%.*]] = pointer_to_address [[ADDRESS]]
+// CHECK: [[KLASS_METATYPE:%.*]] = metatype $@thick Klass.Type
+// CHECK: [[CTOR:%.*]] = function_ref @$s8literals5KlassCACycfC : $@convention(method) (@thick Klass.Type) -> @owned Klass
+// CHECK: [[TMP:%.*]] = apply [[CTOR]]([[KLASS_METATYPE]]) : $@convention(method) (@thick Klass.Type) -> @owned Klass
+// CHECK: store [[TMP]] to [init] [[POINTER]]
+// CHECK: [[METATYPE:%.*]] = metatype $@thick TakesArrayLiteral<Klass>.Type
+// CHECK: [[CTOR:%.*]] = class_method [[METATYPE]] : $@thick TakesArrayLiteral<Klass>.Type, #TakesArrayLiteral.init!allocator.1 : <Element> (TakesArrayLiteral<Element>.Type) -> (Element...) -> TakesArrayLiteral<Element>, $@convention(method)
+// CHECK: [[RESULT:%.*]] = apply [[CTOR]]<Klass>([[ARR]], [[METATYPE]])
+// CHECK: return [[RESULT]]
+func returnsClassElementArray() -> TakesArrayLiteral<Klass> {
+  return [Klass()]
+}
+
+struct Foo<T> {
+  var t: T
+}
+
+// CHECK-LABEL: sil hidden [ossa] @$s8literals30returnsAddressOnlyElementArray1tAA05TakesF7LiteralCyAA3FooVyxGGAH_tlF : $@convention(thin) <T> (@in_guaranteed Foo<T>) -> @owned TakesArrayLiteral<Foo<T>>
+// CHECK: [[ARRAY_LENGTH:%.*]] = integer_literal $Builtin.Word, 1
+// CHECK: [[ALLOCATE_VARARGS:%.*]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
+// CHECK: [[ARR_TMP:%.*]] = apply [[ALLOCATE_VARARGS]]<Foo<T>>([[ARRAY_LENGTH]])
+// CHECK: ([[ARR:%.*]], [[ADDRESS:%.*]]) = destructure_tuple [[ARR_TMP]]
+// CHECK: [[POINTER:%.*]] = pointer_to_address [[ADDRESS]]
+// CHECK: copy_addr %0 to [initialization] [[POINTER]] : $*Foo<T>
+// CHECK: [[METATYPE:%.*]] = metatype $@thick TakesArrayLiteral<Foo<T>>.Type
+// CHECK: [[CTOR:%.*]] = class_method [[METATYPE]] : $@thick TakesArrayLiteral<Foo<T>>.Type, #TakesArrayLiteral.init!allocator.1 : <Element> (TakesArrayLiteral<Element>.Type) -> (Element...) -> TakesArrayLiteral<Element>, $@convention(method)
+// CHECK: [[RESULT:%.*]] = apply [[CTOR]]<Foo<T>>([[ARR]], [[METATYPE]])
+// CHECK: return [[RESULT]]
+func returnsAddressOnlyElementArray<T>(t: Foo<T>) -> TakesArrayLiteral<Foo<T>> {
+  return [t]
+}
+
+// CHECK-LABEL: sil hidden [ossa] @$s8literals3FooV20returnsArrayFromSelfAA05TakesD7LiteralCyACyxGGyF : $@convention(method) <T> (@in_guaranteed Foo<T>) -> @owned TakesArrayLiteral<Foo<T>>
+// CHECK: [[ARRAY_LENGTH:%.*]] = integer_literal $Builtin.Word, 1
+// CHECK: [[ALLOCATE_VARARGS:%.*]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
+// CHECK: [[ARR_TMP:%.*]] = apply [[ALLOCATE_VARARGS]]<Foo<T>>([[ARRAY_LENGTH]])
+// CHECK: ([[ARR:%.*]], [[ADDRESS:%.*]]) = destructure_tuple [[ARR_TMP]]
+// CHECK: [[POINTER:%.*]] = pointer_to_address [[ADDRESS]]
+// CHECK: copy_addr %0 to [initialization] [[POINTER]] : $*Foo<T>
+// CHECK: [[METATYPE:%.*]] = metatype $@thick TakesArrayLiteral<Foo<T>>.Type
+// CHECK: [[CTOR:%.*]] = class_method [[METATYPE]] : $@thick TakesArrayLiteral<Foo<T>>.Type, #TakesArrayLiteral.init!allocator.1 : <Element> (TakesArrayLiteral<Element>.Type) -> (Element...) -> TakesArrayLiteral<Element>, $@convention(method)
+// CHECK: [[RESULT:%.*]] = apply [[CTOR]]<Foo<T>>([[ARR]], [[METATYPE]])
+// CHECK: return [[RESULT]]
+extension Foo {
+  func returnsArrayFromSelf() -> TakesArrayLiteral<Foo<T>> {
+    return [self]
+  }
+}
+
+// CHECK-LABEL: sil hidden [ossa] @$s8literals3FooV28returnsArrayFromMutatingSelfAA05TakesD7LiteralCyACyxGGyF : $@convention(method) <T> (@inout Foo<T>) -> @owned TakesArrayLiteral<Foo<T>>
+// CHECK: [[ARRAY_LENGTH:%.*]] = integer_literal $Builtin.Word, 1
+// CHECK: [[ALLOCATE_VARARGS:%.*]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
+// CHECK: [[ARR_TMP:%.*]] = apply [[ALLOCATE_VARARGS]]<Foo<T>>([[ARRAY_LENGTH]])
+// CHECK: ([[ARR:%.*]], [[ADDRESS:%.*]]) = destructure_tuple [[ARR_TMP]]
+// CHECK: [[POINTER:%.*]] = pointer_to_address [[ADDRESS]]
+// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] %0 : $*Foo<T>
+// CHECK: copy_addr [[ACCESS]] to [initialization] [[POINTER]] : $*Foo<T>
+// CHECK: end_access [[ACCESS]] : $*Foo<T>
+// CHECK: [[METATYPE:%.*]] = metatype $@thick TakesArrayLiteral<Foo<T>>.Type
+// CHECK: [[CTOR:%.*]] = class_method [[METATYPE]] : $@thick TakesArrayLiteral<Foo<T>>.Type, #TakesArrayLiteral.init!allocator.1 : <Element> (TakesArrayLiteral<Element>.Type) -> (Element...) -> TakesArrayLiteral<Element>, $@convention(method)
+// CHECK: [[RESULT:%.*]] = apply [[CTOR]]<Foo<T>>([[ARR]], [[METATYPE]])
+// CHECK: return [[RESULT]]
+extension Foo {
+  mutating func returnsArrayFromMutatingSelf() -> TakesArrayLiteral<Foo<T>> {
+    return [self]
+  }
+}
+
+struct Foo2 {
+  var k: Klass
+}
+
+// CHECK-LABEL: sil hidden [ossa] @$s8literals23returnsNonTrivialStructAA17TakesArrayLiteralCyAA4Foo2VGyF : $@convention(thin) () -> @owned TakesArrayLiteral<Foo2>
+// CHECK: [[ARRAY_LENGTH:%.*]] = integer_literal $Builtin.Word, 1
+// CHECK: [[ALLOCATE_VARARGS:%.*]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
+// CHECK: [[ARR_TMP:%.*]] = apply [[ALLOCATE_VARARGS]]<Foo2>([[ARRAY_LENGTH]])
+// CHECK: ([[ARR:%.*]], [[ADDRESS:%.*]]) = destructure_tuple [[ARR_TMP]]
+// CHECK: [[POINTER:%.*]] = pointer_to_address [[ADDRESS]]
+// CHECK: [[METATYPE_FOO2:%.*]] = metatype $@thin Foo2.Type
+// CHECK: [[METATYPE_KLASS:%.*]] = metatype $@thick Klass.Type
+// CHECK: [[CTOR:%.*]] = function_ref @$s8literals5KlassCACycfC : $@convention(method) (@thick Klass.Type) -> @owned Klass
+// CHECK: [[K:%.*]] = apply [[CTOR]]([[METATYPE_KLASS]]) : $@convention(method) (@thick Klass.Type) -> @owned Klass
+// CHECK: [[CTOR:%.*]] = function_ref @$s8literals4Foo2V1kAcA5KlassC_tcfC : $@convention(method) (@owned Klass, @thin Foo2.Type) -> @owned Foo2
+// CHECK: [[TMP:%.*]] = apply [[CTOR]]([[K]], [[METATYPE_FOO2]]) : $@convention(method) (@owned Klass, @thin Foo2.Type) -> @owned Foo2
+// store [[TMP]] to [init] [[POINTER]] : $*Foo2
+// CHECK: [[METATYPE:%.*]] = metatype $@thick TakesArrayLiteral<Foo2>.Type
+// CHECK: [[CTOR:%.*]] = class_method [[METATYPE]] : $@thick TakesArrayLiteral<Foo2>.Type, #TakesArrayLiteral.init!allocator.1 : <Element> (TakesArrayLiteral<Element>.Type) -> (Element...) -> TakesArrayLiteral<Element>, $@convention(method)
+// CHECK: [[RESULT:%.*]] = apply [[CTOR]]<Foo2>([[ARR]], [[METATYPE]])
+// CHECK: return [[RESULT]]
+func returnsNonTrivialStruct() -> TakesArrayLiteral<Foo2> {
+  return [Foo2(k: Klass())]
+}
+
+// CHECK-LABEL: sil hidden [ossa] @$s8literals16NestedLValuePathV11wrapInArrayyyF : $@convention(method) (@inout NestedLValuePath) -> ()
+// CHECK: [[METATYPE_NESTED:%.*]] = metatype $@thin NestedLValuePath.Type
+// CHECK: [[ARRAY_LENGTH:%.*]] = integer_literal $Builtin.Word, 1
+// CHECK: [[ALLOCATE_VARARGS:%.*]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
+// CHECK: [[ARR_TMP:%.*]] = apply [[ALLOCATE_VARARGS]]<NestedLValuePath>([[ARRAY_LENGTH]])
+// CHECK: ([[ARR:%.*]], [[ADDRESS:%.*]]) = destructure_tuple [[ARR_TMP]]
+// CHECK: [[POINTER:%.*]] = pointer_to_address [[ADDRESS]]
+
+// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unknown] %0 : $*NestedLValuePath
+// CHECK: [[OTHER_FN:%.*]] = function_ref @$s8literals16NestedLValuePathV21otherMutatingFunctionACyF : $@convention(method) (@inout NestedLValuePath) -> @owned NestedLValuePath
+// CHECK: [[TMP:%.*]] = apply [[OTHER_FN]]([[ACCESS]]) : $@convention(method) (@inout NestedLValuePath) -> @owned NestedLValuePath
+// CHECK: end_access [[ACCESS]] : $*NestedLValuePath
+// CHECK: store [[TMP]] to [init] [[POINTER]] : $*NestedLValuePath
+// CHECK: [[METATYPE:%.*]] = metatype $@thick TakesArrayLiteral<NestedLValuePath>.Type
+// CHECK: [[CTOR:%.*]] = class_method [[METATYPE]] : $@thick TakesArrayLiteral<NestedLValuePath>.Type, #TakesArrayLiteral.init!allocator.1 : <Element> (TakesArrayLiteral<Element>.Type) -> (Element...) -> TakesArrayLiteral<Element>, $@convention(method)
+// CHECK: [[ARR_RESULT:%.*]] = apply [[CTOR]]<NestedLValuePath>([[ARR]], [[METATYPE]])
+// CHECK: [[CTOR:%.*]] = function_ref @$s8literals16NestedLValuePathV3arrAcA17TakesArrayLiteralCyACG_tcfC : $@convention(method) (@owned TakesArrayLiteral<NestedLValuePath>, @thin NestedLValuePath.Type) -> @owned NestedLValuePath // user: %18
+// CHECK: [[RESULT:%.*]] = apply [[CTOR]]([[ARR_RESULT]], [[METATYPE_NESTED]]) : $@convention(method) (@owned TakesArrayLiteral<NestedLValuePath>, @thin NestedLValuePath.Type) -> @owned NestedLValuePath
+// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unknown] %0 : $*NestedLValuePath
+// CHECK: assign [[RESULT]] to [[ACCESS]] : $*NestedLValuePath
+// CHECK: end_access [[ACCESS]] : $*NestedLValuePath
+// CHECK: [[VOID:%.*]] = tuple ()
+// CHECK: return [[VOID]] : $()
+struct NestedLValuePath {
+  var arr: TakesArrayLiteral<NestedLValuePath>
+
+  mutating func wrapInArray() {
+    self = NestedLValuePath(arr: [self.otherMutatingFunction()])
+  }
+
+  mutating func otherMutatingFunction() -> NestedLValuePath {
+    return self
+  }
+}
+
+protocol WrapsSelfInArray {}
+
+// CHECK-LABEL: sil hidden [ossa] @$s8literals16WrapsSelfInArrayPAAE04wrapdE0AA05TakesE7LiteralCyAaB_pGyF : $@convention(method) <Self where Self : WrapsSelfInArray> (@inout Self) -> @owned TakesArrayLiteral<WrapsSelfInArray>
+// CHECK: [[ARRAY_LENGTH:%.*]] = integer_literal $Builtin.Word, 1
+// CHECK: [[ALLOCATE_VARARGS:%.*]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
+// CHECK: [[ARR_TMP:%.*]] = apply [[ALLOCATE_VARARGS]]<WrapsSelfInArray>([[ARRAY_LENGTH]])
+// CHECK: ([[ARR:%.*]], [[ADDRESS:%.*]]) = destructure_tuple [[ARR_TMP]]
+// CHECK: [[POINTER:%.*]] = pointer_to_address [[ADDRESS]]
+// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] %0 : $*Self
+// CHECK: [[EXISTENTIAL:%.*]] = init_existential_addr [[POINTER]] : $*WrapsSelfInArray, $Self
+// CHECK: copy_addr [[ACCESS]] to [initialization] [[EXISTENTIAL]] : $*Self
+// CHECK: end_access [[ACCESS]] : $*Self
+// CHECK: [[METATYPE:%.*]] = metatype $@thick TakesArrayLiteral<WrapsSelfInArray>.Type
+// CHECK: [[CTOR:%.*]] = class_method [[METATYPE]] : $@thick TakesArrayLiteral<WrapsSelfInArray>.Type, #TakesArrayLiteral.init!allocator.1 : <Element> (TakesArrayLiteral<Element>.Type) -> (Element...) -> TakesArrayLiteral<Element>, $@convention(method)
+// CHECK: [[RESULT:%.*]] = apply [[CTOR]]<WrapsSelfInArray>([[ARR]], [[METATYPE]])
+// CHECK: return [[RESULT]]
+extension WrapsSelfInArray {
+  mutating func wrapInArray() -> TakesArrayLiteral<WrapsSelfInArray> {
+    return [self]
+  }
+}
+
+protocol FooProtocol {
+  init()
+}
+
+func makeThrowing<T : FooProtocol>() throws -> T { return T() }
+func makeBasic<T : FooProtocol>() -> T { return T() }
+
+// CHECK-LABEL: sil hidden [ossa] @$s8literals15throwingElementSayxGyKAA11FooProtocolRzlF : $@convention(thin) <T where T : FooProtocol> () -> (@owned Array<T>, @error Error)
+// CHECK: [[ARRAY_LENGTH:%.*]] = integer_literal $Builtin.Word, 2
+// CHECK: [[ALLOCATE_VARARGS:%.*]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
+// CHECK: [[ARR_TMP:%.*]] = apply [[ALLOCATE_VARARGS]]<T>([[ARRAY_LENGTH]])
+// CHECK: ([[ARR:%.*]], [[ADDRESS:%.*]]) = destructure_tuple [[ARR_TMP]]
+// CHECK: [[POINTER:%.*]] = pointer_to_address [[ADDRESS]]
+// CHECK: [[FN:%.*]] = function_ref @$s8literals9makeBasicxyAA11FooProtocolRzlF : $@convention(thin)
+// CHECK: [[TMP:%.*]] = apply [[FN]]<T>([[POINTER]])
+// CHECK: [[IDX:%.*]] = integer_literal $Builtin.Word, 1
+// CHECK: [[POINTER1:%.*]] = index_addr [[POINTER]] : $*T, [[IDX]] : $Builtin.Word
+// CHECK: [[FN:%.*]] = function_ref @$s8literals12makeThrowingxyKAA11FooProtocolRzlF : $@convention(thin)
+// CHECK: try_apply [[FN]]<T>([[POINTER1]]) : {{.*}} normal bb1, error bb2
+
+// CHECK: bb1([[TMP:%.*]] : $()):
+// CHECK: return [[ARR]]
+
+// CHECK: bb2([[ERR:%.*]] : @owned $Error):
+// CHECK: destroy_addr [[POINTER]] : $*T
+// CHECK: [[DEALLOC:%.*]] = function_ref @$ss29_deallocateUninitializedArrayyySayxGnlF
+// CHECK: [[TMP:%.*]] = apply [[DEALLOC]]<T>([[ARR]])
+// CHECK: throw [[ERR]] : $Error
+func throwingElement<T : FooProtocol>() throws -> [T] {
+  return try [makeBasic(), makeThrowing()]
+}
diff --git a/test/SILGen/objc_bridging_array.swift b/test/SILGen/objc_bridging_array.swift
new file mode 100644
index 0000000..664fe37
--- /dev/null
+++ b/test/SILGen/objc_bridging_array.swift
@@ -0,0 +1,38 @@
+
+// RUN: %target-swift-emit-silgen(mock-sdk: %clang-importer-sdk) %s | %FileCheck %s
+
+// REQUIRES: objc_interop
+
+import Foundation
+
+class Child : NSObject {}
+
+@objc protocol Parent {
+  var children: [Child] { get set }
+}
+
+func setChildren(p: Parent, c: Child) {
+  p.children = [c]
+}
+
+// CHECK-LABEL: sil hidden [ossa] @$s19objc_bridging_array11setChildren1p1cyAA6Parent_p_AA5ChildCtF : $@convention(thin) (@guaranteed Parent, @guaranteed Child) -> () {
+// CHECK: [[OPENED:%.*]] = open_existential_ref %0 : $Parent to $[[OPENED_TYPE:.* Parent]]
+// CHECK: [[COPIED:%.*]] = copy_value [[OPENED]] : $[[OPENED_TYPE]]
+// CHECK: [[LENGTH:%.*]] = integer_literal $Builtin.Word, 1
+// CHECK: [[FN:%.*]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer)
+// CHECK: [[ARRAY_AND_BUFFER:%.*]] = apply [[FN]]<Child>([[LENGTH]]) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer)
+// CHECK: ([[ARRAY:%.*]], [[BUFFER_PTR:%.*]]) = destructure_tuple [[ARRAY_AND_BUFFER]] : $(Array<Child>, Builtin.RawPointer)
+// CHECK: [[BUFFER:%.*]] = pointer_to_address [[BUFFER_PTR]] : $Builtin.RawPointer to [strict] $*Child
+// CHECK: [[CHILD:%.*]] = copy_value %1 : $Child
+// CHECK: store [[CHILD]] to [init] [[BUFFER]] : $*Child
+// CHECK: [[FN:%.*]] = function_ref @$sSa10FoundationE19_bridgeToObjectiveCSo7NSArrayCyF : $@convention(method) <τ_0_0> (@guaranteed Array<τ_0_0>) -> @owned NSArray
+// CHECK: [[BORROW_ARRAY:%.*]] = begin_borrow [[ARRAY]] : $Array<Child>
+// CHECK: [[BRIDGED_ARRAY:%.*]] = apply [[FN]]<Child>([[BORROW_ARRAY]]) : $@convention(method) <τ_0_0> (@guaranteed Array<τ_0_0>) -> @owned NSArray
+// CHECK: end_borrow [[BORROW_ARRAY]] : $Array<Child>
+// CHECK: destroy_value [[ARRAY]] : $Array<Child>
+// CHECK: [[FN:%.*]] = objc_method [[COPIED]] : $[[OPENED_TYPE]], #Parent.children!setter.1.foreign : <Self where Self : Parent> (Self) -> ([Child]) -> (), $@convention(objc_method) <τ_0_0 where τ_0_0 : Parent> (NSArray, τ_0_0) -> ()
+// CHECK: apply [[FN]]<[[OPENED_TYPE]]>([[BRIDGED_ARRAY]], [[COPIED]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : Parent> (NSArray, τ_0_0) -> ()
+// CHECK: destroy_value [[BRIDGED_ARRAY]] : $NSArray
+// CHECK: destroy_value [[COPIED]] : $[[OPENED_TYPE]]
+// CHECK: [[RESULT:%.*]] = tuple ()
+// CHECK: return [[RESULT]] : $()
diff --git a/test/SILGen/scalar_to_tuple_args.swift b/test/SILGen/scalar_to_tuple_args.swift
index 83f203b..a549998 100644
--- a/test/SILGen/scalar_to_tuple_args.swift
+++ b/test/SILGen/scalar_to_tuple_args.swift
@@ -7,7 +7,7 @@
 func scalarWithDefaults(_ x: Int, y: Int = 0, z: Int = 0) {}
 func scalarWithCallerSideDefaults(_ x: Int, y: Int = #line) {}
 
-func tupleWithDefaults(x x: (Int, Int), y: Int = 0, z: Int = 0) {}
+func tupleWithDefaults(x: (Int, Int), y: Int = 0, z: Int = 0) {}
 
 func variadicFirst(_ x: Int...) {}
 func variadicSecond(_ x: Int, _ y: Int...) {}
@@ -57,16 +57,15 @@
 // CHECK: ([[ARRAY:%.*]], [[MEMORY:%.*]]) = destructure_tuple [[ALLOC_ARRAY]]
 // CHECK: [[ADDR:%.*]] = pointer_to_address [[MEMORY]]
 // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int
-// CHECK: [[X:%.*]] = load [trivial] [[READ]]
-// CHECK: store [[X]] to [trivial] [[ADDR]]
+// CHECK: copy_addr [[READ]] to [initialization] [[ADDR]]
 // CHECK: [[VARIADIC_FIRST:%.*]] = function_ref @$s20scalar_to_tuple_args13variadicFirstyySid_tF
 // CHECK: apply [[VARIADIC_FIRST]]([[ARRAY]])
 variadicFirst(x)
 
-// CHECK: [[ALLOC_ARRAY:%.*]] = apply {{.*}} -> (@owned Array<τ_0_0>, Builtin.RawPointer)
-// CHECK: ([[ARRAY:%.*]], [[MEMORY:%.*]]) = destructure_tuple [[ALLOC_ARRAY]]
 // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int
 // CHECK: [[X:%.*]] = load [trivial] [[READ]]
+// CHECK: [[ALLOC_ARRAY:%.*]] = apply {{.*}} -> (@owned Array<τ_0_0>, Builtin.RawPointer)
+// CHECK: ([[ARRAY:%.*]], [[MEMORY:%.*]]) = destructure_tuple [[ALLOC_ARRAY]]
 // CHECK: [[VARIADIC_SECOND:%.*]] = function_ref @$s20scalar_to_tuple_args14variadicSecondyySi_SidtF
 // CHECK: apply [[VARIADIC_SECOND]]([[X]], [[ARRAY]])
 variadicSecond(x)
diff --git a/test/SILGen/sil_locations.swift b/test/SILGen/sil_locations.swift
index 60814ac..850f58d 100644
--- a/test/SILGen/sil_locations.swift
+++ b/test/SILGen/sil_locations.swift
@@ -261,7 +261,7 @@
 func containers() -> ([Int], Dictionary<String, Int>) {
   return ([1, 2, 3], ["Ankeny": 1, "Burnside": 2, "Couch": 3])
   // CHECK-LABEL: sil hidden [ossa] @$s13sil_locations10containers{{[_0-9a-zA-Z]*}}F
-  // CHECK: apply {{%.*}}<(String, Int)>({{%.*}}), loc "{{.*}}":[[@LINE-2]]:22
+  // CHECK: apply {{%.*}}<(String, Int)>({{%.*}}), loc "{{.*}}":[[@LINE-2]]:23
   
   // CHECK: string_literal utf8 "Ankeny", loc "{{.*}}":[[@LINE-4]]:23
 
diff --git a/test/SILGen/stored_property_default_arg.swift b/test/SILGen/stored_property_default_arg.swift
index 62beda7..039418f 100644
--- a/test/SILGen/stored_property_default_arg.swift
+++ b/test/SILGen/stored_property_default_arg.swift
@@ -7,14 +7,15 @@
   var c: Bool = false
 }
 
+// CHECK-LABEL: sil hidden [ossa] @$s27stored_property_default_arg17checkConcreteTypeyyF : $@convention(thin) () -> () {
+func checkConcreteType() {
 // CHECK: function_ref variable initialization expression of A.c
 // CHECK-NEXT: [[C1_REF:%.*]] = function_ref @$s27stored_property_default_arg1AV1cSbvpfi : $@convention(thin) () -> Bool
 // CHECK-NEXT: [[C1:%.*]] = apply [[C1_REF]]() : $@convention(thin) () -> Bool
 // CHECK-NEXT: function_ref A.init(b:c:)
 // CHECK-NEXT: [[A1_REF:%.*]] = function_ref @$s27stored_property_default_arg1AV1b1cACSi_SbtcfC : $@convention(method) (Int, Bool, @thin A.Type) -> A
 // CHECK-NEXT: {{.*}} = apply [[A1_REF]]({{.*}}, [[C1]], {{.*}}) : $@convention(method) (Int, Bool, @thin A.Type) -> A
-
-let d = A(b: 1)
+  let d = A(b: 1)
 
 // CHECK: function_ref variable initialization expression of A.b
 // CHECK-NEXT: [[B1_REF:%.*]] = function_ref @$s27stored_property_default_arg1AV1bSivpfi : $@convention(thin) () -> Int
@@ -22,40 +23,43 @@
 // CHECK-NEXT: function_ref A.init(b:c:)
 // CHECK-NEXT: [[A2_REF:%.*]] = function_ref @$s27stored_property_default_arg1AV1b1cACSi_SbtcfC : $@convention(method) (Int, Bool, @thin A.Type) -> A
 // CHECK-NEXT: {{.*}} = apply [[A2_REF]]([[B1]], {{.*}}, {{.*}}) : $@convention(method) (Int, Bool, @thin A.Type) -> A
-
-let e = A(c: true)
+  let e = A(c: true)
+}
 
 struct F<T> {
   var g: T
   var h: Int = 0
 }
 
+// CHECK-LABEL: sil hidden [ossa] @$s27stored_property_default_arg16checkGenericTypeyyF : $@convention(thin) () -> () {
+func checkGenericType() {
 // CHECK: function_ref variable initialization expression of F.h
 // CHECK-NEXT: [[H1_REF:%.*]] = function_ref @$s27stored_property_default_arg1FV1hSivpfi : $@convention(thin) <τ_0_0> () -> Int
 // CHECK-NEXT: [[H1:%.*]] = apply [[H1_REF]]<Int>() : $@convention(thin) <τ_0_0> () -> Int
 // CHECK-NEXT: function_ref F.init(g:h:)
 // CHECK-NEXT: [[F1_REF:%.*]] = function_ref @$s27stored_property_default_arg1FV1g1hACyxGx_SitcfC : $@convention(method) <τ_0_0> (@in τ_0_0, Int, @thin F<τ_0_0>.Type) -> @out F<τ_0_0>
 // CHECK-NEXT: {{.*}} = apply [[F1_REF]]<Int>({{.*}}, {{.*}}, [[H1]], {{.*}}) : $@convention(method) <τ_0_0> (@in τ_0_0, Int, @thin F<τ_0_0>.Type) -> @out F<τ_0_0>
-
-let i = F(g: 128)
+  let i = F(g: 128)
+}
 
 struct J {
   lazy var k: Bool = false
   lazy var l: Int = 0
 }
 
+// CHECK-LABEL: sil hidden [ossa] @$s27stored_property_default_arg16checkOptionalNilyyF : $@convention(thin) () -> () {
+func checkOptionalNil() {
 // CHECK: {{.*}} = metatype $@thin Optional<Int>.Type
 // CHECK-NEXT: [[L1_REF:%.*]] = enum $Optional<Int>, #Optional.none!enumelt
 // CHECK-NEXT: function_ref J.init(k:l:)
 // CHECK-NEXT: [[J1_REF:%.*]] = function_ref @$s27stored_property_default_arg1JV1k1lACSbSg_SiSgtcfC : $@convention(method) (Optional<Bool>, Optional<Int>, @thin J.Type) -> J
 // CHECK-NEXT: {{.*}} = apply [[J1_REF]]({{.*}}, [[L1_REF]], {{.*}}) : $@convention(method) (Optional<Bool>, Optional<Int>, @thin J.Type) -> J
-
-let m = J(k: true)
+  let m = J(k: true)
 
 // CHECK: {{.*}} = metatype $@thin Optional<Bool>.Type
 // CHECK-NEXT: [[K1_REF:%.*]] = enum $Optional<Bool>, #Optional.none!enumelt
-// CHECK-NEXT: function_ref J.init(k:l:)
+// CHECK: function_ref J.init(k:l:)
 // CHECK-NEXT: [[J2_REF:%.*]] = function_ref @$s27stored_property_default_arg1JV1k1lACSbSg_SiSgtcfC : $@convention(method) (Optional<Bool>, Optional<Int>, @thin J.Type) -> J
 // CHECK-NEXT: {{.*}} = apply [[J2_REF]]([[K1_REF]], {{.*}}, {{.*}}) : $@convention(method) (Optional<Bool>, Optional<Int>, @thin J.Type) -> J
-
-let n = J(l: 316)
+  let n = J(l: 316)
+}
diff --git a/test/SILGen/witness_accessibility_multi.swift b/test/SILGen/witness_accessibility_multi.swift
index 340f5c2..a6577ac 100644
--- a/test/SILGen/witness_accessibility_multi.swift
+++ b/test/SILGen/witness_accessibility_multi.swift
@@ -15,7 +15,7 @@
 // CHECK-LABEL: sil [ossa] @$s27witness_accessibility_multi22callsPublicRequirement1sy0a1_B6_other1SV_tF : $@convention(thin) (S) -> ()
 public func callsPublicRequirement(s: S) {
 
-  // CHECK: witness_method $S, #P.publicRequirement!1 : <Self where Self : P> (Self) -> () -> () : $@convention(witness_method: P) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> ()
+  // CHECK: witness_method $S, #P.publicRequirement!1 : <Self where Self : witness_accessibility_other.P> (Self) -> () -> () : $@convention(witness_method: P) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> ()
   s.publicRequirement()
 
   // CHECK: function_ref @$s27witness_accessibility_other1QPAAE19internalRequirementyyF : $@convention(method) <τ_0_0 where τ_0_0 : Q> (@in_guaranteed τ_0_0) -> ()
diff --git a/test/Sanitizers/tsan-emptyarraystorage.swift b/test/Sanitizers/tsan-emptyarraystorage.swift
new file mode 100644
index 0000000..808b9e3
--- /dev/null
+++ b/test/Sanitizers/tsan-emptyarraystorage.swift
@@ -0,0 +1,40 @@
+// RUN: %target-swiftc_driver %s -target %sanitizers-target-triple -g -sanitize=thread -o %t_tsan-binary
+// RUN: %target-codesign %t_tsan-binary
+// RUN: %target-run %t_tsan-binary 2>&1 | %FileCheck %s
+// REQUIRES: executable_test
+// REQUIRES: tsan_runtime
+// UNSUPPORTED: OS=tvos
+
+// FIXME: This should be covered by "tsan_runtime"; older versions of Apple OSs
+// don't support TSan.
+// UNSUPPORTED: remote_run
+
+import Foundation
+
+let sem = DispatchSemaphore(value: 0)
+
+class T1: Thread {
+  override func main() {
+    var oneEmptyArray: [[String:String]] = []
+    oneEmptyArray.append(contentsOf: [])
+    sem.signal()
+  }
+}
+let t1 = T1()
+t1.start()
+
+class T2: Thread {
+  override func main() {
+    var aCompletelyUnrelatedOtherEmptyArray: [[Double:Double]] = []
+    aCompletelyUnrelatedOtherEmptyArray.append(contentsOf: [])
+    sem.signal()
+  }
+}
+let t2 = T2()
+t2.start()
+
+sem.wait()
+sem.wait()
+print("Done!")
+
+// CHECK: Done!
diff --git a/test/Serialization/Inputs/autolinking_implementation_only.swift b/test/Serialization/Inputs/autolinking_implementation_only.swift
new file mode 100644
index 0000000..ed4fd1e
--- /dev/null
+++ b/test/Serialization/Inputs/autolinking_implementation_only.swift
@@ -0,0 +1 @@
+public func dfunc() {}
diff --git a/test/Serialization/Inputs/autolinking_module_inferred.swift b/test/Serialization/Inputs/autolinking_module_inferred.swift
index 41f60c9..f50f084 100644
--- a/test/Serialization/Inputs/autolinking_module_inferred.swift
+++ b/test/Serialization/Inputs/autolinking_module_inferred.swift
@@ -2,7 +2,9 @@
 import autolinking_other
 import autolinking_indirect
 import autolinking_private
+@_implementationOnly import autolinking_implementation_only
 
 public func bfunc(x: Int = afunc(), y: Int = afunc2()) {
   cfunc()
+  dfunc()
 }
diff --git a/test/Serialization/Inputs/import-multi-file-other.swift b/test/Serialization/Inputs/import-multi-file-other.swift
new file mode 100644
index 0000000..7e95211
--- /dev/null
+++ b/test/Serialization/Inputs/import-multi-file-other.swift
@@ -0,0 +1,5 @@
+@_implementationOnly import A
+import B
+@_implementationOnly import C
+@_exported import D
+@_implementationOnly import E
diff --git a/test/Serialization/autolinking-inlinable-inferred.swift b/test/Serialization/autolinking-inlinable-inferred.swift
index 5bbb25d..709b63e 100644
--- a/test/Serialization/autolinking-inlinable-inferred.swift
+++ b/test/Serialization/autolinking-inlinable-inferred.swift
@@ -5,29 +5,72 @@
 // RUN: %target-swift-frontend -emit-module %S/Inputs/autolinking_private.swift -emit-module-path %t/autolinking_private.swiftmodule -module-link-name autolinking_private -I %t -swift-version 4
 // RUN: %target-swift-frontend -emit-module %S/Inputs/autolinking_other2.swift -emit-module-path %t/autolinking_other2.swiftmodule -module-link-name autolinking_other2 -swift-version 4
 // RUN: %target-swift-frontend -emit-module %S/Inputs/autolinking_indirect.swift -emit-module-path %t/autolinking_indirect.swiftmodule -module-link-name autolinking_indirect -I %t -swift-version 4
+// RUN: %target-swift-frontend -emit-module %S/Inputs/autolinking_implementation_only.swift -emit-module-path %t/autolinking_implementation_only.swiftmodule -module-link-name autolinking_implementation_only_BAD -I %t -swift-version 4
 
 // RUN: %target-swift-frontend -emit-module %S/Inputs/autolinking_module_inferred.swift -emit-module-path %t/autolinking_module_inferred.swiftmodule -module-link-name autolinking_module_inferred -I %t -swift-version 4
-// RUN: %target-swift-frontend -emit-ir %s -I %t -swift-version 4 -enable-objc-interop | %FileCheck %s -check-prefix CHECK -check-prefix CHECK-%target-os
+
+// RUN: %target-swift-frontend -emit-ir %s -I %t -swift-version 4 -enable-objc-interop -D NORMAL_IMPORT | %FileCheck -check-prefix CHECK -check-prefix CHECK-NORMAL -check-prefix CHECK-NORMAL-%target-os -implicit-check-not BAD %s
+// RUN: %target-swift-frontend -emit-ir %s -I %t -swift-version 4 -enable-objc-interop -D IMPLEMENTATION_ONLY_IMPORT | %FileCheck -check-prefix CHECK -check-prefix CHECK-IMPL_ONLY -check-prefix CHECK-IMPL_ONLY-%target-os -implicit-check-not BAD %s
+
+// RUN: %target-swift-frontend -emit-ir %s -I %t -swift-version 4 -enable-objc-interop -D NORMAL_AND_IMPLEMENTATION_ONLY | %FileCheck -check-prefix CHECK -check-prefix CHECK-NORMAL -check-prefix CHECK-NORMAL-%target-os -implicit-check-not BAD %s
+// RUN: %target-swift-frontend -emit-ir %s -I %t -swift-version 4 -enable-objc-interop -D IMPLEMENTATION_ONLY_AND_NORMAL | %FileCheck -check-prefix CHECK -check-prefix CHECK-NORMAL -check-prefix CHECK-NORMAL-%target-os -implicit-check-not BAD %s
+// RUN: %target-swift-frontend -emit-ir %s -I %t -swift-version 4 -enable-objc-interop -D EXPORTED_AND_IMPLEMENTATION_ONLY | %FileCheck -check-prefix CHECK -check-prefix CHECK-NORMAL -check-prefix CHECK-NORMAL-%target-os -implicit-check-not BAD %s
+// RUN: %target-swift-frontend -emit-ir %s -I %t -swift-version 4 -enable-objc-interop -D IMPLEMENTATION_ONLY_AND_EXPORTED | %FileCheck -check-prefix CHECK -check-prefix CHECK-NORMAL -check-prefix CHECK-NORMAL-%target-os -implicit-check-not BAD %s
 
 // Linux uses a different autolinking mechanism, based on
 // swift-autolink-extract. This file tests the Darwin mechanism.
 /// UNSUPPORTED: autolink-extract
 
+#if NORMAL_IMPORT
 import autolinking_module_inferred
 
+#elseif IMPLEMENTATION_ONLY_IMPORT
+@_implementationOnly import autolinking_module_inferred
+
+#elseif NORMAL_AND_IMPLEMENTATION_ONLY
+import autolinking_module_inferred
+@_implementationOnly import autolinking_module_inferred
+
+#elseif IMPLEMENTATION_ONLY_AND_NORMAL
+@_implementationOnly import autolinking_module_inferred
+import autolinking_module_inferred
+
+#elseif EXPORTED_AND_IMPLEMENTATION_ONLY
+@_exported import autolinking_module_inferred
+@_implementationOnly import autolinking_module_inferred
+
+#elseif IMPLEMENTATION_ONLY_AND_EXPORTED
+@_implementationOnly import autolinking_module_inferred
+@_exported import autolinking_module_inferred
+
+#else
+#error("must pick an import mode to test")
+#endif
+
 bfunc()
 
 // CHECK: !llvm.linker.options = !{
-// CHECK-SAME: [[MODULE:![0-9]+]],
-// CHECK-SAME: [[PUBLIC:![0-9]+]],
-// CHECK-SAME: [[SWIFTONONESUPPORT:![0-9]+]],
-// CHECK-SAME: [[SWIFTCORE:![0-9]+]],
-// CHECK-windows-msvc-SAME: [[STDIO:![0-9]+]],
+
+// CHECK-NORMAL-SAME: [[MODULE:![0-9]+]],
+// CHECK-NORMAL-SAME: [[PUBLIC:![0-9]+]],
+// CHECK-NORMAL-SAME: [[SWIFTONONESUPPORT:![0-9]+]],
+// CHECK-NORMAL-SAME: [[SWIFTCORE:![0-9]+]],
+// CHECK-NORMAL-windows-msvc-SAME: [[STDIO:![0-9]+]],
+
+// This is the same set as the above, just in a different order due to a
+// different traversal of the transitive import graph.
+// CHECK-IMPL_ONLY-SAME: [[SWIFTONONESUPPORT:![0-9]+]],
+// CHECK-IMPL_ONLY-SAME: [[SWIFTCORE:![0-9]+]],
+// CHECK-IMPL_ONLY-windows-msvc-SAME: [[STDIO:![0-9]+]],
+// CHECK-IMPL_ONLY-SAME: [[MODULE:![0-9]+]],
+// CHECK-IMPL_ONLY-SAME: [[PUBLIC:![0-9]+]],
+
 // CHECK-SAME: [[PRIVATE:![0-9]+]],
 // CHECK-SAME: [[OTHER:![0-9]+]],
 // CHECK-SAME: [[INDIRECT:![0-9]+]],
 // CHECK-SAME: [[OTHER2:![0-9]+]],
 // CHECK-SAME: [[OBJC:![0-9]+]]
+
 // CHECK-SAME: }
 
 // CHECK-DAG: [[MODULE]] = !{!{{"-lautolinking_module_inferred"|"/DEFAULTLIB:autolinking_module_inferred.lib"}}}
diff --git a/test/Serialization/import-multi-file.swift b/test/Serialization/import-multi-file.swift
new file mode 100644
index 0000000..591967d
--- /dev/null
+++ b/test/Serialization/import-multi-file.swift
@@ -0,0 +1,26 @@
+// RUN: %empty-directory(%t)
+// RUN: mkdir %t/a %t/b %t/c %t/d %t/e
+// RUN: %target-swift-frontend -emit-module -o %t/a/A.swiftmodule %S/../Inputs/empty.swift
+// RUN: %target-swift-frontend -emit-module -o %t/b/B.swiftmodule %S/../Inputs/empty.swift
+// RUN: %target-swift-frontend -emit-module -o %t/c/C.swiftmodule %S/../Inputs/empty.swift
+// RUN: %target-swift-frontend -emit-module -o %t/d/D.swiftmodule %S/../Inputs/empty.swift
+// RUN: %target-swift-frontend -emit-module -o %t/e/E.swiftmodule %S/../Inputs/empty.swift
+
+// RUN: %target-swift-frontend -emit-module -o %t/Library.swiftmodule %s %S/Inputs/import-multi-file-other.swift -I %t/a -I %t/b -I %t/c -I %t/d -I %t/e
+
+// RUN: echo "import Library" > %t/main.swift
+// RUN: %target-swift-frontend -typecheck %t/main.swift -I %t -I %t/a -I %t/b -I %t/c -I %t/d -I %t/e
+
+// We should be able to drop "E", which is implementation-only imported in both
+// files, but not any of the others.
+// RUN: %target-swift-frontend -typecheck %t/main.swift -I %t -I %t/a -I %t/b -I %t/c -I %t/d
+// RUN: not %target-swift-frontend -typecheck %t/main.swift -I %t -I %t/a -I %t/b -I %t/c -I %t/e
+// RUN: not %target-swift-frontend -typecheck %t/main.swift -I %t -I %t/a -I %t/b -I %t/d -I %t/e
+// RUN: not %target-swift-frontend -typecheck %t/main.swift -I %t -I %t/a -I %t/c -I %t/d -I %t/e
+// RUN: not %target-swift-frontend -typecheck %t/main.swift -I %t -I %t/b -I %t/c -I %t/d -I %t/e
+
+import A
+@_implementationOnly import B
+@_exported import C
+@_implementationOnly import D
+@_implementationOnly import E
diff --git a/test/Serialization/module-merging-implementation-only.swift b/test/Serialization/module-merging-implementation-only.swift
new file mode 100644
index 0000000..a31bdfd
--- /dev/null
+++ b/test/Serialization/module-merging-implementation-only.swift
@@ -0,0 +1,23 @@
+// This is a very simple test that module merging does not eliminate
+// @_implementationOnly imports or declarations referenced from those imports.
+// More thorough tests exist in LLDB, which can look into those imports when
+// debugging a client of the module with @_implementationOnly imports.
+
+// RUN: %empty-directory(%t)
+// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/def_struct.swift
+
+// RUN: %target-swift-frontend -emit-module -I %t -o %t/main~partial.swiftmodule -module-name main %s
+// RUN: llvm-bcanalyzer -dump %t/main~partial.swiftmodule | %FileCheck %s
+// RUN: grep -q TwoInts %t/main~partial.swiftmodule
+
+// RUN: %target-swift-frontend -merge-modules -emit-module -I %t -o %t/main.swiftmodule %t/main~partial.swiftmodule
+// RUN: llvm-bcanalyzer -dump %t/main.swiftmodule | %FileCheck %s
+// RUN: grep -q TwoInts %t/main.swiftmodule
+
+@_implementationOnly import def_struct
+
+struct Container {
+  var wrapped: TwoInts
+}
+
+// CHECK: <IMPORTED_MODULE abbrevid={{[0-9]+}} op0=2 op1=0{{.*}}/> blob data = 'def_struct'
diff --git a/test/SourceKit/DocSupport/doc_swift_module.swift.response b/test/SourceKit/DocSupport/doc_swift_module.swift.response
index 221f283..6c2a4f5 100644
--- a/test/SourceKit/DocSupport/doc_swift_module.swift.response
+++ b/test/SourceKit/DocSupport/doc_swift_module.swift.response
@@ -1,6 +1,6 @@
 import SwiftOnoneSupport
 
-class C1 : Prot {
+class C1 : cake.Prot {
 
     typealias Element = Int
 
@@ -26,13 +26,13 @@
     subscript(_ index: Int) -> Int { get }
 }
 
-extension C1 : P4 {
+extension C1 : cake.P4 {
 
     func C1foo()
 
     struct C1S1 {
 
-        func C1S1foo(a a: P4)
+        func C1S1foo(a a: cake.P4)
     }
 }
 
@@ -100,7 +100,7 @@
     associatedtype Element
 }
 
-protocol P6 : P5 {
+protocol P6 : cake.P5 {
 }
 
 extension P6 {
@@ -155,12 +155,12 @@
     static func != (_ lhs: S1.SE, _ rhs: S1.SE) -> Bool
 }
 
-struct S2 : P3 {
+struct S2 : cake.P3 {
 
     typealias T = cake.S2
 }
 
-struct S3<Wrapped> : P5 where Wrapped : P5 {
+struct S3<Wrapped> : cake.P5 where Wrapped : cake.P5 {
 
     typealias Element = Wrapped.Element
 }
@@ -170,7 +170,7 @@
     var null: Wrapped.Element? { get }
 }
 
-func genfoo<T1, T2>(x ix: T1, y iy: T2) where T1 : Prot, T2 : cake.C1, T1.Element == Int
+func genfoo<T1, T2>(x ix: T1, y iy: T2) where T1 : cake.Prot, T2 : cake.C1, T1.Element == Int
 
 
 [
@@ -195,762 +195,760 @@
     key.length: 2
   },
   {
-    key.kind: source.lang.swift.ref.protocol,
-    key.name: "Prot",
-    key.usr: "s:4cake4ProtP",
+    key.kind: source.lang.swift.syntaxtype.typeidentifier,
     key.offset: 37,
     key.length: 4
   },
   {
+    key.kind: source.lang.swift.ref.protocol,
+    key.name: "Prot",
+    key.usr: "s:4cake4ProtP",
+    key.offset: 42,
+    key.length: 4
+  },
+  {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 49,
+    key.offset: 54,
     key.length: 9
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 59,
+    key.offset: 64,
     key.length: 7
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 69,
+    key.offset: 74,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 78,
+    key.offset: 83,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 82,
+    key.offset: 87,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 85,
+    key.offset: 90,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 94,
-    key.length: 4
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.identifier,
     key.offset: 99,
-    key.length: 3
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 110,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
+    key.offset: 104,
+    key.length: 3
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.keyword,
     key.offset: 115,
     key.length: 4
   },
   {
-    key.kind: source.lang.swift.syntaxtype.argument,
+    key.kind: source.lang.swift.syntaxtype.identifier,
     key.offset: 120,
+    key.length: 4
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.argument,
+    key.offset: 125,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.parameter,
-    key.offset: 123,
+    key.offset: 128,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 127,
+    key.offset: 132,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.argument,
-    key.offset: 132,
+    key.offset: 137,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.parameter,
-    key.offset: 135,
+    key.offset: 140,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 139,
+    key.offset: 144,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 149,
+    key.offset: 154,
     key.length: 9
   },
   {
     key.kind: source.lang.swift.syntaxtype.argument,
-    key.offset: 159,
+    key.offset: 164,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.syntaxtype.parameter,
-    key.offset: 161,
+    key.offset: 166,
     key.length: 5
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 168,
+    key.offset: 173,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 176,
+    key.offset: 181,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 182,
+    key.offset: 187,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 193,
+    key.offset: 198,
     key.length: 9
   },
   {
     key.kind: source.lang.swift.syntaxtype.argument,
-    key.offset: 203,
+    key.offset: 208,
     key.length: 5
   },
   {
     key.kind: source.lang.swift.syntaxtype.parameter,
-    key.offset: 209,
+    key.offset: 214,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Float",
     key.usr: "s:Sf",
-    key.offset: 212,
+    key.offset: 217,
     key.length: 5
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 222,
+    key.offset: 227,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 228,
+    key.offset: 233,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 239,
+    key.offset: 244,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 244,
+    key.offset: 249,
     key.length: 7
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 254,
+    key.offset: 259,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 269,
+    key.offset: 274,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 274,
+    key.offset: 279,
     key.length: 5
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 291,
+    key.offset: 296,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 296,
+    key.offset: 301,
     key.length: 6
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 310,
-    key.length: 4
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.identifier,
     key.offset: 315,
     key.length: 4
   },
   {
+    key.kind: source.lang.swift.syntaxtype.identifier,
+    key.offset: 320,
+    key.length: 4
+  },
+  {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 327,
+    key.offset: 332,
     key.length: 9
   },
   {
     key.kind: source.lang.swift.syntaxtype.argument,
-    key.offset: 337,
+    key.offset: 342,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.syntaxtype.parameter,
-    key.offset: 339,
+    key.offset: 344,
     key.length: 5
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 346,
+    key.offset: 351,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 354,
+    key.offset: 359,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 360,
+    key.offset: 365,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 369,
+    key.offset: 374,
     key.length: 9
   },
   {
     key.kind: source.lang.swift.ref.class,
     key.name: "C1",
     key.usr: "s:4cake2C1C",
-    key.offset: 379,
-    key.length: 2
-  },
-  {
-    key.kind: source.lang.swift.ref.protocol,
-    key.name: "P4",
-    key.usr: "s:4cake2P4P",
     key.offset: 384,
     key.length: 2
   },
   {
-    key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 394,
+    key.kind: source.lang.swift.syntaxtype.typeidentifier,
+    key.offset: 389,
     key.length: 4
   },
   {
-    key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 399,
-    key.length: 5
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 412,
-    key.length: 6
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 419,
-    key.length: 4
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 435,
-    key.length: 4
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 440,
-    key.length: 7
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.argument,
-    key.offset: 448,
-    key.length: 1
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.parameter,
-    key.offset: 450,
-    key.length: 1
-  },
-  {
     key.kind: source.lang.swift.ref.protocol,
     key.name: "P4",
     key.usr: "s:4cake2P4P",
-    key.offset: 453,
+    key.offset: 394,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 466,
+    key.offset: 404,
+    key.length: 4
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.identifier,
+    key.offset: 409,
+    key.length: 5
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.keyword,
+    key.offset: 422,
+    key.length: 6
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.identifier,
+    key.offset: 429,
+    key.length: 4
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.keyword,
+    key.offset: 445,
+    key.length: 4
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.identifier,
+    key.offset: 450,
+    key.length: 7
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.argument,
+    key.offset: 458,
+    key.length: 1
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.parameter,
+    key.offset: 460,
+    key.length: 1
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.typeidentifier,
+    key.offset: 463,
+    key.length: 4
+  },
+  {
+    key.kind: source.lang.swift.ref.protocol,
+    key.name: "P4",
+    key.usr: "s:4cake2P4P",
+    key.offset: 468,
+    key.length: 2
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.keyword,
+    key.offset: 481,
     key.length: 9
   },
   {
     key.kind: source.lang.swift.ref.class,
     key.name: "C1",
     key.usr: "s:4cake2C1C",
-    key.offset: 476,
+    key.offset: 491,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.ref.enum,
     key.name: "C1Cases",
     key.usr: "s:4cake2C1C0B5CasesO",
-    key.offset: 479,
+    key.offset: 494,
     key.length: 7
   },
   {
     key.kind: source.lang.swift.syntaxtype.attribute.builtin,
-    key.offset: 494,
+    key.offset: 509,
     key.length: 10
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 505,
+    key.offset: 520,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 509,
+    key.offset: 524,
     key.length: 9
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 520,
+    key.offset: 535,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 526,
+    key.offset: 541,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.attribute.builtin,
-    key.offset: 537,
+    key.offset: 552,
     key.length: 10
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 548,
+    key.offset: 563,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 553,
+    key.offset: 568,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.argument,
-    key.offset: 558,
+    key.offset: 573,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.parameter,
-    key.offset: 563,
+    key.offset: 578,
     key.length: 6
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 571,
+    key.offset: 586,
     key.length: 5
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Hasher",
     key.usr: "s:s6HasherV",
-    key.offset: 577,
+    key.offset: 592,
     key.length: 6
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 590,
+    key.offset: 605,
     key.length: 6
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 597,
+    key.offset: 612,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.argument,
-    key.offset: 606,
+    key.offset: 621,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.syntaxtype.parameter,
-    key.offset: 608,
+    key.offset: 623,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.ref.class,
     key.name: "C1",
     key.usr: "s:4cake2C1C",
-    key.offset: 613,
+    key.offset: 628,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.ref.enum,
     key.name: "C1Cases",
     key.usr: "s:4cake2C1C0B5CasesO",
-    key.offset: 616,
+    key.offset: 631,
     key.length: 7
   },
   {
     key.kind: source.lang.swift.syntaxtype.argument,
-    key.offset: 625,
+    key.offset: 640,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.syntaxtype.parameter,
-    key.offset: 627,
+    key.offset: 642,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.ref.class,
     key.name: "C1",
     key.usr: "s:4cake2C1C",
-    key.offset: 632,
+    key.offset: 647,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.ref.enum,
     key.name: "C1Cases",
     key.usr: "s:4cake2C1C0B5CasesO",
-    key.offset: 635,
+    key.offset: 650,
     key.length: 7
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Bool",
     key.usr: "s:Sb",
-    key.offset: 647,
+    key.offset: 662,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 655,
+    key.offset: 670,
     key.length: 5
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 661,
+    key.offset: 676,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.typeidentifier,
-    key.offset: 666,
+    key.offset: 681,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.ref.class,
     key.name: "C1",
     key.usr: "s:4cake2C1C",
-    key.offset: 671,
+    key.offset: 686,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 681,
+    key.offset: 696,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 686,
+    key.offset: 701,
     key.length: 5
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 699,
+    key.offset: 714,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 704,
+    key.offset: 719,
     key.length: 7
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 714,
+    key.offset: 729,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 729,
+    key.offset: 744,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 734,
+    key.offset: 749,
     key.length: 5
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 751,
+    key.offset: 766,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 756,
+    key.offset: 771,
     key.length: 6
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 770,
+    key.offset: 785,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 775,
+    key.offset: 790,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 787,
+    key.offset: 802,
     key.length: 9
   },
   {
     key.kind: source.lang.swift.syntaxtype.argument,
-    key.offset: 797,
+    key.offset: 812,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.syntaxtype.parameter,
-    key.offset: 799,
+    key.offset: 814,
     key.length: 5
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 806,
+    key.offset: 821,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 814,
-    key.length: 3
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 820,
-    key.length: 3
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.keyword,
     key.offset: 829,
+    key.length: 3
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.keyword,
+    key.offset: 835,
+    key.length: 3
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.keyword,
+    key.offset: 844,
     key.length: 9
   },
   {
     key.kind: source.lang.swift.ref.class,
     key.name: "C2",
     key.usr: "s:4cake2C2C",
-    key.offset: 839,
+    key.offset: 854,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.ref.protocol,
     key.name: "P4",
     key.usr: "s:4cake2P4P",
-    key.offset: 844,
+    key.offset: 859,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 854,
+    key.offset: 869,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 859,
+    key.offset: 874,
     key.length: 5
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 872,
+    key.offset: 887,
     key.length: 6
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 879,
+    key.offset: 894,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 895,
+    key.offset: 910,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 900,
+    key.offset: 915,
     key.length: 7
   },
   {
     key.kind: source.lang.swift.syntaxtype.argument,
-    key.offset: 908,
+    key.offset: 923,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.syntaxtype.parameter,
-    key.offset: 910,
+    key.offset: 925,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.ref.protocol,
     key.name: "P4",
     key.usr: "s:4cake2P4P",
-    key.offset: 913,
+    key.offset: 928,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 926,
+    key.offset: 941,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 931,
+    key.offset: 946,
     key.length: 6
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 940,
+    key.offset: 955,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 951,
+    key.offset: 966,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 956,
+    key.offset: 971,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.attribute.builtin,
-    key.offset: 966,
+    key.offset: 981,
     key.length: 10
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 977,
+    key.offset: 992,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 981,
+    key.offset: 996,
     key.length: 9
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 992,
+    key.offset: 1007,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 998,
+    key.offset: 1013,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.attribute.builtin,
-    key.offset: 1009,
+    key.offset: 1024,
     key.length: 10
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1020,
+    key.offset: 1035,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1025,
+    key.offset: 1040,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.argument,
-    key.offset: 1030,
+    key.offset: 1045,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.parameter,
-    key.offset: 1035,
+    key.offset: 1050,
     key.length: 6
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1043,
+    key.offset: 1058,
     key.length: 5
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Hasher",
     key.usr: "s:s6HasherV",
-    key.offset: 1049,
+    key.offset: 1064,
     key.length: 6
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1062,
+    key.offset: 1077,
     key.length: 6
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1069,
+    key.offset: 1084,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.argument,
-    key.offset: 1078,
-    key.length: 1
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.parameter,
-    key.offset: 1080,
-    key.length: 3
-  },
-  {
-    key.kind: source.lang.swift.ref.enum,
-    key.name: "MyEnum",
-    key.usr: "s:4cake6MyEnumO",
-    key.offset: 1085,
-    key.length: 6
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.argument,
     key.offset: 1093,
     key.length: 1
   },
@@ -967,704 +965,702 @@
     key.length: 6
   },
   {
+    key.kind: source.lang.swift.syntaxtype.argument,
+    key.offset: 1108,
+    key.length: 1
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.parameter,
+    key.offset: 1110,
+    key.length: 3
+  },
+  {
+    key.kind: source.lang.swift.ref.enum,
+    key.name: "MyEnum",
+    key.usr: "s:4cake6MyEnumO",
+    key.offset: 1115,
+    key.length: 6
+  },
+  {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Bool",
     key.usr: "s:Sb",
-    key.offset: 1111,
+    key.offset: 1126,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.attribute.builtin,
-    key.offset: 1119,
+    key.offset: 1134,
     key.length: 5
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1125,
+    key.offset: 1140,
     key.length: 8
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1134,
+    key.offset: 1149,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.attribute.builtin,
-    key.offset: 1144,
+    key.offset: 1159,
     key.length: 5
   },
   {
     key.kind: source.lang.swift.syntaxtype.attribute.builtin,
-    key.offset: 1150,
+    key.offset: 1165,
     key.length: 8
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1159,
-    key.length: 4
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1164,
-    key.length: 4
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.keyword,
     key.offset: 1174,
+    key.length: 4
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.identifier,
+    key.offset: 1179,
+    key.length: 4
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.keyword,
+    key.offset: 1189,
     key.length: 8
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1183,
+    key.offset: 1198,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1193,
+    key.offset: 1208,
     key.length: 14
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1208,
+    key.offset: 1223,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1213,
+    key.offset: 1228,
     key.length: 8
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1222,
+    key.offset: 1237,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1230,
+    key.offset: 1245,
     key.length: 8
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1239,
+    key.offset: 1254,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1249,
+    key.offset: 1264,
     key.length: 14
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1264,
+    key.offset: 1279,
     key.length: 7
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1275,
+    key.offset: 1290,
     key.length: 8
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1284,
+    key.offset: 1299,
     key.length: 2
   },
   {
+    key.kind: source.lang.swift.syntaxtype.typeidentifier,
+    key.offset: 1304,
+    key.length: 4
+  },
+  {
     key.kind: source.lang.swift.ref.protocol,
     key.name: "P5",
     key.usr: "s:4cake2P5P",
-    key.offset: 1289,
+    key.offset: 1309,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1297,
+    key.offset: 1317,
     key.length: 9
   },
   {
     key.kind: source.lang.swift.ref.protocol,
     key.name: "P6",
     key.usr: "s:4cake2P6P",
-    key.offset: 1307,
+    key.offset: 1327,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1317,
+    key.offset: 1337,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1321,
+    key.offset: 1341,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.ref.generic_type_param,
     key.name: "Self",
     key.usr: "s:4cake2P6P4Selfxmfp",
-    key.offset: 1327,
+    key.offset: 1347,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.typeidentifier,
-    key.offset: 1332,
+    key.offset: 1352,
     key.length: 7
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1343,
+    key.offset: 1363,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1352,
+    key.offset: 1372,
     key.length: 8
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1361,
+    key.offset: 1381,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1373,
+    key.offset: 1393,
     key.length: 14
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1388,
+    key.offset: 1408,
     key.length: 7
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1401,
+    key.offset: 1421,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1405,
+    key.offset: 1425,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 1408,
+    key.offset: 1428,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1414,
+    key.offset: 1434,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1425,
+    key.offset: 1445,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1430,
+    key.offset: 1450,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1441,
+    key.offset: 1461,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1446,
+    key.offset: 1466,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1456,
+    key.offset: 1476,
     key.length: 9
   },
   {
     key.kind: source.lang.swift.ref.protocol,
     key.name: "Prot",
     key.usr: "s:4cake4ProtP",
-    key.offset: 1466,
+    key.offset: 1486,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1478,
+    key.offset: 1498,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1483,
+    key.offset: 1503,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1495,
+    key.offset: 1515,
     key.length: 9
   },
   {
     key.kind: source.lang.swift.syntaxtype.argument,
-    key.offset: 1505,
+    key.offset: 1525,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.syntaxtype.parameter,
-    key.offset: 1507,
+    key.offset: 1527,
     key.length: 5
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 1514,
+    key.offset: 1534,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 1522,
+    key.offset: 1542,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1528,
+    key.offset: 1548,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1537,
+    key.offset: 1557,
     key.length: 9
   },
   {
     key.kind: source.lang.swift.ref.protocol,
     key.name: "Prot",
     key.usr: "s:4cake4ProtP",
-    key.offset: 1547,
+    key.offset: 1567,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1552,
+    key.offset: 1572,
     key.length: 5
   },
   {
     key.kind: source.lang.swift.ref.generic_type_param,
     key.name: "Self",
     key.usr: "s:4cake4ProtPAASi7ElementRtzrlE4Selfxmfp",
-    key.offset: 1558,
+    key.offset: 1578,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.typeidentifier,
-    key.offset: 1563,
+    key.offset: 1583,
     key.length: 7
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 1574,
+    key.offset: 1594,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1585,
+    key.offset: 1605,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1590,
+    key.offset: 1610,
     key.length: 6
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1602,
+    key.offset: 1622,
     key.length: 6
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1609,
+    key.offset: 1629,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1619,
+    key.offset: 1639,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1624,
+    key.offset: 1644,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1638,
+    key.offset: 1658,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1643,
+    key.offset: 1663,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1654,
+    key.offset: 1674,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1659,
+    key.offset: 1679,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1670,
+    key.offset: 1690,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1675,
+    key.offset: 1695,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1688,
+    key.offset: 1708,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1693,
+    key.offset: 1713,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1705,
+    key.offset: 1725,
     key.length: 6
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1712,
+    key.offset: 1732,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1726,
+    key.offset: 1746,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1730,
+    key.offset: 1750,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 1733,
+    key.offset: 1753,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1746,
+    key.offset: 1766,
     key.length: 9
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "S1",
     key.usr: "s:4cake2S1V",
-    key.offset: 1756,
+    key.offset: 1776,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.ref.enum,
     key.name: "SE",
     key.usr: "s:4cake2S1V2SEO",
-    key.offset: 1759,
+    key.offset: 1779,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1769,
+    key.offset: 1789,
     key.length: 6
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1776,
+    key.offset: 1796,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.argument,
-    key.offset: 1785,
+    key.offset: 1805,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.syntaxtype.parameter,
-    key.offset: 1787,
+    key.offset: 1807,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "S1",
     key.usr: "s:4cake2S1V",
-    key.offset: 1792,
+    key.offset: 1812,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.ref.enum,
     key.name: "SE",
     key.usr: "s:4cake2S1V2SEO",
-    key.offset: 1795,
+    key.offset: 1815,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.argument,
-    key.offset: 1799,
+    key.offset: 1819,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.syntaxtype.parameter,
-    key.offset: 1801,
+    key.offset: 1821,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "S1",
     key.usr: "s:4cake2S1V",
-    key.offset: 1806,
+    key.offset: 1826,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.ref.enum,
     key.name: "SE",
     key.usr: "s:4cake2S1V2SEO",
-    key.offset: 1809,
+    key.offset: 1829,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Bool",
     key.usr: "s:Sb",
-    key.offset: 1816,
+    key.offset: 1836,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1824,
+    key.offset: 1844,
     key.length: 6
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1831,
+    key.offset: 1851,
     key.length: 2
   },
   {
+    key.kind: source.lang.swift.syntaxtype.typeidentifier,
+    key.offset: 1856,
+    key.length: 4
+  },
+  {
     key.kind: source.lang.swift.ref.protocol,
     key.name: "P3",
     key.usr: "s:4cake2P3P",
-    key.offset: 1836,
+    key.offset: 1861,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1846,
+    key.offset: 1871,
     key.length: 9
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1856,
+    key.offset: 1881,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.syntaxtype.typeidentifier,
-    key.offset: 1860,
+    key.offset: 1885,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "S2",
     key.usr: "s:4cake2S2V",
-    key.offset: 1865,
+    key.offset: 1890,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1871,
+    key.offset: 1896,
     key.length: 6
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1878,
+    key.offset: 1903,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1881,
+    key.offset: 1906,
     key.length: 7
   },
   {
+    key.kind: source.lang.swift.syntaxtype.typeidentifier,
+    key.offset: 1917,
+    key.length: 4
+  },
+  {
     key.kind: source.lang.swift.ref.protocol,
     key.name: "P5",
     key.usr: "s:4cake2P5P",
-    key.offset: 1892,
+    key.offset: 1922,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1895,
+    key.offset: 1925,
     key.length: 5
   },
   {
     key.kind: source.lang.swift.syntaxtype.typeidentifier,
-    key.offset: 1901,
-    key.length: 7
-  },
-  {
-    key.kind: source.lang.swift.ref.protocol,
-    key.name: "P5",
-    key.usr: "s:4cake2P5P",
-    key.offset: 1911,
-    key.length: 2
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1921,
-    key.length: 9
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.identifier,
     key.offset: 1931,
     key.length: 7
   },
   {
     key.kind: source.lang.swift.syntaxtype.typeidentifier,
     key.offset: 1941,
+    key.length: 4
+  },
+  {
+    key.kind: source.lang.swift.ref.protocol,
+    key.name: "P5",
+    key.usr: "s:4cake2P5P",
+    key.offset: 1946,
+    key.length: 2
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.keyword,
+    key.offset: 1956,
+    key.length: 9
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.identifier,
+    key.offset: 1966,
     key.length: 7
   },
   {
     key.kind: source.lang.swift.syntaxtype.typeidentifier,
-    key.offset: 1949,
+    key.offset: 1976,
+    key.length: 7
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.typeidentifier,
+    key.offset: 1984,
     key.length: 7
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1960,
+    key.offset: 1995,
     key.length: 9
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "S3",
     key.usr: "s:4cake2S3V",
-    key.offset: 1970,
+    key.offset: 2005,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 1980,
+    key.offset: 2015,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 1984,
+    key.offset: 2019,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.typeidentifier,
-    key.offset: 1990,
+    key.offset: 2025,
     key.length: 7
   },
   {
     key.kind: source.lang.swift.syntaxtype.typeidentifier,
-    key.offset: 1998,
+    key.offset: 2033,
     key.length: 7
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 2009,
+    key.offset: 2044,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 2018,
+    key.offset: 2053,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 2023,
+    key.offset: 2058,
     key.length: 6
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 2030,
+    key.offset: 2065,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 2034,
-    key.length: 2
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.argument,
-    key.offset: 2038,
-    key.length: 1
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.parameter,
-    key.offset: 2040,
-    key.length: 2
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.typeidentifier,
-    key.offset: 2044,
-    key.length: 2
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.argument,
-    key.offset: 2048,
-    key.length: 1
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.parameter,
-    key.offset: 2050,
-    key.length: 2
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.typeidentifier,
-    key.offset: 2054,
-    key.length: 2
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 2058,
-    key.length: 5
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.typeidentifier,
-    key.offset: 2064,
-    key.length: 2
-  },
-  {
-    key.kind: source.lang.swift.ref.protocol,
-    key.name: "Prot",
-    key.usr: "s:4cake4ProtP",
     key.offset: 2069,
-    key.length: 4
+    key.length: 2
   },
   {
-    key.kind: source.lang.swift.syntaxtype.typeidentifier,
+    key.kind: source.lang.swift.syntaxtype.argument,
+    key.offset: 2073,
+    key.length: 1
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.parameter,
     key.offset: 2075,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.typeidentifier,
-    key.offset: 2080,
-    key.length: 4
+    key.offset: 2079,
+    key.length: 2
   },
   {
-    key.kind: source.lang.swift.ref.class,
-    key.name: "C1",
-    key.usr: "s:4cake2C1C",
+    key.kind: source.lang.swift.syntaxtype.argument,
+    key.offset: 2083,
+    key.length: 1
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.parameter,
     key.offset: 2085,
     key.length: 2
   },
@@ -1674,15 +1670,59 @@
     key.length: 2
   },
   {
+    key.kind: source.lang.swift.syntaxtype.keyword,
+    key.offset: 2093,
+    key.length: 5
+  },
+  {
     key.kind: source.lang.swift.syntaxtype.typeidentifier,
-    key.offset: 2092,
+    key.offset: 2099,
+    key.length: 2
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.typeidentifier,
+    key.offset: 2104,
+    key.length: 4
+  },
+  {
+    key.kind: source.lang.swift.ref.protocol,
+    key.name: "Prot",
+    key.usr: "s:4cake4ProtP",
+    key.offset: 2109,
+    key.length: 4
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.typeidentifier,
+    key.offset: 2115,
+    key.length: 2
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.typeidentifier,
+    key.offset: 2120,
+    key.length: 4
+  },
+  {
+    key.kind: source.lang.swift.ref.class,
+    key.name: "C1",
+    key.usr: "s:4cake2C1C",
+    key.offset: 2125,
+    key.length: 2
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.typeidentifier,
+    key.offset: 2129,
+    key.length: 2
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.typeidentifier,
+    key.offset: 2132,
     key.length: 7
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 2103,
+    key.offset: 2143,
     key.length: 3
   }
 ]
@@ -1692,7 +1732,7 @@
     key.name: "C1",
     key.usr: "s:4cake2C1C",
     key.offset: 26,
-    key.length: 341,
+    key.length: 346,
     key.fully_annotated_decl: "<decl.class><syntaxtype.keyword>class</syntaxtype.keyword> <decl.name>C1</decl.name> : <ref.protocol usr=\"s:4cake4ProtP\">Prot</ref.protocol></decl.class>",
     key.conforms: [
       {
@@ -1706,7 +1746,7 @@
         key.kind: source.lang.swift.decl.typealias,
         key.name: "Element",
         key.usr: "s:4cake2C1C7Elementa",
-        key.offset: 49,
+        key.offset: 54,
         key.length: 23,
         key.fully_annotated_decl: "<decl.typealias><syntaxtype.keyword>typealias</syntaxtype.keyword> <ref.class usr=\"s:4cake2C1C\">C1</ref.class>.<decl.name>Element</decl.name> = <ref.struct usr=\"s:Si\">Int</ref.struct></decl.typealias>",
         key.conforms: [
@@ -1731,7 +1771,7 @@
         key.kind: source.lang.swift.decl.var.instance,
         key.name: "p",
         key.usr: "s:4cake2C1C1pSivp",
-        key.offset: 78,
+        key.offset: 83,
         key.length: 10,
         key.fully_annotated_decl: "<decl.var.instance><syntaxtype.keyword>var</syntaxtype.keyword> <decl.name>p</decl.name>: <decl.var.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.type></decl.var.instance>",
         key.conforms: [
@@ -1746,7 +1786,7 @@
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "foo()",
         key.usr: "s:4cake2C1C3fooyyF",
-        key.offset: 94,
+        key.offset: 99,
         key.length: 10,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>foo</decl.name>()</decl.function.method.instance>",
         key.conforms: [
@@ -1761,7 +1801,7 @@
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "foo1(i0:i1:)",
         key.usr: "s:4cake2C1C4foo12i02i1ySin_SihtF",
-        key.offset: 110,
+        key.offset: 115,
         key.length: 33,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>foo1</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>i0</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.argument_label>i1</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.method.instance>",
         key.entities: [
@@ -1769,14 +1809,14 @@
             key.kind: source.lang.swift.decl.var.local,
             key.keyword: "i0",
             key.name: "i0",
-            key.offset: 127,
+            key.offset: 132,
             key.length: 3
           },
           {
             key.kind: source.lang.swift.decl.var.local,
             key.keyword: "i1",
             key.name: "i1",
-            key.offset: 139,
+            key.offset: 144,
             key.length: 3
           }
         ]
@@ -1785,7 +1825,7 @@
         key.kind: source.lang.swift.decl.function.subscript,
         key.name: "subscript(_:)",
         key.usr: "s:4cake2C1CyS2icip",
-        key.offset: 149,
+        key.offset: 154,
         key.length: 38,
         key.fully_annotated_decl: "<decl.function.subscript><syntaxtype.keyword>subscript</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.name>index</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Si\">Int</ref.struct></decl.function.returntype> { <syntaxtype.keyword>get</syntaxtype.keyword> }</decl.function.subscript>",
         key.entities: [
@@ -1793,7 +1833,7 @@
             key.kind: source.lang.swift.decl.var.local,
             key.keyword: "_",
             key.name: "index",
-            key.offset: 168,
+            key.offset: 173,
             key.length: 3
           }
         ]
@@ -1802,7 +1842,7 @@
         key.kind: source.lang.swift.decl.function.subscript,
         key.name: "subscript(index:)",
         key.usr: "s:4cake2C1C5indexSiSf_tcip",
-        key.offset: 193,
+        key.offset: 198,
         key.length: 40,
         key.fully_annotated_decl: "<decl.function.subscript><syntaxtype.keyword>subscript</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.argument_label>index</decl.var.parameter.argument_label> <decl.var.parameter.name>i</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"s:Sf\">Float</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Si\">Int</ref.struct></decl.function.returntype> { <syntaxtype.keyword>get</syntaxtype.keyword> }</decl.function.subscript>",
         key.entities: [
@@ -1810,7 +1850,7 @@
             key.kind: source.lang.swift.decl.var.local,
             key.keyword: "index",
             key.name: "i",
-            key.offset: 212,
+            key.offset: 217,
             key.length: 5
           }
         ]
@@ -1819,7 +1859,7 @@
         key.kind: source.lang.swift.decl.enum,
         key.name: "C1Cases",
         key.usr: "s:4cake2C1C0B5CasesO",
-        key.offset: 239,
+        key.offset: 244,
         key.length: 46,
         key.fully_annotated_decl: "<decl.enum><syntaxtype.keyword>enum</syntaxtype.keyword> <decl.name>C1Cases</decl.name> : <ref.struct usr=\"s:Si\">Int</ref.struct></decl.enum>",
         key.inherits: [
@@ -1834,7 +1874,7 @@
             key.kind: source.lang.swift.decl.enumelement,
             key.name: "case1",
             key.usr: "s:4cake2C1C0B5CasesO5case1yA2EmF",
-            key.offset: 269,
+            key.offset: 274,
             key.length: 10,
             key.fully_annotated_decl: "<decl.enumelement><syntaxtype.keyword>case</syntaxtype.keyword> <decl.name>case1</decl.name></decl.enumelement>"
           }
@@ -1845,7 +1885,7 @@
         key.name: "extfoo()",
         key.usr: "s:4cake4ProtPAASi7ElementRtzrlE6extfooyyF::SYNTHESIZED::s:4cake2C1C",
         key.original_usr: "s:4cake4ProtPAASi7ElementRtzrlE6extfooyyF",
-        key.offset: 291,
+        key.offset: 296,
         key.length: 13,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>extfoo</decl.name>()</decl.function.method.instance>"
       },
@@ -1854,7 +1894,7 @@
         key.name: "foo1()",
         key.usr: "s:4cake4ProtPAAE4foo1yyF::SYNTHESIZED::s:4cake2C1C",
         key.original_usr: "s:4cake4ProtPAAE4foo1yyF",
-        key.offset: 310,
+        key.offset: 315,
         key.length: 11,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>foo1</decl.name>()</decl.function.method.instance>"
       },
@@ -1863,7 +1903,7 @@
         key.name: "subscript(_:)",
         key.usr: "s:4cake4ProtPAAEyS2icip::SYNTHESIZED::s:4cake2C1C",
         key.original_usr: "s:4cake4ProtPAAEyS2icip",
-        key.offset: 327,
+        key.offset: 332,
         key.length: 38,
         key.fully_annotated_decl: "<decl.function.subscript><syntaxtype.keyword>subscript</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.name>index</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Si\">Int</ref.struct></decl.function.returntype> { <syntaxtype.keyword>get</syntaxtype.keyword> }</decl.function.subscript>",
         key.entities: [
@@ -1871,7 +1911,7 @@
             key.kind: source.lang.swift.decl.var.local,
             key.keyword: "_",
             key.name: "index",
-            key.offset: 346,
+            key.offset: 351,
             key.length: 3
           }
         ]
@@ -1880,8 +1920,8 @@
   },
   {
     key.kind: source.lang.swift.decl.extension.class,
-    key.offset: 369,
-    key.length: 95,
+    key.offset: 374,
+    key.length: 105,
     key.conforms: [
       {
         key.kind: source.lang.swift.ref.protocol,
@@ -1899,7 +1939,7 @@
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "C1foo()",
         key.usr: "s:4cake2C1C5C1fooyyF",
-        key.offset: 394,
+        key.offset: 404,
         key.length: 12,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>C1foo</decl.name>()</decl.function.method.instance>"
       },
@@ -1907,24 +1947,24 @@
         key.kind: source.lang.swift.decl.struct,
         key.name: "C1S1",
         key.usr: "s:4cake2C1C0B2S1V",
-        key.offset: 412,
-        key.length: 50,
+        key.offset: 422,
+        key.length: 55,
         key.fully_annotated_decl: "<decl.struct><syntaxtype.keyword>struct</syntaxtype.keyword> <decl.name>C1S1</decl.name></decl.struct>",
         key.entities: [
           {
             key.kind: source.lang.swift.decl.function.method.instance,
             key.name: "C1S1foo(a:)",
             key.usr: "s:4cake2C1C0B2S1V0B5S1foo1ayAA2P4_p_tF",
-            key.offset: 435,
-            key.length: 21,
+            key.offset: 445,
+            key.length: 26,
             key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>C1S1foo</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>a</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.protocol usr=\"s:4cake2P4P\">P4</ref.protocol></decl.var.parameter.type></decl.var.parameter>)</decl.function.method.instance>",
             key.entities: [
               {
                 key.kind: source.lang.swift.decl.var.local,
                 key.keyword: "a",
                 key.name: "a",
-                key.offset: 453,
-                key.length: 2
+                key.offset: 463,
+                key.length: 7
               }
             ]
           }
@@ -1942,7 +1982,7 @@
         key.description: "Self.RawValue : Hashable"
       }
     ],
-    key.offset: 466,
+    key.offset: 481,
     key.length: 187,
     key.fully_annotated_generic_signature: "&lt;<decl.generic_type_param usr=\"s:SYsSHRzSH8RawValueSYRpzrlE4Selfxmfp\"><decl.generic_type_param.name>Self</decl.generic_type_param.name></decl.generic_type_param> <syntaxtype.keyword>where</syntaxtype.keyword> <decl.generic_type_requirement><ref.generic_type_param usr=\"s:SYsSHRzSH8RawValueSYRpzrlE4Selfxmfp\">Self</ref.generic_type_param> : <ref.protocol usr=\"s:SH\">Hashable</ref.protocol></decl.generic_type_requirement>, <decl.generic_type_requirement><ref.generic_type_param usr=\"s:SYsSHRzSH8RawValueSYRpzrlE4Selfxmfp\">Self</ref.generic_type_param> : <ref.protocol usr=\"s:SY\">RawRepresentable</ref.protocol></decl.generic_type_requirement>, <decl.generic_type_requirement><ref.generic_type_param usr=\"s:SYsSHRzSH8RawValueSYRpzrlE4Selfxmfp\">Self</ref.generic_type_param>.RawValue : <ref.protocol usr=\"s:SH\">Hashable</ref.protocol></decl.generic_type_requirement>&gt;",
     key.extends: {
@@ -1956,7 +1996,7 @@
         key.name: "hashValue",
         key.usr: "s:SYsSHRzSH8RawValueSYRpzrlE04hashB0Sivp::SYNTHESIZED::s:4cake2C1C0B5CasesO",
         key.original_usr: "s:SYsSHRzSH8RawValueSYRpzrlE04hashB0Sivp",
-        key.offset: 494,
+        key.offset: 509,
         key.length: 37,
         key.fully_annotated_decl: "<decl.var.instance><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@inlinable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>var</syntaxtype.keyword> <decl.name>hashValue</decl.name>: <decl.var.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.type> { <syntaxtype.keyword>get</syntaxtype.keyword> }</decl.var.instance>"
       },
@@ -1965,7 +2005,7 @@
         key.name: "hash(into:)",
         key.usr: "s:SYsSHRzSH8RawValueSYRpzrlE4hash4intoys6HasherVz_tF::SYNTHESIZED::s:4cake2C1C0B5CasesO",
         key.original_usr: "s:SYsSHRzSH8RawValueSYRpzrlE4hash4intoys6HasherVz_tF",
-        key.offset: 537,
+        key.offset: 552,
         key.length: 47,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@inlinable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>hash</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>into</decl.var.parameter.argument_label> <decl.var.parameter.name>hasher</decl.var.parameter.name>: <syntaxtype.keyword>inout</syntaxtype.keyword> <decl.var.parameter.type><ref.struct usr=\"s:s6HasherV\">Hasher</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.method.instance>",
         key.entities: [
@@ -1973,7 +2013,7 @@
             key.kind: source.lang.swift.decl.var.local,
             key.keyword: "into",
             key.name: "hasher",
-            key.offset: 577,
+            key.offset: 592,
             key.length: 6
           }
         ]
@@ -1983,7 +2023,7 @@
         key.name: "!=(_:_:)",
         key.usr: "s:SQsE2neoiySbx_xtFZ::SYNTHESIZED::s:4cake2C1C0B5CasesO",
         key.original_usr: "s:SQsE2neoiySbx_xtFZ",
-        key.offset: 590,
+        key.offset: 605,
         key.length: 61,
         key.fully_annotated_decl: "<decl.function.operator.infix><syntaxtype.keyword>static</syntaxtype.keyword> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>!= </decl.name>(<decl.var.parameter><decl.var.parameter.name>lhs</decl.var.parameter.name>: <decl.var.parameter.type><ref.class usr=\"s:4cake2C1C\">C1</ref.class>.<ref.enum usr=\"s:4cake2C1C0B5CasesO\">C1Cases</ref.enum></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.name>rhs</decl.var.parameter.name>: <decl.var.parameter.type><ref.class usr=\"s:4cake2C1C\">C1</ref.class>.<ref.enum usr=\"s:4cake2C1C0B5CasesO\">C1Cases</ref.enum></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Sb\">Bool</ref.struct></decl.function.returntype></decl.function.operator.infix>",
         key.entities: [
@@ -1991,14 +2031,14 @@
             key.kind: source.lang.swift.decl.var.local,
             key.keyword: "_",
             key.name: "lhs",
-            key.offset: 613,
+            key.offset: 628,
             key.length: 10
           },
           {
             key.kind: source.lang.swift.decl.var.local,
             key.keyword: "_",
             key.name: "rhs",
-            key.offset: 632,
+            key.offset: 647,
             key.length: 10
           }
         ]
@@ -2009,7 +2049,7 @@
     key.kind: source.lang.swift.decl.class,
     key.name: "C2",
     key.usr: "s:4cake2C2C",
-    key.offset: 655,
+    key.offset: 670,
     key.length: 172,
     key.fully_annotated_decl: "<decl.class><syntaxtype.keyword>class</syntaxtype.keyword> <decl.name>C2</decl.name> : <ref.class usr=\"s:4cake2C1C\">C1</ref.class></decl.class>",
     key.inherits: [
@@ -2024,7 +2064,7 @@
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "C2foo()",
         key.usr: "s:4cake2C2C5C2fooyyF",
-        key.offset: 681,
+        key.offset: 696,
         key.length: 12,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>C2foo</decl.name>()</decl.function.method.instance>"
       },
@@ -2033,7 +2073,7 @@
         key.name: "C1Cases",
         key.usr: "s:4cake2C1C0B5CasesO::SYNTHESIZED::s:4cake2C2C",
         key.original_usr: "s:4cake2C1C0B5CasesO",
-        key.offset: 699,
+        key.offset: 714,
         key.length: 46,
         key.fully_annotated_decl: "<decl.enum><syntaxtype.keyword>enum</syntaxtype.keyword> <decl.name>C1Cases</decl.name> : <ref.struct usr=\"s:Si\">Int</ref.struct></decl.enum>",
         key.inherits: [
@@ -2048,7 +2088,7 @@
             key.kind: source.lang.swift.decl.enumelement,
             key.name: "case1",
             key.usr: "s:4cake2C1C0B5CasesO5case1yA2EmF",
-            key.offset: 729,
+            key.offset: 744,
             key.length: 10,
             key.fully_annotated_decl: "<decl.enumelement><syntaxtype.keyword>case</syntaxtype.keyword> <decl.name>case1</decl.name></decl.enumelement>"
           }
@@ -2059,7 +2099,7 @@
         key.name: "extfoo()",
         key.usr: "s:4cake4ProtPAASi7ElementRtzrlE6extfooyyF::SYNTHESIZED::s:4cake2C2C",
         key.original_usr: "s:4cake4ProtPAASi7ElementRtzrlE6extfooyyF",
-        key.offset: 751,
+        key.offset: 766,
         key.length: 13,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>extfoo</decl.name>()</decl.function.method.instance>"
       },
@@ -2068,7 +2108,7 @@
         key.name: "foo1()",
         key.usr: "s:4cake4ProtPAAE4foo1yyF::SYNTHESIZED::s:4cake2C2C",
         key.original_usr: "s:4cake4ProtPAAE4foo1yyF",
-        key.offset: 770,
+        key.offset: 785,
         key.length: 11,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>foo1</decl.name>()</decl.function.method.instance>"
       },
@@ -2077,7 +2117,7 @@
         key.name: "subscript(_:)",
         key.usr: "s:4cake4ProtPAAEyS2icip::SYNTHESIZED::s:4cake2C2C",
         key.original_usr: "s:4cake4ProtPAAEyS2icip",
-        key.offset: 787,
+        key.offset: 802,
         key.length: 38,
         key.fully_annotated_decl: "<decl.function.subscript><syntaxtype.keyword>subscript</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.name>index</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Si\">Int</ref.struct></decl.function.returntype> { <syntaxtype.keyword>get</syntaxtype.keyword> }</decl.function.subscript>",
         key.entities: [
@@ -2085,7 +2125,7 @@
             key.kind: source.lang.swift.decl.var.local,
             key.keyword: "_",
             key.name: "index",
-            key.offset: 806,
+            key.offset: 821,
             key.length: 3
           }
         ]
@@ -2094,7 +2134,7 @@
   },
   {
     key.kind: source.lang.swift.decl.extension.class,
-    key.offset: 829,
+    key.offset: 844,
     key.length: 95,
     key.conforms: [
       {
@@ -2114,7 +2154,7 @@
         key.name: "C1foo()",
         key.usr: "s:4cake2C1C5C1fooyyF::SYNTHESIZED::s:4cake2C2C",
         key.original_usr: "s:4cake2C1C5C1fooyyF",
-        key.offset: 854,
+        key.offset: 869,
         key.length: 12,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>C1foo</decl.name>()</decl.function.method.instance>"
       },
@@ -2123,7 +2163,7 @@
         key.name: "C1S1",
         key.usr: "s:4cake2C1C0B2S1V::SYNTHESIZED::s:4cake2C2C",
         key.original_usr: "s:4cake2C1C0B2S1V",
-        key.offset: 872,
+        key.offset: 887,
         key.length: 50,
         key.fully_annotated_decl: "<decl.struct><syntaxtype.keyword>struct</syntaxtype.keyword> <decl.name>C1S1</decl.name></decl.struct>",
         key.entities: [
@@ -2131,7 +2171,7 @@
             key.kind: source.lang.swift.decl.function.method.instance,
             key.name: "C1S1foo(a:)",
             key.usr: "s:4cake2C1C0B2S1V0B5S1foo1ayAA2P4_p_tF",
-            key.offset: 895,
+            key.offset: 910,
             key.length: 21,
             key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>C1S1foo</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>a</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.protocol usr=\"s:4cake2P4P\">P4</ref.protocol></decl.var.parameter.type></decl.var.parameter>)</decl.function.method.instance>",
             key.entities: [
@@ -2139,7 +2179,7 @@
                 key.kind: source.lang.swift.decl.var.local,
                 key.keyword: "a",
                 key.name: "a",
-                key.offset: 913,
+                key.offset: 928,
                 key.length: 2
               }
             ]
@@ -2152,7 +2192,7 @@
     key.kind: source.lang.swift.decl.enum,
     key.name: "MyEnum",
     key.usr: "s:4cake6MyEnumO",
-    key.offset: 926,
+    key.offset: 941,
     key.length: 191,
     key.fully_annotated_decl: "<decl.enum><syntaxtype.keyword>enum</syntaxtype.keyword> <decl.name>MyEnum</decl.name> : <ref.struct usr=\"s:Si\">Int</ref.struct></decl.enum>",
     key.inherits: [
@@ -2167,7 +2207,7 @@
         key.kind: source.lang.swift.decl.enumelement,
         key.name: "Blah",
         key.usr: "s:4cake6MyEnumO4BlahyA2CmF",
-        key.offset: 951,
+        key.offset: 966,
         key.length: 9,
         key.fully_annotated_decl: "<decl.enumelement><syntaxtype.keyword>case</syntaxtype.keyword> <decl.name>Blah</decl.name></decl.enumelement>"
       },
@@ -2176,7 +2216,7 @@
         key.name: "hashValue",
         key.usr: "s:SYsSHRzSH8RawValueSYRpzrlE04hashB0Sivp::SYNTHESIZED::s:4cake6MyEnumO",
         key.original_usr: "s:SYsSHRzSH8RawValueSYRpzrlE04hashB0Sivp",
-        key.offset: 966,
+        key.offset: 981,
         key.length: 37,
         key.fully_annotated_decl: "<decl.var.instance><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@inlinable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>var</syntaxtype.keyword> <decl.name>hashValue</decl.name>: <decl.var.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.type> { <syntaxtype.keyword>get</syntaxtype.keyword> }</decl.var.instance>"
       },
@@ -2185,7 +2225,7 @@
         key.name: "hash(into:)",
         key.usr: "s:SYsSHRzSH8RawValueSYRpzrlE4hash4intoys6HasherVz_tF::SYNTHESIZED::s:4cake6MyEnumO",
         key.original_usr: "s:SYsSHRzSH8RawValueSYRpzrlE4hash4intoys6HasherVz_tF",
-        key.offset: 1009,
+        key.offset: 1024,
         key.length: 47,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@inlinable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>hash</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>into</decl.var.parameter.argument_label> <decl.var.parameter.name>hasher</decl.var.parameter.name>: <syntaxtype.keyword>inout</syntaxtype.keyword> <decl.var.parameter.type><ref.struct usr=\"s:s6HasherV\">Hasher</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.method.instance>",
         key.entities: [
@@ -2193,7 +2233,7 @@
             key.kind: source.lang.swift.decl.var.local,
             key.keyword: "into",
             key.name: "hasher",
-            key.offset: 1049,
+            key.offset: 1064,
             key.length: 6
           }
         ]
@@ -2203,7 +2243,7 @@
         key.name: "!=(_:_:)",
         key.usr: "s:SQsE2neoiySbx_xtFZ::SYNTHESIZED::s:4cake6MyEnumO",
         key.original_usr: "s:SQsE2neoiySbx_xtFZ",
-        key.offset: 1062,
+        key.offset: 1077,
         key.length: 53,
         key.fully_annotated_decl: "<decl.function.operator.infix><syntaxtype.keyword>static</syntaxtype.keyword> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>!= </decl.name>(<decl.var.parameter><decl.var.parameter.name>lhs</decl.var.parameter.name>: <decl.var.parameter.type><ref.enum usr=\"s:4cake6MyEnumO\">MyEnum</ref.enum></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.name>rhs</decl.var.parameter.name>: <decl.var.parameter.type><ref.enum usr=\"s:4cake6MyEnumO\">MyEnum</ref.enum></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Sb\">Bool</ref.struct></decl.function.returntype></decl.function.operator.infix>",
         key.entities: [
@@ -2211,14 +2251,14 @@
             key.kind: source.lang.swift.decl.var.local,
             key.keyword: "_",
             key.name: "lhs",
-            key.offset: 1085,
+            key.offset: 1100,
             key.length: 6
           },
           {
             key.kind: source.lang.swift.decl.var.local,
             key.keyword: "_",
             key.name: "rhs",
-            key.offset: 1100,
+            key.offset: 1115,
             key.length: 6
           }
         ]
@@ -2229,7 +2269,7 @@
     key.kind: source.lang.swift.decl.protocol,
     key.name: "P2",
     key.usr: "c:@M@cake@objc(pl)P2",
-    key.offset: 1119,
+    key.offset: 1134,
     key.length: 53,
     key.fully_annotated_decl: "<decl.protocol><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@objc</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>protocol</syntaxtype.keyword> <decl.name>P2</decl.name></decl.protocol>",
     key.entities: [
@@ -2237,7 +2277,7 @@
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "foo1()",
         key.usr: "c:@M@cake@objc(pl)P2(im)foo1",
-        key.offset: 1144,
+        key.offset: 1159,
         key.length: 26,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@objc</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>optional</syntaxtype.keyword> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>foo1</decl.name>()</decl.function.method.instance>",
         key.is_optional: 1
@@ -2248,7 +2288,7 @@
     key.kind: source.lang.swift.decl.protocol,
     key.name: "P3",
     key.usr: "s:4cake2P3P",
-    key.offset: 1174,
+    key.offset: 1189,
     key.length: 37,
     key.fully_annotated_decl: "<decl.protocol><syntaxtype.keyword>protocol</syntaxtype.keyword> <decl.name>P3</decl.name></decl.protocol>",
     key.entities: [
@@ -2256,7 +2296,7 @@
         key.kind: source.lang.swift.decl.associatedtype,
         key.name: "T",
         key.usr: "s:4cake2P3P1TQa",
-        key.offset: 1193,
+        key.offset: 1208,
         key.length: 16,
         key.fully_annotated_decl: "<decl.associatedtype><syntaxtype.keyword>associatedtype</syntaxtype.keyword> <decl.name>T</decl.name></decl.associatedtype>"
       }
@@ -2266,7 +2306,7 @@
     key.kind: source.lang.swift.decl.protocol,
     key.name: "P4",
     key.usr: "s:4cake2P4P",
-    key.offset: 1213,
+    key.offset: 1228,
     key.length: 15,
     key.fully_annotated_decl: "<decl.protocol><syntaxtype.keyword>protocol</syntaxtype.keyword> <decl.name>P4</decl.name></decl.protocol>"
   },
@@ -2274,7 +2314,7 @@
     key.kind: source.lang.swift.decl.protocol,
     key.name: "P5",
     key.usr: "s:4cake2P5P",
-    key.offset: 1230,
+    key.offset: 1245,
     key.length: 43,
     key.fully_annotated_decl: "<decl.protocol><syntaxtype.keyword>protocol</syntaxtype.keyword> <decl.name>P5</decl.name></decl.protocol>",
     key.entities: [
@@ -2282,7 +2322,7 @@
         key.kind: source.lang.swift.decl.associatedtype,
         key.name: "Element",
         key.usr: "s:4cake2P5P7ElementQa",
-        key.offset: 1249,
+        key.offset: 1264,
         key.length: 22,
         key.fully_annotated_decl: "<decl.associatedtype><syntaxtype.keyword>associatedtype</syntaxtype.keyword> <decl.name>Element</decl.name></decl.associatedtype>"
       }
@@ -2292,8 +2332,8 @@
     key.kind: source.lang.swift.decl.protocol,
     key.name: "P6",
     key.usr: "s:4cake2P6P",
-    key.offset: 1275,
-    key.length: 20,
+    key.offset: 1290,
+    key.length: 25,
     key.fully_annotated_decl: "<decl.protocol><syntaxtype.keyword>protocol</syntaxtype.keyword> <decl.name>P6</decl.name> : <ref.protocol usr=\"s:4cake2P5P\">P5</ref.protocol></decl.protocol>",
     key.conforms: [
       {
@@ -2305,7 +2345,7 @@
   },
   {
     key.kind: source.lang.swift.decl.extension.protocol,
-    key.offset: 1297,
+    key.offset: 1317,
     key.length: 53,
     key.fully_annotated_generic_signature: "&lt;<decl.generic_type_param usr=\"s:4cake2P6P4Selfxmfp\"><decl.generic_type_param.name>Self</decl.generic_type_param.name></decl.generic_type_param> <syntaxtype.keyword>where</syntaxtype.keyword> <decl.generic_type_requirement><ref.generic_type_param usr=\"s:4cake2P6P4Selfxmfp\">Self</ref.generic_type_param> : <ref.protocol usr=\"s:4cake2P6P\">P6</ref.protocol></decl.generic_type_requirement>&gt;",
     key.extends: {
@@ -2318,7 +2358,7 @@
         key.kind: source.lang.swift.decl.var.instance,
         key.name: "null",
         key.usr: "s:4cake2P6PAAE4null7ElementQzSgvp",
-        key.offset: 1317,
+        key.offset: 1337,
         key.length: 31,
         key.fully_annotated_decl: "<decl.var.instance><syntaxtype.keyword>var</syntaxtype.keyword> <decl.name>null</decl.name>: <decl.var.type><ref.generic_type_param usr=\"s:4cake2P6P4Selfxmfp\">Self</ref.generic_type_param>.Element?</decl.var.type> { <syntaxtype.keyword>get</syntaxtype.keyword> }</decl.var.instance>"
       }
@@ -2328,7 +2368,7 @@
     key.kind: source.lang.swift.decl.protocol,
     key.name: "Prot",
     key.usr: "s:4cake4ProtP",
-    key.offset: 1352,
+    key.offset: 1372,
     key.length: 102,
     key.fully_annotated_decl: "<decl.protocol><syntaxtype.keyword>protocol</syntaxtype.keyword> <decl.name>Prot</decl.name></decl.protocol>",
     key.entities: [
@@ -2336,7 +2376,7 @@
         key.kind: source.lang.swift.decl.associatedtype,
         key.name: "Element",
         key.usr: "s:4cake4ProtP7ElementQa",
-        key.offset: 1373,
+        key.offset: 1393,
         key.length: 22,
         key.fully_annotated_decl: "<decl.associatedtype><syntaxtype.keyword>associatedtype</syntaxtype.keyword> <decl.name>Element</decl.name></decl.associatedtype>"
       },
@@ -2344,7 +2384,7 @@
         key.kind: source.lang.swift.decl.var.instance,
         key.name: "p",
         key.usr: "s:4cake4ProtP1pSivp",
-        key.offset: 1401,
+        key.offset: 1421,
         key.length: 18,
         key.fully_annotated_decl: "<decl.var.instance><syntaxtype.keyword>var</syntaxtype.keyword> <decl.name>p</decl.name>: <decl.var.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.type> { <syntaxtype.keyword>get</syntaxtype.keyword> }</decl.var.instance>"
       },
@@ -2352,7 +2392,7 @@
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "foo()",
         key.usr: "s:4cake4ProtP3fooyyF",
-        key.offset: 1425,
+        key.offset: 1445,
         key.length: 10,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>foo</decl.name>()</decl.function.method.instance>"
       },
@@ -2360,7 +2400,7 @@
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "foo1()",
         key.usr: "s:4cake4ProtP4foo1yyF",
-        key.offset: 1441,
+        key.offset: 1461,
         key.length: 11,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>foo1</decl.name>()</decl.function.method.instance>"
       }
@@ -2368,7 +2408,7 @@
   },
   {
     key.kind: source.lang.swift.decl.extension.protocol,
-    key.offset: 1456,
+    key.offset: 1476,
     key.length: 79,
     key.fully_annotated_generic_signature: "&lt;<decl.generic_type_param usr=\"s:4cake4ProtP4Selfxmfp\"><decl.generic_type_param.name>Self</decl.generic_type_param.name></decl.generic_type_param> <syntaxtype.keyword>where</syntaxtype.keyword> <decl.generic_type_requirement><ref.generic_type_param usr=\"s:4cake4ProtP4Selfxmfp\">Self</ref.generic_type_param> : <ref.protocol usr=\"s:4cake4ProtP\">Prot</ref.protocol></decl.generic_type_requirement>&gt;",
     key.extends: {
@@ -2382,7 +2422,7 @@
         key.name: "foo1()",
         key.usr: "s:4cake4ProtPAAE4foo1yyF",
         key.default_implementation_of: "s:4cake4ProtP4foo1yyF",
-        key.offset: 1478,
+        key.offset: 1498,
         key.length: 11,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>foo1</decl.name>()</decl.function.method.instance>"
       },
@@ -2390,7 +2430,7 @@
         key.kind: source.lang.swift.decl.function.subscript,
         key.name: "subscript(_:)",
         key.usr: "s:4cake4ProtPAAEyS2icip",
-        key.offset: 1495,
+        key.offset: 1515,
         key.length: 38,
         key.fully_annotated_decl: "<decl.function.subscript><syntaxtype.keyword>subscript</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.name>index</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Si\">Int</ref.struct></decl.function.returntype> { <syntaxtype.keyword>get</syntaxtype.keyword> }</decl.function.subscript>",
         key.entities: [
@@ -2398,7 +2438,7 @@
             key.kind: source.lang.swift.decl.var.local,
             key.keyword: "_",
             key.name: "index",
-            key.offset: 1514,
+            key.offset: 1534,
             key.length: 3
           }
         ]
@@ -2412,7 +2452,7 @@
         key.description: "Self.Element == Int"
       }
     ],
-    key.offset: 1537,
+    key.offset: 1557,
     key.length: 63,
     key.fully_annotated_generic_signature: "&lt;<decl.generic_type_param usr=\"s:4cake4ProtPAASi7ElementRtzrlE4Selfxmfp\"><decl.generic_type_param.name>Self</decl.generic_type_param.name></decl.generic_type_param> <syntaxtype.keyword>where</syntaxtype.keyword> <decl.generic_type_requirement><ref.generic_type_param usr=\"s:4cake4ProtPAASi7ElementRtzrlE4Selfxmfp\">Self</ref.generic_type_param> : <ref.protocol usr=\"s:4cake4ProtP\">Prot</ref.protocol></decl.generic_type_requirement>, <decl.generic_type_requirement><ref.generic_type_param usr=\"s:4cake4ProtPAASi7ElementRtzrlE4Selfxmfp\">Self</ref.generic_type_param>.Element == <ref.struct usr=\"s:Si\">Int</ref.struct></decl.generic_type_requirement>&gt;",
     key.extends: {
@@ -2425,7 +2465,7 @@
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "extfoo()",
         key.usr: "s:4cake4ProtPAASi7ElementRtzrlE6extfooyyF",
-        key.offset: 1585,
+        key.offset: 1605,
         key.length: 13,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>extfoo</decl.name>()</decl.function.method.instance>"
       }
@@ -2435,7 +2475,7 @@
     key.kind: source.lang.swift.decl.struct,
     key.name: "S1",
     key.usr: "s:4cake2S1V",
-    key.offset: 1602,
+    key.offset: 1622,
     key.length: 142,
     key.fully_annotated_decl: "<decl.struct><syntaxtype.keyword>struct</syntaxtype.keyword> <decl.name>S1</decl.name></decl.struct>",
     key.entities: [
@@ -2443,7 +2483,7 @@
         key.kind: source.lang.swift.decl.enum,
         key.name: "SE",
         key.usr: "s:4cake2S1V2SEO",
-        key.offset: 1619,
+        key.offset: 1639,
         key.length: 63,
         key.fully_annotated_decl: "<decl.enum><syntaxtype.keyword>enum</syntaxtype.keyword> <ref.struct usr=\"s:4cake2S1V\">S1</ref.struct>.<decl.name>SE</decl.name></decl.enum>",
         key.entities: [
@@ -2451,7 +2491,7 @@
             key.kind: source.lang.swift.decl.enumelement,
             key.name: "a",
             key.usr: "s:4cake2S1V2SEO1ayA2EmF",
-            key.offset: 1638,
+            key.offset: 1658,
             key.length: 6,
             key.fully_annotated_decl: "<decl.enumelement><syntaxtype.keyword>case</syntaxtype.keyword> <decl.name>a</decl.name></decl.enumelement>"
           },
@@ -2459,7 +2499,7 @@
             key.kind: source.lang.swift.decl.enumelement,
             key.name: "b",
             key.usr: "s:4cake2S1V2SEO1byA2EmF",
-            key.offset: 1654,
+            key.offset: 1674,
             key.length: 6,
             key.fully_annotated_decl: "<decl.enumelement><syntaxtype.keyword>case</syntaxtype.keyword> <decl.name>b</decl.name></decl.enumelement>"
           },
@@ -2467,7 +2507,7 @@
             key.kind: source.lang.swift.decl.enumelement,
             key.name: "c",
             key.usr: "s:4cake2S1V2SEO1cyA2EmF",
-            key.offset: 1670,
+            key.offset: 1690,
             key.length: 6,
             key.fully_annotated_decl: "<decl.enumelement><syntaxtype.keyword>case</syntaxtype.keyword> <decl.name>c</decl.name></decl.enumelement>"
           }
@@ -2477,7 +2517,7 @@
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "foo1()",
         key.usr: "s:4cake2S1V4foo1yyF",
-        key.offset: 1688,
+        key.offset: 1708,
         key.length: 11,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>foo1</decl.name>()</decl.function.method.instance>"
       },
@@ -2485,7 +2525,7 @@
         key.kind: source.lang.swift.decl.struct,
         key.name: "S2",
         key.usr: "s:4cake2S1V2S2V",
-        key.offset: 1705,
+        key.offset: 1725,
         key.length: 37,
         key.fully_annotated_decl: "<decl.struct><syntaxtype.keyword>struct</syntaxtype.keyword> <decl.name>S2</decl.name></decl.struct>",
         key.entities: [
@@ -2493,7 +2533,7 @@
             key.kind: source.lang.swift.decl.var.instance,
             key.name: "b",
             key.usr: "s:4cake2S1V2S2V1bSivp",
-            key.offset: 1726,
+            key.offset: 1746,
             key.length: 10,
             key.fully_annotated_decl: "<decl.var.instance><syntaxtype.keyword>let</syntaxtype.keyword> <decl.name>b</decl.name>: <decl.var.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.type></decl.var.instance>"
           }
@@ -2503,7 +2543,7 @@
   },
   {
     key.kind: source.lang.swift.decl.extension.enum,
-    key.offset: 1746,
+    key.offset: 1766,
     key.length: 76,
     key.fully_annotated_generic_signature: "&lt;<decl.generic_type_param usr=\"s:SQ4Selfxmfp\"><decl.generic_type_param.name>Self</decl.generic_type_param.name></decl.generic_type_param> <syntaxtype.keyword>where</syntaxtype.keyword> <decl.generic_type_requirement><ref.generic_type_param usr=\"s:SQ4Selfxmfp\">Self</ref.generic_type_param> : <ref.protocol usr=\"s:SQ\">Equatable</ref.protocol></decl.generic_type_requirement>&gt;",
     key.extends: {
@@ -2517,7 +2557,7 @@
         key.name: "!=(_:_:)",
         key.usr: "s:SQsE2neoiySbx_xtFZ::SYNTHESIZED::s:4cake2S1V2SEO",
         key.original_usr: "s:SQsE2neoiySbx_xtFZ",
-        key.offset: 1769,
+        key.offset: 1789,
         key.length: 51,
         key.fully_annotated_decl: "<decl.function.operator.infix><syntaxtype.keyword>static</syntaxtype.keyword> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>!= </decl.name>(<decl.var.parameter><decl.var.parameter.name>lhs</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"s:4cake2S1V\">S1</ref.struct>.<ref.enum usr=\"s:4cake2S1V2SEO\">SE</ref.enum></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.name>rhs</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"s:4cake2S1V\">S1</ref.struct>.<ref.enum usr=\"s:4cake2S1V2SEO\">SE</ref.enum></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Sb\">Bool</ref.struct></decl.function.returntype></decl.function.operator.infix>",
         key.entities: [
@@ -2525,14 +2565,14 @@
             key.kind: source.lang.swift.decl.var.local,
             key.keyword: "_",
             key.name: "lhs",
-            key.offset: 1792,
+            key.offset: 1812,
             key.length: 5
           },
           {
             key.kind: source.lang.swift.decl.var.local,
             key.keyword: "_",
             key.name: "rhs",
-            key.offset: 1806,
+            key.offset: 1826,
             key.length: 5
           }
         ]
@@ -2543,8 +2583,8 @@
     key.kind: source.lang.swift.decl.struct,
     key.name: "S2",
     key.usr: "s:4cake2S2V",
-    key.offset: 1824,
-    key.length: 45,
+    key.offset: 1844,
+    key.length: 50,
     key.fully_annotated_decl: "<decl.struct><syntaxtype.keyword>struct</syntaxtype.keyword> <decl.name>S2</decl.name> : <ref.protocol usr=\"s:4cake2P3P\">P3</ref.protocol></decl.struct>",
     key.conforms: [
       {
@@ -2558,7 +2598,7 @@
         key.kind: source.lang.swift.decl.typealias,
         key.name: "T",
         key.usr: "s:4cake2S2V1Ta",
-        key.offset: 1846,
+        key.offset: 1871,
         key.length: 21,
         key.fully_annotated_decl: "<decl.typealias><syntaxtype.keyword>typealias</syntaxtype.keyword> <ref.struct usr=\"s:4cake2S2V\">S2</ref.struct>.<decl.name>T</decl.name> = <ref.struct usr=\"s:4cake2S2V\">S2</ref.struct></decl.typealias>",
         key.conforms: [
@@ -2585,8 +2625,8 @@
         key.description: "Wrapped : P5"
       }
     ],
-    key.offset: 1871,
-    key.length: 87,
+    key.offset: 1896,
+    key.length: 97,
     key.fully_annotated_decl: "<decl.struct><syntaxtype.keyword>struct</syntaxtype.keyword> <decl.name>S3</decl.name>&lt;<decl.generic_type_param usr=\"s:4cake2S3V7Wrappedxmfp\"><decl.generic_type_param.name>Wrapped</decl.generic_type_param.name></decl.generic_type_param>&gt; : <ref.protocol usr=\"s:4cake2P5P\">P5</ref.protocol> <syntaxtype.keyword>where</syntaxtype.keyword> <decl.generic_type_requirement>Wrapped : <ref.protocol usr=\"s:4cake2P5P\">P5</ref.protocol></decl.generic_type_requirement></decl.struct>",
     key.conforms: [
       {
@@ -2600,7 +2640,7 @@
         key.kind: source.lang.swift.decl.typealias,
         key.name: "Element",
         key.usr: "s:4cake2S3V7Elementa",
-        key.offset: 1921,
+        key.offset: 1956,
         key.length: 35,
         key.fully_annotated_decl: "<decl.typealias><syntaxtype.keyword>typealias</syntaxtype.keyword> <ref.struct usr=\"s:4cake2S3V\">S3</ref.struct>&lt;Wrapped&gt;.<decl.name>Element</decl.name> = Wrapped.Element</decl.typealias>",
         key.conforms: [
@@ -2615,7 +2655,7 @@
   },
   {
     key.kind: source.lang.swift.decl.extension.struct,
-    key.offset: 1960,
+    key.offset: 1995,
     key.length: 56,
     key.fully_annotated_generic_signature: "&lt;<decl.generic_type_param usr=\"s:4cake2P6P4Selfxmfp\"><decl.generic_type_param.name>Self</decl.generic_type_param.name></decl.generic_type_param> <syntaxtype.keyword>where</syntaxtype.keyword> <decl.generic_type_requirement><ref.generic_type_param usr=\"s:4cake2P6P4Selfxmfp\">Self</ref.generic_type_param> : <ref.protocol usr=\"s:4cake2P6P\">P6</ref.protocol></decl.generic_type_requirement>&gt;",
     key.extends: {
@@ -2629,7 +2669,7 @@
         key.name: "null",
         key.usr: "s:4cake2P6PAAE4null7ElementQzSgvp::SYNTHESIZED::s:4cake2S3V",
         key.original_usr: "s:4cake2P6PAAE4null7ElementQzSgvp",
-        key.offset: 1980,
+        key.offset: 2015,
         key.length: 34,
         key.fully_annotated_decl: "<decl.var.instance><syntaxtype.keyword>var</syntaxtype.keyword> <decl.name>null</decl.name>: <decl.var.type>Wrapped.Element?</decl.var.type> { <syntaxtype.keyword>get</syntaxtype.keyword> }</decl.var.instance>"
       }
@@ -2658,22 +2698,22 @@
         key.description: "T1.Element == Int"
       }
     ],
-    key.offset: 2018,
-    key.length: 88,
+    key.offset: 2053,
+    key.length: 93,
     key.fully_annotated_decl: "<decl.function.free><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>genfoo</decl.name>&lt;<decl.generic_type_param usr=\"s:4cake6genfoo1x1yyx_q_tAA4ProtRzAA2C1CRb_Si7ElementRtzr0_lF2T1L_xmfp\"><decl.generic_type_param.name>T1</decl.generic_type_param.name></decl.generic_type_param>, <decl.generic_type_param usr=\"s:4cake6genfoo1x1yyx_q_tAA4ProtRzAA2C1CRb_Si7ElementRtzr0_lF2T2L_q_mfp\"><decl.generic_type_param.name>T2</decl.generic_type_param.name></decl.generic_type_param>&gt;(<decl.var.parameter><decl.var.parameter.argument_label>x</decl.var.parameter.argument_label> <decl.var.parameter.name>ix</decl.var.parameter.name>: <decl.var.parameter.type>T1</decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.argument_label>y</decl.var.parameter.argument_label> <decl.var.parameter.name>iy</decl.var.parameter.name>: <decl.var.parameter.type>T2</decl.var.parameter.type></decl.var.parameter>) <syntaxtype.keyword>where</syntaxtype.keyword> <decl.generic_type_requirement>T1 : <ref.protocol usr=\"s:4cake4ProtP\">Prot</ref.protocol></decl.generic_type_requirement>, <decl.generic_type_requirement>T2 : <ref.class usr=\"s:4cake2C1C\">C1</ref.class></decl.generic_type_requirement>, <decl.generic_type_requirement>T1.Element == <ref.struct usr=\"s:Si\">Int</ref.struct></decl.generic_type_requirement></decl.function.free>",
     key.entities: [
       {
         key.kind: source.lang.swift.decl.var.local,
         key.keyword: "x",
         key.name: "ix",
-        key.offset: 2044,
+        key.offset: 2079,
         key.length: 2
       },
       {
         key.kind: source.lang.swift.decl.var.local,
         key.keyword: "y",
         key.name: "iy",
-        key.offset: 2054,
+        key.offset: 2089,
         key.length: 2
       }
     ]
diff --git a/test/SourceKit/DocSupport/doc_swift_module1.swift.response b/test/SourceKit/DocSupport/doc_swift_module1.swift.response
index a4f9d04..1c310d0 100644
--- a/test/SourceKit/DocSupport/doc_swift_module1.swift.response
+++ b/test/SourceKit/DocSupport/doc_swift_module1.swift.response
@@ -1,6 +1,6 @@
 import SwiftOnoneSupport
 
-class InitClassImpl : InitProto {
+class InitClassImpl : cake1.InitProto {
 
     required init(x x: Int)
 
@@ -17,7 +17,7 @@
     init()
 }
 
-struct InitStructImpl : InitProto {
+struct InitStructImpl : cake1.InitProto {
 
     init(x x: Int)
 
@@ -37,7 +37,7 @@
     func fooConstraint()
 }
 
-protocol P2 : P1 {
+protocol P2 : cake1.P1 {
 
     func bar1()
 
@@ -55,7 +55,7 @@
     subscript(_ a: Int) -> Int
 }
 
-extension P2 where Self : P3 {
+extension P2 where Self : cake1.P3 {
 
     func fooConstraint()
 }
@@ -70,7 +70,7 @@
     func foo()
 }
 
-extension Dictionary.Keys where Key : P1 {
+extension Dictionary.Keys where Key : cake1.P1 {
 
     func bar()
 }
@@ -98,565 +98,590 @@
     key.length: 13
   },
   {
+    key.kind: source.lang.swift.syntaxtype.typeidentifier,
+    key.offset: 48,
+    key.length: 5
+  },
+  {
     key.kind: source.lang.swift.ref.protocol,
     key.name: "InitProto",
     key.usr: "s:5cake19InitProtoP",
-    key.offset: 48,
+    key.offset: 54,
     key.length: 9
   },
   {
     key.kind: source.lang.swift.syntaxtype.attribute.builtin,
-    key.offset: 65,
+    key.offset: 71,
     key.length: 8
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 74,
+    key.offset: 80,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.argument,
-    key.offset: 79,
+    key.offset: 85,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.syntaxtype.parameter,
-    key.offset: 81,
+    key.offset: 87,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 84,
+    key.offset: 90,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.attribute.builtin,
-    key.offset: 94,
+    key.offset: 100,
     key.length: 11
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 106,
+    key.offset: 112,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 116,
+    key.offset: 122,
     key.length: 8
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 125,
+    key.offset: 131,
     key.length: 9
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 142,
+    key.offset: 148,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.argument,
-    key.offset: 147,
+    key.offset: 153,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.syntaxtype.parameter,
-    key.offset: 149,
+    key.offset: 155,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 152,
+    key.offset: 158,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 160,
+    key.offset: 166,
     key.length: 9
   },
   {
     key.kind: source.lang.swift.ref.protocol,
     key.name: "InitProto",
     key.usr: "s:5cake19InitProtoP",
-    key.offset: 170,
+    key.offset: 176,
     key.length: 9
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 187,
+    key.offset: 193,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 197,
+    key.offset: 203,
     key.length: 6
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 204,
+    key.offset: 210,
     key.length: 14
   },
   {
+    key.kind: source.lang.swift.syntaxtype.typeidentifier,
+    key.offset: 227,
+    key.length: 5
+  },
+  {
     key.kind: source.lang.swift.ref.protocol,
     key.name: "InitProto",
     key.usr: "s:5cake19InitProtoP",
-    key.offset: 221,
+    key.offset: 233,
     key.length: 9
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 238,
+    key.offset: 250,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.argument,
-    key.offset: 243,
+    key.offset: 255,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.syntaxtype.parameter,
-    key.offset: 245,
+    key.offset: 257,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 248,
+    key.offset: 260,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 258,
+    key.offset: 270,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 268,
+    key.offset: 280,
     key.length: 8
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 277,
+    key.offset: 289,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 287,
+    key.offset: 299,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 292,
-    key.length: 4
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.keyword,
     key.offset: 304,
+    key.length: 4
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.keyword,
+    key.offset: 316,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 308,
+    key.offset: 320,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 313,
+    key.offset: 325,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 319,
+    key.offset: 331,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 323,
+    key.offset: 335,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 334,
-    key.length: 4
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 339,
-    key.length: 4
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.argument,
-    key.offset: 344,
-    key.length: 1
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.parameter,
     key.offset: 346,
-    key.length: 1
+    key.length: 4
   },
   {
-    key.kind: source.lang.swift.ref.struct,
-    key.name: "Int",
-    key.usr: "s:Si",
-    key.offset: 349,
-    key.length: 3
+    key.kind: source.lang.swift.syntaxtype.identifier,
+    key.offset: 351,
+    key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.argument,
-    key.offset: 354,
-    key.length: 1
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.parameter,
     key.offset: 356,
     key.length: 1
   },
   {
+    key.kind: source.lang.swift.syntaxtype.parameter,
+    key.offset: 358,
+    key.length: 1
+  },
+  {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 359,
+    key.offset: 361,
     key.length: 3
   },
   {
-    key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 369,
-    key.length: 9
-  },
-  {
     key.kind: source.lang.swift.syntaxtype.argument,
-    key.offset: 379,
+    key.offset: 366,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.syntaxtype.parameter,
-    key.offset: 381,
+    key.offset: 368,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 384,
+    key.offset: 371,
+    key.length: 3
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.keyword,
+    key.offset: 381,
+    key.length: 9
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.argument,
+    key.offset: 391,
+    key.length: 1
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.parameter,
+    key.offset: 393,
+    key.length: 1
+  },
+  {
+    key.kind: source.lang.swift.ref.struct,
+    key.name: "Int",
+    key.usr: "s:Si",
+    key.offset: 396,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 392,
+    key.offset: 404,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 398,
+    key.offset: 410,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 402,
+    key.offset: 414,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 413,
+    key.offset: 425,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 418,
+    key.offset: 430,
     key.length: 13
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 437,
+    key.offset: 449,
     key.length: 8
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 446,
+    key.offset: 458,
     key.length: 2
   },
   {
+    key.kind: source.lang.swift.syntaxtype.typeidentifier,
+    key.offset: 463,
+    key.length: 5
+  },
+  {
     key.kind: source.lang.swift.ref.protocol,
     key.name: "P1",
     key.usr: "s:5cake12P1P",
-    key.offset: 451,
+    key.offset: 469,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 461,
+    key.offset: 479,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 466,
+    key.offset: 484,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 478,
+    key.offset: 496,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 483,
+    key.offset: 501,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 493,
+    key.offset: 511,
     key.length: 9
   },
   {
     key.kind: source.lang.swift.ref.protocol,
     key.name: "P2",
     key.usr: "s:5cake12P2P",
-    key.offset: 503,
+    key.offset: 521,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 513,
+    key.offset: 531,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 518,
+    key.offset: 536,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 530,
-    key.length: 3
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 534,
-    key.length: 3
-  },
-  {
-    key.kind: source.lang.swift.ref.struct,
-    key.name: "Int",
-    key.usr: "s:Si",
-    key.offset: 539,
-    key.length: 3
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.keyword,
     key.offset: 548,
+    key.length: 3
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.identifier,
+    key.offset: 552,
+    key.length: 3
+  },
+  {
+    key.kind: source.lang.swift.ref.struct,
+    key.name: "Int",
+    key.usr: "s:Si",
+    key.offset: 557,
+    key.length: 3
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.keyword,
+    key.offset: 566,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 553,
+    key.offset: 571,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.argument,
-    key.offset: 558,
+    key.offset: 576,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.syntaxtype.parameter,
-    key.offset: 560,
+    key.offset: 578,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 563,
+    key.offset: 581,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.argument,
-    key.offset: 568,
+    key.offset: 586,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.syntaxtype.parameter,
-    key.offset: 570,
+    key.offset: 588,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 573,
+    key.offset: 591,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 583,
+    key.offset: 601,
     key.length: 9
   },
   {
     key.kind: source.lang.swift.syntaxtype.argument,
-    key.offset: 593,
+    key.offset: 611,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.syntaxtype.parameter,
-    key.offset: 595,
+    key.offset: 613,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 598,
+    key.offset: 616,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Int",
     key.usr: "s:Si",
-    key.offset: 606,
+    key.offset: 624,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 613,
+    key.offset: 631,
     key.length: 9
   },
   {
     key.kind: source.lang.swift.ref.protocol,
     key.name: "P2",
     key.usr: "s:5cake12P2P",
-    key.offset: 623,
+    key.offset: 641,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 626,
+    key.offset: 644,
     key.length: 5
   },
   {
     key.kind: source.lang.swift.ref.generic_type_param,
     key.name: "Self",
     key.usr: "s:5cake12P2PA2A2P3RzrlE4Selfxmfp",
-    key.offset: 632,
+    key.offset: 650,
     key.length: 4
   },
   {
+    key.kind: source.lang.swift.syntaxtype.typeidentifier,
+    key.offset: 657,
+    key.length: 5
+  },
+  {
     key.kind: source.lang.swift.ref.protocol,
     key.name: "P3",
     key.usr: "s:5cake12P3P",
-    key.offset: 639,
+    key.offset: 663,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 649,
-    key.length: 4
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 654,
-    key.length: 13
-  },
-  {
-    key.kind: source.lang.swift.syntaxtype.keyword,
     key.offset: 673,
+    key.length: 4
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.identifier,
+    key.offset: 678,
+    key.length: 13
+  },
+  {
+    key.kind: source.lang.swift.syntaxtype.keyword,
+    key.offset: 697,
     key.length: 8
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 682,
+    key.offset: 706,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 692,
+    key.offset: 716,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 697,
+    key.offset: 721,
     key.length: 10
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 713,
+    key.offset: 737,
     key.length: 9
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Dictionary",
     key.usr: "s:SD",
-    key.offset: 723,
+    key.offset: 747,
     key.length: 10
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Keys",
     key.usr: "s:SD4KeysV",
-    key.offset: 734,
+    key.offset: 758,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 746,
+    key.offset: 770,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 751,
+    key.offset: 775,
     key.length: 3
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 760,
+    key.offset: 784,
     key.length: 9
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Dictionary",
     key.usr: "s:SD",
-    key.offset: 770,
+    key.offset: 794,
     key.length: 10
   },
   {
     key.kind: source.lang.swift.ref.struct,
     key.name: "Keys",
     key.usr: "s:SD4KeysV",
-    key.offset: 781,
+    key.offset: 805,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 786,
+    key.offset: 810,
     key.length: 5
   },
   {
     key.kind: source.lang.swift.syntaxtype.typeidentifier,
-    key.offset: 792,
+    key.offset: 816,
     key.length: 3
   },
   {
+    key.kind: source.lang.swift.syntaxtype.typeidentifier,
+    key.offset: 822,
+    key.length: 5
+  },
+  {
     key.kind: source.lang.swift.ref.protocol,
     key.name: "P1",
     key.usr: "s:5cake12P1P",
-    key.offset: 798,
+    key.offset: 828,
     key.length: 2
   },
   {
     key.kind: source.lang.swift.syntaxtype.keyword,
-    key.offset: 808,
+    key.offset: 838,
     key.length: 4
   },
   {
     key.kind: source.lang.swift.syntaxtype.identifier,
-    key.offset: 813,
+    key.offset: 843,
     key.length: 3
   }
 ]
@@ -666,7 +691,7 @@
     key.name: "InitClassImpl",
     key.usr: "s:5cake113InitClassImplC",
     key.offset: 26,
-    key.length: 88,
+    key.length: 94,
     key.fully_annotated_decl: "<decl.class><syntaxtype.keyword>class</syntaxtype.keyword> <decl.name>InitClassImpl</decl.name> : <ref.protocol usr=\"s:5cake19InitProtoP\">InitProto</ref.protocol></decl.class>",
     key.conforms: [
       {
@@ -680,7 +705,7 @@
         key.kind: source.lang.swift.decl.function.constructor,
         key.name: "init(x:)",
         key.usr: "s:5cake113InitClassImplC1xACSi_tcfc",
-        key.offset: 65,
+        key.offset: 71,
         key.length: 23,
         key.fully_annotated_decl: "<decl.function.constructor><syntaxtype.keyword>required</syntaxtype.keyword> <syntaxtype.keyword>init</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.argument_label>x</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.constructor>",
         key.conforms: [
@@ -695,7 +720,7 @@
             key.kind: source.lang.swift.decl.var.local,
             key.keyword: "x",
             key.name: "x",
-            key.offset: 84,
+            key.offset: 90,
             key.length: 3
           }
         ]
@@ -705,7 +730,7 @@
         key.name: "init()",
         key.usr: "s:5cake19InitProtoPAAExycfc::SYNTHESIZED::s:5cake113InitClassImplC",
         key.original_usr: "s:5cake19InitProtoPAAExycfc",
-        key.offset: 94,
+        key.offset: 100,
         key.length: 18,
         key.fully_annotated_decl: "<decl.function.constructor><syntaxtype.keyword>convenience</syntaxtype.keyword> <syntaxtype.keyword>init</syntaxtype.keyword>()</decl.function.constructor>"
       }
@@ -715,7 +740,7 @@
     key.kind: source.lang.swift.decl.protocol,
     key.name: "InitProto",
     key.usr: "s:5cake19InitProtoP",
-    key.offset: 116,
+    key.offset: 122,
     key.length: 42,
     key.fully_annotated_decl: "<decl.protocol><syntaxtype.keyword>protocol</syntaxtype.keyword> <decl.name>InitProto</decl.name></decl.protocol>",
     key.entities: [
@@ -723,7 +748,7 @@
         key.kind: source.lang.swift.decl.function.constructor,
         key.name: "init(x:)",
         key.usr: "s:5cake19InitProtoP1xxSi_tcfc",
-        key.offset: 142,
+        key.offset: 148,
         key.length: 14,
         key.fully_annotated_decl: "<decl.function.constructor><syntaxtype.keyword>init</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.argument_label>x</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.constructor>",
         key.entities: [
@@ -731,7 +756,7 @@
             key.kind: source.lang.swift.decl.var.local,
             key.keyword: "x",
             key.name: "x",
-            key.offset: 152,
+            key.offset: 158,
             key.length: 3
           }
         ]
@@ -740,7 +765,7 @@
   },
   {
     key.kind: source.lang.swift.decl.extension.protocol,
-    key.offset: 160,
+    key.offset: 166,
     key.length: 35,
     key.fully_annotated_generic_signature: "&lt;<decl.generic_type_param usr=\"s:5cake19InitProtoP4Selfxmfp\"><decl.generic_type_param.name>Self</decl.generic_type_param.name></decl.generic_type_param> <syntaxtype.keyword>where</syntaxtype.keyword> <decl.generic_type_requirement><ref.generic_type_param usr=\"s:5cake19InitProtoP4Selfxmfp\">Self</ref.generic_type_param> : <ref.protocol usr=\"s:5cake19InitProtoP\">InitProto</ref.protocol></decl.generic_type_requirement>&gt;",
     key.extends: {
@@ -753,7 +778,7 @@
         key.kind: source.lang.swift.decl.function.constructor,
         key.name: "init()",
         key.usr: "s:5cake19InitProtoPAAExycfc",
-        key.offset: 187,
+        key.offset: 193,
         key.length: 6,
         key.fully_annotated_decl: "<decl.function.constructor><syntaxtype.keyword>init</syntaxtype.keyword>()</decl.function.constructor>"
       }
@@ -763,8 +788,8 @@
     key.kind: source.lang.swift.decl.struct,
     key.name: "InitStructImpl",
     key.usr: "s:5cake114InitStructImplV",
-    key.offset: 197,
-    key.length: 69,
+    key.offset: 203,
+    key.length: 75,
     key.fully_annotated_decl: "<decl.struct><syntaxtype.keyword>struct</syntaxtype.keyword> <decl.name>InitStructImpl</decl.name> : <ref.protocol usr=\"s:5cake19InitProtoP\">InitProto</ref.protocol></decl.struct>",
     key.conforms: [
       {
@@ -778,7 +803,7 @@
         key.kind: source.lang.swift.decl.function.constructor,
         key.name: "init(x:)",
         key.usr: "s:5cake114InitStructImplV1xACSi_tcfc",
-        key.offset: 238,
+        key.offset: 250,
         key.length: 14,
         key.fully_annotated_decl: "<decl.function.constructor><syntaxtype.keyword>init</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.argument_label>x</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.constructor>",
         key.conforms: [
@@ -793,7 +818,7 @@
             key.kind: source.lang.swift.decl.var.local,
             key.keyword: "x",
             key.name: "x",
-            key.offset: 248,
+            key.offset: 260,
             key.length: 3
           }
         ]
@@ -803,7 +828,7 @@
         key.name: "init()",
         key.usr: "s:5cake19InitProtoPAAExycfc::SYNTHESIZED::s:5cake114InitStructImplV",
         key.original_usr: "s:5cake19InitProtoPAAExycfc",
-        key.offset: 258,
+        key.offset: 270,
         key.length: 6,
         key.fully_annotated_decl: "<decl.function.constructor><syntaxtype.keyword>init</syntaxtype.keyword>()</decl.function.constructor>"
       }
@@ -813,7 +838,7 @@
     key.kind: source.lang.swift.decl.protocol,
     key.name: "P1",
     key.usr: "s:5cake12P1P",
-    key.offset: 268,
+    key.offset: 280,
     key.length: 167,
     key.fully_annotated_decl: "<decl.protocol><syntaxtype.keyword>protocol</syntaxtype.keyword> <decl.name>P1</decl.name></decl.protocol>",
     key.entities: [
@@ -821,7 +846,7 @@
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "foo1()",
         key.usr: "s:5cake12P1P4foo1yyF",
-        key.offset: 287,
+        key.offset: 299,
         key.length: 11,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>foo1</decl.name>()</decl.function.method.instance>"
       },
@@ -829,7 +854,7 @@
         key.kind: source.lang.swift.decl.var.instance,
         key.name: "Ins",
         key.usr: "s:5cake12P1P3InsSivp",
-        key.offset: 304,
+        key.offset: 316,
         key.length: 24,
         key.fully_annotated_decl: "<decl.var.instance><syntaxtype.keyword>var</syntaxtype.keyword> <decl.name>Ins</decl.name>: <decl.var.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.type> { <syntaxtype.keyword>get</syntaxtype.keyword> <syntaxtype.keyword>set</syntaxtype.keyword> }</decl.var.instance>"
       },
@@ -837,7 +862,7 @@
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "foo2(a:b:)",
         key.usr: "s:5cake12P1P4foo21a1bySi_SitF",
-        key.offset: 334,
+        key.offset: 346,
         key.length: 29,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>foo2</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>a</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.argument_label>b</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.method.instance>",
         key.entities: [
@@ -845,14 +870,14 @@
             key.kind: source.lang.swift.decl.var.local,
             key.keyword: "a",
             key.name: "a",
-            key.offset: 349,
+            key.offset: 361,
             key.length: 3
           },
           {
             key.kind: source.lang.swift.decl.var.local,
             key.keyword: "b",
             key.name: "b",
-            key.offset: 359,
+            key.offset: 371,
             key.length: 3
           }
         ]
@@ -861,7 +886,7 @@
         key.kind: source.lang.swift.decl.function.subscript,
         key.name: "subscript(_:)",
         key.usr: "s:5cake12P1PyS2icip",
-        key.offset: 369,
+        key.offset: 381,
         key.length: 38,
         key.fully_annotated_decl: "<decl.function.subscript><syntaxtype.keyword>subscript</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.name>a</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Si\">Int</ref.struct></decl.function.returntype> { <syntaxtype.keyword>get</syntaxtype.keyword> <syntaxtype.keyword>set</syntaxtype.keyword> }</decl.function.subscript>",
         key.entities: [
@@ -869,7 +894,7 @@
             key.kind: source.lang.swift.decl.var.local,
             key.keyword: "_",
             key.name: "a",
-            key.offset: 384,
+            key.offset: 396,
             key.length: 3
           }
         ]
@@ -878,7 +903,7 @@
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "fooConstraint()",
         key.usr: "s:5cake12P1P13fooConstraintyyF",
-        key.offset: 413,
+        key.offset: 425,
         key.length: 20,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>fooConstraint</decl.name>()</decl.function.method.instance>"
       }
@@ -888,8 +913,8 @@
     key.kind: source.lang.swift.decl.protocol,
     key.name: "P2",
     key.usr: "s:5cake12P2P",
-    key.offset: 437,
-    key.length: 54,
+    key.offset: 449,
+    key.length: 60,
     key.fully_annotated_decl: "<decl.protocol><syntaxtype.keyword>protocol</syntaxtype.keyword> <decl.name>P2</decl.name> : <ref.protocol usr=\"s:5cake12P1P\">P1</ref.protocol></decl.protocol>",
     key.conforms: [
       {
@@ -903,7 +928,7 @@
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "bar1()",
         key.usr: "s:5cake12P2P4bar1yyF",
-        key.offset: 461,
+        key.offset: 479,
         key.length: 11,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>bar1</decl.name>()</decl.function.method.instance>"
       },
@@ -911,7 +936,7 @@
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "bar2()",
         key.usr: "s:5cake12P2P4bar2yyF",
-        key.offset: 478,
+        key.offset: 496,
         key.length: 11,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>bar2</decl.name>()</decl.function.method.instance>"
       }
@@ -919,7 +944,7 @@
   },
   {
     key.kind: source.lang.swift.decl.extension.protocol,
-    key.offset: 493,
+    key.offset: 511,
     key.length: 118,
     key.fully_annotated_generic_signature: "&lt;<decl.generic_type_param usr=\"s:5cake12P2P4Selfxmfp\"><decl.generic_type_param.name>Self</decl.generic_type_param.name></decl.generic_type_param> <syntaxtype.keyword>where</syntaxtype.keyword> <decl.generic_type_requirement><ref.generic_type_param usr=\"s:5cake12P2P4Selfxmfp\">Self</ref.generic_type_param> : <ref.protocol usr=\"s:5cake12P2P\">P2</ref.protocol></decl.generic_type_requirement>&gt;",
     key.extends: {
@@ -933,7 +958,7 @@
         key.name: "foo1()",
         key.usr: "s:5cake12P2PAAE4foo1yyF",
         key.default_implementation_of: "s:5cake12P1P4foo1yyF",
-        key.offset: 513,
+        key.offset: 531,
         key.length: 11,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>foo1</decl.name>()</decl.function.method.instance>"
       },
@@ -942,7 +967,7 @@
         key.name: "Ins",
         key.usr: "s:5cake12P2PAAE3InsSivp",
         key.default_implementation_of: "s:5cake12P1P3InsSivp",
-        key.offset: 530,
+        key.offset: 548,
         key.length: 12,
         key.fully_annotated_decl: "<decl.var.instance><syntaxtype.keyword>var</syntaxtype.keyword> <decl.name>Ins</decl.name>: <decl.var.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.type> { <syntaxtype.keyword>get</syntaxtype.keyword> <syntaxtype.keyword>set</syntaxtype.keyword> }</decl.var.instance>"
       },
@@ -951,7 +976,7 @@
         key.name: "foo2(a:b:)",
         key.usr: "s:5cake12P2PAAE4foo21a1bySi_SitF",
         key.default_implementation_of: "s:5cake12P1P4foo21a1bySi_SitF",
-        key.offset: 548,
+        key.offset: 566,
         key.length: 29,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>foo2</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>a</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.argument_label>b</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.method.instance>",
         key.entities: [
@@ -959,14 +984,14 @@
             key.kind: source.lang.swift.decl.var.local,
             key.keyword: "a",
             key.name: "a",
-            key.offset: 563,
+            key.offset: 581,
             key.length: 3
           },
           {
             key.kind: source.lang.swift.decl.var.local,
             key.keyword: "b",
             key.name: "b",
-            key.offset: 573,
+            key.offset: 591,
             key.length: 3
           }
         ]
@@ -976,7 +1001,7 @@
         key.name: "subscript(_:)",
         key.usr: "s:5cake12P2PAAEyS2icip",
         key.default_implementation_of: "s:5cake12P1PyS2icip",
-        key.offset: 583,
+        key.offset: 601,
         key.length: 26,
         key.fully_annotated_decl: "<decl.function.subscript><syntaxtype.keyword>subscript</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.name>a</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Si\">Int</ref.struct></decl.function.returntype> { <syntaxtype.keyword>get</syntaxtype.keyword> <syntaxtype.keyword>set</syntaxtype.keyword> }</decl.function.subscript>",
         key.entities: [
@@ -984,7 +1009,7 @@
             key.kind: source.lang.swift.decl.var.local,
             key.keyword: "_",
             key.name: "a",
-            key.offset: 598,
+            key.offset: 616,
             key.length: 3
           }
         ]
@@ -998,8 +1023,8 @@
         key.description: "Self : P3"
       }
     ],
-    key.offset: 613,
-    key.length: 58,
+    key.offset: 631,
+    key.length: 64,
     key.fully_annotated_generic_signature: "&lt;<decl.generic_type_param usr=\"s:5cake12P2PA2A2P3RzrlE4Selfxmfp\"><decl.generic_type_param.name>Self</decl.generic_type_param.name></decl.generic_type_param> <syntaxtype.keyword>where</syntaxtype.keyword> <decl.generic_type_requirement><ref.generic_type_param usr=\"s:5cake12P2PA2A2P3RzrlE4Selfxmfp\">Self</ref.generic_type_param> : <ref.protocol usr=\"s:5cake12P2P\">P2</ref.protocol></decl.generic_type_requirement>, <decl.generic_type_requirement><ref.generic_type_param usr=\"s:5cake12P2PA2A2P3RzrlE4Selfxmfp\">Self</ref.generic_type_param> : <ref.protocol usr=\"s:5cake12P3P\">P3</ref.protocol></decl.generic_type_requirement>&gt;",
     key.extends: {
       key.kind: source.lang.swift.ref.protocol,
@@ -1012,7 +1037,7 @@
         key.name: "fooConstraint()",
         key.usr: "s:5cake12P2PA2A2P3RzrlE13fooConstraintyyF",
         key.default_implementation_of: "s:5cake12P1P13fooConstraintyyF",
-        key.offset: 649,
+        key.offset: 673,
         key.length: 20,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>fooConstraint</decl.name>()</decl.function.method.instance>"
       }
@@ -1022,7 +1047,7 @@
     key.kind: source.lang.swift.decl.protocol,
     key.name: "P3",
     key.usr: "s:5cake12P3P",
-    key.offset: 673,
+    key.offset: 697,
     key.length: 38,
     key.fully_annotated_decl: "<decl.protocol><syntaxtype.keyword>protocol</syntaxtype.keyword> <decl.name>P3</decl.name></decl.protocol>",
     key.entities: [
@@ -1030,7 +1055,7 @@
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "p3Required()",
         key.usr: "s:5cake12P3P10p3RequiredyyF",
-        key.offset: 692,
+        key.offset: 716,
         key.length: 17,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>p3Required</decl.name>()</decl.function.method.instance>"
       }
@@ -1051,7 +1076,7 @@
         key.description: "Key : Hashable"
       }
     ],
-    key.offset: 713,
+    key.offset: 737,
     key.length: 45,
     key.fully_annotated_generic_signature: "&lt;<decl.generic_type_param usr=\"s:SD3Keyxmfp\"><decl.generic_type_param.name>Key</decl.generic_type_param.name></decl.generic_type_param>, <decl.generic_type_param usr=\"s:SD5Valueq_mfp\"><decl.generic_type_param.name>Value</decl.generic_type_param.name></decl.generic_type_param> <syntaxtype.keyword>where</syntaxtype.keyword> <decl.generic_type_requirement>Key : <ref.protocol usr=\"s:SH\">Hashable</ref.protocol></decl.generic_type_requirement>&gt;",
     key.extends: {
@@ -1064,7 +1089,7 @@
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "foo()",
         key.usr: "s:SD4KeysV5cake1E3fooyyF",
-        key.offset: 746,
+        key.offset: 770,
         key.length: 10,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>foo</decl.name>()</decl.function.method.instance>"
       }
@@ -1080,8 +1105,8 @@
         key.description: "Key : P1"
       }
     ],
-    key.offset: 760,
-    key.length: 60,
+    key.offset: 784,
+    key.length: 66,
     key.fully_annotated_generic_signature: "&lt;<decl.generic_type_param usr=\"s:SD4KeysV5cake1AC2P1RzrlE3Keyxmfp\"><decl.generic_type_param.name>Key</decl.generic_type_param.name></decl.generic_type_param>, <decl.generic_type_param usr=\"s:SD4KeysV5cake1AC2P1RzrlE5Valueq_mfp\"><decl.generic_type_param.name>Value</decl.generic_type_param.name></decl.generic_type_param> <syntaxtype.keyword>where</syntaxtype.keyword> <decl.generic_type_requirement>Key : <ref.protocol usr=\"s:SH\">Hashable</ref.protocol></decl.generic_type_requirement>, <decl.generic_type_requirement>Key : <ref.protocol usr=\"s:5cake12P1P\">P1</ref.protocol></decl.generic_type_requirement>&gt;",
     key.extends: {
       key.kind: source.lang.swift.ref.struct,
@@ -1093,7 +1118,7 @@
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "bar()",
         key.usr: "s:SD4KeysV5cake1AC2P1RzrlE3baryyF",
-        key.offset: 808,
+        key.offset: 838,
         key.length: 10,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>bar</decl.name>()</decl.function.method.instance>"
       }
diff --git a/test/api-digester/Outputs/Cake-abi.txt b/test/api-digester/Outputs/Cake-abi.txt
index 1aaa9f2..0fb4f38 100644
--- a/test/api-digester/Outputs/Cake-abi.txt
+++ b/test/api-digester/Outputs/Cake-abi.txt
@@ -1,7 +1,7 @@
 
 /* Generic Signature Changes */
 cake1: Func P1.P1Constraint() has generic signature change from <τ_0_0 where τ_0_0 : P1, τ_0_0 : P2> to <τ_0_0 where τ_0_0 : P1>
-cake1: Protocol P3 has generic signature change from <τ_0_0 : P1, τ_0_0 : P2> to <τ_0_0 : P1, τ_0_0 : P4>
+cake1: Protocol P3 has generic signature change from <τ_0_0 : cake.P1, τ_0_0 : cake.P2> to <τ_0_0 : cake.P1, τ_0_0 : cake.P4>
 
 /* RawRepresentable Changes */
 
diff --git a/test/api-digester/Outputs/Cake.txt b/test/api-digester/Outputs/Cake.txt
index b415e2c..222487d 100644
--- a/test/api-digester/Outputs/Cake.txt
+++ b/test/api-digester/Outputs/Cake.txt
@@ -1,7 +1,7 @@
 
 /* Generic Signature Changes */
 cake1: Func P1.P1Constraint() has generic signature change from <Self where Self : P1, Self : P2> to <Self where Self : P1>
-cake1: Protocol P3 has generic signature change from <Self : P1, Self : P2> to <Self : P1, Self : P4>
+cake1: Protocol P3 has generic signature change from <Self : cake.P1, Self : cake.P2> to <Self : cake.P1, Self : cake.P4>
 
 /* RawRepresentable Changes */
 
diff --git a/test/api-digester/Outputs/cake-abi.json b/test/api-digester/Outputs/cake-abi.json
index d90815b..599c3a9 100644
--- a/test/api-digester/Outputs/cake-abi.json
+++ b/test/api-digester/Outputs/cake-abi.json
@@ -59,7 +59,7 @@
       "declKind": "Protocol",
       "usr": "s:4cake2P3P",
       "moduleName": "cake",
-      "genericSig": "<τ_0_0 : P1, τ_0_0 : P2>",
+      "genericSig": "<τ_0_0 : cake.P1, τ_0_0 : cake.P2>",
       "conformances": [
         {
           "kind": "Conformance",
@@ -1057,7 +1057,7 @@
       "declKind": "Protocol",
       "usr": "s:4cake4PSubP",
       "moduleName": "cake",
-      "genericSig": "<τ_0_0 : PSuper>",
+      "genericSig": "<τ_0_0 : cake.PSuper>",
       "conformances": [
         {
           "kind": "Conformance",
diff --git a/test/api-digester/Outputs/cake.json b/test/api-digester/Outputs/cake.json
index c37af7b..a5b0dfb 100644
--- a/test/api-digester/Outputs/cake.json
+++ b/test/api-digester/Outputs/cake.json
@@ -59,7 +59,7 @@
       "declKind": "Protocol",
       "usr": "s:4cake2P3P",
       "moduleName": "cake",
-      "genericSig": "<Self : P1, Self : P2>",
+      "genericSig": "<Self : cake.P1, Self : cake.P2>",
       "conformances": [
         {
           "kind": "Conformance",
@@ -1004,7 +1004,7 @@
       "declKind": "Protocol",
       "usr": "s:4cake4PSubP",
       "moduleName": "cake",
-      "genericSig": "<Self : PSuper>",
+      "genericSig": "<Self : cake.PSuper>",
       "conformances": [
         {
           "kind": "Conformance",
diff --git a/test/api-digester/compare-dump.swift b/test/api-digester/compare-dump.swift
index 6b79bad..daf7dd0 100644
--- a/test/api-digester/compare-dump.swift
+++ b/test/api-digester/compare-dump.swift
@@ -1,18 +1,19 @@
-// RUN: %empty-directory(%t.mod)
+// RUN: %empty-directory(%t.mod1)
+// RUN: %empty-directory(%t.mod2)
 // RUN: %empty-directory(%t.sdk)
 // RUN: %empty-directory(%t.module-cache)
-// RUN: %swift -emit-module -o %t.mod/cake1.swiftmodule %S/Inputs/cake1.swift -parse-as-library -enable-library-evolution -I %S/Inputs/APINotesLeft %clang-importer-sdk-nosource
-// RUN: %swift -emit-module -o %t.mod/cake2.swiftmodule %S/Inputs/cake2.swift -parse-as-library -enable-library-evolution -I %S/Inputs/APINotesRight %clang-importer-sdk-nosource
-// RUN: %api-digester -dump-sdk -module cake1 -o %t.dump1.json -module-cache-path %t.module-cache %clang-importer-sdk-nosource -I %t.mod -I %S/Inputs/APINotesLeft
-// RUN: %api-digester -dump-sdk -module cake2 -o %t.dump2.json -module-cache-path %t.module-cache %clang-importer-sdk-nosource -I %t.mod -I %S/Inputs/APINotesRight
+// RUN: %swift -emit-module -o %t.mod1/cake.swiftmodule %S/Inputs/cake1.swift -parse-as-library -enable-library-evolution -I %S/Inputs/APINotesLeft %clang-importer-sdk-nosource
+// RUN: %swift -emit-module -o %t.mod2/cake.swiftmodule %S/Inputs/cake2.swift -parse-as-library -enable-library-evolution -I %S/Inputs/APINotesRight %clang-importer-sdk-nosource
+// RUN: %api-digester -dump-sdk -module cake -o - -module-cache-path %t.module-cache %clang-importer-sdk-nosource -I %t.mod1 -I %S/Inputs/APINotesLeft | sed 's/"cake"/"cake1"/' > %t.dump1.json
+// RUN: %api-digester -dump-sdk -module cake -o - -module-cache-path %t.module-cache %clang-importer-sdk-nosource -I %t.mod2 -I %S/Inputs/APINotesLeft | sed 's/"cake"/"cake2"/' > %t.dump2.json
 // RUN: %api-digester -diagnose-sdk -print-module --input-paths %t.dump1.json -input-paths %t.dump2.json -o %t.result
 
 // RUN: %clang -E -P -x c %S/Outputs/Cake.txt -o - | sed '/^\s*$/d' > %t.expected
 // RUN: %clang -E -P -x c %t.result -o - | sed '/^\s*$/d' > %t.result.tmp
 // RUN: diff -u %t.expected %t.result.tmp
 
-// RUN: %api-digester -dump-sdk -module cake1 -o %t.dump1.json -module-cache-path %t.module-cache %clang-importer-sdk-nosource -I %t.mod -I %S/Inputs/APINotesLeft -abi
-// RUN: %api-digester -dump-sdk -module cake2 -o %t.dump2.json -module-cache-path %t.module-cache %clang-importer-sdk-nosource -I %t.mod -I %S/Inputs/APINotesRight -abi
+// RUN: %api-digester -dump-sdk -module cake -o - -module-cache-path %t.module-cache %clang-importer-sdk-nosource -I %t.mod1 -I %S/Inputs/APINotesLeft -abi | sed 's/"cake"/"cake1"/' > %t.dump1.json
+// RUN: %api-digester -dump-sdk -module cake -o - -module-cache-path %t.module-cache %clang-importer-sdk-nosource -I %t.mod2 -I %S/Inputs/APINotesLeft -abi | sed 's/"cake"/"cake2"/' > %t.dump2.json
 // RUN: %api-digester -diagnose-sdk -print-module --input-paths %t.dump1.json -input-paths %t.dump2.json -abi -o %t.result
 
 // RUN: %clang -E -P -x c %S/Outputs/Cake-abi.txt -o - | sed '/^\s*$/d' > %t.abi.expected
diff --git a/test/decl/import/import.swift b/test/decl/import/import.swift
index 5bcecc4..06cf3c0 100644
--- a/test/decl/import/import.swift
+++ b/test/decl/import/import.swift
@@ -2,7 +2,7 @@
 // RUN: echo "public struct X {}; public var x = X()" | %target-swift-frontend -module-name import_builtin -parse-stdlib -emit-module -o %t -
 // RUN: echo "public func foo() -> Int { return false }" > %t/import_text.swift
 // RUN: echo "public func phoûx() -> Int { return false }" > %t/français.swift
-// RUN: %target-swift-frontend -typecheck %s -I %t -sdk "" -enable-source-import -module-name main -verify -show-diagnostics-after-fatal -verify-ignore-unknown
+// RUN: %target-swift-frontend -typecheck %s -I %t -I %S/../../Inputs/ -sdk "" -enable-source-import -module-name main -verify -show-diagnostics-after-fatal -verify-ignore-unknown
 
 // -verify-ignore-unknown is for:
 // <unknown>:0: error: unexpected note produced: did you forget to set an SDK using -sdk or SDKROOT?
@@ -68,3 +68,5 @@
 import func français.phoûx
 
 import main // expected-warning {{file 'import.swift' is part of module 'main'; ignoring import}}
+
+@_exported @_implementationOnly import empty // expected-error {{module 'empty' cannot be both exported and implementation-only}} {{12-33=}}
diff --git a/test/decl/overload.swift b/test/decl/overload.swift
index 745946f..68d3d8d 100644
--- a/test/decl/overload.swift
+++ b/test/decl/overload.swift
@@ -258,6 +258,16 @@
   subscript(x x: Int) -> String { return "" }
 }
 
+struct Subscript4 {
+    subscript(f: @escaping (Int) -> Int) -> Int { // expected-note{{previously declared here}}
+        get { return f(0) }
+    }
+
+    subscript(f: (Int) -> Int) -> Int { // expected-error{{invalid redeclaration of 'subscript(_:)'}}
+        get { return f(0) }
+    }
+}
+
 struct GenericSubscripts {
   subscript<T>(x: T) -> Int { return 0 } // expected-note{{previously declared here}}
 }
diff --git a/test/expr/primary/literal/collection_upcast_opt.swift b/test/expr/primary/literal/collection_upcast_opt.swift
index fce59f1..8130a6d 100644
--- a/test/expr/primary/literal/collection_upcast_opt.swift
+++ b/test/expr/primary/literal/collection_upcast_opt.swift
@@ -15,7 +15,6 @@
 // CHECK: assign_expr
 // CHECK-NOT: collection_upcast_expr
 // CHECK: array_expr type='[(X) -> Void]'
-// CHECK: semantic_expr
 // CHECK: function_conversion_expr implicit type='(X) -> Void'
 // CHECK-NEXT: {{declref_expr.*x1}}
 // CHECK-NEXT: function_conversion_expr implicit type='(X) -> Void'
diff --git a/test/refactoring/RefactoringKind/trailingclosure.swift b/test/refactoring/RefactoringKind/trailingclosure.swift
index bc6ec02..7f412f3 100644
--- a/test/refactoring/RefactoringKind/trailingclosure.swift
+++ b/test/refactoring/RefactoringKind/trailingclosure.swift
@@ -39,7 +39,7 @@
 // RUN: %refactor -source-filename %s -pos=10:9 | %FileCheck %s -check-prefix=CHECK-NO-TRAILING-CLOSURE
 // RUN: %refactor -source-filename %s -pos=10:17 | %FileCheck %s -check-prefix=CHECK-TRAILING-CLOSURE
 
-// RUN: %refactor -source-filename %s -pos=12:4 | %FileCheck %s -check-prefix=CHECK-NO-TRAILING-CLOSURE
+// RUN: %refactor -source-filename %s -pos=12:4 | %FileCheck %s -check-prefix=CHECK-TRAILING-CLOSURE
 // RUN: %refactor -source-filename %s -pos=13:5 | %FileCheck %s -check-prefix=CHECK-TRAILING-CLOSURE
 // RUN: %refactor -source-filename %s -pos=14:5 | %FileCheck %s -check-prefix=CHECK-TRAILING-CLOSURE
 
diff --git a/tools/SourceKit/CMakeLists.txt b/tools/SourceKit/CMakeLists.txt
index b7455d3..d00d06b 100644
--- a/tools/SourceKit/CMakeLists.txt
+++ b/tools/SourceKit/CMakeLists.txt
@@ -8,27 +8,8 @@
   message(SEND_ERROR "SourceKit cannot be built standalone")
 endif()
 
-if(NOT CMAKE_C_COMPILER_ID MATCHES Clang)
-  if(CMAKE_SYSTEM_NAME STREQUAL CMAKE_HOST_SYSTEM_NAME)
-    get_target_property(CLANG_LOCATION clang LOCATION)
-    get_filename_component(CLANG_LOCATION ${CLANG_LOCATION} DIRECTORY)
-
-    if("${CMAKE_C_COMPILER_ID}" STREQUAL "MSVC" OR
-        "${CMAKE_C_SIMULATE_ID}" STREQUAL "MSVC")
-      set(CMAKE_C_COMPILER
-        ${CLANG_LOCATION}/clang-cl${CMAKE_EXECUTABLE_SUFFIX})
-      set(CMAKE_CXX_COMPILER
-        ${CLANG_LOCATION}/clang-cl${CMAKE_EXECUTABLE_SUFFIX})
-    else()
-      set(CMAKE_C_COMPILER
-        ${CLANG_LOCATION}/clang${CMAKE_EXECUTABLE_SUFFIX})
-      set(CMAKE_CXX_COMPILER
-        ${CLANG_LOCATION}/clang++${CMAKE_EXECUTABLE_SUFFIX})
-    endif()
-  else()
-    message(SEND_ERROR "SourceKit requires a clang based compiler")
-  endif()
-endif()
+include(SwiftWindowsSupport)
+swift_swap_compiler_if_needed("SourceKit")
 
 if (DARWIN_TOOLCHAIN_VERSION)
   set(SOURCEKIT_VERSION_STRING "${DARWIN_TOOLCHAIN_VERSION}")
diff --git a/tools/SourceKit/lib/SwiftLang/CodeCompletionOrganizer.cpp b/tools/SourceKit/lib/SwiftLang/CodeCompletionOrganizer.cpp
index f58e037..6f07d4d 100644
--- a/tools/SourceKit/lib/SwiftLang/CodeCompletionOrganizer.cpp
+++ b/tools/SourceKit/lib/SwiftLang/CodeCompletionOrganizer.cpp
@@ -338,8 +338,11 @@
 
   // Private imports from this module.
   // FIXME: only the private imports from the current source file.
+  ModuleDecl::ImportFilter importFilter;
+  importFilter |= ModuleDecl::ImportFilterKind::Private;
+  importFilter |= ModuleDecl::ImportFilterKind::ImplementationOnly;
   SmallVector<ModuleDecl::ImportedModule, 16> mainImports;
-  main->getImportedModules(mainImports, ModuleDecl::ImportFilter::Private);
+  main->getImportedModules(mainImports, importFilter);
   for (auto &import : mainImports) {
     uint8_t depth = 1;
     if (auxImports.count(import.second->getName().str()))
diff --git a/tools/SourceKit/lib/SwiftLang/SwiftASTManager.cpp b/tools/SourceKit/lib/SwiftLang/SwiftASTManager.cpp
index 065a256..8d3650c 100644
--- a/tools/SourceKit/lib/SwiftLang/SwiftASTManager.cpp
+++ b/tools/SourceKit/lib/SwiftLang/SwiftASTManager.cpp
@@ -788,8 +788,16 @@
     return;
 
   auto ClangModuleLoader = TopMod->getASTContext().getClangModuleLoader();
+
+  ModuleDecl::ImportFilter ImportFilter;
+  ImportFilter |= ModuleDecl::ImportFilterKind::Public;
+  ImportFilter |= ModuleDecl::ImportFilterKind::Private;
+  if (Visited.empty()) {
+    // Only collect implementation-only dependencies from the main module.
+    ImportFilter |= ModuleDecl::ImportFilterKind::ImplementationOnly;
+  }
   SmallVector<ModuleDecl::ImportedModule, 8> Imports;
-  TopMod->getImportedModules(Imports, ModuleDecl::ImportFilter::All);
+  TopMod->getImportedModules(Imports, ImportFilter);
 
   for (auto Import : Imports) {
     ModuleDecl *Mod = Import.second;
diff --git a/tools/SourceKit/lib/SwiftLang/SwiftIndexing.cpp b/tools/SourceKit/lib/SwiftLang/SwiftIndexing.cpp
index 1631338..cc56684 100644
--- a/tools/SourceKit/lib/SwiftLang/SwiftIndexing.cpp
+++ b/tools/SourceKit/lib/SwiftLang/SwiftIndexing.cpp
@@ -190,7 +190,9 @@
     // documentation file.
     // FIXME: refactor the frontend to provide an easy way to figure out the
     // correct filename here.
-    auto FUnit = Loader->loadAST(*Mod, None, std::move(Buf), nullptr);
+    auto FUnit = Loader->loadAST(*Mod, None, std::move(Buf), nullptr,
+                                 /*isFramework*/false,
+                                 /*treatAsPartialModule*/false);
 
     // FIXME: Not knowing what went wrong is pretty bad. loadModule() should be
     // more modular, rather than emitting diagnostics itself.
diff --git a/tools/libSwiftSyntaxParser/CMakeLists.txt b/tools/libSwiftSyntaxParser/CMakeLists.txt
index 9d78c0a..e94b531 100644
--- a/tools/libSwiftSyntaxParser/CMakeLists.txt
+++ b/tools/libSwiftSyntaxParser/CMakeLists.txt
@@ -1,3 +1,6 @@
+include(SwiftWindowsSupport)
+swift_swap_compiler_if_needed("SwiftSyntaxParser")
+
 # Use an 'internal' name, this is primarily intended for SwiftSyntax to import.
 set(SYNTAX_PARSER_LIB_NAME "_InternalSwiftSyntaxParser")
 
diff --git a/tools/swift-api-digester/CMakeLists.txt b/tools/swift-api-digester/CMakeLists.txt
index a6fba59..12cc78e 100644
--- a/tools/swift-api-digester/CMakeLists.txt
+++ b/tools/swift-api-digester/CMakeLists.txt
@@ -3,6 +3,7 @@
   ModuleAnalyzerNodes.cpp
   ModuleDiagsConsumer.cpp
   SWIFT_COMPONENT tools
+  SWIFT_COMPONENT toolchain-tools
 )
 target_link_libraries(swift-api-digester
                       PRIVATE
diff --git a/tools/swift-ide-test/swift-ide-test.cpp b/tools/swift-ide-test/swift-ide-test.cpp
index 4571c27..bbb12ef 100644
--- a/tools/swift-ide-test/swift-ide-test.cpp
+++ b/tools/swift-ide-test/swift-ide-test.cpp
@@ -2644,7 +2644,8 @@
       llvm::outs() << ":\n";
 
       scratch.clear();
-      next.second->getImportedModules(scratch, ModuleDecl::ImportFilter::Public);
+      next.second->getImportedModules(scratch,
+                                      ModuleDecl::ImportFilterKind::Public);
       for (auto &import : scratch) {
         llvm::outs() << "\t" << import.second->getName();
         for (auto accessPathPiece : import.first) {
diff --git a/tools/swift-syntax-parser-test/CMakeLists.txt b/tools/swift-syntax-parser-test/CMakeLists.txt
index 6f49a5b..c1beb79 100644
--- a/tools/swift-syntax-parser-test/CMakeLists.txt
+++ b/tools/swift-syntax-parser-test/CMakeLists.txt
@@ -1,3 +1,6 @@
+include(SwiftWindowsSupport)
+swift_swap_compiler_if_needed("SwiftSyntaxParserTest")
+
 add_swift_host_tool(swift-syntax-parser-test
   swift-syntax-parser-test.cpp
   LLVM_COMPONENT_DEPENDS
diff --git a/unittests/SyntaxParser/CMakeLists.txt b/unittests/SyntaxParser/CMakeLists.txt
index 4b839ba..6082cbe 100644
--- a/unittests/SyntaxParser/CMakeLists.txt
+++ b/unittests/SyntaxParser/CMakeLists.txt
@@ -1,3 +1,6 @@
+include(SwiftWindowsSupport)
+swift_swap_compiler_if_needed("SyntaxParserUnitTests")
+
 add_swift_unittest(SwiftSyntaxParserTests
   SyntaxParserTests.cpp
 )
diff --git a/utils/api_checker/CMakeLists.txt b/utils/api_checker/CMakeLists.txt
index 6d8dc1d..56e2250 100644
--- a/utils/api_checker/CMakeLists.txt
+++ b/utils/api_checker/CMakeLists.txt
@@ -1,6 +1,6 @@
-swift_install_in_component(tools
+swift_install_in_either_component(tools toolchain-tools
   FILES "swift-api-checker.py"
   DESTINATION "bin")
-swift_install_in_component(tools
+swift_install_in_either_component(tools toolchain-tools
   DIRECTORY "sdk-module-lists"
   DESTINATION "bin")
diff --git a/utils/api_checker/sdk-module-lists/fixed-modules-watchos.txt b/utils/api_checker/sdk-module-lists/fixed-modules-watchos.txt
index e69de29..d15abba 100644
--- a/utils/api_checker/sdk-module-lists/fixed-modules-watchos.txt
+++ b/utils/api_checker/sdk-module-lists/fixed-modules-watchos.txt
@@ -0,0 +1 @@
+// Empty
diff --git a/utils/build-presets.ini b/utils/build-presets.ini
index 5fdcce9..76626b0 100644
--- a/utils/build-presets.ini
+++ b/utils/build-presets.ini
@@ -16,7 +16,7 @@
 [preset: mixin_buildbot_install_components]
 dash-dash
 
-swift-install-components=compiler;clang-builtin-headers;stdlib;sdk-overlay;parser-lib;editor-integration;tools;testsuite-tools;sourcekit-xpc-service;swift-remote-mirror;swift-remote-mirror-headers;
+swift-install-components=compiler;clang-builtin-headers;stdlib;sdk-overlay;parser-lib;editor-integration;tools;toolchain-tools;testsuite-tools;sourcekit-xpc-service;swift-remote-mirror;swift-remote-mirror-headers;
 
 
 [preset: mixin_buildbot_trunk_base]
@@ -736,7 +736,7 @@
 install-xctest
 install-libicu
 install-prefix=/usr
-swift-install-components=autolink-driver;compiler;clang-resource-dir-symlink;stdlib;swift-remote-mirror;sdk-overlay;parser-lib;license;sourcekit-inproc
+swift-install-components=autolink-driver;compiler;clang-resource-dir-symlink;stdlib;swift-remote-mirror;sdk-overlay;parser-lib;toolchain-tools;license;sourcekit-inproc
 llvm-install-components=llvm-cov;llvm-profdata;IndexStore;clang;clang-headers;compiler-rt;clangd
 install-libcxx
 build-swift-static-stdlib
@@ -1129,7 +1129,7 @@
 # If someone uses this for incremental builds, force reconfiguration.
 reconfigure
 
-swift-install-components=compiler;clang-resource-dir-symlink;stdlib;sdk-overlay;parser-lib;license;sourcekit-xpc-service;swift-remote-mirror;swift-remote-mirror-headers
+swift-install-components=compiler;clang-resource-dir-symlink;stdlib;sdk-overlay;parser-lib;toolchain-tools;license;sourcekit-xpc-service;swift-remote-mirror;swift-remote-mirror-headers
 llvm-install-components=llvm-cov;llvm-profdata;IndexStore;clang;clang-headers;compiler-rt;clangd
 install-libcxx
 
diff --git a/validation-test/Serialization/xref-badtag-49336277/Inputs/basemod.swift b/validation-test/Serialization/xref-badtag-49336277/Inputs/basemod.swift
new file mode 100644
index 0000000..353732c
--- /dev/null
+++ b/validation-test/Serialization/xref-badtag-49336277/Inputs/basemod.swift
@@ -0,0 +1,13 @@
+import itermod
+
+public protocol MySequence {
+  associatedtype Element
+  associatedtype Iterator: MyIter where Iterator.Element == Element
+}
+
+public struct MyBar: MySequence, MyIter {
+  public func callme() {}
+
+  public typealias Element = UInt8
+  public typealias Iterator = MyBar
+}
diff --git a/validation-test/Serialization/xref-badtag-49336277/Inputs/dependmod.swift b/validation-test/Serialization/xref-badtag-49336277/Inputs/dependmod.swift
new file mode 100644
index 0000000..411b0c8
--- /dev/null
+++ b/validation-test/Serialization/xref-badtag-49336277/Inputs/dependmod.swift
@@ -0,0 +1,4 @@
+import itermod
+import basemod
+
+extension MyIter where Element == MyBar {}
diff --git a/validation-test/Serialization/xref-badtag-49336277/Inputs/itermod.swift b/validation-test/Serialization/xref-badtag-49336277/Inputs/itermod.swift
new file mode 100644
index 0000000..a90d06b
--- /dev/null
+++ b/validation-test/Serialization/xref-badtag-49336277/Inputs/itermod.swift
@@ -0,0 +1,3 @@
+public protocol MyIter {
+  associatedtype Element
+}
diff --git a/validation-test/Serialization/xref-badtag-49336277/main.swift b/validation-test/Serialization/xref-badtag-49336277/main.swift
new file mode 100644
index 0000000..f646480
--- /dev/null
+++ b/validation-test/Serialization/xref-badtag-49336277/main.swift
@@ -0,0 +1,14 @@
+// RUN: %empty-directory(%t)
+// RUN: %target-swift-frontend %S/Inputs/itermod.swift -module-name itermod -emit-module -o %t/itermod.swiftmodule
+// RUN: %target-swift-frontend %S/Inputs/basemod.swift -module-name basemod -emit-module -o %t/basemod.swiftmodule -I %t
+// RUN: %target-swift-frontend %S/Inputs/dependmod.swift -module-name dependmod -emit-module -o %t/dependmod.swiftmodule -I %t
+// RUN: %target-swift-frontend -typecheck %s -I %t -verify
+
+import basemod
+import dependmod
+
+func test(b: MyBar) {
+  b.callme()
+  // Check that there was typechecking.
+  b.non_existent() // expected-error {{no member 'non_existent'}}
+}
diff --git a/validation-test/compiler_crashers_2_fixed/0189-rdar49371608.swift b/validation-test/compiler_crashers_2_fixed/0189-rdar49371608.swift
new file mode 100644
index 0000000..219570b
--- /dev/null
+++ b/validation-test/compiler_crashers_2_fixed/0189-rdar49371608.swift
@@ -0,0 +1,11 @@
+// RUN: %target-typecheck-verify-swift
+
+struct A<T> {
+  let foo: [T]
+}
+
+extension A : Codable where T: Codable {
+  enum CodingKeys: String, CodingKey {
+    case foo = "foo"
+  }
+}