Merge remote-tracking branch 'origin/swift-4.0-branch' into stable

* origin/swift-4.0-branch:
  Revert "Modules: Use a PCMCache to manage memory buffers"
  Revert "[Modules] Fallback to building the module if a timeout occurs"
diff --git a/include/clang/Basic/DiagnosticCommonKinds.td b/include/clang/Basic/DiagnosticCommonKinds.td
index aeaa824..fe83b85 100644
--- a/include/clang/Basic/DiagnosticCommonKinds.td
+++ b/include/clang/Basic/DiagnosticCommonKinds.td
@@ -90,10 +90,10 @@
   "%select{|umbrella }0header '%1' not found">;
 def err_module_shadowed : Error<
   "import of shadowed module '%0'">;
-def remark_module_lock_failure : Remark<
-  "could not acquire lock file for module '%0': %1">, InGroup<ModuleBuild>;
-def remark_module_lock_timeout : Remark<
-  "timed out waiting to acquire lock file for module '%0'">, InGroup<ModuleBuild>;
+def err_module_lock_failure : Error<
+  "could not acquire lock file for module '%0': %1">, DefaultFatal;
+def err_module_lock_timeout : Error<
+  "timed out waiting to acquire lock file for module '%0'">, DefaultFatal;
 def err_module_cycle : Error<"cyclic dependency in module '%0': %1">, 
   DefaultFatal;
 def err_module_prebuilt : Error<
diff --git a/include/clang/Basic/DiagnosticSerializationKinds.td b/include/clang/Basic/DiagnosticSerializationKinds.td
index 46adf2c..066a1f5 100644
--- a/include/clang/Basic/DiagnosticSerializationKinds.td
+++ b/include/clang/Basic/DiagnosticSerializationKinds.td
@@ -125,11 +125,6 @@
   "duplicate module file extension block name '%0'">,
   InGroup<ModuleFileExtension>;
 
-def warn_module_system_bit_conflict : Warning<
-  "module file '%0' was validated as a system module and is now being imported "
-  "as a non-system module; any difference in diagnostic options will be ignored">,
-  InGroup<ModuleConflict>;
-
 } // let CategoryName
 } // let Component
 
diff --git a/include/clang/Basic/MemoryBufferCache.h b/include/clang/Basic/MemoryBufferCache.h
deleted file mode 100644
index c79c3c4..0000000
--- a/include/clang/Basic/MemoryBufferCache.h
+++ /dev/null
@@ -1,80 +0,0 @@
-//===- MemoryBufferCache.h - Cache for loaded memory buffers ----*- C++ -*-===//
-//
-//                     The LLVM Compiler Infrastructure
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef LLVM_CLANG_BASIC_MEMORYBUFFERCACHE_H
-#define LLVM_CLANG_BASIC_MEMORYBUFFERCACHE_H
-
-#include "llvm/ADT/IntrusiveRefCntPtr.h"
-#include "llvm/ADT/StringMap.h"
-#include <memory>
-
-namespace llvm {
-class MemoryBuffer;
-} // end namespace llvm
-
-namespace clang {
-
-/// Manage memory buffers across multiple users.
-///
-/// Ensures that multiple users have a consistent view of each buffer.  This is
-/// used by \a CompilerInstance when building PCMs to ensure that each \a
-/// ModuleManager sees the same files.
-///
-/// \a finalizeCurrentBuffers() should be called before creating a new user.
-/// This locks in the current buffers, ensuring that no buffer that has already
-/// been accessed can be purged, preventing use-after-frees.
-class MemoryBufferCache : public llvm::RefCountedBase<MemoryBufferCache> {
-  struct BufferEntry {
-    std::unique_ptr<llvm::MemoryBuffer> Buffer;
-
-    /// Track the timeline of when this was added to the cache.
-    unsigned Index;
-  };
-
-  /// Cache of buffers.
-  llvm::StringMap<BufferEntry> Buffers;
-
-  /// Monotonically increasing index.
-  unsigned NextIndex = 0;
-
-  /// Bumped to prevent "older" buffers from being removed.
-  unsigned FirstRemovableIndex = 0;
-
-public:
-  /// Store the Buffer under the Filename.
-  ///
-  /// \pre There is not already buffer is not already in the cache.
-  /// \return a reference to the buffer as a convenience.
-  llvm::MemoryBuffer &addBuffer(llvm::StringRef Filename,
-                                std::unique_ptr<llvm::MemoryBuffer> Buffer);
-
-  /// Try to remove a buffer from the cache.
-  ///
-  /// \return false on success, iff \c !isBufferFinal().
-  bool tryToRemoveBuffer(llvm::StringRef Filename);
-
-  /// Get a pointer to the buffer if it exists; else nullptr.
-  llvm::MemoryBuffer *lookupBuffer(llvm::StringRef Filename);
-
-  /// Check whether the buffer is final.
-  ///
-  /// \return true iff \a finalizeCurrentBuffers() has been called since the
-  /// buffer was added.  This prevents buffers from being removed.
-  bool isBufferFinal(llvm::StringRef Filename);
-
-  /// Finalize the current buffers in the cache.
-  ///
-  /// Should be called when creating a new user to ensure previous uses aren't
-  /// invalidated.
-  void finalizeCurrentBuffers();
-};
-
-} // end namespace clang
-
-#endif // LLVM_CLANG_BASIC_MEMORYBUFFERCACHE_H
diff --git a/include/clang/Frontend/ASTUnit.h b/include/clang/Frontend/ASTUnit.h
index 2a8df1b..03961f1 100644
--- a/include/clang/Frontend/ASTUnit.h
+++ b/include/clang/Frontend/ASTUnit.h
@@ -51,7 +51,6 @@
 class FileEntry;
 class FileManager;
 class HeaderSearch;
-class MemoryBufferCache;
 class Preprocessor;
 class PCHContainerOperations;
 class PCHContainerReader;
@@ -85,7 +84,6 @@
   IntrusiveRefCntPtr<DiagnosticsEngine>   Diagnostics;
   IntrusiveRefCntPtr<FileManager>         FileMgr;
   IntrusiveRefCntPtr<SourceManager>       SourceMgr;
-  IntrusiveRefCntPtr<MemoryBufferCache>   PCMCache;
   std::unique_ptr<HeaderSearch>           HeaderInfo;
   IntrusiveRefCntPtr<TargetInfo>          Target;
   std::shared_ptr<Preprocessor>           PP;
diff --git a/include/clang/Frontend/CompilerInstance.h b/include/clang/Frontend/CompilerInstance.h
index 62a5fd2..7716e2b 100644
--- a/include/clang/Frontend/CompilerInstance.h
+++ b/include/clang/Frontend/CompilerInstance.h
@@ -44,7 +44,6 @@
 class FileEntry;
 class FileManager;
 class FrontendAction;
-class MemoryBufferCache;
 class Module;
 class Preprocessor;
 class Sema;
@@ -91,9 +90,6 @@
   /// The source manager.
   IntrusiveRefCntPtr<SourceManager> SourceMgr;
 
-  /// The cache of PCM files.
-  IntrusiveRefCntPtr<MemoryBufferCache> PCMCache;
-
   /// The preprocessor.
   std::shared_ptr<Preprocessor> PP;
 
