Merge pull request #10685 from itaiferber/codingerror-bridging-and-conveniences

EncodingError/DecodingError bridging fixes and conveniences
diff --git a/cmake/modules/DarwinSDKs.cmake b/cmake/modules/DarwinSDKs.cmake
index 8e680e6..de7b650 100644
--- a/cmake/modules/DarwinSDKs.cmake
+++ b/cmake/modules/DarwinSDKs.cmake
@@ -1,8 +1,16 @@
+set(SUPPORTED_IOS_ARCHS "armv7;armv7s;arm64")
+set(SUPPORTED_IOS_SIMULATOR_ARCHS "i386;x86_64")
+set(SUPPORTED_TVOS_ARCHS "arm64")
+set(SUPPORTED_TVOS_SIMULATOR_ARCHS "x86_64")
+set(SUPPORTED_WATCHOS_ARCHS "armv7k")
+set(SUPPORTED_WATCHOS_SIMULATOR_ARCHS "i386")
+set(SUPPORTED_OSX_ARCHS "x86_64")
+
 is_sdk_requested(OSX swift_build_osx)
 if(swift_build_osx)
   configure_sdk_darwin(
       OSX "OS X" "${SWIFT_DARWIN_DEPLOYMENT_VERSION_OSX}"
-      macosx macosx macosx "x86_64")
+      macosx macosx macosx "${SUPPORTED_OSX_ARCHS}")
   configure_target_variant(OSX-DA "OS X Debug+Asserts"   OSX DA "Debug+Asserts")
   configure_target_variant(OSX-RA "OS X Release+Asserts" OSX RA "Release+Asserts")
   configure_target_variant(OSX-R  "OS X Release"         OSX R  "Release")
@@ -15,7 +23,7 @@
 if(swift_build_ios)
   configure_sdk_darwin(
       IOS "iOS" "${SWIFT_DARWIN_DEPLOYMENT_VERSION_IOS}"
-      iphoneos ios ios "armv7;armv7s;arm64")
+      iphoneos ios ios "${SUPPORTED_IOS_ARCHS}")
   configure_target_variant(IOS-DA "iOS Debug+Asserts"   IOS DA "Debug+Asserts")
   configure_target_variant(IOS-RA "iOS Release+Asserts" IOS RA "Release+Asserts")
   configure_target_variant(IOS-R  "iOS Release"         IOS R "Release")
@@ -25,7 +33,7 @@
 if(swift_build_ios_simulator)
   configure_sdk_darwin(
       IOS_SIMULATOR "iOS Simulator" "${SWIFT_DARWIN_DEPLOYMENT_VERSION_IOS}"
-      iphonesimulator ios-simulator ios "i386;x86_64")
+      iphonesimulator ios-simulator ios "${SUPPORTED_IOS_SIMULATOR_ARCHS}")
   configure_target_variant(
       IOS_SIMULATOR-DA "iOS Debug+Asserts"   IOS_SIMULATOR DA "Debug+Asserts")
   configure_target_variant(
@@ -38,7 +46,7 @@
 if(swift_build_tvos)
   configure_sdk_darwin(
       TVOS "tvOS" "${SWIFT_DARWIN_DEPLOYMENT_VERSION_TVOS}"
-      appletvos tvos tvos "arm64")
+      appletvos tvos tvos "${SUPPORTED_TVOS_ARCHS}")
   configure_target_variant(TVOS-DA "tvOS Debug+Asserts"   TVOS DA "Debug+Asserts")
   configure_target_variant(TVOS-RA "tvOS Release+Asserts" TVOS RA "Release+Asserts")
   configure_target_variant(TVOS-R  "tvOS Release"         TVOS R "Release")
@@ -48,7 +56,7 @@
 if(swift_build_tvos_simulator)
   configure_sdk_darwin(
       TVOS_SIMULATOR "tvOS Simulator" "${SWIFT_DARWIN_DEPLOYMENT_VERSION_TVOS}"
-      appletvsimulator tvos-simulator tvos "x86_64")
+      appletvsimulator tvos-simulator tvos "${SUPPORTED_TVOS_SIMULATOR_ARCHS}")
   configure_target_variant(
     TVOS_SIMULATOR-DA "tvOS Debug+Asserts"   TVOS_SIMULATOR DA "Debug+Asserts")
   configure_target_variant(
@@ -61,7 +69,7 @@
 if(swift_build_watchos)
   configure_sdk_darwin(
       WATCHOS "watchOS" "${SWIFT_DARWIN_DEPLOYMENT_VERSION_WATCHOS}"
-      watchos watchos watchos "armv7k")
+      watchos watchos watchos "${SUPPORTED_WATCHOS_ARCHS}")
   configure_target_variant(WATCHOS-DA "watchOS Debug+Asserts"   WATCHOS DA "Debug+Asserts")
   configure_target_variant(WATCHOS-RA "watchOS Release+Asserts" WATCHOS RA "Release+Asserts")
   configure_target_variant(WATCHOS-R  "watchOS Release"         WATCHOS R "Release")
@@ -71,7 +79,7 @@
 if(swift_build_watchos_simulator)
   configure_sdk_darwin(
       WATCHOS_SIMULATOR "watchOS Simulator" "${SWIFT_DARWIN_DEPLOYMENT_VERSION_WATCHOS}"
-      watchsimulator watchos-simulator watchos "i386")
+      watchsimulator watchos-simulator watchos "${SUPPORTED_WATCHOS_SIMULATOR_ARCHS}")
   configure_target_variant(WATCHOS_SIMULATOR-DA "watchOS Debug+Asserts"   WATCHOS_SIMULATOR DA "Debug+Asserts")
   configure_target_variant(WATCHOS_SIMULATOR-RA "watchOS Release+Asserts" WATCHOS_SIMULATOR RA "Release+Asserts")
   configure_target_variant(WATCHOS_SIMULATOR-R  "watchOS Release"         WATCHOS_SIMULATOR R "Release")
diff --git a/cmake/modules/SwiftSource.cmake b/cmake/modules/SwiftSource.cmake
index ac97012..aa525d3 100644
--- a/cmake/modules/SwiftSource.cmake
+++ b/cmake/modules/SwiftSource.cmake
@@ -59,9 +59,6 @@
   if (NOT SWIFTSOURCES_IS_MAIN)
     list(APPEND swift_compile_flags "-module-link-name" "${name}")
   endif()
-  if("${SWIFTSOURCES_SDK}" STREQUAL "CYGWIN")
-    list(APPEND swift_compile_flags -DCYGWIN)
-  endif()
 
   if(swift_sources)
     compute_library_subdir(SWIFTSOURCES_LIBRARY_SUBDIR
diff --git a/include/swift/AST/DiagnosticsSema.def b/include/swift/AST/DiagnosticsSema.def
index 03f7815..649cf2a 100644
--- a/include/swift/AST/DiagnosticsSema.def
+++ b/include/swift/AST/DiagnosticsSema.def
@@ -909,6 +909,10 @@
       "use of %0 refers to %1 %2 rather than %3 %4 in %5 %6",
       (DeclName, DescriptiveDeclKind, DeclName, DescriptiveDeclKind, DeclName,
        DescriptiveDeclKind, DeclName))
+ERROR(member_shadows_global_function_near_match,none,
+      "use of %0 nearly matches %3 %4 in %5 %6 rather than %1 %2",
+      (DeclName, DescriptiveDeclKind, DeclName, DescriptiveDeclKind, DeclName,
+      DescriptiveDeclKind, DeclName))
 
 ERROR(instance_member_use_on_type,none,
       "instance member %1 cannot be used on type %0; "
diff --git a/include/swift/Basic/LangOptions.h b/include/swift/Basic/LangOptions.h
index 5a64126..ef88835 100644
--- a/include/swift/Basic/LangOptions.h
+++ b/include/swift/Basic/LangOptions.h
@@ -185,6 +185,9 @@
     /// accesses.
     bool DisableTsanInoutInstrumentation = false;
 
+    /// \brief Staging flag for reporting runtime issues to the debugger.
+    bool ReportErrorsToDebugger = false;
+
     /// \brief Staging flag for class resilience, which we do not want to enable
     /// fully until more code is in place, to allow the standard library to be
     /// tested with value type resilience only.
diff --git a/include/swift/Option/FrontendOptions.td b/include/swift/Option/FrontendOptions.td
index 62926fe..4bc4968 100644
--- a/include/swift/Option/FrontendOptions.td
+++ b/include/swift/Option/FrontendOptions.td
@@ -294,6 +294,9 @@
   "disable-tsan-inout-instrumentation">,
   HelpText<"Disable treatment of inout parameters as Thread Sanitizer accesses">;
 
+def report_errors_to_debugger : Flag<["-"], "report-errors-to-debugger">,
+  HelpText<"Invoke the debugger hook on fatalError calls">;
+
 def enable_infer_import_as_member :
   Flag<["-"], "enable-infer-import-as-member">,
   HelpText<"Infer when a global could be imported as a member">;
diff --git a/include/swift/Runtime/Debug.h b/include/swift/Runtime/Debug.h
index 7512d1a..3e67edb 100644
--- a/include/swift/Runtime/Debug.h
+++ b/include/swift/Runtime/Debug.h
@@ -210,6 +210,9 @@
 void reportToDebugger(uintptr_t flags, const char *message,
                       RuntimeErrorDetails *details = nullptr);
 
+SWIFT_RUNTIME_EXPORT
+bool _swift_reportFatalErrorsToDebugger;
+
 // namespace swift
 }
 
