Merge pull request #21112 from slavapestov/on-demand-accessor-fix

Force SILGen emission of on-demand synthesized accessors
diff --git a/cmake/modules/AddSwift.cmake b/cmake/modules/AddSwift.cmake
index 6b1783d..f91e3d1 100644
--- a/cmake/modules/AddSwift.cmake
+++ b/cmake/modules/AddSwift.cmake
@@ -938,10 +938,15 @@
       # target_sources(${target}
       #                PRIVATE
       #                  $<TARGET_OBJECTS:swiftImageRegistrationObject${SWIFT_SDK_${SWIFTLIB_SINGLE_SDK}_OBJECT_FORMAT}-${SWIFT_SDK_${SWIFTLIB_SINGLE_SDK}_LIB_SUBDIR}-${SWIFTLIB_SINGLE_ARCHITECTURE}>)
+      if(SWIFTLIB_SINGLE_SDK STREQUAL WINDOWS)
+        set(extension .obj)
+      else()
+        set(extension .o)
+      endif()
       target_sources(${target}
                      PRIVATE
-                       "${SWIFTLIB_DIR}/${SWIFTLIB_SINGLE_SUBDIR}/swiftrt${CMAKE_C_OUTPUT_EXTENSION}")
-      set_source_files_properties("${SWIFTLIB_DIR}/${SWIFTLIB_SINGLE_SUBDIR}/swiftrt${CMAKE_C_OUTPUT_EXTENSION}"
+                       "${SWIFTLIB_DIR}/${SWIFTLIB_SINGLE_SUBDIR}/swiftrt${extension}")
+      set_source_files_properties("${SWIFTLIB_DIR}/${SWIFTLIB_SINGLE_SUBDIR}/swiftrt${extension}"
                                   PROPERTIES
                                     GENERATED 1)
     endif()
diff --git a/include/swift/AST/DiagnosticsSema.def b/include/swift/AST/DiagnosticsSema.def
index 0272755..38edaf2 100644
--- a/include/swift/AST/DiagnosticsSema.def
+++ b/include/swift/AST/DiagnosticsSema.def
@@ -630,9 +630,9 @@
 ERROR(serialization_missing_shadowed_module,Fatal,
       "cannot load underlying module for %0", (Identifier))
 ERROR(serialization_name_mismatch,Fatal,
-      "cannot load module '%0' as %1", (StringRef, Identifier))
+      "cannot load module '%0' as '%1'", (StringRef, StringRef))
 ERROR(serialization_name_mismatch_repl,none,
-      "cannot load module '%0' as %1", (StringRef, Identifier))
+      "cannot load module '%0' as '%1'", (StringRef, StringRef))
 ERROR(serialization_target_incompatible,Fatal,
       "module %0 was created for incompatible target %1: %2",
       (Identifier, StringRef, StringRef))
diff --git a/include/swift/Frontend/ParseableInterfaceSupport.h b/include/swift/Frontend/ParseableInterfaceSupport.h
index b8b84ac..c369e38 100644
--- a/include/swift/Frontend/ParseableInterfaceSupport.h
+++ b/include/swift/Frontend/ParseableInterfaceSupport.h
@@ -71,12 +71,12 @@
 
   void
   configureSubInvocationAndOutputPaths(CompilerInvocation &SubInvocation,
-                                       StringRef InPath,
+                                       Identifier ModuleName, StringRef InPath,
                                        llvm::SmallString<128> &OutPath);
 
   std::error_code
-  openModuleFiles(StringRef DirName, StringRef ModuleFilename,
-                  StringRef ModuleDocFilename,
+  openModuleFiles(AccessPathElem ModuleID, StringRef DirName,
+                  StringRef ModuleFilename, StringRef ModuleDocFilename,
                   std::unique_ptr<llvm::MemoryBuffer> *ModuleBuffer,
                   std::unique_ptr<llvm::MemoryBuffer> *ModuleDocBuffer,
                   llvm::SmallVectorImpl<char> &Scratch) override;
diff --git a/include/swift/Serialization/SerializedModuleLoader.h b/include/swift/Serialization/SerializedModuleLoader.h
index ccdd770..1f9e6878 100644
--- a/include/swift/Serialization/SerializedModuleLoader.h
+++ b/include/swift/Serialization/SerializedModuleLoader.h
@@ -52,8 +52,8 @@
                   bool &isFramework);
 
   virtual std::error_code