@@ -182,7 +178,7 @@
   explicit CompilerInstance(
       std::shared_ptr<PCHContainerOperations> PCHContainerOps =
           std::make_shared<PCHContainerOperations>(),
-      MemoryBufferCache *SharedPCMCache = nullptr);
+      bool BuildingModule = false);
   ~CompilerInstance() override;
 
   /// @name High-Level Operations
@@ -794,8 +790,6 @@
   }
 
   void setExternalSemaSource(IntrusiveRefCntPtr<ExternalSemaSource> ESS);
-
-  MemoryBufferCache &getPCMCache() const { return *PCMCache; }
 };
 
 } // end namespace clang
diff --git a/include/clang/Lex/Preprocessor.h b/include/clang/Lex/Preprocessor.h
index ee4b3c8..7ce1aad 100644
--- a/include/clang/Lex/Preprocessor.h
+++ b/include/clang/Lex/Preprocessor.h
@@ -47,7 +47,6 @@
 class FileManager;
 class FileEntry;
 class HeaderSearch;
-class MemoryBufferCache;
 class PragmaNamespace;
 class PragmaHandler;
 class CommentHandler;
@@ -103,7 +102,6 @@
   const TargetInfo  *AuxTarget;
   FileManager       &FileMgr;
   SourceManager     &SourceMgr;
-  MemoryBufferCache &PCMCache;
   std::unique_ptr<ScratchBuffer> ScratchBuf;
   HeaderSearch      &HeaderInfo;
   ModuleLoader      &TheModuleLoader;
@@ -654,7 +652,6 @@
 public:
   Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts,
                DiagnosticsEngine &diags, LangOptions &opts, SourceManager &SM,
-               MemoryBufferCache &PCMCache,
                HeaderSearch &Headers, ModuleLoader &TheModuleLoader,
                IdentifierInfoLookup *IILookup = nullptr,
                bool OwnsHeaderSearch = false,
@@ -694,7 +691,6 @@
   const TargetInfo *getAuxTargetInfo() const { return AuxTarget; }
   FileManager &getFileManager() const { return FileMgr; }
   SourceManager &getSourceManager() const { return SourceMgr; }
-  MemoryBufferCache &getPCMCache() const { return PCMCache; }
   HeaderSearch &getHeaderSearchInfo() const { return HeaderInfo; }
 
   IdentifierTable &getIdentifierTable() { return Identifiers; }
diff --git a/include/clang/Serialization/ASTReader.h b/include/clang/Serialization/ASTReader.h
index e174517..17cd871 100644
--- a/include/clang/Serialization/ASTReader.h
+++ b/include/clang/Serialization/ASTReader.h
@@ -408,9 +408,6 @@
   /// \brief The module manager which manages modules and their dependencies
   ModuleManager ModuleMgr;
 
-  /// The cache that manages memory buffers for PCM files.
-  MemoryBufferCache &PCMCache;
-
   /// \brief A dummy identifier resolver used to merge TU-scope declarations in
   /// C, for the cases where we don't have a Sema object to provide a real
   /// identifier resolver.
diff --git a/include/clang/Serialization/ASTWriter.h b/include/clang/Serialization/ASTWriter.h
index 57b0a65..cdcc650 100644
--- a/include/clang/Serialization/ASTWriter.h
+++ b/include/clang/Serialization/ASTWriter.h
@@ -54,7 +54,6 @@
 class OpaqueValueExpr;
 class OpenCLOptions;
 class ASTReader;
-class MemoryBufferCache;
 class Module;
 class ModuleFileExtension;
 class ModuleFileExtensionWriter;
@@ -110,9 +109,6 @@
   /// The buffer associated with the bitstream.
   const SmallVectorImpl<char> &Buffer;
 
-  /// \brief The PCM manager which manages memory buffers for pcm files.
-  MemoryBufferCache &PCMCache;
-
   /// \brief The ASTContext we're writing.
   ASTContext *Context = nullptr;
 
@@ -515,7 +511,6 @@
   /// \brief Create a new precompiled header writer that outputs to
   /// the given bitstream.
   ASTWriter(llvm::BitstreamWriter &Stream, SmallVectorImpl<char> &Buffer,
-            MemoryBufferCache &PCMCache,
             ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
             bool IncludeTimestamps = true);
   ~ASTWriter() override;
diff --git a/include/clang/Serialization/Module.h b/include/clang/Serialization/Module.h
index d28a2f3..c35a6c1 100644
--- a/include/clang/Serialization/Module.h
+++ b/include/clang/Serialization/Module.h
@@ -163,9 +163,9 @@
   /// \brief The generation of which this module file is a part.
   unsigned Generation;
   
-  /// The memory buffer that stores the data associated with
-  /// this AST file, owned by the PCMCache in the ModuleManager.
-  llvm::MemoryBuffer *Buffer;
+  /// \brief The memory buffer that stores the data associated with
+  /// this AST file.
+  std::unique_ptr<llvm::MemoryBuffer> Buffer;
 
   /// \brief The size of this file, in bits.
   uint64_t SizeInBits = 0;
diff --git a/include/clang/Serialization/ModuleManager.h b/include/clang/Serialization/ModuleManager.h
index da6bedc..0f4ec66 100644
--- a/include/clang/Serialization/ModuleManager.h
+++ b/include/clang/Serialization/ModuleManager.h
@@ -24,7 +24,6 @@
 namespace clang { 
 
 class GlobalModuleIndex;
-class MemoryBufferCache;
 class ModuleMap;
 class PCHContainerReader;
 
@@ -52,9 +51,6 @@
   /// FileEntry *.
   FileManager &FileMgr;
 
-  /// Cache of PCM files.
-  IntrusiveRefCntPtr<MemoryBufferCache> PCMCache;
-
   /// \brief Knows how to unwrap module containers.
   const PCHContainerReader &PCHContainerRdr;
 
@@ -127,7 +123,7 @@
       ModuleReverseIterator;
   typedef std::pair<uint32_t, StringRef> ModuleOffset;
 
-  explicit ModuleManager(FileManager &FileMgr, MemoryBufferCache &PCMCache,
+  explicit ModuleManager(FileManager &FileMgr,
                          const PCHContainerReader &PCHContainerRdr);
   ~ModuleManager();
 
@@ -294,8 +290,6 @@
 
   /// \brief View the graphviz representation of the module graph.
   void viewGraph();
-
-  MemoryBufferCache &getPCMCache() const { return *PCMCache; }
 };
 
 } } // end namespace clang::serialization
diff --git a/lib/Basic/CMakeLists.txt b/lib/Basic/CMakeLists.txt
index b6a289a..42e0167 100644
--- a/lib/Basic/CMakeLists.txt
+++ b/lib/Basic/CMakeLists.txt
@@ -74,7 +74,6 @@
   FileSystemStatCache.cpp
   IdentifierTable.cpp
   LangOptions.cpp
-  MemoryBufferCache.cpp
   Module.cpp
   ObjCRuntime.cpp
   OpenMPKinds.cpp
