Merge pull request #18257 from lorentey/NSObject-hashing2

[ObjectiveC] NSObject: Clarify hashing implementation
diff --git a/include/swift/ABI/MetadataValues.h b/include/swift/ABI/MetadataValues.h
index a1e6570..0e48429 100644
--- a/include/swift/ABI/MetadataValues.h
+++ b/include/swift/ABI/MetadataValues.h
@@ -1180,35 +1180,51 @@
     // Generic flags build upwards from 0.
     // Type-specific flags build downwards from 15.
 
-    /// Set if the type represents an imported C tag type.
-    ///
-    /// Meaningful for all type-descriptor kinds.
-    IsCTag = 0,
-
-    /// Set if the type represents an imported C typedef type.
-    ///
-    /// Meaningful for all type-descriptor kinds.
-    IsCTypedef = 1,
-
     /// Set if the type supports reflection.  C and Objective-C enums
     /// currently don't.
     ///
     /// Meaningful for all type-descriptor kinds.
-    IsReflectable = 2,
-    
-    /// Set if the type is a Clang-importer-synthesized related entity. After
-    /// the null terminator for the type name is another null-terminated string
-    /// containing the tag that discriminates the entity from other synthesized
-    /// declarations associated with the same declaration.
-    IsSynthesizedRelatedEntity = 3,
+    IsReflectable = 0,
 
-    /// Set if the type requires non-trivial but non-generic metadata
-    /// initialization.  It may or may not be truly "in place" depending
-    /// on the kind of metadata.
+    /// Whether there's something unusual about how the metadata is
+    /// initialized.
     ///
-    /// Currently only meaningful for value descriptors, but will be
-    /// extended to class descriptors.
-    HasInPlaceMetadataInitialization = 4,
+    /// Meaningful for all type-descriptor kinds.
+    MetadataInitialization = 1,
+    MetadataInitialization_width = 2,
+
+    /// The namespace of the imported declaration that gave rise to this type.
+    /// Some languages (most importantly, C/C++/Objective-C) have different
+    /// symbol namespaces in which types can be declared; for example,
+    /// `struct A` and `typedef ... A` can be declared in the same scope and
+    /// resolve to unrelated types.  When these declarations are imported,
+    /// there are several possible ways to distinguish them in Swift, e.g.
+    /// by implicitly renaming them; however, the external name used for
+    /// mangling and metadata must be stable and so is based on the original
+    /// declared name.  Therefore, in these languages, we privilege one
+    /// symbol namespace as the default (although which may depend on the
+    /// type kind), and declarations from the other(s) must be marked in
+    /// order to differentiate them.
+    ///
+    /// Meaningful for all type-descriptor kinds.
+    ImportNamespace = 3,
+    ImportNamespace_width = 3,
+    
+    /// Set if the type is an importer-synthesized related entity.
+    /// A related entity is an entity synthesized in response to an imported
+    /// type which is not the type itself; for example, when the importer
+    /// sees an ObjC error domain, it creates an error-wrapper type (a
+    /// related entity) and a Code enum (not a related entity because it's
+    /// exactly the original type).
+    ///
+    /// The name and import namespace (together with the parent context)
+    /// identify the original declaration.
+    ///
+    /// If this flag is set, then after the null terminator for the type name
+    /// is another null-terminated string containing the tag that discriminates
+    /// the entity from other synthesized declarations associated with the
+    /// same declaration.
+    IsSynthesizedRelatedEntity = 6,
 
     /// Set if the context descriptor is includes metadata for dynamically
     /// constructing a class's vtables at metadata instantiation time.
@@ -1237,18 +1253,74 @@
   explicit TypeContextDescriptorFlags(uint16_t bits) : FlagSet(bits) {}
   constexpr TypeContextDescriptorFlags() {}
 
-  FLAGSET_DEFINE_FLAG_ACCESSORS(IsCTag, isCTag, setIsCTag)
-  FLAGSET_DEFINE_FLAG_ACCESSORS(IsCTypedef, isCTypedef, setIsCTypedef)
   FLAGSET_DEFINE_FLAG_ACCESSORS(IsReflectable, isReflectable, setIsReflectable)
 
+  enum MetadataInitializationKind {
+    /// There are either no special rules for initializing the metadata
+    /// or the metadata is generic.  (Genericity is set in the
+    /// non-kind-specific descriptor flags.)
+    NoMetadataInitialization = 0,
+
+    /// The type requires non-trivial singleton initialization using the
+    /// "in-place" code pattern.
+    InPlaceMetadataInitialization = 1,
+
+    // We only have two bits here, so if you add a third special kind,
+    // include more flag bits in its out-of-line storage.
+  };
+
+  FLAGSET_DEFINE_FIELD_ACCESSORS(MetadataInitialization,
+                                 MetadataInitialization_width,
+                                 MetadataInitializationKind,
+                                 getMetadataInitialization,
+                                 setMetadataInitialization)
+
+  bool hasInPlaceMetadataInitialization() const {
+    return getMetadataInitialization() == InPlaceMetadataInitialization;
+  }
+
+  enum ImportNamespaceKind {
+    /// The type comes the default namespace for its language.
+    DefaultNamespace = 0,
+
+    // The behavior for C imported types is complicated in ways that don't
+    // entirely make sense according to the design laid out in the comment
+    // on the ImportNamespace field.  The rules are basically:
+    //   - Classes are assumed to come from Objective-C by default.
+    //     ObjC classes are in the ordinary namespace in C.
+    //   - Protocols are assumed to come from Objective-C by default.
+    //     ObjC protocols are in their own namespace in C.
+    //   - Structs and enums seem to always get either CTag or CTypedef.
+    //     It would probably make more sense to assume they come from the
+    //     tag namespace in C and then just use CTypedef as an override.
+
+    /// The type comes from an imported C tag type.
+    CTag = 1,
+
+    /// The type comes from an imported C typedef type.
+    CTypedef = 2,
+
+    // We only have three bits here, so be judicious about adding new
+    // namespaces.
+  };
+
+  FLAGSET_DEFINE_FIELD_ACCESSORS(ImportNamespace,
+                                 ImportNamespace_width,
+                                 ImportNamespaceKind,
+                                 getImportNamespace,
+                                 setImportNamespace)
+
+  bool isCTag() const {
+    return getImportNamespace() == CTag;
+  }
+  bool isCTypedef() const {
+    return getImportNamespace() == CTypedef;
+  }
+
   FLAGSET_DEFINE_FLAG_ACCESSORS(IsSynthesizedRelatedEntity,
                                 isSynthesizedRelatedEntity,
                                 setIsSynthesizedRelatedEntity)
 
-  FLAGSET_DEFINE_FLAG_ACCESSORS(HasInPlaceMetadataInitialization,
-                                hasInPlaceMetadataInitialization,
-                                setHasInPlaceMetadataInitialization)
-
   FLAGSET_DEFINE_FLAG_ACCESSORS(Class_HasVTable,
                                 class_hasVTable,
                                 class_setHasVTable)
diff --git a/include/swift/AST/Decl.h b/include/swift/AST/Decl.h
index ab116e2..75e9665 100644
--- a/include/swift/AST/Decl.h
+++ b/include/swift/AST/Decl.h
@@ -480,17 +480,13 @@
     IsDebuggerAlias : 1
   );
 
-  SWIFT_INLINE_BITFIELD(NominalTypeDecl, GenericTypeDecl, 1+1+1,
+  SWIFT_INLINE_BITFIELD(NominalTypeDecl, GenericTypeDecl, 1+1,
     /// Whether we have already added implicitly-defined initializers
     /// to this declaration.
     AddedImplicitInitializers : 1,
 
     /// Whether there is are lazily-loaded conformances for this nominal type.
-    HasLazyConformances : 1,
-
-    /// Whether we have already validated all members of the type that
-    /// affect layout.
-    HasValidatedLayout : 1
+    HasLazyConformances : 1
   );
 
   SWIFT_INLINE_BITFIELD_FULL(ProtocolDecl, NominalTypeDecl, 1+1+1+1+1+1+1+1+2+8+16,
@@ -3029,7 +3025,6 @@
     Bits.NominalTypeDecl.AddedImplicitInitializers = false;
     ExtensionGeneration = 0;
     Bits.NominalTypeDecl.HasLazyConformances = false;
-    Bits.NominalTypeDecl.HasValidatedLayout = false;
   }
 
   friend class ProtocolType;
@@ -3067,18 +3062,6 @@
     Bits.NominalTypeDecl.AddedImplicitInitializers = true;
   }
 
-  /// Determine whether we have already validated any members
-  /// which affect layout.
-  bool hasValidatedLayout() const {
-    return Bits.NominalTypeDecl.HasValidatedLayout;
-  }
-
-  /// Note that we have attempted to validate any members
-  /// which affect layout.
-  void setHasValidatedLayout() {
-    Bits.NominalTypeDecl.HasValidatedLayout = true;
-  }
-
   /// Set the interface type of this nominal type to the metatype of the
   /// declared interface type.
   void computeType();
diff --git a/include/swift/AST/DiagnosticsSema.def b/include/swift/AST/DiagnosticsSema.def
index 4839da6..f1a7c39 100644
--- a/include/swift/AST/DiagnosticsSema.def
+++ b/include/swift/AST/DiagnosticsSema.def
@@ -3033,6 +3033,10 @@
       "'%0' cannot transfer control out of a defer statement",
       (StringRef))
 
+WARNING(defer_stmt_at_block_end,none,
+     "'defer' statement before end of scope always executes immediately; "
+     "replace with 'do' statement to silence this warning", ())
+
 ERROR(return_invalid_outside_func,none,
       "return invalid outside of a func", ())
 
diff --git a/include/swift/Frontend/Types.def b/include/swift/Basic/FileTypes.def
similarity index 97%
rename from include/swift/Frontend/Types.def
rename to include/swift/Basic/FileTypes.def
index 6f987dd..d9f53cd 100644
--- a/include/swift/Frontend/Types.def
+++ b/include/swift/Basic/FileTypes.def
@@ -52,7 +52,7 @@
 TYPE("assembly",            Assembly,                  "s",               "")
 TYPE("raw-sil",             RawSIL,                    "sil",             "")
 TYPE("raw-sib",             RawSIB,                    "sib",             "")
-TYPE("llvm-ir",             LLVM_IR,                   "ir",              "")
+TYPE("llvm-ir",             LLVM_IR,                   "ll",              "")
 TYPE("llvm-bc",             LLVM_BC,                   "bc",              "")
 TYPE("diagnostics",         SerializedDiagnostics,     "dia",             "")
 TYPE("objc-header",         ObjCHeader,                "h",               "")
diff --git a/include/swift/Frontend/FileTypes.h b/include/swift/Basic/FileTypes.h
similarity index 71%
rename from include/swift/Frontend/FileTypes.h
rename to include/swift/Basic/FileTypes.h
index fb8cf55..1b62e53 100644
--- a/include/swift/Frontend/FileTypes.h
+++ b/include/swift/Basic/FileTypes.h
@@ -1,8 +1,8 @@
-//===--- FileTypes.h - Input & Temporary Driver Types -----------*- C++ -*-===//
+//===--- FileTypes.h - Input & output formats used by the tools -*- C++ -*-===//
 //
 // This source file is part of the Swift.org open source project
 //
-// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
 // Licensed under Apache License v2.0 with Runtime Library Exception
 //
 // See https://swift.org/LICENSE.txt for license information
@@ -10,19 +10,19 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef SWIFT_FRONTEND_FILETYPES_H
-#define SWIFT_FRONTEND_FILETYPES_H
+#ifndef SWIFT_BASIC_FILETYPES_H
+#define SWIFT_BASIC_FILETYPES_H
 
 #include "swift/Basic/LLVM.h"
 #include "llvm/ADT/DenseMapInfo.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringRef.h"
-#include <functional>
 
 namespace swift {
 namespace file_types {
 enum ID : uint8_t {
-#define TYPE(NAME, ID, TEMP_SUFFIX, FLAGS) TY_##ID,
-#include "swift/Frontend/Types.def"
+#define TYPE(NAME, ID, EXTENSION, FLAGS) TY_##ID,
+#include "swift/Basic/FileTypes.def"
 #undef TYPE
   TY_INVALID
 };
@@ -30,9 +30,9 @@
 /// Return the name of the type for \p Id.
 StringRef getTypeName(ID Id);
 
-/// Return the suffix to use when creating a temp file of this type,
-/// or null if unspecified.
-StringRef getTypeTempSuffix(ID Id);
+/// Return the extension to use when creating a file of this type,
+/// or an empty string if unspecified.
+StringRef getExtension(ID Id);
 
 /// Lookup the type to use for the file extension \p Ext.
 /// If the extension is empty or is otherwise not recognized, return
@@ -58,8 +58,12 @@
 /// These need to be passed to the Swift frontend
 bool isPartOfSwiftCompilation(ID Id);
 
-template <typename Fn> void forAllTypes(const Fn &fn);
-} // namespace file_types
+static inline void forAllTypes(llvm::function_ref<void(file_types::ID)> fn) {
+  for (uint8_t i = 0; i < static_cast<uint8_t>(TY_INVALID); ++i)
+    fn(static_cast<ID>(i));
+}
+
+} // end namespace file_types
 } // end namespace swift
 
 namespace llvm {
@@ -72,14 +76,6 @@
   static unsigned getHashValue(ID Val) { return (unsigned)Val * 37U; }
   static bool isEqual(ID LHS, ID RHS) { return LHS == RHS; }
 };
-} // namespace llvm
-
-template <typename Fn> void swift::file_types::forAllTypes(const Fn &fn) {
-  static_assert(
-      std::is_constructible<std::function<void(file_types::ID)>, Fn>::value,
-      "must have the signature 'void(file_types::ID)'");
-  for (uint8_t i = 0; i < static_cast<uint8_t>(TY_INVALID); ++i)
-    fn(static_cast<ID>(i));
-}
+} // end namespace llvm
 
 #endif
diff --git a/include/swift/Driver/Action.h b/include/swift/Driver/Action.h
index 28dee31..c230b09 100644
--- a/include/swift/Driver/Action.h
+++ b/include/swift/Driver/Action.h
@@ -13,9 +13,9 @@
 #ifndef SWIFT_DRIVER_ACTION_H
 #define SWIFT_DRIVER_ACTION_H
 
+#include "swift/Basic/FileTypes.h"
 #include "swift/Basic/LLVM.h"
 #include "swift/Driver/Util.h"
-#include "swift/Frontend/FileTypes.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/StringSwitch.h"
diff --git a/include/swift/Driver/Driver.h b/include/swift/Driver/Driver.h
index 66c0571..3929d7b 100644
--- a/include/swift/Driver/Driver.h
+++ b/include/swift/Driver/Driver.h
@@ -18,11 +18,11 @@
 #define SWIFT_DRIVER_DRIVER_H
 
 #include "swift/AST/IRGenOptions.h"
+#include "swift/Basic/FileTypes.h"
 #include "swift/Basic/LLVM.h"
 #include "swift/Basic/OptionSet.h"
 #include "swift/Basic/Sanitizers.h"
 #include "swift/Driver/Util.h"
-#include "swift/Frontend/FileTypes.h"
 #include "swift/Frontend/OutputFileMap.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/StringMap.h"
diff --git a/include/swift/Driver/Job.h b/include/swift/Driver/Job.h
index 0e4203d..57b5a6e 100644
--- a/include/swift/Driver/Job.h
+++ b/include/swift/Driver/Job.h
@@ -13,10 +13,10 @@
 #ifndef SWIFT_DRIVER_JOB_H
 #define SWIFT_DRIVER_JOB_H
 
+#include "swift/Basic/FileTypes.h"
 #include "swift/Basic/LLVM.h"
 #include "swift/Driver/Action.h"
 #include "swift/Driver/Util.h"
-#include "swift/Frontend/FileTypes.h"
 #include "swift/Frontend/OutputFileMap.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMap.h"
diff --git a/include/swift/Driver/PrettyStackTrace.h b/include/swift/Driver/PrettyStackTrace.h
index f30030b..39685bd 100644
--- a/include/swift/Driver/PrettyStackTrace.h
+++ b/include/swift/Driver/PrettyStackTrace.h
@@ -13,7 +13,7 @@
 #ifndef SWIFT_DRIVER_PRETTYSTACKTRACE_H
 #define SWIFT_DRIVER_PRETTYSTACKTRACE_H
 
-#include "swift/Frontend/FileTypes.h"
+#include "swift/Basic/FileTypes.h"
 #include "llvm/Support/PrettyStackTrace.h"
 
 namespace swift {
diff --git a/include/swift/Driver/ToolChain.h b/include/swift/Driver/ToolChain.h
index 783b812..d22cbb3 100644
--- a/include/swift/Driver/ToolChain.h
+++ b/include/swift/Driver/ToolChain.h
@@ -13,10 +13,10 @@
 #ifndef SWIFT_DRIVER_TOOLCHAIN_H
 #define SWIFT_DRIVER_TOOLCHAIN_H
 
+#include "swift/Basic/FileTypes.h"
 #include "swift/Basic/LLVM.h"
 #include "swift/Driver/Action.h"
 #include "swift/Driver/Job.h"
-#include "swift/Frontend/FileTypes.h"
 #include "swift/Option/Options.h"
 #include "llvm/ADT/Triple.h"
 #include "llvm/Option/Option.h"
diff --git a/include/swift/Driver/Util.h b/include/swift/Driver/Util.h
index 1752e38..9859f0a 100644
--- a/include/swift/Driver/Util.h
+++ b/include/swift/Driver/Util.h
@@ -13,8 +13,8 @@
 #ifndef SWIFT_DRIVER_UTIL_H
 #define SWIFT_DRIVER_UTIL_H
 
+#include "swift/Basic/FileTypes.h"
 #include "swift/Basic/LLVM.h"
-#include "swift/Frontend/FileTypes.h"
 #include "llvm/ADT/SmallVector.h"
 
 namespace llvm {
diff --git a/include/swift/Frontend/FrontendOptions.h b/include/swift/Frontend/FrontendOptions.h
index 59e4d47..a3738a7 100644
--- a/include/swift/Frontend/FrontendOptions.h
+++ b/include/swift/Frontend/FrontendOptions.h
@@ -13,6 +13,7 @@
 #ifndef SWIFT_FRONTEND_FRONTENDOPTIONS_H
 #define SWIFT_FRONTEND_FRONTENDOPTIONS_H
 
+#include "swift/Basic/FileTypes.h"
 #include "swift/Frontend/FrontendInputsAndOutputs.h"
 #include "swift/Frontend/InputFile.h"
 #include "llvm/ADT/Hashing.h"
@@ -312,7 +313,7 @@
   static bool doesActionProduceOutput(ActionType);
   static bool doesActionProduceTextualOutput(ActionType);
   static bool needsProperModuleName(ActionType);
-  static StringRef suffixForPrincipalOutputFileForAction(ActionType);
+  static file_types::ID formatForPrincipalOutputFileForAction(ActionType);
 };
 
 }
diff --git a/include/swift/Frontend/OutputFileMap.h b/include/swift/Frontend/OutputFileMap.h
index c103293..3a1ad89 100644
--- a/include/swift/Frontend/OutputFileMap.h
+++ b/include/swift/Frontend/OutputFileMap.h
@@ -13,8 +13,8 @@
 #ifndef SWIFT_DRIVER_OUTPUTFILEMAP_H
 #define SWIFT_DRIVER_OUTPUTFILEMAP_H
 
+#include "swift/Basic/FileTypes.h"
 #include "swift/Basic/LLVM.h"
-#include "swift/Frontend/FileTypes.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringSet.h"
diff --git a/include/swift/IDE/RefactoringKinds.def b/include/swift/IDE/RefactoringKinds.def
index 3764fdf..4883886 100644
--- a/include/swift/IDE/RefactoringKinds.def
+++ b/include/swift/IDE/RefactoringKinds.def
@@ -50,6 +50,8 @@
 
 CURSOR_REFACTORING(TrailingClosure, "Convert To Trailing Closure", trailingclosure)
 
+CURSOR_REFACTORING(MemberwiseInitLocalRefactoring, "Generate Memberwise Initializer", memberwise.init.local.refactoring)
+
 RANGE_REFACTORING(ExtractExpr, "Extract Expression", extract.expr)
 
 RANGE_REFACTORING(ExtractFunction, "Extract Method", extract.function)
diff --git a/include/swift/Reflection/ReflectionContext.h b/include/swift/Reflection/ReflectionContext.h
index 33dbe73..c000f4e 100644
--- a/include/swift/Reflection/ReflectionContext.h
+++ b/include/swift/Reflection/ReflectionContext.h
@@ -77,10 +77,12 @@
 public:
   using super::getBuilder;
   using super::readDemanglingForContextDescriptor;
-  using super::readIsaMask;
-  using super::readTypeFromMetadata;
   using super::readGenericArgFromMetadata;
+  using super::readIsaMask;
+  using super::readMetadataAndValueErrorExistential;
+  using super::readMetadataAndValueOpaqueExistential;
   using super::readMetadataFromInstance;
+  using super::readTypeFromMetadata;
   using typename super::StoredPointer;
 
   explicit ReflectionContext(std::shared_ptr<MemoryReader> reader)
@@ -479,126 +481,38 @@
       *OutInstanceAddress = ExistentialAddress;
       return true;
 
