Merge pull request #21471 from drodriguez/android-aarch64-preset

[build-preset] Add Android AArch64 preset.
diff --git a/CMakeLists.txt b/CMakeLists.txt
index cd63221..8166b35 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -898,14 +898,20 @@
   if(CMAKE_C_COMPILER_ID STREQUAL Clang AND
      CMAKE_C_COMPILER_VERSION VERSION_GREATER 3.8
      OR LLVM_USE_SANITIZER)
-   set(SWIFT_LIBDISPATCH_C_COMPILER ${CMAKE_C_COMPILER})
-   set(SWIFT_LIBDISPATCH_CXX_COMPILER ${CMAKE_CXX_COMPILER})
- elseif(${CMAKE_SYSTEM_NAME} STREQUAL ${CMAKE_HOST_SYSTEM_NAME})
-   set(SWIFT_LIBDISPATCH_C_COMPILER ${PATH_TO_CLANG_BUILD}/bin/clang)
-   set(SWIFT_LIBDISPATCH_CXX_COMPILER ${PATH_TO_CLANG_BUILD}/bin/clang++)
- else()
-   message(SEND_ERROR "libdispatch requires a newer clang compiler (${CMAKE_C_COMPILER_VERSION} < 3.9)")
- endif()
+    set(SWIFT_LIBDISPATCH_C_COMPILER ${CMAKE_C_COMPILER})
+    set(SWIFT_LIBDISPATCH_CXX_COMPILER ${CMAKE_CXX_COMPILER})
+  elseif(${CMAKE_SYSTEM_NAME} STREQUAL ${CMAKE_HOST_SYSTEM_NAME})
+    set(SWIFT_LIBDISPATCH_C_COMPILER ${PATH_TO_CLANG_BUILD}/bin/clang)
+    set(SWIFT_LIBDISPATCH_CXX_COMPILER ${PATH_TO_CLANG_BUILD}/bin/clang++)
+  else()
+    message(SEND_ERROR "libdispatch requires a newer clang compiler (${CMAKE_C_COMPILER_VERSION} < 3.9)")
+  endif()
+
+  if(SWIFT_HOST_VARIANT_SDK STREQUAL Windows)
+    set(SOURCEKIT_LIBDISPATCH_RUNTIME_DIR bin)
+  else()
+    set(SOURCEKIT_LIBDISPATCH_RUNTIME_DIR lib)
+  endif()
 
   include(ExternalProject)
   ExternalProject_Add(libdispatch
@@ -923,6 +929,7 @@
                         -DCMAKE_LINKER=${CMAKE_LINKER}
                         -DCMAKE_RANLIB=${CMAKE_RANLIB}
                         -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE}
+                        -DBUILD_SHARED_LIBS=YES
                         -DENABLE_SWIFT=NO
                         -DENABLE_TESTING=NO
                       INSTALL_COMMAND
@@ -933,9 +940,9 @@
                       STEP_TARGETS
                         install
                       BUILD_BYPRODUCTS
-                        <INSTALL_DIR>/lib/${CMAKE_SHARED_LIBRARY_PREFIX}dispatch${CMAKE_SHARED_LIBRARY_SUFFIX}
+                        <INSTALL_DIR>/${SOURCEKIT_LIBDISPATCH_RUNTIME_DIR}/${CMAKE_SHARED_LIBRARY_PREFIX}dispatch${CMAKE_SHARED_LIBRARY_SUFFIX}
                         <INSTALL_DIR>/lib/${CMAKE_IMPORT_LIBRARY_PREFIX}dispatch${CMAKE_IMPORT_LIBRARY_SUFFIX}
-                        <INSTALL_DIR>/lib/${CMAKE_SHARED_LIBRARY_PREFIX}BlocksRuntime${CMAKE_SHARED_LIBRARY_SUFFIX}
+                        <INSTALL_DIR>/${SOURCEKIT_LIBDISPATCH_RUNTIME_DIR}/${CMAKE_SHARED_LIBRARY_PREFIX}BlocksRuntime${CMAKE_SHARED_LIBRARY_SUFFIX}
                         <INSTALL_DIR>/lib/${CMAKE_IMPORT_LIBRARY_PREFIX}BlocksRuntime${CMAKE_IMPORT_LIBRARY_SUFFIX}
                       BUILD_ALWAYS
                         1)
@@ -951,7 +958,7 @@
   set_target_properties(dispatch
                         PROPERTIES
                           IMPORTED_LOCATION
-                            ${install_dir}/lib/${CMAKE_SHARED_LIBRARY_PREFIX}dispatch${CMAKE_SHARED_LIBRARY_SUFFIX}
+                            ${install_dir}/${SOURCEKIT_LIBDISPATCH_RUNTIME_DIR}/${CMAKE_SHARED_LIBRARY_PREFIX}dispatch${CMAKE_SHARED_LIBRARY_SUFFIX}
                           IMPORTED_IMPLIB
                             ${install_dir}/lib/${CMAKE_IMPORT_LIBRARY_PREFIX}dispatch${CMAKE_IMPORT_LIBRARY_SUFFIX}
                           INTERFACE_INCLUDE_DIRECTORIES
@@ -961,7 +968,7 @@
   set_target_properties(BlocksRuntime
                         PROPERTIES
                           IMPORTED_LOCATION
-                            ${install_dir}/lib/${CMAKE_SHARED_LIBRARY_PREFIX}BlocksRuntime${CMAKE_SHARED_LIBRARY_SUFFIX}
+                            ${install_dir}/${SOURCEKIT_LIBDISPATCH_RUNTIME_DIR}/${CMAKE_SHARED_LIBRARY_PREFIX}BlocksRuntime${CMAKE_SHARED_LIBRARY_SUFFIX}
                           IMPORTED_IMPLIB
                             ${install_dir}/lib/${CMAKE_IMPORT_LIBRARY_PREFIX}BlocksRuntime${CMAKE_IMPORT_LIBRARY_SUFFIX}
                           INTERFACE_INCLUDE_DIRECTORIES
diff --git a/docs/ABI/Mangling.rst b/docs/ABI/Mangling.rst
index 41829c7..34bef31 100644
--- a/docs/ABI/Mangling.rst
+++ b/docs/ABI/Mangling.rst
@@ -633,7 +633,9 @@
 ::
 
   concrete-protocol-conformance ::= type protocol-conformance-ref any-protocol-conformance-list 'HC'
-  protocol-conformance-ref ::= protocol module? 'HP'
+  protocol-conformance-ref ::= protocol 'HP'   // same module as conforming type
+  protocol-conformance-ref ::= protocol 'Hp'   // same module as protocol
+  protocol-conformance-ref ::= protocol module // "retroactive"
 
   any-protocol-conformance ::= concrete-protocol-conformance
   any-protocol-conformance ::= dependent-protocol-conformance
@@ -651,10 +653,13 @@
   dependent-associated-conformance ::= type protocol
 
 A compact representation used to represent mangled protocol conformance witness
-arguments at runtime. The ``module`` is only specified for conformances that are
-"retroactive", meaning that the context in which the conformance is defined is
-in neither the protocol or type module. The concrete protocol conformances that
-follow are for the conditional conformance requirements.
+arguments at runtime. The ``module`` is only specified for conformances that
+are "retroactive", meaning that the context in which the conformance is defined
+is in neither the protocol or type module. For a non-retroactive conformance
+where both the type *and* the protocol are in the same module, or for
+synthesized conformances that have no owning module, the "HP" operator is
+preferred. The concrete protocol conformances that follow are for the
+conditional conformance requirements.
 
 Dependent protocol conformances mangle the access path required to extract a
 protocol conformance from some conformance passed into the environment. The
diff --git a/include/swift/AST/DiagnosticsSema.def b/include/swift/AST/DiagnosticsSema.def
index 355b135..1467616 100644
--- a/include/swift/AST/DiagnosticsSema.def
+++ b/include/swift/AST/DiagnosticsSema.def
@@ -1703,11 +1703,11 @@
       "matches a requirement in protocol %3",
       (DescriptiveDeclKind, DeclName, AccessLevel, DeclName))
 ERROR(witness_not_usable_from_inline,none,
-      "%0 %1 must be declared '@usableFromInline' because "
+      "%0 %1 must be declared '@usableFromInline' "
       "because it matches a requirement in protocol %2",
       (DescriptiveDeclKind, DeclName, DeclName))
 WARNING(witness_not_usable_from_inline_warn,none,
-        "%0 %1 should be declared '@usableFromInline' because "
+        "%0 %1 should be declared '@usableFromInline' "
         "because it matches a requirement in protocol %2",
         (DescriptiveDeclKind, DeclName, DeclName))
 ERROR(type_witness_objc_generic_parameter,none,
diff --git a/include/swift/AST/KnownIdentifiers.def b/include/swift/AST/KnownIdentifiers.def
index 0808f93..5624a18 100644
--- a/include/swift/AST/KnownIdentifiers.def
+++ b/include/swift/AST/KnownIdentifiers.def
@@ -175,7 +175,6 @@
 IDENTIFIER_WITH_NAME(dollarInterpolation, "$interpolation")
 IDENTIFIER(arrayLiteral)
 IDENTIFIER(dictionaryLiteral)
-IDENTIFIER_(getBuiltinLogicValue)
 IDENTIFIER(className)
 
 IDENTIFIER_(ErrorType)
diff --git a/include/swift/Demangling/DemangleNodes.def b/include/swift/Demangling/DemangleNodes.def
index 0255314..6adf033 100644
--- a/include/swift/Demangling/DemangleNodes.def
+++ b/include/swift/Demangling/DemangleNodes.def
@@ -156,7 +156,9 @@
 CONTEXT_NODE(Protocol)
 CONTEXT_NODE(ProtocolSymbolicReference)
 NODE(ProtocolConformance)
-NODE(ProtocolConformanceRef)
+NODE(ProtocolConformanceRefInTypeModule)
+NODE(ProtocolConformanceRefInProtocolModule)
+NODE(ProtocolConformanceRefInOtherModule)
 NODE(ProtocolDescriptor)
 NODE(ProtocolConformanceDescriptor)
 NODE(ProtocolList)
diff --git a/include/swift/Demangling/Demangler.h b/include/swift/Demangling/Demangler.h
index b416b7e..9c3dbd0 100644
--- a/include/swift/Demangling/Demangler.h
+++ b/include/swift/Demangling/Demangler.h
@@ -458,7 +458,7 @@
   NodePointer getDependentGenericParamType(int depth, int index);
   NodePointer demangleGenericParamIndex();
   NodePointer popProtocolConformance();
-  NodePointer demangleProtocolConformanceRef();
+  NodePointer demangleRetroactiveProtocolConformanceRef();
   NodePointer popAnyProtocolConformance();
   NodePointer demangleConcreteProtocolConformance();
   NodePointer popDependentProtocolConformance();
diff --git a/include/swift/SIL/SILModule.h b/include/swift/SIL/SILModule.h
index 97ede7c..edba967 100644
--- a/include/swift/SIL/SILModule.h
+++ b/include/swift/SIL/SILModule.h
@@ -570,11 +570,6 @@
   /// hierarchy of \p Class.
   SILFunction *lookUpFunctionInVTable(ClassDecl *Class, SILDeclRef Member);
 
-  // Given a protocol conformance, attempt to create a witness table declaration
-  // for it.
-  SILWitnessTable *
-  createWitnessTableDeclaration(ProtocolConformance *C, SILLinkage linkage);
-
   // Given a protocol, attempt to create a default witness table declaration
   // for it.
   SILDefaultWitnessTable *
diff --git a/include/swift/SILOptimizer/Utils/Devirtualize.h b/include/swift/SILOptimizer/Utils/Devirtualize.h
index ee08fd8..c9d3e3c 100644
--- a/include/swift/SILOptimizer/Utils/Devirtualize.h
+++ b/include/swift/SILOptimizer/Utils/Devirtualize.h
@@ -48,6 +48,18 @@
                       SILModule &M,
                       ClassHierarchyAnalysis::ClassList &Subs);
 
+/// Given an apply instruction of a protocol requirement and a witness method
+/// for the requirement, compute a substitution suitable for a direct call
+/// to the witness method.
+///
+/// \p Module SILModule
+/// \p AI ApplySite that applies a procotol method
+/// \p F SILFunction with convention @convention(witness_method)
+/// \p CRef a concrete ProtocolConformanceRef
+SubstitutionMap getWitnessMethodSubstitutions(SILModule &Module, ApplySite AI,
+                                              SILFunction *F,
+                                              ProtocolConformanceRef CRef);
+
 /// Attempt to devirtualize the given apply site.  If this fails,
 /// the returned ApplySite will be null.
 ///
diff --git a/lib/AST/ASTMangler.cpp b/lib/AST/ASTMangler.cpp
index 8cc79af..114d38a 100644
--- a/lib/AST/ASTMangler.cpp
+++ b/lib/AST/ASTMangler.cpp
@@ -1105,6 +1105,24 @@
   }
 }
 
+static bool conformanceHasIdentity(const RootProtocolConformance *root) {
+  auto conformance = dyn_cast<NormalProtocolConformance>(root);
+  if (!conformance) {
+    assert(isa<SelfProtocolConformance>(root));
+    return true;
+  }
+
+  // Synthesized non-unique conformances all get collapsed together at run time.
+  if (conformance->isSynthesizedNonUnique())
+    return false;
+
+  // Objective-C protocol conformances are checked by the ObjC runtime.
+  if (conformance->getProtocol()->isObjC())
+    return false;
+
+  return true;
+}
+
 /// Determine whether the given protocol conformance is itself retroactive,
 /// meaning that there might be multiple conflicting conformances of the
 /// same type to the same protocol.
@@ -1115,20 +1133,7 @@
     return false; // self-conformances are never retroactive.
   }
 
-  /// Non-retroactive conformances are... never retroactive.
-  if (!conformance->isRetroactive())
-    return false;
-
-  /// Synthesized non-unique conformances all get collapsed together at run
-  /// time.
-  if (conformance->isSynthesizedNonUnique())
-    return false;
-
-  /// Objective-C protocol conformances don't have identity.
-  if (conformance->getProtocol()->isObjC())
-    return false;
-
-  return true;
+  return conformance->isRetroactive();
 }
 
 /// Determine whether the given protocol conformance contains a retroactive