diff --git a/lib/Basic/MemoryBufferCache.cpp b/lib/Basic/MemoryBufferCache.cpp
deleted file mode 100644
index f4b751c..0000000
--- a/lib/Basic/MemoryBufferCache.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-//===- MemoryBufferCache.cpp - Cache for loaded memory buffers ------------===//
-//
-//                     The LLVM Compiler Infrastructure
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "clang/Basic/MemoryBufferCache.h"
-#include "llvm/Support/MemoryBuffer.h"
-
-using namespace clang;
-
-llvm::MemoryBuffer &
-MemoryBufferCache::addBuffer(llvm::StringRef Filename,
-                             std::unique_ptr<llvm::MemoryBuffer> Buffer) {
-  auto Insertion = Buffers.insert(std::make_pair(
-      Filename, BufferEntry{std::move(Buffer), NextIndex++}));
-  assert(Insertion.second && "Already has a buffer");
-  return *Insertion.first->second.Buffer;
-}
-
-llvm::MemoryBuffer *MemoryBufferCache::lookupBuffer(llvm::StringRef Filename) {
-  auto I = Buffers.find(Filename);
-  if (I == Buffers.end())
-    return nullptr;
-  return I->second.Buffer.get();
-}
-
-bool MemoryBufferCache::isBufferFinal(llvm::StringRef Filename) {
-  auto I = Buffers.find(Filename);
-  if (I == Buffers.end())
-    return false;
-  return I->second.Index < FirstRemovableIndex;
-}
-
-bool MemoryBufferCache::tryToRemoveBuffer(llvm::StringRef Filename) {
-  auto I = Buffers.find(Filename);
-  assert(I != Buffers.end() && "No buffer to remove...");
-  if (I->second.Index < FirstRemovableIndex)
-    return true;
-
-  Buffers.erase(I);
-  return false;
-}
-
-void MemoryBufferCache::finalizeCurrentBuffers() { FirstRemovableIndex = NextIndex; }
diff --git a/lib/Frontend/ASTUnit.cpp b/lib/Frontend/ASTUnit.cpp
index aba662b..260855a 100644
--- a/lib/Frontend/ASTUnit.cpp
+++ b/lib/Frontend/ASTUnit.cpp
@@ -18,7 +18,6 @@
 #include "clang/AST/StmtVisitor.h"
 #include "clang/AST/TypeOrdering.h"
 #include "clang/Basic/Diagnostic.h"
-#include "clang/Basic/MemoryBufferCache.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Basic/TargetOptions.h"
 #include "clang/Basic/VirtualFileSystem.h"
@@ -186,8 +185,7 @@
   llvm::BitstreamWriter Stream;
   ASTWriter Writer;
 
-  ASTWriterData(MemoryBufferCache &PCMCache)
-      : Stream(Buffer), Writer(Stream, Buffer, PCMCache, {}) {}
+  ASTWriterData() : Stream(Buffer), Writer(Stream, Buffer, {}) {}
 };
 
 void ASTUnit::clearFileLevelDecls() {
@@ -683,7 +681,6 @@
   AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
                                      AST->getFileManager(),
                                      UserFilesAreVolatile);
-  AST->PCMCache = new MemoryBufferCache;
   AST->HSOpts = std::make_shared<HeaderSearchOptions>();
   AST->HSOpts->ModuleFormat = PCHContainerRdr.getFormat();
   AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
@@ -704,7 +701,7 @@
 
   AST->PP = std::make_shared<Preprocessor>(
       std::move(PPOpts), AST->getDiagnostics(), AST->ASTFileLangOpts,
-      AST->getSourceManager(), *AST->PCMCache, HeaderInfo, *AST,
+      AST->getSourceManager(), HeaderInfo, *AST,
       /*IILookup=*/nullptr,
       /*OwnsHeaderSearch=*/false);
   Preprocessor &PP = *AST->PP;
@@ -1730,7 +1727,6 @@
   AST->UserFilesAreVolatile = UserFilesAreVolatile;
   AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
                                      UserFilesAreVolatile);
-  AST->PCMCache = new MemoryBufferCache;
 
   return AST;
 }
@@ -1998,7 +1994,6 @@
   if (!VFS)
     return nullptr;
   AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
-  AST->PCMCache = new MemoryBufferCache;
   AST->OnlyLocalDecls = OnlyLocalDecls;
   AST->CaptureDiagnostics = CaptureDiagnostics;
   AST->TUKind = TUKind;
@@ -2010,7 +2005,7 @@
   AST->StoredDiagnostics.swap(StoredDiagnostics);
   AST->Invocation = CI;
   if (ForSerialization)
-    AST->WriterData.reset(new ASTWriterData(*AST->PCMCache));
+    AST->WriterData.reset(new ASTWriterData());
   // Zero out now to ease cleanup during crash recovery.
   CI = nullptr;
   Diags = nullptr;
@@ -2525,8 +2520,7 @@
 
   SmallString<128> Buffer;
   llvm::BitstreamWriter Stream(Buffer);
-  MemoryBufferCache PCMCache;
-  ASTWriter Writer(Stream, Buffer, PCMCache, {});
+  ASTWriter Writer(Stream, Buffer, {});
   return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
 }
 
diff --git a/lib/Frontend/CompilerInstance.cpp b/lib/Frontend/CompilerInstance.cpp
index af0f94b..1447471 100644
--- a/lib/Frontend/CompilerInstance.cpp
+++ b/lib/Frontend/CompilerInstance.cpp
@@ -14,7 +14,6 @@
 #include "clang/AST/Decl.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/FileManager.h"
-#include "clang/Basic/MemoryBufferCache.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Basic/Version.h"
@@ -57,15 +56,9 @@
 
 CompilerInstance::CompilerInstance(
     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
-    MemoryBufferCache *SharedPCMCache)
-    : ModuleLoader(/* BuildingModule = */ SharedPCMCache),
-      Invocation(new CompilerInvocation()),
-      PCMCache(SharedPCMCache ? SharedPCMCache : new MemoryBufferCache),
-      ThePCHContainerOperations(std::move(PCHContainerOps)) {
-  // Don't allow this to invalidate buffers in use by others.
-  if (SharedPCMCache)
-    getPCMCache().finalizeCurrentBuffers();
-}
+    bool BuildingModule)
+    : ModuleLoader(BuildingModule), Invocation(new CompilerInvocation()),
+      ThePCHContainerOperations(std::move(PCHContainerOps)) {}
 
 CompilerInstance::~CompilerInstance() {
   assert(OutputFiles.empty() && "Still output files in flight?");
@@ -136,8 +129,6 @@
   return ModuleManager;
 }
 void CompilerInstance::setModuleManager(IntrusiveRefCntPtr<ASTReader> Reader) {
-  assert(PCMCache.get() == &Reader->getModuleManager().getPCMCache() &&
-         "Expected ASTReader to use the same PCM cache");
   ModuleManager = std::move(Reader);
 }
 
@@ -380,7 +371,7 @@
                        getDiagnostics(), getLangOpts(), &getTarget());
   PP = std::make_shared<Preprocessor>(
       Invocation->getPreprocessorOptsPtr(), getDiagnostics(), getLangOpts(),
-      getSourceManager(), getPCMCache(), *HeaderInfo, *this, PTHMgr,
+      getSourceManager(), *HeaderInfo, *this, PTHMgr,
       /*OwnsHeaderSearch=*/true, TUKind);
   PP->Initialize(getTarget(), getAuxTarget());
 
@@ -1104,11 +1095,9 @@
          Invocation->getModuleHash() && "Module hash mismatch!");
   
   // Construct a compiler instance that will be used to actually create the
-  // module.  Since we're sharing a PCMCache,
-  // CompilerInstance::CompilerInstance is responsible for finalizing the
-  // buffers to prevent use-after-frees.
+  // module.
   CompilerInstance Instance(ImportingInstance.getPCHContainerOperations(),
-                            &ImportingInstance.getPreprocessor().getPCMCache());
+                            /*BuildingModule=*/true);
   auto &Inv = *Invocation;
   Instance.setInvocation(std::move(Invocation));
 
