Merge pull request #21240 from rjmccall/remove-xi-witnesses-5.0

[5.0] Remove the extra-inhabitant value witnesses
diff --git a/include/swift/AST/Attr.def b/include/swift/AST/Attr.def
index 1e15e8b..7e3712c 100644
--- a/include/swift/AST/Attr.def
+++ b/include/swift/AST/Attr.def
@@ -338,7 +338,7 @@
   NotSerialized, 67)
 DECL_ATTR(_objcRuntimeName, ObjCRuntimeName,
   OnClass |
-  UserInaccessible | RejectByParser |
+  UserInaccessible |
   NotSerialized, 68)
 SIMPLE_DECL_ATTR(_staticInitializeObjCMetadata, StaticInitializeObjCMetadata,
   OnClass | LongAttribute | RejectByParser |
diff --git a/include/swift/AST/DiagnosticsParse.def b/include/swift/AST/DiagnosticsParse.def
index 96ee05e..6ba0f9c 100644
--- a/include/swift/AST/DiagnosticsParse.def
+++ b/include/swift/AST/DiagnosticsParse.def
@@ -1327,6 +1327,9 @@
 ERROR(swift_native_objc_runtime_base_must_be_identifier,none,
       "@_swift_native_objc_runtime_base class name must be an identifier", ())
 
+ERROR(objc_runtime_name_must_be_identifier,none,
+      "@_objcRuntimeName name must be an identifier", ())
+
 ERROR(attr_only_at_non_local_scope, none,
       "attribute '%0' can only be used in a non-local scope", (StringRef))
 
diff --git a/include/swift/AST/ModuleLoader.h b/include/swift/AST/ModuleLoader.h
index 70bd5a7..4e6220f 100644
--- a/include/swift/AST/ModuleLoader.h
+++ b/include/swift/AST/ModuleLoader.h
@@ -38,6 +38,16 @@
 
 enum class KnownProtocolKind : uint8_t;
 
+enum class Bridgeability : unsigned {
+  /// This context does not permit bridging at all.  For example, the
+  /// target of a C pointer.
+  None,
+
+  /// This context permits all kinds of bridging.  For example, the
+  /// imported result of a method declaration.
+  Full
+};
+
 /// Records dependencies on files outside of the current module;
 /// implemented in terms of a wrapped clang::DependencyCollector.
 class DependencyTracker {
diff --git a/include/swift/SIL/TypeLowering.h b/include/swift/SIL/TypeLowering.h
index e872e06..feb17cf 100644
--- a/include/swift/SIL/TypeLowering.h
+++ b/include/swift/SIL/TypeLowering.h
@@ -31,6 +31,7 @@
 
 namespace swift {
   class AnyFunctionRef;
+  enum class Bridgeability : unsigned;
   class ForeignErrorConvention;
   enum IsInitialization_t : bool;
   enum IsTake_t : bool;
@@ -851,6 +852,7 @@
   /// Map an AST-level type to the corresponding foreign representation type we
   /// implicitly convert to for a given calling convention.
   Type getLoweredBridgedType(AbstractionPattern pattern, Type t,
+                             Bridgeability bridging,
                              SILFunctionTypeRepresentation rep,
                              BridgedTypePurpose purpose);
 
@@ -871,7 +873,8 @@
   /// Given a function type, yield its bridged formal type.
   CanAnyFunctionType getBridgedFunctionType(AbstractionPattern fnPattern,
                                             CanAnyFunctionType fnType,
-                                            AnyFunctionType::ExtInfo extInfo);
+                                            AnyFunctionType::ExtInfo extInfo,
+                                            Bridgeability bridging);
 
   /// Given a referenced value and the substituted formal type of a
   /// resulting l-value expression, produce the substituted formal
@@ -977,22 +980,26 @@
   CanType getLoweredRValueType(AbstractionPattern origType, CanType substType);
 
   Type getLoweredCBridgedType(AbstractionPattern pattern, Type t,
-                              bool canBridgeBool,
-                              bool bridgedCollectionsAreOptional);
+                              Bridgeability bridging,
+                              SILFunctionTypeRepresentation rep,
+                              BridgedTypePurpose purpose);
 
   AnyFunctionType::Param
   getBridgedParam(SILFunctionTypeRepresentation rep,
                   AbstractionPattern pattern,
-                  AnyFunctionType::Param param);
+                  AnyFunctionType::Param param,
+                  Bridgeability bridging);
 
   void getBridgedParams(SILFunctionTypeRepresentation rep,
                         AbstractionPattern pattern,
                         ArrayRef<AnyFunctionType::Param> params,
-                        SmallVectorImpl<AnyFunctionType::Param> &bridged);
+                        SmallVectorImpl<AnyFunctionType::Param> &bridged,
+                        Bridgeability bridging);
 
   CanType getBridgedResultType(SILFunctionTypeRepresentation rep,
                                AbstractionPattern pattern,
                                CanType result,
+                               Bridgeability bridging,
                                bool suppressOptional);
 };
 
diff --git a/lib/ClangImporter/ImporterImpl.h b/lib/ClangImporter/ImporterImpl.h
index 0d826d1..ec93cf0 100644
--- a/lib/ClangImporter/ImporterImpl.h
+++ b/lib/ClangImporter/ImporterImpl.h
@@ -181,16 +181,6 @@
   Enum
 };
 
-enum class Bridgeability {
-  /// This context does not permit bridging at all.  For example, the
-  /// target of a C pointer.
-  None,
-
-  /// This context permits all kinds of bridging.  For example, the
-  /// imported result of a method declaration.
-  Full
-};
-
 /// Controls whether a typedef for \p type should name the fully-bridged Swift
 /// type or the original Clang type.
 ///
diff --git a/lib/IRGen/GenKeyPath.cpp b/lib/IRGen/GenKeyPath.cpp
index 72c2da4..569e8d7 100644
--- a/lib/IRGen/GenKeyPath.cpp
+++ b/lib/IRGen/GenKeyPath.cpp
@@ -1305,17 +1305,10 @@
                        {},
                        hasSubscriptIndices);
   