diff --git a/lib/AST/Decl.cpp b/lib/AST/Decl.cpp
index c3b14c5..9857e63 100644
--- a/lib/AST/Decl.cpp
+++ b/lib/AST/Decl.cpp
@@ -3282,20 +3282,10 @@
 
   auto module = getParentModule();
 
-  auto genericSig = getGenericSignature();
-  // The signature should look like <Self where Self : ThisProtocol>, and we
-  // reuse the two parts of it because the parameter and the requirement are
-  // exactly what we need.
-  auto validSig = genericSig->getGenericParams().size() == 1 &&
-                  genericSig->getRequirements().size() == 1;
-  if (!validSig) {
-    // This doesn't look like a protocol we can handle, so some other error must
-    // have occurred (usually a protocol nested within another declaration)
-    return;
-  }
-
-  auto selfType = genericSig->getGenericParams()[0];
-  auto requirement = genericSig->getRequirements()[0];
+  auto selfType = getSelfInterfaceType()->castTo<GenericTypeParamType>();
+  auto requirement =
+    Requirement(RequirementKind::Conformance, selfType,
+                getDeclaredInterfaceType());
 
   GenericSignatureBuilder builder(getASTContext(),
                                   LookUpConformanceInModule(module));
@@ -3307,7 +3297,7 @@
   builder.addRequirement(
          requirement,
          GenericSignatureBuilder::RequirementSource
-          ::forRequirementSignature(selfPA, this),
+           ::forRequirementSignature(selfPA, this),
          nullptr);
   
   RequirementSignature = builder.computeGenericSignature(SourceLoc());
diff --git a/lib/Basic/LangOptions.cpp b/lib/Basic/LangOptions.cpp
index d648b4a..6906b01 100644
--- a/lib/Basic/LangOptions.cpp
+++ b/lib/Basic/LangOptions.cpp
@@ -36,6 +36,7 @@
   "Windows",
   "Android",
   "PS4",
+  "Cygwin",
 };
 
 static const StringRef SupportedConditionalCompilationArches[] = {
@@ -157,6 +158,8 @@
     addPlatformConditionValue(PlatformConditionKind::OS, "FreeBSD");
   else if (triple.isOSWindows())
     addPlatformConditionValue(PlatformConditionKind::OS, "Windows");
+  else if (triple.isWindowsCygwinEnvironment())
+    addPlatformConditionValue(PlatformConditionKind::OS, "Cygwin");
   else if (triple.isPS4())
     addPlatformConditionValue(PlatformConditionKind::OS, "PS4");
   else
diff --git a/lib/Demangling/Demangler.cpp b/lib/Demangling/Demangler.cpp
index 9b51d11..e3b8b48 100644
--- a/lib/Demangling/Demangler.cpp
+++ b/lib/Demangling/Demangler.cpp
@@ -109,14 +109,11 @@
 
 } // anonymous namespace
 