@@ -1212,14 +1201,10 @@
     llvm::LockFileManager Locked(ModuleFileName);
     switch (Locked) {
     case llvm::LockFileManager::LFS_Error:
-      // PCMCache takes care of correctness and locks are only necessary for
-      // performance. If there are errors creating the lock, do not use it
-      // and fallback to building the module ourselves.
-      Diags.Report(ModuleNameLoc, diag::remark_module_lock_failure)
+      Diags.Report(ModuleNameLoc, diag::err_module_lock_failure)
           << Module->Name << Locked.getErrorMessage();
-      // Clear the lock file in case there's some leftover around.
-      Locked.unsafeRemoveLockFile();
-      // FALLTHROUGH
+      return false;
+
     case llvm::LockFileManager::LFS_Owned:
       // We're responsible for building the module ourselves.
       if (!compileModuleImpl(ImportingInstance, ModuleNameLoc, Module,
@@ -1239,14 +1224,11 @@
       case llvm::LockFileManager::Res_OwnerDied:
         continue; // try again to get the lock.
       case llvm::LockFileManager::Res_Timeout:
-        // Since PCMCache takes care of correctness, we try waiting for another
-        // process to complete the build so that this isn't done twice. If we
-        // reach a timeout, it's not a problem, try to build it ourselves then.
-        Diags.Report(ModuleNameLoc, diag::remark_module_lock_timeout)
+        Diags.Report(ModuleNameLoc, diag::err_module_lock_timeout)
             << Module->Name;
         // Clear the lock file so that future invokations can make progress.
         Locked.unsafeRemoveLockFile();
-        continue;
+        return false;
       }
       break;
     }
diff --git a/lib/Lex/Preprocessor.cpp b/lib/Lex/Preprocessor.cpp
index babef5d..91319be 100644
--- a/lib/Lex/Preprocessor.cpp
+++ b/lib/Lex/Preprocessor.cpp
@@ -70,15 +70,15 @@
 
 Preprocessor::Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts,
                            DiagnosticsEngine &diags, LangOptions &opts,
-                           SourceManager &SM, MemoryBufferCache &PCMCache,
-                           HeaderSearch &Headers, ModuleLoader &TheModuleLoader,
+                           SourceManager &SM, HeaderSearch &Headers,
+                           ModuleLoader &TheModuleLoader,
                            IdentifierInfoLookup *IILookup, bool OwnsHeaders,
                            TranslationUnitKind TUKind)
     : PPOpts(std::move(PPOpts)), Diags(&diags), LangOpts(opts), Target(nullptr),
       AuxTarget(nullptr), FileMgr(Headers.getFileMgr()), SourceMgr(SM),
-      PCMCache(PCMCache), ScratchBuf(new ScratchBuffer(SourceMgr)),
-      HeaderInfo(Headers), TheModuleLoader(TheModuleLoader),
-      ExternalSource(nullptr), Identifiers(opts, IILookup),
+      ScratchBuf(new ScratchBuffer(SourceMgr)), HeaderInfo(Headers),
+      TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
+      Identifiers(opts, IILookup),
       PragmaHandlers(new PragmaNamespace(StringRef())),
       IncrementalProcessing(false), TUKind(TUKind), CodeComplete(nullptr),
       CodeCompletionFile(nullptr), CodeCompletionOffset(0),
diff --git a/lib/Serialization/ASTReader.cpp b/lib/Serialization/ASTReader.cpp
index 3061aed..c1781b6 100644
--- a/lib/Serialization/ASTReader.cpp
+++ b/lib/Serialization/ASTReader.cpp
@@ -36,7 +36,6 @@
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/FileSystemOptions.h"
 #include "clang/Basic/LangOptions.h"
-#include "clang/Basic/MemoryBufferCache.h"
 #include "clang/Basic/ObjCRuntime.h"
 #include "clang/Basic/OperatorKinds.h"
 #include "clang/Basic/Sanitizers.h"
@@ -462,30 +461,6 @@
   return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
 }
 
-/// Return the top import module if it is implicit, nullptr otherwise.
-static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
-                                          Preprocessor &PP) {
-  // If the original import came from a file explicitly generated by the user,
-  // don't check the diagnostic mappings.
-  // FIXME: currently this is approximated by checking whether this is not a
-  // module import of an implicitly-loaded module file.
-  // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
-  // the transitive closure of its imports, since unrelated modules cannot be
-  // imported until after this module finishes validation.
-  ModuleFile *TopImport = &*ModuleMgr.rbegin();
-  while (!TopImport->ImportedBy.empty())
-    TopImport = TopImport->ImportedBy[0];
-  if (TopImport->Kind != MK_ImplicitModule)
-    return nullptr;
-
-  StringRef ModuleName = TopImport->ModuleName;
-  assert(!ModuleName.empty() && "diagnostic options read before module name");
-
-  Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
-  assert(M && "missing module");
-  return M;
-}
-
 bool PCHValidator::ReadDiagnosticOptions(
     IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
   DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
@@ -499,14 +474,28 @@
   ModuleManager &ModuleMgr = Reader.getModuleManager();
   assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
 
-  Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
-  if (!TopM)
+  // If the original import came from a file explicitly generated by the user,
+  // don't check the diagnostic mappings.
+  // FIXME: currently this is approximated by checking whether this is not a
+  // module import of an implicitly-loaded module file.
+  // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
+  // the transitive closure of its imports, since unrelated modules cannot be
+  // imported until after this module finishes validation.
+  ModuleFile *TopImport = &*ModuleMgr.rbegin();
+  while (!TopImport->ImportedBy.empty())
+    TopImport = TopImport->ImportedBy[0];
+  if (TopImport->Kind != MK_ImplicitModule)
     return false;
 
+  StringRef ModuleName = TopImport->ModuleName;
+  assert(!ModuleName.empty() && "diagnostic options read before module name");
+
+  Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
+  assert(M && "missing module");
+
   // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
   // contains the union of their flags.
-  return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
-                                 Complain);
+  return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
 }
 
 /// \brief Collect the macro definitions provided by the given preprocessor
@@ -4036,41 +4025,12 @@
       Listener.get(),
       WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
 
-  // If F was directly imported by another module, it's implicitly validated by
-  // the importing module.
   if (DisableValidation || WasImportedBy ||
       (AllowConfigurationMismatch && Result == ConfigurationMismatch))
     return Success;
 
-  if (Result == Failure) {
+  if (Result == Failure)
     Error("malformed block record in AST file");
-    return Failure;
-  }
-
-  if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
-    // If this module has already been finalized in the PCMCache, we're stuck
-    // with it; we can only load a single version of each module.
-    //
-    // This can happen when a module is imported in two contexts: in one, as a
-    // user module; in another, as a system module (due to an import from
-    // another module marked with the [system] flag).  It usually indicates a
-    // bug in the module map: this module should also be marked with [system].
-    //
-    // If -Wno-system-headers (the default), and the first import is as a
-    // system module, then validation will fail during the as-user import,
-    // since -Werror flags won't have been validated.  However, it's reasonable
-    // to treat this consistently as a system module.
-    //
-    // If -Wsystem-headers, the PCM on disk was built with
-    // -Wno-system-headers, and the first import is as a user module, then
-    // validation will fail during the as-system import since the PCM on disk
-    // doesn't guarantee that -Werror was respected.  However, the -Werror
-    // flags were checked during the initial as-user import.
-    if (PCMCache.isBufferFinal(F.FileName)) {
-      Diag(diag::warn_module_system_bit_conflict) << F.FileName;
-      return Success;
-    }
-  }
 
   return Result;
 }