-  auto size = fields.getNextOffsetFromGlobal();
-  
   auto var = cast<llvm::GlobalVariable>(
     getAddrOfPropertyDescriptor(prop->getDecl(),
                                 fields.finishAndCreateFuture()));
   var->setConstant(true);
   var->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
-  // A simple stored component descriptor can fit in four bytes. Anything else
-  // needs pointer alignment.
-  if (size <= Size(4))
-    var->setAlignment(4);
-  else
-    var->setAlignment(getPointerAlignment().getValue());
+  var->setAlignment(4);
 }
diff --git a/lib/Parse/ParseDecl.cpp b/lib/Parse/ParseDecl.cpp
index d46cfb4..0998727 100644
--- a/lib/Parse/ParseDecl.cpp
+++ b/lib/Parse/ParseDecl.cpp
@@ -902,7 +902,6 @@
 
   case DAK_RawDocComment:
   case DAK_ObjCBridged:
-  case DAK_ObjCRuntimeName:
   case DAK_RestatedObjCConformance:
   case DAK_SynthesizedProtocol:
   case DAK_ClangImporterSynthesizedType:
@@ -1494,6 +1493,34 @@
     Attributes.add(attr);
     break;
   }
+  case DAK_ObjCRuntimeName: {
+    if (!consumeIf(tok::l_paren)) {
+      diagnose(Loc, diag::attr_expected_lparen, AttrName,
+               DeclAttribute::isDeclModifier(DK));
+      return false;
+    }
+
+    if (Tok.isNot(tok::identifier)) {
+      diagnose(Loc, diag::objc_runtime_name_must_be_identifier);
+      return false;
+    }
+
+    auto name = Tok.getText();
+
+    consumeToken(tok::identifier);
+
+    auto range = SourceRange(Loc, Tok.getRange().getStart());
+
+    if (!consumeIf(tok::r_paren)) {
+      diagnose(Loc, diag::attr_expected_rparen, AttrName,
+               DeclAttribute::isDeclModifier(DK));
+      return false;
+    }
+
+    Attributes.add(new (Context) ObjCRuntimeNameAttr(name, AtLoc, range,
+                                                     /*implicit*/ false));
+    break;
+  }
 
 
   case DAK_DynamicReplacement: {
diff --git a/lib/SIL/AbstractionPattern.cpp b/lib/SIL/AbstractionPattern.cpp
index 0b7df20..4236095 100644
--- a/lib/SIL/AbstractionPattern.cpp
+++ b/lib/SIL/AbstractionPattern.cpp
@@ -60,6 +60,17 @@
   return cast<clang::ObjCPropertyDecl>(decl)->getType().getTypePtr();
 }
 