@@ -1137,16 +1142,32 @@
                                       const ProtocolConformance *conformance,
                                       ModuleDecl *module) {
   // If the root conformance is retroactive, it's retroactive.
-  if (isRetroactiveConformance(conformance->getRootConformance()))
+  const RootProtocolConformance *rootConformance =
+      conformance->getRootConformance();
+  if (isRetroactiveConformance(rootConformance) &&
+      conformanceHasIdentity(rootConformance))
     return true;
 
-  // If any of the substitutions used to form this conformance are retroactive,
-  // it's retroactive.
+  // If the conformance is conditional and any of the substitutions used to
+  // satisfy the conditions are retroactive, it's retroactive.
   auto subMap = conformance->getSubstitutions(module);
-  for (auto conformance : subMap.getConformances()) {
-    if (conformance.isConcrete() &&
-        containsRetroactiveConformance(conformance.getConcrete(), module))
+  for (auto requirement : rootConformance->getConditionalRequirements()) {
+    if (requirement.getKind() != RequirementKind::Conformance)
+      continue;
+    ProtocolDecl *proto =
+        requirement.getSecondType()->castTo<ProtocolType>()->getDecl();
+    Optional<ProtocolConformanceRef> conformance =
+        subMap.lookupConformance(requirement.getFirstType()->getCanonicalType(),
+                                 proto);
+    if (!conformance) {
+      // This should only happen when mangling invalid ASTs, but that happens
+      // for indexing purposes.
+      continue;
+    }
+    if (conformance->isConcrete() &&
+        containsRetroactiveConformance(conformance->getConcrete(), module)) {
       return true;
+    }
   }
 
   return false;
@@ -2278,12 +2299,19 @@
   appendProtocolName(conformance->getProtocol());
 
   // For retroactive conformances, add a reference to the module in which the
-  // conformance resides. For @objc protocols, there is no point: conformances
-  // are global anyway.
-  if (isRetroactiveConformance(conformance))
+  // conformance resides. Otherwise, use an operator to indicate which known
+  // module it's associated with.
+  if (!conformanceHasIdentity(conformance)) {
+    // Same as "conformance module matches type", below.
+    appendOperator("HP");
+  } else if (isRetroactiveConformance(conformance)) {
     appendModule(conformance->getDeclContext()->getParentModule());
-
-  appendOperator("HP");
+  } else if (conformance->getDeclContext()->getParentModule() ==
+               conformance->getType()->getAnyNominal()->getParentModule()) {
+    appendOperator("HP");
+  } else {
+    appendOperator("Hp");
+  }
 }
 
 /// Retrieve the index of the conformance requirement indicated by the
diff --git a/lib/AST/ASTVerifier.cpp b/lib/AST/ASTVerifier.cpp
index 568607b..f7d7e06 100644
--- a/lib/AST/ASTVerifier.cpp
+++ b/lib/AST/ASTVerifier.cpp
@@ -996,7 +996,7 @@
       case StmtConditionElement::CK_Boolean: {
         auto *E = elt.getBoolean();
         if (shouldVerifyChecked(E))
-          checkSameType(E->getType(), BuiltinIntegerType::get(1, Ctx),
+          checkSameType(E->getType(), Ctx.getBoolDecl()->getDeclaredType(),
                         "condition type");
         break;
       }
@@ -2070,8 +2070,8 @@
       PrettyStackTraceExpr debugStack(Ctx, "verifying IfExpr", E);
 
       auto condTy = E->getCondExpr()->getType();
-      if (!condTy->isBuiltinIntegerType(1)) {
-        Out << "IfExpr condition is not an i1\n";
+      if (!condTy->isBool()) {
+        Out << "IfExpr condition is not Bool\n";
         abort();
       }
 
diff --git a/lib/Demangling/Demangler.cpp b/lib/Demangling/Demangler.cpp
index f9d9985..1888edf 100644
--- a/lib/Demangling/Demangler.cpp
+++ b/lib/Demangling/Demangler.cpp
@@ -610,7 +610,12 @@
       case 'C': return demangleConcreteProtocolConformance();
       case 'D': return demangleDependentProtocolConformanceRoot();
       case 'I': return demangleDependentProtocolConformanceInherited();
-      case 'P': return demangleProtocolConformanceRef();
+      case 'P':
+        return createWithChild(
+            Node::Kind::ProtocolConformanceRefInTypeModule, popProtocol());
+      case 'p':
+        return createWithChild(
+            Node::Kind::ProtocolConformanceRefInProtocolModule, popProtocol());
       default:
         pushBack();
         pushBack();
@@ -1295,22 +1300,27 @@
   });
 }
 
-NodePointer Demangler::demangleProtocolConformanceRef() {
+NodePointer Demangler::demangleRetroactiveProtocolConformanceRef() {
   NodePointer module = popModule();
   NodePointer proto = popProtocol();
   auto protocolConformanceRef =
-    createWithChild(Node::Kind::ProtocolConformanceRef, proto);
-
-  // The module is optional, present only for retroactive conformances. Add it
-  // as the second child.
-  if (protocolConformanceRef && module)
-    protocolConformanceRef->addChild(module, *this);
+      createWithChildren(Node::Kind::ProtocolConformanceRefInOtherModule,
+                         proto, module);
   return protocolConformanceRef;
 }
 
 NodePointer Demangler::demangleConcreteProtocolConformance() {
   NodePointer conditionalConformanceList = popAnyProtocolConformanceList();
-  NodePointer conformanceRef = popNode(Node::Kind::ProtocolConformanceRef);
+
+  NodePointer conformanceRef =
+      popNode(Node::Kind::ProtocolConformanceRefInTypeModule);
+  if (!conformanceRef) {
+    conformanceRef =
+        popNode(Node::Kind::ProtocolConformanceRefInProtocolModule);
+  }
+  if (!conformanceRef)
+    conformanceRef = demangleRetroactiveProtocolConformanceRef();
+
   NodePointer type = popNode(Node::Kind::Type);
   return createWithChildren(Node::Kind::ConcreteProtocolConformance,
                             type, conformanceRef, conditionalConformanceList);
diff --git a/lib/Demangling/NodePrinter.cpp b/lib/Demangling/NodePrinter.cpp
index ba3350f..345748d 100644
--- a/lib/Demangling/NodePrinter.cpp
+++ b/lib/Demangling/NodePrinter.cpp
@@ -497,7 +497,9 @@
     case Node::Kind::DependentProtocolConformanceAssociated:
     case Node::Kind::DependentProtocolConformanceInherited:
     case Node::Kind::DependentProtocolConformanceRoot:
-    case Node::Kind::ProtocolConformanceRef:
+    case Node::Kind::ProtocolConformanceRefInTypeModule:
+    case Node::Kind::ProtocolConformanceRefInProtocolModule:
+    case Node::Kind::ProtocolConformanceRefInOtherModule:
     case Node::Kind::DynamicallyReplaceableFunctionKey:
     case Node::Kind::DynamicallyReplaceableFunctionImpl:
     case Node::Kind::DynamicallyReplaceableFunctionVar:
@@ -2172,7 +2174,16 @@
       << " ";
     printChildren(Node);
     return nullptr;
-  case Node::Kind::ProtocolConformanceRef:
+  case Node::Kind::ProtocolConformanceRefInTypeModule:
+    Printer << "protocol conformance ref (type's module) ";
+    printChildren(Node);
+    return nullptr;
+  case Node::Kind::ProtocolConformanceRefInProtocolModule:
+    Printer << "protocol conformance ref (protocol's module) ";
+    printChildren(Node);
+    return nullptr;
+  case Node::Kind::ProtocolConformanceRefInOtherModule:
+    Printer << "protocol conformance ref (retroactive) ";
     printChildren(Node);
     return nullptr;
   }
diff --git a/lib/Demangling/OldRemangler.cpp b/lib/Demangling/OldRemangler.cpp
index 9556ba6..71c6abf 100644
--- a/lib/Demangling/OldRemangler.cpp
+++ b/lib/Demangling/OldRemangler.cpp
@@ -680,7 +680,15 @@
   unreachable("Retroactive conformances aren't in the old mangling");
 }
 
-void Remangler::mangleProtocolConformanceRef(Node *node) {
+void Remangler::mangleProtocolConformanceRefInTypeModule(Node *node) {
+  unreachable("Protocol conformance references aren't in the old mangling");
+}
+
+void Remangler::mangleProtocolConformanceRefInProtocolModule(Node *node) {
+  unreachable("Protocol conformance references aren't in the old mangling");
+}
+
+void Remangler::mangleProtocolConformanceRefInOtherModule(Node *node) {
   unreachable("Protocol conformance references aren't in the old mangling");
 }
 
diff --git a/lib/Demangling/Remangler.cpp b/lib/Demangling/Remangler.cpp
index c42a977..a11e80e 100644
--- a/lib/Demangling/Remangler.cpp
+++ b/lib/Demangling/Remangler.cpp
@@ -1655,16 +1655,24 @@
     mangle(GenSig);
 }
 