-    // Opaque existentials fall under two cases:
-    // If the value fits in three words, it starts at the beginning of the
-    // container. If it doesn't, the first word is a pointer to a heap box.
     case RecordKind::OpaqueExistential: {
-      auto Fields = ExistentialRecordTI->getFields();
-      auto ExistentialMetadataField = std::find_if(Fields.begin(), Fields.end(),
-                                   [](const FieldInfo &FI) -> bool {
-        return FI.Name.compare("metadata") == 0;
-      });
-      if (ExistentialMetadataField == Fields.end())
+      auto OptMetaAndValue =
+          readMetadataAndValueOpaqueExistential(ExistentialAddress);
+      if (!OptMetaAndValue)
         return false;
+      RemoteAddress MetadataAddress = OptMetaAndValue->first;
+      RemoteAddress ValueAddress = OptMetaAndValue->second;
 
-      // Get the metadata pointer for the contained instance type.
-      // This is equivalent to:
-      // auto PointerArray = reinterpret_cast<uintptr_t*>(ExistentialAddress);
-      // uintptr_t MetadataAddress = PointerArray[Offset];
-      auto MetadataAddressAddress
-        = RemoteAddress(ExistentialAddress.getAddressData() +
-                        ExistentialMetadataField->Offset);
-
-      StoredPointer MetadataAddress = 0;
-      if (!getReader().readInteger(MetadataAddressAddress, &MetadataAddress))
-        return false;
-
-      auto InstanceTR = readTypeFromMetadata(MetadataAddress);
+      auto InstanceTR = readTypeFromMetadata(MetadataAddress.getAddressData());
       if (!InstanceTR)
         return false;
 
       *OutInstanceTR = InstanceTR;
-
-      auto InstanceTI = getTypeInfo(InstanceTR);
-      if (!InstanceTI)
-        return false;
-
-      if (InstanceTI->getSize() <= ExistentialMetadataField->Offset) {
-        // The value fits in the existential container, so it starts at the
-        // start of the container.
-        *OutInstanceAddress = ExistentialAddress;
-      } else {
-        // Otherwise it's in a box somewhere off in the heap. The first word
-        // of the container has the address to that box.
-        StoredPointer BoxAddress = 0;
-
-        if (!getReader().readInteger(ExistentialAddress, &BoxAddress))
-          return false;
-
-        // Address = BoxAddress + (sizeof(HeapObject) + alignMask) & ~alignMask)
-        auto Alignment = InstanceTI->getAlignment();
-        auto StartOfValue = BoxAddress + getSizeOfHeapObject();
-        // Align.
-        StartOfValue += Alignment - StartOfValue % Alignment;
-        *OutInstanceAddress = RemoteAddress(StartOfValue);
-      }
+      *OutInstanceAddress = ValueAddress;
       return true;
     }
     case RecordKind::ErrorExistential: {
-      // We have a pointer to an error existential, which is always heap object.
-
-      auto MetadataAddress
-        = readMetadataFromInstance(ExistentialAddress.getAddressData());
-
-      if (!MetadataAddress)
+      auto OptMetaAndValue =
+          readMetadataAndValueErrorExistential(ExistentialAddress);
+      if (!OptMetaAndValue)
         return false;
 
-      bool isObjC = false;
+      RemoteAddress InstanceMetadataAddress = OptMetaAndValue->first;
+      RemoteAddress InstanceAddress = OptMetaAndValue->second;
 
-      // If we can determine the Objective-C class name, this is probably an
-      // error existential with NSError-compatible layout.
-      std::string ObjCClassName;
-      if (readObjCClassName(*MetadataAddress, ObjCClassName)) {
-        if (ObjCClassName == "_SwiftNativeNSError")
-          isObjC = true;
-      } else {
-        // Otherwise, we can check to see if this is a class metadata with the
-        // kind value's least significant bit set, which indicates a pure
-        // Swift class.
-        auto Meta = readMetadata(*MetadataAddress);
-        auto ClassMeta = dyn_cast<TargetClassMetadata<Runtime>>(Meta);
-        if (!ClassMeta)
-          return false;
-
-        isObjC = ClassMeta->isPureObjC();
-      }
-
-      // In addition to the isa pointer and two 32-bit reference counts, if the
-      // error existential is layout-compatible with NSError, we also need to
-      // skip over its three word-sized fields: the error code, the domain,
-      // and userInfo.
-      StoredPointer InstanceMetadataAddressAddress
-        = ExistentialAddress.getAddressData() +
-          (isObjC ? 5 : 2) * sizeof(StoredPointer);
-
-      // We need to get the instance's alignment info so we can get the exact
-      // offset of the start of its data in the class.
-      auto InstanceMetadataAddress =
-        readMetadataFromInstance(InstanceMetadataAddressAddress);
-      if (!InstanceMetadataAddress)
-        return false;
-
-      auto InstanceTR = readTypeFromMetadata(*InstanceMetadataAddress);
+      auto InstanceTR =
+          readTypeFromMetadata(InstanceMetadataAddress.getAddressData());
       if (!InstanceTR)
         return false;
 
-      auto InstanceTI = getTypeInfo(InstanceTR);
-      if (!InstanceTI)
-        return false;
-
-      // Now we need to skip over the instance metadata pointer and instance's
-      // conformance pointer for Swift.Error.
-      StoredPointer InstanceAddress = InstanceMetadataAddressAddress +
-        2 * sizeof(StoredPointer);
-
-      // Round up to alignment, and we have the start address of the
-      // instance payload.
-      auto Alignment = InstanceTI->getAlignment();
-      InstanceAddress += Alignment - InstanceAddress % Alignment;
-
       *OutInstanceTR = InstanceTR;
       *OutInstanceAddress = RemoteAddress(InstanceAddress);
-
       return true;
     }
     default:
diff --git a/include/swift/Remote/MetadataReader.h b/include/swift/Remote/MetadataReader.h
index ea8de7b..cbbce7e 100644
--- a/include/swift/Remote/MetadataReader.h
+++ b/include/swift/Remote/MetadataReader.h
@@ -24,6 +24,8 @@
 #include "swift/Basic/Defer.h"
 #include "swift/Basic/Range.h"
 #include "swift/Basic/LLVM.h"
+#include "swift/Runtime/ExistentialContainer.h"
+#include "swift/Runtime/HeapObject.h"
 #include "swift/Runtime/Unreachable.h"
 
 #include <vector>
@@ -261,7 +263,131 @@
 
     return start;
   }