+static Bridgeability getClangDeclBridgeability(const clang::Decl *decl) {
+  // These declarations are always imported without bridging (for now).
+  if (isa<clang::VarDecl>(decl) ||
+      isa<clang::FieldDecl>(decl) ||
+      isa<clang::IndirectFieldDecl>(decl))
+    return Bridgeability::None;
+
+  // Functions and methods always use normal bridging.
+  return Bridgeability::Full;
+}
+
 AbstractionPattern
 TypeConverter::getAbstractionPattern(VarDecl *var, bool isNonObjC) {
   CanGenericSignature genericSig;
@@ -77,7 +88,7 @@
     auto contextType = var->getDeclContext()->mapTypeIntoContext(swiftType);
     swiftType = getLoweredBridgedType(
         AbstractionPattern(genericSig, swiftType, clangType),
-        contextType,
+        contextType, getClangDeclBridgeability(clangDecl),
         SILFunctionTypeRepresentation::CFunctionPointer,
         TypeConverter::ForMemory)->getCanonicalType();
     return AbstractionPattern(genericSig, swiftType, clangType);
diff --git a/lib/SIL/Bridging.cpp b/lib/SIL/Bridging.cpp
index 9dbd86a..0c85889 100644
--- a/lib/SIL/Bridging.cpp
+++ b/lib/SIL/Bridging.cpp
@@ -38,12 +38,13 @@
 AnyFunctionType::Param
 TypeConverter::getBridgedParam(SILFunctionTypeRepresentation rep,
                                AbstractionPattern pattern,
-                               AnyFunctionType::Param param) {
+                               AnyFunctionType::Param param,
+                               Bridgeability bridging) {
   assert(!param.getParameterFlags().isInOut() &&
          !param.getParameterFlags().isVariadic());
 
-  auto bridged = getLoweredBridgedType(pattern, param.getPlainType(), rep,
-                                       TypeConverter::ForArgument);
+  auto bridged = getLoweredBridgedType(pattern, param.getPlainType(), bridging,
+                                       rep, TypeConverter::ForArgument);
   if (!bridged) {
     Context.Diags.diagnose(SourceLoc(), diag::could_not_find_bridge_type,
                            param.getPlainType());
@@ -59,10 +60,12 @@
 getBridgedParams(SILFunctionTypeRepresentation rep,
                  AbstractionPattern pattern,
                  ArrayRef<AnyFunctionType::Param> params,
-                 SmallVectorImpl<AnyFunctionType::Param> &bridgedParams) {
+                 SmallVectorImpl<AnyFunctionType::Param> &bridgedParams,
+                 Bridgeability bridging) {
   for (unsigned i : indices(params)) {
     auto paramPattern = pattern.getFunctionParamType(i);
-    bridgedParams.push_back(getBridgedParam(rep, paramPattern, params[i]));
+    auto bridgedParam = getBridgedParam(rep, paramPattern, params[i], bridging);
+    bridgedParams.push_back(bridgedParam);
   }
 }
 
@@ -70,9 +73,10 @@
 CanType TypeConverter::getBridgedResultType(SILFunctionTypeRepresentation rep,
                                             AbstractionPattern pattern,
                                             CanType result,
+                                            Bridgeability bridging,
                                             bool suppressOptional) {
   auto loweredType =
-    getLoweredBridgedType(pattern, result, rep,
+    getLoweredBridgedType(pattern, result, bridging, rep,
                           suppressOptional
                             ? TypeConverter::ForNonOptionalResult
                             : TypeConverter::ForResult);
@@ -89,6 +93,7 @@
 
 Type TypeConverter::getLoweredBridgedType(AbstractionPattern pattern,
                                           Type t,
+                                          Bridgeability bridging,
                                           SILFunctionTypeRepresentation rep,
                                           BridgedTypePurpose purpose) {
   switch (rep) {
@@ -104,39 +109,46 @@
   case SILFunctionTypeRepresentation::Block:
     // Map native types back to bridged types.
 
-    bool canBridgeBool = (rep == SILFunctionTypeRepresentation::ObjCMethod);
-
     // Look through optional types.
     if (auto valueTy = t->getOptionalObjectType()) {
       pattern = pattern.getOptionalObjectType();
-      auto ty = getLoweredCBridgedType(pattern, valueTy, canBridgeBool, false);
+      auto ty = getLoweredCBridgedType(pattern, valueTy, bridging, rep,
+                                      BridgedTypePurpose::ForNonOptionalResult);
       return ty ? OptionalType::get(ty) : ty;
     }
-    return getLoweredCBridgedType(pattern, t, canBridgeBool,
-                                  purpose == ForResult);
+    return getLoweredCBridgedType(pattern, t, bridging, rep, purpose);
   }
 
   llvm_unreachable("Unhandled SILFunctionTypeRepresentation in switch.");
 };
 
 Type TypeConverter::getLoweredCBridgedType(AbstractionPattern pattern,
-                                           Type t,
-                                           bool canBridgeBool,
-                                           bool bridgedCollectionsAreOptional) {
+                                           Type t, Bridgeability bridging,
+                                           SILFunctionTypeRepresentation rep,
+                                           BridgedTypePurpose purpose) {
   auto clangTy = pattern.isClangType() ? pattern.getClangType() : nullptr;
 
   // Bridge Bool back to ObjC bool, unless the original Clang type was _Bool
   // or the Darwin Boolean type.
   auto nativeBoolTy = getBoolType();
   if (nativeBoolTy && t->isEqual(nativeBoolTy)) {
+    // If we have a Clang type that was imported as Bool, it had better be
+    // one of a small set of types.
     if (clangTy) {
-      if (clangTy->isBooleanType())
+      auto builtinTy = clangTy->castAs<clang::BuiltinType>();
+      if (builtinTy->getKind() == clang::BuiltinType::Bool)
         return t;
-      if (clangTy->isSpecificBuiltinType(clang::BuiltinType::UChar))
+      if (builtinTy->getKind() == clang::BuiltinType::UChar)
         return getDarwinBooleanType();
-    }
-    if (clangTy || canBridgeBool)
+      assert(builtinTy->getKind() == clang::BuiltinType::SChar);
       return getObjCBoolType();
+    }
+
+    // Otherwise, always assume ObjC methods should use ObjCBool.
+    if (bridging != Bridgeability::None &&
+        rep == SILFunctionTypeRepresentation::ObjCMethod)
+      return getObjCBoolType();
+
     return t;
   }
 
@@ -180,12 +192,13 @@
       // so we use the ObjCMethod representation.
       SmallVector<AnyFunctionType::Param, 8> newParams;
       getBridgedParams(SILFunctionType::Representation::ObjCMethod,
-                       pattern, funTy->getParams(), newParams);
+                       pattern, funTy->getParams(), newParams, bridging);
 
       Type newResult =
           getBridgedResultType(SILFunctionType::Representation::ObjCMethod,
                                pattern.getFunctionResultType(),
                                funTy->getResult()->getCanonicalType(),
+                               bridging,
                                /*non-optional*/false);
 
       return FunctionType::get(newParams, newResult,
@@ -213,7 +226,7 @@
         M.getASTContext().Id_ObjectiveCType,
         nullptr);
     assert(bridgedTy && "Missing _ObjectiveCType witness?");
-    if (bridgedCollectionsAreOptional && clangTy)
+    if (purpose == BridgedTypePurpose::ForResult && clangTy)
       bridgedTy = OptionalType::get(bridgedTy);
     return bridgedTy;
   }
diff --git a/lib/SIL/SILFunctionType.cpp b/lib/SIL/SILFunctionType.cpp
index 670acfc..64254fb 100644
--- a/lib/SIL/SILFunctionType.cpp
+++ b/lib/SIL/SILFunctionType.cpp
@@ -2530,7 +2530,8 @@
 CanAnyFunctionType
 TypeConverter::getBridgedFunctionType(AbstractionPattern pattern,
                                       CanAnyFunctionType t,
-                                      AnyFunctionType::ExtInfo extInfo) {
+                                      AnyFunctionType::ExtInfo extInfo,
+                                      Bridgeability bridging) {
   // Pull out the generic signature.
   CanGenericSignature genericSig = t.getOptGenericSignature();
 
@@ -2551,12 +2552,13 @@
   case SILFunctionTypeRepresentation::Block:
   case SILFunctionTypeRepresentation::ObjCMethod: {
     SmallVector<AnyFunctionType::Param, 8> params;
-    getBridgedParams(rep, pattern, t->getParams(), params);
+    getBridgedParams(rep, pattern, t->getParams(), params, bridging);
 
     bool suppressOptional = pattern.hasForeignErrorStrippingResultOptionality();
     auto result = getBridgedResultType(rep,
                                        pattern.getFunctionResultType(),
                                        t.getResult(),
+                                       bridging,
                                        suppressOptional);
 
     return CanAnyFunctionType::get(genericSig, llvm::makeArrayRef(params),
@@ -2627,6 +2629,10 @@
 TypeConverter::LoweredFormalTypes
 TypeConverter::getLoweredFormalTypes(SILDeclRef constant,
                                      CanAnyFunctionType fnType) {
+  // We always use full bridging when importing a constant because we can
+  // directly bridge its arguments and results when calling it.
+  auto bridging = Bridgeability::Full;
+
   unsigned numParameterLists = constant.getParameterListCount();
   auto extInfo = fnType->getExtInfo();
 
@@ -2638,7 +2644,7 @@
   // Fast path: no uncurrying required.
   if (numParameterLists == 1) {
     auto bridgedFnType =
-      getBridgedFunctionType(bridgingFnPattern, fnType, extInfo);
+      getBridgedFunctionType(bridgingFnPattern, fnType, extInfo, bridging);
     bridgingFnPattern.rewriteType(bridgingFnPattern.getGenericSignature(),
                                   bridgedFnType);
     return { bridgingFnPattern, bridgedFnType };
@@ -2685,17 +2691,18 @@
       // The "self" parameter should not get bridged unless it's a metatype.
       if (selfParam.getPlainType()->is<AnyMetatypeType>()) {
         auto selfPattern = bridgingFnPattern.getFunctionParamType(0);
-        selfParam = getBridgedParam(rep, selfPattern, selfParam);
+        selfParam = getBridgedParam(rep, selfPattern, selfParam, bridging);
       }
     }
 
     auto partialFnPattern = bridgingFnPattern.getFunctionResultType();
-    getBridgedParams(rep, partialFnPattern, methodParams, bridgedParams);
+    getBridgedParams(rep, partialFnPattern, methodParams, bridgedParams,
+                     bridging);
 
     bridgedResultType =
       getBridgedResultType(rep,
                            partialFnPattern.getFunctionResultType(),
-                           resultType, suppressOptionalResult);
+                           resultType, bridging, suppressOptionalResult);
     break;
   }
 
diff --git a/lib/SIL/TypeLowering.cpp b/lib/SIL/TypeLowering.cpp
index c06a919..b688413 100644
--- a/lib/SIL/TypeLowering.cpp
+++ b/lib/SIL/TypeLowering.cpp
@@ -1472,9 +1472,16 @@
     auto extInfo = substFnType->getExtInfo();
     if (getSILFunctionLanguage(extInfo.getSILRepresentation())
           == SILFunctionLanguage::C) {
+      // The importer only applies fully-reversible bridging to the
+      // component types of C function pointers.
+      auto bridging = Bridgeability::Full;
+      if (extInfo.getSILRepresentation()
+                        == SILFunctionTypeRepresentation::CFunctionPointer)
+        bridging = Bridgeability::None;
+
       // Bridge the parameters and result of the function type.
       auto bridgedFnType = getBridgedFunctionType(origType, substFnType,
-                                                  extInfo);
+                                                  extInfo, bridging);
       substFnType = bridgedFnType;
 
       // Also rewrite the type of the abstraction pattern.
diff --git a/lib/SILGen/SILGenApply.cpp b/lib/SILGen/SILGenApply.cpp
index 618702f..f0aba4a 100644
--- a/lib/SILGen/SILGenApply.cpp
+++ b/lib/SILGen/SILGenApply.cpp
@@ -76,7 +76,8 @@
     // bridged to a foreign type.
     auto bridgedType =
       SGF.SGM.Types.getBridgedFunctionType(pattern, fnType,
-                                           fnType->getExtInfo());
+                                           fnType->getExtInfo(),
+                                           Bridgeability::Full);
     pattern.rewriteType(CanGenericSignature(), bridgedType);
     return pattern;
   }
diff --git a/lib/SILGen/SILGenBridging.cpp b/lib/SILGen/SILGenBridging.cpp
index eba396c..f23486a 100644
--- a/lib/SILGen/SILGenBridging.cpp
+++ b/lib/SILGen/SILGenBridging.cpp
@@ -358,7 +358,8 @@
 static CanAnyFunctionType getBridgedBlockType(SILGenModule &SGM,
                                               CanAnyFunctionType blockType) {
   return SGM.Types.getBridgedFunctionType(AbstractionPattern(blockType),
-                                         blockType, blockType->getExtInfo());
+                                         blockType, blockType->getExtInfo(),
+                                         Bridgeability::Full);
 }
 
 static void buildFuncToBlockInvokeBody(SILGenFunction &SGF,
diff --git a/lib/Sema/ConstraintSystem.cpp b/lib/Sema/ConstraintSystem.cpp
index 67ef5b7..572cf84 100644
--- a/lib/Sema/ConstraintSystem.cpp
+++ b/lib/Sema/ConstraintSystem.cpp
@@ -1190,20 +1190,6 @@
   // Figure out the instance type used for the base.
   Type baseObjTy = getFixedTypeRecursive(baseTy, /*wantRValue=*/true);
 
-  ParameterTypeFlags baseFlags;
-  // FIXME(diagnostics): `InOutType` could appear here as a result
-  // of successful re-typecheck of the one of the sub-expressions e.g.
-  // `let _: Int = { (s: inout S) in s.bar() }`. On the first
-  // attempt to type-check whole expression `s.bar()` - is going
-  // to have a base which points directly to declaration of `S`.
-  // But when diagnostics attempts to type-check `s.bar()` standalone
-  // its base would be tranformed into `InOutExpr -> DeclRefExr`,
-  // and `InOutType` is going to be recorded in constraint system.
-  if (auto objType = baseObjTy->getInOutObjectType()) {
-    baseObjTy = objType;
-    baseFlags = baseFlags.withInOut(true);
-  }
-
   bool isInstance = true;
   if (auto baseMeta = baseObjTy->getAs<AnyMetatypeType>()) {
     baseObjTy = baseMeta->getInstanceType();
@@ -1215,7 +1201,7 @@
     return getTypeOfReference(value, functionRefKind, locator, useDC, base);
   }
 
-  FunctionType::Param baseObjParam(baseObjTy, Identifier(), baseFlags);
+  FunctionType::Param baseObjParam(baseObjTy);
 
   // Don't open existentials when accessing typealias members of
   // protocols.
diff --git a/lib/Sema/TypeCheckConstraints.cpp b/lib/Sema/TypeCheckConstraints.cpp
index 4e7365a..a55e4a2 100644
--- a/lib/Sema/TypeCheckConstraints.cpp
+++ b/lib/Sema/TypeCheckConstraints.cpp
@@ -984,6 +984,30 @@
           CallArgs.insert(arg);
       }
 
+      // FIXME(diagnostics): `InOutType` could appear here as a result
+      // of successful re-typecheck of the one of the sub-expressions e.g.
+      // `let _: Int = { (s: inout S) in s.bar() }`. On the first
+      // attempt to type-check whole expression `s.bar()` - is going
+      // to have a base which points directly to declaration of `S`.
+      // But when diagnostics attempts to type-check `s.bar()` standalone
+      // its base would be tranformed into `InOutExpr -> DeclRefExr`,
+      // and `InOutType` is going to be recorded in constraint system.
+      // One possible way to fix this (if diagnostics still use typecheck)
+      // might be to make it so self is not wrapped into `InOutExpr`
+      // but instead used as @lvalue type in some case of mutable members.
+      if (!expr->isImplicit()) {
+        if (isa<MemberRefExpr>(expr) || isa<DynamicMemberRefExpr>(expr)) {
+          auto *LE = cast<LookupExpr>(expr);
+          if (auto *IOE = dyn_cast<InOutExpr>(LE->getBase()))
+            LE->setBase(IOE->getSubExpr());
+        }
+
+        if (auto *DSCE = dyn_cast<DotSyntaxCallExpr>(expr)) {
+          if (auto *IOE = dyn_cast<InOutExpr>(DSCE->getBase()))
+            DSCE->setBase(IOE->getSubExpr());
+        }
+      }
+
       // Local function used to finish up processing before returning. Every
       // return site should call through here.
       auto finish = [&](bool recursive, Expr *expr) {
diff --git a/stdlib/public/core/KeyPath.swift b/stdlib/public/core/KeyPath.swift
index 9c499d8..0b056cf 100644
--- a/stdlib/public/core/KeyPath.swift
+++ b/stdlib/public/core/KeyPath.swift
@@ -26,7 +26,12 @@
 
 // MARK: Type-erased abstract base classes
 
-/// A type-erased key path, from any root type to any resulting value type.
+/// A type-erased key path, from any root type to any resulting value
+/// type. NOTE: older runtimes had Swift.AnyKeyPath as the ObjC name.
+/// The two must coexist, so it was renamed. The old name must not be
+/// used in the new runtime. _TtCs11_AnyKeyPath is the mangled name for
+/// Swift._AnyKeyPath.
+@_objcRuntimeName(_TtCs11_AnyKeyPath)
 public class AnyKeyPath: Hashable, _AppendKeyPath {
   /// The root type for this key path.
   @inlinable
@@ -2396,6 +2401,29 @@
   return end - base
 }
 
+// Resolve a mangled name in a generic environment, described by either a
+// flat GenericEnvironment * (if the bottom tag bit is 0) or possibly-nested
+// ContextDescriptor * (if the bottom tag bit is 1)
+internal func _getTypeByMangledNameInEnvironmentOrContext(
+  _ name: UnsafePointer<UInt8>,
+  _ nameLength: UInt,
+  genericEnvironmentOrContext: UnsafeRawPointer?,
+  genericArguments: UnsafeRawPointer?)
+  -> Any.Type? {
+
+  let taggedPointer = UInt(bitPattern: genericEnvironmentOrContext)
+  if taggedPointer & 1 == 0 {
+    return _getTypeByMangledNameInEnvironment(name, nameLength,
+                      genericEnvironment: genericEnvironmentOrContext,
+                      genericArguments: genericArguments)
+  } else {
+    let context = UnsafeRawPointer(bitPattern: taggedPointer & ~1)
+    return _getTypeByMangledNameInContext(name, nameLength,
+                      genericContext: context,
+                      genericArguments: genericArguments)
+  }
+}
+
 // Resolve the given generic argument reference to a generic argument.
 internal func _resolveKeyPathGenericArgReference(
     _ reference: UnsafeRawPointer,
@@ -2431,8 +2459,8 @@
                                           capacity: nameLength + 1)
   // FIXME: Could extract this information from the mangled name.
   guard let result =
-    _getTypeByMangledName(namePtr, UInt(nameLength),
-                         genericEnvironment: genericEnvironment,
+    _getTypeByMangledNameInEnvironmentOrContext(namePtr, UInt(nameLength),
+                         genericEnvironmentOrContext: genericEnvironment,
                          genericArguments: arguments)
     else {
       let nameStr = String._fromUTF8Repairing(
diff --git a/stdlib/public/core/Misc.swift b/stdlib/public/core/Misc.swift
index 5810f71..0e86f55 100644
--- a/stdlib/public/core/Misc.swift
+++ b/stdlib/public/core/Misc.swift
@@ -96,9 +96,17 @@
   -> Any.Type?
 
 @_silgen_name("swift_getTypeByMangledNameInEnvironment")
-internal func _getTypeByMangledName(
+public func _getTypeByMangledNameInEnvironment(
   _ name: UnsafePointer<UInt8>,
   _ nameLength: UInt,
   genericEnvironment: UnsafeRawPointer?,
   genericArguments: UnsafeRawPointer?)
   -> Any.Type?
+
+@_silgen_name("swift_getTypeByMangledNameInContext")
+public func _getTypeByMangledNameInContext(
+  _ name: UnsafePointer<UInt8>,
+  _ nameLength: UInt,
+  genericContext: UnsafeRawPointer?,
+  genericArguments: UnsafeRawPointer?)
+  -> Any.Type?
diff --git a/stdlib/public/core/VarArgs.swift b/stdlib/public/core/VarArgs.swift
index 5d42c58..dcc7f31 100644
--- a/stdlib/public/core/VarArgs.swift
+++ b/stdlib/public/core/VarArgs.swift
@@ -127,7 +127,7 @@
 @inlinable // c-abi
 public func withVaList<R>(_ args: [CVarArg],
   _ body: (CVaListPointer) -> R) -> R {
-  let builder = _VaListBuilder()
+  let builder = __VaListBuilder()
   for a in args {
     builder.append(a)
   }
@@ -137,7 +137,7 @@
 /// Invoke `body` with a C `va_list` argument derived from `builder`.
 @inlinable // c-abi
 internal func _withVaList<R>(
-  _ builder: _VaListBuilder,
+  _ builder: __VaListBuilder,
   _ body: (CVaListPointer) -> R
 ) -> R {
   let result = body(builder.va_list())
@@ -168,7 +168,7 @@
 ///   `va_list` argument.
 @inlinable // c-abi
 public func getVaList(_ args: [CVarArg]) -> CVaListPointer {
-  let builder = _VaListBuilder()
+  let builder = __VaListBuilder()
   for a in args {
     builder.append(a)
   }
@@ -406,9 +406,12 @@
 
 /// An object that can manage the lifetime of storage backing a
 /// `CVaListPointer`.
+// NOTE: older runtimes called this _VaListBuilder. The two must
+// coexist, so it was renamed. The old name must not be used in the new
+// runtime.
 @_fixed_layout
 @usableFromInline // c-abi
-final internal class _VaListBuilder {
+final internal class __VaListBuilder {
   @_fixed_layout // c-abi
   @usableFromInline
   internal struct Header {
@@ -503,9 +506,12 @@
 
 /// An object that can manage the lifetime of storage backing a
 /// `CVaListPointer`.
+// NOTE: older runtimes called this _VaListBuilder. The two must
+// coexist, so it was renamed. The old name must not be used in the new
+// runtime.
 @_fixed_layout
 @usableFromInline // c-abi
-final internal class _VaListBuilder {
+final internal class __VaListBuilder {
 
   @inlinable // c-abi
   internal init() {}
@@ -533,16 +539,16 @@
   }
 
   // NB: This function *cannot* be @inlinable because it expects to project
-  // and escape the physical storage of `_VaListBuilder.alignedStorageForEmptyVaLists`.
+  // and escape the physical storage of `__VaListBuilder.alignedStorageForEmptyVaLists`.
   // Marking it inlinable will cause it to resiliently use accessors to
-  // project `_VaListBuilder.alignedStorageForEmptyVaLists` as a computed
+  // project `__VaListBuilder.alignedStorageForEmptyVaLists` as a computed
   // property.
   @usableFromInline // c-abi
   internal func va_list() -> CVaListPointer {
     // Use Builtin.addressof to emphasize that we are deliberately escaping this
     // pointer and assuming it is safe to do so.
     let emptyAddr = UnsafeMutablePointer<Int>(
-      Builtin.addressof(&_VaListBuilder.alignedStorageForEmptyVaLists))
+      Builtin.addressof(&__VaListBuilder.alignedStorageForEmptyVaLists))
     return CVaListPointer(_fromUnsafeMutablePointer: storage ?? emptyAddr)
   }
 
diff --git a/test/ClangImporter/Inputs/custom-modules/BlocksReturningBool.h b/test/ClangImporter/Inputs/custom-modules/BlocksReturningBool.h
new file mode 100644
index 0000000..832d461
--- /dev/null
+++ b/test/ClangImporter/Inputs/custom-modules/BlocksReturningBool.h
@@ -0,0 +1,5 @@
+typedef unsigned long size_t;
+typedef _Bool (^predicate_t)(size_t);
+typedef struct {
+  void (*takePredicate)(predicate_t);
+} Aggregate;
diff --git a/test/ClangImporter/Inputs/custom-modules/module.map b/test/ClangImporter/Inputs/custom-modules/module.map
index 93cfbaf..3e7e616 100644
--- a/test/ClangImporter/Inputs/custom-modules/module.map
+++ b/test/ClangImporter/Inputs/custom-modules/module.map
@@ -203,6 +203,10 @@
   header "ObjCBridgeNonconforming.h"
 }
 
+module BlocksReturningBool {
+  header "BlocksReturningBool.h"
+}
+
 module Warnings1 { header "Warnings1.h" }
 module Warnings2 { header "Warnings2.h" }
 module Warnings3 { header "Warnings3.h" }
diff --git a/test/ClangImporter/blocks_returning_bool.swift b/test/ClangImporter/blocks_returning_bool.swift
new file mode 100644
index 0000000..7fdaff1
--- /dev/null
+++ b/test/ClangImporter/blocks_returning_bool.swift
@@ -0,0 +1,14 @@
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-silgen %s -I %S/Inputs/ | %FileCheck %s
+
+// REQUIRES: objc_interop
+
+import Foundation
+import BlocksReturningBool
+
+// rdar://43656704
+
+// CHECK-LABEL: sil {{.*}} @$sSo9Aggregatea13takePredicateABySbSicSgXCSg_tcfC
+// CHECK-SAME: Optional<@convention(c) (Optional<@convention(block) (Int) -> Bool>) -> ()>
+func foo() -> Aggregate {
+  return Aggregate(takePredicate: nil)
+}
diff --git a/test/Constraints/operator.swift b/test/Constraints/operator.swift
index 28a583f..281aedb 100644
--- a/test/Constraints/operator.swift
+++ b/test/Constraints/operator.swift
@@ -208,3 +208,19 @@
 var c: Int = 0
 c ??= 5 // expected-error{{binary operator '??=' cannot be applied to two 'Int' operands}}
 // expected-note@-1{{expected an argument list of type '(inout T?, T?)'}}
+
+func rdar46459603() {
+  enum E {
+  case foo(value: String)
+  }
+
+  let e = E.foo(value: "String")
+  var arr = ["key": e]
+
+  _ = arr.values == [e]
+  // expected-error@-1 {{binary operator '==' cannot be applied to operands of type 'Dictionary<String, E>.Values' and '[E]'}}
+  // expected-note@-2  {{expected an argument list of type '(Self, Self)'}}
+  _ = [arr.values] == [[e]]
+  // expected-error@-1 {{binary operator '==' cannot be applied to operands of type '[Dictionary<String, E>.Values]' and '[[E]]'}}
+  // expected-note@-2  {{expected an argument list of type '(Self, Self)'}}
+}
diff --git a/test/IRGen/objc_runtime_name_attr.swift b/test/IRGen/objc_runtime_name_attr.swift
new file mode 100644
index 0000000..ad41d40
--- /dev/null
+++ b/test/IRGen/objc_runtime_name_attr.swift
@@ -0,0 +1,17 @@
+// RUN: %empty-directory(%t)
+// RUN: %target-swift-frontend %s -emit-ir | %FileCheck %s
+
+// REQUIRES: objc_interop
+
+//import Foundation
+
+class NormalEverydayClass {}
+// CHECK: @"$s22objc_runtime_name_attr19NormalEverydayClassCMm" = hidden global %objc_class
+// CHECK: @_DATA__TtC22objc_runtime_name_attr19NormalEverydayClass = private constant
+
+
+@_objcRuntimeName(RenamedClass)
+class ThisWillBeRenamed {}
+// CHECK: @"$s22objc_runtime_name_attr17ThisWillBeRenamedCMm" = hidden global %objc_class
+// CHECK: @_DATA_RenamedClass = private constant
+
diff --git a/test/api-digester/Inputs/stdlib-stable-abi.json b/test/api-digester/Inputs/stdlib-stable-abi.json
index 150ccd9..4fab20c 100644
--- a/test/api-digester/Inputs/stdlib-stable-abi.json
+++ b/test/api-digester/Inputs/stdlib-stable-abi.json
@@ -254167,9 +254167,9 @@
         },
         {
           "kind": "TypeNominal",
-          "name": "_VaListBuilder",
-          "printedName": "_VaListBuilder",
-          "usr": "s:s14_VaListBuilderC"
+          "name": "__VaListBuilder",
+          "printedName": "__VaListBuilder",
+          "usr": "s:s15__VaListBuilderC"
         },
         {
           "kind": "TypeFunc",
@@ -254272,8 +254272,8 @@
     },
     {
       "kind": "TypeDecl",
-      "name": "_VaListBuilder",
-      "printedName": "_VaListBuilder",
+      "name": "__VaListBuilder",
+      "printedName": "__VaListBuilder",
       "children": [
         {
           "kind": "TypeDecl",
@@ -254288,12 +254288,12 @@
                 {
                   "kind": "TypeNominal",
                   "name": "Header",
-                  "printedName": "_VaListBuilder.Header",
-                  "usr": "s:s14_VaListBuilderC6HeaderV"
+                  "printedName": "__VaListBuilder.Header",
+                  "usr": "s:s15__VaListBuilderC6HeaderV"
                 }
               ],
               "declKind": "Constructor",
-              "usr": "s:s14_VaListBuilderC6HeaderVADycfc",
+              "usr": "s:s15__VaListBuilderC6HeaderVADycfc",
               "moduleName": "Swift",
               "declAttributes": [
                 "Inlinable"
@@ -254323,7 +254323,7 @@
                     }
                   ],
                   "declKind": "Accessor",
-                  "usr": "s:s14_VaListBuilderC6HeaderV9gp_offsets6UInt32Vvg",
+                  "usr": "s:s15__VaListBuilderC6HeaderV9gp_offsets6UInt32Vvg",
                   "moduleName": "Swift",
                   "implicit": true,
                   "declAttributes": [
@@ -254332,7 +254332,7 @@
                 }
               ],
               "declKind": "Var",
-              "usr": "s:s14_VaListBuilderC6HeaderV9gp_offsets6UInt32Vvp",
+              "usr": "s:s15__VaListBuilderC6HeaderV9gp_offsets6UInt32Vvp",
               "moduleName": "Swift",
               "declAttributes": [
                 "HasInitialValue",
@@ -254365,7 +254365,7 @@
                     }
                   ],
                   "declKind": "Accessor",
-                  "usr": "s:s14_VaListBuilderC6HeaderV9fp_offsets6UInt32Vvg",
+                  "usr": "s:s15__VaListBuilderC6HeaderV9fp_offsets6UInt32Vvg",
                   "moduleName": "Swift",
                   "implicit": true,
                   "declAttributes": [
@@ -254374,7 +254374,7 @@
                 }
               ],
               "declKind": "Var",
-              "usr": "s:s14_VaListBuilderC6HeaderV9fp_offsets6UInt32Vvp",
+              "usr": "s:s15__VaListBuilderC6HeaderV9fp_offsets6UInt32Vvp",
               "moduleName": "Swift",
               "declAttributes": [
                 "HasInitialValue",
@@ -254439,7 +254439,7 @@
                     }
                   ],
                   "declKind": "Accessor",
-                  "usr": "s:s14_VaListBuilderC6HeaderV17overflow_arg_areaSpySiGSgvg",
+                  "usr": "s:s15__VaListBuilderC6HeaderV17overflow_arg_areaSpySiGSgvg",
                   "moduleName": "Swift",
                   "implicit": true,
                   "declAttributes": [
@@ -254448,7 +254448,7 @@
                 }
               ],
               "declKind": "Var",
-              "usr": "s:s14_VaListBuilderC6HeaderV17overflow_arg_areaSpySiGSgvp",
+              "usr": "s:s15__VaListBuilderC6HeaderV17overflow_arg_areaSpySiGSgvp",
               "moduleName": "Swift",
               "declAttributes": [
                 "HasInitialValue",
@@ -254513,7 +254513,7 @@
                     }
                   ],
                   "declKind": "Accessor",
-                  "usr": "s:s14_VaListBuilderC6HeaderV13reg_save_areaSpySiGSgvg",
+                  "usr": "s:s15__VaListBuilderC6HeaderV13reg_save_areaSpySiGSgvg",
                   "moduleName": "Swift",
                   "implicit": true,
                   "declAttributes": [
@@ -254522,7 +254522,7 @@
                 }
               ],
               "declKind": "Var",
-              "usr": "s:s14_VaListBuilderC6HeaderV13reg_save_areaSpySiGSgvp",
+              "usr": "s:s15__VaListBuilderC6HeaderV13reg_save_areaSpySiGSgvp",
               "moduleName": "Swift",
               "declAttributes": [
                 "HasInitialValue",
@@ -254533,7 +254533,7 @@
             }
           ],
           "declKind": "Struct",
-          "usr": "s:s14_VaListBuilderC6HeaderV",
+          "usr": "s:s15__VaListBuilderC6HeaderV",
           "moduleName": "Swift",
           "declAttributes": [
             "UsableFromInline",
@@ -254564,7 +254564,7 @@
                 }
               ],
               "declKind": "Accessor",
-              "usr": "s:s14_VaListBuilderC15gpRegistersUsedSivg",
+              "usr": "s:s15__VaListBuilderC15gpRegistersUsedSivg",
               "moduleName": "Swift",
               "implicit": true,
               "declAttributes": [
@@ -254574,7 +254574,7 @@
             }
           ],
           "declKind": "Var",
-          "usr": "s:s14_VaListBuilderC15gpRegistersUsedSivp",
+          "usr": "s:s15__VaListBuilderC15gpRegistersUsedSivp",
           "moduleName": "Swift",
           "declAttributes": [
             "Final",
@@ -254608,7 +254608,7 @@
                 }
               ],
               "declKind": "Accessor",
-              "usr": "s:s14_VaListBuilderC15fpRegistersUsedSivg",
+              "usr": "s:s15__VaListBuilderC15fpRegistersUsedSivg",
               "moduleName": "Swift",
               "implicit": true,
               "declAttributes": [
@@ -254618,7 +254618,7 @@
             }
           ],
           "declKind": "Var",