-void Remangler::mangleProtocolConformanceRef(Node *node) {
+void Remangler::mangleProtocolConformanceRefInTypeModule(Node *node) {
   manglePureProtocol(node->getChild(0));
-  if (node->getNumChildren() > 1)
-    mangleChildNode(node, 1);
   Buffer << "HP";
 }
 
+void Remangler::mangleProtocolConformanceRefInProtocolModule(Node *node) {
+  manglePureProtocol(node->getChild(0));
+  Buffer << "Hp";
+}
+
+void Remangler::mangleProtocolConformanceRefInOtherModule(Node *node) {
+  manglePureProtocol(node->getChild(0));
+  mangleChildNode(node, 1);
+}
+
 void Remangler::mangleConcreteProtocolConformance(Node *node) {
   mangleType(node->getChild(0));
-  mangleProtocolConformanceRef(node->getChild(1));
+  mangle(node->getChild(1));
   if (node->getNumChildren() > 2)
     mangleAnyProtocolConformanceList(node->getChild(2));
   else
diff --git a/lib/IRGen/GenClass.cpp b/lib/IRGen/GenClass.cpp
index fe009fa..15b0b7f 100644
--- a/lib/IRGen/GenClass.cpp
+++ b/lib/IRGen/GenClass.cpp
@@ -1908,8 +1908,9 @@
       else
         (void)0;
       
-      // If the property has storage, emit the ivar name last.
-      if (prop->hasStorage())
+      // If the property is an instance property and has storage, emit the ivar
+      // name last.
+      if (!prop->isStatic() && prop->hasStorage())
         outs << ",V" << prop->getName();
     }
 
diff --git a/lib/IRGen/IRGenModule.cpp b/lib/IRGen/IRGenModule.cpp
index 45b3542..6d18685 100644
--- a/lib/IRGen/IRGenModule.cpp
+++ b/lib/IRGen/IRGenModule.cpp
@@ -769,7 +769,7 @@
 }
 
 void IRGenerator::addLazyWitnessTable(const ProtocolConformance *Conf) {
-  if (SILWitnessTable *wt = SIL.lookUpWitnessTable(Conf)) {
+  if (auto *wt = SIL.lookUpWitnessTable(Conf, /*deserializeLazily=*/false)) {
     // Add it to the queue if it hasn't already been put there.
     if (canEmitWitnessTableLazily(wt) &&
         LazilyEmittedWitnessTables.insert(wt).second) {
diff --git a/lib/ParseSIL/ParseSIL.cpp b/lib/ParseSIL/ParseSIL.cpp
index 9a9d9f8..43fe6b2 100644
--- a/lib/ParseSIL/ParseSIL.cpp
+++ b/lib/ParseSIL/ParseSIL.cpp
@@ -6184,6 +6184,8 @@
 
   if (!wt)
     wt = SILWitnessTable::create(M, *Linkage, theConformance);
+  else
+    wt->setLinkage(*Linkage);
   wt->convertToDefinition(witnessEntries, conditionalConformances,
                           isSerialized);
   BodyScope.reset();
diff --git a/lib/SIL/Linker.cpp b/lib/SIL/Linker.cpp
index ee67081..187593d 100644
--- a/lib/SIL/Linker.cpp
+++ b/lib/SIL/Linker.cpp
@@ -200,7 +200,7 @@
 
 void SILLinkerVisitor::visitProtocolConformance(
     ProtocolConformanceRef ref, const Optional<SILDeclRef> &Member) {
-  // If an abstract protocol conformance was passed in, just return false.
+  // If an abstract protocol conformance was passed in, do nothing.
   if (ref.isAbstract())
     return;
   
@@ -211,31 +211,16 @@
   
   if (!VisitedConformances.insert(C).second)
     return;
-  
-  SILWitnessTable *WT = Mod.lookUpWitnessTable(C, true);
 
-  // If we don't find any witness table for the conformance, bail and return
-  // false.
-  if (!WT) {
-    Mod.createWitnessTableDeclaration(
-        C, getLinkageForProtocolConformance(
-               C->getRootNormalConformance(), NotForDefinition));
-
-    // Adding the declaration may allow us to now deserialize the body.
-    // Force the body if we must deserialize this witness table.
-    if (mustDeserialize) {
-      WT = Mod.lookUpWitnessTable(C, true);
-      assert(WT && WT->isDefinition()
-             && "unable to deserialize witness table when we must?!");
-    } else {
-      return;
-    }
-  }
+  auto *WT = Mod.lookUpWitnessTable(C, mustDeserialize);
 
   // If the looked up witness table is a declaration, there is nothing we can
-  // do here. Just bail and return false.
-  if (WT->isDeclaration())
+  // do here.
+  if (WT == nullptr || WT->isDeclaration()) {
+    assert(!mustDeserialize &&
+           "unable to deserialize witness table when we must?!");
     return;
+  }
 
   auto maybeVisitRelatedConformance = [&](ProtocolConformanceRef c) {
     // Formally all conformances referenced by a used conformance are used.
diff --git a/lib/SIL/SILInstructions.cpp b/lib/SIL/SILInstructions.cpp
index 3ac4137..fa3045d 100644
--- a/lib/SIL/SILInstructions.cpp
+++ b/lib/SIL/SILInstructions.cpp
@@ -312,16 +312,6 @@
   return getLoc().getAsASTNode<VarDecl>();
 }
 
-static void declareWitnessTable(SILModule &Mod,
-                                ProtocolConformanceRef conformanceRef) {
-  if (conformanceRef.isAbstract()) return;
-  auto C = conformanceRef.getConcrete();
-  if (!Mod.lookUpWitnessTable(C, false))
-    Mod.createWitnessTableDeclaration(C,
-        getLinkageForProtocolConformance(C->getRootNormalConformance(),
-                                         NotForDefinition));
-}
-
 AllocExistentialBoxInst *AllocExistentialBoxInst::create(
     SILDebugLocation Loc, SILType ExistentialType, CanType ConcreteType,
     ArrayRef<ProtocolConformanceRef> Conformances,
@@ -333,8 +323,6 @@
   SILModule &Mod = F->getModule();
   auto Size = totalSizeToAlloc<swift::Operand>(TypeDependentOperands.size());
   auto Buffer = Mod.allocateInst(Size, alignof(AllocExistentialBoxInst));
-  for (ProtocolConformanceRef C : Conformances)
-    declareWitnessTable(Mod, C);
   return ::new (Buffer) AllocExistentialBoxInst(Loc,
                                                 ExistentialType,
                                                 ConcreteType,
@@ -1633,7 +1621,6 @@
   auto Size = totalSizeToAlloc<swift::Operand>(TypeDependentOperands.size());
   auto Buffer = Mod.allocateInst(Size, alignof(WitnessMethodInst));
 
-  declareWitnessTable(Mod, Conformance);
   return ::new (Buffer) WitnessMethodInst(Loc, LookupType, Conformance, Member,
                                           Ty, TypeDependentOperands);
 }
@@ -1667,8 +1654,6 @@
       totalSizeToAlloc<swift::Operand>(1 + TypeDependentOperands.size());
   void *Buffer = Mod.allocateInst(size,
                                   alignof(InitExistentialAddrInst));
-  for (ProtocolConformanceRef C : Conformances)
-    declareWitnessTable(Mod, C);
   return ::new (Buffer) InitExistentialAddrInst(Loc, Existential,
                                                 TypeDependentOperands,
                                                 ConcreteType,
@@ -1688,9 +1673,6 @@
       totalSizeToAlloc<swift::Operand>(1 + TypeDependentOperands.size());
 
   void *Buffer = Mod.allocateInst(size, alignof(InitExistentialRefInst));
-  for (ProtocolConformanceRef C : Conformances)
-    declareWitnessTable(Mod, C);
-
   return ::new (Buffer)
       InitExistentialValueInst(Loc, ExistentialType, ConcreteType, Instance,
                                 TypeDependentOperands, Conformances);
@@ -1711,9 +1693,6 @@
 
   void *Buffer = Mod.allocateInst(size,
                                   alignof(InitExistentialRefInst));
-  for (ProtocolConformanceRef C : Conformances)
-    declareWitnessTable(Mod, C);
-
   return ::new (Buffer) InitExistentialRefInst(Loc, ExistentialType,
                                                ConcreteType,
                                                Instance,
@@ -1746,9 +1725,6 @@
       1 + TypeDependentOperands.size(), conformances.size());
 
   void *buffer = M.allocateInst(size, alignof(InitExistentialMetatypeInst));
-  for (ProtocolConformanceRef conformance : conformances)
-    declareWitnessTable(M, conformance);
-
   return ::new (buffer) InitExistentialMetatypeInst(
       Loc, existentialMetatypeType, metatype,
       TypeDependentOperands, conformances);
diff --git a/lib/SIL/SILModule.cpp b/lib/SIL/SILModule.cpp
index ee8da6f..d3f298f 100644
--- a/lib/SIL/SILModule.cpp
+++ b/lib/SIL/SILModule.cpp
@@ -144,19 +144,6 @@
 }
 
 SILWitnessTable *
-SILModule::createWitnessTableDeclaration(ProtocolConformance *C,
-                                         SILLinkage linkage) {
-  // If we are passed in a null conformance (a valid value), just return nullptr
-  // since we cannot map a witness table to it.
-  if (!C)
-    return nullptr;
-
-  // Extract the root conformance.
-  auto rootC = C->getRootConformance();
-  return SILWitnessTable::create(*this, linkage, rootC);
-}
-
-SILWitnessTable *
 SILModule::lookUpWitnessTable(ProtocolConformanceRef C,
                               bool deserializeLazily) {
   // If we have an abstract conformance passed in (a legal value), just return
@@ -172,6 +159,8 @@
                               bool deserializeLazily) {
   assert(C && "null conformance passed to lookUpWitnessTable");
 
+  SILWitnessTable *wtable;
+
   auto rootC = C->getRootConformance();
   // Attempt to lookup the witness table from the table.
   auto found = WitnessTableMap.find(rootC);
@@ -189,17 +178,25 @@
              "Found witness table that is not"
              " in the witness table lookup cache.");
 #endif
-    return nullptr;
+
+    // If we don't have a witness table and we're not going to try
+    // deserializing it, do not create a declaration.
+    if (!deserializeLazily)
+      return nullptr;
+
+    auto linkage = getLinkageForProtocolConformance(rootC, NotForDefinition);
+    wtable = SILWitnessTable::create(*this, linkage,
+                                 const_cast<RootProtocolConformance *>(rootC));
+  } else {
+    wtable = found->second;
+    assert(wtable != nullptr && "Should never map a conformance to a null witness"
+                            " table.");
+
+    // If we have a definition, return it.
+    if (wtable->isDefinition())
+      return wtable;
   }
 
-  SILWitnessTable *wtable = found->second;
-  assert(wtable != nullptr && "Should never map a conformance to a null witness"
-                          " table.");
-
-  // If we have a definition, return it.
-  if (wtable->isDefinition())
-    return wtable;
-
   // If the module is at or past the Lowered stage, then we can't do any
   // further deserialization, since pre-IRGen SIL lowering changes the types
   // of definitions to make them incompatible with canonical serialized SIL.
diff --git a/lib/SIL/SILVerifier.cpp b/lib/SIL/SILVerifier.cpp
index 3c574c6..6798e44 100644
--- a/lib/SIL/SILVerifier.cpp
+++ b/lib/SIL/SILVerifier.cpp
@@ -2493,8 +2493,6 @@
       auto conformance = AMI->getConformance().getConcrete();
       require(conformance->getType()->isEqual(AMI->getLookupType()),
               "concrete type lookup requires conformance that matches type");
-      require(AMI->getModule().lookUpWitnessTable(conformance, false),
-              "Could not find witness table for conformance");
     }
 
     require(AMI->getMember().requiresNewWitnessTableEntry(),
@@ -3204,13 +3202,6 @@
       require(conformances[i].getRequirement() == protocols[i]->getDecl(),
               "init_existential instruction must have conformances in "
               "proper order");
-
-      if (conformances[i].isConcrete()) {
-        auto conformance = conformances[i].getConcrete();
-        require(F.getModule().lookUpWitnessTable(conformance, false),
-                "Could not find witness table for conformance.");
-
-      }
     }
   }
 
diff --git a/lib/SILGen/SILGenDecl.cpp b/lib/SILGen/SILGenDecl.cpp
index e56ba53..6c6eee7 100644
--- a/lib/SILGen/SILGenDecl.cpp
+++ b/lib/SILGen/SILGenDecl.cpp
@@ -696,9 +696,12 @@
        getUnmanagedValue();
   }
 
+  assert(testBool->getType().getASTType()->isBool());
+  auto i1Value = SGF.emitUnwrapIntegerResult(loc, testBool);
+
   SILBasicBlock *contBB = SGF.B.splitBlockForFallthrough();
   auto falseBB = SGF.Cleanups.emitBlockForCleanups(getFailureDest(), loc);
-  SGF.B.createCondBranch(loc, testBool, contBB, falseBB);
+  SGF.B.createCondBranch(loc, i1Value, contBB, falseBB);
 
   SGF.B.setInsertionPoint(contBB);
 }
@@ -995,13 +998,7 @@
   assert(isInit && "Only initialization is supported for refutable patterns");
 
   // Extract the i1 from the Bool struct.
-  StructDecl *BoolStruct = cast<StructDecl>(SGF.getASTContext().getBoolDecl());
-  auto Members = BoolStruct->lookupDirect(SGF.getASTContext().Id_value_);
-  assert(Members.size() == 1 &&
-         "Bool should have only one property with name '_value'");
-  auto Member = dyn_cast<VarDecl>(Members[0]);
-  assert(Member &&"Bool should have a property with name '_value' of type Int1");
-  auto *i1Val = SGF.B.createStructExtract(loc, value.forward(SGF), Member);
+  auto i1Value = SGF.emitUnwrapIntegerResult(loc, value.forward(SGF));
 
   // Branch on the boolean based on whether we're testing for true or false.
   SILBasicBlock *trueBB = SGF.B.splitBlockForFallthrough();
@@ -1010,7 +1007,7 @@
 
   if (!pattern->getValue())
     std::swap(trueBB, falseBB);
-  SGF.B.createCondBranch(loc, i1Val, trueBB, falseBB);
+  SGF.B.createCondBranch(loc, i1Value, trueBB, falseBB);
   SGF.B.setInsertionPoint(contBB);
 }
 
@@ -1264,6 +1261,7 @@
       // Evaluate the condition as an i1 value (guaranteed by Sema).
       FullExpr Scope(Cleanups, CleanupLocation(expr));
       booleanTestValue = emitRValue(expr).forwardAsSingleValue(*this, expr);
+      booleanTestValue = emitUnwrapIntegerResult(expr, booleanTestValue);
       booleanTestLoc = expr;
       break;
     }
diff --git a/lib/SILGen/SILGenForeignError.cpp b/lib/SILGen/SILGenForeignError.cpp
index 5d16487..067338b 100644
--- a/lib/SILGen/SILGenForeignError.cpp
+++ b/lib/SILGen/SILGenForeignError.cpp
@@ -281,25 +281,6 @@
   emitThrow(loc, error);
 }
 
-/// Unwrap a value of a wrapped integer type to get at the juicy
-/// Builtin.IntegerN value within.
-static SILValue emitUnwrapIntegerResult(SILGenFunction &SGF,
-                                        SILLocation loc,
-                                        SILValue value) {
-  // This is a loop because we want to handle types that wrap integer types,
-  // like ObjCBool (which may be Bool or Int8).
-  while (!value->getType().is<BuiltinIntegerType>()) {
-    auto structDecl = value->getType().getStructOrBoundGenericStruct();
-    assert(structDecl && "value for error result wasn't of struct type!");
-    assert(std::next(structDecl->getStoredProperties().begin())
-             == structDecl->getStoredProperties().end());
-    auto property = *structDecl->getStoredProperties().begin();
-    value = SGF.B.createStructExtract(loc, value, property);
-  }
-
-  return value;
-}
-
 /// Perform a foreign error check by testing whether the call result is zero.
 /// The call result is otherwise ignored.
 static void
@@ -312,7 +293,7 @@
   }
 
   SILValue resultValue =
-    emitUnwrapIntegerResult(SGF, loc, result.getUnmanagedValue());
+    SGF.emitUnwrapIntegerResult(loc, result.getUnmanagedValue());
   auto resultType = resultValue->getType().getASTType();
 
   if (!resultType->isBuiltinIntegerType(1)) {
diff --git a/lib/SILGen/SILGenFunction.cpp b/lib/SILGen/SILGenFunction.cpp
index 28f7590..e4ef770 100644
--- a/lib/SILGen/SILGenFunction.cpp
+++ b/lib/SILGen/SILGenFunction.cpp
@@ -687,3 +687,19 @@
     return SP->getPGOParent(Node);
   return None;
 }
+
+SILValue SILGenFunction::emitUnwrapIntegerResult(SILLocation loc,
+                                                 SILValue value) {
+  // This is a loop because we want to handle types that wrap integer types,
+  // like ObjCBool (which may be Bool or Int8).
+  while (!value->getType().is<BuiltinIntegerType>()) {
+    auto structDecl = value->getType().getStructOrBoundGenericStruct();
+    assert(structDecl && "value for error result wasn't of struct type!");
+    assert(std::next(structDecl->getStoredProperties().begin())
+           == structDecl->getStoredProperties().end());
+    auto property = *structDecl->getStoredProperties().begin();
+    value = B.createStructExtract(loc, value, property);
+  }
+
+  return value;
+}
diff --git a/lib/SILGen/SILGenFunction.h b/lib/SILGen/SILGenFunction.h
index 1cdcaeb..233cfac 100644
--- a/lib/SILGen/SILGenFunction.h
+++ b/lib/SILGen/SILGenFunction.h
@@ -1343,6 +1343,8 @@
                                            SILValue semanticValue,
                                            SILType storageType);
 
+  SILValue emitUnwrapIntegerResult(SILLocation loc, SILValue value);
+  
   /// Load an r-value out of the given address. This does not handle
   /// reabstraction or bridging. If that is needed, use the other emit load
   /// entry point.
diff --git a/lib/SILGen/SILGenPattern.cpp b/lib/SILGen/SILGenPattern.cpp
index d38c136..209981b 100644
--- a/lib/SILGen/SILGenPattern.cpp
+++ b/lib/SILGen/SILGenPattern.cpp
@@ -1210,7 +1210,9 @@
     testBool = SGF.emitRValueAsSingleValue(guard).getUnmanagedValue();
   }
 
-  SGF.B.createCondBranch(loc, testBool, trueBB, falseBB);
+  // Extract the i1 from the Bool struct.
+  auto i1Value = SGF.emitUnwrapIntegerResult(loc, testBool);
+  SGF.B.createCondBranch(loc, i1Value, trueBB, falseBB);
 
   SGF.B.setInsertionPoint(falseBB);
   failure(loc);
@@ -2250,15 +2252,8 @@
   SILValue srcValue = src.getFinalManagedValue().forward(SGF);
 
   // Extract the i1 from the Bool struct.
-  StructDecl *BoolStruct = cast<StructDecl>(Context.getBoolDecl());
-  auto Members = BoolStruct->lookupDirect(Context.Id_value_);
-  assert(Members.size() == 1 &&
-         "Bool should have only one property with name '_value'");
-  auto Member = dyn_cast<VarDecl>(Members[0]);
-  assert(Member &&"Bool should have a property with name '_value' of type Int1");
-  auto *ETI = SGF.B.createStructExtract(loc, srcValue, Member);
-
-  SGF.B.createSwitchValue(loc, SILValue(ETI), defaultBB, caseBBs);
+  auto i1Value = SGF.emitUnwrapIntegerResult(loc, srcValue);
+  SGF.B.createSwitchValue(loc, i1Value, defaultBB, caseBBs);
 
   // Okay, now emit all the cases.
   for (unsigned i = 0, e = caseInfos.size(); i != e; ++i) {
diff --git a/lib/SILGen/SILGenStmt.cpp b/lib/SILGen/SILGenStmt.cpp
index 1ff751e..b38fb2d 100644
--- a/lib/SILGen/SILGenStmt.cpp
+++ b/lib/SILGen/SILGenStmt.cpp
@@ -232,15 +232,14 @@
   assert(B.hasValidInsertionPoint() &&
          "emitting condition at unreachable point");
 
-  // Sema forces conditions to have Builtin.i1 type, which guarantees this.
+  // Sema forces conditions to have Bool type, which guarantees this.
   SILValue V;
   {
     FullExpr Scope(Cleanups, CleanupLocation(E));
     V = emitRValue(E).forwardAsSingleValue(*this, E);
   }
-  assert(V->getType().castTo<BuiltinIntegerType>()->isFixedWidth(1));
-
-  return emitCondition(V, E, invertValue, contArgs, NumTrueTaken,
+  auto i1Value = emitUnwrapIntegerResult(E, V);
+  return emitCondition(i1Value, E, invertValue, contArgs, NumTrueTaken,
                        NumFalseTaken);
 }
 
@@ -525,8 +524,8 @@
         SGF.emitRValueAsSingleValue(stmt->getCondition()).getUnmanagedValue();
   }
 
-  // Sema forces conditions to have Builtin.i1 type.
-  assert(condition->getType().castTo<BuiltinIntegerType>()->isFixedWidth(1));
+  // Extract the i1 from the Bool struct.
+  auto i1Value = SGF.emitUnwrapIntegerResult(stmt, condition);
 
   SILValue message = SGF.B.createStringLiteral(
       stmt, stmt->getMessage(), StringLiteralInst::Encoding::UTF8);