-  
+
+  /// Given a pointer to the metadata, attempt to read the value
+  /// witness table. Note that it's not safe to access any non-mandatory
+  /// members of the value witness table, like extra inhabitants or enum members.
+  llvm::Optional<TargetValueWitnessTable<Runtime>>
+  readValueWitnessTable(StoredPointer MetadataAddress) {
+    // The value witness table pointer is at offset -1 from the metadata
+    // pointer, that is, the pointer-sized word immediately before the
+    // pointer's referenced address.
+    TargetValueWitnessTable<Runtime> VWT;
+    auto ValueWitnessTableAddrAddr = MetadataAddress - sizeof(StoredPointer);
+    StoredPointer ValueWitnessTableAddr;
+    if (!Reader->readInteger(RemoteAddress(ValueWitnessTableAddrAddr),
+                             &ValueWitnessTableAddr))
+      return llvm::None;
+    if (!Reader->readBytes(RemoteAddress(ValueWitnessTableAddr),
+                           (uint8_t *)&VWT, sizeof(VWT)))
+      return llvm::None;
+    return VWT;
+  }
+
+  /// Given a pointer to a known-error existential, attempt to discover the
+  /// pointer to its metadata address and its value address.
+  llvm::Optional<std::pair<RemoteAddress, RemoteAddress>>
+  readMetadataAndValueErrorExistential(RemoteAddress ExistentialAddress) {
+    // An pointer to an error existential is always an heap object.
+    auto MetadataAddress =
+        readMetadataFromInstance(ExistentialAddress.getAddressData());
+    if (!MetadataAddress)
+      return llvm::None;
+
+    bool isObjC = false;
+
+    // If we can determine the Objective-C class name, this is probably an
+    // error existential with NSError-compatible layout.
+    std::string ObjCClassName;
+    if (readObjCClassName(*MetadataAddress, ObjCClassName)) {
+      if (ObjCClassName == "_SwiftNativeNSError")
+        isObjC = true;
+    } else {
+      // Otherwise, we can check to see if this is a class metadata with the
+      // kind value's least significant bit set, which indicates a pure
+      // Swift class.
+      auto Meta = readMetadata(*MetadataAddress);
+      auto ClassMeta = dyn_cast<TargetClassMetadata<Runtime>>(Meta);
+      if (!ClassMeta)
+        return llvm::None;
+
+      isObjC = ClassMeta->isPureObjC();
+    }
+
+    // In addition to the isa pointer and two 32-bit reference counts, if the
+    // error existential is layout-compatible with NSError, we also need to
+    // skip over its three word-sized fields: the error code, the domain,
+    // and userInfo.
+    StoredPointer InstanceMetadataAddressAddress =
+        ExistentialAddress.getAddressData() +
+        (isObjC ? 5 : 2) * sizeof(StoredPointer);
+
+    // We need to get the instance's alignment info so we can get the exact
+    // offset of the start of its data in the class.
+    auto InstanceMetadataAddress =
+        readMetadataFromInstance(InstanceMetadataAddressAddress);
+    if (!InstanceMetadataAddress)
+      return llvm::None;
+
+    // Read the value witness table.
+    auto VWT = readValueWitnessTable(*InstanceMetadataAddress);
+    if (!VWT)
+      return llvm::None;
+
+    // Now we need to skip over the instance metadata pointer and instance's
+    // conformance pointer for Swift.Error.
+    StoredPointer InstanceAddress =
+        InstanceMetadataAddressAddress + 2 * sizeof(StoredPointer);
+
+    // Round up to alignment, and we have the start address of the
+    // instance payload.
+    auto AlignmentMask = VWT->getAlignmentMask();
+    auto Offset = (sizeof(HeapObject) + AlignmentMask) & ~AlignmentMask;
+    InstanceAddress += Offset;
+
+    return llvm::Optional<std::pair<RemoteAddress, RemoteAddress>>(
+        {RemoteAddress(*InstanceMetadataAddress),
+         RemoteAddress(InstanceAddress)});
+  }
+
+  /// Given a known-opaque existential, attemp to discover the pointer to its
+  /// metadata address and its value.
+  llvm::Optional<std::pair<RemoteAddress, RemoteAddress>>
+  readMetadataAndValueOpaqueExistential(RemoteAddress ExistentialAddress) {
+    // OpaqueExistentialContainer is the layout of an opaque existential.
+    // `Type` is the pointer to the metadata.
+    TargetOpaqueExistentialContainer<Runtime> Container;
+    if (!Reader->readBytes(RemoteAddress(ExistentialAddress),
+                           (uint8_t *)&Container, sizeof(Container)))
+      return llvm::None;
+    auto MetadataAddress = reinterpret_cast<StoredPointer>(Container.Type);
+    auto Metadata = readMetadata(MetadataAddress);
+    if (!Metadata)
+      return llvm::None;
+
+    auto VWT = readValueWitnessTable(MetadataAddress);
+    if (!VWT)
+      return llvm::None;
+
+    // Inline representation (the value fits in the existential container).
+    // So, the value starts at the first word of the container.
+    if (VWT->isValueInline())
+      return llvm::Optional<std::pair<RemoteAddress, RemoteAddress>>(
+          {RemoteAddress(MetadataAddress), ExistentialAddress});
+
+    // Non-inline (box'ed) representation.
+    // The first word of the container stores the address to the box.
+    StoredPointer BoxAddress;
+    if (!Reader->readInteger(ExistentialAddress, &BoxAddress))
+      return llvm::None;
+
+    auto AlignmentMask = VWT->getAlignmentMask();
+    auto Offset = (sizeof(HeapObject) + AlignmentMask) & ~AlignmentMask;
+    auto StartOfValue = BoxAddress + Offset;
+    return llvm::Optional<std::pair<RemoteAddress, RemoteAddress>>(
+        {RemoteAddress(MetadataAddress), RemoteAddress(StartOfValue)});
+  }
+
   /// Given a remote pointer to metadata, attempt to turn it into a type.
   BuiltType readTypeFromMetadata(StoredPointer MetadataAddress,
                                  bool skipArtificialSubclasses = false) {
diff --git a/include/swift/Strings.h b/include/swift/Strings.h
index 00d131b..aba6a2b 100644
--- a/include/swift/Strings.h
+++ b/include/swift/Strings.h
@@ -18,21 +18,6 @@
 
 namespace swift {
 
-/// The extension for serialized modules.
-constexpr static const char SERIALIZED_MODULE_EXTENSION[] = "swiftmodule";
-/// The extension for serialized documentation comments.
-constexpr static const char SERIALIZED_MODULE_DOC_EXTENSION[] = "swiftdoc";
-/// The extension for PCH files.
-constexpr static const char PCH_EXTENSION[] = "pch";
-/// The extension for replacement map files.
-constexpr static const char REMAP_EXTENSION[] = "remap";
-/// The extension for SIL files.
-constexpr static const char SIL_EXTENSION[] = "sil";
-/// The extension for SIB files.
-constexpr static const char SIB_EXTENSION[] = "sib";
-/// The extension for LLVM IR files.
-constexpr static const char LLVM_BC_EXTENSION[] = "bc";
-constexpr static const char LLVM_IR_EXTENSION[] = "ll";
 /// The name of the standard library, which is a reserved module name.
 constexpr static const char STDLIB_NAME[] = "Swift";
 /// The name of the Onone support library, which is a reserved module name.
diff --git a/lib/AST/GenericSignatureBuilder.cpp b/lib/AST/GenericSignatureBuilder.cpp
index 08f1ac6..2e39f03 100644
--- a/lib/AST/GenericSignatureBuilder.cpp
+++ b/lib/AST/GenericSignatureBuilder.cpp
@@ -7062,7 +7062,7 @@
                               EquivalenceClass *equivClass) {
   assert(equivClass->superclass && "No superclass constraint?");
 
-  // Resolve any this-far-unresolved dependent types.
+  // Resolve any thus-far-unresolved dependent types.
   Type resolvedSuperclass =
     resolveDependentMemberTypes(*this, equivClass->superclass);
 
@@ -7075,13 +7075,13 @@
 
         Type resolvedType =
           resolveDependentMemberTypes(*this, constraint.value);
-        return resolvedType->isEqual(equivClass->superclass);
+        return resolvedType->isEqual(resolvedSuperclass);
       },
       [&](const Constraint<Type> &constraint) {
         Type superclass = constraint.value;
 
         // If this class is a superclass of the "best"
-        if (superclass->isExactSuperclassOf(equivClass->superclass))
+        if (superclass->isExactSuperclassOf(resolvedSuperclass))
           return ConstraintRelation::Redundant;
 
         // Otherwise, it conflicts.
@@ -7091,7 +7091,7 @@
       diag::redundant_superclass_constraint,
       diag::superclass_redundancy_here);
 
-  // Resolve any this-far-unresolved dependent types.
+  // Record the resolved superclass type.
   equivClass->superclass = resolvedSuperclass;
 
   // If we have a concrete type, check it.
diff --git a/lib/Basic/CMakeLists.txt b/lib/Basic/CMakeLists.txt
index 7378dcc..18e1e04 100644
--- a/lib/Basic/CMakeLists.txt
+++ b/lib/Basic/CMakeLists.txt
@@ -72,6 +72,7 @@
   Edit.cpp
   EditorPlaceholder.cpp
   FileSystem.cpp
+  FileTypes.cpp
   JSONSerialization.cpp
   LangOptions.cpp
   LLVMContext.cpp
diff --git a/lib/Frontend/Types.cpp b/lib/Basic/FileTypes.cpp
similarity index 87%
rename from lib/Frontend/Types.cpp
rename to lib/Basic/FileTypes.cpp
index 4329a44..45afd51 100644
--- a/lib/Frontend/Types.cpp
+++ b/lib/Basic/FileTypes.cpp
@@ -1,8 +1,8 @@
-//===--- Types.cpp - Driver input & temporary type information ------------===//
+//===--- FileTypes.cpp - Input & output formats used by the tools ---------===//
 //
 // This source file is part of the Swift.org open source project
 //
-// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
 // Licensed under Apache License v2.0 with Runtime Library Exception
 //
 // See https://swift.org/LICENSE.txt for license information
@@ -10,8 +10,9 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "swift/Frontend/FileTypes.h"
+#include "swift/Basic/FileTypes.h"
 
+#include "swift/Strings.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/Support/ErrorHandling.h"
@@ -19,16 +20,18 @@
 using namespace swift;
 using namespace swift::file_types;
 
+namespace {
 struct TypeInfo {
   const char *Name;
   const char *Flags;
-  const char *TempSuffix;
+  const char *Extension;
 };
+} // end anonymous namespace
 
 static const TypeInfo TypeInfos[] = {
-#define TYPE(NAME, ID, TEMP_SUFFIX, FLAGS) \
-  { NAME, FLAGS, TEMP_SUFFIX },
-#include "swift/Frontend/Types.def"
+#define TYPE(NAME, ID, EXTENSION, FLAGS) \
+  { NAME, FLAGS, EXTENSION },
+#include "swift/Basic/FileTypes.def"
 };
 
 static const TypeInfo &getInfo(unsigned Id) {
@@ -38,8 +41,8 @@
 
 StringRef file_types::getTypeName(ID Id) { return getInfo(Id).Name; }
 
-StringRef file_types::getTypeTempSuffix(ID Id) {
-  return getInfo(Id).TempSuffix;
+StringRef file_types::getExtension(ID Id) {
+  return getInfo(Id).Extension;
 }
 
 ID file_types::lookupTypeForExtension(StringRef Ext) {
@@ -47,17 +50,17 @@
     return TY_INVALID;
   assert(Ext.front() == '.' && "not a file extension");
   return llvm::StringSwitch<file_types::ID>(Ext.drop_front())
-#define TYPE(NAME, ID, SUFFIX, FLAGS) \
-           .Case(SUFFIX, TY_##ID)
-#include "swift/Frontend/Types.def"
+#define TYPE(NAME, ID, EXTENSION, FLAGS) \
+           .Case(EXTENSION, TY_##ID)
+#include "swift/Basic/FileTypes.def"
       .Default(TY_INVALID);
 }
 
 ID file_types::lookupTypeForName(StringRef Name) {
   return llvm::StringSwitch<file_types::ID>(Name)
-#define TYPE(NAME, ID, SUFFIX, FLAGS) \
+#define TYPE(NAME, ID, EXTENSION, FLAGS) \
            .Case(NAME, TY_##ID)
-#include "swift/Frontend/Types.def"
+#include "swift/Basic/FileTypes.def"
       .Default(TY_INVALID);
 }
 
diff --git a/lib/ClangImporter/ClangImporter.cpp b/lib/ClangImporter/ClangImporter.cpp
index 6b57968..fb1bb84 100644
--- a/lib/ClangImporter/ClangImporter.cpp
+++ b/lib/ClangImporter/ClangImporter.cpp
@@ -36,7 +36,6 @@
 #include "swift/Parse/Lexer.h"
 #include "swift/Parse/Parser.h"
 #include "swift/Config.h"
-#include "swift/Strings.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Mangle.h"
 #include "clang/Basic/CharInfo.h"
@@ -419,7 +418,7 @@
   auto languageVersion = ctx.LangOpts.EffectiveLanguageVersion;
 
   if (llvm::sys::path::extension(importerOpts.BridgingHeader)
-          .endswith(PCH_EXTENSION)) {
+          .endswith(file_types::getExtension(file_types::TY_PCH))) {
     invocationArgStrs.insert(invocationArgStrs.end(), {
         "-include-pch", importerOpts.BridgingHeader
     });
@@ -788,7 +787,7 @@
 ClangImporter::getPCHFilename(const ClangImporterOptions &ImporterOptions,
                               StringRef SwiftPCHHash, bool &isExplicit) {
   if (llvm::sys::path::extension(ImporterOptions.BridgingHeader)
-        .endswith(PCH_EXTENSION)) {
+        .endswith(file_types::getExtension(file_types::TY_PCH))) {
     isExplicit = true;
     return ImporterOptions.BridgingHeader;
   }
@@ -879,8 +878,8 @@
   for (auto &argStr : invocationArgStrs)
     invocationArgs.push_back(argStr.c_str());
 
-  if (llvm::sys::path::extension(importerOpts.BridgingHeader).endswith(
-        PCH_EXTENSION)) {
+  if (llvm::sys::path::extension(importerOpts.BridgingHeader)
+        .endswith(file_types::getExtension(file_types::TY_PCH))) {
     importer->Impl.setSinglePCHImport(importerOpts.BridgingHeader);
     importer->Impl.IsReadingBridgingPCH = true;
     if (tracker) {
@@ -1289,7 +1288,8 @@
                                          SourceLoc diagLoc,
                                          bool trackParsedSymbols,
                                          bool implicitImport) {
-  if (llvm::sys::path::extension(header).endswith(PCH_EXTENSION)) {
+  if (llvm::sys::path::extension(header)
+        .endswith(file_types::getExtension(file_types::TY_PCH))) {
     Impl.ImportedHeaderOwners.push_back(adapter);
     // We already imported this with -include-pch above, so we should have
     // collected a bunch of PCH-encoded module imports that we just need to
diff --git a/lib/ClangImporter/ImportName.cpp b/lib/ClangImporter/ImportName.cpp
index 4d602a3..9ac0415 100644
--- a/lib/ClangImporter/ImportName.cpp
+++ b/lib/ClangImporter/ImportName.cpp
@@ -682,9 +682,9 @@
   auto attr = decl->getAttr<clang::SwiftNameAttr>();
   if (!attr) return nullptr;
 
-  // API notes produce implicit attributes; ignore them because they weren't
-  // used for naming in Swift 2.
-  if (attr->isImplicit()) return nullptr;
+  // API notes produce attributes with no source location; ignore them because
+  // they weren't used for naming in Swift 2.
+  if (attr->getLocation().isInvalid()) return nullptr;
 
   // Hardcode certain kinds of explicitly-written Swift names that were
   // permitted and used in Swift 2. All others are ignored, so that we are
diff --git a/lib/ClangImporter/ImporterImpl.h b/lib/ClangImporter/ImporterImpl.h
index e205b4a..d9d4745 100644
--- a/lib/ClangImporter/ImporterImpl.h
+++ b/lib/ClangImporter/ImporterImpl.h
@@ -28,8 +28,8 @@
 #include "swift/AST/Module.h"
 #include "swift/AST/Type.h"
 #include "swift/AST/ForeignErrorConvention.h"
+#include "swift/Basic/FileTypes.h"
 #include "swift/Basic/StringExtras.h"
-#include "swift/Strings.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DeclVisitor.h"
 #include "clang/Basic/IdentifierTable.h"
@@ -1360,7 +1360,7 @@
   void setSinglePCHImport(Optional<std::string> PCHFilename) {
     if (PCHFilename.hasValue()) {
       assert(llvm::sys::path::extension(PCHFilename.getValue())
-                 .endswith(PCH_EXTENSION) &&
+                 .endswith(file_types::getExtension(file_types::TY_PCH)) &&
              "Single PCH imported filename doesn't have .pch extension!");
     }
     SinglePCHImport = PCHFilename;
diff --git a/lib/Driver/Driver.cpp b/lib/Driver/Driver.cpp
index 341065c..0a99f9e 100644
--- a/lib/Driver/Driver.cpp
+++ b/lib/Driver/Driver.cpp
@@ -724,7 +724,7 @@
   if (Inputs.size() == 1) {
     InputName = Inputs[0].second->getSpelling();
   }
-  StringRef OutputType = file_types::getTypeTempSuffix(OI.CompilerOutputType);
+  StringRef OutputType = file_types::getExtension(OI.CompilerOutputType);
   return llvm::make_unique<UnifiedStatsReporter>("swift-driver",
                                                  OI.ModuleName,
                                                  InputName,
@@ -2019,7 +2019,7 @@
 static Optional<StringRef> getOutputFilenameFromPathArgOrAsTopLevel(
     const OutputInfo &OI, const llvm::opt::DerivedArgList &Args,
     llvm::opt::OptSpecifier PathArg, file_types::ID ExpectedOutputType,
-    bool TreatAsTopLevelOutput, StringRef workingDirectory, StringRef ext,
+    bool TreatAsTopLevelOutput, StringRef workingDirectory,
     llvm::SmallString<128> &Buffer) {
   if (const Arg *A = Args.getLastArg(PathArg))
     return StringRef(A->getValue());
@@ -2033,13 +2033,17 @@
       Buffer = A->getValue();
       llvm::sys::path::remove_filename(Buffer);
       llvm::sys::path::append(Buffer, OI.ModuleName);
-      llvm::sys::path::replace_extension(Buffer, ext);
+      llvm::sys::path::replace_extension(
+          Buffer, file_types::getExtension(ExpectedOutputType));
       return Buffer.str();
     }
 
     // A top-level output wasn't specified, so just output to
     // <ModuleName>.<ext>.
-    formFilenameFromBaseAndExt(OI.ModuleName, ext, workingDirectory, Buffer);
+    formFilenameFromBaseAndExt(OI.ModuleName,
+                               file_types::getExtension(ExpectedOutputType),
+                               workingDirectory,
+                               Buffer);
     return Buffer.str();
   }
 
@@ -2054,7 +2058,7 @@
   // We should output to a temporary file, since we're not at the top level
   // (or are generating a bridging PCH, which is currently always a temp).
   StringRef Stem = llvm::sys::path::stem(BaseName);
-  StringRef Suffix = file_types::getTypeTempSuffix(JA->getType());
+  StringRef Suffix = file_types::getExtension(JA->getType());
   std::error_code EC = llvm::sys::fs::createTemporaryFile(Stem, Suffix, Buffer);
   if (EC) {
     Diags.diagnose(SourceLoc(), diag::error_unable_to_make_temporary_file,
@@ -2118,8 +2122,7 @@
   if (isa<MergeModuleJobAction>(JA)) {
     auto optFilename = getOutputFilenameFromPathArgOrAsTopLevel(
         OI, Args, options::OPT_emit_module_path, file_types::TY_SwiftModuleFile,
-        OI.ShouldTreatModuleAsTopLevelOutput, workingDirectory,
-        SERIALIZED_MODULE_EXTENSION, Buffer);
+        OI.ShouldTreatModuleAsTopLevelOutput, workingDirectory, Buffer);
     if (optFilename)
       return *optFilename;
   }
@@ -2128,7 +2131,7 @@
   if (isa<GenerateDSYMJobAction>(JA)) {
     Buffer = PrimaryInput;
     Buffer.push_back('.');
-    Buffer.append(file_types::getTypeTempSuffix(JA->getType()));
+    Buffer.append(file_types::getExtension(JA->getType()));
     return Buffer.str();
   }
 
@@ -2171,7 +2174,7 @@
     return Buffer.str();
   }
 
-  StringRef Suffix = file_types::getTypeTempSuffix(JA->getType());
+  StringRef Suffix = file_types::getExtension(JA->getType());
   assert(Suffix.data() &&
          "All types used for output should have a suffix.");
 
@@ -2241,7 +2244,7 @@
 
     bool isTempFile = C.isTemporaryFile(path);
     llvm::sys::path::replace_extension(
-        path, file_types::getTypeTempSuffix(outputType));
+        path, file_types::getExtension(outputType));
     output.setAdditionalOutputForType(outputType, path);
     if (isTempFile)
       C.addTemporaryFile(path);
@@ -2264,7 +2267,7 @@
   StringRef headerPath = output.getBaseInput(JA->getInputIndex());
   StringRef stem = llvm::sys::path::stem(headerPath);
   StringRef suffix =
-      file_types::getTypeTempSuffix(file_types::TY_SerializedDiagnostics);
+      file_types::getExtension(file_types::TY_SerializedDiagnostics);
   SmallString<256> outPathBuf;
 
   if (const Arg *A = C.getArgs().getLastArg(options::OPT_emit_module_path)) {
@@ -2627,17 +2630,16 @@
   }
 
   const Arg *A = C.getArgs().getLastArg(options::OPT_emit_module_path);
+  using file_types::TY_SwiftModuleFile;
 
   if (!OFMModuleOutputPath.empty()) {
     // Prefer a path from the OutputMap.
-    Output->setAdditionalOutputForType(file_types::TY_SwiftModuleFile,
-                                       OFMModuleOutputPath);
+    Output->setAdditionalOutputForType(TY_SwiftModuleFile, OFMModuleOutputPath);
   } else if (A && OI.CompilerMode == OutputInfo::Mode::SingleCompile) {
     // We're performing a single compilation (and thus no merge module step),
     // so prefer to use -emit-module-path, if present.
-    Output->setAdditionalOutputForType(file_types::TY_SwiftModuleFile,
-                                       A->getValue());
-  } else if (Output->getPrimaryOutputType() == file_types::TY_SwiftModuleFile) {
+    Output->setAdditionalOutputForType(TY_SwiftModuleFile, A->getValue());
+  } else if (Output->getPrimaryOutputType() == TY_SwiftModuleFile) {
     // If the primary type is already a module type, we're out of
     // options for overriding the primary name choice: stop now.
     assert(!Output->getPrimaryOutputFilename().empty());
@@ -2647,29 +2649,28 @@
     // We're performing a single compile and don't have -emit-module-path,
     // but have been told to treat the module as a top-level output.
     // Determine an appropriate path.
+    llvm::SmallString<128> Path;
     if (const Arg *A = C.getArgs().getLastArg(options::OPT_o)) {
       // Put the module next to the top-level output.
-      llvm::SmallString<128> Path(A->getValue());
+      Path = A->getValue();
       llvm::sys::path::remove_filename(Path);
-      llvm::sys::path::append(Path, OI.ModuleName);
-      llvm::sys::path::replace_extension(Path, SERIALIZED_MODULE_EXTENSION);
-      Output->setAdditionalOutputForType(file_types::TY_SwiftModuleFile, Path);
     } else {
       // A top-level output wasn't specified, so just output to
-      // <ModuleName>.swiftmodule.
-      llvm::SmallString<128> Path(OI.ModuleName);
-      llvm::sys::path::replace_extension(Path, SERIALIZED_MODULE_EXTENSION);
-      Output->setAdditionalOutputForType(file_types::TY_SwiftModuleFile, Path);
+      // <ModuleName>.swiftmodule in the current directory.
     }
+    llvm::sys::path::append(Path, OI.ModuleName);
+    llvm::sys::path::replace_extension(
+        Path, file_types::getExtension(TY_SwiftModuleFile));
+    Output->setAdditionalOutputForType(TY_SwiftModuleFile, Path);
   } else if (Output->getPrimaryOutputType() != file_types::TY_Nothing) {
     // We're only generating the module as an intermediate, so put it next
     // to the primary output of the compile command.
     llvm::SmallString<128> Path(Output->getPrimaryOutputFilenames()[0]);
     assert(!Path.empty());
     bool isTempFile = C.isTemporaryFile(Path);
-    llvm::sys::path::replace_extension(Path, SERIALIZED_MODULE_EXTENSION);
-    Output->setAdditionalOutputForType(file_types::ID::TY_SwiftModuleFile,
-                                       Path);
+    llvm::sys::path::replace_extension(
+        Path, file_types::getExtension(TY_SwiftModuleFile));
+    Output->setAdditionalOutputForType(TY_SwiftModuleFile, Path);
     if (isTempFile)
       C.addTemporaryFile(Path);
   }
@@ -2698,7 +2699,8 @@
     llvm::SmallString<128> Path(
         Output->getAnyOutputForType(file_types::TY_SwiftModuleFile));
     bool isTempFile = C.isTemporaryFile(Path);
-    llvm::sys::path::replace_extension(Path, SERIALIZED_MODULE_DOC_EXTENSION);
+    llvm::sys::path::replace_extension(
+        Path, file_types::getExtension(file_types::TY_SwiftModuleDocFile));
     Output->setAdditionalOutputForType(file_types::TY_SwiftModuleDocFile, Path);
     if (isTempFile)
       C.addTemporaryFile(Path);
@@ -2724,7 +2726,8 @@
   } else {
     llvm::SmallString<128> Path(Output->getPrimaryOutputFilenames()[0]);
     bool isTempFile = C.isTemporaryFile(Path);
-    llvm::sys::path::replace_extension(Path, "remap");
+    llvm::sys::path::replace_extension(Path,
+        file_types::getExtension(file_types::ID::TY_Remapping));
     Output->setAdditionalOutputForType(file_types::ID::TY_Remapping, Path);
     if (isTempFile)
       C.addTemporaryFile(Path);
@@ -2798,7 +2801,7 @@
       filename = *getOutputFilenameFromPathArgOrAsTopLevel(
           OI, C.getArgs(), options::OPT_emit_loaded_module_trace_path,
           file_types::TY_ModuleTrace,
-          /*TreatAsTopLevelOutput=*/true, workingDirectory, "trace.json", Buf);
+          /*TreatAsTopLevelOutput=*/true, workingDirectory, Buf);
     }
 
     Output->setAdditionalOutputForType(file_types::TY_ModuleTrace, filename);
@@ -2828,7 +2831,7 @@
     auto filename = *getOutputFilenameFromPathArgOrAsTopLevel(
         OI, C.getArgs(), options::OPT_save_optimization_record_path,
         file_types::TY_OptRecord, /*TreatAsTopLevelOutput=*/true,
-        workingDirectory, "opt.yaml", Buf);
+        workingDirectory, Buf);
 
     Output->setAdditionalOutputForType(file_types::TY_OptRecord, filename);
   } else
diff --git a/lib/Driver/ParseableOutput.cpp b/lib/Driver/ParseableOutput.cpp
index b626787..7c6b4fb 100644
--- a/lib/Driver/ParseableOutput.cpp
+++ b/lib/Driver/ParseableOutput.cpp
@@ -12,11 +12,11 @@
 
 #include "swift/Driver/ParseableOutput.h"
 
+#include "swift/Basic/FileTypes.h"
 #include "swift/Basic/JSONSerialization.h"
 #include "swift/Basic/TaskQueue.h"
 #include "swift/Driver/Action.h"
 #include "swift/Driver/Job.h"
-#include "swift/Frontend/FileTypes.h"
 #include "llvm/Option/Arg.h"
 #include "llvm/Support/raw_ostream.h"
 
diff --git a/lib/Driver/PrettyStackTrace.cpp b/lib/Driver/PrettyStackTrace.cpp
index 1bfd8ad..a6765fa 100644
--- a/lib/Driver/PrettyStackTrace.cpp
+++ b/lib/Driver/PrettyStackTrace.cpp
@@ -1,4 +1,4 @@
-//===--- PrettyStackTrace.cpp - Defines Driver crash prettifiers -------------===//
+//===--- PrettyStackTrace.cpp - Defines Driver crash prettifiers ----------===//
 //
 // This source file is part of the Swift.org open source project
 //
@@ -11,9 +11,10 @@
 //===----------------------------------------------------------------------===//
 
 #include "swift/Driver/PrettyStackTrace.h"
+
+#include "swift/Basic/FileTypes.h"
 #include "swift/Driver/Action.h"
 #include "swift/Driver/Job.h"
-#include "swift/Frontend/FileTypes.h"
 #include "llvm/Option/Arg.h"
 #include "llvm/Support/raw_ostream.h"
 
diff --git a/lib/Frontend/ArgsToFrontendOutputsConverter.cpp b/lib/Frontend/ArgsToFrontendOutputsConverter.cpp
index 4364b25..610c70b 100644
--- a/lib/Frontend/ArgsToFrontendOutputsConverter.cpp
+++ b/lib/Frontend/ArgsToFrontendOutputsConverter.cpp
@@ -117,11 +117,14 @@
     return None;
   }
 
+  const file_types::ID outputType =
+      FrontendOptions::formatForPrincipalOutputFileForAction(requestedAction);
+
   return OutputFilesComputer(
       diags, inputsAndOutputs, std::move(outputFileArguments),
       outputDirectoryArgument, firstInput, requestedAction,
       args.getLastArg(options::OPT_module_name),
-      FrontendOptions::suffixForPrincipalOutputFileForAction(requestedAction),
+      file_types::getExtension(outputType),
       FrontendOptions::doesActionProduceTextualOutput(requestedAction));
 }
 
@@ -354,36 +357,41 @@
   using namespace options;
 
   auto dependenciesFilePath = determineSupplementaryOutputFilename(
-      OPT_emit_dependencies, pathsFromArguments.DependenciesFilePath, "d", "",
+      OPT_emit_dependencies, pathsFromArguments.DependenciesFilePath,
+      file_types::TY_Dependencies, "",
       defaultSupplementaryOutputPathExcludingExtension);
 
   auto referenceDependenciesFilePath = determineSupplementaryOutputFilename(
       OPT_emit_reference_dependencies,
-      pathsFromArguments.ReferenceDependenciesFilePath, "swiftdeps", "",
+      pathsFromArguments.ReferenceDependenciesFilePath,
+      file_types::TY_SwiftDeps, "",
       defaultSupplementaryOutputPathExcludingExtension);
 
   auto serializedDiagnosticsPath = determineSupplementaryOutputFilename(
       OPT_serialize_diagnostics, pathsFromArguments.SerializedDiagnosticsPath,
-      "dia", "", defaultSupplementaryOutputPathExcludingExtension);
+      file_types::TY_SerializedDiagnostics, "",
+      defaultSupplementaryOutputPathExcludingExtension);
 
   // There is no non-path form of -emit-fixits-path
   auto fixItsOutputPath = pathsFromArguments.FixItsOutputPath;
 
   auto objcHeaderOutputPath = determineSupplementaryOutputFilename(
-      OPT_emit_objc_header, pathsFromArguments.ObjCHeaderOutputPath, "h", "",
+      OPT_emit_objc_header, pathsFromArguments.ObjCHeaderOutputPath,
+      file_types::TY_ObjCHeader, "",
       defaultSupplementaryOutputPathExcludingExtension);
 
   auto loadedModuleTracePath = determineSupplementaryOutputFilename(
       OPT_emit_loaded_module_trace, pathsFromArguments.LoadedModuleTracePath,
-      "trace.json", "", defaultSupplementaryOutputPathExcludingExtension);
+      file_types::TY_ModuleTrace, "",
+      defaultSupplementaryOutputPathExcludingExtension);
 
   auto tbdPath = determineSupplementaryOutputFilename(
-      OPT_emit_tbd, pathsFromArguments.TBDPath, "tbd", "",
+      OPT_emit_tbd, pathsFromArguments.TBDPath, file_types::TY_TBD, "",
       defaultSupplementaryOutputPathExcludingExtension);
 
   auto moduleDocOutputPath = determineSupplementaryOutputFilename(
       OPT_emit_module_doc, pathsFromArguments.ModuleDocOutputPath,
-      SERIALIZED_MODULE_DOC_EXTENSION, "",
+      file_types::TY_SwiftModuleDocFile, "",
       defaultSupplementaryOutputPathExcludingExtension);
 
   // There is no non-path form of -emit-interface-path
@@ -396,8 +404,8 @@
                              mainOutputIfUsableForModule);
 
   auto moduleOutputPath = determineSupplementaryOutputFilename(
-      emitModuleOption, pathsFromArguments.ModuleOutputPath, moduleExtension,
-      mainOutputIfUsableForModule,
+      emitModuleOption, pathsFromArguments.ModuleOutputPath,
+      file_types::TY_SwiftModuleFile, mainOutputIfUsableForModule,
       defaultSupplementaryOutputPathExcludingExtension);
 
   SupplementaryOutputPaths sop;
@@ -429,7 +437,7 @@
 
 std::string
 SupplementaryOutputPathsComputer::determineSupplementaryOutputFilename(
-    options::ID emitOpt, std::string pathFromArguments, StringRef extension,
+    options::ID emitOpt, std::string pathFromArguments, file_types::ID type,
     StringRef mainOutputIfUsable,
     StringRef defaultSupplementaryOutputPathExcludingExtension) const {
 
@@ -444,7 +452,7 @@
   }
 
   llvm::SmallString<128> path(defaultSupplementaryOutputPathExcludingExtension);
-  llvm::sys::path::replace_extension(path, extension);
+  llvm::sys::path::replace_extension(path, file_types::getExtension(type));
   return path.str().str();
 };
 
@@ -464,7 +472,8 @@
       RequestedAction == FrontendOptions::ActionType::MergeModules ||
       RequestedAction == FrontendOptions::ActionType::EmitModuleOnly || isSIB;
 
-  extension = isSIB ? SIB_EXTENSION : SERIALIZED_MODULE_EXTENSION;
+  extension = file_types::getExtension(
+      isSIB ? file_types::TY_SIB : file_types::TY_SwiftModuleFile);
 
   mainOutputIfUsable =
       canUseMainOutputForModule && !OutputFiles.empty() ? OutputFiles[0] : "";
diff --git a/lib/Frontend/ArgsToFrontendOutputsConverter.h b/lib/Frontend/ArgsToFrontendOutputsConverter.h
index b99a8ab..bdb9997 100644
--- a/lib/Frontend/ArgsToFrontendOutputsConverter.h
+++ b/lib/Frontend/ArgsToFrontendOutputsConverter.h
@@ -164,7 +164,7 @@
   /// \return empty string if no output file.
   std::string determineSupplementaryOutputFilename(
       options::ID emitOpt, std::string pathFromArgumentsOrFilelists,
-      StringRef extension, StringRef mainOutputIfUsable,
+      file_types::ID type, StringRef mainOutputIfUsable,
       StringRef defaultSupplementaryOutputPathExcludingExtension) const;
 
   void deriveModulePathParameters(options::ID &emitOption,
diff --git a/lib/Frontend/CMakeLists.txt b/lib/Frontend/CMakeLists.txt
index e71cf0a..cd38309 100644
--- a/lib/Frontend/CMakeLists.txt
+++ b/lib/Frontend/CMakeLists.txt
@@ -10,7 +10,6 @@
   OutputFileMap.cpp
   PrintingDiagnosticConsumer.cpp
   SerializedDiagnosticConsumer.cpp
-  Types.cpp
   DEPENDS
     SwiftOptions
   LINK_LIBRARIES
diff --git a/lib/Frontend/Frontend.cpp b/lib/Frontend/Frontend.cpp
index ed4d885..cafd248 100644
--- a/lib/Frontend/Frontend.cpp
+++ b/lib/Frontend/Frontend.cpp
@@ -20,6 +20,7 @@
 #include "swift/AST/DiagnosticsFrontend.h"
 #include "swift/AST/DiagnosticsSema.h"
 #include "swift/AST/Module.h"
+#include "swift/Basic/FileTypes.h"
 #include "swift/Basic/SourceManager.h"
 #include "swift/Basic/Statistic.h"
 #include "swift/Parse/DelayedParsingCallbacks.h"
@@ -345,8 +346,9 @@
 Optional<std::unique_ptr<llvm::MemoryBuffer>>
 CompilerInstance::openModuleDoc(const InputFile &input) {
   llvm::SmallString<128> moduleDocFilePath(input.file());
-  llvm::sys::path::replace_extension(moduleDocFilePath,
-                                     SERIALIZED_MODULE_DOC_EXTENSION);
+  llvm::sys::path::replace_extension(
+      moduleDocFilePath,
+      file_types::getExtension(file_types::TY_SwiftModuleDocFile));
   using FileOrError = llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>;
   FileOrError moduleDocFileOrErr =
       llvm::MemoryBuffer::getFileOrSTDIN(moduleDocFilePath);
diff --git a/lib/Frontend/FrontendInputsAndOutputs.cpp b/lib/Frontend/FrontendInputsAndOutputs.cpp
index 152d501..35dcc48 100644
--- a/lib/Frontend/FrontendInputsAndOutputs.cpp
+++ b/lib/Frontend/FrontendInputsAndOutputs.cpp
@@ -13,6 +13,7 @@
 #include "swift/Frontend/FrontendInputsAndOutputs.h"
 
 #include "swift/AST/DiagnosticsFrontend.h"
+#include "swift/Basic/FileTypes.h"
 #include "swift/Basic/PrimarySpecificPaths.h"
 #include "swift/Frontend/FrontendOptions.h"
 #include "swift/Option/Options.h"
@@ -155,9 +156,14 @@
 
 bool FrontendInputsAndOutputs::shouldTreatAsLLVM() const {
   if (hasSingleInput()) {
-    StringRef Input(getFilenameOfFirstInput());
-    return llvm::sys::path::extension(Input).endswith(LLVM_BC_EXTENSION) ||
-           llvm::sys::path::extension(Input).endswith(LLVM_IR_EXTENSION);
+    StringRef InputExt = llvm::sys::path::extension(getFilenameOfFirstInput());
+    switch (file_types::lookupTypeForExtension(InputExt)) {
+    case file_types::TY_LLVM_BC:
+    case file_types::TY_LLVM_IR:
+      return true;
+    default:
+      return false;
+    }
   }
   return false;
 }
@@ -166,12 +172,13 @@
   if (hasSingleInput()) {
     // If we have exactly one input filename, and its extension is "sil",
     // treat the input as SIL.
-    const std::string &Input(getFilenameOfFirstInput());
-    return llvm::sys::path::extension(Input).endswith(SIL_EXTENSION);
+    StringRef extension = llvm::sys::path::extension(getFilenameOfFirstInput());
+    return file_types::lookupTypeForExtension(extension) == file_types::TY_SIL;
   }
   // If we have one primary input and it's a filename with extension "sil",
   // treat the input as SIL.
-  unsigned silPrimaryCount = numberOfPrimaryInputsEndingWith(SIL_EXTENSION);
+  const unsigned silPrimaryCount = numberOfPrimaryInputsEndingWith(
+      file_types::getExtension(file_types::TY_SIL));
   if (silPrimaryCount == 0)
     return false;
   if (silPrimaryCount == primaryInputCount()) {
@@ -186,7 +193,8 @@
   for (const InputFile &input : AllInputs) {
     if (input.isPrimary())
       continue;
-    if (!llvm::sys::path::extension(input.file()).endswith(SIB_EXTENSION)) {
+    StringRef extension = llvm::sys::path::extension(input.file());
+    if (file_types::lookupTypeForExtension(extension) != file_types::TY_SIB) {
       return false;
     }
   }
diff --git a/lib/Frontend/FrontendOptions.cpp b/lib/Frontend/FrontendOptions.cpp
index d89a7b2..6218122 100644
--- a/lib/Frontend/FrontendOptions.cpp
+++ b/lib/Frontend/FrontendOptions.cpp
@@ -2,7 +2,7 @@
 //
 // This source file is part of the Swift.org open source project
 //
-// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
 // Licensed under Apache License v2.0 with Runtime Library Exception
 //
 // See https://swift.org/LICENSE.txt for license information
@@ -130,11 +130,13 @@
   }
 }
 
-StringRef
-FrontendOptions::suffixForPrincipalOutputFileForAction(ActionType action) {
+file_types::ID
+FrontendOptions::formatForPrincipalOutputFileForAction(ActionType action) {
+  using namespace file_types;
+
   switch (action) {
   case ActionType::NoneAction:
-    return StringRef();
+    return TY_Nothing;
 
   case ActionType::Parse:
   case ActionType::ResolveImports:
@@ -146,42 +148,46 @@
   case ActionType::PrintAST:
   case ActionType::DumpScopeMaps:
   case ActionType::DumpTypeRefinementContexts:
-    return StringRef();
+    return TY_Nothing;
 
   case ActionType::EmitPCH:
-    return PCH_EXTENSION;
+    return TY_PCH;
 
   case ActionType::EmitSILGen:
+    return TY_RawSIL;
+
   case ActionType::EmitSIL:
-    return SIL_EXTENSION;
+    return TY_SIL;
 
   case ActionType::EmitSIBGen:
+    return TY_RawSIB;
+
   case ActionType::EmitSIB:
-    return SIB_EXTENSION;
+    return TY_SIB;
 
   case ActionType::MergeModules:
   case ActionType::EmitModuleOnly:
-    return SERIALIZED_MODULE_EXTENSION;
+    return TY_SwiftModuleFile;
 
   case ActionType::Immediate:
   case ActionType::REPL:
     // These modes have no frontend-generated output.
-    return StringRef();
+    return TY_Nothing;
 
   case ActionType::EmitAssembly:
-    return "s";
+    return TY_Assembly;
 
   case ActionType::EmitIR:
-    return "ll";
+    return TY_LLVM_IR;
 
   case ActionType::EmitBC:
-    return "bc";
+    return TY_LLVM_BC;
 
   case ActionType::EmitObject:
-    return "o";
+    return TY_Object;
 
   case ActionType::EmitImportedModules:
-    return "importedmodules";
+    return TY_ImportedModules;
   }
 }
 
diff --git a/lib/FrontendTool/FrontendTool.cpp b/lib/FrontendTool/FrontendTool.cpp
index 676be29..0791676 100644
--- a/lib/FrontendTool/FrontendTool.cpp
+++ b/lib/FrontendTool/FrontendTool.cpp
@@ -25,7 +25,6 @@
 #include "ReferenceDependencies.h"
 #include "TBD.h"
 
-#include "swift/Strings.h"
 #include "swift/Subsystems.h"
 #include "swift/AST/ASTScope.h"
 #include "swift/AST/DiagnosticsFrontend.h"
@@ -225,8 +224,8 @@
     // Decide if this is a swiftmodule based on the extension of the raw
     // dependency path, as the true file may have a different one.
     auto ext = llvm::sys::path::extension(dep);
-    if (ext.startswith(".") &&
-        ext.drop_front() == SERIALIZED_MODULE_EXTENSION) {
+    if (file_types::lookupTypeForExtension(ext) ==
+          file_types::TY_SwiftModuleFile) {
       swiftModules.push_back(realPath);
     }
   }
diff --git a/lib/IDE/Refactoring.cpp b/lib/IDE/Refactoring.cpp
index 8ba981f..a42b1f8 100644
--- a/lib/IDE/Refactoring.cpp
+++ b/lib/IDE/Refactoring.cpp
@@ -2571,6 +2571,110 @@
   return false;
 }
 
+static void generateMemberwiseInit(SourceEditConsumer &EditConsumer,
+                            SourceManager &SM,
+                            SmallVectorImpl<std::string>& memberNameVector,
+                            SmallVectorImpl<std::string>& memberTypeVector,
+                            SourceLoc targetLocation) {
+  
+  assert(!memberTypeVector.empty());
+  assert(memberTypeVector.size() == memberNameVector.size());
+  
+  EditConsumer.accept(SM, targetLocation, "\ninternal init(");
+  
+  for (size_t i = 0, n = memberTypeVector.size(); i < n ; i++) {
+    EditConsumer.accept(SM, targetLocation, memberNameVector[i] + ": " +
+                        memberTypeVector[i]);
+    
+    if (i != memberTypeVector.size() - 1) {
+      EditConsumer.accept(SM, targetLocation, ", ");
+    }
+  }
+  
+  EditConsumer.accept(SM, targetLocation, ") {\n");
+  
+  for (auto varName: memberNameVector) {
+    EditConsumer.accept(SM, targetLocation,
+                        "self." + varName + " = " + varName + "\n");
+  }
+  
+  EditConsumer.accept(SM, targetLocation, "}\n");
+}
+  
+static SourceLoc collectMembersForInit(ResolvedCursorInfo CursorInfo,
+                           SmallVectorImpl<std::string>& memberNameVector,
+                           SmallVectorImpl<std::string>& memberTypeVector) {
+  
+  if (!CursorInfo.ValueD)
+    return SourceLoc();
+  
+  ClassDecl *classDecl = dyn_cast<ClassDecl>(CursorInfo.ValueD);
+  if (!classDecl || classDecl->getStoredProperties().empty() ||
+      CursorInfo.IsRef) {
+    return SourceLoc();
+  }
+  
+  SourceLoc bracesStart = classDecl->getBraces().Start;
+  if (!bracesStart.isValid())
+    return SourceLoc();
+  
+  SourceLoc targetLocation = bracesStart.getAdvancedLoc(1);
+  if (!targetLocation.isValid())
+    return SourceLoc();
+  
+  for (auto varDecl : classDecl->getStoredProperties()) {
+    auto parentPatternBinding = varDecl->getParentPatternBinding();
+    if (!parentPatternBinding)
+      continue;
+    
+    auto varDeclIndex =
+      parentPatternBinding->getPatternEntryIndexForVarDecl(varDecl);
+    
+    if (auto init = varDecl->getParentPatternBinding()->getInit(varDeclIndex)) {
+      if (init->getStartLoc().isValid())
+        continue;
+    }
+    
+    StringRef memberName = varDecl->getName().str();
+    memberNameVector.push_back(memberName.str());
+    
+    std::string memberType = varDecl->getType().getString();
+    memberTypeVector.push_back(memberType);
+  }
+  
+  if (memberNameVector.empty() || memberTypeVector.empty()) {
+    return SourceLoc();
+  }
+  
+  return targetLocation;
+}
+
+bool RefactoringActionMemberwiseInitLocalRefactoring::
+isApplicable(ResolvedCursorInfo Tok, DiagnosticEngine &Diag) {
+  
+  SmallVector<std::string, 8> memberNameVector;
+  SmallVector<std::string, 8> memberTypeVector;
+  
+  return collectMembersForInit(Tok, memberNameVector,
+                               memberTypeVector).isValid();
+}
+    
+bool RefactoringActionMemberwiseInitLocalRefactoring::performChange() {
+  
+  SmallVector<std::string, 8> memberNameVector;
+  SmallVector<std::string, 8> memberTypeVector;
+  
+  SourceLoc targetLocation = collectMembersForInit(CursorInfo, memberNameVector,
+                                         memberTypeVector);
+  if (targetLocation.isInvalid())
+    return true;
+  
+  generateMemberwiseInit(EditConsumer, SM, memberNameVector,
+                         memberTypeVector, targetLocation);
+  
+  return false;
+}
+
 static CharSourceRange
   findSourceRangeToWrapInCatch(ResolvedCursorInfo CursorInfo,
                                SourceFile *TheFile,
diff --git a/lib/IRGen/GenMeta.cpp b/lib/IRGen/GenMeta.cpp
index 25edcd9..84c8b9b 100644
--- a/lib/IRGen/GenMeta.cpp
+++ b/lib/IRGen/GenMeta.cpp
@@ -822,20 +822,25 @@
       IGM.setTrueConstGlobal(var);
       return var;
     }
+
+    void setCommonFlags(TypeContextDescriptorFlags &flags) {
+      setClangImportedFlags(flags);
+      setMetadataInitializationKind(flags);
+    }
     
     /// Flags to indicate Clang-imported declarations so we mangle them
     /// consistently at runtime.
-    void getClangImportedFlags(TypeContextDescriptorFlags &flags) const {
+    void setClangImportedFlags(TypeContextDescriptorFlags &flags) {
       if (Type->getAttrs().getAttribute<ClangImporterSynthesizedTypeAttr>()) {
         flags.setIsSynthesizedRelatedEntity(true);
       }
       
       if (auto clangDecl = Mangle::ASTMangler::getClangDeclForMangling(Type)) {
         if (isa<clang::TagDecl>(clangDecl)) {
-          flags.setIsCTag(true);
+          flags.setImportNamespace(TypeContextDescriptorFlags::CTag);
         } else if (isa<clang::TypedefNameDecl>(clangDecl)
                    || isa<clang::ObjCCompatibleAliasDecl>(clangDecl)) {
-          flags.setIsCTypedef(true);
+          flags.setImportNamespace(TypeContextDescriptorFlags::CTypedef);
         }
       }
     }
@@ -859,9 +864,11 @@
       return HasInPlaceMetadataInitialization;
     }
 
-    void setHasInPlaceMetadataInitialization(TypeContextDescriptorFlags &flags){
-      flags.setHasInPlaceMetadataInitialization(
-                                              HasInPlaceMetadataInitialization);
+    void setMetadataInitializationKind(TypeContextDescriptorFlags &flags) {
+      if (HasInPlaceMetadataInitialization) {
+        flags.setMetadataInitialization(
+                     TypeContextDescriptorFlags::InPlaceMetadataInitialization);
+      }
     }
 
     void maybeAddInPlaceMetadataInitialization() {
@@ -1011,9 +1018,7 @@
       flags.setIsReflectable(
                             !IGM.shouldEmitOpaqueTypeMetadataRecord(getType()));
 
-      setHasInPlaceMetadataInitialization(flags);
-
-      getClangImportedFlags(flags);
+      setCommonFlags(flags);
       return flags.getOpaqueValue();
     }
   };
@@ -1071,9 +1076,7 @@
 
       flags.setIsReflectable(Strategy.isReflectable());
 
-      setHasInPlaceMetadataInitialization(flags);
-
-      getClangImportedFlags(flags);
+      setCommonFlags(flags);
       return flags.getOpaqueValue();
     }
   };
@@ -1130,6 +1133,8 @@
       // Classes are always reflectable.
       flags.setIsReflectable(true);
 
+      setCommonFlags(flags);
+
       if (!getType()->isForeign()) {
         if (MetadataLayout->areImmediateMembersNegative())
           flags.class_setAreImmediateMembersNegative(true);
@@ -1145,8 +1150,6 @@
         flags.class_setSuperclassReferenceKind(SuperClassRef->getKind());
       }
       
-      getClangImportedFlags(flags);
-      
       return flags.getOpaqueValue();
     }
     
diff --git a/lib/Sema/CSApply.cpp b/lib/Sema/CSApply.cpp
index f8b85c7..782b37a 100644
--- a/lib/Sema/CSApply.cpp
+++ b/lib/Sema/CSApply.cpp
@@ -7498,6 +7498,11 @@
     cs.setType(apply, fnType->getResult());
     apply->setIsSuper(isSuper);
 
+    // We need the layout of nominal types returned from a function call.
+    if (auto nominalResult = fnType->getResult()->getAnyNominal()) {
+      tc.requestNominalLayout(nominalResult);
+    }
+
     cs.setExprTypes(apply);
     Expr *result = tc.substituteInputSugarTypeForResult(apply);
     cs.cacheExprTypes(result);
@@ -7907,21 +7912,43 @@
 /// Emit the fixes computed as part of the solution, returning true if we were
 /// able to emit an error message, or false if none of the fixits worked out.
 bool ConstraintSystem::applySolutionFixes(Expr *E, const Solution &solution) {
-  bool diagnosed = false;
-  for (unsigned i = 0, e = solution.Fixes.size(); i != e; ++i)
-    diagnosed |= applySolutionFix(E, solution, i);
+  llvm::SmallDenseMap<Expr *,
+                      SmallVector<std::pair<Fix, ConstraintLocator *>, 4>>
+      fixesPerExpr;
 
+  for (const auto &fix : solution.Fixes)
+    fixesPerExpr[fix.second->getAnchor()].push_back(fix);
+
+  auto diagnoseExprFailures = [&](Expr *expr) -> bool {
+    auto fixes = fixesPerExpr.find(expr);
+    if (fixes == fixesPerExpr.end())
+      return false;
+
+    bool diagnosed = false;
+    for (auto &fix : fixes->second)
+      diagnosed |= applySolutionFix(expr, solution, fix);
+    return diagnosed;
+  };
+
+  bool diagnosed = false;
+  E->forEachChildExpr([&](Expr *subExpr) -> Expr * {
+    // Diagnose root expression at the end to
+    // preserve ordering.
+    if (subExpr != E)
+      diagnosed |= diagnoseExprFailures(subExpr);
+    return subExpr;
+  });
+
+  diagnosed |= diagnoseExprFailures(E);
   return diagnosed;
 }
 
-/// \brief Apply the specified Fix # to this solution, producing a fixit hint
-/// diagnostic for it and returning true.  If the fixit hint turned out to be
+/// \brief Apply the specified Fix to this solution, producing a fix-it hint
+/// diagnostic for it and returning true.  If the fix-it hint turned out to be
 /// bogus, this returns false and doesn't emit anything.
-bool ConstraintSystem::applySolutionFix(Expr *expr,
-                                        const Solution &solution,
-                                        unsigned fixNo) {
-  auto &fix = solution.Fixes[fixNo];
-  
+bool ConstraintSystem::applySolutionFix(
+    Expr *expr, const Solution &solution,
+    std::pair<Fix, ConstraintLocator *> &fix) {
   // Some fixes need more information from the locator.
   ConstraintLocator *locator = fix.second;
 
@@ -8098,6 +8125,13 @@
                 getASTContext().TheAnyType);
     return true;
   }
+
+  case FixKind::RelabelArguments: {
+    auto *call = cast<CallExpr>(locator->getAnchor());
+    return diagnoseArgumentLabelError(getASTContext(), call->getArg(),
+                                      fix.first.getArgumentLabels(*this),
+                                      isa<SubscriptExpr>(call->getFn()));
+  }
   }
 
   // FIXME: It would be really nice to emit a follow-up note showing where
diff --git a/lib/Sema/CSSimplify.cpp b/lib/Sema/CSSimplify.cpp
index d441bbe..910a09f 100644
--- a/lib/Sema/CSSimplify.cpp
+++ b/lib/Sema/CSSimplify.cpp
@@ -499,6 +499,15 @@
         auto fromArgIdx = boundArgIdx;
         auto toArgIdx = argIdx;
 
+        // If there is no re-ordering going on, and index is past
+        // the number of parameters, it could only mean that this
+        // is variadic parameter, so let's just move on.
+        if (fromArgIdx == toArgIdx && toArgIdx >= params.size()) {
+          assert(args[fromArgIdx].getLabel().empty());
+          argIdx++;
+          continue;
+        }
+
         // First let's double check if out-of-order argument is nothing
         // more than a simple label mismatch, because in situation where
         // one argument requires label and another one doesn't, but caller
@@ -692,6 +701,40 @@
   return std::make_tuple(nullptr, 0, argLabels, hasTrailingClosure);
 }
 