-          "usr": "s:s14_VaListBuilderC15fpRegistersUsedSivp",
+          "usr": "s:s15__VaListBuilderC15fpRegistersUsedSivp",
           "moduleName": "Swift",
           "declAttributes": [
             "Final",
@@ -254636,8 +254636,8 @@
             {
               "kind": "TypeNominal",
               "name": "Header",
-              "printedName": "_VaListBuilder.Header",
-              "usr": "s:s14_VaListBuilderC6HeaderV"
+              "printedName": "__VaListBuilder.Header",
+              "usr": "s:s15__VaListBuilderC6HeaderV"
             },
             {
               "kind": "Getter",
@@ -254647,12 +254647,12 @@
                 {
                   "kind": "TypeNominal",
                   "name": "Header",
-                  "printedName": "_VaListBuilder.Header",
-                  "usr": "s:s14_VaListBuilderC6HeaderV"
+                  "printedName": "__VaListBuilder.Header",
+                  "usr": "s:s15__VaListBuilderC6HeaderV"
                 }
               ],
               "declKind": "Accessor",
-              "usr": "s:s14_VaListBuilderC6headerAB6HeaderVvg",
+              "usr": "s:s15__VaListBuilderC6headerAB6HeaderVvg",
               "moduleName": "Swift",
               "implicit": true,
               "declAttributes": [
@@ -254662,7 +254662,7 @@
             }
           ],
           "declKind": "Var",