@@ -534,7 +533,7 @@
   auto resultType = SGF.getASTContext().TheEmptyTupleType;
   SGF.B.createBuiltin(
       stmt, SGF.getASTContext().getIdentifier("poundAssert"),
-      SGF.getLoweredType(resultType), {}, {condition, message});
+      SGF.getLoweredType(resultType), {}, {i1Value, message});
 }
 
 namespace {
diff --git a/lib/SILOptimizer/Utils/Devirtualize.cpp b/lib/SILOptimizer/Utils/Devirtualize.cpp
index 728ada3..f026857 100644
--- a/lib/SILOptimizer/Utils/Devirtualize.cpp
+++ b/lib/SILOptimizer/Utils/Devirtualize.cpp
@@ -883,9 +883,10 @@
       witnessThunkSig);
 }
 
-static SubstitutionMap
-getWitnessMethodSubstitutions(SILModule &Module, ApplySite AI, SILFunction *F,
-                              ProtocolConformanceRef CRef) {
+SubstitutionMap
+swift::getWitnessMethodSubstitutions(SILModule &Module, ApplySite AI,
+                                     SILFunction *F,
+                                     ProtocolConformanceRef CRef) {
   auto witnessFnTy = F->getLoweredFunctionType();
   assert(witnessFnTy->getRepresentation() ==
          SILFunctionTypeRepresentation::WitnessMethod);
@@ -901,9 +902,9 @@
       == CRef.getRequirement());
   auto *classWitness = witnessFnTy->getWitnessMethodClass(*mod);
 
-  return getWitnessMethodSubstitutions(
-      mod, CRef, requirementSig, witnessThunkSig,
-      origSubs, isDefaultWitness, classWitness);
+  return ::getWitnessMethodSubstitutions(mod, CRef, requirementSig,
+                                         witnessThunkSig, origSubs,
+                                         isDefaultWitness, classWitness);
 }
 
 /// Generate a new apply of a function_ref to replace an apply of a
diff --git a/lib/Sema/CSApply.cpp b/lib/Sema/CSApply.cpp
index 850d0f0..e0a8311 100644
--- a/lib/Sema/CSApply.cpp
+++ b/lib/Sema/CSApply.cpp
@@ -3143,10 +3143,7 @@
       auto resultTy = simplifyType(cs.getType(expr));
       cs.setType(expr, resultTy);
 
-      // Convert the condition to a logic value.
-      auto cond
-        = solution.convertBooleanTypeToBuiltinI1(expr->getCondExpr(),
-                                                 cs.getConstraintLocator(expr));
+      auto cond = cs.coerceToRValue(expr->getCondExpr());
       expr->setCondExpr(cond);
 
       // Coerce the then/else branches to the common type.
@@ -8011,81 +8008,6 @@
   return result;
 }
 
-Expr *
-Solution::convertBooleanTypeToBuiltinI1(Expr *expr,
-                                        ConstraintLocator *locator) const {
-  auto &cs = getConstraintSystem();
-
-  // Load lvalues here.
-  expr = cs.coerceToRValue(expr);
-
-  auto &tc = cs.getTypeChecker();
-  auto &ctx = tc.Context;
-
-  auto type = cs.getType(expr);
-
-  // We allow UnresolvedType <c $T for all $T, so we might end up here
-  // in diagnostics. Just bail out.
-  if (type->is<UnresolvedType>())
-    return expr;
-
-  // Look for the builtin name. If we don't have it, we need to call the
-  // general name via the witness table.
-  NameLookupOptions lookupOptions = defaultMemberLookupOptions;
-  if (isa<AbstractFunctionDecl>(cs.DC))
-    lookupOptions |= NameLookupFlags::KnownPrivate;
-  auto members = tc.lookupMember(cs.DC, type,
-                                 tc.Context.Id_getBuiltinLogicValue,
-                                 lookupOptions);
-
-  // Find the builtin method.
-  if (members.size() != 1) {
-    tc.diagnose(expr->getLoc(), diag::broken_bool);
-    return expr;
-  }
-  auto *builtinMethod = dyn_cast<FuncDecl>(members[0].getValueDecl());
-  if (!builtinMethod) {
-    tc.diagnose(expr->getLoc(), diag::broken_bool);
-    return expr;
-  }
-
-  // The method is not generic, so there are no substitutions.
-  tc.validateDeclForNameLookup(builtinMethod);
-  auto builtinMethodType = builtinMethod->getInterfaceType()
-    ->castTo<FunctionType>();
-
-  // Form an unbound reference to the builtin method.
-  auto *declRef = new (ctx) DeclRefExpr(builtinMethod,
-                                        DeclNameLoc(expr->getLoc()),
-                                        /*Implicit=*/true);
-  declRef->setFunctionRefKind(FunctionRefKind::DoubleApply);
-  cs.setType(declRef, builtinMethodType);
-
-  auto getType = [&](const Expr *E) -> Type {
-    return cs.getType(E);
-  };
-
-  // Apply 'self' to get the method value.
-  auto *methodRef = new (ctx) DotSyntaxCallExpr(declRef,
-                                                SourceLoc(),
-                                                expr);
-  cs.setType(methodRef, builtinMethodType->getResult());
-
-  // Apply the empty argument list to get the final result.
-  auto *result = CallExpr::createImplicit(ctx, methodRef,
-                                          { }, { }, getType);
-  cs.setType(result, builtinMethodType->getResult()
-                  ->castTo<FunctionType>()->getResult());
-  cs.setType(result->getArg(), ctx.TheEmptyTupleType);
-
-  if (!cs.getType(result)->isBuiltinIntegerType(1)) {
-    tc.diagnose(expr->getLoc(), diag::broken_bool);
-    return result;
-  }
-
-  return result;
-}
-
 Expr *Solution::convertOptionalToBool(Expr *expr,
                                       ConstraintLocator *locator) const {
   auto &cs = getConstraintSystem();
diff --git a/lib/Sema/CSGen.cpp b/lib/Sema/CSGen.cpp
index e901099..0afe8c0 100644
--- a/lib/Sema/CSGen.cpp
+++ b/lib/Sema/CSGen.cpp
@@ -3315,22 +3315,6 @@
           continue;
         }
 
-        // Strip off 'Bool' to 'Builtin.Int1' conversion. Otherwise, we'll have
-        // to handle multiple ways of type-checking.
-        if (expr->isImplicit()) {
-          if (auto call = dyn_cast<CallExpr>(expr)) {
-            if (auto DSCE = dyn_cast<DotSyntaxCallExpr>(call->getFn())) {
-              auto RefD = DSCE->getFn()->getReferencedDecl().getDecl();
-              if (RefD->getBaseName() == TC.Context.Id_getBuiltinLogicValue &&
-                  RefD->getDeclContext()->getSelfNominalTypeDecl() ==
-                      TC.Context.getBoolDecl()) {
-                expr = DSCE->getBase();
-                continue;
-              }
-            }
-          }
-        }
-
         // Remove any semantic expression injected by typechecking.
         if (auto CE = dyn_cast<CollectionExpr>(expr)) {
           CE->setSemanticExpr(nullptr);
diff --git a/lib/Sema/ConstraintSystem.h b/lib/Sema/ConstraintSystem.h
index 8a1ccea..96b7c12 100644
--- a/lib/Sema/ConstraintSystem.h
+++ b/lib/Sema/ConstraintSystem.h
@@ -636,19 +636,6 @@
                      bool ignoreTopLevelInjection = false,
                      Optional<Pattern*> typeFromPattern = None) const;
 
-  /// Convert the given expression to a logic value.
-  ///
-  /// This operation cannot fail.
-  ///
-  /// \param expr The expression to coerce. The type of this expression
-  /// must conform to the LogicValue protocol.
-  ///
-  /// \param locator Locator used to describe the location of this expression.
-  ///
-  /// \returns the expression converted to a logic value (Builtin i1).
-  Expr *convertBooleanTypeToBuiltinI1(Expr *expr,
-                                      ConstraintLocator *locator) const;
-
   /// Convert the given optional-producing expression to a Bool
   /// indicating whether the optional has a value.
   ///
diff --git a/lib/Sema/TypeCheckConstraints.cpp b/lib/Sema/TypeCheckConstraints.cpp
index 5d6f174..7c9a114 100644
--- a/lib/Sema/TypeCheckConstraints.cpp
+++ b/lib/Sema/TypeCheckConstraints.cpp
@@ -2699,10 +2699,9 @@
 }
 
 bool TypeChecker::typeCheckCondition(Expr *&expr, DeclContext *dc) {
-  // If this expression is already typechecked and has an i1 type, then it has
-  // already got its conversion from Boolean back to i1.  Just re-typecheck
-  // it.
-  if (expr->getType() && expr->getType()->isBuiltinIntegerType(1)) {
+  // If this expression is already typechecked and has type Bool, then just
+  // re-typecheck it.
+  if (expr->getType() && expr->getType()->isBool()) {
     auto resultTy = typeCheckExpression(expr, dc);
     return !resultTy;
   }
@@ -2728,19 +2727,6 @@
                        cs.getConstraintLocator(expr));
       return false;
     }
-
-    // Convert the result to a Builtin.i1.
-    Expr *appliedSolution(constraints::Solution &solution,
-                          Expr *expr) override {
-      auto &cs = solution.getConstraintSystem();
-
-      auto converted =
-        solution.convertBooleanTypeToBuiltinI1(expr,
-                                             cs.getConstraintLocator(OrigExpr));
-      cs.setExprTypes(converted);
-      return converted;
-    }
-    
   };
 
   ConditionListener listener;
diff --git a/stdlib/public/SwiftShims/System.h b/stdlib/public/SwiftShims/System.h
index 5a21f79..7571e91 100644
--- a/stdlib/public/SwiftShims/System.h
+++ b/stdlib/public/SwiftShims/System.h
@@ -142,10 +142,10 @@
 /// Darwin reserves the low 4GB of address space.
 #define SWIFT_ABI_DARWIN_ARM64_LEAST_VALID_POINTER 0x100000000ULL
 
-// TBI guarantees the top byte of pointers is unused.
+// TBI guarantees the top byte of pointers is unused, but ARMv8.5-A
+// claims the bottom four bits of that for memory tagging.
 // Heap objects are eight-byte aligned.
-#define SWIFT_ABI_ARM64_SWIFT_SPARE_BITS_MASK                                  \
-  SWIFT_ABI_DEFAULT_64BIT_SPARE_BITS_MASK
+#define SWIFT_ABI_ARM64_SWIFT_SPARE_BITS_MASK 0xF000000000000007ULL
 
 // Objective-C reserves just the high bit for tagged pointers.
 #define SWIFT_ABI_ARM64_OBJC_RESERVED_BITS_MASK 0x8000000000000000ULL