-namespace swift {
-namespace Demangle {
-
 //////////////////////////////////
 // Public utility functions    //
 //////////////////////////////////
 
-int getManglingPrefixLength(const char *mangledName) {
+int swift::Demangle::getManglingPrefixLength(const char *mangledName) {
   // Check for the swift-4 prefix
   if (mangledName[0] == '_' && mangledName[1] == 'T' && mangledName[2] == '0')
     return 3;
@@ -129,7 +126,7 @@
   return 0;
 }
 
-bool isSwiftSymbol(const char *mangledName) {
+bool swift::Demangle::isSwiftSymbol(const char *mangledName) {
   // The old mangling.
   if (mangledName[0] == '_' && mangledName[1] == 'T')
     return true;
@@ -137,6 +134,9 @@
   return getManglingPrefixLength(mangledName) != 0;
 }
 
+namespace swift {
+namespace Demangle {
+
 //////////////////////////////////
 // Node member functions        //
 //////////////////////////////////
diff --git a/lib/Frontend/CompilerInvocation.cpp b/lib/Frontend/CompilerInvocation.cpp
index cf98610..1f60276 100644
--- a/lib/Frontend/CompilerInvocation.cpp
+++ b/lib/Frontend/CompilerInvocation.cpp
@@ -964,6 +964,9 @@
   Opts.DisableTsanInoutInstrumentation |=
       Args.hasArg(OPT_disable_tsan_inout_instrumentation);
 
+  Opts.ReportErrorsToDebugger |=
+      Args.hasArg(OPT_report_errors_to_debugger);
+
   if (FrontendOpts.InputKind == InputFileKind::IFK_SIL)
     Opts.DisableAvailabilityChecking = true;
   
diff --git a/lib/IRGen/IRGenModule.cpp b/lib/IRGen/IRGenModule.cpp
index 5651135..b936bf1 100644
--- a/lib/IRGen/IRGenModule.cpp
+++ b/lib/IRGen/IRGenModule.cpp
@@ -44,6 +44,7 @@
 #include "llvm/ADT/PointerUnion.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/MD5.h"
+#include "llvm/Transforms/Utils/ModuleUtils.h"
 
 #include "GenEnum.h"
 #include "GenType.h"
@@ -1042,6 +1043,31 @@
   }
 }
 
+void IRGenModule::emitEnableReportErrorsToDebugger() {
+  if (!Context.LangOpts.ReportErrorsToDebugger)
+    return;
+
+  if (!getSwiftModule()->hasEntryPoint())
+    return;
+
+  llvm::Function *NewFn = llvm::Function::Create(
+      llvm::FunctionType::get(VoidTy, false), llvm::GlobalValue::PrivateLinkage,
+      "_swift_enable_report_errors_to_debugger");
+  IRGenFunction NewIGF(*this, NewFn);
+  NewFn->setAttributes(constructInitialAttributes());
+  Module.getFunctionList().push_back(NewFn);
+  NewFn->setCallingConv(DefaultCC);
+
+  llvm::Value *addr =
+      Module.getOrInsertGlobal("_swift_reportFatalErrorsToDebugger", Int1Ty);
+  llvm::Value *one = llvm::ConstantInt::get(Int1Ty, 1);
+
+  NewIGF.Builder.CreateStore(one, addr, Alignment(1));
+  NewIGF.Builder.CreateRetVoid();
+
+  llvm::appendToGlobalCtors(Module, NewFn, 0, nullptr);
+}
+
 void IRGenModule::cleanupClangCodeGenMetadata() {
   // Remove llvm.ident that ClangCodeGen might have left in the module.
   auto *LLVMIdent = Module.getNamedMetadata("llvm.ident");
@@ -1110,6 +1136,7 @@
     return false;
 
   emitAutolinkInfo();
+  emitEnableReportErrorsToDebugger();
   emitGlobalLists();
   if (DebugInfo)
     DebugInfo->finalize();
diff --git a/lib/IRGen/IRGenModule.h b/lib/IRGen/IRGenModule.h
index 38f8d44..d0c7f53 100644
--- a/lib/IRGen/IRGenModule.h
+++ b/lib/IRGen/IRGenModule.h
@@ -795,6 +795,7 @@
 
   void emitGlobalLists();
   void emitAutolinkInfo();
+  void emitEnableReportErrorsToDebugger();
   void cleanupClangCodeGenMetadata();
 
 //--- Remote reflection metadata --------------------------------------------
diff --git a/lib/Parse/ParseStmt.cpp b/lib/Parse/ParseStmt.cpp
index 5c3bd0b..fdf630c 100644
--- a/lib/Parse/ParseStmt.cpp
+++ b/lib/Parse/ParseStmt.cpp
@@ -1511,9 +1511,14 @@
 
   // Parse the 'else'.  If it is missing, and if the following token isn't a {
   // then the parser is hopelessly lost - just give up instead of spewing.
-  if (parseToken(tok::kw_else, diag::expected_else_after_guard) &&
-      Tok.isNot(tok::l_brace))
-    return recoverWithCond(Status, Condition);
+  if (!consumeIf(tok::kw_else)) {
+    checkForInputIncomplete();
+    auto diag = diagnose(Tok, diag::expected_else_after_guard);
+    if (Tok.is(tok::l_brace))
+      diag.fixItInsert(Tok.getLoc(), "else ");
+    else
+      return recoverWithCond(Status, Condition);
+  }
 
   // Before parsing the body, disable all of the bound variables so that they
   // cannot be used unbound.
diff --git a/lib/SILGen/SILGenDecl.cpp b/lib/SILGen/SILGenDecl.cpp
index 7fa87c1..2918f5e 100644
--- a/lib/SILGen/SILGenDecl.cpp
+++ b/lib/SILGen/SILGenDecl.cpp
@@ -666,7 +666,7 @@
   void bindVariable(SILLocation loc, VarDecl *var, ManagedValue value,
                     CanType formalValueType, SILGenFunction &SGF) {
     // Initialize the variable value.
-    InitializationPtr init = SGF.emitInitializationForVarDecl(var);
+    InitializationPtr init = SGF.emitInitializationForVarDecl(var, var->isLet());
     RValue(SGF, loc, formalValueType, value).forwardInto(SGF, loc, init.get());
   }
 
@@ -1008,7 +1008,7 @@
       return InitializationPtr(new BlackHoleInitialization());
     }
 
-    return SGF.emitInitializationForVarDecl(P->getDecl());
+    return SGF.emitInitializationForVarDecl(P->getDecl(), P->getDecl()->isLet());
   }
 
   // Bind a tuple pattern by aggregating the component variables into a
@@ -1053,7 +1053,8 @@
 
 } // end anonymous namespace
 
-InitializationPtr SILGenFunction::emitInitializationForVarDecl(VarDecl *vd) {
+InitializationPtr
+SILGenFunction::emitInitializationForVarDecl(VarDecl *vd, bool forceImmutable) {
   // If this is a computed variable, we don't need to do anything here.
   // We'll generate the getter and setter when we see their FuncDecls.
   if (!vd->hasStorage())
@@ -1076,7 +1077,7 @@
 
   // If this is a 'let' initialization for a non-global, set up a
   // let binding, which stores the initialization value into VarLocs directly.
-  if (vd->isLet() && vd->getDeclContext()->isLocalContext() &&
+  if (forceImmutable && vd->getDeclContext()->isLocalContext() &&
       !isa<ReferenceStorageType>(varType))
     return InitializationPtr(new LetValueInitialization(vd, *this));
 
diff --git a/lib/SILGen/SILGenFunction.h b/lib/SILGen/SILGenFunction.h
index ef39b34..8b8a6c0 100644
--- a/lib/SILGen/SILGenFunction.h
+++ b/lib/SILGen/SILGenFunction.h
@@ -1678,7 +1678,8 @@
   void visitVarDecl(VarDecl *D);
 
   /// Emit an Initialization for a 'var' or 'let' decl in a pattern.
-  std::unique_ptr<Initialization> emitInitializationForVarDecl(VarDecl *vd);
+  std::unique_ptr<Initialization> emitInitializationForVarDecl(VarDecl *vd,
+                                                               bool immutable);
   
   /// Emit the allocation for a local variable, provides an Initialization
   /// that can be used to initialize it, and registers cleanups in the active
diff --git a/lib/SILGen/SILGenPattern.cpp b/lib/SILGen/SILGenPattern.cpp
index c0afb40..5002239 100644
--- a/lib/SILGen/SILGenPattern.cpp
+++ b/lib/SILGen/SILGenPattern.cpp
@@ -1206,12 +1206,12 @@
   // If this binding is one of multiple patterns, each individual binding
   // will just be let, and then the chosen value will get forwarded into
   // a var box in the final shared case block.
-  bool forcedLet = hasMultipleItems && !var->isLet();
-  if (forcedLet)
-    var->setLet(true);
+  bool forcedLet = var->isLet();
+  if (hasMultipleItems && !var->isLet())
+    forcedLet = true;
   
   // Initialize the variable value.
-  InitializationPtr init = SGF.emitInitializationForVarDecl(var);
+  InitializationPtr init = SGF.emitInitializationForVarDecl(var, forcedLet);
 
   RValue rv(SGF, loc, formalValueType, value.getFinalManagedValue());
   if (shouldTake(value, isIrrefutable)) {
@@ -1219,9 +1219,6 @@
   } else {
     std::move(rv).copyInto(SGF, loc, init.get());
   }
-  
-  if (forcedLet)
-    var->setLet(false);
 }
 
 /// Evaluate a guard expression and, if it returns false, branch to
@@ -2374,12 +2371,13 @@
         if (V->isLet()) {
           // Just emit a let with cleanup.
           SGF.VarLocs[V].value = caseBB->getArgument(argIndex++);
-          SGF.emitInitializationForVarDecl(V)->finishInitialization(SGF);
+          SGF.emitInitializationForVarDecl(V, V->isLet())
+            ->finishInitialization(SGF);
         } else {
           // The pattern variables were all emitted as lets and one got passed in,
           // now we finally alloc a box for the var and forward in the chosen value.
           SGF.VarLocs.erase(V);
-          auto newVar = SGF.emitInitializationForVarDecl(V);
+          auto newVar = SGF.emitInitializationForVarDecl(V, V->isLet());
           auto loc = SGF.CurrentSILLoc;
           auto value =
               ManagedValue::forUnmanaged(caseBB->getArgument(argIndex++));
diff --git a/lib/Sema/CSDiag.cpp b/lib/Sema/CSDiag.cpp
index 3687956..6fa592f 100644
--- a/lib/Sema/CSDiag.cpp
+++ b/lib/Sema/CSDiag.cpp
@@ -4699,16 +4699,39 @@
                                    base);
 
     calleeInfo.filterList(argType, argLabels);
-    if (calleeInfo.closeness != CC_ExactMatch)
+
+    auto diagnostic = diag::member_shadows_global_function_near_match;
+    switch (calleeInfo.closeness) {
+    case CC_Unavailable:
+    case CC_Inaccessible:
+    case CC_SelfMismatch:
+    case CC_ArgumentLabelMismatch:
+    case CC_ArgumentCountMismatch:
+    case CC_GeneralMismatch:
       return false;
 
+    case CC_NonLValueInOut:
+    case CC_OneArgumentNearMismatch:
+    case CC_OneArgumentMismatch:
+    case CC_OneGenericArgumentNearMismatch:
+    case CC_OneGenericArgumentMismatch:
+    case CC_ArgumentNearMismatch:
+    case CC_ArgumentMismatch:
+    case CC_GenericNonsubstitutableMismatch:
+      break; // Near match cases
+
+    case CC_ExactMatch:
+      diagnostic = diag::member_shadows_global_function;
+      break;
+    }
+
     auto choice = calleeInfo.candidates[0].getDecl();
     auto baseKind = getBaseKind(base);
     auto baseName = getBaseName(choice->getDeclContext());
 
     auto origCandidate = CCI[0].getDecl();
-    TC.diagnose(UDE->getLoc(), diag::member_shadows_global_function,
-                UDE->getName(), origCandidate->getDescriptiveKind(),
+    TC.diagnose(UDE->getLoc(), diagnostic, UDE->getName(),
+                origCandidate->getDescriptiveKind(),
                 origCandidate->getFullName(), choice->getDescriptiveKind(),
                 choice->getFullName(), baseKind, baseName);
 
diff --git a/lib/Sema/TypeCheckDecl.cpp b/lib/Sema/TypeCheckDecl.cpp
index da653da..16634bb 100644
--- a/lib/Sema/TypeCheckDecl.cpp
+++ b/lib/Sema/TypeCheckDecl.cpp
@@ -7302,9 +7302,6 @@
 
     validateAttributes(*this, D);
 
-    if (!proto->isRequirementSignatureComputed())
-      proto->computeRequirementSignature();
-
     // If the protocol is @objc, it may only refine other @objc protocols.
     // FIXME: Revisit this restriction.
     if (proto->getAttrs().hasAttribute<ObjCAttr>()) {
diff --git a/lib/Sema/TypeCheckGeneric.cpp b/lib/Sema/TypeCheckGeneric.cpp
index 193bb41..14d3a99 100644
--- a/lib/Sema/TypeCheckGeneric.cpp
+++ b/lib/Sema/TypeCheckGeneric.cpp
@@ -1162,6 +1162,13 @@
 
   prepareGenericParamList(gp, typeDecl);
 
+  // For a protocol, compute the requirement signature first. It will be used
+  // by clients of the protocol.
+  if (auto proto = dyn_cast<ProtocolDecl>(typeDecl)) {
+    if (!proto->isRequirementSignatureComputed())
+      proto->computeRequirementSignature();
+  }
+
   auto *env = checkGenericEnvironment(gp, dc, dc->getGenericSignatureOfContext(),
                                       /*allowConcreteGenericParams=*/false);
   typeDecl->setGenericEnvironment(env);
diff --git a/lib/Sema/TypeCheckPattern.cpp b/lib/Sema/TypeCheckPattern.cpp
index 54feb77..e3bfc9c 100644
--- a/lib/Sema/TypeCheckPattern.cpp
+++ b/lib/Sema/TypeCheckPattern.cpp
@@ -1402,8 +1402,17 @@
             goto recur;
           }
 
-          diagnose(EEP->getLoc(), diag::enum_element_pattern_member_not_found,
-                   EEP->getName().str(), type);
+          auto diag = diagnose(EEP->getLoc(),
+                               diag::enum_element_pattern_member_not_found,
+                               EEP->getName().str(), type);
+
+          // If we have an optional type let's try to see if the case
+          // exists in its base type, if so we can suggest a fix-it for that.
+          if (auto baseType = type->getOptionalObjectType()) {
+            if (lookupEnumMemberElement(*this, dc, baseType, EEP->getName(),
+                                        EEP->getLoc()))
+              diag.fixItInsertAfter(EEP->getEndLoc(), "?");
+          }
         }
         return true;
       }
diff --git a/stdlib/private/StdlibUnittest/RaceTest.swift b/stdlib/private/StdlibUnittest/RaceTest.swift
index e88288d..08d1938 100644
--- a/stdlib/private/StdlibUnittest/RaceTest.swift
+++ b/stdlib/private/StdlibUnittest/RaceTest.swift
@@ -41,7 +41,7 @@
 import SwiftPrivatePthreadExtras
 #if os(OSX) || os(iOS)
 import Darwin
-#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || CYGWIN
+#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin)
 import Glibc
 #endif
 
diff --git a/stdlib/private/StdlibUnittest/StdlibCoreExtras.swift b/stdlib/private/StdlibUnittest/StdlibCoreExtras.swift
index 7307e81..960d1ff 100644
--- a/stdlib/private/StdlibUnittest/StdlibCoreExtras.swift
+++ b/stdlib/private/StdlibUnittest/StdlibCoreExtras.swift
@@ -14,7 +14,7 @@
 import SwiftPrivateLibcExtras
 #if os(OSX) || os(iOS)
 import Darwin
-#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || CYGWIN
+#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin)
 import Glibc
 #endif
 
diff --git a/stdlib/private/StdlibUnittest/StdlibUnittest.swift.gyb b/stdlib/private/StdlibUnittest/StdlibUnittest.swift.gyb
index d8e130c..5f7d274 100644
--- a/stdlib/private/StdlibUnittest/StdlibUnittest.swift.gyb
+++ b/stdlib/private/StdlibUnittest/StdlibUnittest.swift.gyb
@@ -20,7 +20,7 @@
 
 #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
 import Darwin
-#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || CYGWIN
+#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin)
 import Glibc
 #endif
 
@@ -1497,7 +1497,7 @@
   return .ps4
 #elseif os(Android)
   return .android
-#elseif os(Windows) && CYGWIN
+#elseif os(Cygwin)
   return .windowsCygnus
 #elseif os(Windows)
   return .windows
diff --git a/stdlib/private/SwiftPrivateLibcExtras/Subprocess.swift b/stdlib/private/SwiftPrivateLibcExtras/Subprocess.swift
index 618e24b..e4350d9 100644
--- a/stdlib/private/SwiftPrivateLibcExtras/Subprocess.swift
+++ b/stdlib/private/SwiftPrivateLibcExtras/Subprocess.swift
@@ -13,13 +13,14 @@
 import SwiftPrivate
 #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
 import Darwin
-#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || CYGWIN
+#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin)
 import Glibc
 #endif
 
 
-#if !os(Windows) || CYGWIN
-// posix_spawn is not available on Android or Windows.
+#if !os(Windows)
+// posix_spawn is not available on Windows.
+// posix_spawn is not available on Android.
 #if !os(Android)
 // swift_posix_spawn isn't available in the public watchOS SDK, we sneak by the
 // unavailable attribute declaration here of the APIs that we need.
@@ -264,7 +265,7 @@
 
 public func posixWaitpid(_ pid: pid_t) -> ProcessTerminationStatus {
   var status: CInt = 0
-#if CYGWIN
+#if os(Cygwin)
   withUnsafeMutablePointer(to: &status) {
     statusPtr in
     let statusPtrWrapper = __wait_status_ptr_t(__int_ptr: statusPtr)
@@ -304,7 +305,7 @@
   return environ
 #elseif os(Android)
   return environ
-#elseif CYGWIN
+#elseif os(Cygwin)
   return environ
 #else
   return __environ
diff --git a/stdlib/private/SwiftPrivateLibcExtras/SwiftPrivateLibcExtras.swift b/stdlib/private/SwiftPrivateLibcExtras/SwiftPrivateLibcExtras.swift
index 2850883..8d4412f 100644
--- a/stdlib/private/SwiftPrivateLibcExtras/SwiftPrivateLibcExtras.swift
+++ b/stdlib/private/SwiftPrivateLibcExtras/SwiftPrivateLibcExtras.swift
@@ -13,13 +13,13 @@
 import SwiftPrivate
 #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
 import Darwin
-#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || CYGWIN
+#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin)
 import Glibc
 #elseif os(Windows)
 import ucrt
 #endif
 
-#if !os(Windows) || CYGWIN
+#if !os(Windows)
 public func _stdlib_mkstemps(_ template: inout String, _ suffixlen: CInt) -> CInt {
 #if os(Android)
   preconditionFailure("mkstemps doesn't work on Android")
@@ -85,7 +85,7 @@
   }
 }
 
-#if !os(Windows) || CYGWIN
+#if !os(Windows)
 public func _stdlib_select(
   _ readfds: inout _stdlib_fd_set, _ writefds: inout _stdlib_fd_set,
   _ errorfds: inout _stdlib_fd_set, _ timeout: UnsafeMutablePointer<timeval>?
@@ -99,7 +99,7 @@
         let readAddr = readfds.baseAddress
         let writeAddr = writefds.baseAddress
         let errorAddr = errorfds.baseAddress
-#if CYGWIN
+#if os(Cygwin)
         typealias fd_set = _types_fd_set
 #endif
         func asFdSetPtr(
@@ -125,10 +125,10 @@
 public func _stdlib_pipe() -> (readEnd: CInt, writeEnd: CInt, error: CInt) {
   var fds: [CInt] = [0, 0]
   let ret = fds.withUnsafeMutableBufferPointer { unsafeFds -> CInt in
-#if !os(Windows) || CYGWIN
-    return pipe(unsafeFds.baseAddress)
-#else
+#if os(Windows)
     return _pipe(unsafeFds.baseAddress, 0, 0)
+#else
+    return pipe(unsafeFds.baseAddress)
 #endif
   }
   return (readEnd: fds[0], writeEnd: fds[1], error: ret)
diff --git a/stdlib/private/SwiftPrivatePthreadExtras/PthreadBarriers.swift b/stdlib/private/SwiftPrivatePthreadExtras/PthreadBarriers.swift
index 2ebe4b3..df922f9 100644
--- a/stdlib/private/SwiftPrivatePthreadExtras/PthreadBarriers.swift
+++ b/stdlib/private/SwiftPrivatePthreadExtras/PthreadBarriers.swift
@@ -12,7 +12,7 @@
 
 #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
 import Darwin
-#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || CYGWIN
+#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin)
 import Glibc
 #endif
 
@@ -43,7 +43,7 @@
 }
 
 public struct _stdlib_pthread_barrier_t {
-#if CYGWIN || os(FreeBSD)
+#if os(Cygwin) || os(FreeBSD)
   var mutex: UnsafeMutablePointer<pthread_mutex_t?>?
   var cond: UnsafeMutablePointer<pthread_cond_t?>?
 #else
diff --git a/stdlib/private/SwiftPrivatePthreadExtras/SwiftPrivatePthreadExtras.swift b/stdlib/private/SwiftPrivatePthreadExtras/SwiftPrivatePthreadExtras.swift
index fe0c4f0..26809a0 100644
--- a/stdlib/private/SwiftPrivatePthreadExtras/SwiftPrivatePthreadExtras.swift
+++ b/stdlib/private/SwiftPrivatePthreadExtras/SwiftPrivatePthreadExtras.swift
@@ -17,7 +17,7 @@
 
 #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
 import Darwin
-#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || CYGWIN
+#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin)
 import Glibc
 #endif
 
@@ -59,7 +59,7 @@
   return context.run()
 }
 
-#if CYGWIN || os(FreeBSD)
+#if os(Cygwin) || os(FreeBSD)
 public typealias _stdlib_pthread_attr_t = UnsafePointer<pthread_attr_t?>
 #else
 public typealias _stdlib_pthread_attr_t = UnsafePointer<pthread_attr_t>
diff --git a/stdlib/public/Platform/Platform.swift b/stdlib/public/Platform/Platform.swift
index 1512aa0..fd7c660 100644
--- a/stdlib/public/Platform/Platform.swift
+++ b/stdlib/public/Platform/Platform.swift
@@ -141,23 +141,23 @@
 // fcntl.h
 //===----------------------------------------------------------------------===//
 
-#if !os(Windows) || CYGWIN
-@_silgen_name("_swift_Platform_open")
-func _swift_Platform_open(
-  _ path: UnsafePointer<CChar>,
-  _ oflag: Int32,
-  _ mode: mode_t
-) -> Int32
-#else
+#if os(Windows)
 @_silgen_name("_swift_Platform_open")
 func _swift_Platform_open(
   _ path: UnsafePointer<CChar>,
   _ oflag: Int32,
   _ mode: Int32
 ) -> Int32
+#else
+@_silgen_name("_swift_Platform_open")
+func _swift_Platform_open(
+  _ path: UnsafePointer<CChar>,
+  _ oflag: Int32,
+  _ mode: mode_t
+) -> Int32
 #endif
 
-#if !os(Windows) || CYGWIN
+#if !os(Windows)
 @_silgen_name("_swift_Platform_openat")
 func _swift_Platform_openat(
   _ fd: Int32,
@@ -174,7 +174,15 @@
   return _swift_Platform_open(path, oflag, 0)
 }
 
-#if !os(Windows) || CYGWIN
+#if os(Windows)
+public func open(
+  _ path: UnsafePointer<CChar>,
+  _ oflag: Int32,
+  _ mode: Int32
+) -> Int32 {
+  return _swift_Platform_open(path, oflag, mode)
+}
+#else
 public func open(
   _ path: UnsafePointer<CChar>,
   _ oflag: Int32,
@@ -199,17 +207,9 @@
 ) -> Int32 {
   return _swift_Platform_openat(fd, path, oflag, mode)
 }
-#else
-public func open(
-  _ path: UnsafePointer<CChar>,
-  _ oflag: Int32,
-  _ mode: Int32
-) -> Int32 {
-  return _swift_Platform_open(path, oflag, mode)
-}
 #endif
 
-#if !os(Windows) || CYGWIN
+#if !os(Windows)
 @_silgen_name("_swift_Platform_fcntl")
 internal func _swift_Platform_fcntl(
   _ fd: Int32,
@@ -248,7 +248,18 @@
 }
 #endif
 
-#if !os(Windows) || CYGWIN
+#if os(Windows)
+public var S_IFMT: Int32 { return Int32(0xf000) }
+
+public var S_IFREG: Int32 { return Int32(0x8000) }
+public var S_IFDIR: Int32 { return Int32(0x4000) }
+public var S_IFCHR: Int32 { return Int32(0x2000) }
+public var S_IFIFO: Int32 { return Int32(0x1000) }
+
+public var S_IREAD: Int32  { return Int32(0x0100) }
+public var S_IWRITE: Int32 { return Int32(0x0080) }
+public var S_IEXEC: Int32  { return Int32(0x0040) }
+#else
 public var S_IFMT: mode_t   { return mode_t(0o170000) }
 public var S_IFIFO: mode_t  { return mode_t(0o010000) }
 public var S_IFCHR: mode_t  { return mode_t(0o020000) }
@@ -286,24 +297,13 @@
 public var S_IWRITE: mode_t { return S_IWUSR }
 public var S_IEXEC: mode_t  { return S_IXUSR }
 #endif
-#else
-public var S_IFMT: Int32 { return Int32(0xf000) }
-
-public var S_IFREG: Int32 { return Int32(0x8000) }
-public var S_IFDIR: Int32 { return Int32(0x4000) }
-public var S_IFCHR: Int32 { return Int32(0x2000) }
-public var S_IFIFO: Int32 { return Int32(0x1000) }
-
-public var S_IREAD: Int32  { return Int32(0x0100) }
-public var S_IWRITE: Int32 { return Int32(0x0080) }
-public var S_IEXEC: Int32  { return Int32(0x0040) }
 #endif
 
 //===----------------------------------------------------------------------===//
 // ioctl.h
 //===----------------------------------------------------------------------===//
 
-#if !os(Windows) || CYGWIN
+#if !os(Windows)
 @_silgen_name("_swift_Platform_ioctl")
 internal func _swift_Platform_ioctl(
   _ fd: CInt,
@@ -380,8 +380,7 @@
 public var SIG_HOLD: sighandler_t {
   return unsafeBitCast(2, to: sighandler_t.self)
 }
-#elseif os(Windows)
-#if CYGWIN
+#elseif os(Cygwin)
 public typealias sighandler_t = _sig_func_ptr
 
 public var SIG_DFL: sighandler_t? { return nil }
@@ -394,7 +393,7 @@
 public var SIG_HOLD: sighandler_t {
   return unsafeBitCast(2, to: sighandler_t.self)
 }
-#else
+#elseif os(Windows)
 public var SIG_DFL: _crt_signal_t? { return nil }
 public var SIG_IGN: _crt_signal_t {
   return unsafeBitCast(1, to: _crt_signal_t.self)
@@ -402,7 +401,6 @@
 public var SIG_ERR: _crt_signal_t {
   return unsafeBitCast(-1, to: _crt_signal_t.self)
 }
-#endif
 #else
 internal var _ignore = _UnsupportedPlatformError()
 #endif
@@ -411,13 +409,13 @@
 // semaphore.h
 //===----------------------------------------------------------------------===//
 
-#if !os(Windows) || CYGWIN
+#if !os(Windows) 
 /// The value returned by `sem_open()` in the case of failure.
 public var SEM_FAILED: UnsafeMutablePointer<sem_t>? {
 #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
   // The value is ABI.  Value verified to be correct for OS X, iOS, watchOS, tvOS.
   return UnsafeMutablePointer<sem_t>(bitPattern: -1)
-#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || CYGWIN
+#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin)
   // The value is ABI.  Value verified to be correct on Glibc.
   return UnsafeMutablePointer<sem_t>(bitPattern: 0)
 #else
diff --git a/stdlib/public/Platform/tgmath.swift.gyb b/stdlib/public/Platform/tgmath.swift.gyb
index 6f44204..34bd544 100644
--- a/stdlib/public/Platform/tgmath.swift.gyb
+++ b/stdlib/public/Platform/tgmath.swift.gyb
@@ -216,13 +216,13 @@
 %if T == 'Double':
 #if os(Linux)
   return Int(__fpclassify(CDouble(value)))
-#elseif os(Windows) && !CYGWIN
+#elseif os(Windows) 
   return Int(_dclass(CDouble(value)))
 #else
   return Int(__fpclassifyd(CDouble(value)))
 #endif
 %else:
-#if os(Windows) && !CYGWIN
+#if os(Windows) 
   return Int(_${f}dclass(${CT}(value)))
 #else
   return Int(__fpclassify${f}(${CT}(value)))
@@ -298,7 +298,7 @@
 
 % # This is AllFloatTypes not OverlayFloatTypes because of the tuple return.
 % for T, CT, f in AllFloatTypes():
-#if os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || CYGWIN
+#if os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin)
 @_transparent
 public func lgamma(_ x: ${T}) -> (${T}, Int) {
   var sign = Int32(0)
@@ -306,16 +306,7 @@
   return (${T}(value), Int(sign))
 }
 #elseif os(Windows)
-#if CYGWIN
-@_transparent
-public func lgamma(_ x: ${T}) -> (${T}, Int) {
-  var sign = Int32(0)
-  let value = lgamma${f}_r(${CT}(x), &sign)
-  return (${T}(value), Int(sign))
-}
-#else
 // TODO(compnerd): implement
-#endif
 #else
 % # On Darwin platform,
 % # The real lgamma_r is not imported because it hides behind macro _REENTRANT.
@@ -360,11 +351,7 @@
 @_transparent
 public func jn(_ n: Int, _ x: Double) -> Double {
 #if os(Windows)
-#if CYGWIN
-  return jn(Int32(n), x)
-#else
   return _jn(Int32(n), x)
-#endif
 #else
   return jn(Int32(n), x)
 #endif
@@ -373,11 +360,7 @@
 @_transparent
 public func yn(_ n: Int, _ x: Double) -> Double {
 #if os(Windows)
-#if CYGWIN
-  return yn(Int32(n), x)
-#else
   return _yn(Int32(n), x)
-#endif
 #else
   return yn(Int32(n), x)
 #endif
diff --git a/stdlib/public/SDK/Foundation/JSONEncoder.swift b/stdlib/public/SDK/Foundation/JSONEncoder.swift
index 49d2ec4..c6367be 100644
--- a/stdlib/public/SDK/Foundation/JSONEncoder.swift
+++ b/stdlib/public/SDK/Foundation/JSONEncoder.swift
@@ -62,8 +62,11 @@
 
     /// The strategy to use for encoding `Data` values.
     public enum DataEncodingStrategy {
+        /// Defer to `Data` for choosing an encoding.
+        case deferredToData
+
         /// Encoded the `Data` as a Base64-encoded string. This is the default strategy.
-        case base64Encode
+        case base64
 
         /// Encode the `Data` as a custom value encoded by the given closure.
         ///
@@ -86,8 +89,8 @@
     /// The strategy to use in encoding dates. Defaults to `.deferredToDate`.
     open var dateEncodingStrategy: DateEncodingStrategy = .deferredToDate
 
-    /// The strategy to use in encoding binary data. Defaults to `.base64Encode`.
-    open var dataEncodingStrategy: DataEncodingStrategy = .base64Encode
+    /// The strategy to use in encoding binary data. Defaults to `.base64`.
+    open var dataEncodingStrategy: DataEncodingStrategy = .base64
 
     /// The strategy to use in encoding non-conforming numbers. Defaults to `.throw`.
     open var nonConformingFloatEncodingStrategy: NonConformingFloatEncodingStrategy = .throw
@@ -665,7 +668,12 @@
 
     fileprivate func box(_ data: Data) throws -> NSObject {
         switch self.options.dataEncodingStrategy {
-        case .base64Encode:
+        case .deferredToData:
+            // Must be called with a surrounding with(pushedKey:) call.
+            try data.encode(to: self)
+            return self.storage.popContainer()
+
+        case .base64:
             return NSString(string: data.base64EncodedString())
 
         case .custom(let closure):
@@ -817,8 +825,11 @@
 
     /// The strategy to use for decoding `Data` values.
     public enum DataDecodingStrategy {
+        /// Defer to `Data` for decoding.
+        case deferredToData
+
         /// Decode the `Data` from a Base64-encoded string. This is the default strategy.
-        case base64Decode
+        case base64
 
         /// Decode the `Data` as a custom value decoded by the given closure.
         case custom((_ decoder: Decoder) throws -> Data)
@@ -836,8 +847,8 @@
     /// The strategy to use in decoding dates. Defaults to `.deferredToDate`.
     open var dateDecodingStrategy: DateDecodingStrategy = .deferredToDate
 
-    /// The strategy to use in decoding binary data. Defaults to `.base64Decode`.
-    open var dataDecodingStrategy: DataDecodingStrategy = .base64Decode
+    /// The strategy to use in decoding binary data. Defaults to `.base64`.
+    open var dataDecodingStrategy: DataDecodingStrategy = .base64
 
     /// The strategy to use in decoding non-conforming numbers. Defaults to `.throw`.
     open var nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy = .throw
@@ -1942,7 +1953,13 @@
         guard !(value is NSNull) else { return nil }
 
         switch self.options.dataDecodingStrategy {
-        case .base64Decode:
+        case .deferredToData:
+            self.storage.push(container: value)
+            let data = try Data(from: self)
+            self.storage.popContainer()
+            return data
+
+        case .base64:
             guard let string = value as? String else {
                 throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
             }
diff --git a/stdlib/public/core/CTypes.swift b/stdlib/public/core/CTypes.swift
index 1f59945..923580a 100644
--- a/stdlib/public/core/CTypes.swift
+++ b/stdlib/public/core/CTypes.swift
@@ -43,14 +43,14 @@
 public typealias CInt = Int32
 
 /// The C 'long' type.
-#if os(Windows) && !CYGWIN && arch(x86_64)
+#if os(Windows) && arch(x86_64)
 public typealias CLong = Int32
 #else
 public typealias CLong = Int
 #endif
 
 /// The C 'long long' type.
-#if os(Windows) && !CYGWIN && arch(x86_64)
+#if os(Windows) && arch(x86_64)
 public typealias CLongLong = Int
 #else
 public typealias CLongLong = Int64
diff --git a/stdlib/public/core/FloatingPoint.swift.gyb b/stdlib/public/core/FloatingPoint.swift.gyb
index e34a1c1..620c897 100644
--- a/stdlib/public/core/FloatingPoint.swift.gyb
+++ b/stdlib/public/core/FloatingPoint.swift.gyb
@@ -1465,7 +1465,7 @@
   /// - Parameter value: A floating-point value.
   init(_ value: Double)
 
-#if (!os(Windows) || CYGWIN) && (arch(i386) || arch(x86_64))
+#if !os(Windows) && (arch(i386) || arch(x86_64))
   /// Creates a new instance from the given value, rounded to the closest
   /// possible representation.
   ///
diff --git a/stdlib/public/core/FloatingPointParsing.swift.gyb b/stdlib/public/core/FloatingPointParsing.swift.gyb
index 1fe02dd..b647108 100644
--- a/stdlib/public/core/FloatingPointParsing.swift.gyb
+++ b/stdlib/public/core/FloatingPointParsing.swift.gyb
@@ -38,7 +38,7 @@
 %   Self = floatName(bits)
 
 % if bits == 80:
-#if (!os(Windows) || CYGWIN) && (arch(i386) || arch(x86_64))
+#if !os(Windows) && (arch(i386) || arch(x86_64))
 % end
 
 //===--- Parsing ----------------------------------------------------------===//
diff --git a/stdlib/public/core/FloatingPointTypes.swift.gyb b/stdlib/public/core/FloatingPointTypes.swift.gyb
index d3fa0c6..5b4548b 100644
--- a/stdlib/public/core/FloatingPointTypes.swift.gyb
+++ b/stdlib/public/core/FloatingPointTypes.swift.gyb
@@ -64,7 +64,7 @@
 }%
 
 % if bits == 80:
-#if (!os(Windows) || CYGWIN) && (arch(i386) || arch(x86_64))
+#if !os(Windows) && (arch(i386) || arch(x86_64))
 % end
 
 ${SelfDocComment}
@@ -702,7 +702,7 @@
   }
 }
 
-#if (!os(Windows) || CYGWIN) && (arch(i386) || arch(x86_64))
+#if !os(Windows) && (arch(i386) || arch(x86_64))
 
 % builtinFloatLiteralBits = 80
 extension ${Self} : _ExpressibleByBuiltinFloatLiteral {
@@ -847,7 +847,7 @@
 %   That = src_type.stdlib_name
 
 %   if srcBits == 80:
-#if (!os(Windows) || CYGWIN) && (arch(i386) || arch(x86_64))
+#if !os(Windows) && (arch(i386) || arch(x86_64))
 %   end
 
 %   if srcBits == bits:
diff --git a/stdlib/public/core/Policy.swift b/stdlib/public/core/Policy.swift
index 306d3fc..8172198 100644
--- a/stdlib/public/core/Policy.swift
+++ b/stdlib/public/core/Policy.swift
@@ -104,7 +104,7 @@
 // IEEE Binary64, and we need 1 bit to represent the sign.  Instead of using
 // 1025, we use the next round number -- 2048.
 public typealias _MaxBuiltinIntegerType = Builtin.Int2048
-#if (!os(Windows) || CYGWIN) && (arch(i386) || arch(x86_64))
+#if !os(Windows) && (arch(i386) || arch(x86_64))
 public typealias _MaxBuiltinFloatType = Builtin.FPIEEE80
 #else
 public typealias _MaxBuiltinFloatType = Builtin.FPIEEE64
diff --git a/stdlib/public/core/Runtime.swift.gyb b/stdlib/public/core/Runtime.swift.gyb
index 4a097fd..c1abf23 100644
--- a/stdlib/public/core/Runtime.swift.gyb
+++ b/stdlib/public/core/Runtime.swift.gyb
@@ -340,7 +340,7 @@
 % for bits in [ 32, 64, 80 ]:
 
 % if bits == 80:
-#if (!os(Windows) || CYGWIN) && (arch(i386) || arch(x86_64))
+#if !os(Windows) && (arch(i386) || arch(x86_64))
 % end
 
 @_silgen_name("swift_float${bits}ToString")
diff --git a/stdlib/public/stubs/Assert.cpp b/stdlib/public/stubs/Assert.cpp
index 69fa5ca..39c9b74 100644
--- a/stdlib/public/stubs/Assert.cpp
+++ b/stdlib/public/stubs/Assert.cpp
@@ -21,6 +21,8 @@
 
 using namespace swift;
 
+bool swift::_swift_reportFatalErrorsToDebugger = false;
+
 static int swift_asprintf(char **strp, const char *fmt, ...) {
   va_list args;
   va_start(args, fmt);
@@ -49,6 +51,24 @@
   return result;
 }
 
+static void logPrefixAndMessageToDebugger(
+    const unsigned char *prefix, int prefixLength,
+    const unsigned char *message, int messageLength
+) {
+  if (!_swift_reportFatalErrorsToDebugger)
+    return;
+
+  char *debuggerMessage;
+  if (messageLength) {
+    swift_asprintf(&debuggerMessage, "%.*s: %.*s", prefixLength, prefix,
+        messageLength, message);
+  } else {
+    swift_asprintf(&debuggerMessage, "%.*s", prefixLength, prefix);
+  }
+  reportToDebugger(RuntimeErrorFlagFatal, debuggerMessage);
+  free(debuggerMessage);
+}
+
 void swift::_swift_stdlib_reportFatalErrorInFile(
     const unsigned char *prefix, int prefixLength,
     const unsigned char *message, int messageLength,
@@ -56,6 +76,8 @@
     uint32_t line,
     uint32_t flags
 ) {
+  logPrefixAndMessageToDebugger(prefix, prefixLength, message, messageLength);
+
   char *log;
   swift_asprintf(
       &log, "%.*s: %.*s%sfile %.*s, line %" PRIu32 "\n",
@@ -74,6 +96,8 @@
     const unsigned char *message, int messageLength,
     uint32_t flags
 ) {
+  logPrefixAndMessageToDebugger(prefix, prefixLength, message, messageLength);
+
   char *log;
   swift_asprintf(
       &log, "%.*s: %.*s\n",
diff --git a/test/Constraints/members.swift b/test/Constraints/members.swift
index 09bf137..7f7ddaa 100644
--- a/test/Constraints/members.swift
+++ b/test/Constraints/members.swift
@@ -390,3 +390,30 @@
   func r25341015_local() {}
   r25341015_local(x: 1, y: 2) // expected-error {{argument passed to call that takes no arguments}}
 }
+
+// rdar://problem/32854314 - Emit shadowing diagnostics even if argument types do not much completely
+
+func foo_32854314() -> Double {
+  return 42
+}
+
+func bar_32854314() -> Int {
+  return 0
+}
+
+extension Array where Element == Int {
+  func foo() {
+    let _ = min(foo_32854314(), bar_32854314()) // expected-note {{use 'Swift.' to reference the global function in module 'Swift'}} {{13-13=Swift.}}
+    // expected-error@-1 {{use of 'min' nearly matches global function 'min' in module 'Swift' rather than instance method 'min()'}}
+  }
+
+  func foo(_ x: Int, _ y: Double) {
+    let _ = min(x, y) // expected-note {{use 'Swift.' to reference the global function in module 'Swift'}} {{13-13=Swift.}}
+    // expected-error@-1 {{use of 'min' nearly matches global function 'min' in module 'Swift' rather than instance method 'min()'}}
+  }
+
+  func bar() {
+    let _ = min(1.0, 2) // expected-note {{use 'Swift.' to reference the global function in module 'Swift'}} {{13-13=Swift.}}
+    // expected-error@-1 {{use of 'min' nearly matches global function 'min' in module 'Swift' rather than instance method 'min()'}}
+  }
+}
diff --git a/test/Constraints/patterns.swift b/test/Constraints/patterns.swift
index d99ccb3..f024d23 100644
--- a/test/Constraints/patterns.swift
+++ b/test/Constraints/patterns.swift
@@ -314,3 +314,25 @@
 }
 
 _ = 0
+
+// rdar://problem/32241441 - Add fix-it for cases in switch with optional chaining
+
+struct S_32241441 {
+  enum E_32241441 {
+    case foo
+    case bar
+  }
+
+  var type: E_32241441 = E_32241441.foo
+}
+
+func rdar32241441() {
+  let s: S_32241441? = S_32241441()
+
+  switch s?.type {
+  case .foo: // expected-error {{enum case 'foo' not found in type 'S_32241441.E_32241441?'}} {{12-12=?}}
+    break;
+  case .bar: // expected-error {{enum case 'bar' not found in type 'S_32241441.E_32241441?'}} {{12-12=?}}
+    break;
+  }
+}
diff --git a/test/Parse/ConditionalCompilation/x64CygwinTarget.swift b/test/Parse/ConditionalCompilation/x64CygwinTarget.swift
new file mode 100644
index 0000000..0af7084
--- /dev/null
+++ b/test/Parse/ConditionalCompilation/x64CygwinTarget.swift
@@ -0,0 +1,8 @@
+// RUN: %swift -parse %s -verify -D FOO -D BAR -target x86_64-unknown-windows-cygnus -disable-objc-interop -D FOO -parse-stdlib
+// RUN: %swift-ide-test -test-input-complete -source-filename=%s -target x86_64-unknown-windows-cygnus
+#if arch(x86_64) && os(Cygwin) && _runtime(_Native)
+class C {}
+var x = C()
+#endif
+var y = x
+
diff --git a/test/Parse/ConditionalCompilation/x64WindowsTarget.swift b/test/Parse/ConditionalCompilation/x64WindowsTarget.swift
index 89f0f91..f89314c 100644
--- a/test/Parse/ConditionalCompilation/x64WindowsTarget.swift
+++ b/test/Parse/ConditionalCompilation/x64WindowsTarget.swift
@@ -1,5 +1,5 @@
-// RUN: %swift -typecheck %s -verify -D FOO -D BAR -target x86_64-unknown-windows-cygnus -disable-objc-interop -D FOO -parse-stdlib
-// RUN: %swift-ide-test -test-input-complete -source-filename=%s -target x86_64-unknown-windows-cygnus
+// RUN: %swift -typecheck %s -verify -D FOO -D BAR -target x86_64-unknown-windows-msvc -disable-objc-interop -D FOO -parse-stdlib
+// RUN: %swift-ide-test -test-input-complete -source-filename=%s -target x86_64-unknown-windows-msvc
 
 #if arch(x86_64) && os(Windows) && _runtime(_Native) && _endian(little)
 class C {}
diff --git a/test/stdlib/TestJSONEncoder.swift b/test/stdlib/TestJSONEncoder.swift
index c2519d3..5a8a4a8 100644
--- a/test/stdlib/TestJSONEncoder.swift
+++ b/test/stdlib/TestJSONEncoder.swift
@@ -123,7 +123,7 @@
 
   // MARK: - Date Strategy Tests
   func testEncodingDate() {
-    // We can't encode a top-level Date, so it'll be wrapped in an array.
+    // We can't encode a top-level Date, so it'll be wrapped in a dictionary.
     _testRoundTrip(of: TopLevelWrapper(Date()))
   }
 
@@ -132,7 +132,7 @@
     let seconds = 1000.0
     let expectedJSON = "{\"value\":1000}".data(using: .utf8)!
 
-    // We can't encode a top-level Date, so it'll be wrapped in an array.
+    // We can't encode a top-level Date, so it'll be wrapped in a dictionary.
     _testRoundTrip(of: TopLevelWrapper(Date(timeIntervalSince1970: seconds)),
                    expectedJSON: expectedJSON,
                    dateEncodingStrategy: .secondsSince1970,
@@ -144,7 +144,7 @@
     let seconds = 1000.0
     let expectedJSON = "{\"value\":1000000}".data(using: .utf8)!
 
-    // We can't encode a top-level Date, so it'll be wrapped in an array.
+    // We can't encode a top-level Date, so it'll be wrapped in a dictionary.
     _testRoundTrip(of: TopLevelWrapper(Date(timeIntervalSince1970: seconds)),
                    expectedJSON: expectedJSON,
                    dateEncodingStrategy: .millisecondsSince1970,
@@ -159,7 +159,7 @@
       let timestamp = Date(timeIntervalSince1970: 1000)
       let expectedJSON = "{\"value\":\"\(formatter.string(from: timestamp))\"}".data(using: .utf8)!
 
-      // We can't encode a top-level Date, so it'll be wrapped in an array.
+      // We can't encode a top-level Date, so it'll be wrapped in a dictionary.
       _testRoundTrip(of: TopLevelWrapper(timestamp),
                      expectedJSON: expectedJSON,
                      dateEncodingStrategy: .iso8601,
@@ -175,7 +175,7 @@
     let timestamp = Date(timeIntervalSince1970: 1000)
     let expectedJSON = "{\"value\":\"\(formatter.string(from: timestamp))\"}".data(using: .utf8)!
 
-    // We can't encode a top-level Date, so it'll be wrapped in an array.
+    // We can't encode a top-level Date, so it'll be wrapped in a dictionary.
     _testRoundTrip(of: TopLevelWrapper(timestamp),
                    expectedJSON: expectedJSON,
                    dateEncodingStrategy: .formatted(formatter),
@@ -192,7 +192,7 @@
     }
     let decode = { (_: Decoder) throws -> Date in return timestamp }
 
-    // We can't encode a top-level Date, so it'll be wrapped in an array.
+    // We can't encode a top-level Date, so it'll be wrapped in a dictionary.
     let expectedJSON = "{\"value\":42}".data(using: .utf8)!
     _testRoundTrip(of: TopLevelWrapper(timestamp),
                    expectedJSON: expectedJSON,
@@ -207,7 +207,7 @@
     let encode = { (_: Date, _: Encoder) throws -> Void in }
     let decode = { (_: Decoder) throws -> Date in return timestamp }
 
-    // We can't encode a top-level Date, so it'll be wrapped in an array.
+    // We can't encode a top-level Date, so it'll be wrapped in a dictionary.
     let expectedJSON = "{\"value\":{}}".data(using: .utf8)!
     _testRoundTrip(of: TopLevelWrapper(timestamp),
                    expectedJSON: expectedJSON,
@@ -216,10 +216,21 @@
   }
 
   // MARK: - Data Strategy Tests
+  func testEncodingData() {
+    let data = Data(bytes: [0xDE, 0xAD, 0xBE, 0xEF])
+
+    // We can't encode a top-level Data, so it'll be wrapped in a dictionary.
+    let expectedJSON = "{\"value\":[222,173,190,239]}".data(using: .utf8)!
+    _testRoundTrip(of: TopLevelWrapper(data),
+                   expectedJSON: expectedJSON,
+                   dataEncodingStrategy: .deferredToData,
+                   dataDecodingStrategy: .deferredToData)
+  }
+
   func testEncodingBase64Data() {
     let data = Data(bytes: [0xDE, 0xAD, 0xBE, 0xEF])
 
-    // We can't encode a top-level Data, so it'll be wrapped in an array.
+    // We can't encode a top-level Data, so it'll be wrapped in a dictionary.
     let expectedJSON = "{\"value\":\"3q2+7w==\"}".data(using: .utf8)!
     _testRoundTrip(of: TopLevelWrapper(data), expectedJSON: expectedJSON)
   }
@@ -232,7 +243,7 @@
     }
     let decode = { (_: Decoder) throws -> Data in return Data() }
 
-    // We can't encode a top-level Data, so it'll be wrapped in an array.
+    // We can't encode a top-level Data, so it'll be wrapped in a dictionary.
     let expectedJSON = "{\"value\":42}".data(using: .utf8)!
     _testRoundTrip(of: TopLevelWrapper(Data()),
                    expectedJSON: expectedJSON,
@@ -245,7 +256,7 @@
     let encode = { (_: Data, _: Encoder) throws -> Void in }
     let decode = { (_: Decoder) throws -> Data in return Data() }
 
-    // We can't encode a top-level Data, so it'll be wrapped in an array.
+    // We can't encode a top-level Data, so it'll be wrapped in a dictionary.
     let expectedJSON = "{\"value\":{}}".data(using: .utf8)!
     _testRoundTrip(of: TopLevelWrapper(Data()),
                    expectedJSON: expectedJSON,
@@ -352,8 +363,8 @@
                                  outputFormatting: JSONEncoder.OutputFormatting = [],
                                  dateEncodingStrategy: JSONEncoder.DateEncodingStrategy = .deferredToDate,
                                  dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .deferredToDate,
-                                 dataEncodingStrategy: JSONEncoder.DataEncodingStrategy = .base64Encode,
-                                 dataDecodingStrategy: JSONDecoder.DataDecodingStrategy = .base64Decode,
+                                 dataEncodingStrategy: JSONEncoder.DataEncodingStrategy = .base64,
+                                 dataDecodingStrategy: JSONDecoder.DataDecodingStrategy = .base64,
                                  nonConformingFloatEncodingStrategy: JSONEncoder.NonConformingFloatEncodingStrategy = .throw,
                                  nonConformingFloatDecodingStrategy: JSONDecoder.NonConformingFloatDecodingStrategy = .throw) where T : Codable, T : Equatable {
     var payload: Data! = nil
@@ -879,6 +890,7 @@
 JSONEncoderTests.test("testEncodingDateFormatted") { TestJSONEncoder().testEncodingDateFormatted() }
 JSONEncoderTests.test("testEncodingDateCustom") { TestJSONEncoder().testEncodingDateCustom() }
 JSONEncoderTests.test("testEncodingDateCustomEmpty") { TestJSONEncoder().testEncodingDateCustomEmpty() }
+JSONEncoderTests.test("testEncodingData") { TestJSONEncoder().testEncodingData() }
 JSONEncoderTests.test("testEncodingBase64Data") { TestJSONEncoder().testEncodingBase64Data() }
 JSONEncoderTests.test("testEncodingCustomData") { TestJSONEncoder().testEncodingCustomData() }
 JSONEncoderTests.test("testEncodingCustomDataEmpty") { TestJSONEncoder().testEncodingCustomDataEmpty() }
diff --git a/test/stmt/statements.swift b/test/stmt/statements.swift
index e8dcd1a..5297ec8 100644
--- a/test/stmt/statements.swift
+++ b/test/stmt/statements.swift
@@ -374,7 +374,7 @@
     markUsed(g)  // expected-error {{variable declared in 'guard' condition is not usable in its body}}
   }
 
-  guard let h = y, cond {}  // expected-error {{expected 'else' after 'guard' condition}}
+  guard let h = y, cond {}  // expected-error {{expected 'else' after 'guard' condition}} {{25-25=else }}
 
 
   guard case _ = x else {}  // expected-warning {{'guard' condition is always true, body is unreachable}}
diff --git a/utils/build-script b/utils/build-script
index dd2a8bb..32ade32 100755
--- a/utils/build-script
+++ b/utils/build-script
@@ -2282,4 +2282,7 @@
 
 
 if __name__ == "__main__":
-    sys.exit(main())
+    try:
+        sys.exit(main())
+    except KeyboardInterrupt:
+        sys.exit(1)
diff --git a/validation-test/compiler_crashers/28791-formprotocolrelativetype-swift-protocoldecl-swift-genericsignaturebuilder-potent.swift b/validation-test/compiler_crashers_fixed/28791-formprotocolrelativetype-swift-protocoldecl-swift-genericsignaturebuilder-potent.swift
similarity index 88%
rename from validation-test/compiler_crashers/28791-formprotocolrelativetype-swift-protocoldecl-swift-genericsignaturebuilder-potent.swift
rename to validation-test/compiler_crashers_fixed/28791-formprotocolrelativetype-swift-protocoldecl-swift-genericsignaturebuilder-potent.swift
index 5265b58..1c5768e 100644
--- a/validation-test/compiler_crashers/28791-formprotocolrelativetype-swift-protocoldecl-swift-genericsignaturebuilder-potent.swift
+++ b/validation-test/compiler_crashers_fixed/28791-formprotocolrelativetype-swift-protocoldecl-swift-genericsignaturebuilder-potent.swift
@@ -5,5 +5,5 @@
 // See https://swift.org/LICENSE.txt for license information
 // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
 
-// RUN: not --crash %target-swift-frontend %s -emit-ir
+// RUN: not %target-swift-frontend %s -emit-ir
 extension CountableRange{class a{protocol P{protocol P{}typealias e:P
diff --git a/validation-test/compiler_crashers/28792-conforms-equivclass-conformsto-end.swift b/validation-test/compiler_crashers_fixed/28792-conforms-equivclass-conformsto-end.swift
similarity index 88%
rename from validation-test/compiler_crashers/28792-conforms-equivclass-conformsto-end.swift
rename to validation-test/compiler_crashers_fixed/28792-conforms-equivclass-conformsto-end.swift
index f38207e..7fd018a 100644
--- a/validation-test/compiler_crashers/28792-conforms-equivclass-conformsto-end.swift
+++ b/validation-test/compiler_crashers_fixed/28792-conforms-equivclass-conformsto-end.swift
@@ -6,5 +6,5 @@
 // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
 
 // REQUIRES: asserts
-// RUN: not --crash %target-swift-frontend %s -emit-ir
+// RUN: not %target-swift-frontend %s -emit-ir
 protocol A:A{struct B{{}var a{class a{class ss:a
diff --git a/validation-test/compiler_crashers/28794-swift-type-transformrec-llvm-function-ref-llvm-optional-swift-type-swift-typebas.swift b/validation-test/compiler_crashers_fixed/28794-swift-type-transformrec-llvm-function-ref-llvm-optional-swift-type-swift-typebas.swift
similarity index 87%
rename from validation-test/compiler_crashers/28794-swift-type-transformrec-llvm-function-ref-llvm-optional-swift-type-swift-typebas.swift
rename to validation-test/compiler_crashers_fixed/28794-swift-type-transformrec-llvm-function-ref-llvm-optional-swift-type-swift-typebas.swift
index aaa020a..f63fe5a 100644
--- a/validation-test/compiler_crashers/28794-swift-type-transformrec-llvm-function-ref-llvm-optional-swift-type-swift-typebas.swift
+++ b/validation-test/compiler_crashers_fixed/28794-swift-type-transformrec-llvm-function-ref-llvm-optional-swift-type-swift-typebas.swift
@@ -5,5 +5,5 @@
 // See https://swift.org/LICENSE.txt for license information
 // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
 
-// RUN: not --crash %target-swift-frontend %s -emit-ir
+// RUN: not %target-swift-frontend %s -emit-ir
 class a<a:{a {}extension{P{}protocol A:a{P{}var f
diff --git a/validation-test/compiler_crashers/28795-inprotocol-isrequirementsignaturecomputed-missing-signature.swift b/validation-test/compiler_crashers_fixed/28795-inprotocol-isrequirementsignaturecomputed-missing-signature.swift
similarity index 88%
rename from validation-test/compiler_crashers/28795-inprotocol-isrequirementsignaturecomputed-missing-signature.swift
rename to validation-test/compiler_crashers_fixed/28795-inprotocol-isrequirementsignaturecomputed-missing-signature.swift
index 5cf18bd..1714776 100644
--- a/validation-test/compiler_crashers/28795-inprotocol-isrequirementsignaturecomputed-missing-signature.swift
+++ b/validation-test/compiler_crashers_fixed/28795-inprotocol-isrequirementsignaturecomputed-missing-signature.swift
@@ -6,6 +6,6 @@
 // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
 
 // REQUIRES: asserts
-// RUN: not --crash %target-swift-frontend %s -emit-ir
+// RUN: not %target-swift-frontend %s -emit-ir
 protocol A:A.b{func 丏
 protocol b:Collection