@@ -4123,7 +4083,7 @@
       if (Listener && ValidateDiagnosticOptions &&
           !AllowCompatibleConfigurationMismatch &&
           ParseDiagnosticOptions(Record, Complain, *Listener))
-        Result = OutOfDate; // Don't return early.  Read the signature.
+        return OutOfDate;
       break;
     }
     case DIAG_PRAGMA_MAPPINGS:
@@ -7288,7 +7248,7 @@
 /// by heap-backed versus mmap'ed memory.
 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
   for (ModuleFile &I : ModuleMgr) {
-    if (llvm::MemoryBuffer *buf = I.Buffer) {
+    if (llvm::MemoryBuffer *buf = I.Buffer.get()) {
       size_t bytes = buf->getBufferSize();
       switch (buf->getBufferKind()) {
         case llvm::MemoryBuffer::MemoryBuffer_Malloc:
@@ -9105,10 +9065,8 @@
                    : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
       SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
       PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
-      Context(Context),
-      ModuleMgr(PP.getFileManager(), PP.getPCMCache(), PCHContainerRdr),
-      PCMCache(PP.getPCMCache()), DummyIdResolver(PP),
-      ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
+      Context(Context), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
+      DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
       DisableValidation(DisableValidation),
       AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
       AllowConfigurationMismatch(AllowConfigurationMismatch),
diff --git a/lib/Serialization/ASTWriter.cpp b/lib/Serialization/ASTWriter.cpp
index 1ac2562..3505049 100644
--- a/lib/Serialization/ASTWriter.cpp
+++ b/lib/Serialization/ASTWriter.cpp
@@ -35,7 +35,6 @@
 #include "clang/Basic/FileSystemOptions.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/LangOptions.h"
-#include "clang/Basic/MemoryBufferCache.h"
 #include "clang/Basic/Module.h"
 #include "clang/Basic/ObjCRuntime.h"
 #include "clang/Basic/SourceManager.h"
@@ -4259,11 +4258,10 @@
 }
 
 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
-                     SmallVectorImpl<char> &Buffer, MemoryBufferCache &PCMCache,
+                     SmallVectorImpl<char> &Buffer,
                      ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
                      bool IncludeTimestamps)
-    : Stream(Stream), Buffer(Buffer), PCMCache(PCMCache),
-      IncludeTimestamps(IncludeTimestamps) {
+    : Stream(Stream), Buffer(Buffer), IncludeTimestamps(IncludeTimestamps) {
   for (const auto &Ext : Extensions) {
     if (auto Writer = Ext->createExtensionWriter(*this))
       ModuleFileExtensionWriters.push_back(std::move(Writer));
@@ -4310,12 +4308,6 @@
   this->BaseDirectory.clear();
 
   WritingAST = false;
-  if (SemaRef.Context.getLangOpts().ImplicitModules && WritingModule) {
-    // Construct MemoryBuffer and update buffer manager.
-    PCMCache.addBuffer(OutputFile,
-                       llvm::MemoryBuffer::getMemBufferCopy(
-                           StringRef(Buffer.begin(), Buffer.size())));
-  }
   return Signature;
 }
 
diff --git a/lib/Serialization/GeneratePCH.cpp b/lib/Serialization/GeneratePCH.cpp
index 429ae8e..141a559 100644
--- a/lib/Serialization/GeneratePCH.cpp
+++ b/lib/Serialization/GeneratePCH.cpp
@@ -28,8 +28,7 @@
     bool AllowASTWithErrors, bool IncludeTimestamps)
     : PP(PP), OutputFile(OutputFile), isysroot(isysroot.str()),
       SemaPtr(nullptr), Buffer(Buffer), Stream(Buffer->Data),
-      Writer(Stream, Buffer->Data, PP.getPCMCache(), Extensions,
-             IncludeTimestamps),
+      Writer(Stream, Buffer->Data, Extensions, IncludeTimestamps),
       AllowASTWithErrors(AllowASTWithErrors) {
   Buffer->IsComplete = false;
 }
diff --git a/lib/Serialization/ModuleManager.cpp b/lib/Serialization/ModuleManager.cpp
index e35a44d..b7ee302 100644
--- a/lib/Serialization/ModuleManager.cpp
+++ b/lib/Serialization/ModuleManager.cpp
@@ -12,7 +12,6 @@
 //
 //===----------------------------------------------------------------------===//
 #include "clang/Serialization/ModuleManager.h"
-#include "clang/Basic/MemoryBufferCache.h"
 #include "clang/Frontend/PCHContainerOperations.h"
 #include "clang/Lex/HeaderSearch.h"
 #include "clang/Lex/ModuleMap.h"
@@ -139,9 +138,7 @@
   // Load the contents of the module
   if (std::unique_ptr<llvm::MemoryBuffer> Buffer = lookupBuffer(FileName)) {
     // The buffer was already provided for us.
-    NewModule->Buffer = &PCMCache->addBuffer(FileName, std::move(Buffer));
-  } else if (llvm::MemoryBuffer *Buffer = PCMCache->lookupBuffer(FileName)) {
-    NewModule->Buffer = Buffer;
+    NewModule->Buffer = std::move(Buffer);
   } else {
     // Open the AST file.
     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buf((std::error_code()));
@@ -162,7 +159,7 @@
       return Missing;
     }
 
-    NewModule->Buffer = &PCMCache->addBuffer(FileName, std::move(*Buf));
+    NewModule->Buffer = std::move(*Buf);
   }
 
   // Initialize the stream.
@@ -171,13 +168,8 @@
   // Read the signature eagerly now so that we can check it.  Avoid calling
   // ReadSignature unless there's something to check though.
   if (ExpectedSignature && checkSignature(ReadSignature(NewModule->Data),
-                                          ExpectedSignature, ErrorStr)) {
-    // Try to remove the buffer.  If it can't be removed, then it was already
-    // validated by this process.
-    if (!PCMCache->tryToRemoveBuffer(NewModule->FileName))
-      FileMgr.invalidateCache(NewModule->File);
+                                          ExpectedSignature, ErrorStr))
     return OutOfDate;
-  }
 
   // We're keeping this module.  Store it everywhere.
   Module = Modules[Entry] = NewModule.get();
@@ -244,12 +236,7 @@
     // Files that didn't make it through ReadASTCore successfully will be
     // rebuilt (or there was an error). Invalidate them so that we can load the
     // new files that will be renamed over the old ones.
-    //
-    // The PCMCache tracks whether the module was succesfully loaded in another
-    // thread/context; in that case, it won't need to be rebuilt (and we can't
-    // safely invalidate it anyway).
-    if (LoadedSuccessfully.count(&*victim) == 0 &&
-        !PCMCache->tryToRemoveBuffer(victim->FileName))
+    if (LoadedSuccessfully.count(&*victim) == 0)
       FileMgr.invalidateCache(victim->File);
   }
 
@@ -306,10 +293,10 @@
   ModulesInCommonWithGlobalIndex.push_back(MF);
 }
 