-          "usr": "s:s14_VaListBuilderC6headerAB6HeaderVvp",
+          "usr": "s:s15__VaListBuilderC6headerAB6HeaderVvp",
           "moduleName": "Swift",
           "declAttributes": [
             "HasInitialValue",
@@ -254712,7 +254712,7 @@
                 }
               ],
               "declKind": "Accessor",
-              "usr": "s:s14_VaListBuilderC7storages15ContiguousArrayVySiGvg",
+              "usr": "s:s15__VaListBuilderC7storages15ContiguousArrayVySiGvg",
               "moduleName": "Swift",
               "implicit": true,
               "declAttributes": [
@@ -254722,7 +254722,7 @@
             }
           ],
           "declKind": "Var",
-          "usr": "s:s14_VaListBuilderC7storages15ContiguousArrayVySiGvp",
+          "usr": "s:s15__VaListBuilderC7storages15ContiguousArrayVySiGvp",
           "moduleName": "Swift",
           "declAttributes": [
             "Final",
@@ -254738,13 +254738,13 @@
           "children": [
             {
               "kind": "TypeNominal",
-              "name": "_VaListBuilder",
-              "printedName": "_VaListBuilder",
-              "usr": "s:s14_VaListBuilderC"
+              "name": "__VaListBuilder",
+              "printedName": "__VaListBuilder",
+              "usr": "s:s15__VaListBuilderC"
             }
           ],
           "declKind": "Constructor",
-          "usr": "s:s14_VaListBuilderCABycfc",
+          "usr": "s:s15__VaListBuilderCABycfc",
           "moduleName": "Swift",
           "declAttributes": [
             "Inlinable"
@@ -254768,7 +254768,7 @@
             }
           ],
           "declKind": "Func",
-          "usr": "s:s14_VaListBuilderC6appendyys7CVarArg_pF",
+          "usr": "s:s15__VaListBuilderC6appendyys7CVarArg_pF",
           "moduleName": "Swift",
           "declAttributes": [
             "Final",
@@ -254789,7 +254789,7 @@
             }
           ],
           "declKind": "Func",
-          "usr": "s:s14_VaListBuilderC7va_lists03CVaB7PointerVyF",
+          "usr": "s:s15__VaListBuilderC7va_lists03CVaB7PointerVyF",
           "moduleName": "Swift",
           "declAttributes": [
             "Final",
@@ -254799,7 +254799,7 @@
         }
       ],
       "declKind": "Class",
-      "usr": "s:s14_VaListBuilderC",
+      "usr": "s:s15__VaListBuilderC",
       "moduleName": "Swift",
       "declAttributes": [
         "Final",