-  openModuleFiles(StringRef DirName, StringRef ModuleFilename,
-                  StringRef ModuleDocFilename,
+  openModuleFiles(AccessPathElem ModuleID, StringRef DirName,
+                  StringRef ModuleFilename, StringRef ModuleDocFilename,
                   std::unique_ptr<llvm::MemoryBuffer> *ModuleBuffer,
                   std::unique_ptr<llvm::MemoryBuffer> *ModuleDocBuffer,
                   llvm::SmallVectorImpl<char> &Scratch);
@@ -129,8 +129,8 @@
   {}
 
   std::error_code
-  openModuleFiles(StringRef DirName, StringRef ModuleFilename,
-                  StringRef ModuleDocFilename,
+  openModuleFiles(AccessPathElem ModuleID, StringRef DirName,
+                  StringRef ModuleFilename, StringRef ModuleDocFilename,
                   std::unique_ptr<llvm::MemoryBuffer> *ModuleBuffer,
                   std::unique_ptr<llvm::MemoryBuffer> *ModuleDocBuffer,
                   llvm::SmallVectorImpl<char> &Scratch) override;
diff --git a/lib/Frontend/ParseableInterfaceSupport.cpp b/lib/Frontend/ParseableInterfaceSupport.cpp
index 8950937..4dd3817 100644
--- a/lib/Frontend/ParseableInterfaceSupport.cpp
+++ b/lib/Frontend/ParseableInterfaceSupport.cpp
@@ -14,6 +14,7 @@
 #include "swift/AST/ASTContext.h"
 #include "swift/AST/Decl.h"
 #include "swift/AST/DiagnosticsFrontend.h"
+#include "swift/AST/DiagnosticsSema.h"
 #include "swift/AST/ExistentialLayout.h"
 #include "swift/AST/FileSystem.h"
 #include "swift/AST/Module.h"
@@ -47,7 +48,7 @@
 static swift::version::Version InterfaceFormatVersion({1, 0});
 
 static bool
-extractSwiftInterfaceVersionAndArgs(DiagnosticEngine &Diags,
+extractSwiftInterfaceVersionAndArgs(DiagnosticEngine &Diags, SourceLoc DiagLoc,
                                     clang::vfs::FileSystem &FS,
                                     StringRef SwiftInterfacePathIn,
                                     swift::version::Version &Vers,
@@ -55,7 +56,7 @@
                                     SmallVectorImpl<const char *> &SubArgs) {
   auto FileOrError = swift::vfs::getFileOrSTDIN(FS, SwiftInterfacePathIn);
   if (!FileOrError) {
-    Diags.diagnose(SourceLoc(), diag::error_open_input_file,
+    Diags.diagnose(DiagLoc, diag::error_open_input_file,
                    SwiftInterfacePathIn, FileOrError.getError().message());
     return true;
   }
@@ -64,12 +65,12 @@
   auto FlagRe = getSwiftInterfaceModuleFlagsRegex();
   SmallVector<StringRef, 1> VersMatches, FlagMatches;
   if (!VersRe.match(SB, &VersMatches)) {
-    Diags.diagnose(SourceLoc(),
+    Diags.diagnose(DiagLoc,
                    diag::error_extracting_version_from_parseable_interface);
     return true;
   }
   if (!FlagRe.match(SB, &FlagMatches)) {
-    Diags.diagnose(SourceLoc(),
+    Diags.diagnose(DiagLoc,
                    diag::error_extracting_flags_from_parseable_interface);
     return true;
   }
@@ -83,11 +84,11 @@
 static std::unique_ptr<llvm::MemoryBuffer>
 getBufferOfDependency(clang::vfs::FileSystem &FS,
                       StringRef ModulePath, StringRef DepPath,
-                      DiagnosticEngine &Diags) {
+                      DiagnosticEngine &Diags, SourceLoc DiagLoc) {
   auto DepBuf = FS.getBufferForFile(DepPath, /*FileSize=*/-1,
                                     /*RequiresNullTerminator=*/false);
   if (!DepBuf) {
-    Diags.diagnose(SourceLoc(),
+    Diags.diagnose(DiagLoc,
                    diag::missing_dependency_of_parseable_module_interface,
                    DepPath, ModulePath, DepBuf.getError().message());
     return nullptr;
@@ -130,6 +131,7 @@
 void
 ParseableInterfaceModuleLoader::configureSubInvocationAndOutputPaths(
     CompilerInvocation &SubInvocation,
+    Identifier ModuleName,
     StringRef InPath,
     llvm::SmallString<128> &OutPath) {
 
@@ -145,37 +147,46 @@
   SubInvocation.setRuntimeResourcePath(SearchPathOpts.RuntimeResourcePath);
   SubInvocation.setTargetTriple(LangOpts.Target);
   SubInvocation.setClangModuleCachePath(CacheDir);
+  SubInvocation.setModuleName(ModuleName.str());
 
   // Inhibit warnings from the SubInvocation since we are assuming the user
   // is not in a position to fix them.
   SubInvocation.getDiagnosticOptions().SuppressWarnings = true;
 
+  // Inherit this setting down so that it can affect error diagnostics (mostly
+  // by making them non-fatal).
+  SubInvocation.getLangOptions().DebuggerSupport = LangOpts.DebuggerSupport;
+
+  // Disable this; deinitializers always get printed with `@objc` even in
+  // modules that don't import Foundation.
+  SubInvocation.getLangOptions().EnableObjCAttrRequiresFoundation = false;
+
   // Calculate an output filename that includes a hash of relevant key data, and
   // wire up the SubInvocation's InputsAndOutputs to contain both input and
   // output filenames.
   OutPath = CacheDir;
-  llvm::sys::path::append(OutPath, llvm::sys::path::stem(InPath));
+  llvm::sys::path::append(OutPath, ModuleName.str());
   OutPath.append("-");
   OutPath.append(getCacheHash(Ctx, SubInvocation, InPath));
   OutPath.append(".");
   auto OutExt = file_types::getExtension(file_types::TY_SwiftModuleFile);
   OutPath.append(OutExt);
 
-  auto &FEOpts = SubInvocation.getFrontendOptions();
-  FEOpts.RequestedAction = FrontendOptions::ActionType::EmitModuleOnly;
-  FEOpts.EnableParseableModuleInterface = true;
-  FEOpts.InputsAndOutputs.addPrimaryInputFile(InPath);
+  auto &SubFEOpts = SubInvocation.getFrontendOptions();
+  SubFEOpts.RequestedAction = FrontendOptions::ActionType::EmitModuleOnly;
+  SubFEOpts.EnableParseableModuleInterface = true;
+  SubFEOpts.InputsAndOutputs.addPrimaryInputFile(InPath);
   SupplementaryOutputPaths SOPs;
   SOPs.ModuleOutputPath = OutPath.str();
   StringRef MainOut = "/dev/null";
-  FEOpts.InputsAndOutputs.setMainAndSupplementaryOutputs({MainOut}, {SOPs});
+  SubFEOpts.InputsAndOutputs.setMainAndSupplementaryOutputs({MainOut}, {SOPs});
 }
 
 // Check that the output .swiftmodule file is at least as new as all the
 // dependencies it read when it was built last time.
 static bool
 swiftModuleIsUpToDate(clang::vfs::FileSystem &FS,
-                      StringRef ModuleCachePath,
+                      std::pair<Identifier, SourceLoc> ModuleID,
                       StringRef OutPath,
                       DiagnosticEngine &Diags,
                       DependencyTracker *OuterTracker) {
@@ -193,10 +204,14 @@
   if (VI.status != serialization::Status::Valid)
     return false;
 
+  assert(VI.name == ModuleID.first.str() &&
+         "we built a module at this path with a different name?");
+
   for (auto In : AllDeps) {
     if (OuterTracker)
       OuterTracker->addDependency(In.Path, /*IsSystem=*/false);
-    auto DepBuf = getBufferOfDependency(FS, OutPath, In.Path, Diags);
+    auto DepBuf = getBufferOfDependency(FS, OutPath, In.Path, Diags,
+                                        ModuleID.second);
     if (!DepBuf ||
         DepBuf->getBufferSize() != In.Size ||
         xxHash64(DepBuf->getBuffer()) != In.Hash) {
@@ -225,7 +240,7 @@
                             CompilerInstance &SubInstance,
                             StringRef InPath, StringRef ModuleCachePath,
                             SmallVectorImpl<FileDependency> &Deps,
-                            DiagnosticEngine &Diags,
+                            DiagnosticEngine &Diags, SourceLoc DiagLoc,
                             DependencyTracker *OuterTracker) {
   auto DTDeps = SubInstance.getDependencyTracker()->getDependencies();
   SmallVector<StringRef, 16> InitialDepNames(DTDeps.begin(), DTDeps.end());
@@ -235,7 +250,7 @@
     if (AllDepNames.insert(DepName).second && OuterTracker) {
         OuterTracker->addDependency(DepName, /*IsSystem=*/false);
     }
-    auto DepBuf = getBufferOfDependency(FS, InPath, DepName, Diags);
+    auto DepBuf = getBufferOfDependency(FS, InPath, DepName, Diags, DiagLoc);
     if (!DepBuf) {
       return true;
     }
@@ -256,7 +271,7 @@
           DepBuf->getBuffer(),
           /*ExtendedValidationInfo=*/nullptr, &SubDeps);
       if (VI.status != serialization::Status::Valid) {
-        Diags.diagnose(SourceLoc(),
+        Diags.diagnose(DiagLoc,
                        diag::error_extracting_dependencies_from_cached_module,
                        DepName);
         return true;
@@ -274,7 +289,7 @@
 }
 
 static bool buildSwiftModuleFromSwiftInterface(
-    clang::vfs::FileSystem &FS, DiagnosticEngine &Diags,
+    clang::vfs::FileSystem &FS, DiagnosticEngine &Diags, SourceLoc DiagLoc,
     CompilerInvocation &SubInvocation, StringRef InPath, StringRef OutPath,
     StringRef ModuleCachePath, DependencyTracker *OuterTracker) {
   bool SubError = false;
@@ -285,7 +300,7 @@
     llvm::StringSaver SubArgSaver(SubArgsAlloc);
     SmallVector<const char *, 16> SubArgs;
     swift::version::Version Vers;
-    if (extractSwiftInterfaceVersionAndArgs(Diags, FS, InPath, Vers,
+    if (extractSwiftInterfaceVersionAndArgs(Diags, DiagLoc, FS, InPath, Vers,
                                             SubArgSaver, SubArgs)) {
       SubError = true;
       return;
@@ -295,18 +310,29 @@
     // minor versions might be interesting for debugging, or special-casing a
     // compatible field variant.
     if (Vers.asMajorVersion() != InterfaceFormatVersion.asMajorVersion()) {
-      Diags.diagnose(SourceLoc(),
+      Diags.diagnose(DiagLoc,
                      diag::unsupported_version_of_parseable_interface,
                      InPath, Vers);
       SubError = true;
       return;
     }
 
+    SmallString<32> ExpectedModuleName = SubInvocation.getModuleName();
     if (SubInvocation.parseArgs(SubArgs, Diags)) {
       SubError = true;
       return;
     }
 
+    if (SubInvocation.getModuleName() != ExpectedModuleName) {
+      auto DiagKind = diag::serialization_name_mismatch;
+      if (SubInvocation.getLangOptions().DebuggerSupport)
+        DiagKind = diag::serialization_name_mismatch_repl;
+      Diags.diagnose(DiagLoc, DiagKind, SubInvocation.getModuleName(),
+                     ExpectedModuleName);
+      SubError = true;
+      return;
+    }
+
     // Optimize emitted modules. This has to happen after we parse arguments,
     // because parseSILOpts would override the current optimization mode.
     SubInvocation.getSILOptions().OptMode = OptimizationMode::ForSpeed;
@@ -353,7 +379,7 @@
     SerializationOpts.ModuleLinkName = FEOpts.ModuleLinkName;
     SmallVector<FileDependency, 16> Deps;
     if (collectDepsForSerialization(FS, SubInstance, InPath, ModuleCachePath,
-                                    Deps, Diags, OuterTracker)) {
+                                    Deps, Diags, DiagLoc, OuterTracker)) {
       SubError = true;
       return;
     }
@@ -389,7 +415,8 @@
 /// cache or by converting it in a subordinate \c CompilerInstance, caching
 /// the results.
 std::error_code ParseableInterfaceModuleLoader::openModuleFiles(
-    StringRef DirName, StringRef ModuleFilename, StringRef ModuleDocFilename,
+    AccessPathElem ModuleID, StringRef DirName, StringRef ModuleFilename,
+    StringRef ModuleDocFilename,
     std::unique_ptr<llvm::MemoryBuffer> *ModuleBuffer,
     std::unique_ptr<llvm::MemoryBuffer> *ModuleDocBuffer,
     llvm::SmallVectorImpl<char> &Scratch) {
@@ -430,12 +457,14 @@
   // Set up a _potential_ sub-invocation to consume the .swiftinterface and emit
   // the .swiftmodule.
   CompilerInvocation SubInvocation;
-  configureSubInvocationAndOutputPaths(SubInvocation, InPath, OutPath);
+  configureSubInvocationAndOutputPaths(SubInvocation, ModuleID.first, InPath,
+                                       OutPath);
 
   // Evaluate if we need to run this sub-invocation, and if so run it.
-  if (!swiftModuleIsUpToDate(FS, CacheDir, OutPath, Diags, dependencyTracker)) {
-    if (buildSwiftModuleFromSwiftInterface(FS, Diags, SubInvocation, InPath,
-                                           OutPath, CacheDir, dependencyTracker))
+  if (!swiftModuleIsUpToDate(FS, ModuleID, OutPath, Diags, dependencyTracker)) {
+    if (buildSwiftModuleFromSwiftInterface(FS, Diags, ModuleID.second,
+                                           SubInvocation, InPath, OutPath,
+                                           CacheDir, dependencyTracker))
       return std::make_error_code(std::errc::invalid_argument);
   }
 
@@ -444,8 +473,8 @@
   LLVM_DEBUG(llvm::dbgs() << "Loading " << OutPath
              << " via normal module loader\n");
   auto ErrorCode = SerializedModuleLoaderBase::openModuleFiles(
-      CacheDir, llvm::sys::path::filename(OutPath), ModuleDocFilename,
-      ModuleBuffer, ModuleDocBuffer, Scratch);
+      ModuleID, CacheDir, llvm::sys::path::filename(OutPath),
+      ModuleDocFilename, ModuleBuffer, ModuleDocBuffer, Scratch);
   LLVM_DEBUG(llvm::dbgs() << "Loaded " << OutPath
              << " via normal module loader");
   if (ErrorCode) {
diff --git a/lib/IDE/TypeReconstruction.cpp b/lib/IDE/TypeReconstruction.cpp
index a96a8e8f6..b88dfd2 100644
--- a/lib/IDE/TypeReconstruction.cpp
+++ b/lib/IDE/TypeReconstruction.cpp
@@ -1913,18 +1913,6 @@
   }
 }
 
-static void VisitNodeInOut(
-    ASTContext *ast,
-    Demangle::NodePointer cur_node, VisitNodeResult &result) {
-  VisitNodeResult type_result;
-  VisitNode(ast, cur_node->getFirstChild(), type_result);
-  if (type_result._types.size() == 1 && type_result._types[0]) {
-    result._types.push_back(InOutType::get(type_result._types[0]));
-  } else {
-    result._error = "couldn't resolve referent type";
-  }
-}
-
 static void VisitNodeExistentialMetatype(ASTContext *ast,
                                          Demangle::NodePointer cur_node,
                                          VisitNodeResult &result) {
@@ -2122,9 +2110,6 @@
 
   auto tupleType = tuple_type_result._types.front();
   auto typeFlags = ParameterTypeFlags();
-  typeFlags = typeFlags.withInOut(tupleType->is<InOutType>());
-  if (auto *inOutTy = tupleType->getAs<InOutType>())
-    tupleType = inOutTy->getObjectType();
   Identifier idName =
       tuple_name.empty() ? Identifier() : ast->getIdentifier(tuple_name);
   result._tuple_type_element = TupleTypeElt(tupleType, idName, typeFlags);
@@ -2365,10 +2350,6 @@
     VisitNodeSetterGetter(ast, node, result);
     break;
 
-  case Demangle::Node::Kind::InOut:
-    VisitNodeInOut(ast, node, result);
-    break;
-
   case Demangle::Node::Kind::ExistentialMetatype:
     VisitNodeExistentialMetatype(ast, node, result);
     break;
diff --git a/lib/SILOptimizer/UtilityPasses/ValueOwnershipKindDumper.cpp b/lib/SILOptimizer/UtilityPasses/ValueOwnershipKindDumper.cpp
index 0befce4..9d1c0f3 100644
--- a/lib/SILOptimizer/UtilityPasses/ValueOwnershipKindDumper.cpp
+++ b/lib/SILOptimizer/UtilityPasses/ValueOwnershipKindDumper.cpp
@@ -23,16 +23,6 @@
 
 using namespace swift;
 
-static void checkEnumInstIsTrivial(EnumInst *EI) {
-  if (!EI->hasOperand())
-    return;
-
-  if (EI->getOperand()->getType().isTrivial(EI->getModule()))
-    return;
-
-  llvm_unreachable("Found enum with non-trivial operand but trivial ownership?!");
-}
-
 namespace {
 
 class ValueOwnershipKindDumper : public SILFunctionTransform {
diff --git a/lib/Sema/ConstraintSystem.cpp b/lib/Sema/ConstraintSystem.cpp
index fd689a8..0073cbc 100644
--- a/lib/Sema/ConstraintSystem.cpp
+++ b/lib/Sema/ConstraintSystem.cpp
@@ -1189,6 +1189,21 @@
     OpenedTypeMap *replacementsPtr) {
   // Figure out the instance type used for the base.
   Type baseObjTy = getFixedTypeRecursive(baseTy, /*wantRValue=*/true);
+
+  ParameterTypeFlags baseFlags;
+  // FIXME(diagnostics): `InOutType` could appear here as a result
+  // of successful re-typecheck of the one of the sub-expressions e.g.
+  // `let _: Int = { (s: inout S) in s.bar() }`. On the first
+  // attempt to type-check whole expression `s.bar()` - is going
+  // to have a base which points directly to declaration of `S`.
+  // But when diagnostics attempts to type-check `s.bar()` standalone
+  // its base would be tranformed into `InOutExpr -> DeclRefExr`,
+  // and `InOutType` is going to be recorded in constraint system.
+  if (auto objType = baseObjTy->getInOutObjectType()) {
+    baseObjTy = objType;
+    baseFlags = baseFlags.withInOut(true);
+  }
+
   bool isInstance = true;
   if (auto baseMeta = baseObjTy->getAs<AnyMetatypeType>()) {
     baseObjTy = baseMeta->getInstanceType();
@@ -1200,7 +1215,7 @@
     return getTypeOfReference(value, functionRefKind, locator, useDC, base);
   }
 
-  FunctionType::Param baseObjParam(baseObjTy);
+  FunctionType::Param baseObjParam(baseObjTy, Identifier(), baseFlags);
 
   // Don't open existentials when accessing typealias members of
   // protocols.
diff --git a/lib/Serialization/SerializedModuleLoader.cpp b/lib/Serialization/SerializedModuleLoader.cpp
index d151d5b..64f0888 100644
--- a/lib/Serialization/SerializedModuleLoader.cpp
+++ b/lib/Serialization/SerializedModuleLoader.cpp
@@ -43,7 +43,8 @@
 SerializedModuleLoader::~SerializedModuleLoader() = default;
 
 std::error_code SerializedModuleLoaderBase::openModuleFiles(
-    StringRef DirName, StringRef ModuleFilename, StringRef ModuleDocFilename,
+    AccessPathElem ModuleID, StringRef DirName, StringRef ModuleFilename,
+    StringRef ModuleDocFilename,
     std::unique_ptr<llvm::MemoryBuffer> *ModuleBuffer,
     std::unique_ptr<llvm::MemoryBuffer> *ModuleDocBuffer,
     llvm::SmallVectorImpl<char> &Scratch) {
@@ -94,14 +95,16 @@
 }
 
 std::error_code SerializedModuleLoader::openModuleFiles(
-    StringRef DirName, StringRef ModuleFilename, StringRef ModuleDocFilename,
+    AccessPathElem ModuleID, StringRef DirName, StringRef ModuleFilename,
+    StringRef ModuleDocFilename,
     std::unique_ptr<llvm::MemoryBuffer> *ModuleBuffer,
     std::unique_ptr<llvm::MemoryBuffer> *ModuleDocBuffer,
     llvm::SmallVectorImpl<char> &Scratch) {
   if (LoadMode == ModuleLoadingMode::OnlyParseable)
     return std::make_error_code(std::errc::not_supported);
 
-  return SerializedModuleLoaderBase::openModuleFiles(DirName, ModuleFilename,
+  return SerializedModuleLoaderBase::openModuleFiles(ModuleID, DirName,
+                                                     ModuleFilename,
                                                      ModuleDocFilename,
                                                      ModuleBuffer,
                                                      ModuleDocBuffer, Scratch);
@@ -204,14 +207,14 @@
 
     if (statResult && statResult->isDirectory()) {
       // A .swiftmodule directory contains architecture-specific files.
-      result = openModuleFiles(currPath,
+      result = openModuleFiles(moduleID, currPath,
                                archFileNames.first, archFileNames.second,
                                moduleBuffer, moduleDocBuffer,
                                scratch);
 
       if (result == std::errc::no_such_file_or_directory &&
           !alternateArchName.empty()) {
-        result = openModuleFiles(currPath,
+        result = openModuleFiles(moduleID, currPath,
                                  alternateArchFileNames.first,
                                  alternateArchFileNames.second,
                                  moduleBuffer, moduleDocBuffer,
@@ -228,7 +231,7 @@
     } else {
       // We can't just return the error; the path we're looking for might not
       // be "Foo.swiftmodule".
-      result = openModuleFiles(path,
+      result = openModuleFiles(moduleID, path,
                                moduleFilename.str(), moduleDocFilename.str(),
                                moduleBuffer, moduleDocBuffer,
                                scratch);
@@ -254,13 +257,13 @@
       // Frameworks always use architecture-specific files within a .swiftmodule
       // directory.
       llvm::sys::path::append(currPath, "Modules", moduleFilename.str());
-      auto err = openModuleFiles(currPath,
+      auto err = openModuleFiles(moduleID, currPath,
                                  archFileNames.first, archFileNames.second,
                                  moduleBuffer, moduleDocBuffer, scratch);
 
       if (err == std::errc::no_such_file_or_directory &&
           !alternateArchName.empty()) {
-        err = openModuleFiles(currPath,
+        err = openModuleFiles(moduleID, currPath,
                               alternateArchFileNames.first,
                               alternateArchFileNames.second,
                               moduleBuffer, moduleDocBuffer, scratch);
@@ -302,7 +305,7 @@
 
   // Search the runtime import path.
   isFramework = false;
-  return !openModuleFiles(Ctx.SearchPathOpts.RuntimeLibraryImportPath,
+  return !openModuleFiles(moduleID, Ctx.SearchPathOpts.RuntimeLibraryImportPath,
                           moduleFilename.str(), moduleDocFilename.str(),
                           moduleBuffer, moduleDocBuffer, scratch);
 }
@@ -543,7 +546,7 @@
     auto diagKind = diag::serialization_name_mismatch;
     if (Ctx.LangOpts.DebuggerSupport)
       diagKind = diag::serialization_name_mismatch_repl;
-    Ctx.Diags.diagnose(diagLoc, diagKind, loadInfo.name, ModuleName);
+    Ctx.Diags.diagnose(diagLoc, diagKind, loadInfo.name, ModuleName.str());
     break;
   }
 
diff --git a/test/ClangImporter/inlinable_bitfields.swift b/test/ClangImporter/inlinable_bitfields.swift
index 5f992f2..ea417b6 100644
--- a/test/ClangImporter/inlinable_bitfields.swift
+++ b/test/ClangImporter/inlinable_bitfields.swift
@@ -2,9 +2,6 @@
 // RUN: %target-swift-frontend %clang-importer-sdk %S/Inputs/inlinable_bitfields_other.swift -emit-module -emit-module-path %t/inlinable_bitfields_other.swiftmodule
 // RUN: %target-swift-frontend %clang-importer-sdk -I %t %s -emit-ir -disable-llvm-optzns -O | %FileCheck %s -DINT=i%target-ptrsize
 
-// rdar://46486435
-// REQUIRES: CPU=x86_64
-
 import inlinable_bitfields_other
 
 public func g(_ m: MM) -> UInt32 {
diff --git a/test/Constraints/closures.swift b/test/Constraints/closures.swift
index 894bcc0..95be013 100644
--- a/test/Constraints/closures.swift
+++ b/test/Constraints/closures.swift
@@ -849,3 +849,12 @@
     }
   }
 }
+
+func rdar45771997() {
+  struct S {
+    mutating func foo() {}
+  }
+
+  let _: Int = { (s: inout S) in s.foo() }
+  // expected-error@-1 {{cannot convert value of type '(inout S) -> ()' to specified type 'Int'}}
+}
diff --git a/test/DebugInfo/Inputs/type-reconstr-names.txt b/test/DebugInfo/Inputs/type-reconstr-names.txt
index 7400ed1..1034ca8 100644
--- a/test/DebugInfo/Inputs/type-reconstr-names.txt
+++ b/test/DebugInfo/Inputs/type-reconstr-names.txt
@@ -3,7 +3,6 @@
 $Ss5Int32VD ---> Int32
 $S4blah4mainyyF8PatatinoL_VMa ---> Can't resolve type of $S4blah4mainyyF8PatatinoL_VMa
 $Ss10CollectionP7Element ---> Can't resolve type of $Ss10CollectionP7Element
-$Ss15ContiguousArrayV9formIndex5afterySiz_tFSS_Tg5 ---> (inout Int) -> ()
 $S12TypeReconstr8PatatinoaySiGD ---> Patatino<Int>
 $S7ElementQzD ---> τ_0_0.Element
 $S13EyeCandySwift21_previousUniqueNumber33_ADC08935D64EA4F796440E7335798735LLs6UInt64Vvp ---> UInt64
diff --git a/test/ParseableInterface/ModuleCache/ObjCAttrWithoutFoundation.swiftinterface b/test/ParseableInterface/ModuleCache/ObjCAttrWithoutFoundation.swiftinterface
new file mode 100644
index 0000000..18a6428
--- /dev/null
+++ b/test/ParseableInterface/ModuleCache/ObjCAttrWithoutFoundation.swiftinterface
@@ -0,0 +1,10 @@
+// swift-interface-format-version: 1.0
+// swift-module-flags: -module-name ObjCAttrWithoutFoundation -enable-resilience -enable-objc-interop
+
+// RUN: %empty-directory(%t)
+// RUN: echo 'import ObjCAttrWithoutFoundation' | %target-swift-frontend -typecheck -enable-parseable-module-interface -module-cache-path %t -I %S -
+
+public class MyClass {
+  public init()
+  @objc deinit
+}
diff --git a/test/ParseableInterface/ModuleCache/WrongName.swiftinterface b/test/ParseableInterface/ModuleCache/WrongName.swiftinterface
new file mode 100644
index 0000000..70b2724
--- /dev/null
+++ b/test/ParseableInterface/ModuleCache/WrongName.swiftinterface
@@ -0,0 +1,7 @@
+// swift-interface-format-version: 1.0
+// swift-module-flags: -module-name DreadPirateRoberts
+
+// RUN: %empty-directory(%t)
+// RUN: echo 'import WrongName' | not %target-swift-frontend -typecheck -enable-parseable-module-interface -module-cache-path %t -I %S - 2>&1 | %FileCheck %s
+
+// CHECK: :1:8: error: cannot load module 'DreadPirateRoberts' as 'WrongName'