diff --git a/stdlib/public/core/AtomicInt.swift.gyb b/stdlib/public/core/AtomicInt.swift.gyb
index 9ba447b..6a20166 100644
--- a/stdlib/public/core/AtomicInt.swift.gyb
+++ b/stdlib/public/core/AtomicInt.swift.gyb
@@ -60,7 +60,7 @@
   object target: UnsafeMutablePointer<Int>,
   expected: UnsafeMutablePointer<Int>,
   desired: Int) -> Bool {
-#if arch(i386) || arch(arm) || arch(arm64_32)
+#if arch(i386) || arch(arm)
   let (oldValue, won) = Builtin.cmpxchg_seqcst_seqcst_Int32(
     target._rawValue, expected.pointee._value, desired._value)
 #elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x)
@@ -75,7 +75,7 @@
 @usableFromInline // used by SwiftPrivate._stdlib_AtomicInt
 internal func _swift_stdlib_atomicLoadInt(
   object target: UnsafeMutablePointer<Int>) -> Int {
-#if arch(i386) || arch(arm) || arch(arm64_32)
+#if arch(i386) || arch(arm)
   let value = Builtin.atomicload_seqcst_Int32(target._rawValue)
   return Int(value)
 #elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x)
@@ -88,7 +88,7 @@
 internal func _swift_stdlib_atomicStoreInt(
   object target: UnsafeMutablePointer<Int>,
   desired: Int) {
-#if arch(i386) || arch(arm) || arch(arm64_32)
+#if arch(i386) || arch(arm)
   Builtin.atomicstore_seqcst_Int32(target._rawValue, desired._value)
 #elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x)
   Builtin.atomicstore_seqcst_Int64(target._rawValue, desired._value)
diff --git a/stdlib/public/core/Bool.swift b/stdlib/public/core/Bool.swift
index 33b2e49..3754165 100644
--- a/stdlib/public/core/Bool.swift
+++ b/stdlib/public/core/Bool.swift
@@ -170,15 +170,6 @@
   }
 }
 
-extension Bool {
-  // This is a magic entry point known to the compiler.
-  @_transparent
-  public // COMPILER_INTRINSIC
-  func _getBuiltinLogicValue() -> Builtin.Int1 {
-    return _value
-  }
-}
-
 extension Bool : CustomStringConvertible {
   /// A textual representation of the Boolean value.
   @inlinable
diff --git a/stdlib/public/core/CMakeLists.txt b/stdlib/public/core/CMakeLists.txt
index 7323a89..e0cc9f2 100644
--- a/stdlib/public/core/CMakeLists.txt
+++ b/stdlib/public/core/CMakeLists.txt
@@ -284,6 +284,10 @@
    list(APPEND swift_core_private_link_libraries swiftImageInspectionShared)
 endif()
 
+if(SWIFT_PRIMARY_VARIANT_SDK STREQUAL Windows)
+  list(APPEND swift_core_private_link_libraries shell32)
+endif()
+
 add_swift_target_library(swiftCore
                   ${SWIFT_STDLIB_LIBRARY_BUILD_TYPES} IS_STDLIB IS_STDLIB_CORE
                     ${SWIFTLIB_SOURCES}
diff --git a/stdlib/public/runtime/MetadataLookup.cpp b/stdlib/public/runtime/MetadataLookup.cpp
index c677617..6f511cc 100644
--- a/stdlib/public/runtime/MetadataLookup.cpp
+++ b/stdlib/public/runtime/MetadataLookup.cpp
@@ -231,13 +231,13 @@
 /// Find the context descriptor for the type extended by the given extension.
 static const ContextDescriptor *
 _findExtendedTypeContextDescriptor(const ExtensionContextDescriptor *extension,
+                                   Demangler &demangler,
                                    Demangle::NodePointer *demangledNode
                                      = nullptr) {
   Demangle::NodePointer localNode;
   Demangle::NodePointer &node = demangledNode ? *demangledNode : localNode;
 
   auto mangledName = extension->getMangledExtendedContext();
-  auto demangler = getDemanglerForRuntimeTypeResolution();
   node = demangler.demangleType(mangledName);
   if (!node)
     return nullptr;
@@ -423,7 +423,7 @@
 
       Demangle::NodePointer extendedContextDemangled;
       auto extendedDescriptorFromDemangled =
-        _findExtendedTypeContextDescriptor(extension,
+        _findExtendedTypeContextDescriptor(extension, demangler,
                                            &extendedContextDemangled);
 
       // Determine whether the contexts match.
@@ -822,8 +822,10 @@
                                  std::vector<unsigned> &genericParamCounts) {
   // If we have an extension descriptor, extract the extended type and use
   // that.
+  auto demangler = getDemanglerForRuntimeTypeResolution();
   if (auto extension = dyn_cast<ExtensionContextDescriptor>(descriptor)) {
-    if (auto extendedType = _findExtendedTypeContextDescriptor(extension))
+    if (auto extendedType =
+            _findExtendedTypeContextDescriptor(extension, demangler))
       descriptor = extendedType;
   }
 
diff --git a/test/Compatibility/attr_usableFromInline_protocol.swift b/test/Compatibility/attr_usableFromInline_protocol.swift
index 1b01305..4941d69 100644
--- a/test/Compatibility/attr_usableFromInline_protocol.swift
+++ b/test/Compatibility/attr_usableFromInline_protocol.swift
@@ -7,8 +7,8 @@
 }
 
 @usableFromInline struct UFIAdopter<T> : PublicProtoWithReqs {}
-// expected-warning@-1 {{type alias 'Assoc' should be declared '@usableFromInline' because because it matches a requirement in protocol 'PublicProtoWithReqs'}} {{none}}
-// expected-warning@-2 {{instance method 'foo()' should be declared '@usableFromInline' because because it matches a requirement in protocol 'PublicProtoWithReqs'}} {{none}}
+// expected-warning@-1 {{type alias 'Assoc' should be declared '@usableFromInline' because it matches a requirement in protocol 'PublicProtoWithReqs'}} {{none}}
+// expected-warning@-2 {{instance method 'foo()' should be declared '@usableFromInline' because it matches a requirement in protocol 'PublicProtoWithReqs'}} {{none}}
 extension UFIAdopter {
   typealias Assoc = Int
   // expected-note@-1 {{'Assoc' declared here}}
@@ -18,9 +18,9 @@
 
 @usableFromInline struct UFIAdopterAllInOne<T> : PublicProtoWithReqs {
   typealias Assoc = Int
-  // expected-warning@-1 {{type alias 'Assoc' should be declared '@usableFromInline' because because it matches a requirement in protocol 'PublicProtoWithReqs'}} {{none}}
+  // expected-warning@-1 {{type alias 'Assoc' should be declared '@usableFromInline' because it matches a requirement in protocol 'PublicProtoWithReqs'}} {{none}}
   func foo() {}
-  // expected-warning@-1 {{instance method 'foo()' should be declared '@usableFromInline' because because it matches a requirement in protocol 'PublicProtoWithReqs'}} {{none}}
+  // expected-warning@-1 {{instance method 'foo()' should be declared '@usableFromInline' because it matches a requirement in protocol 'PublicProtoWithReqs'}} {{none}}
 }
 
 internal struct InternalAdopter<T> : PublicProtoWithReqs {}
@@ -36,8 +36,8 @@
 }
 
 public struct PublicAdopter<T> : UFIProtoWithReqs {}
-// expected-warning@-1 {{type alias 'Assoc' should be declared '@usableFromInline' because because it matches a requirement in protocol 'UFIProtoWithReqs'}} {{none}}
-// expected-warning@-2 {{instance method 'foo()' should be declared '@usableFromInline' because because it matches a requirement in protocol 'UFIProtoWithReqs'}} {{none}}
+// expected-warning@-1 {{type alias 'Assoc' should be declared '@usableFromInline' because it matches a requirement in protocol 'UFIProtoWithReqs'}} {{none}}
+// expected-warning@-2 {{instance method 'foo()' should be declared '@usableFromInline' because it matches a requirement in protocol 'UFIProtoWithReqs'}} {{none}}
 extension PublicAdopter {
   typealias Assoc = Int
   // expected-note@-1 {{'Assoc' declared here}}
diff --git a/test/DebugInfo/DumpDeclFromMangledName.swift b/test/DebugInfo/DumpDeclFromMangledName.swift
index 4ca202f..2a9bb70 100644
--- a/test/DebugInfo/DumpDeclFromMangledName.swift
+++ b/test/DebugInfo/DumpDeclFromMangledName.swift
@@ -16,12 +16,12 @@
 // RUN: not %lldb-moduleimport-test %t/DeclReconstr \
 // RUN:   --decl-from-mangled=patatino 2>&1 | \
 // RUN:   %FileCheck %s --check-prefix=INVALID-DECL
-// INVALID-DECL: patatino does not exists, exiting.
+// INVALID-DECL: patatino does not exist, exiting.
 
 // RUN: not %lldb-moduleimport-test %t/DeclReconstr \
 // RUN:   --type-from-mangled=patatino 2>&1 | \
 // RUN:   %FileCheck %s --check-prefix=INVALID-TYPE
-// INVALID-TYPE: patatino does not exists, exiting.
+// INVALID-TYPE: patatino does not exist, exiting.
 
 // RUN: %lldb-moduleimport-test %t/DeclReconstr \
 // RUN:   -decl-from-mangled=%t.input > %t.output 2>&1
diff --git a/test/DebugInfo/patternmatching.swift b/test/DebugInfo/patternmatching.swift
index dc6668b..be7c23b 100644
--- a/test/DebugInfo/patternmatching.swift
+++ b/test/DebugInfo/patternmatching.swift
@@ -15,9 +15,10 @@
 switch p {
     case (let x, let y) where
       // CHECK:   call {{.*}}double {{.*}}return_same{{.*}}, !dbg ![[LOC1:.*]]
-      // CHECK: br {{.*}}, label {{.*}}, label {{.*}}, !dbg ![[LOC1]]
+      // CHECK: br {{.*}}, label {{.*}}, label {{.*}}, !dbg ![[LOC2:.*]]
       // CHECK: call{{.*}}markUsed{{.*}}, !dbg ![[LOC3:.*]]
-      // CHECK: ![[LOC1]] = !DILocation(line: [[@LINE+1]],
+      // CHECK: ![[LOC1]] = !DILocation(line: [[@LINE+2]],
+      // CHECK: ![[LOC2]] = !DILocation(line: [[@LINE+1]],
                         return_same(x) == return_same(y):
       // CHECK: ![[LOC3]] = !DILocation(line: [[@LINE+1]],
       markUsed(x)
diff --git a/test/Demangle/Inputs/manglings.txt b/test/Demangle/Inputs/manglings.txt
index d3f3d11..0f77ba8 100644
--- a/test/Demangle/Inputs/manglings.txt
+++ b/test/Demangle/Inputs/manglings.txt
@@ -301,7 +301,9 @@
 _T0So11CrappyColorVs16RawRepresentableSCMA ---> reflection metadata associated type descriptor __C.CrappyColor : Swift.RawRepresentable in __C_Synthesized
 $S28protocol_conformance_records15NativeValueTypeVAA8RuncibleAAMc ---> protocol conformance descriptor for protocol_conformance_records.NativeValueType : protocol_conformance_records.Runcible in protocol_conformance_records
 $SSC9SomeErrorLeVD ---> __C_Synthesized.related decl 'e' for SomeError
-$s20mangling_retroactive5test0yyAA1ZVy12RetroactiveB1XVSiAE1YVAG0D1A1PAAHPyHCg_AiJ1QAAHPyHCg1_GF ---> mangling_retroactive.test0(mangling_retroactive.Z<RetroactiveB.X, Swift.Int, RetroactiveB.Y>) -> ()
+$s20mangling_retroactive5test0yyAA1ZVy12RetroactiveB1XVSiAE1YVAG0D1A1PAAyHCg_AiJ1QAAyHCg1_GF ---> mangling_retroactive.test0(mangling_retroactive.Z<RetroactiveB.X, Swift.Int, RetroactiveB.Y>) -> ()
+$s20mangling_retroactive5test0yyAA1ZVy12RetroactiveB1XVSiAE1YVAG0D1A1PHPyHCg_AiJ1QHPyHCg1_GF ---> mangling_retroactive.test0(mangling_retroactive.Z<RetroactiveB.X, Swift.Int, RetroactiveB.Y>) -> ()
+$s20mangling_retroactive5test0yyAA1ZVy12RetroactiveB1XVSiAE1YVAG0D1A1PHpyHCg_AiJ1QHpyHCg1_GF ---> mangling_retroactive.test0(mangling_retroactive.Z<RetroactiveB.X, Swift.Int, RetroactiveB.Y>) -> ()
 _T0LiteralAByxGxd_tcfC ---> _T0LiteralAByxGxd_tcfC
 _T0XZ ---> _T0XZ
 _TTSf0os___TFVs17_LegacyStringCore15_invariantCheckfT_T_ ---> function signature specialization <Arg[0] = Guaranteed To Owned and Exploded> of Swift._LegacyStringCore._invariantCheck() -> ()
diff --git a/test/IRGen/bridge_object_arm64.sil b/test/IRGen/bridge_object_arm64.sil
index 181b4ec..689cbbc 100644
--- a/test/IRGen/bridge_object_arm64.sil
+++ b/test/IRGen/bridge_object_arm64.sil
@@ -35,8 +35,8 @@
 // CHECK:         [[TAGGED_RESULT:%.*]] = bitcast [[BRIDGE]] %0 to [[C:%objc_object\*]]
 // CHECK:         br label %tagged-cont
 // CHECK:       not-tagged-pointer:
-// --                                                     0x00ff_ffff_ffff_fff8
-// CHECK:         [[MASKED_BITS:%.*]] = and i64 [[BOBITS]], 72057594037927928
+// --                                                     0x0fff_ffff_ffff_fff8
+// CHECK:         [[MASKED_BITS:%.*]] = and i64 [[BOBITS]], 1152921504606846968
 // CHECK:         [[MASKED_RESULT:%.*]] = inttoptr i64 [[MASKED_BITS]] to [[C]]
 // CHECK:         br label %tagged-cont
 // CHECK:      tagged-cont:
diff --git a/test/IRGen/enum_top_bits_reserved.sil b/test/IRGen/enum_top_bits_reserved.sil
new file mode 100644
index 0000000..d654702
--- /dev/null
+++ b/test/IRGen/enum_top_bits_reserved.sil
@@ -0,0 +1,58 @@
+// RUN: %swift -module-name test -emit-ir -target arm64-apple-ios10.0 %s | %FileCheck %s -check-prefix=CHECK -check-prefix=CHECK-arm64
+// RUN: %swift -module-name test -emit-ir -target x86_64-apple-macosx10.12 %s | %FileCheck %s -check-prefix=CHECK -check-prefix=CHECK-x86_64
+
+class NativeClass {}
+sil_vtable NativeClass {}
+
+// On 64-bit targets, there are 3 spare bits in the alignment bits and
+// either 4 (arm64) or 8 (everywhere else) spare bits in the high byte.
+// Consume those bits one by one.
+
+enum A {
+  case either(NativeClass)
+  case or(NativeClass)
+}
+
+enum B {
+  case either(A)
+  case or(A)
+}
+
+enum C {
+  case either(B)
+  case or(B)
+}
+
+enum D {
+  case either(C)
+  case or(C)
+}
+
+enum E {
+  case either(D)
+  case or(D)
+}
+
+enum F {
+  case either(E)
+  case or(E)
+}
+
+enum G {
+  case either(F)
+  case or(F)
+}
+
+// Okay, we've claimed 7 spare bits.  On ARM64, the eighth spare bit will
+// require an extra discriminator.
+
+// CHECK-LABEL: @"$s4test1HOWV" = internal constant %swift.enum_vwtable
+// CHECK-x86_64-SAME:     i64 8,
+// CHECK-x86_64-SAME:     i64 8,
+// CHECK-arm64-SAME:      i64 9,
+// CHECK-arm64-SAME:      i64 16,
+
+enum H {
+  case either(G)
+  case or(G)
+}
diff --git a/test/IRGen/errors.sil b/test/IRGen/errors.sil
index 4635061..a2b21c6 100644
--- a/test/IRGen/errors.sil
+++ b/test/IRGen/errors.sil
@@ -1,5 +1,4 @@
 // RUN: %target-swift-frontend -primary-file %s -emit-ir | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-runtime --check-prefix=CHECK-%target-cpu
-// REQUIRES: executable_test
 
 sil_stage canonical
 
diff --git a/test/IRGen/existential_metatypes.sil b/test/IRGen/existential_metatypes.sil
index 461ad85..d2801da 100644
--- a/test/IRGen/existential_metatypes.sil
+++ b/test/IRGen/existential_metatypes.sil
@@ -109,10 +109,10 @@
   return %9 : $()
 }
 
-sil_witness_table Int: Kindable module existential_metatypes {
+sil_witness_table public_external Int: Kindable module existential_metatypes {
   method #Kindable.kind!getter.1: @int_kind_getter_witness
 }
 
-sil_witness_table Float: Kindable module existential_metatypes {
+sil_witness_table public_external Float: Kindable module existential_metatypes {
   method #Kindable.kind!getter.1: @float_kind_getter_witness
 }
diff --git a/test/IRGen/objc_properties.swift b/test/IRGen/objc_properties.swift
index 8e87328..45d3737 100644
--- a/test/IRGen/objc_properties.swift
+++ b/test/IRGen/objc_properties.swift
@@ -47,6 +47,8 @@
   @objc class var extensionClassProp : SomeObject.Type {
     return self
   }
+
+  @objc static var extensionStoredStaticProp: Int64 = 0
 }
 
 // <rdar://problem/16952186> Crash with @lazy in @objc class
@@ -77,14 +79,14 @@
 }
 
 // CHECK-NEW: [[SHARED_NAME:@.*]] = private unnamed_addr constant [11 x i8] c"sharedProp\00"
-// CHECK-NEW: [[SHARED_ATTRS:@.*]] = private unnamed_addr constant [17 x i8] c"Tq,N,VsharedProp\00"
+// CHECK-NEW: [[SHARED_ATTRS:@.*]] = private unnamed_addr constant [5 x i8] c"Tq,N\00"
 
 // CHECK-NEW: @_CLASS_PROPERTIES__TtC15objc_properties10SomeObject = private constant { {{.*}}] } {
 // CHECK-NEW:   i32 16,
 // CHECK-NEW:   i32 1,
 // CHECK-NEW:   [1 x { i8*, i8* }] [{
 // CHECK-NEW:     i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SHARED_NAME]], i64 0, i64 0),
-// CHECK-NEW:     i8* getelementptr inbounds ([17 x i8], [17 x i8]* [[SHARED_ATTRS]], i64 0, i64 0)
+// CHECK-NEW:     i8* getelementptr inbounds ([5 x i8], [5 x i8]* [[SHARED_ATTRS]], i64 0, i64 0)
 // CHECK-NEW:   }]
 // CHECK-NEW: }, section "__DATA, __objc_const", align 8
 
@@ -209,14 +211,17 @@
 
 // CHECK-NEW: [[EXTENSIONCLASSPROPERTY_NAME:@.*]] = private unnamed_addr constant [19 x i8] c"extensionClassProp\00"
 // CHECK-NEW: [[EXTENSIONCLASSPROPERTY_ATTRS:@.*]] = private unnamed_addr constant [7 x i8] c"T#,N,R\00"
+// CHECK-NEW: [[EXTENSIONSTATICPROPERTY_NAME:@.*]] = private unnamed_addr constant [26 x i8] c"extensionStoredStaticProp\00"
 
 // CHECK-NEW: @"_CATEGORY_CLASS_PROPERTIES__TtC15objc_properties10SomeObject_$_objc_properties" = private constant { {{.*}}] } {
 // CHECK-NEW:   i32 16,
-// CHECK-NEW:   i32 1,
-// CHECK-NEW:   [1 x { i8*, i8* }] [{
+// CHECK-NEW:   i32 2,
+// CHECK-NEW:   [2 x { i8*, i8* }] [{
 // CHECK-NEW:     i8* getelementptr inbounds ([19 x i8], [19 x i8]* [[EXTENSIONCLASSPROPERTY_NAME]], i64 0, i64 0),
 // CHECK-NEW:     i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[EXTENSIONCLASSPROPERTY_ATTRS]], i64 0, i64 0)
-// CHECK-NEW:   }]
+// CHECK-NEW:   }, {
+// CHECK-NEW:	  i8* getelementptr inbounds ([26 x i8], [26 x i8]* [[EXTENSIONSTATICPROPERTY_NAME]], i64 0, i64 0),
+// CHECK-NEW:	  i8* getelementptr inbounds ([5 x i8], [5 x i8]* [[SHARED_ATTRS]], i64 0, i64 0) }]
 // CHECK-NEW: }, section "__DATA, __objc_const", align 8
 
 // CHECK: @"_CATEGORY__TtC15objc_properties10SomeObject_$_objc_properties" = private constant { {{.+}} } {
diff --git a/test/Interpreter/SDK/Inputs/OldABI/OldABI.h b/test/Interpreter/SDK/Inputs/OldABI/OldABI.h
new file mode 100644
index 0000000..cce9ddb
--- /dev/null
+++ b/test/Interpreter/SDK/Inputs/OldABI/OldABI.h
@@ -0,0 +1,3 @@
+#include <objc/objc.h>
+OBJC_EXTERN bool CanTestOldABI();
+OBJC_EXTERN id _Nonnull AllocOldABIObject();
diff --git a/test/Interpreter/SDK/Inputs/OldABI/OldABI.mm b/test/Interpreter/SDK/Inputs/OldABI/OldABI.mm
new file mode 100644
index 0000000..81f235b
--- /dev/null
+++ b/test/Interpreter/SDK/Inputs/OldABI/OldABI.mm
@@ -0,0 +1,172 @@
+#include "OldABI.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+#include <unistd.h>
+#include <sys/mman.h>
+#include <malloc/malloc.h>
+#include <objc/runtime.h>
+#include <Foundation/Foundation.h>
+
+// Implementation of ObjC classes
+// with bits set to mimic the pre-stable Swift ABI
+// and additional memory protection to detect mis-use
+
+#if __has_include(<objc/objc-internal.h>)
+#include <objc/objc-internal.h>
+#else
+extern "C" Class objc_initializeClassPair(Class superclass, const char *name, Class cls, Class metacls);
+extern "C" id _objc_rootRetain(id);
+extern "C" void _objc_rootRelease(id);
+extern "C" id _objc_rootAutorelease(id);
+extern "C" uintptr_t _objc_rootRetainCount(id);
+extern "C" bool _objc_rootTryRetain(id);
+extern "C" bool _objc_rootIsDeallocating(id);
+#endif
+
+// This class stands in for the pre-stable ABI's SwiftObject.
+// Stable Swift's class is named Swift._SwiftObject (but mangled).
+
+__attribute__((objc_root_class))
+@interface SwiftObject { id isa; } @end
+
+@implementation SwiftObject
++(void)initialize { }
++(id)allocWithZone:(struct _malloc_zone_t *)zone {
+  return class_createInstance(self, 0);
+}
++(id)alloc { return [self allocWithZone:nil]; }
++(id)class { return self; }
+-(id)class { return object_getClass(self); }
++(id)superclass { return class_getSuperclass(self); }
+-(id)superclass { return class_getSuperclass([self class]); }
++(BOOL)isMemberOfClass:(Class)cls { return object_getClass(self) == cls; }
+-(BOOL)isMemberOfClass:(Class)cls { return [self class] == cls; }
+-(id)self { return self; }
+-(BOOL)isProxy { return NO; }
+-(struct _malloc_zone_t *)zone { return malloc_default_zone(); }
+-(void)doesNotRecognizeSelector:(SEL)sel {
+  Class cls = [self class];
+  fprintf(stderr, "unrecognized selector %c[%s %s]\n",
+          class_isMetaClass(cls) ? '+' : '-',
+          class_getName(cls), sel_getName(sel));
+  abort();
+}
+
++(id)retain { return self; }
++(void)release { }
++(id)autorelease { return self; }
++(uintptr_t)retainCount { return ~(uintptr_t)0; }
++(BOOL)_tryRetain { return YES; }
++(BOOL)_isDeallocating { return NO; }
+
+-(id)retain { return _objc_rootRetain(self); }
+-(void)release { _objc_rootRelease(self); }
+-(id)autorelease { return _objc_rootAutorelease(self); }
+-(uintptr_t)retainCount { return _objc_rootRetainCount(self); }
+-(BOOL)_tryRetain { return _objc_rootTryRetain(self); }
+-(BOOL)_isDeallocating { return _objc_rootIsDeallocating(self); }
+-(void)dealloc { object_dispose(self); }
+
+-(BOOL)isKindOfClass:(Class)other {
+  for (Class cls = object_getClass(self); cls; cls = class_getSuperclass(cls))
+    if (cls == other) return YES;
+  return NO;
+}
++(BOOL)isSubclassOfClass:(Class)other {
+  for (Class cls = self; cls; cls = class_getSuperclass(cls))
+    if (cls == other) return YES;
+  return NO;
+}
+-(BOOL)respondsToSelector:(SEL)sel {
+  if (!sel) return NO;
+  return class_respondsToSelector(object_getClass(self), sel);
+}
++(BOOL)instancesRespondToSelector:(SEL)sel {
+  if (!sel) return NO;
+  return class_respondsToSelector(self, sel);
+}
+
+-(uintptr_t)hash { return (uintptr_t)self; }
+-(BOOL)isEqual:(id)other { return self == other; }
++(NSString *)description { return @"FakeSwiftObject class"; }
+-(NSString *)description { return @"FakeSwiftObject instance"; }
+-(NSString *)debugDescription { return [self description]; }
+
+- (BOOL)isNSArray__      { return NO; }
+- (BOOL)isNSCFConstantString__  { return NO; }
+- (BOOL)isNSData__       { return NO; }
+- (BOOL)isNSDate__       { return NO; }
+- (BOOL)isNSDictionary__ { return NO; }
+- (BOOL)isNSObject__     { return NO; }
+- (BOOL)isNSOrderedSet__ { return NO; }
+- (BOOL)isNSNumber__     { return NO; }
+- (BOOL)isNSSet__        { return NO; }
+- (BOOL)isNSString__     { return NO; }
+- (BOOL)isNSTimeZone__   { return NO; }
+- (BOOL)isNSValue__      { return NO; }
+
+@end
+
+
+static char *AllocTailGuardedPointer(size_t size) {
+  // Round up to page boundary.
+  size_t writeableSize = (size + PAGE_MAX_SIZE - 1) & ~(PAGE_MAX_SIZE - 1);
+
+  // Allocate writeable memory plus one guard page.
+  char *writeableBuffer = (char *)mmap(0, writeableSize + PAGE_MAX_SIZE,
+                                       PROT_READ | PROT_WRITE,
+                                       MAP_ANON | MAP_PRIVATE, -1, 0);
+  if (writeableBuffer == MAP_FAILED) abort();
+
+  // Mark the guard page inaccessible.
+  mprotect(writeableBuffer + writeableSize, PAGE_MAX_SIZE, 0);
+
+  // Scribble on the prefix.
+  memset(writeableBuffer, 0x55, writeableSize - size);
+
+  // Return the address just before the guard page.
+  // FIXME: this doesn't handle alignment properly,
+  // but we don't need to for this test's usage.
+  return writeableBuffer + writeableSize - size;
+}
+
+static Class CreateOldABISubclass(Class supercls, const char *name) {
+  // Allocate class and metaclass in tail-guarded memory.
+  // If the Swift runtime incorrectly tries to read Swift
+  // metadata from this class then it'll crash.
+  char *clsbuf  = AllocTailGuardedPointer(5*sizeof(uintptr_t));
+  char *metabuf = AllocTailGuardedPointer(5*sizeof(uintptr_t));
+  Class result = objc_initializeClassPair(supercls, name,
+                                          (Class)clsbuf, (Class)metabuf);
+
+  // Set the old is-Swift bit in the class.
+  uintptr_t *words = (uintptr_t *)clsbuf;
+  words[4] |= 1;
+
+  return result;
+}
+
+static Class FakeOldABIClass;
+
+__attribute__((constructor))
+static void initialize(void) {
+  FakeOldABIClass = CreateOldABISubclass([SwiftObject class],
+                                         "_TtC6OldABI8Subclass");
+}
+
+bool CanTestOldABI() {
+  // These tests don't work until the stable ABI is using its designed bit.
+  // This check can be removed after SWIFT_DARWIN_ENABLE_STABLE_ABI_BIT
+  // is set everywhere.
+  Class cls = objc_getClass("_TtCs19__EmptyArrayStorage");
+  if (!cls) abort();
+  uintptr_t *words = (uintptr_t *)cls;
+  if ((words[4] & 3) != 2) return false;  // wrong stable is-Swift bit
+  return true;
+}
+
+id AllocOldABIObject() {
+  return [FakeOldABIClass alloc];
+}
diff --git a/test/Interpreter/SDK/Inputs/OldABI/module.map b/test/Interpreter/SDK/Inputs/OldABI/module.map
new file mode 100644
index 0000000..4701a30
--- /dev/null
+++ b/test/Interpreter/SDK/Inputs/OldABI/module.map
@@ -0,0 +1,3 @@
+module OldABI {
+  header "OldABI.h"
+}
diff --git a/test/Interpreter/SDK/objc_old_swift.swift b/test/Interpreter/SDK/objc_old_swift.swift
new file mode 100644
index 0000000..76c9a89
--- /dev/null
+++ b/test/Interpreter/SDK/objc_old_swift.swift
@@ -0,0 +1,81 @@
+// RUN: %empty-directory(%t)
+//
+// RUN: cp %s %t/main.swift
+// RUN: %target-clang %S/Inputs/OldABI/OldABI.mm -g -c -o %t/OldABI.o
+// RUN: %target-build-swift %t/main.swift -framework Foundation -I %S/Inputs/OldABI/ -Xlinker %t/OldABI.o -o %t/objc_old_swift -Xfrontend -disable-access-control
+// RUN: %target-codesign %t/objc_old_swift
+// RUN: %target-run %t/objc_old_swift
+
+// REQUIRES: executable_test
+// REQUIRES: objc_interop
+
+// Verify that objects that appear to be from the pre-stable Swift ABI
+// are correctly ignored by stable Swift's entry points.
+
+import Foundation
+import OldABI
+import StdlibUnittest
+
+var tests = TestSuite("objc_old_swift")
+
+tests.test("description")
+  .skip(.custom({ !CanTestOldABI() },
+                reason: "not using stable ABI's is-Swift bit yet"))
+  .code {
+  let obj = AllocOldABIObject()
+  expectEqual(String(describing:obj), "OldABI.Subclass")
+  expectEqual((obj as AnyObject).description!, "FakeSwiftObject instance")
+}
+
+tests.test("casts")
+  .skip(.custom({ !CanTestOldABI() },
+                reason: "not using stable ABI's is-Swift bit yet"))
+  .code {
+  let obj = AllocOldABIObject()
+  expectNil(obj as? String)
+  expectNotNil(obj as Any)
+  expectNotNil(obj as AnyObject)
+}
+
+tests.test("array")
+  .skip(.custom({ !CanTestOldABI() },
+                reason: "not using stable ABI's is-Swift bit yet"))
+  .code {
+  let array = Array(repeating: AllocOldABIObject(), count:5)
+  expectEqual(String(describing: array), "[OldABI.Subclass, OldABI.Subclass, OldABI.Subclass, OldABI.Subclass, OldABI.Subclass]")
+
+  var array2 = Array(repeating: AllocOldABIObject(), count:0)
+  for i in 0..<array.count {
+    expectNotNil(array[i])
+    array2.append(i as NSNumber)
+    array2.append(array[i]);
+  }
+  expectEqual(String(describing: array2), "[0, OldABI.Subclass, 1, OldABI.Subclass, 2, OldABI.Subclass, 3, OldABI.Subclass, 4, OldABI.Subclass]")
+
+  // Bridge an array of pre-stable objects to NSArray
+  let nsarray = NSMutableArray(array: array2)
+  expectEqual(nsarray.description, #"""
+    (
+        0,
+        "FakeSwiftObject instance",
+        1,
+        "FakeSwiftObject instance",
+        2,
+        "FakeSwiftObject instance",
+        3,
+        "FakeSwiftObject instance",
+        4,
+        "FakeSwiftObject instance"
+    )
+    """#)
+
+  nsarray.add(5 as NSNumber)
+
+  // Bridge back from NSArray
+  let array3 = nsarray as [AnyObject]
+  expectEqual(String(describing: array3), "[0, OldABI.Subclass, 1, OldABI.Subclass, 2, OldABI.Subclass, 3, OldABI.Subclass, 4, OldABI.Subclass, 5]")
+}
+
+// FIXME: add coverage of more Swift runtime entrypoints
+
+runAllTests()
diff --git a/test/NameBinding/reference-dependencies.swift b/test/NameBinding/reference-dependencies.swift
index 1d1c120..5c61d42 100644
--- a/test/NameBinding/reference-dependencies.swift
+++ b/test/NameBinding/reference-dependencies.swift
@@ -416,7 +416,6 @@
 // CHECK-DAG: - !private ["s33ExpressibleByUnicodeScalarLiteralP", ""]
 // CHECK-DAG: - !private ["Sx", "Stride"]
 // CHECK-DAG: - !private ["Sa", "reduce"]
-// CHECK-DAG: - !private ["Sb", "_getBuiltinLogicValue"]
 // CHECK-DAG: - ["Sb", "InnerToBool"]
 // CHECK-DAG: - !private ["4main17OtherFileIntArrayV", "deinit"]
 // CHECK-DAG: - !private ["4main18OtherFileOuterTypeV", "InnerType"]
diff --git a/test/Parse/if_expr.swift b/test/Parse/if_expr.swift
index c029d60..07b0c8d 100644
--- a/test/Parse/if_expr.swift
+++ b/test/Parse/if_expr.swift
@@ -3,13 +3,10 @@
 // CHECK: (func_decl{{.*}}"r13756261(_:_:)"
 func r13756261(_ x: Bool, _ y: Int) -> Int {
   // CHECK: (if_expr
-  // CHECK:   (call_expr
   // CHECK:   (declref_expr
   // CHECK:   (if_expr
-  // CHECK:     (call_expr
   // CHECK:     (declref_expr
   // CHECK:     (if_expr
-  // CHECK:       (call_expr
   // CHECK:       (declref_expr
   // CHECK:       (declref_expr
   return (x) ? y : (x) ? y : (x) ? y : y
@@ -18,13 +15,10 @@
 // CHECK: (func_decl{{.*}}"r13756221(_:_:)"
 func r13756221(_ x: Bool, _ y: Int) -> Int {
   // CHECK: (if_expr
-  // CHECK:   (call_expr
   // CHECK:   (declref_expr
   // CHECK:   (if_expr
-  // CHECK:     (call_expr
   // CHECK:     (declref_expr
   // CHECK:     (if_expr
-  // CHECK:       (call_expr
   // CHECK:       (declref_expr
   // CHECK:       (declref_expr
   return (x) ? y
@@ -36,11 +30,8 @@
 // CHECK: (func_decl{{.*}}"telescoping_if(_:_:)"
 func telescoping_if(_ x: Bool, _ y: Int) -> Int {
   // CHECK: (if_expr
-  // CHECK:   (call_expr
   // CHECK:   (if_expr
-  // CHECK:     (call_expr
   // CHECK:     (if_expr
-  // CHECK:       (call_expr
   // CHECK:       (declref_expr
   // CHECK:       (declref_expr
   // CHECK:     (declref_expr
@@ -91,11 +82,9 @@
   // CHECK:     (binary_expr
   // CHECK:       (declref_expr
   // CHECK:       (if_expr
-  // CHECK:         (call_expr
   // CHECK:         (binary_expr
   // CHECK:         (declref_expr
   // CHECK:     (if_expr
-  // CHECK:       (call_expr
   // CHECK:       (binary_expr
   // CHECK:       (declref_expr
   // CHECK:   (declref_expr
@@ -109,14 +98,12 @@
   // CHECK: (binary_expr
   // CHECK:   (declref_expr
   // CHECK:   (if_expr
-  // CHECK:     (call_expr
   // CHECK:     (binary_expr
   // CHECK:       (declref_expr
   // CHECK:       (declref_expr
   // CHECK:     (binary_expr
   // CHECK:       (declref_expr
   // CHECK:       (if_expr
-  // CHECK:         (call_expr
   // CHECK:         (binary_expr
   // CHECK:           (declref_expr
   // CHECK:           (declref_expr
diff --git a/test/Runtime/demangleToMetadataObjC.swift b/test/Runtime/demangleToMetadataObjC.swift
index f6a89c9..fba76ef 100644
--- a/test/Runtime/demangleToMetadataObjC.swift
+++ b/test/Runtime/demangleToMetadataObjC.swift
@@ -92,6 +92,7 @@
 }
 
 DemangleToMetadataTests.test("members of runtime-only Objective-C classes") {
+  expectNotNil(_typeByName("So17OS_dispatch_queueC8DispatchE10AttributesV"))
   expectEqual(DispatchQueue.Attributes.self,
     _typeByName("So17OS_dispatch_queueC8DispatchE10AttributesV")!)
 }
diff --git a/test/SIL/Parser/witness_table_redeclare.sil b/test/SIL/Parser/witness_table_redeclare.sil
new file mode 100644
index 0000000..528646a
--- /dev/null
+++ b/test/SIL/Parser/witness_table_redeclare.sil
@@ -0,0 +1,12 @@
+// RUN: %target-sil-opt %s -module-name=witness_table_redeclare | %target-sil-opt -module-name=witness_table_redeclare | %FileCheck %s
+
+protocol P {}
+
+struct S : P {}
+
+sil_witness_table S: P module witness_table_redeclare
+
+sil_witness_table S: P module witness_table_redeclare {}
+
+// CHECK-LABEL: sil_witness_table S: P module witness_table_redeclare {
+// CHECK-NEXT: }
diff --git a/test/SIL/Serialization/Inputs/init_existential_inst_deserializes_witness_tables_input.swift b/test/SIL/Serialization/Inputs/init_existential_inst_deserializes_witness_tables_input.swift
index 4caca33..51ac863 100644
--- a/test/SIL/Serialization/Inputs/init_existential_inst_deserializes_witness_tables_input.swift
+++ b/test/SIL/Serialization/Inputs/init_existential_inst_deserializes_witness_tables_input.swift
@@ -13,6 +13,7 @@
   public init() {}
 }
 
+@inlinable
 public func whatShouldIDo(_ p : P) {
   p.doSomething()
 }
diff --git a/test/SILGen/expressions.swift b/test/SILGen/expressions.swift
index 2578dc7..7e9cb28 100644
--- a/test/SILGen/expressions.swift
+++ b/test/SILGen/expressions.swift
@@ -444,7 +444,7 @@
     : z
   // CHECK:   [[READ:%.*]] = begin_access [read] [unknown] [[PBA]]
   // CHECK:   [[A:%[0-9]+]] = load [trivial] [[READ]]
-  // CHECK:   [[ACOND:%[0-9]+]] = apply {{.*}}([[A]])
+  // CHECK:   [[ACOND:%[0-9]+]] = struct_extract [[A]] : $Bool, #Bool._value
   // CHECK:   cond_br [[ACOND]], [[IF_A:bb[0-9]+]], [[ELSE_A:bb[0-9]+]]
   // CHECK: [[IF_A]]:
   // CHECK:   [[READ:%.*]] = begin_access [read] [unknown] [[PBX]]
@@ -453,7 +453,7 @@
   // CHECK: [[ELSE_A]]:
   // CHECK:   [[READ:%.*]] = begin_access [read] [unknown] [[PBB]]
   // CHECK:   [[B:%[0-9]+]] = load [trivial] [[READ]]
-  // CHECK:   [[BCOND:%[0-9]+]] = apply {{.*}}([[B]])
+  // CHECK:   [[BCOND:%[0-9]+]] = struct_extract [[B]] : $Bool, #Bool._value
   // CHECK:   cond_br [[BCOND]], [[IF_B:bb[0-9]+]], [[ELSE_B:bb[0-9]+]]
   // CHECK: [[IF_B]]:
   // CHECK:   [[READ:%.*]] = begin_access [read] [unknown] [[PBY]]
diff --git a/test/SILGen/if_while_binding.swift b/test/SILGen/if_while_binding.swift
index 47b5ffb..31329e6 100644
--- a/test/SILGen/if_while_binding.swift
+++ b/test/SILGen/if_while_binding.swift
@@ -247,7 +247,7 @@
   // CHECK:   br [[DONE]]
 
   // CHECK: [[CHECK_WHERE]]([[B:%[0-9]+]] : @owned $String):
-  // CHECK:   function_ref Swift.Bool._getBuiltinLogicValue() -> Builtin.Int1
+  // CHECK:   struct_extract {{.*}}
   // CHECK:   cond_br {{.*}}, [[IF_BODY:bb[0-9]+]], [[IF_EXIT3:bb[0-9]+]]
   if let a = foo(), var b = bar(), a == b {
     // CHECK: [[IF_BODY]]:
@@ -274,8 +274,7 @@
   // CHECK: debug_value %0 : $Int, let, name "a"
   // CHECK: [[EQRESULT:%[0-9]+]] = apply {{.*}}(%0, %0{{.*}}) : $@convention({{.*}}) (Int, Int{{.*}}) -> Bool
 
-  // CHECK:      [[FN:%.*]] = function_ref {{.*}}
-  // CHECK-NEXT: [[EQRESULTI1:%[0-9]+]] = apply [[FN:%.*]]([[EQRESULT]]) : $@convention(method) (Bool) -> Builtin.Int1
+  // CHECK: [[EQRESULTI1:%[0-9]+]] = struct_extract {{.*}} : $Bool, #Bool._value
   // CHECK-NEXT: cond_br [[EQRESULTI1]], [[CHECKFOO:bb[0-9]+]], [[ELSE:bb[0-9]+]]
 
   // Call Foo and test for the optional being present.
diff --git a/test/SILGen/mangling_retroactive.swift b/test/SILGen/mangling_retroactive.swift
index dba5acc..099003e 100644
--- a/test/SILGen/mangling_retroactive.swift
+++ b/test/SILGen/mangling_retroactive.swift
@@ -12,14 +12,14 @@
 extension X: P { } // retroactive
 extension Y: Q { } // retroactive
 
-// CHECK: sil hidden [ossa] @$s20mangling_retroactive5test0yyAA1ZVy12RetroactiveB1XVSiAE1YVAG0D1A1PAAHPyHCg_AiJ1QAAHPyHCg1_GF
+// CHECK: sil hidden [ossa] @$s20mangling_retroactive5test0yyAA1ZVy12RetroactiveB1XVSiAE1YVAG0D1A1PAAyHCg_AiJ1QAAyHCg1_GF
 func test0(_: Z<X, Int, Y>) { }
 
 struct Z2<T: P> {
   struct Inner<V: Q> { }
 }
 
-// CHECK: sil hidden [ossa] @$s20mangling_retroactive5test1yyAA2Z2V5InnerVy12RetroactiveB1XV_AG1YVAI0F1A1PAAHPyHCg_AkL1QAAHPyHCg0_GF
+// CHECK: sil hidden [ossa] @$s20mangling_retroactive5test1yyAA2Z2V5InnerVy12RetroactiveB1XV_AG1YVAI0F1A1PAAyHCg_AkL1QAAyHCg0_GF
 func test1(_: Z2<X>.Inner<Y>) { }
 
 extension X: Hashable {
@@ -38,5 +38,52 @@
 struct RequiresEquatable<T: Equatable> { }
 
 // Conditional requirement involves retroactive conformances.
-// CHECK: sil hidden [ossa] @$s20mangling_retroactive5test2yyAA17RequiresEquatableVyAA1ZVy12RetroactiveB1XVSiAG1YVAI0F1A1PAAHPyHCg_AkL1QAAHPyHCg1_GAOSQHPAISHAAHPyHC_AKSQAAHPyHCHCg_GF
+// CHECK: sil hidden [ossa] @$s20mangling_retroactive5test2yyAA17RequiresEquatableVyAA1ZVy12RetroactiveB1XVSiAG1YVAI0F1A1PAAyHCg_AkL1QAAyHCg1_GAOSQHPAISHAAyHC_AKSQAAyHCHCg_GF
 func test2(_: RequiresEquatable<Z<X, Int, Y>>) { }
+
+struct UnconditionallyP<T: Q>: P {}
+struct RequiresP<T: P> {}
+
+// RequiresP uses a non-retroactive conformance for its generic param
+// UnconditionallyP, even though UnconditionallyP's generic param uses a
+// retroactive conformance to conform to Q.
+func rdar46735592(_: RequiresP<UnconditionallyP<Y>>) { }
+// CHECK: sil hidden [ossa] @$s20mangling_retroactive12rdar46735592yyAA9RequiresPVyAA16UnconditionallyPVy12RetroactiveB1YVAI0F1A1QAAyHCg_GGF
+
+struct QImpl: Q {}
+struct ConditionallyP<T> {}
+extension ConditionallyP: P where T: Q {}
+
+func useConditionallyP(_: RequiresP<ConditionallyP<QImpl>>) {}
+func useConditionallyP_retroactive(_: RequiresP<ConditionallyP<Y>>) {}
+// CHECK: sil hidden [ossa] @$s20mangling_retroactive17useConditionallyPyyAA9RequiresPVyAA0D1PVyAA5QImplVGGF
+// CHECK: sil hidden [ossa] @$s20mangling_retroactive018useConditionallyP_B0yyAA9RequiresPVyAA0D1PVy12RetroactiveB1YVGAJ0F1A1PHPAiK1QAAyHC_HCg_GF
+
+protocol Wrapper {
+  associatedtype Wrapped
+}
+struct WrapperImpl<Wrapped>: Wrapper {}
+
+struct IndirectlyConditionallyP<T: Wrapper> {}
+extension IndirectlyConditionallyP: P where T.Wrapped: Q {}
+
+func useIndirectlyConditionallyP(_: RequiresP<IndirectlyConditionallyP<WrapperImpl<QImpl>>>) {}
+func useIndirectlyConditionallyP_retroactive(_: RequiresP<IndirectlyConditionallyP<WrapperImpl<Y>>>) {}
+// CHECK: sil hidden [ossa] @$s20mangling_retroactive27useIndirectlyConditionallyPyyAA9RequiresPVyAA0dE1PVyAA11WrapperImplVyAA5QImplVGGGF
+// CHECK: sil hidden [ossa] @$s20mangling_retroactive028useIndirectlyConditionallyP_B0yyAA9RequiresPVyAA0dE1PVyAA11WrapperImplVy12RetroactiveB1YVGGAM0I1A1PHPAkN1QAAyHC_HCg_GF
+
+struct IndirectlyConditionallyP2<T> {}
+extension IndirectlyConditionallyP2: P where T: Wrapper, T.Wrapped: Q {}
+
+func useIndirectlyConditionallyP2(_: RequiresP<IndirectlyConditionallyP<WrapperImpl<QImpl>>>) {}
+func useIndirectlyConditionallyP2_retroactive(_: RequiresP<IndirectlyConditionallyP<WrapperImpl<Y>>>) {}
+// CHECK: sil hidden [ossa] @$s20mangling_retroactive28useIndirectlyConditionallyP2yyAA9RequiresPVyAA0dE1PVyAA11WrapperImplVyAA5QImplVGGGF
+// CHECK: sil hidden [ossa] @$s20mangling_retroactive029useIndirectlyConditionallyP2_B0yyAA9RequiresPVyAA0dE1PVyAA11WrapperImplVy12RetroactiveB1YVGGAM0J1A1PHPAkN1QAAyHC_HCg_GF
+
+protocol NonRetroactive {}
+extension Y: NonRetroactive {}
+struct ConditionallyP2<T> {}
+extension ConditionallyP2: P where T: Q, T: NonRetroactive {}
+
+func useConditionallyP2(_: RequiresP<ConditionallyP2<Y>>) {}
+// CHECK: sil hidden [ossa] @$s20mangling_retroactive18useConditionallyP2yyAA9RequiresPVyAA0dE0Vy12RetroactiveB1YVGAJ0G1A1PHPAiK1QAAyHC_AiA03NonG0HpyHCHCg_GF
diff --git a/test/SILGen/pound_assert.swift b/test/SILGen/pound_assert.swift
index 90e4bbf..3e0ce39 100644
--- a/test/SILGen/pound_assert.swift
+++ b/test/SILGen/pound_assert.swift
@@ -3,8 +3,7 @@
 // CHECK-LABEL: sil hidden [ossa] @$s12pound_assert15noCustomMessage{{[_0-9a-zA-Z]*}}
 func noCustomMessage() {
   #assert(true)
-  // CHECK: [[GET_LOGIC_VALUE:%.*]] = function_ref {{.*}}_getBuiltinLogicValue
-  // CHECK-NEXT: [[LOGIC_VALUE:%.*]] = apply [[GET_LOGIC_VALUE]]
+  // CHECK: [[LOGIC_VALUE:%.*]] = struct_extract {{.*}}
   // CHECK-NEXT: [[MESSAGE:%.*]] = string_literal utf8 ""
   // CHECK-NEXT: builtin "poundAssert"([[LOGIC_VALUE]] : $Builtin.Int1, [[MESSAGE]] : $Builtin.RawPointer)
 }
@@ -13,8 +12,7 @@
 // CHECK-LABEL: sil hidden [ossa] @$s12pound_assert13customMessage{{[_0-9a-zA-Z]*}}
 func customMessage() {
   #assert(true, "custom message")
-  // CHECK: [[GET_LOGIC_VALUE:%.*]] = function_ref {{.*}}_getBuiltinLogicValue
-  // CHECK-NEXT: [[LOGIC_VALUE:%.*]] = apply [[GET_LOGIC_VALUE]]
+  // CHECK: [[LOGIC_VALUE:%.*]] = struct_extract {{.*}}
   // CHECK-NEXT: [[MESSAGE:%.*]] = string_literal utf8 "custom message"
   // CHECK-NEXT: builtin "poundAssert"([[LOGIC_VALUE]] : $Builtin.Int1, [[MESSAGE]] : $Builtin.RawPointer)
 }
diff --git a/test/SILGen/sil_locations.swift b/test/SILGen/sil_locations.swift
index 800e39f1..60814ac 100644
--- a/test/SILGen/sil_locations.swift
+++ b/test/SILGen/sil_locations.swift
@@ -335,7 +335,7 @@
   // CHECK-LABEL: sil hidden [ossa] @$s13sil_locations21testStringForEachStmtyyF
   // CHECK: br {{.*}} line:[[@LINE-8]]:3
   // CHECK: switch_enum {{.*}} line:[[@LINE-9]]:3
-  // CHECK: cond_br {{.*}} line:[[@LINE-8]]:8
+  // CHECK: cond_br {{.*}} line:[[@LINE-8]]:10
   // Break branch:
   // CHECK: br {{.*}} line:[[@LINE-9]]:7
   // Looping back branch:
@@ -388,9 +388,9 @@
   
   // CHECK-LABEL: sil hidden [ossa] @$s13sil_locations15testRepeatWhileyyF
   // CHECK: br {{.*}} line:[[@LINE-6]]:3
-  // CHECK: cond_br {{.*}} line:[[@LINE-5]]:11
+  // CHECK: cond_br {{.*}} line:[[@LINE-5]]:14
   // Loop back branch:
-  // CHECK: br {{.*}} line:[[@LINE-7]]:11  
+  // CHECK: br {{.*}} line:[[@LINE-7]]:14
 }
 
 
@@ -408,9 +408,9 @@
   // CHECK-LABEL: sil hidden [ossa] @$s13sil_locations9testWhileyyF
   // CHECK: br {{.*}} line:[[@LINE-9]]:3
   // While loop conditional branch:
-  // CHECK: cond_br {{.*}} line:[[@LINE-11]]:9
+  // CHECK: cond_br {{.*}} line:[[@LINE-11]]:11
   // If stmt condition branch:
-  // CHECK: cond_br {{.*}} line:[[@LINE-11]]:8
+  // CHECK: cond_br {{.*}} line:[[@LINE-11]]:10
   // Break branch:
   // CHECK: br {{.*}} line:[[@LINE-12]]:7
   // Looping back branch:
diff --git a/test/SILGen/statements.swift b/test/SILGen/statements.swift
index 2288b70..6c2dbce 100644
--- a/test/SILGen/statements.swift
+++ b/test/SILGen/statements.swift
@@ -323,8 +323,7 @@
 func test_if_break(_ a : Bool) {
   // CHECK: br [[LOOP:bb[0-9]+]]
   // CHECK: [[LOOP]]:
-  // CHECK: function_ref @$sSb21_getBuiltinLogicValue{{[_0-9a-zA-Z]*}}F
-  // CHECK-NEXT: apply
+  // CHECK-NEXT: struct_extract {{.*}}
   // CHECK-NEXT: cond_br {{.*}}, [[LOOPTRUE:bb[0-9]+]], [[EXIT:bb[0-9]+]]
   while a {
     if a {
@@ -335,8 +334,7 @@
   }
 
   // CHECK: [[LOOPTRUE]]:
-  // CHECK: function_ref @$sSb21_getBuiltinLogicValue{{[_0-9a-zA-Z]*}}F
-  // CHECK-NEXT: apply
+  // CHECK-NEXT: struct_extract {{.*}}
   // CHECK-NEXT: cond_br {{.*}}, [[IFTRUE:bb[0-9]+]], [[IFFALSE:bb[0-9]+]]
 
   // [[IFTRUE]]:
@@ -473,7 +471,7 @@
   callee3()
   
 // test the condition.
-// CHECK:  [[CONDTRUE:%.*]] = apply {{.*}}(%0)
+// CHECK:  [[CONDTRUE:%.*]] = struct_extract {{.*}}
 // CHECK: cond_br [[CONDTRUE]], [[BODY:bb[0-9]+]], [[EXIT:bb[0-9]+]]
   while cond {
 // CHECK: [[BODY]]:
diff --git a/test/SILOptimizer/dead_witness_module.swift b/test/SILOptimizer/dead_witness_module.swift
index 577811f..743fb20 100644
--- a/test/SILOptimizer/dead_witness_module.swift
+++ b/test/SILOptimizer/dead_witness_module.swift
@@ -5,9 +5,11 @@
 // DeadFunctionElimination may not remove a method from a witness table which
 // is imported from another module.
 
+// FIXME: Ever since @usableFromInline began to be enforced, this test did not
+// test anything useful, and now the witness table is never deserialized at all.
+
 import TestModule
 
 testit(MyStruct())
 
-// CHECK: sil_witness_table public_external MyStruct: Proto module TestModule
-// CHECK-NEXT: method #Proto.confx!1: {{.*}} : @$s{{.*}}confx{{.*}}FTW
+// CHECK-NOT: sil_witness_table MyStruct: Proto module TestModule
diff --git a/test/SILOptimizer/devirt_jump_thread.sil b/test/SILOptimizer/devirt_jump_thread.sil
index e7a76bb..e5eaf9a 100644
--- a/test/SILOptimizer/devirt_jump_thread.sil
+++ b/test/SILOptimizer/devirt_jump_thread.sil
@@ -437,9 +437,6 @@
 }
 
 
-sil [transparent] [serialized] @_TFSb21_getBuiltinLogicValuefSbFT_Bi1_ : $@convention(method) (Bool) -> Builtin.Int1
-
-
 sil [serialized] @_TZFsoi3eeeFTGSqPs9AnyObject__GSqPS____Sb : $@convention(thin) (@owned Optional<AnyObject>, @owned Optional<AnyObject>) -> Bool
 
 
diff --git a/test/api-digester/Inputs/stdlib-stable-abi.json b/test/api-digester/Inputs/stdlib-stable-abi.json
index 85021c0..9f19d8a 100644
--- a/test/api-digester/Inputs/stdlib-stable-abi.json
+++ b/test/api-digester/Inputs/stdlib-stable-abi.json
@@ -14654,25 +14654,6 @@
           ]
         },
         {
-          "kind": "Function",
-          "name": "_getBuiltinLogicValue",
-          "printedName": "_getBuiltinLogicValue()",
-          "children": [
-            {
-              "kind": "TypeNominal",
-              "name": "BuiltinInteger",
-              "printedName": "Builtin.Int1"
-            }
-          ],
-          "declKind": "Func",
-          "usr": "s:Sb21_getBuiltinLogicValueBi1_yF",
-          "moduleName": "Swift",
-          "declAttributes": [
-            "Transparent"
-          ],
-          "funcSelfKind": "NonMutating"
-        },
-        {
           "kind": "Var",
           "name": "description",
           "printedName": "description",
diff --git a/test/attr/attr_usableFromInline_protocol.swift b/test/attr/attr_usableFromInline_protocol.swift
index a940abb..c2459e1 100644
--- a/test/attr/attr_usableFromInline_protocol.swift
+++ b/test/attr/attr_usableFromInline_protocol.swift
@@ -7,8 +7,8 @@
 }
 
 @usableFromInline struct UFIAdopter<T> : PublicProtoWithReqs {}
-// expected-error@-1 {{type alias 'Assoc' must be declared '@usableFromInline' because because it matches a requirement in protocol 'PublicProtoWithReqs'}} {{none}}
-// expected-error@-2 {{instance method 'foo()' must be declared '@usableFromInline' because because it matches a requirement in protocol 'PublicProtoWithReqs'}} {{none}}
+// expected-error@-1 {{type alias 'Assoc' must be declared '@usableFromInline' because it matches a requirement in protocol 'PublicProtoWithReqs'}} {{none}}
+// expected-error@-2 {{instance method 'foo()' must be declared '@usableFromInline' because it matches a requirement in protocol 'PublicProtoWithReqs'}} {{none}}
 extension UFIAdopter {
   typealias Assoc = Int
   // expected-note@-1 {{'Assoc' declared here}}
@@ -18,9 +18,9 @@
 
 @usableFromInline struct UFIAdopterAllInOne<T> : PublicProtoWithReqs {
   typealias Assoc = Int
-  // expected-error@-1 {{type alias 'Assoc' must be declared '@usableFromInline' because because it matches a requirement in protocol 'PublicProtoWithReqs'}} {{none}}
+  // expected-error@-1 {{type alias 'Assoc' must be declared '@usableFromInline' because it matches a requirement in protocol 'PublicProtoWithReqs'}} {{none}}
   func foo() {}
-  // expected-error@-1 {{instance method 'foo()' must be declared '@usableFromInline' because because it matches a requirement in protocol 'PublicProtoWithReqs'}} {{none}}
+  // expected-error@-1 {{instance method 'foo()' must be declared '@usableFromInline' because it matches a requirement in protocol 'PublicProtoWithReqs'}} {{none}}
 }
 
 internal struct InternalAdopter<T> : PublicProtoWithReqs {}
@@ -36,8 +36,8 @@
 }
 
 public struct PublicAdopter<T> : UFIProtoWithReqs {}
-// expected-error@-1 {{type alias 'Assoc' must be declared '@usableFromInline' because because it matches a requirement in protocol 'UFIProtoWithReqs'}} {{none}}
-// expected-error@-2 {{instance method 'foo()' must be declared '@usableFromInline' because because it matches a requirement in protocol 'UFIProtoWithReqs'}} {{none}}
+// expected-error@-1 {{type alias 'Assoc' must be declared '@usableFromInline' because it matches a requirement in protocol 'UFIProtoWithReqs'}} {{none}}
+// expected-error@-2 {{instance method 'foo()' must be declared '@usableFromInline' because it matches a requirement in protocol 'UFIProtoWithReqs'}} {{none}}
 extension PublicAdopter {
   typealias Assoc = Int
   // expected-note@-1 {{'Assoc' declared here}}
diff --git a/test/benchmark/Benchmark_O.test.md b/test/benchmark/Benchmark_O.test.md
index ff2fe61..f55965d 100644
--- a/test/benchmark/Benchmark_O.test.md
+++ b/test/benchmark/Benchmark_O.test.md
@@ -163,7 +163,7 @@
 MEASUREENV: VCS {{[0-9]+}} - {{[0-9]+}} = {{[0-9]+}}
 RUNJUSTONCE-LABEL: 1,Ackermann
 RUNJUSTONCE-NOT: 1,Ackermann
-LOGFORMAT: ,{{[0-9]+}},{{[0-9]+}},,{{[0-9]+}},{{[0-9]+}}
+LOGFORMAT: ,{{[0-9]+}},{{[0-9]+}},,{{,|[0-9]+}},{{[0-9]+}}
 LOGVERBOSE-LABEL: Running AngryPhonebook
 LOGVERBOSE: Collecting 2 samples.
 ````
diff --git a/tools/lldb-moduleimport-test/lldb-moduleimport-test.cpp b/tools/lldb-moduleimport-test/lldb-moduleimport-test.cpp
index 5627cf4..ecdc220 100644
--- a/tools/lldb-moduleimport-test/lldb-moduleimport-test.cpp
+++ b/tools/lldb-moduleimport-test/lldb-moduleimport-test.cpp
@@ -229,7 +229,7 @@
     if (Filename.empty())
       return true;
     if (!llvm::sys::fs::exists(llvm::Twine(Filename))) {
-      llvm::errs() << Filename << " does not exists, exiting.\n";
+      llvm::errs() << Filename << " does not exist, exiting.\n";
       return false;
     }
     if (!llvm::sys::fs::is_regular_file(llvm::Twine(Filename))) {
diff --git a/utils/WindowsSDKVFSOverlay.yaml.in b/utils/WindowsSDKVFSOverlay.yaml.in
index d44c2f9..e9e2a00 100644
--- a/utils/WindowsSDKVFSOverlay.yaml.in
+++ b/utils/WindowsSDKVFSOverlay.yaml.in
@@ -17,6 +17,9 @@
       - name: wtypesbase.h
         type: file
         external-contents: "@UniversalCRTSdkDir@/Include/@UCRTVersion@/shared/WTypesbase.h"
+      - name: ConcurrencySal.h
+        type: file
+        external-contents: "@UniversalCRTSdkDir@/Include/@UCRTVersion@/shared/concurrencysal.h"
   - name: "@UniversalCRTSdkDir@/Include/@UCRTVersion@/um"
     type: directory
     contents:
diff --git a/utils/build_swift/argparse/types.py b/utils/build_swift/argparse/types.py
index 76ee6e2..7686c0d 100644
--- a/utils/build_swift/argparse/types.py
+++ b/utils/build_swift/argparse/types.py
@@ -115,7 +115,7 @@
         path = os.path.abspath(path)
 
         if self._assert_exists and not os.path.exists(path):
-            raise ArgumentTypeError('{} does not exists'.format(path))
+            raise ArgumentTypeError('{} does not exist'.format(path))
 
         if self._assert_executable and not PathType._is_executable(path):
             raise ArgumentTypeError('{} is not an executable'.format(path))