-ModuleManager::ModuleManager(FileManager &FileMgr, MemoryBufferCache &PCMCache,
+ModuleManager::ModuleManager(FileManager &FileMgr,
                              const PCHContainerReader &PCHContainerRdr)
-    : FileMgr(FileMgr), PCMCache(&PCMCache), PCHContainerRdr(PCHContainerRdr),
-      GlobalIndex(), FirstVisitState(nullptr) {}
+    : FileMgr(FileMgr), PCHContainerRdr(PCHContainerRdr), GlobalIndex(),
+      FirstVisitState(nullptr) {}
 
 ModuleManager::~ModuleManager() { delete FirstVisitState; }
 
diff --git a/test/Modules/Inputs/outofdate-rebuild/AppKit.h b/test/Modules/Inputs/outofdate-rebuild/AppKit.h
deleted file mode 100644
index e357918..0000000
--- a/test/Modules/Inputs/outofdate-rebuild/AppKit.h
+++ /dev/null
@@ -1,3 +0,0 @@
-// AppKit
-#import "CoreVideo.h" // CoreVideo
-struct B { int i; };
diff --git a/test/Modules/Inputs/outofdate-rebuild/Cocoa.h b/test/Modules/Inputs/outofdate-rebuild/Cocoa.h
deleted file mode 100644
index d631140..0000000
--- a/test/Modules/Inputs/outofdate-rebuild/Cocoa.h
+++ /dev/null
@@ -1,5 +0,0 @@
-// Cocoa
-#import "Foundation.h"
-#import "AppKit.h"
-
-struct A {  int i; };
diff --git a/test/Modules/Inputs/outofdate-rebuild/CoreText.h b/test/Modules/Inputs/outofdate-rebuild/CoreText.h
deleted file mode 100644
index 7ff0e23..0000000
--- a/test/Modules/Inputs/outofdate-rebuild/CoreText.h
+++ /dev/null
@@ -1 +0,0 @@
-struct C { int i; };
diff --git a/test/Modules/Inputs/outofdate-rebuild/CoreVideo.h b/test/Modules/Inputs/outofdate-rebuild/CoreVideo.h
deleted file mode 100644
index bd249dc..0000000
--- a/test/Modules/Inputs/outofdate-rebuild/CoreVideo.h
+++ /dev/null
@@ -1,3 +0,0 @@
-// CoreVideo
-#import "Foundation.h" // Foundation
-struct E { int i; };
diff --git a/test/Modules/Inputs/outofdate-rebuild/Foundation.h b/test/Modules/Inputs/outofdate-rebuild/Foundation.h
deleted file mode 100644
index b2d053a..0000000
--- a/test/Modules/Inputs/outofdate-rebuild/Foundation.h
+++ /dev/null
@@ -1,3 +0,0 @@
-// Foundation
-#import "CoreText.h"
-struct D { int i; };
diff --git a/test/Modules/Inputs/outofdate-rebuild/module.modulemap b/test/Modules/Inputs/outofdate-rebuild/module.modulemap
deleted file mode 100644
index 71c99e8..0000000
--- a/test/Modules/Inputs/outofdate-rebuild/module.modulemap
+++ /dev/null
@@ -1,19 +0,0 @@
-module Cocoa {
-  header "Cocoa.h"
-}
-
-module AppKit {
-  header "AppKit.h"
-}
-
-module CoreText {
-  header "CoreText.h"
-}
-
-module Foundation {
-  header "Foundation.h"
-}
-
-module CoreVideo {
-  header "CoreVideo.h"
-}
diff --git a/test/Modules/Inputs/system-out-of-date/X.h b/test/Modules/Inputs/system-out-of-date/X.h
deleted file mode 100644
index edcfa18..0000000
--- a/test/Modules/Inputs/system-out-of-date/X.h
+++ /dev/null
@@ -1 +0,0 @@
-#import <Y.h>
diff --git a/test/Modules/Inputs/system-out-of-date/Y.h b/test/Modules/Inputs/system-out-of-date/Y.h
deleted file mode 100644
index 90fe1bc..0000000
--- a/test/Modules/Inputs/system-out-of-date/Y.h
+++ /dev/null
@@ -1 +0,0 @@
-//empty
diff --git a/test/Modules/Inputs/system-out-of-date/Z.h b/test/Modules/Inputs/system-out-of-date/Z.h
deleted file mode 100644
index edcfa18..0000000
--- a/test/Modules/Inputs/system-out-of-date/Z.h
+++ /dev/null
@@ -1 +0,0 @@
-#import <Y.h>
diff --git a/test/Modules/Inputs/system-out-of-date/module.map b/test/Modules/Inputs/system-out-of-date/module.map
deleted file mode 100644
index 0c0f42a..0000000
--- a/test/Modules/Inputs/system-out-of-date/module.map
+++ /dev/null
@@ -1,12 +0,0 @@
-module X [system] {
-  header "X.h" // imports Y
-  export *
-}
-module Y {
-  header "Y.h"
-  export *
-}
-module Z {
-  header "Z.h" // imports Y
-  export *
-}
diff --git a/test/Modules/Inputs/warning-mismatch/Mismatch.h b/test/Modules/Inputs/warning-mismatch/Mismatch.h
deleted file mode 100644
index a07b0ee..0000000
--- a/test/Modules/Inputs/warning-mismatch/Mismatch.h
+++ /dev/null
@@ -1 +0,0 @@
-struct Mismatch { int i; };
diff --git a/test/Modules/Inputs/warning-mismatch/System.h b/test/Modules/Inputs/warning-mismatch/System.h
deleted file mode 100644
index 8e69e70..0000000
--- a/test/Modules/Inputs/warning-mismatch/System.h
+++ /dev/null
@@ -1,2 +0,0 @@
-#import "Mismatch.h"
-struct System { int i; };
diff --git a/test/Modules/Inputs/warning-mismatch/module.modulemap b/test/Modules/Inputs/warning-mismatch/module.modulemap
deleted file mode 100644
index c22cde4..0000000
--- a/test/Modules/Inputs/warning-mismatch/module.modulemap
+++ /dev/null
@@ -1,7 +0,0 @@
-module System [system] {
-  header "System.h"
-}
-
-module Mismatch {
-  header "Mismatch.h"
-}
diff --git a/test/Modules/outofdate-rebuild.m b/test/Modules/outofdate-rebuild.m
deleted file mode 100644
index e933dce..0000000
--- a/test/Modules/outofdate-rebuild.m
+++ /dev/null
@@ -1,12 +0,0 @@
-// RUN: rm -rf %t.cache
-// RUN: echo "@import CoreText;" > %t.m
-// RUN: %clang_cc1 -fdisable-module-hash -fmodules-cache-path=%t.cache -fmodules -fimplicit-module-maps -I %S/Inputs/outofdate-rebuild %s -fsyntax-only -Rmodule-build
-// RUN: echo -----------------------------------------------
-// RUN: %clang_cc1 -DMISMATCH -Werror -fdisable-module-hash -fmodules-cache-path=%t.cache -fmodules -fimplicit-module-maps -I %S/Inputs/outofdate-rebuild %t.m -fsyntax-only -Rmodule-build
-// RUN: echo -----------------------------------------------
-// RUN: %clang_cc1 -fdisable-module-hash -fmodules-cache-path=%t.cache -fmodules -fimplicit-module-maps -I %S/Inputs/outofdate-rebuild %s -fsyntax-only -Rmodule-build
-
-// This testcase reproduces a use-after-free in
-// https://reviews.llvm.org/D28299 when ModuleManager removes an entry
-// from the PCMcache without notifying its parent ASTReader.
-@import Cocoa;
diff --git a/test/Modules/system-out-of-date-test.m b/test/Modules/system-out-of-date-test.m
deleted file mode 100644
index 9ce14cc..0000000
--- a/test/Modules/system-out-of-date-test.m
+++ /dev/null
@@ -1,13 +0,0 @@
-// RUN: rm -rf %t
-// RUN: echo '@import X;' | \
-// RUN:   %clang_cc1 -fmodules -fimplicit-module-maps \
-// RUN:     -fmodules-cache-path=%t -I %S/Inputs/system-out-of-date \
-// RUN:     -fsyntax-only -x objective-c -
-
-// We have an version built with different diagnostic options.
-// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I %S/Inputs/system-out-of-date -Wnon-modular-include-in-framework-module -Werror=non-modular-include-in-framework-module %s -fsyntax-only 2>&1 | FileCheck %s
- @import X;
- 
- #import <Z.h>
-// CHECK: While building module 'Z' imported from
-// CHECK: {{.*}}Y-{{.*}}pcm' was validated as a system module and is now being imported as a non-system module
diff --git a/test/Modules/warning-mismatch.m b/test/Modules/warning-mismatch.m
deleted file mode 100644
index 7c83664..0000000
--- a/test/Modules/warning-mismatch.m
+++ /dev/null
@@ -1,9 +0,0 @@
-// RUN: rm -rf %t.cache
-// RUN: echo "@import Mismatch;" >%t.m
-// RUN: %clang_cc1 -Wno-system-headers -fdisable-module-hash -fmodules-cache-path=%t.cache -fmodules -fimplicit-module-maps -I %S/Inputs/warning-mismatch %t.m -fsyntax-only -Rmodule-build
-// RUN: echo -----------------------------------------------
-// RUN: %clang_cc1 -Wsystem-headers -fdisable-module-hash -fmodules-cache-path=%t.cache -fmodules -fimplicit-module-maps -I %S/Inputs/warning-mismatch %s -fsyntax-only -Rmodule-build
-
-// This testcase triggers a warning flag mismatch in an already validated header.
-@import Mismatch;
-@import System;
diff --git a/unittests/Basic/CMakeLists.txt b/unittests/Basic/CMakeLists.txt
index 3a9f34f..3cb3cb8 100644
--- a/unittests/Basic/CMakeLists.txt
+++ b/unittests/Basic/CMakeLists.txt
@@ -6,7 +6,6 @@
   CharInfoTest.cpp
   DiagnosticTest.cpp
   FileManagerTest.cpp
-  MemoryBufferCacheTest.cpp
   SourceManagerTest.cpp
   VirtualFileSystemTest.cpp
   )