+class ArgumentFailureTracker : public MatchCallArgumentListener {
+  ConstraintSystem &CS;
+  ConstraintLocatorBuilder Locator;
+
+public:
+  ArgumentFailureTracker(ConstraintSystem &cs, ConstraintLocatorBuilder locator)
+    : CS(cs), Locator(locator) {}
+
+  bool missingLabel(unsigned paramIndex) override {
+    return !CS.shouldAttemptFixes();
+  }
+
+  bool extraneousLabel(unsigned paramIndex) override {
+    return !CS.shouldAttemptFixes();
+  }
+
+  bool incorrectLabel(unsigned paramIndex) override {
+    return !CS.shouldAttemptFixes();
+  }
+
+  bool relabelArguments(ArrayRef<Identifier> newLabels) override {
+    if (!CS.shouldAttemptFixes())
+      return true;
+
+    auto *anchor = Locator.getBaseLocator()->getAnchor();
+    if (!anchor || !isa<CallExpr>(anchor))
+      return true;
+
+    CS.recordFix(Fix::fixArgumentLabels(CS, newLabels),
+                 CS.getConstraintLocator(anchor));
+    return false;
+  }
+};
+
 // Match the argument of a call to the parameter.
 static ConstraintSystem::TypeMatchResult
 matchCallArguments(ConstraintSystem &cs, ConstraintKind kind,
@@ -747,7 +790,7 @@
   auto args = decomposeArgType(argType, argLabels);
   
   // Match up the call arguments to the parameters.
-  MatchCallArgumentListener listener;
+  ArgumentFailureTracker listener(cs, locator);
   SmallVector<ParamBinding, 4> parameterBindings;
   if (constraints::matchCallArguments(args, params,
                                       defaultMap,
@@ -4910,6 +4953,7 @@
   case FixKind::ExplicitlyEscaping:
   case FixKind::ExplicitlyEscapingToAny:
   case FixKind::CoerceToCheckedCast:
+  case FixKind::RelabelArguments:
     llvm_unreachable("handled elsewhere");
   }
 
diff --git a/lib/Sema/Constraint.cpp b/lib/Sema/Constraint.cpp
index 628e05f..070ac8a 100644
--- a/lib/Sema/Constraint.cpp
+++ b/lib/Sema/Constraint.cpp
@@ -493,6 +493,13 @@
   return Fix(FixKind::UnwrapOptionalBase, index);
 }
 
+Fix Fix::fixArgumentLabels(ConstraintSystem &cs,
+                           ArrayRef<Identifier> newLabels) {
+  unsigned index = cs.FixedArgLabels.size();
+  cs.FixedArgLabels.push_back(newLabels);
+  return Fix(FixKind::RelabelArguments, index);
+}
+
 Type Fix::getTypeArgument(ConstraintSystem &cs) const {
   assert(getKind() == FixKind::ForceDowncast);
   return cs.FixedTypes[Data];
@@ -504,6 +511,11 @@
   return cs.FixedDeclNames[Data];
 }
 
+ArrayRef<Identifier> Fix::getArgumentLabels(ConstraintSystem &cs) const {
+  assert(getKind() == FixKind::RelabelArguments);
+  return cs.FixedArgLabels[Data];
+}
+
 StringRef Fix::getName(FixKind kind) {
   switch (kind) {
   case FixKind::ForceOptional:
@@ -519,6 +531,8 @@
   case FixKind::ExplicitlyEscaping:
   case FixKind::ExplicitlyEscapingToAny:
     return "fix: add @escaping";
+  case FixKind::RelabelArguments:
+    return "fix: re-label argument(s)";
   }
 
   llvm_unreachable("Unhandled FixKind in switch.");
diff --git a/lib/Sema/Constraint.h b/lib/Sema/Constraint.h
index 560a80f..ee7f61a 100644
--- a/lib/Sema/Constraint.h
+++ b/lib/Sema/Constraint.h
@@ -249,6 +249,10 @@
   ExplicitlyEscaping,
   /// Mark function type as explicitly '@escaping' to be convertable to 'Any'.
   ExplicitlyEscapingToAny,
+
+  /// Arguments have labeling failures - missing/extraneous or incorrect
+  /// labels attached to the, fix it by suggesting proper labels.
+  RelabelArguments,
 };
 
 /// Describes a fix that can be applied to a constraint before visiting it.
@@ -276,6 +280,11 @@
   /// with the given name.
   static Fix getUnwrapOptionalBase(ConstraintSystem &cs, DeclName memberName);
 
+  /// Produce a new fix that re-labels existing arguments so they much
+  /// what parameters expect.
+  static Fix fixArgumentLabels(ConstraintSystem &cs,
+                               ArrayRef<Identifier> newLabels);
+
   /// Retrieve the kind of fix.
   FixKind getKind() const { return Kind; }
 
@@ -285,6 +294,9 @@
   /// If this fix has a name argument, retrieve it.
   DeclName getDeclNameArgument(ConstraintSystem &cs) const;
 
+  /// If this fix is an argument re-labeling, retrieve new labels.
+  ArrayRef<Identifier> getArgumentLabels(ConstraintSystem &cs) const;
+
   /// Return a string representation of a fix.
   static llvm::StringRef getName(FixKind kind);
 
diff --git a/lib/Sema/ConstraintSystem.h b/lib/Sema/ConstraintSystem.h
index 976d387..0259e00 100644
--- a/lib/Sema/ConstraintSystem.h
+++ b/lib/Sema/ConstraintSystem.h
@@ -1008,6 +1008,9 @@
   /// Declaration names used in fixes.
   std::vector<DeclName> FixedDeclNames;
 
+  /// Argument labels fixed by the constraint solver.
+  SmallVector<std::vector<Identifier>, 4> FixedArgLabels;
+
   /// \brief The set of remembered disjunction choices used to reach
   /// the current constraint system.
   SmallVector<std::pair<ConstraintLocator*, unsigned>, 32>
@@ -1515,10 +1518,11 @@
   /// able to emit an error message, or false if none of the fixits worked out.
   bool applySolutionFixes(Expr *E, const Solution &solution);
 
-  /// \brief Apply the specified Fix # to this solution, producing a fixit hint
-  /// diagnostic for it and returning true.  If the fixit hint turned out to be
+  /// \brief Apply the specified Fix to this solution, producing a fix-it hint
+  /// diagnostic for it and returning true.  If the fix-it hint turned out to be
   /// bogus, this returns false and doesn't emit anything.
-  bool applySolutionFix(Expr *expr, const Solution &solution, unsigned fixNo);
+  bool applySolutionFix(Expr *expr, const Solution &solution,
+                        std::pair<Fix, ConstraintLocator *> &fix);
 
   /// \brief If there is more than one viable solution,
   /// attempt to pick the best solution and remove all of the rest.
diff --git a/lib/Sema/TypeCheckDecl.cpp b/lib/Sema/TypeCheckDecl.cpp
index 6a1b12a..e095bef 100644
--- a/lib/Sema/TypeCheckDecl.cpp
+++ b/lib/Sema/TypeCheckDecl.cpp
@@ -2306,6 +2306,8 @@
 
 static void finalizeAbstractStorageDecl(TypeChecker &TC,
                                         AbstractStorageDecl *storage) {
+  TC.validateDecl(storage);
+
   for (auto accessor : storage->getAllAccessors()) {
     // Are there accessors we can safely ignore here, like maybe observers?
     TC.validateDecl(accessor);
@@ -2330,8 +2332,8 @@
     if (auto VD = dyn_cast<ValueDecl>(decl)) {
       checkRedeclaration(TC, VD);
 
-      (void)VD->isObjC();
-      (void)VD->isDynamic();
+      // Make sure we finalize this declaration.
+      TC.DeclsToFinalize.insert(VD);
 
       // If this is a member of a nominal type, don't allow it to have a name of
       // "Type" or "Protocol" since we reserve the X.Type and X.Protocol
@@ -2721,8 +2723,6 @@
 
     checkUnsupportedNestedType(ED);
     TC.validateDecl(ED);
-    TC.DeclsToFinalize.remove(ED);
-    ED->setHasValidatedLayout();
 
     {
       // Check for circular inheritance of the raw type.
@@ -2760,8 +2760,6 @@
     checkUnsupportedNestedType(SD);
 
     TC.validateDecl(SD);
-    TC.DeclsToFinalize.remove(SD);
-    SD->setHasValidatedLayout();
 
     TC.addImplicitConstructors(SD);
 
@@ -2891,8 +2889,6 @@
 
     TC.validateDecl(CD);
     TC.requestSuperclassLayout(CD);
-    TC.DeclsToFinalize.remove(CD);
-    CD->setHasValidatedLayout();
 
     {
       // Check for circular inheritance.
@@ -4624,6 +4620,14 @@
   if (auto *protocolDecl = dyn_cast<ProtocolDecl>(dc))
     requestNominalLayout(protocolDecl);
 
+  if (auto ext = dyn_cast<ExtensionDecl>(dc)) {
+    if (ext->getAsClassOrClassExtensionContext()) {
+      // Finalize members of class extensions, to ensure we compute their
+      // @objc and dynamic state.
+      DeclsToFinalize.insert(member);
+    }
+  }
+
   // If this represents (abstract) storage, form the appropriate accessors.
   if (auto storage = dyn_cast<AbstractStorageDecl>(member)) {
     validateAbstractStorageDecl(*this, storage);
@@ -4641,11 +4645,6 @@
 }
 
 void TypeChecker::requestNominalLayout(NominalTypeDecl *nominalDecl) {
-  if (nominalDecl->hasValidatedLayout())
-    return;
-
-  nominalDecl->setHasValidatedLayout();
-
   if (isa<SourceFile>(nominalDecl->getModuleScopeContext()))
     DeclsToFinalize.insert(nominalDecl);
 }
@@ -4682,23 +4681,16 @@
     if (!shouldValidateMemberDuringFinalization(nominal, VD))
       continue;
 
-    TC.validateDecl(VD);
-
-    // Compute overrides.
-    (void)VD->getOverriddenDecls();
-
-    // Check whether the member is @objc or dynamic.
-    (void)VD->isObjC();
-    (void)VD->isDynamic();
+    TC.DeclsToFinalize.insert(VD);
 
     // The only thing left to do is synthesize storage for lazy variables.
     auto *prop = dyn_cast<VarDecl>(D);
     if (!prop)
       continue;
 
-    if (prop->getAttrs().hasAttribute<LazyAttr>() && !prop->isStatic()
-                                                  && prop->getGetter()) {
-      assert(!prop->getGetter()->hasBody());
+    if (prop->getAttrs().hasAttribute<LazyAttr>() && !prop->isStatic() &&
+        (!prop->getGetter() || !prop->getGetter()->hasBody())) {
+      finalizeAbstractStorageDecl(TC, prop);
       TC.completeLazyVarImplementation(prop);
     }
   }
@@ -4738,18 +4730,20 @@
 }
 
 void TypeChecker::finalizeDecl(ValueDecl *decl) {
+  validateDecl(decl);
+
   if (auto nominal = dyn_cast<NominalTypeDecl>(decl)) {
     finalizeType(*this, nominal);
-  } else if (auto func = dyn_cast<AbstractFunctionDecl>(decl)) {
-    // We synthesize certain functions --- mostly accessors --- at
-    // times that can be inconvenient for immediate validation.  We add
-    // them to the list of declarations to finalize so that we can
-    // fully validate them at a more opportune time.
-    validateDecl(func);
-  } else {
-    auto storage = cast<AbstractStorageDecl>(decl);
+  } else if (auto storage = dyn_cast<AbstractStorageDecl>(decl)) {
     finalizeAbstractStorageDecl(*this, storage);
   }
+
+  // Compute overrides.
+  (void)decl->getOverriddenDecls();
+
+  // Check whether the member is @objc or dynamic.
+  (void)decl->isObjC();
+  (void)decl->isDynamic();
 }
 
 bool swift::isPassThroughTypealias(TypeAliasDecl *typealias) {
diff --git a/lib/Sema/TypeCheckProtocol.cpp b/lib/Sema/TypeCheckProtocol.cpp
index 392b615..81092e42 100644
--- a/lib/Sema/TypeCheckProtocol.cpp
+++ b/lib/Sema/TypeCheckProtocol.cpp
@@ -2158,8 +2158,7 @@
 
 void ConformanceChecker::recordTypeWitness(AssociatedTypeDecl *assocType,
                                            Type type,
-                                           TypeDecl *typeDecl,
-                                           bool performRedeclarationCheck) {
+                                           TypeDecl *typeDecl) {
 
   // If we already recoded this type witness, there's nothing to do.
   if (Conformance->hasTypeWitness(assocType)) {
@@ -2210,26 +2209,6 @@
     }
   } else {
     // If there was no type declaration, synthesize one.
-
-    // If we're just setting an error, double-check that nobody has
-    // introduced a type declaration since we deduced one. This can
-    // happen when type-checking a different conformance deduces a
-    // different type witness with the same name. For non-error cases,
-    // the caller handles this.
-    if (performRedeclarationCheck && type->hasError()) {
-      switch (resolveTypeWitnessViaLookup(assocType)) {
-      case ResolveWitnessResult::Success:
-      case ResolveWitnessResult::ExplicitFailed:
-        // A type witness has shown up, and will have been
-        // recorded. There is nothing more to do.
-        return;
-
-      case ResolveWitnessResult::Missing:
-        // The type witness is still missing: create a new one.
-        break;
-      }
-    }
-
     auto aliasDecl = new (TC.Context) TypeAliasDecl(SourceLoc(),
                                                     SourceLoc(),
                                                     assocType->getName(),
@@ -2294,8 +2273,7 @@
     auto overriddenRootConformance =
       overriddenConformance->getConcrete()->getRootNormalConformance();
     ConformanceChecker(TC, overriddenRootConformance, GlobalMissingWitnesses)
-      .recordTypeWitness(overridden, type, typeDecl,
-                         /*performRedeclarationCheck=*/true);
+      .recordTypeWitness(overridden, type, typeDecl);
   }
 }
 
@@ -3197,12 +3175,12 @@
     auto interfaceType = viable.front().MemberType;
     if (interfaceType->hasArchetype())
       interfaceType = interfaceType->mapTypeOutOfContext();
-    recordTypeWitness(assocType, interfaceType, viable.front().Member, true);
+    recordTypeWitness(assocType, interfaceType, viable.front().Member);
     return ResolveWitnessResult::Success;
   }
 
   // Record an error.
-  recordTypeWitness(assocType, ErrorType::get(TC.Context), nullptr, false);
+  recordTypeWitness(assocType, ErrorType::get(TC.Context), nullptr);
 
   // If we had multiple viable types, diagnose the ambiguity.
   if (!viable.empty()) {
diff --git a/lib/Sema/TypeCheckProtocol.h b/lib/Sema/TypeCheckProtocol.h
index c11ddb4..ad7e025 100644
--- a/lib/Sema/TypeCheckProtocol.h
+++ b/lib/Sema/TypeCheckProtocol.h
@@ -564,7 +564,7 @@
   ///
   /// \param typeDecl The decl the witness type came from; can be null.
   void recordTypeWitness(AssociatedTypeDecl *assocType, Type type,
-                         TypeDecl *typeDecl, bool performRedeclarationCheck);
+                         TypeDecl *typeDecl);
 
   /// Enforce restrictions on non-final classes witnessing requirements
   /// involving the protocol 'Self' type.
diff --git a/lib/Sema/TypeCheckProtocolInference.cpp b/lib/Sema/TypeCheckProtocolInference.cpp
index 6178841..71597f4 100644
--- a/lib/Sema/TypeCheckProtocolInference.cpp
+++ b/lib/Sema/TypeCheckProtocolInference.cpp
@@ -1979,8 +1979,7 @@
   if (auto inferred = inference.solve(*this)) {
     for (const auto &inferredWitness : *inferred) {
       recordTypeWitness(inferredWitness.first, inferredWitness.second,
-                        /*typeDecl=*/nullptr,
-                        /*performRedeclarationCheck=*/true);
+                        /*typeDecl=*/nullptr);
     }
 
     ensureRequirementsAreSatisfied(/*failUnsubstituted=*/false);
@@ -1997,7 +1996,7 @@
     if (Conformance->hasTypeWitness(assocType))
       continue;
 
-    recordTypeWitness(assocType, ErrorType::get(TC.Context), nullptr, true);
+    recordTypeWitness(assocType, ErrorType::get(TC.Context), nullptr);
   }
 }
 
diff --git a/lib/Sema/TypeCheckStmt.cpp b/lib/Sema/TypeCheckStmt.cpp
index 32a3435..82e377c 100644
--- a/lib/Sema/TypeCheckStmt.cpp
+++ b/lib/Sema/TypeCheckStmt.cpp
@@ -313,6 +313,9 @@
   /// expressions are not discarded.
   bool IsREPL;
 
+  /// Used to distinguish the first BraceStmt that starts a TopLevelCodeDecl.
+  bool IsBraceStmtFromTopLevelDecl;
+
   struct AddLabeledStmt {
     StmtChecker &SC;
     AddLabeledStmt(StmtChecker &SC, LabeledStmt *LS) : SC(SC) {
@@ -352,16 +355,21 @@
   };
 
   StmtChecker(TypeChecker &TC, AbstractFunctionDecl *AFD)
-    : TC(TC), TheFunc(AFD), DC(AFD), IsREPL(false) { }
+      : TC(TC), TheFunc(AFD), DC(AFD), IsREPL(false),
+        IsBraceStmtFromTopLevelDecl(false) {}
 
   StmtChecker(TypeChecker &TC, ClosureExpr *TheClosure)
-    : TC(TC), TheFunc(TheClosure), DC(TheClosure), IsREPL(false) { }
+      : TC(TC), TheFunc(TheClosure), DC(TheClosure), IsREPL(false),
+        IsBraceStmtFromTopLevelDecl(false) {}
 
   StmtChecker(TypeChecker &TC, DeclContext *DC)
-    : TC(TC), TheFunc(), DC(DC), IsREPL(false) {
+      : TC(TC), TheFunc(), DC(DC), IsREPL(false),
+        IsBraceStmtFromTopLevelDecl(false) {
     if (const SourceFile *SF = DC->getParentSourceFile())
       if (SF->Kind == SourceFileKind::REPL)
         IsREPL = true;
+
+    IsBraceStmtFromTopLevelDecl = isa<TopLevelCodeDecl>(DC);
   }
 
   //===--------------------------------------------------------------------===//
@@ -550,7 +558,7 @@
     Expr *theCall = DS->getCallExpr();
     TC.typeCheckExpression(theCall, DC);
     DS->setCallExpr(theCall);
-    
+
     return DS;
   }
   
@@ -1397,6 +1405,21 @@
 
 Stmt *StmtChecker::visitBraceStmt(BraceStmt *BS) {
   const SourceManager &SM = TC.Context.SourceMgr;
+
+  // Diagnose defer statement being last one in block (only if
+  // BraceStmt does not start a TopLevelDecl).
+  if (IsBraceStmtFromTopLevelDecl) {
+    IsBraceStmtFromTopLevelDecl = false;
+  } else if (BS->getNumElements() > 0) {
+    if (auto stmt =
+            BS->getElement(BS->getNumElements() - 1).dyn_cast<Stmt *>()) {
+      if (auto deferStmt = dyn_cast<DeferStmt>(stmt)) {
+        TC.diagnose(deferStmt->getStartLoc(), diag::defer_stmt_at_block_end)
+            .fixItReplace(deferStmt->getStartLoc(), "do");
+      }
+    }
+  }
+
   for (auto &elem : BS->getElements()) {
     if (auto *SubExpr = elem.dyn_cast<Expr*>()) {
       SourceLoc Loc = SubExpr->getStartLoc();
@@ -1452,7 +1475,7 @@
 
     TC.typeCheckDecl(SubDecl);
   }
-  
+
   return BS;
 }
 
diff --git a/lib/Sema/TypeChecker.cpp b/lib/Sema/TypeChecker.cpp
index 9cb9e8d..f6fcb2c 100644
--- a/lib/Sema/TypeChecker.cpp
+++ b/lib/Sema/TypeChecker.cpp
@@ -567,9 +567,15 @@
     // Note: if we ever start putting extension members in vtables, we'll need
     // to validate those members too.
     // FIXME: If we're not planning to run SILGen, this is wasted effort.
-    while (!TC.DeclsToFinalize.empty()) {
-      auto decl = TC.DeclsToFinalize.pop_back_val();
-      if (decl->isInvalid() || TC.Context.hadError())
+    while (TC.NextDeclToFinalize < TC.DeclsToFinalize.size()) {
+      auto decl = TC.DeclsToFinalize[TC.NextDeclToFinalize++];
+      if (decl->isInvalid())
+        continue;
+
+      // If we've already encountered an error, don't finalize declarations
+      // from other source files.
+      if (TC.Context.hadError() &&
+          decl->getDeclContext()->getParentSourceFile() != &SF)
         continue;
 
       TC.finalizeDecl(decl);
@@ -603,7 +609,7 @@
            currentExternalDef < TC.Context.ExternalDefinitions.size() ||
            currentSynthesizedDecl < SF.SynthesizedDecls.size() ||
            !TC.FunctionsToSynthesize.empty() ||
-           !TC.DeclsToFinalize.empty() ||
+           TC.NextDeclToFinalize < TC.DeclsToFinalize.size() ||
            !TC.ConformanceContexts.empty() ||
            !TC.DelayedRequirementSignatures.empty() ||
            !TC.UsedConformances.empty() ||
diff --git a/lib/Sema/TypeChecker.h b/lib/Sema/TypeChecker.h
index fc869c8..60580dc 100644
--- a/lib/Sema/TypeChecker.h
+++ b/lib/Sema/TypeChecker.h
@@ -652,6 +652,10 @@
   /// we can hand them off to SILGen etc.
   llvm::SetVector<ValueDecl *> DeclsToFinalize;
 
+  /// Track the index of the next declaration that needs to be finalized,
+  /// from the \c DeclsToFinalize set.
+  unsigned NextDeclToFinalize = 0;
+
   /// The list of functions that need to have their bodies synthesized.
   llvm::MapVector<FuncDecl*, SynthesizedFunction> FunctionsToSynthesize;
 
diff --git a/lib/Serialization/Serialization.cpp b/lib/Serialization/Serialization.cpp
index 19df58a..38e00ae 100644
--- a/lib/Serialization/Serialization.cpp
+++ b/lib/Serialization/Serialization.cpp
@@ -4788,9 +4788,33 @@
   const NominalTypeDecl *nominalParent = nullptr;
 
   for (const Decl *member : members) {
+    // If there is a corresponding Objective-C method, record it.
+    auto recordObjCMethod = [&] {
+      if (isLocal)
+        return;
+
+      if (auto func = dyn_cast<AbstractFunctionDecl>(member)) {
+        if (func->isObjC()) {
+          if (auto owningClass =
+                func->getDeclContext()->getAsClassOrClassExtensionContext()) {
+            Mangle::ASTMangler mangler;
+            std::string ownerName = mangler.mangleNominalType(owningClass);
+            assert(!ownerName.empty() && "Mangled type came back empty!");
+
+            objcMethods[func->getObjCSelector()].push_back(
+              std::make_tuple(ownerName,
+                              func->isObjCInstanceMethod(),
+                              S.addDeclRef(func)));
+          }
+        }
+      }
+    };
+
     if (auto memberValue = dyn_cast<ValueDecl>(member)) {
-      if (!memberValue->hasName())
+      if (!memberValue->hasName()) {
+        recordObjCMethod();
         continue;
+      }
 
       if (memberValue->isOperator()) {
         // Add operator methods.
@@ -4826,23 +4850,7 @@
     }
 
     // Record Objective-C methods.
-    if (!isLocal) {
-      if (auto func = dyn_cast<AbstractFunctionDecl>(member)) {
-        if (func->isObjC()) {
-          if (auto owningClass =
-                func->getDeclContext()->getAsClassOrClassExtensionContext()) {
-            Mangle::ASTMangler mangler;
-            std::string ownerName = mangler.mangleNominalType(owningClass);
-            assert(!ownerName.empty() && "Mangled type came back empty!");
-
-            objcMethods[func->getObjCSelector()].push_back(
-              std::make_tuple(ownerName,
-                              func->isObjCInstanceMethod(),
-                              S.addDeclRef(func)));
-          }
-        }
-      }
-    }
+    recordObjCMethod();
   }
 }
 
diff --git a/lib/Serialization/SerializedModuleLoader.cpp b/lib/Serialization/SerializedModuleLoader.cpp
index 285abc2..9c9ac15 100644
--- a/lib/Serialization/SerializedModuleLoader.cpp
+++ b/lib/Serialization/SerializedModuleLoader.cpp
@@ -12,10 +12,10 @@
 
 #include "swift/Serialization/SerializedModuleLoader.h"
 #include "swift/Serialization/ModuleFile.h"
-#include "swift/Strings.h"
 #include "swift/AST/ASTContext.h"
 #include "swift/AST/DiagnosticsSema.h"
 #include "swift/Basic/Defer.h"
+#include "swift/Basic/FileTypes.h"
 #include "swift/Basic/STLExtras.h"
 #include "swift/Basic/SourceManager.h"
 #include "swift/Basic/Version.h"
@@ -106,8 +106,8 @@
     auto entry = *directoryIterator;
     StringRef filePath(entry.path());
     StringRef extension = llvm::sys::path::extension(filePath);
-    if (extension.startswith(".") &&
-        extension.drop_front() == SERIALIZED_MODULE_EXTENSION) {
+    if (file_types::lookupTypeForExtension(extension) ==
+          file_types::TY_SwiftModuleFile) {
       foundArchs = foundArchs + (foundArchs.length() > 0 ? ", " : "") +
                    llvm::sys::path::stem(filePath).str();
     }
@@ -125,11 +125,12 @@
   llvm::SmallString<64> moduleName(moduleID.first.str());
   llvm::SmallString<64> moduleFilename(moduleName);
   moduleFilename += '.';
-  moduleFilename += SERIALIZED_MODULE_EXTENSION;
+  moduleFilename += file_types::getExtension(file_types::TY_SwiftModuleFile);
 
   llvm::SmallString<64> moduleDocFilename(moduleID.first.str());
   moduleDocFilename += '.';
-  moduleDocFilename += SERIALIZED_MODULE_DOC_EXTENSION;
+  moduleDocFilename +=
+      file_types::getExtension(file_types::TY_SwiftModuleDocFile);
 
   // FIXME: Which name should we be using here? Do we care about CPU subtypes?
   // FIXME: At the very least, don't hardcode "arch".
@@ -139,10 +140,10 @@
   llvm::SmallString<16> archDocFile{archName};
   if (!archFile.empty()) {
     archFile += '.';
-    archFile += SERIALIZED_MODULE_EXTENSION;
+    archFile += file_types::getExtension(file_types::TY_SwiftModuleFile);
 
     archDocFile += '.';
-    archDocFile += SERIALIZED_MODULE_DOC_EXTENSION;
+    archDocFile += file_types::getExtension(file_types::TY_SwiftModuleDocFile);
   }
 
   llvm::SmallString<128> scratch;
diff --git a/stdlib/public/core/BidirectionalCollection.swift b/stdlib/public/core/BidirectionalCollection.swift
index f86af70..b537c6b 100644
--- a/stdlib/public/core/BidirectionalCollection.swift
+++ b/stdlib/public/core/BidirectionalCollection.swift
@@ -62,6 +62,116 @@
   ///   `startIndex`.
   func formIndex(before i: inout Index)
 
+  /// Returns the position immediately after the given index.
+  ///
+  /// The successor of an index must be well defined. For an index `i` into a
+  /// collection `c`, calling `c.index(after: i)` returns the same index every
+  /// time.
+  ///
+  /// - Parameter i: A valid index of the collection. `i` must be less than
+  ///   `endIndex`.
+  /// - Returns: The index value immediately after `i`.
+  func index(after i: Index) -> Index
+
+  /// Replaces the given index with its successor.
+  ///
+  /// - Parameter i: A valid index of the collection. `i` must be less than
+  ///   `endIndex`.
+  func formIndex(after i: inout Index)
+
+  /// Returns an index that is the specified distance from the given index.
+  ///
+  /// The following example obtains an index advanced four positions from a
+  /// string's starting index and then prints the character at that position.
+  ///
+  ///     let s = "Swift"
+  ///     let i = s.index(s.startIndex, offsetBy: 4)
+  ///     print(s[i])
+  ///     // Prints "t"
+  ///
+  /// The value passed as `distance` must not offset `i` beyond the bounds of
+  /// the collection.
+  ///
+  /// - Parameters:
+  ///   - i: A valid index of the collection.
+  ///   - distance: The distance to offset `i`. `distance` must not be negative
+  ///     unless the collection conforms to the `BidirectionalCollection`
+  ///     protocol.
+  /// - Returns: An index offset by `distance` from the index `i`. If
+  ///   `distance` is positive, this is the same value as the result of
+  ///   `distance` calls to `index(after:)`. If `distance` is negative, this
+  ///   is the same value as the result of `abs(distance)` calls to
+  ///   `index(before:)`.
+  ///
+  /// - Complexity: O(1) if the collection conforms to
+  ///   `RandomAccessCollection`; otherwise, O(*k*), where *k* is the absolute
+  ///   value of `distance`.
+  func index(_ i: Index, offsetBy distance: Int) -> Index
+
+  /// Returns an index that is the specified distance from the given index,
+  /// unless that distance is beyond a given limiting index.
+  ///
+  /// The following example obtains an index advanced four positions from a
+  /// string's starting index and then prints the character at that position.
+  /// The operation doesn't require going beyond the limiting `s.endIndex`
+  /// value, so it succeeds.
+  ///
+  ///     let s = "Swift"
+  ///     if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
+  ///         print(s[i])
+  ///     }
+  ///     // Prints "t"
+  ///
+  /// The next example attempts to retrieve an index six positions from
+  /// `s.startIndex` but fails, because that distance is beyond the index
+  /// passed as `limit`.
+  ///
+  ///     let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)
+  ///     print(j)
+  ///     // Prints "nil"
+  ///
+  /// The value passed as `distance` must not offset `i` beyond the bounds of
+  /// the collection, unless the index passed as `limit` prevents offsetting
+  /// beyond those bounds.
+  ///
+  /// - Parameters:
+  ///   - i: A valid index of the collection.
+  ///   - distance: The distance to offset `i`. `distance` must not be negative
+  ///     unless the collection conforms to the `BidirectionalCollection`
+  ///     protocol.
+  ///   - limit: A valid index of the collection to use as a limit. If
+  ///     `distance > 0`, a limit that is less than `i` has no effect.
+  ///     Likewise, if `distance < 0`, a limit that is greater than `i` has no
+  ///     effect.
+  /// - Returns: An index offset by `distance` from the index `i`, unless that
+  ///   index would be beyond `limit` in the direction of movement. In that
+  ///   case, the method returns `nil`.
+  ///
+  /// - Complexity: O(1) if the collection conforms to
+  ///   `RandomAccessCollection`; otherwise, O(*k*), where *k* is the absolute
+  ///   value of `distance`.
+  func index(
+    _ i: Index, offsetBy distance: Int, limitedBy limit: Index
+  ) -> Index?
+
+  /// Returns the distance between two indices.
+  ///
+  /// Unless the collection conforms to the `BidirectionalCollection` protocol,
+  /// `start` must be less than or equal to `end`.
+  ///
+  /// - Parameters:
+  ///   - start: A valid index of the collection.
+  ///   - end: Another valid index of the collection. If `end` is equal to
+  ///     `start`, the result is zero.
+  /// - Returns: The distance between `start` and `end`. The result can be
+  ///   negative only if the collection conforms to the
+  ///   `BidirectionalCollection` protocol.
+  ///
+  /// - Complexity: O(1) if the collection conforms to
+  ///   `RandomAccessCollection`; otherwise, O(*k*), where *k* is the
+  ///   resulting distance.
+  func distance(from start: Index, to end: Index) -> Int
+
   /// The indices that are valid for subscripting the collection, in ascending
   /// order.
   ///
@@ -257,9 +367,7 @@
     _precondition(k >= 0, "Number of elements to remove should be non-negative")
     _precondition(count >= k,
       "Can't remove more items from a collection than it contains")
-    // FIXME: using non-_'d `index` incorrectly calls the Collection one for
-    // conditional conformances to BidirectionalCollections.
-    self = self[startIndex..<_index(endIndex, offsetBy: -k)]
+    self = self[startIndex..<index(endIndex, offsetBy: -k)]
   }
 }
 
@@ -287,9 +395,7 @@
   public func dropLast(_ k: Int) -> SubSequence {
     _precondition(
       k >= 0, "Can't drop a negative number of elements from a collection")
-    // FIXME: using non-_'d `index` incorrectly calls the Collection one for
-    // conditional conformances to BidirectionalCollections.
-    let end = _index(
+    let end = index(
       endIndex,
       offsetBy: -k,
       limitedBy: startIndex) ?? startIndex
@@ -321,9 +427,7 @@
     _precondition(
       maxLength >= 0,
       "Can't take a suffix of negative length from a collection")
-    // FIXME: using non-_'d `index` incorrectly calls the Collection one for
-    // conditional conformances to BidirectionalCollections.
-    let start = _index(
+    let start = index(
       endIndex,
       offsetBy: -maxLength,
       limitedBy: startIndex) ?? startIndex
diff --git a/stdlib/public/core/RandomAccessCollection.swift b/stdlib/public/core/RandomAccessCollection.swift
index 03538e4..8406419 100644
--- a/stdlib/public/core/RandomAccessCollection.swift
+++ b/stdlib/public/core/RandomAccessCollection.swift
@@ -97,6 +97,129 @@
 
   // FIXME(ABI): Associated type inference requires this.
   var endIndex: Index { get }
+
+  /// Returns the position immediately before the given index.
+  ///
+  /// - Parameter i: A valid index of the collection. `i` must be greater than
+  ///   `startIndex`.
+  /// - Returns: The index value immediately before `i`.
+  func index(before i: Index) -> Index
+
+  /// Replaces the given index with its predecessor.
+  ///
+  /// - Parameter i: A valid index of the collection. `i` must be greater than
+  ///   `startIndex`.
+  func formIndex(before i: inout Index)
+
+  /// Returns the position immediately after the given index.
+  ///
+  /// The successor of an index must be well defined. For an index `i` into a
+  /// collection `c`, calling `c.index(after: i)` returns the same index every
+  /// time.
+  ///
+  /// - Parameter i: A valid index of the collection. `i` must be less than
+  ///   `endIndex`.
+  /// - Returns: The index value immediately after `i`.
+  func index(after i: Index) -> Index
+
+  /// Replaces the given index with its successor.
+  ///
+  /// - Parameter i: A valid index of the collection. `i` must be less than
+  ///   `endIndex`.
+  func formIndex(after i: inout Index)
+
+  /// Returns an index that is the specified distance from the given index.
+  ///
+  /// The following example obtains an index advanced four positions from a
+  /// string's starting index and then prints the character at that position.
+  ///
+  ///     let s = "Swift"
+  ///     let i = s.index(s.startIndex, offsetBy: 4)
+  ///     print(s[i])
+  ///     // Prints "t"
+  ///
+  /// The value passed as `distance` must not offset `i` beyond the bounds of
+  /// the collection.
+  ///
+  /// - Parameters:
+  ///   - i: A valid index of the collection.
+  ///   - distance: The distance to offset `i`. `distance` must not be negative
+  ///     unless the collection conforms to the `BidirectionalCollection`
+  ///     protocol.
+  /// - Returns: An index offset by `distance` from the index `i`. If
+  ///   `distance` is positive, this is the same value as the result of
+  ///   `distance` calls to `index(after:)`. If `distance` is negative, this
+  ///   is the same value as the result of `abs(distance)` calls to
+  ///   `index(before:)`.
+  ///
+  /// - Complexity: O(1) if the collection conforms to
+  ///   `RandomAccessCollection`; otherwise, O(*k*), where *k* is the absolute
+  ///   value of `distance`.
+  func index(_ i: Index, offsetBy distance: Int) -> Index
+
+  /// Returns an index that is the specified distance from the given index,
+  /// unless that distance is beyond a given limiting index.
+  ///
+  /// The following example obtains an index advanced four positions from a
+  /// string's starting index and then prints the character at that position.
+  /// The operation doesn't require going beyond the limiting `s.endIndex`
+  /// value, so it succeeds.
+  ///
+  ///     let s = "Swift"
+  ///     if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
+  ///         print(s[i])
+  ///     }
+  ///     // Prints "t"
+  ///
+  /// The next example attempts to retrieve an index six positions from
+  /// `s.startIndex` but fails, because that distance is beyond the index
+  /// passed as `limit`.
+  ///
+  ///     let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)
+  ///     print(j)
+  ///     // Prints "nil"
+  ///
+  /// The value passed as `distance` must not offset `i` beyond the bounds of
+  /// the collection, unless the index passed as `limit` prevents offsetting
+  /// beyond those bounds.
+  ///
+  /// - Parameters:
+  ///   - i: A valid index of the collection.
+  ///   - distance: The distance to offset `i`. `distance` must not be negative
+  ///     unless the collection conforms to the `BidirectionalCollection`
+  ///     protocol.
+  ///   - limit: A valid index of the collection to use as a limit. If
+  ///     `distance > 0`, a limit that is less than `i` has no effect.
+  ///     Likewise, if `distance < 0`, a limit that is greater than `i` has no
+  ///     effect.
+  /// - Returns: An index offset by `distance` from the index `i`, unless that
+  ///   index would be beyond `limit` in the direction of movement. In that
+  ///   case, the method returns `nil`.
+  ///
+  /// - Complexity: O(1) if the collection conforms to
+  ///   `RandomAccessCollection`; otherwise, O(*k*), where *k* is the absolute
+  ///   value of `distance`.
+  func index(
+    _ i: Index, offsetBy distance: Int, limitedBy limit: Index
+  ) -> Index?
+
+  /// Returns the distance between two indices.
+  ///
+  /// Unless the collection conforms to the `BidirectionalCollection` protocol,
+  /// `start` must be less than or equal to `end`.
+  ///
+  /// - Parameters:
+  ///   - start: A valid index of the collection.
+  ///   - end: Another valid index of the collection. If `end` is equal to
+  ///     `start`, the result is zero.
+  /// - Returns: The distance between `start` and `end`. The result can be
+  ///   negative only if the collection conforms to the
+  ///   `BidirectionalCollection` protocol.
+  ///
+  /// - Complexity: O(1) if the collection conforms to
+  ///   `RandomAccessCollection`; otherwise, O(*k*), where *k* is the
+  ///   resulting distance.
+  func distance(from start: Index, to end: Index) -> Int
 }
 
 // TODO: swift-3-indexing-model - (By creating an ambiguity?), try to
diff --git a/test/ClangImporter/availability_returns_twice.swift b/test/ClangImporter/availability_returns_twice.swift
index 2ddc562..05de4ea 100644
--- a/test/ClangImporter/availability_returns_twice.swift
+++ b/test/ClangImporter/availability_returns_twice.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
   import Darwin
diff --git a/test/ClangImporter/objc_factory_method.swift b/test/ClangImporter/objc_factory_method.swift
index dea1009..c87fb58 100644
--- a/test/ClangImporter/objc_factory_method.swift
+++ b/test/ClangImporter/objc_factory_method.swift
@@ -22,8 +22,7 @@
   _ = NSObjectFactorySub() // okay, prefers init method
   _ = NSObjectFactorySub(integer: 1)
   _ = NSObjectFactorySub(double: 314159)
-  _ = NSObjectFactorySub(float: 314159) // expected-error{{argument labels '(float:)' do not match any available overloads}} 
-  // expected-note @-1 {{overloads for 'NSObjectFactorySub' exist with these partially matching parameter lists: (integer: Int), (double: Double)}}
+  _ = NSObjectFactorySub(float: 314159) // expected-error{{incorrect argument label in call (have 'float:', expected 'integer:')}}
   let a = NSObjectFactorySub(buildingWidgets: ()) // expected-error{{argument labels '(buildingWidgets:)' do not match any available overloads}}
   // expected-note @-1 {{overloads for 'NSObjectFactorySub' exist with these partially matching parameter lists: (integer: Int), (double: Double)}}
   _ = a
diff --git a/test/ClangImporter/objc_implicit_with.swift b/test/ClangImporter/objc_implicit_with.swift
index 3eced3b..f56d985 100644
--- a/test/ClangImporter/objc_implicit_with.swift
+++ b/test/ClangImporter/objc_implicit_with.swift
@@ -33,8 +33,7 @@
   _ = NSObjectFactorySub() // okay, prefers init method
   _ = NSObjectFactorySub(integer: 1)
   _ = NSObjectFactorySub(double: 314159)
-  _ = NSObjectFactorySub(float: 314159) // expected-error{{argument labels '(float:)' do not match any available overloads}} 
-  // expected-note @-1 {{overloads for 'NSObjectFactorySub' exist with these partially matching parameter lists: (integer: Int), (double: Double)}}
+  _ = NSObjectFactorySub(float: 314159) // expected-error{{incorrect argument label in call (have 'float:', expected 'integer:')}}
   let a = NSObjectFactorySub(buildingWidgets: ()) // expected-error{{argument labels '(buildingWidgets:)' do not match any available overloads}}
   // expected-note @-1 {{overloads for 'NSObjectFactorySub' exist with these partially matching parameter lists: (integer: Int), (double: Double)}}
   _ = a
diff --git a/test/ClangImporter/pch-bridging-header.swift b/test/ClangImporter/pch-bridging-header.swift
index e69016d..d2ab92b 100644
--- a/test/ClangImporter/pch-bridging-header.swift
+++ b/test/ClangImporter/pch-bridging-header.swift
@@ -4,7 +4,7 @@
 
 // First test the explicit frontend-based bridging PCH generation and use works
 // RUN: %target-swift-frontend -emit-pch -o %t/sdk-bridging-header.pch %S/Inputs/sdk-bridging-header.h
-// RUN: %target-swift-frontend -typecheck -verify %s -import-objc-header %t/sdk-bridging-header.pch
+// RUN: %target-typecheck-verify-swift -import-objc-header %t/sdk-bridging-header.pch
 
 // Now test the driver-automated version is inert when disabled
 // RUN: env TMPDIR=%t/tmp/ %target-swiftc_driver -typecheck -disable-bridging-pch -save-temps %s -import-objc-header %S/Inputs/sdk-bridging-header.h
@@ -23,11 +23,11 @@
 
 // Test -emit-pch invocation but with a persistent PCH
 // RUN: %target-swift-frontend -emit-pch -pch-output-dir %t/pch %S/Inputs/sdk-bridging-header.h
-// RUN: %target-swift-frontend -typecheck -verify %s -import-objc-header %S/Inputs/sdk-bridging-header.h -pch-output-dir %t/pch -pch-disable-validation
+// RUN: %target-typecheck-verify-swift -import-objc-header %S/Inputs/sdk-bridging-header.h -pch-output-dir %t/pch -pch-disable-validation
 // RUN: ls %t/pch/*.pch >/dev/null 2>&1
 
 // Test implicit use of persistent PCH
-// RUN: %target-swift-frontend -typecheck -verify %s -import-objc-header %S/Inputs/sdk-bridging-header.h -pch-output-dir %t/pch2
+// RUN: %target-typecheck-verify-swift -import-objc-header %S/Inputs/sdk-bridging-header.h -pch-output-dir %t/pch2
 // RUN: ls %t/pch2/*.pch >/dev/null 2>&1
 
 // RUN: touch %t/header.with.dot.h
diff --git a/test/ClangImporter/sdk-bridging-header.swift b/test/ClangImporter/sdk-bridging-header.swift
index d59b94c..5dd5764 100644
--- a/test/ClangImporter/sdk-bridging-header.swift
+++ b/test/ClangImporter/sdk-bridging-header.swift
@@ -1,7 +1,7 @@
-// RUN: %target-swift-frontend -typecheck -verify %s -import-objc-header %S/Inputs/sdk-bridging-header.h
+// RUN: %target-typecheck-verify-swift -import-objc-header %S/Inputs/sdk-bridging-header.h
 // RUN: not %target-swift-frontend -typecheck %s -import-objc-header %S/Inputs/bad-bridging-header.h 2>&1 | %FileCheck -check-prefix=CHECK-FATAL %s
 
-// RUN: %target-swift-frontend -typecheck -verify %s -Xcc -include -Xcc %S/Inputs/sdk-bridging-header.h -import-objc-header %S/../Inputs/empty.swift
+// RUN: %target-typecheck-verify-swift -Xcc -include -Xcc %S/Inputs/sdk-bridging-header.h -import-objc-header %S/../Inputs/empty.swift
 
 // RUN: not %target-swift-frontend -typecheck %s -Xcc -include -Xcc %S/Inputs/bad-bridging-header.h 2>&1 | %FileCheck -check-prefix=CHECK-INCLUDE %s
 // RUN: not %target-swift-frontend -typecheck %s -Xcc -include -Xcc %S/Inputs/bad-bridging-header.h -import-objc-header %S/../Inputs/empty.swift 2>&1 | %FileCheck -check-prefix=CHECK-INCLUDE %s
diff --git a/test/ClangImporter/sdk.swift b/test/ClangImporter/sdk.swift
index 3363372..cfccdfc 100644
--- a/test/ClangImporter/sdk.swift
+++ b/test/ClangImporter/sdk.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 // XFAIL: linux
 
diff --git a/test/Constraints/anyhashable-collection-cast.swift b/test/Constraints/anyhashable-collection-cast.swift
index 8131296..2465dcb 100644
--- a/test/Constraints/anyhashable-collection-cast.swift
+++ b/test/Constraints/anyhashable-collection-cast.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 func dict() -> [AnyHashable: Any] {
    return ["x": "y"]
diff --git a/test/Constraints/associated-types-mixed-explicit-inferred.swift b/test/Constraints/associated-types-mixed-explicit-inferred.swift
index 1034032..7c23020 100644
--- a/test/Constraints/associated-types-mixed-explicit-inferred.swift
+++ b/test/Constraints/associated-types-mixed-explicit-inferred.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 protocol Foo {
   associatedtype Flim
   associatedtype Flam
diff --git a/test/Constraints/bridging.swift b/test/Constraints/bridging.swift
index d176ecc..56d1084 100644
--- a/test/Constraints/bridging.swift
+++ b/test/Constraints/bridging.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 // REQUIRES: objc_interop
 
diff --git a/test/Constraints/bridging_nonobjc.swift b/test/Constraints/bridging_nonobjc.swift
index df05f59..ab23b94 100644
--- a/test/Constraints/bridging_nonobjc.swift
+++ b/test/Constraints/bridging_nonobjc.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s -disable-objc-interop
+// RUN: %target-typecheck-verify-swift -disable-objc-interop
 
 
 var x: Any = 1
diff --git a/test/Constraints/collection-mutablecollection-order-dependency-1.swift b/test/Constraints/collection-mutablecollection-order-dependency-1.swift
index 6be0e93..60f6ca0 100644
--- a/test/Constraints/collection-mutablecollection-order-dependency-1.swift
+++ b/test/Constraints/collection-mutablecollection-order-dependency-1.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 // rdar://problem/29954938 -- A bug in associated type inference exposed an
 // order dependency where, if a type conformed to Collection in one extension
diff --git a/test/Constraints/collection-mutablecollection-order-dependency-1g.swift b/test/Constraints/collection-mutablecollection-order-dependency-1g.swift
index 25fb8c8..64a60b0 100644
--- a/test/Constraints/collection-mutablecollection-order-dependency-1g.swift
+++ b/test/Constraints/collection-mutablecollection-order-dependency-1g.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 // rdar://problem/29954938 -- A bug in associated type inference exposed an
 // order dependency where, if a type conformed to Collection in one extension
diff --git a/test/Constraints/collection-mutablecollection-order-dependency-2.swift b/test/Constraints/collection-mutablecollection-order-dependency-2.swift
index 44b781c..9e1e797 100644
--- a/test/Constraints/collection-mutablecollection-order-dependency-2.swift
+++ b/test/Constraints/collection-mutablecollection-order-dependency-2.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 // rdar://problem/29954938 -- A bug in associated type inference exposed an
 // order dependency where, if a type conformed to Collection in one extension
diff --git a/test/Constraints/collection-mutablecollection-order-dependency-3.swift b/test/Constraints/collection-mutablecollection-order-dependency-3.swift
index 8d21fac..0b681b7 100644
--- a/test/Constraints/collection-mutablecollection-order-dependency-3.swift
+++ b/test/Constraints/collection-mutablecollection-order-dependency-3.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 // rdar://problem/29954938 -- A bug in associated type inference exposed an
 // order dependency where, if a type conformed to Collection in one extension
diff --git a/test/Constraints/collection-of-function.swift b/test/Constraints/collection-of-function.swift
index bec4a60..723c53c 100644
--- a/test/Constraints/collection-of-function.swift
+++ b/test/Constraints/collection-of-function.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 func foo(_:[() -> ()]){}
 func foo(_:[() throws -> ()]){}
diff --git a/test/Constraints/diagnostics_swift4.swift b/test/Constraints/diagnostics_swift4.swift
index 5bfc76d..88ae55b 100644
--- a/test/Constraints/diagnostics_swift4.swift
+++ b/test/Constraints/diagnostics_swift4.swift
@@ -24,8 +24,7 @@
 class C2_2505: P_2505 {
 }
 
-let c_2505 = C_2505(arg: [C2_2505()]) // expected-error {{argument labels '(arg:)' do not match any available overloads}}
-// expected-note@-1 {{overloads for 'C_2505' exist with these partially matching parameter lists: (Any), (from: [T])}}
+let c_2505 = C_2505(arg: [C2_2505()]) // expected-error {{incorrect argument label in call (have 'arg:', expected 'from:')}}
 
 // rdar://problem/31898542 - Swift 4: 'type of expression is ambiguous without more context' errors, without a fixit
 
diff --git a/test/Constraints/dynamic_lookup.swift b/test/Constraints/dynamic_lookup.swift
index a12a9cc..50eaa53 100644
--- a/test/Constraints/dynamic_lookup.swift
+++ b/test/Constraints/dynamic_lookup.swift
@@ -338,6 +338,5 @@
 
 func dynamicInitCrash(ao: AnyObject.Type) {
   let sdk = ao.init(blahblah: ())
-  // expected-error@-1 {{argument labels '(blahblah:)' do not match any available overloads}}
-  // expected-note@-2 {{overloads for 'AnyObject.Type.init' exist with these partially matching parameter lists}}
+  // expected-error@-1 {{incorrect argument label in call (have 'blahblah:', expected 'toMemory:')}}
 }
diff --git a/test/Constraints/inherited_generic_conformance.swift b/test/Constraints/inherited_generic_conformance.swift
index cb5e9cc..99ce6b1 100644
--- a/test/Constraints/inherited_generic_conformance.swift
+++ b/test/Constraints/inherited_generic_conformance.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 protocol P {}
 
diff --git a/test/Constraints/keyword_arguments.swift b/test/Constraints/keyword_arguments.swift
index ee440ee..7440b15 100644
--- a/test/Constraints/keyword_arguments.swift
+++ b/test/Constraints/keyword_arguments.swift
@@ -8,7 +8,9 @@
   init(_ a: Int) { }
   func f1(_ a: Int) {}
 }
-X1(a: 5).f1(b: 5) // expected-error{{extraneous argument label 'a:' in call}}{{4-7=}}
+X1(a: 5).f1(b: 5) 
+// expected-error@-1 {{extraneous argument label 'a:' in call}} {{4-7=}}
+// expected-error@-2 {{extraneous argument label 'b:' in call}} {{13-16=}}
 
 // <rdar://problem/16801056>
 enum Policy {
@@ -33,7 +35,9 @@
   init(a: Int) { }
   func f2(b: Int) { }
 }
-X2(5).f2(5) // expected-error{{missing argument label 'a:' in call}}{{4-4=a: }}
+X2(5).f2(5)
+// expected-error@-1 {{missing argument label 'a:' in call}} {{4-4=a: }}
+// expected-error@-2 {{missing argument label 'b:' in call}} {{10-10=b: }}
 
 
 // -------------------------------------------
@@ -401,3 +405,8 @@
 _ = acceptTuple2((1, "hello", 3.14159))
 
 
+func generic_and_missing_label(x: Int) {}
+func generic_and_missing_label<T>(x: T) {}
+
+generic_and_missing_label(42)
+// expected-error@-1 {{missing argument label 'x:' in call}} {{27-27=x: }}
diff --git a/test/Constraints/openExistential.swift b/test/Constraints/openExistential.swift
index e4fb185..a50d1ef 100644
--- a/test/Constraints/openExistential.swift
+++ b/test/Constraints/openExistential.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 protocol P { }
 
diff --git a/test/Constraints/optional.swift b/test/Constraints/optional.swift
index fc16857..1948c7d 100644
--- a/test/Constraints/optional.swift
+++ b/test/Constraints/optional.swift
@@ -209,7 +209,7 @@
 var sr3248 : ((Int) -> ())!
 sr3248?(a: 2) // expected-error {{extraneous argument label 'a:' in call}}
 sr3248!(a: 2) // expected-error {{extraneous argument label 'a:' in call}}
-sr3248(a: 2)  // expected-error {{cannot call value of non-function type '((Int) -> ())?'}}
+sr3248(a: 2)  // expected-error {{extraneous argument label 'a:' in call}}
 
 struct SR_3248 {
     var callback: (([AnyObject]) -> Void)!
diff --git a/test/Constraints/suspicious_bit_casts.swift b/test/Constraints/suspicious_bit_casts.swift
index 56b8e67..5e5148d 100644
--- a/test/Constraints/suspicious_bit_casts.swift
+++ b/test/Constraints/suspicious_bit_casts.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 func escapeByBitCast(f: () -> ()) -> () -> () {
   return unsafeBitCast(f, to: (() -> ()).self)
diff --git a/test/Constraints/trailing_closures_objc.swift b/test/Constraints/trailing_closures_objc.swift
index ecea125..57f4b7c 100644
--- a/test/Constraints/trailing_closures_objc.swift
+++ b/test/Constraints/trailing_closures_objc.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 // REQUIRES: objc_interop
 // REQUIRES: OS=macosx
diff --git a/test/FixCode/fixits-apply-objc.swift b/test/FixCode/fixits-apply-objc.swift
index f895435..358c692 100644
--- a/test/FixCode/fixits-apply-objc.swift
+++ b/test/FixCode/fixits-apply-objc.swift
@@ -4,15 +4,6 @@
 
 // REQUIRES: objc_interop
 
-@objc class Selectors {
-  func takeSel(_: Selector) {}
-  func mySel() {}
-  func test() {
-    takeSel("mySel")
-    takeSel(Selector("mySel"))
-  }
-}
-
 func foo(an : Any) {
   let a1 : AnyObject
   a1 = an
diff --git a/test/FixCode/fixits-apply-objc.swift.result b/test/FixCode/fixits-apply-objc.swift.result
index c108825..8973406 100644
--- a/test/FixCode/fixits-apply-objc.swift.result
+++ b/test/FixCode/fixits-apply-objc.swift.result
@@ -4,15 +4,6 @@
 
 // REQUIRES: objc_interop
 
-@objc class Selectors {
-  func takeSel(_: Selector) {}
-  func mySel() {}
-  func test() {
-    takeSel(#selector(Selectors.mySel))
-    takeSel(#selector(Selectors.mySel))
-  }
-}
-
 func foo(an : Any) {
   let a1 : AnyObject
   a1 = an as AnyObject
diff --git a/test/IDE/complete_pound_keypath.swift b/test/IDE/complete_pound_keypath.swift
index 78f2a91..6e64791 100644
--- a/test/IDE/complete_pound_keypath.swift
+++ b/test/IDE/complete_pound_keypath.swift
@@ -41,6 +41,5 @@
 // CHECK-IN_KEYPATH: Decl[InstanceVar]/CurrNominal:      prop1[#String#]; name=prop1
 // CHECK-IN_KEYPATH: Decl[InstanceVar]/CurrNominal:      prop2[#ObjCClass?#]; name=prop2
 // CHECK-IN_KEYPATH: Decl[InstanceVar]/Super:            hashValue[#Int#]; name=hashValue
-// CHECK-IN_KEYPATH: Decl[InstanceVar]/Super:            hash[#Int#]; name=hash
 
 
diff --git a/test/IDE/complete_unresolved_members.swift b/test/IDE/complete_unresolved_members.swift
index cb419f5..18b537b 100644
--- a/test/IDE/complete_unresolved_members.swift
+++ b/test/IDE/complete_unresolved_members.swift
@@ -207,7 +207,7 @@
   OptionSetTaker5([.#^UNRESOLVED_18^#], .Option4, .South, .West)
 }
 var Container = OptionTakerContainer1()
-Container.OptionSetTaker1(.#^UNRESOLVED_19^#
+Container.OptionSetTaker1(.#^UNRESOLVED_19^#)
 Container.EnumTaker1(.#^UNRESOLVED_20^#
 
 func parserSync() {}
diff --git a/test/IRGen/cf.sil b/test/IRGen/cf.sil
index 7916e58..3dedb89 100644
--- a/test/IRGen/cf.sil
+++ b/test/IRGen/cf.sil
@@ -21,7 +21,7 @@
 
 // CHECK-64: @"$SSo24CCMutableRefrigeratorRefaMn" = linkonce_odr hidden constant
 // -- is imported C typedef, is class, is nonunique
-// CHECK-64-SAME: <i32 0x0006_0010>
+// CHECK-64-SAME: <i32 0x0011_0010>
 // CHECK-64-SAME: [[MUTABLE_REFRIGERATOR_NAME]]
 
 // CHECK-64: @"$SSo24CCMutableRefrigeratorRefaN" = linkonce_odr hidden global <{ {{.*}} }> <{
diff --git a/test/IRGen/class_metadata.swift b/test/IRGen/class_metadata.swift
index e1c978b..f885543 100644
--- a/test/IRGen/class_metadata.swift
+++ b/test/IRGen/class_metadata.swift
@@ -4,8 +4,8 @@
 
 // CHECK:      [[A_NAME:@.*]] = private constant [2 x i8] c"A\00"
 // CHECK-LABEL: @"$S14class_metadata1ACMn" =
-//   Flags. -2147221424 == 0x8004_0050 == HasVTable | Reflectable | Unique | Class
-// CHECK-SAME: i32 -2147221424,
+//   Flags. -2147418032 == 0x8001_0050 == HasVTable | Reflectable | Unique | Class
+// CHECK-SAME: i32 -2147418032,
 //   Parent.
 // CHECK-SAME: i32 {{.*}} @"$S14class_metadataMXM"
 //   Name.
@@ -33,8 +33,8 @@
 
 // CHECK:      [[B_NAME:@.*]] = private constant [2 x i8] c"B\00"
 // CHECK-LABEL: @"$S14class_metadata1BCMn" =
-//   Flags. 262224 == 0x0004_0050 == Reflectable | Unique | Class
-// CHECK-SAME: i32 262224,
+//   Flags. 65616 == 0x0001_0050 == Reflectable | Unique | Class
+// CHECK-SAME: i32 65616,
 //   Parent.
 // CHECK-SAME: i32 {{.*}} @"$S14class_metadataMXM"
 //   Name.
@@ -53,8 +53,8 @@
 
 // CHECK:      [[C_NAME:@.*]] = private constant [2 x i8] c"C\00"
 // CHECK-LABEL: @"$S14class_metadata1CCMn" =
-//   Flags. 262352 == 0x0004_00d0 == Reflectable | Generic | Unique | Class
-// CHECK-SAME: i32 262352,
+//   Flags. 65744 == 0x0001_00d0 == Reflectable | Generic | Unique | Class
+// CHECK-SAME: i32 65744,
 //   Parent.
 // CHECK-SAME: i32 {{.*}} @"$S14class_metadataMXM"
 //   Name.
@@ -104,8 +104,8 @@
 
 // CHECK:      [[D_NAME:@.*]] = private constant [2 x i8] c"D\00"
 // CHECK-LABEL: @"$S14class_metadata1DCMn" =
-//   Flags. 268697680 == 0x1004_0050 == Reflectable | IndirectSuperclass | Unique | Class
-// CHECK-SAME: i32 268697680,
+//   Flags. 268501072 == 0x1001_0050 == Reflectable | IndirectSuperclass | Unique | Class
+// CHECK-SAME: i32 268501072,
 //   Parent.
 // CHECK-SAME: i32 {{.*}} @"$S14class_metadataMXM"
 //   Name.
diff --git a/test/IRGen/class_resilience.swift b/test/IRGen/class_resilience.swift
index cb55adb..e53779a 100644
--- a/test/IRGen/class_resilience.swift
+++ b/test/IRGen/class_resilience.swift
@@ -32,7 +32,7 @@
 
 // CHECK: @"$S16class_resilience14ResilientChildCMn" = {{(protected )?}}{{(dllexport )?}}constant <{{.*}}> <{
 // --       flags: class, unique, reflectable, has vtable, has resilient superclass
-// CHECK-SAME:   <i32 0xD004_0050>
+// CHECK-SAME:   <i32 0xD001_0050>
 // --       name:
 // CHECK-SAME:   [15 x i8]* [[RESILIENTCHILD_NAME]]
 // --       num fields
diff --git a/test/IRGen/enum_resilience.swift b/test/IRGen/enum_resilience.swift
index 60e4964..eeefa58 100644
--- a/test/IRGen/enum_resilience.swift
+++ b/test/IRGen/enum_resilience.swift
@@ -48,12 +48,12 @@
 // CHECK-SAME: internal global { %swift.type*, i8* } zeroinitializer, align
 
 // CHECK: @"$S15enum_resilience24EnumWithResilientPayloadOMn" = {{.*}}constant
-//   1310802 == 0x00140052
-//              0x0010      - HasInPlaceMetadataInitialization
-//              0x0014      - IsReflectable
+//    196690 == 0x00030052
+//              0x0002      - InPlaceMetadataInitialization
+//              0x0001      - IsReflectable
 //              0x    0040  - IsUnique
 //              0x    0012  - Enum
-// CHECK-SAME: i32 1310802,
+// CHECK-SAME: i32 196690,
 // CHECK-SAME: @"$S15enum_resilience24EnumWithResilientPayloadOMl"
 // CHECK-SAME: @"$S15enum_resilience24EnumWithResilientPayloadOMf", i32 0, i32 1)
 // CHECK-SAME: @"$S15enum_resilience24EnumWithResilientPayloadOMr"
diff --git a/test/IRGen/generic_classes.sil b/test/IRGen/generic_classes.sil
index ee40441..2c7c86a 100644
--- a/test/IRGen/generic_classes.sil
+++ b/test/IRGen/generic_classes.sil
@@ -16,7 +16,7 @@
 
 // CHECK-LABEL: @"$S15generic_classes11RootGenericCMn" =
 // --       flags: class, generic, unique, reflectable, has vtable
-// CHECK-SAME:   <i32 0x8004_00D0>
+// CHECK-SAME:   <i32 0x8001_00D0>
 // --       name
 // CHECK-SAME:   [12 x i8]* [[ROOTGENERIC_NAME]]
 // --       negative size in words
@@ -80,7 +80,7 @@
 // CHECK: [[ROOTNONGENERIC_NAME:@.*]] = private constant [15 x i8] c"RootNonGeneric\00"
 // CHECK: @"$S15generic_classes14RootNonGenericCMn" = hidden constant <{ {{.*}} %swift.method_descriptor }> <{
 // --       flags: class, unique, has vtable, reflectable
-// CHECK-SAME:   <i32 0x8004_0050>
+// CHECK-SAME:   <i32 0x8001_0050>
 // --       name
 // CHECK-SAME:   [15 x i8]* [[ROOTNONGENERIC_NAME]]
 // --       num fields
diff --git a/test/IRGen/generic_structs.sil b/test/IRGen/generic_structs.sil
index b82b53f..152856b 100644
--- a/test/IRGen/generic_structs.sil
+++ b/test/IRGen/generic_structs.sil
@@ -39,7 +39,7 @@
 // CHECK: [[SINGLEDYNAMIC_NAME:@.*]] = private constant [14 x i8] c"SingleDynamic\00"
 // CHECK: @"$S15generic_structs13SingleDynamicVMn" = hidden constant 
 // --       flags: struct, unique, generic, reflectable
-// CHECK-SAME:   <i32 0x0004_00D1>
+// CHECK-SAME:   <i32 0x0001_00D1>
 // --       name
 // CHECK-SAME:   [14 x i8]* [[SINGLEDYNAMIC_NAME]]
 // --       field count
@@ -65,7 +65,7 @@
 // CHECK: [[DYNAMICWITHREQUIREMENTS_NAME:@.*]] = private constant [24 x i8] c"DynamicWithRequirements\00"
 // CHECK: @"$S15generic_structs23DynamicWithRequirementsVMn" = hidden constant <{ {{.*}} i32 }> <{
 // --       flags: struct, unique, generic, reflectable
-// CHECK-SAME:   <i32 0x0004_00D1>
+// CHECK-SAME:   <i32 0x0001_00D1>
 // --       name
 // CHECK-SAME: [24 x i8]* [[DYNAMICWITHREQUIREMENTS_NAME]]
 // --       field count
diff --git a/test/IRGen/generic_types.swift b/test/IRGen/generic_types.swift
index 7902ae4..f0f3fe6 100644
--- a/test/IRGen/generic_types.swift
+++ b/test/IRGen/generic_types.swift
@@ -11,7 +11,7 @@
 // CHECK-LABEL: @"$S13generic_types1ACMI" = internal global [16 x i8*] zeroinitializer, align 8
 
 // CHECK-LABEL: @"$S13generic_types1ACMn" = hidden constant
-// CHECK-SAME:   i32 -2147221296,
+// CHECK-SAME:   i32 -2147417904,
 // CHECK-SAME:   @"$S13generic_typesMXM"
 //               <name>
 // CHECK-SAME:   @"$S13generic_types1ACMa"
diff --git a/test/IRGen/generic_vtable.swift b/test/IRGen/generic_vtable.swift
index f0b2800..298789a 100644
--- a/test/IRGen/generic_vtable.swift
+++ b/test/IRGen/generic_vtable.swift
@@ -24,7 +24,7 @@
 
 // CHECK-LABEL: @"$S14generic_vtable4BaseCMn" = {{(dllexport )?}}{{(protected )?}}constant
 // -- flags: has vtable, reflectable, is class, is unique
-// CHECK-SAME: <i32 0x8004_0050>,
+// CHECK-SAME: <i32 0x8001_0050>,
 // -- vtable offset
 // CHECK-SAME: i32 10,
 // -- vtable size
@@ -49,7 +49,7 @@
 
 // CHECK-LABEL: @"$S14generic_vtable7DerivedCMn" = {{(dllexport )?}}{{(protected )?}}constant
 // -- flags: has vtable, reflectable, is class, is unique, is generic
-// CHECK-SAME: <i32 0x8004_00D0>,
+// CHECK-SAME: <i32 0x8001_00D0>,
 // -- vtable offset
 // CHECK-SAME: i32 14,
 // -- vtable size
@@ -73,7 +73,7 @@
 
 // CHECK-LABEL: @"$S14generic_vtable8ConcreteCMn" = {{(dllexport )?}}{{(protected )?}}constant
 // -- flags: has vtable, reflectable, is class, is unique
-// CHECK-SAME: <i32 0x8004_0050>,
+// CHECK-SAME: <i32 0x8001_0050>,
 // -- vtable offset
 // CHECK-SAME: i32 15,
 // -- vtable size
diff --git a/test/NameBinding/dynamic-member-lookup.swift b/test/NameBinding/dynamic-member-lookup.swift
index d89e097..3e1546b 100644
--- a/test/NameBinding/dynamic-member-lookup.swift
+++ b/test/NameBinding/dynamic-member-lookup.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 var global = 42
 
 @dynamicMemberLookup
diff --git a/test/Parse/deprecated_where.swift b/test/Parse/deprecated_where.swift
index 9388822..8878b38 100644
--- a/test/Parse/deprecated_where.swift
+++ b/test/Parse/deprecated_where.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s -swift-version 4
+// RUN: %target-typecheck-verify-swift -swift-version 4
 
 protocol Mashable { }
 protocol Womparable { }
diff --git a/test/SILGen/statements.swift b/test/SILGen/statements.swift
index 6a26304..6d2c341 100644
--- a/test/SILGen/statements.swift
+++ b/test/SILGen/statements.swift
@@ -524,7 +524,7 @@
   // CHECK-LABEL: sil private @$S10statements017defer_in_closure_C8_genericyyxlFyycfU_ : $@convention(thin) <T> () -> ()
   _ = {
     // CHECK-LABEL: sil private @$S10statements017defer_in_closure_C8_genericyyxlFyycfU_6$deferL_yylF : $@convention(thin) <T> () -> ()
-    defer { generic_callee_1(T.self) }
+    defer { generic_callee_1(T.self) } // expected-warning {{'defer' statement before end of scope always executes immediately}}{{5-10=do}}
   }
 }
 
@@ -537,7 +537,7 @@
   // CHECK: function_ref @$S10statements13defer_mutableyySiF6$deferL_yyF : $@convention(thin) (@inout_aliasable Int) -> ()
   // CHECK-NOT: [[BOX]]
   // CHECK: destroy_value [[BOX]]
-  defer { _ = x }
+  defer { _ = x } // expected-warning {{'defer' statement before end of scope always executes immediately}}{{3-8=do}}
 }
 
 protocol StaticFooProtocol { static func foo() }
diff --git a/test/SILOptimizer/definite_init_diagnostics_globals.swift b/test/SILOptimizer/definite_init_diagnostics_globals.swift
index da5db23..6c5aec4 100644
--- a/test/SILOptimizer/definite_init_diagnostics_globals.swift
+++ b/test/SILOptimizer/definite_init_diagnostics_globals.swift
@@ -21,7 +21,7 @@
 // Test top-level functions.
 
 func testFunc() {       // expected-error {{variable 'x' used by function definition before being initialized}}
-  defer { print(x) }
+  defer { print(x) }    // expected-warning {{'defer' statement before end of scope always executes immediately}}{{3-8=do}}
 }
 
 // Test top-level closures.
diff --git a/test/SILOptimizer/unreachable_code.swift b/test/SILOptimizer/unreachable_code.swift
index 84ab7f5..be82600 100644
--- a/test/SILOptimizer/unreachable_code.swift
+++ b/test/SILOptimizer/unreachable_code.swift
@@ -328,7 +328,7 @@
 }
 
 func noReturnInDefer() {
-  defer {
+  defer { // expected-warning {{'defer' statement before end of scope always executes immediately}}{{3-8=do}}
     _ = Lisp()
     die() // expected-note {{a call to a never-returning function}}
     die() // expected-warning {{will never be executed}}
diff --git a/test/Sema/diag_defer_block_end.swift b/test/Sema/diag_defer_block_end.swift
new file mode 100644
index 0000000..80f9cc6
--- /dev/null
+++ b/test/Sema/diag_defer_block_end.swift
@@ -0,0 +1,23 @@
+// RUN: %target-typecheck-verify-swift
+
+let x = 1
+let y = 2
+if (x > y) {
+    defer { // expected-warning {{'defer' statement before end of scope always executes immediately}}{{5-10=do}}
+        print("not so useful defer stmt.")
+    }
+}
+
+func sr7307(_ value: Bool) {
+    let negated = !value 
+    defer { // expected-warning {{'defer' statement before end of scope always executes immediately}}{{5-10=do}}
+        print("negated value is {negated}")
+    }
+}
+
+sr7307(true)
+
+defer { // No note
+    print("end of program.")
+}
+
diff --git a/test/Sema/diag_defer_captures.swift b/test/Sema/diag_defer_captures.swift
index 24f8ecd..1f04272 100644
--- a/test/Sema/diag_defer_captures.swift
+++ b/test/Sema/diag_defer_captures.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 // This used to crash in SILGen (rightly so).
 func sr3210_crash() {
diff --git a/test/Sema/diag_express_tuple.swift b/test/Sema/diag_express_tuple.swift
index cb8ea32..7253e1b 100644
--- a/test/Sema/diag_express_tuple.swift
+++ b/test/Sema/diag_express_tuple.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 func foo(a : [(some: Int, (key: Int, value: String))]) -> String {
   for (i , (j, k)) in a { // expected-error {{cannot express tuple conversion '(some: Int, (key: Int, value: String))' to '(Int, (Int, String))'}}{8-8=some: }} {{13-13=key: }} {{16-16=value: }}
diff --git a/test/Sema/diag_use_before_declaration.swift b/test/Sema/diag_use_before_declaration.swift
index 2bbef02..ecef5b2 100644
--- a/test/Sema/diag_use_before_declaration.swift
+++ b/test/Sema/diag_use_before_declaration.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 // SR-5163
 func sr5163() {
diff --git a/test/Sema/diag_variable_used_in_initial.swift b/test/Sema/diag_variable_used_in_initial.swift
index 10e5876..711ed41 100644
--- a/test/Sema/diag_variable_used_in_initial.swift
+++ b/test/Sema/diag_variable_used_in_initial.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 class A1 {
   func foo1() {}
diff --git a/test/Sema/enum_raw_representable_explicit.swift b/test/Sema/enum_raw_representable_explicit.swift
index d06108e..eceec84 100644
--- a/test/Sema/enum_raw_representable_explicit.swift
+++ b/test/Sema/enum_raw_representable_explicit.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 enum Foo: Int, RawRepresentable { case A }
 
diff --git a/test/Sema/enum_raw_representable_explicit_cart_before_horse.swift b/test/Sema/enum_raw_representable_explicit_cart_before_horse.swift
index 09d6ed5..7058411 100644
--- a/test/Sema/enum_raw_representable_explicit_cart_before_horse.swift
+++ b/test/Sema/enum_raw_representable_explicit_cart_before_horse.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 enum Foo: Int { case A }
 extension Foo: RawRepresentable {}
diff --git a/test/Sema/enum_raw_representable_explicit_multi_file.swift b/test/Sema/enum_raw_representable_explicit_multi_file.swift
index c16a4f4..1d18981 100644
--- a/test/Sema/enum_raw_representable_explicit_multi_file.swift
+++ b/test/Sema/enum_raw_representable_explicit_multi_file.swift
@@ -1,5 +1,5 @@
 // RUN: %target-swift-frontend -typecheck -primary-file %s %S/Inputs/enum_raw_representable_explicit_multi_file_2.swift
-// RUN: %target-swift-frontend -typecheck -verify %s -primary-file %S/Inputs/enum_raw_representable_explicit_multi_file_2.swift
+// RUN: %target-typecheck-verify-swift -primary-file %S/Inputs/enum_raw_representable_explicit_multi_file_2.swift
 
 enum Foo: Int { case A }
 
diff --git a/test/attr/attr_implements_bad_types.swift b/test/attr/attr_implements_bad_types.swift
index a79433b..b5cc34f 100644
--- a/test/attr/attr_implements_bad_types.swift
+++ b/test/attr/attr_implements_bad_types.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 protocol NeedsF0 {
   func f0() // expected-note {{protocol requires function 'f0()' with type '() -> ()'; do you want to add a stub?}}
diff --git a/test/attr/attr_indirect.swift b/test/attr/attr_indirect.swift
index 6e6f202..a8aa8ac 100644
--- a/test/attr/attr_indirect.swift
+++ b/test/attr/attr_indirect.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 enum Foo<T> {
   indirect case A // expected-error{{enum case 'A' without associated value cannot be 'indirect'}}
diff --git a/test/attr/attr_objc_any.swift b/test/attr/attr_objc_any.swift
index b18690e..f7a9485 100644
--- a/test/attr/attr_objc_any.swift
+++ b/test/attr/attr_objc_any.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 // REQUIRES: objc_interop
 
 import Foundation
diff --git a/test/decl/ext/extension-generic-objc.swift b/test/decl/ext/extension-generic-objc.swift
index 9ff55cc..1314112 100644
--- a/test/decl/ext/extension-generic-objc.swift
+++ b/test/decl/ext/extension-generic-objc.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 // REQUIRES: objc_interop
 
diff --git a/test/decl/ext/extension-inheritance-conformance-native.swift b/test/decl/ext/extension-inheritance-conformance-native.swift
index 91d0c1e..0bf9ecf 100644
--- a/test/decl/ext/extension-inheritance-conformance-native.swift
+++ b/test/decl/ext/extension-inheritance-conformance-native.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 class Object {}
 class Responder: Object {}
diff --git a/test/decl/func/rethrows.swift b/test/decl/func/rethrows.swift
index 0a00fc2..86ca746 100644
--- a/test/decl/func/rethrows.swift
+++ b/test/decl/func/rethrows.swift
@@ -551,3 +551,36 @@
 public func rdar40472018() {
   variadic_rethrows(1, 2) { _ in }
 }
+
+
+// https://bugs.swift.org/browse/SR-6299
+// Verify that we do not emit an invalid
+//   "... can throw but the expression is not marked with 'try'"
+// error on the use of the operators.
+
+infix operator <|: infixr0
+infix operator |>: infixl1
+
+precedencegroup infixr0 {
+  associativity: right
+}
+precedencegroup infixl1 {
+  associativity: left
+  higherThan: infixr0
+}
+
+func <| <A, B> (f: (A) throws -> B, a: A) rethrows -> B {
+  return try f(a)
+}
+func |> <A, B> (a: A, f: (A) -> B) -> B {
+  return try f(a) // expected-warning {{no calls to throwing functions occur within 'try' expression}}
+}
+
+struct Box<A> {
+  let unbox: A
+}
+func suchThat<A>(_ x: Box<A>) -> (@escaping (A) -> A) -> Box<A> {
+  return { f in Box(unbox: f(x.unbox)) }
+}
+
+Box(unbox: 1) |> suchThat <| { $0 + 1 } // expected-warning {{result of operator '<|' is unused}}
diff --git a/test/decl/inherit/initializer.swift b/test/decl/inherit/initializer.swift
index ca43ee4..98f3790 100644
--- a/test/decl/inherit/initializer.swift
+++ b/test/decl/inherit/initializer.swift
@@ -58,8 +58,7 @@
 
 func testNotInherited1() {
   var n1 = NotInherited1(int: 5)
-  var n2 = NotInherited1(double: 2.71828) // expected-error{{argument labels '(double:)' do not match any available overloads}}
-  // expected-note @-1 {{overloads for 'NotInherited1' exist with these partially matching parameter lists: (int: Int), (float: Float)}}
+  var n2 = NotInherited1(double: 2.71828) // expected-error{{incorrect argument label in call (have 'double:', expected 'float:')}}
 }
 
 class NotInherited1Sub : NotInherited1 {
@@ -71,8 +70,7 @@
 func testNotInherited1Sub() {
   var n1 = NotInherited1Sub(int: 5)
   var n2 = NotInherited1Sub(float: 3.14159)
-  var n3 = NotInherited1Sub(double: 2.71828) // expected-error{{argument labels '(double:)' do not match any available overloads}}
-  // expected-note @-1 {{overloads for 'NotInherited1Sub' exist with these partially matching parameter lists: (int: Int), (float: Float)}}
+  var n3 = NotInherited1Sub(double: 2.71828) // expected-error{{incorrect argument label in call (have 'double:', expected 'float:')}}
 }
 
 // Having a stored property without an initial value prevents
diff --git a/test/decl/protocol/conforms/access_corner_case.swift b/test/decl/protocol/conforms/access_corner_case.swift
index ef68572..f5aef4b 100644
--- a/test/decl/protocol/conforms/access_corner_case.swift
+++ b/test/decl/protocol/conforms/access_corner_case.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 
 // Protocol requirement is witnessed from a member of a
diff --git a/test/decl/protocol/conforms/near_miss_objc.swift b/test/decl/protocol/conforms/near_miss_objc.swift
index 52476e8..ddb534c 100644
--- a/test/decl/protocol/conforms/near_miss_objc.swift
+++ b/test/decl/protocol/conforms/near_miss_objc.swift
@@ -10,7 +10,7 @@
 class C1a : P1 {
   @objc func doSomething(a: Int, c: Double) { }
   // expected-warning@-1{{instance method 'doSomething(a:c:)' nearly matches optional requirement 'doSomething(a:b:)' of protocol 'P1'}}
-  // expected-note@-2{{rename to 'doSomething(a:b:)' to satisfy this requirement}}{{34-34=b }}{{none}}
+  // expected-note@-2{{rename to 'doSomething(a:b:)' to satisfy this requirement}}{{34-34=b }}{{8-8=(doSomethingWithA:b:)}} {{34-34=b }}
   // expected-note@-3{{move 'doSomething(a:c:)' to an extension to silence this warning}}
   // expected-note@-4{{make 'doSomething(a:c:)' private to silence this warning}}{{9-9=private }}
 }
diff --git a/test/expr/capture/noescape-error.swift b/test/expr/capture/noescape-error.swift
index 452c07a..ea8fcbd 100644
--- a/test/expr/capture/noescape-error.swift
+++ b/test/expr/capture/noescape-error.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 class C {}
 class D {}
diff --git a/test/expr/closure/let.swift b/test/expr/closure/let.swift
index 6664df8..6afbf9c 100644
--- a/test/expr/closure/let.swift
+++ b/test/expr/closure/let.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 func frob(x: inout Int) {}
 
diff --git a/test/expr/postfix/dot/init_ref_delegation.swift b/test/expr/postfix/dot/init_ref_delegation.swift
index d12742f..938302d 100644
--- a/test/expr/postfix/dot/init_ref_delegation.swift
+++ b/test/expr/postfix/dot/init_ref_delegation.swift
@@ -294,8 +294,7 @@
   var cs2 = T.init(x: 0) // expected-error{{'required' initializer}}
   var cs3 = T.init() // expected-error{{'required' initializer}}
   var cs4 = T.init(proto: "")
-  var cs5 = T.init(notfound: "") // expected-error{{argument labels '(notfound:)' do not match any available overloads}}
-  // expected-note @-1 {{overloads for 'T.Type.init' exist with these partially matching parameter lists: (x: Int), (required: Double), (proto: String)}}
+  var cs5 = T.init(notfound: "") // expected-error{{incorrect argument label in call (have 'notfound:', expected 'proto:')}}
 
   var csf1: (Double) -> T = T.init
   var csf2: (Int) -> T    = T.init // expected-error{{'required' initializer}}
diff --git a/test/expr/primary/selector/Inputs/fixits_helper.swift b/test/expr/primary/selector/Inputs/fixits_helper.swift
new file mode 100644
index 0000000..3b47dcd
--- /dev/null
+++ b/test/expr/primary/selector/Inputs/fixits_helper.swift
@@ -0,0 +1,27 @@
+import Foundation
+
+public class Bar : Foo {
+  @objc(method2WithValue:) public override func method2(_ value: Int) { }
+
+  @objc(overloadedWithInt:) public func overloaded(_ x: Int) { }
+  @objc(overloadedWithString:) public func overloaded(_ x: String) { }
+
+  @objc(staticOverloadedWithInt:) public static func staticOverloaded(_ x: Int) { }
+  @objc(staticOverloadedWithString:) public static func staticOverloaded(_ x: String) { }
+
+  @objc(staticOrNonStatic:) public func staticOrNonStatic(_ x: Int) { }
+  @objc(staticOrNonStatic:) public static func staticOrNonStatic(_ x: Int) { }
+
+  @objc(theInstanceOne:) public func staticOrNonStatic2(_ x: Int) { }
+  @objc(theStaticOne:) public static func staticOrNonStatic2(_ x: Int) { }
+}
+
+public class Foo {
+  @objc(methodWithValue:label:) public func method(_ value: Int, label: String) { }
+
+  @objc(method2WithValue:) public func method2(_ value: Int) { }
+
+  @objc public func method3() { }
+
+  @objc public var property: String = ""
+}
diff --git a/test/expr/primary/selector/fixits.swift b/test/expr/primary/selector/fixits.swift
index 088a9d9..48be3f4 100644
--- a/test/expr/primary/selector/fixits.swift
+++ b/test/expr/primary/selector/fixits.swift
@@ -9,6 +9,8 @@
 // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-module -o %t.overlays %clang-importer-sdk-path/swift-modules/Foundation.swift
 // FIXME: END -enable-source-import hackaround
 
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-module -o %t.overlays %S/Inputs/fixits_helper.swift -module-name Helper
+
 // Make sure we get the right diagnostics.
 // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t.overlays) -typecheck %s -verify
 
@@ -29,33 +31,7 @@
 // CHECK: warning: string literal is not a valid Objective-C selector
 
 import Foundation
-
-class Bar : Foo {
-  @objc(method2WithValue:) override func method2(_ value: Int) { }
-
-  @objc(overloadedWithInt:) func overloaded(_ x: Int) { }
-  @objc(overloadedWithString:) func overloaded(_ x: String) { }
-
-  @objc(staticOverloadedWithInt:) static func staticOverloaded(_ x: Int) { }
-  @objc(staticOverloadedWithString:) static func staticOverloaded(_ x: String) { }
-
-  @objc(staticOrNonStatic:) func staticOrNonStatic(_ x: Int) { }
-  @objc(staticOrNonStatic:) static func staticOrNonStatic(_ x: Int) { }
-
-  @objc(theInstanceOne:) func staticOrNonStatic2(_ x: Int) { }
-  @objc(theStaticOne:) static func staticOrNonStatic2(_ x: Int) { }
-}
-
-class Foo {
-  @objc(methodWithValue:label:) func method(_ value: Int, label: String) { }
-
-  @objc(method2WithValue:) func method2(_ value: Int) { }
-
-  @objc func method3() { }
-
-  @objc var property: String = ""
-}
-
+import Helper
 
 func testDeprecatedStringLiteralSelector() {
   let sel1: Selector = "methodWithValue:label:" // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' instead}}{{24-48=#selector(Foo.method(_:label:))}}
diff --git a/test/expr/unary/keypath/keypath-mutation.swift b/test/expr/unary/keypath/keypath-mutation.swift
index 0d135fc..4ee6944 100644
--- a/test/expr/unary/keypath/keypath-mutation.swift
+++ b/test/expr/unary/keypath/keypath-mutation.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 struct User {
   var id: Int
diff --git a/test/expr/unary/keypath/keypath-unimplemented.swift b/test/expr/unary/keypath/keypath-unimplemented.swift
index 4791e87..2e2bc66 100644
--- a/test/expr/unary/keypath/keypath-unimplemented.swift
+++ b/test/expr/unary/keypath/keypath-unimplemented.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 struct A {
   subscript(x: Int) -> Int { return x }
diff --git a/test/expr/unary/keypath/keypath.swift b/test/expr/unary/keypath/keypath.swift
index d3a11d2..9a4324c 100644
--- a/test/expr/unary/keypath/keypath.swift
+++ b/test/expr/unary/keypath/keypath.swift
@@ -652,6 +652,13 @@
   testSubtypeKeypathProtocol(\Base.i) // expected-error {{type 'PP' has no member 'i'}}
 }
 
+// rdar://problem/32057712
+struct Container {
+  let base: Base? = Base()
+}
+
+var rdar32057712 = \Container.base?.i
+
 func testSyntaxErrors() { // expected-note{{}}
   _ = \.  ; // expected-error{{expected member name following '.'}}
   _ = \.a ;
diff --git a/test/expr/unary/keypath/salvage-with-other-type-errors.swift b/test/expr/unary/keypath/salvage-with-other-type-errors.swift
index 7a6af78..a564c2a 100644
--- a/test/expr/unary/keypath/salvage-with-other-type-errors.swift
+++ b/test/expr/unary/keypath/salvage-with-other-type-errors.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 // Ensure that key path exprs can tolerate being re-type-checked when necessary
 // to diagnose other errors in adjacent exprs.
diff --git a/test/multifile/Inputs/require-layout-call-result-primary.swift b/test/multifile/Inputs/require-layout-call-result-primary.swift
new file mode 100644
index 0000000..ff9d3e5
--- /dev/null
+++ b/test/multifile/Inputs/require-layout-call-result-primary.swift
@@ -0,0 +1,4 @@
+func foo<T, U: C<T>>(_ t: T, _ u: U) {
+  // Calling a function that returns a C<T> requests its layout
+  _ = bar(t, u)
+}
diff --git a/test/multifile/Inputs/require-member-layout-dynamic-bridging.h b/test/multifile/Inputs/require-member-layout-dynamic-bridging.h
new file mode 100644
index 0000000..9d8c741
--- /dev/null
+++ b/test/multifile/Inputs/require-member-layout-dynamic-bridging.h
@@ -0,0 +1,5 @@
+@import Foundation;
+
+@interface NSObject(Testing)
+-(void)bar:(nonnull NSString *)param;
+@end
diff --git a/test/multifile/Inputs/require-member-layout-dynamic-other.swift b/test/multifile/Inputs/require-member-layout-dynamic-other.swift
new file mode 100644
index 0000000..1d593b6
--- /dev/null
+++ b/test/multifile/Inputs/require-member-layout-dynamic-other.swift
@@ -0,0 +1,5 @@
+import Foundation
+
+extension Foo {
+  open override func bar(_: String) { }
+}
diff --git a/test/multifile/require-layout-call-result.swift b/test/multifile/require-layout-call-result.swift
new file mode 100644
index 0000000..db8b11f
--- /dev/null
+++ b/test/multifile/require-layout-call-result.swift
@@ -0,0 +1,8 @@
+// RUN: %target-typecheck-verify-swift -module-name test -primary-file %S/Inputs/require-layout-call-result-primary.swift
+
+
+class C<T> {
+  dynamic func broken() { } // expected-error{{'dynamic'}}
+}
+
+func bar<T, U: C<T>>(_ t: T, _ u: U) -> C<T> { return u }
diff --git a/test/multifile/require-member-layout-dynamic.swift b/test/multifile/require-member-layout-dynamic.swift
new file mode 100644
index 0000000..ccab41a
--- /dev/null
+++ b/test/multifile/require-member-layout-dynamic.swift
@@ -0,0 +1,11 @@
+// RUN: %target-swift-frontend -module-name test -emit-ir -primary-file %s %S/Inputs/require-member-layout-dynamic-other.swift -import-objc-header %S/Inputs/require-member-layout-dynamic-bridging.h -sdk %sdk -o %t.o
+
+// REQUIRES: objc_interop
+
+import Foundation
+
+public class Foo: NSObject {
+  func foo() {
+    bar("hello")
+  }
+}
diff --git a/test/refactoring/MemberwiseInit/Outputs/class_members/class_members.swift.expected b/test/refactoring/MemberwiseInit/Outputs/class_members/class_members.swift.expected
new file mode 100644
index 0000000..5c3de89
--- /dev/null
+++ b/test/refactoring/MemberwiseInit/Outputs/class_members/class_members.swift.expected
@@ -0,0 +1,14 @@
+class Person {
+internal init(firstName: String?, lastName: String?, age: Int?) {
+self.firstName = firstName
+self.lastName = lastName
+self.age = age
+}
+
+  var firstName: String!
+  var lastName: String!
+  var age: Int!
+  var planet = "Earth", solarSystem = "Milky Way"
+  var avgHeight = 175
+}
+
diff --git a/test/refactoring/MemberwiseInit/class_members.swift b/test/refactoring/MemberwiseInit/class_members.swift
new file mode 100644
index 0000000..78081b6
--- /dev/null
+++ b/test/refactoring/MemberwiseInit/class_members.swift
@@ -0,0 +1,11 @@
+class Person {
+  var firstName: String!
+  var lastName: String!
+  var age: Int!
+  var planet = "Earth", solarSystem = "Milky Way"
+  var avgHeight = 175
+}
+
+// RUN: %empty-directory(%t.result)
+// RUN: %refactor -memberwise-init -source-filename %s -pos=1:8 > %t.result/class_members.swift
+// RUN: diff -u %S/Outputs/class_members/class_members.swift.expected %t.result/class_members.swift
diff --git a/test/refactoring/RefactoringKind/member_init_class_as_value.swift b/test/refactoring/RefactoringKind/member_init_class_as_value.swift
new file mode 100644
index 0000000..c675784
--- /dev/null
+++ b/test/refactoring/RefactoringKind/member_init_class_as_value.swift
@@ -0,0 +1,13 @@
+class Person {
+  var firstName: String!
+  var lastName: String!
+  var age: Int!
+  var planet = "Earth", solarSystem = "Milky Way"
+  var avgHeight = 175
+}
+
+let _ = Person()
+
+// RUN: %refactor -source-filename %s -pos=9:10 | %FileCheck %s -check-prefix=CHECK-NONE
+// CHECK-NONE: Action begins
+// CHECK-NONE-NEXT: Action ends
diff --git a/test/stdlib/KeyPathAppending.swift b/test/stdlib/KeyPathAppending.swift
index cf2daaa..d1e3f9a 100644
--- a/test/stdlib/KeyPathAppending.swift
+++ b/test/stdlib/KeyPathAppending.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 // Check that all combinations of key paths produce the expected result type
 // and choose the expected overloads.
diff --git a/test/stdlib/simd_diagnostics.swift b/test/stdlib/simd_diagnostics.swift
index b386de4..12801f4 100644
--- a/test/stdlib/simd_diagnostics.swift
+++ b/test/stdlib/simd_diagnostics.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 // FIXME: No simd module on linux rdar://problem/20795411
 // XFAIL: linux
diff --git a/test/stmt/errors.swift b/test/stmt/errors.swift
index 688f15e..b632132 100644
--- a/test/stmt/errors.swift
+++ b/test/stmt/errors.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 enum MSV : Error {
   case Foo, Bar, Baz
 
diff --git a/test/stmt/statements.swift b/test/stmt/statements.swift
index 4b8c8a4..5e593a9 100644
--- a/test/stmt/statements.swift
+++ b/test/stmt/statements.swift
@@ -342,7 +342,9 @@
 
   // Not ok.
   while false { defer { break } }   // expected-error {{'break' cannot transfer control out of a defer statement}}
+  // expected-warning@-1 {{'defer' statement before end of scope always executes immediately}}{{17-22=do}}
   defer { return }  // expected-error {{'return' cannot transfer control out of a defer statement}}
+  // expected-warning@-1 {{'defer' statement before end of scope always executes immediately}}{{3-8=do}}
 }
 
 class SomeTestClass {
@@ -350,6 +352,7 @@
   
   func method() {
     defer { x = 97 }  // self. not required here!
+    // expected-warning@-1 {{'defer' statement before end of scope always executes immediately}}{{5-10=do}}
   }
 }
 
diff --git a/test/stmt/yield.swift b/test/stmt/yield.swift
index 8fa85c8..14a55ee 100644
--- a/test/stmt/yield.swift
+++ b/test/stmt/yield.swift
@@ -82,7 +82,7 @@
 struct YieldInDefer {
   var property: String {
     _read {
-      defer {
+      defer { // expected-warning {{'defer' statement before end of scope always executes immediately}}{{7-12=do}}
         // FIXME: this recovery is terrible
         yield ""
         // expected-error@-1 {{expression resolves to an unused function}}
diff --git a/tools/sil-func-extractor/SILFunctionExtractor.cpp b/tools/sil-func-extractor/SILFunctionExtractor.cpp
index 8045c27..bc85bd2 100644
--- a/tools/sil-func-extractor/SILFunctionExtractor.cpp
+++ b/tools/sil-func-extractor/SILFunctionExtractor.cpp
@@ -20,7 +20,7 @@
 //===----------------------------------------------------------------------===//
 
 #define DEBUG_TYPE "sil-func-extractor"
-#include "swift/Strings.h"
+#include "swift/Basic/FileTypes.h"
 #include "swift/Basic/LLVM.h"
 #include "swift/Basic/LLVMInitialize.h"
 #include "swift/Demangling/Demangle.h"
@@ -347,10 +347,12 @@
       OutputFile = OutputFilename;
     } else if (ModuleName.size()) {
       OutputFile = ModuleName;
-      llvm::sys::path::replace_extension(OutputFile, SIB_EXTENSION);
+      llvm::sys::path::replace_extension(
+          OutputFile, file_types::getExtension(file_types::TY_SIB));
     } else {
       OutputFile = CI.getMainModule()->getName().str();
-      llvm::sys::path::replace_extension(OutputFile, SIB_EXTENSION);
+      llvm::sys::path::replace_extension(
+          OutputFile, file_types::getExtension(file_types::TY_SIB));
     }
 
     SerializationOptions serializationOpts;
diff --git a/tools/sil-opt/SILOpt.cpp b/tools/sil-opt/SILOpt.cpp
index 1352c07..605bbcd 100644
--- a/tools/sil-opt/SILOpt.cpp
+++ b/tools/sil-opt/SILOpt.cpp
@@ -15,10 +15,10 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "swift/Strings.h"
 #include "swift/Subsystems.h"
 #include "swift/AST/DiagnosticsFrontend.h"
 #include "swift/AST/SILOptions.h"
+#include "swift/Basic/FileTypes.h"
 #include "swift/Basic/LLVMInitialize.h"
 #include "swift/Basic/LLVMContext.h"
 #include "swift/Frontend/DiagnosticVerifier.h"
@@ -452,10 +452,12 @@
       OutputFile = OutputFilename;
     } else if (ModuleName.size()) {
       OutputFile = ModuleName;
-      llvm::sys::path::replace_extension(OutputFile, SIB_EXTENSION);
+      llvm::sys::path::replace_extension(
+          OutputFile, file_types::getExtension(file_types::TY_SIB));
     } else {
       OutputFile = CI.getMainModule()->getName().str();
-      llvm::sys::path::replace_extension(OutputFile, SIB_EXTENSION);
+      llvm::sys::path::replace_extension(
+          OutputFile, file_types::getExtension(file_types::TY_SIB));
     }
 
     SerializationOptions serializationOpts;
diff --git a/tools/swift-refactor/swift-refactor.cpp b/tools/swift-refactor/swift-refactor.cpp
index 6c9f6b6..5295ebf 100644
--- a/tools/swift-refactor/swift-refactor.cpp
+++ b/tools/swift-refactor/swift-refactor.cpp
@@ -66,7 +66,8 @@
            clEnumValN(RefactoringKind::TrailingClosure,
                       "trailingclosure", "Perform trailing closure refactoring"),
            clEnumValN(RefactoringKind::ReplaceBodiesWithFatalError,
-                      "replace-bodies-with-fatalError", "Perform trailing closure refactoring")));
+                      "replace-bodies-with-fatalError", "Perform trailing closure refactoring"),
+           clEnumValN(RefactoringKind::MemberwiseInitLocalRefactoring, "memberwise-init", "Generate member wise initializer")));
 
 
 static llvm::cl::opt<std::string>
diff --git a/tools/swift-swiftsyntax-test/CMakeLists.txt b/tools/swift-swiftsyntax-test/CMakeLists.txt
index 6550ce4..bcff4a3 100644
--- a/tools/swift-swiftsyntax-test/CMakeLists.txt
+++ b/tools/swift-swiftsyntax-test/CMakeLists.txt
@@ -1,6 +1,7 @@
 add_swift_host_tool(swift-swiftsyntax-test
   main.swift
   CommandLineArguments.swift 
+  empty.c # FIXME: If there is no C file in the target Xcode skips the linking phase and doesn't create the executable
   COMPILE_FLAGS "-module-name" "main"
   DEPENDS 
     swiftSwiftSyntax-macosx
diff --git a/tools/swift-swiftsyntax-test/empty.c b/tools/swift-swiftsyntax-test/empty.c
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/tools/swift-swiftsyntax-test/empty.c
@@ -0,0 +1 @@
+
diff --git a/utils/swift-project-settings.el b/utils/swift-project-settings.el
index 5f230de..b758d74 100644
--- a/utils/swift-project-settings.el
+++ b/utils/swift-project-settings.el
@@ -95,12 +95,12 @@
                 (inline-close . 0)
                 (class-close . 0)
                 (namespace-close . 0)
-                (case-label . -)
+                (case-label . 0)
                 (statement-case-intro . +)
                 (cpp-define-intro . +)
                 (else-clause . 0)
                 (arglist-intro . +)
-                (arglist-cont . +)
+                (arglist-cont . 0)
                 (c . c-lineup-C-comments)
                 (inher-cont . c-lineup-multi-inher)
                 (string . -1000)
diff --git a/utils/update_checkout/__init__.py b/utils/update_checkout/__init__.py
new file mode 100644
index 0000000..7d29392
--- /dev/null
+++ b/utils/update_checkout/__init__.py
@@ -0,0 +1,4 @@
+
+from update_checkout import main
+
+__all__ = ["main"]
diff --git a/utils/update_checkout/tests/__init__.py b/utils/update_checkout/tests/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/utils/update_checkout/tests/__init__.py
diff --git a/utils/update-checkout-config.json b/utils/update_checkout/update-checkout-config.json
similarity index 100%
rename from utils/update-checkout-config.json
rename to utils/update_checkout/update-checkout-config.json
diff --git a/utils/update_checkout/update_checkout/__init__.py b/utils/update_checkout/update_checkout/__init__.py
new file mode 100644
index 0000000..7d29392
--- /dev/null
+++ b/utils/update_checkout/update_checkout/__init__.py
@@ -0,0 +1,4 @@
+
+from update_checkout import main
+
+__all__ = ["main"]
diff --git a/utils/update_checkout.py b/utils/update_checkout/update_checkout/update_checkout.py
similarity index 99%
rename from utils/update_checkout.py
rename to utils/update_checkout/update_checkout/update_checkout.py
index 385d522..4cad486 100755
--- a/utils/update_checkout.py
+++ b/utils/update_checkout/update_checkout/update_checkout.py
@@ -414,7 +414,8 @@
         action='store_true')
     parser.add_argument(
         "--config",
-        default=os.path.join(SCRIPT_DIR, "update-checkout-config.json"),
+        default=os.path.join(SCRIPT_DIR, os.pardir,
+                             "update-checkout-config.json"),
         help="Configuration file to use")
     parser.add_argument(
         "--github-comment",
@@ -518,7 +519,3 @@
     else:
         print("update-checkout succeeded")
     sys.exit(fail_count)
-
-
-if __name__ == "__main__":
-    main()
diff --git a/test/Driver/batch_mode_overlong_argv.swift b/validation-test/Driver/batch_mode_overlong_argv.swift
similarity index 100%
rename from test/Driver/batch_mode_overlong_argv.swift
rename to validation-test/Driver/batch_mode_overlong_argv.swift
diff --git a/validation-test/Python/update_checkout.test-sh b/validation-test/Python/update_checkout.test-sh
new file mode 100644
index 0000000..9ec3957
--- /dev/null
+++ b/validation-test/Python/update_checkout.test-sh
@@ -0,0 +1 @@
+// RUN: %{python} -m unittest discover -s %swift_src_root/utils/update_checkout
\ No newline at end of file
diff --git a/validation-test/compiler_crashers_2_fixed/0128-rdar35088384.swift b/validation-test/compiler_crashers_2_fixed/0128-rdar35088384.swift
index 366529b..3c6e9ca 100644
--- a/validation-test/compiler_crashers_2_fixed/0128-rdar35088384.swift
+++ b/validation-test/compiler_crashers_2_fixed/0128-rdar35088384.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 protocol Command {}
 
diff --git a/validation-test/compiler_crashers_2_fixed/0145-sr7097.swift b/validation-test/compiler_crashers_2_fixed/0145-sr7097.swift
index 4ae7282..11f8bbf 100644
--- a/validation-test/compiler_crashers_2_fixed/0145-sr7097.swift
+++ b/validation-test/compiler_crashers_2_fixed/0145-sr7097.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 // RUN: %target-swift-frontend -typecheck -debug-generic-signatures %s 2>&1 | %FileCheck %s
 // RUN: %target-swift-frontend -primary-file %s -emit-ir -o -
 
diff --git a/validation-test/compiler_crashers_2_fixed/0169-sr8179.swift b/validation-test/compiler_crashers_2_fixed/0169-sr8179.swift
new file mode 100644
index 0000000..085751b
--- /dev/null
+++ b/validation-test/compiler_crashers_2_fixed/0169-sr8179.swift
@@ -0,0 +1,17 @@
+// RUN: %target-swift-frontend -emit-sil %s
+
+protocol SignalInterface {
+	associatedtype OutputValue
+}
+
+class Signal<OV>: SignalInterface {
+  typealias OutputValue = OV
+}
+
+extension Signal {
+  func foo<U>(_: U) -> SignalChannel<[U], Signal<Array<U>>>
+    where OutputValue == Optional<U> { return SignalChannel() }
+}
+
+struct SignalChannel<OutputValue, Output: Signal<OutputValue>> { }
+
diff --git a/validation-test/stdlib/BoolDiagnostics.swift b/validation-test/stdlib/BoolDiagnostics.swift
index 95eee5e..7403e62 100644
--- a/validation-test/stdlib/BoolDiagnostics.swift
+++ b/validation-test/stdlib/BoolDiagnostics.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -typecheck -verify %s
+// RUN: %target-typecheck-verify-swift
 
 func CVarArgs_withBool() {
   func varArgFunc(_ x: Bool, _ args: CVarArg...) { }
diff --git a/validation-test/stdlib/FixedPointDiagnostics.swift.gyb b/validation-test/stdlib/FixedPointDiagnostics.swift.gyb
index 9caccb2..ecc5ce9 100644
--- a/validation-test/stdlib/FixedPointDiagnostics.swift.gyb
+++ b/validation-test/stdlib/FixedPointDiagnostics.swift.gyb
@@ -35,22 +35,19 @@
   _ = UInt8(truncatingBitPattern: UInt(0))
   _ = UInt16(truncatingBitPattern: UInt(0))
   _ = UInt32(truncatingBitPattern: UInt(0))
-  UInt64(truncatingBitPattern: UInt(0)) // expected-error {{argument labels '(truncatingBitPattern:)' do not match any available overloads}}
-// expected-note @-1 {{overloads for 'UInt64' exist with these partially matching parameter lists}}
+  UInt64(truncatingBitPattern: UInt(0)) // expected-error {{extraneous argument label 'truncatingBitPattern:' in call}}
   UInt(truncatingBitPattern: UInt(0))   // expected-error {{}} expected-note * {{}}
 
   _ = Int8(truncatingBitPattern: UInt(0))
   _ = Int16(truncatingBitPattern: UInt(0))
   _ = Int32(truncatingBitPattern: UInt(0))
-  Int64(truncatingBitPattern: UInt(0)) // expected-error {{argument labels '(truncatingBitPattern:)' do not match any available overloads}}
-// expected-note @-1 {{overloads for 'Int64' exist with}}
+  Int64(truncatingBitPattern: UInt(0)) // expected-error {{extraneous argument label 'truncatingBitPattern:' in call}}
   Int(truncatingBitPattern: UInt(0))   // expected-error {{}} expected-note * {{}}
 
   _ = UInt8(truncatingBitPattern: Int(0))
   _ = UInt16(truncatingBitPattern: Int(0))
   _ = UInt32(truncatingBitPattern: Int(0))
-  UInt64(truncatingBitPattern: Int(0)) // expected-error {{argument labels '(truncatingBitPattern:)' do not match any available overloads}}
-// expected-note @-1 {{overloads for 'UInt64' exist with these partially matching parameter lists}}
+  UInt64(truncatingBitPattern: Int(0)) // expected-error {{extraneous argument label 'truncatingBitPattern:' in call}}
   UInt(truncatingBitPattern: Int(0))   // expected-error {{}} expected-note * {{}}
 
   _ = Int8(truncatingBitPattern: Int(0))
diff --git a/validation-test/stdlib/Lazy.swift.gyb b/validation-test/stdlib/Lazy.swift.gyb
index 7f3ad64..6a0dcf9 100644
--- a/validation-test/stdlib/Lazy.swift.gyb
+++ b/validation-test/stdlib/Lazy.swift.gyb
@@ -12,12 +12,6 @@
 // RUN: %target-run-simple-swiftgyb
 // REQUIRES: executable_test
 
-// <rdar://35797159> [Associated Type Inference]
-// heap-use-after-free ASTContext::getSpecializedConformance
-// llvm::FoldingSetBase::InsertNode
-// OR corrupted doubly linked list
-// REQUIRES: OS=macosx
-
 import StdlibUnittest
 import StdlibCollectionUnittest