diff --git a/unittests/Basic/MemoryBufferCacheTest.cpp b/unittests/Basic/MemoryBufferCacheTest.cpp
deleted file mode 100644
index be243c2..0000000
--- a/unittests/Basic/MemoryBufferCacheTest.cpp
+++ /dev/null
@@ -1,94 +0,0 @@
-//===- MemoryBufferCacheTest.cpp - MemoryBufferCache tests ----------------===//
-//
-//                     The LLVM Compiler Infrastructure
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "clang/Basic/MemoryBufferCache.h"
-#include "llvm/Support/MemoryBuffer.h"
-#include "gtest/gtest.h"
-
-using namespace llvm;
-using namespace clang;
-
-namespace {
-
-std::unique_ptr<MemoryBuffer> getBuffer(int I) {
-  SmallVector<char, 8> Bytes;
-  raw_svector_ostream(Bytes) << "data:" << I;
-  return MemoryBuffer::getMemBuffer(StringRef(Bytes.data(), Bytes.size()));
-}
-
-TEST(MemoryBufferCacheTest, addBuffer) {
-  auto B1 = getBuffer(1);
-  auto B2 = getBuffer(2);
-  auto B3 = getBuffer(3);
-  auto *RawB1 = B1.get();
-  auto *RawB2 = B2.get();
-  auto *RawB3 = B3.get();
-
-  // Add a few buffers.
-  MemoryBufferCache Cache;
-  EXPECT_EQ(RawB1, &Cache.addBuffer("1", std::move(B1)));
-  EXPECT_EQ(RawB2, &Cache.addBuffer("2", std::move(B2)));
-  EXPECT_EQ(RawB3, &Cache.addBuffer("3", std::move(B3)));
-  EXPECT_EQ(RawB1, Cache.lookupBuffer("1"));
-  EXPECT_EQ(RawB2, Cache.lookupBuffer("2"));
-  EXPECT_EQ(RawB3, Cache.lookupBuffer("3"));
-  EXPECT_FALSE(Cache.isBufferFinal("1"));
-  EXPECT_FALSE(Cache.isBufferFinal("2"));
-  EXPECT_FALSE(Cache.isBufferFinal("3"));
-
-  // Remove the middle buffer.
-  EXPECT_FALSE(Cache.tryToRemoveBuffer("2"));
-  EXPECT_EQ(nullptr, Cache.lookupBuffer("2"));
-  EXPECT_FALSE(Cache.isBufferFinal("2"));
-
-  // Replace the middle buffer.
-  B2 = getBuffer(2);
-  ASSERT_NE(RawB2, B2.get());
-  RawB2 = B2.get();
-  EXPECT_EQ(RawB2, &Cache.addBuffer("2", std::move(B2)));
-
-  // Check that nothing is final.
-  EXPECT_FALSE(Cache.isBufferFinal("1"));
-  EXPECT_FALSE(Cache.isBufferFinal("2"));
-  EXPECT_FALSE(Cache.isBufferFinal("3"));
-}
-
-TEST(MemoryBufferCacheTest, finalizeCurrentBuffers) {
-  // Add a buffer.
-  MemoryBufferCache Cache;
-  auto B1 = getBuffer(1);
-  auto *RawB1 = B1.get();
-  Cache.addBuffer("1", std::move(B1));
-  ASSERT_FALSE(Cache.isBufferFinal("1"));
-
-  // Finalize it.
-  Cache.finalizeCurrentBuffers();
-  EXPECT_TRUE(Cache.isBufferFinal("1"));
-  EXPECT_TRUE(Cache.tryToRemoveBuffer("1"));
-  EXPECT_EQ(RawB1, Cache.lookupBuffer("1"));
-  EXPECT_TRUE(Cache.isBufferFinal("1"));
-
-  // Repeat.
-  auto B2 = getBuffer(2);
-  auto *RawB2 = B2.get();
-  Cache.addBuffer("2", std::move(B2));
-  EXPECT_FALSE(Cache.isBufferFinal("2"));
-
-  Cache.finalizeCurrentBuffers();
-  EXPECT_TRUE(Cache.isBufferFinal("1"));
-  EXPECT_TRUE(Cache.isBufferFinal("2"));
-  EXPECT_TRUE(Cache.tryToRemoveBuffer("1"));
-  EXPECT_TRUE(Cache.tryToRemoveBuffer("2"));
-  EXPECT_EQ(RawB1, Cache.lookupBuffer("1"));
-  EXPECT_EQ(RawB2, Cache.lookupBuffer("2"));
-  EXPECT_TRUE(Cache.isBufferFinal("1"));
-  EXPECT_TRUE(Cache.isBufferFinal("2"));
-}
-
-} // namespace
diff --git a/unittests/Basic/SourceManagerTest.cpp b/unittests/Basic/SourceManagerTest.cpp
index dddc3f9..a967b0e 100644
--- a/unittests/Basic/SourceManagerTest.cpp
+++ b/unittests/Basic/SourceManagerTest.cpp
@@ -12,7 +12,6 @@
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/LangOptions.h"
-#include "clang/Basic/MemoryBufferCache.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Basic/TargetOptions.h"
 #include "clang/Lex/HeaderSearch.h"
@@ -79,11 +78,10 @@
   SourceMgr.setMainFileID(mainFileID);
 
   VoidModuleLoader ModLoader;
-  MemoryBufferCache PCMCache;
   HeaderSearch HeaderInfo(std::make_shared<HeaderSearchOptions>(), SourceMgr,
                           Diags, LangOpts, &*Target);
   Preprocessor PP(std::make_shared<PreprocessorOptions>(), Diags, LangOpts,
-                  SourceMgr, PCMCache, HeaderInfo, ModLoader,
+                  SourceMgr, HeaderInfo, ModLoader,
                   /*IILookup =*/nullptr,
                   /*OwnsHeaderSearch =*/false);
   PP.Initialize(*Target);
@@ -200,11 +198,10 @@
   SourceMgr.overrideFileContents(headerFile, std::move(HeaderBuf));
 
   VoidModuleLoader ModLoader;
-  MemoryBufferCache PCMCache;
   HeaderSearch HeaderInfo(std::make_shared<HeaderSearchOptions>(), SourceMgr,
                           Diags, LangOpts, &*Target);
   Preprocessor PP(std::make_shared<PreprocessorOptions>(), Diags, LangOpts,
-                  SourceMgr, PCMCache, HeaderInfo, ModLoader,
+                  SourceMgr, HeaderInfo, ModLoader,
                   /*IILookup =*/nullptr,
                   /*OwnsHeaderSearch =*/false);
   PP.Initialize(*Target);
@@ -301,11 +298,10 @@
   SourceMgr.overrideFileContents(headerFile, std::move(HeaderBuf));
 
   VoidModuleLoader ModLoader;
-  MemoryBufferCache PCMCache;
   HeaderSearch HeaderInfo(std::make_shared<HeaderSearchOptions>(), SourceMgr,
                           Diags, LangOpts, &*Target);
   Preprocessor PP(std::make_shared<PreprocessorOptions>(), Diags, LangOpts,
-                  SourceMgr, PCMCache, HeaderInfo, ModLoader,
+                  SourceMgr, HeaderInfo, ModLoader,
                   /*IILookup =*/nullptr,
                   /*OwnsHeaderSearch =*/false);
   PP.Initialize(*Target);
diff --git a/unittests/Lex/LexerTest.cpp b/unittests/Lex/LexerTest.cpp
index b5a6fd9..918167b 100644
--- a/unittests/Lex/LexerTest.cpp
+++ b/unittests/Lex/LexerTest.cpp
@@ -12,7 +12,6 @@
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/LangOptions.h"
-#include "clang/Basic/MemoryBufferCache.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Basic/TargetOptions.h"
@@ -65,12 +64,10 @@
     SourceMgr.setMainFileID(SourceMgr.createFileID(std::move(Buf)));
 
     VoidModuleLoader ModLoader;
-    MemoryBufferCache PCMCache;
     HeaderSearch HeaderInfo(std::make_shared<HeaderSearchOptions>(), SourceMgr,
                             Diags, LangOpts, Target.get());
     Preprocessor PP(std::make_shared<PreprocessorOptions>(), Diags, LangOpts,
-                    SourceMgr, PCMCache, HeaderInfo, ModLoader,
-                    /*IILookup =*/nullptr,
+                    SourceMgr, HeaderInfo, ModLoader, /*IILookup =*/nullptr,
                     /*OwnsHeaderSearch =*/false);
     PP.Initialize(*Target);
     PP.EnterMainSourceFile();
diff --git a/unittests/Lex/PPCallbacksTest.cpp b/unittests/Lex/PPCallbacksTest.cpp
index 0841791..064abaf 100644
--- a/unittests/Lex/PPCallbacksTest.cpp
+++ b/unittests/Lex/PPCallbacksTest.cpp
@@ -14,7 +14,6 @@
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/LangOptions.h"
-#include "clang/Basic/MemoryBufferCache.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Basic/TargetOptions.h"
@@ -162,14 +161,13 @@
     SourceMgr.setMainFileID(SourceMgr.createFileID(std::move(Buf)));
 
     VoidModuleLoader ModLoader;
-    MemoryBufferCache PCMCache;
 
     HeaderSearch HeaderInfo(std::make_shared<HeaderSearchOptions>(), SourceMgr,
                             Diags, LangOpts, Target.get());
     AddFakeHeader(HeaderInfo, HeaderPath, SystemHeader);
 
     Preprocessor PP(std::make_shared<PreprocessorOptions>(), Diags, LangOpts,
-                    SourceMgr, PCMCache, HeaderInfo, ModLoader,
+                    SourceMgr, HeaderInfo, ModLoader,
                     /*IILookup =*/nullptr,
                     /*OwnsHeaderSearch =*/false);
     PP.Initialize(*Target);
@@ -200,12 +198,11 @@
     SourceMgr.setMainFileID(SourceMgr.createFileID(std::move(SourceBuf)));
 
     VoidModuleLoader ModLoader;
-    MemoryBufferCache PCMCache;
     HeaderSearch HeaderInfo(std::make_shared<HeaderSearchOptions>(), SourceMgr,
                             Diags, OpenCLLangOpts, Target.get());
 
     Preprocessor PP(std::make_shared<PreprocessorOptions>(), Diags,
-                    OpenCLLangOpts, SourceMgr, PCMCache, HeaderInfo, ModLoader,
+                    OpenCLLangOpts, SourceMgr, HeaderInfo, ModLoader,
                     /*IILookup =*/nullptr,
                     /*OwnsHeaderSearch =*/false);
     PP.Initialize(*Target);
diff --git a/unittests/Lex/PPConditionalDirectiveRecordTest.cpp b/unittests/Lex/PPConditionalDirectiveRecordTest.cpp
index b635604..dccfffd 100644
--- a/unittests/Lex/PPConditionalDirectiveRecordTest.cpp
+++ b/unittests/Lex/PPConditionalDirectiveRecordTest.cpp
@@ -12,7 +12,6 @@
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/LangOptions.h"
-#include "clang/Basic/MemoryBufferCache.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Basic/TargetOptions.h"
@@ -94,11 +93,10 @@
   SourceMgr.setMainFileID(SourceMgr.createFileID(std::move(Buf)));
 
   VoidModuleLoader ModLoader;
-  MemoryBufferCache PCMCache;
   HeaderSearch HeaderInfo(std::make_shared<HeaderSearchOptions>(), SourceMgr,
                           Diags, LangOpts, Target.get());
   Preprocessor PP(std::make_shared<PreprocessorOptions>(), Diags, LangOpts,
-                  SourceMgr, PCMCache, HeaderInfo, ModLoader,
+                  SourceMgr, HeaderInfo, ModLoader,
                   /*IILookup =*/nullptr,
                   /*OwnsHeaderSearch =*/false);
   PP.Initialize(*Target);