diff --git a/include/clang/Frontend/CompilerInstance.h b/include/clang/Frontend/CompilerInstance.h
index fa20ae4..ba623f2 100644
--- a/include/clang/Frontend/CompilerInstance.h
+++ b/include/clang/Frontend/CompilerInstance.h
@@ -102,6 +102,9 @@ class CompilerInstance : public ModuleLoader {
   /// \brief Non-owning reference to the ASTReader, if one exists.
   ASTReader *ModuleManager;
 
+  /// \brief The dependency file generator.
+  OwningPtr<DependencyFileGenerator> TheDependencyFileGenerator;
+
   /// \brief The set of top-level modules that has already been loaded,
   /// along with the module map
   llvm::DenseMap<const IdentifierInfo *, Module *> KnownModules;
diff --git a/include/clang/Frontend/Utils.h b/include/clang/Frontend/Utils.h
index db52d5c..a9db26d 100644
--- a/include/clang/Frontend/Utils.h
+++ b/include/clang/Frontend/Utils.h
@@ -30,6 +30,7 @@ class ArgList;
 
 namespace clang {
 class ASTConsumer;
+class ASTReader;
 class CompilerInstance;
 class CompilerInvocation;
 class Decl;
@@ -72,10 +73,18 @@ void ProcessWarningOptions(DiagnosticsEngine &Diags,
 void DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream* OS,
                               const PreprocessorOutputOptions &Opts);
 
-/// AttachDependencyFileGen - Create a dependency file generator, and attach
-/// it to the given preprocessor.  This takes ownership of the output stream.
-void AttachDependencyFileGen(Preprocessor &PP,
-                             const DependencyOutputOptions &Opts);
+/// Builds a depdenency file when attached to a Preprocessor (for includes) and
+/// ASTReader (for module imports), and writes it out at the end of processing
+/// a source file.  Users should attach to the ast reader whenever a module is
+/// loaded.
+class DependencyFileGenerator {
+  void *Impl; // Opaque implementation
+  DependencyFileGenerator(void *Impl);
+public:
+  static DependencyFileGenerator *CreateAndAttachToPreprocessor(
+    Preprocessor &PP, const DependencyOutputOptions &Opts);
+  void AttachToASTReader(ASTReader &R);
+};
 
 /// AttachDependencyGraphGen - Create a dependency graph generator, and attach
 /// it to the given preprocessor.
diff --git a/include/clang/Serialization/ASTReader.h b/include/clang/Serialization/ASTReader.h
index 9b92fd8..9f034db 100644
--- a/include/clang/Serialization/ASTReader.h
+++ b/include/clang/Serialization/ASTReader.h
@@ -181,6 +181,36 @@ public:
   virtual bool visitInputFile(StringRef Filename, bool isSystem) { return true;}
 };
 
+/// \brief Simple wrapper class for chaining listeners.
+class ChainedASTReaderListener : public ASTReaderListener {
+  OwningPtr<ASTReaderListener> First;
+  OwningPtr<ASTReaderListener> Second;
+public:
+  ChainedASTReaderListener(ASTReaderListener *First, ASTReaderListener *Second)
+  : First(First), Second(Second) { }
+
+  virtual bool ReadFullVersionInformation(StringRef FullVersion);
+  virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
+                                   bool Complain);
+  virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
+                                 bool Complain);
+  virtual bool ReadDiagnosticOptions(const DiagnosticOptions &DiagOpts,
+                                     bool Complain);
+  virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts,
+                                     bool Complain);
+
+  virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
+                                       bool Complain);
+  virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
+                                       bool Complain,
+                                       std::string &SuggestedPredefines);
+
+  virtual void ReadCounter(const serialization::ModuleFile &M,
+                           unsigned Value);
+  virtual bool needsInputFileVisitation();
+  virtual bool visitInputFile(StringRef Filename, bool isSystem);
+};
+
 /// \brief ASTReaderListener implementation to validate the information of
 /// the PCH file against an initialized Preprocessor.
 class PCHValidator : public ASTReaderListener {
@@ -973,7 +1003,9 @@ private:
   /// \brief Retrieve the file entry and 'overridden' bit for an input
   /// file in the given module file.
   serialization::InputFile getInputFile(ModuleFile &F, unsigned ID,
-                                        bool Complain = true);
+                                        bool Complain = true,
+                                        bool IsSystem = false,
+                                        bool JustVisit = false);
 
   /// \brief Get a FileEntry out of stored-in-PCH filename, making sure we take
   /// into account all the necessary relocations.
@@ -993,7 +1025,8 @@ private:
   };
 
   ASTReadResult ReadASTCore(StringRef FileName, ModuleKind Type,
-                            SourceLocation ImportLoc, ModuleFile *ImportedBy,
+                            SourceLocation ImportLoc, bool IsSystem,
+                            ModuleFile *ImportedBy,
                             SmallVectorImpl<ImportedModule> &Loaded,
                             off_t ExpectedSize, time_t ExpectedModTime,
                             unsigned ClientLoadCapabilities);
@@ -1219,11 +1252,13 @@ public:
   /// \param ImportLoc the location where the module file will be considered as
   /// imported from. For non-module AST types it should be invalid.
   ///
+  /// \param IsSystem whether the AST is from a system file.
+  ///
   /// \param ClientLoadCapabilities The set of client load-failure
   /// capabilities, represented as a bitset of the enumerators of
   /// LoadFailureCapabilities.
   ASTReadResult ReadAST(const std::string &FileName, ModuleKind Type,
-                        SourceLocation ImportLoc,
+                        SourceLocation ImportLoc, bool IsSystem,
                         unsigned ClientLoadCapabilities);
 
   /// \brief Make the entities in the given module and any of its (non-explicit)
@@ -1250,6 +1285,13 @@ public:
     Listener.reset(listener);
   }
 
+  /// \brief Add an AST callbak listener.
+  void addListener(ASTReaderListener *L) {
+    if (Listener)
+      L = new ChainedASTReaderListener(L, Listener.take());
+    Listener.reset(L);
+  }
+
   /// \brief Set the AST deserialization listener.
   void setDeserializationListener(ASTDeserializationListener *Listener);
 
diff --git a/include/clang/Serialization/Module.h b/include/clang/Serialization/Module.h
index f4c0755..06d59b1 100644
--- a/include/clang/Serialization/Module.h
+++ b/include/clang/Serialization/Module.h
@@ -138,6 +138,9 @@ public:
   /// \brief The file entry for the module file.
   const FileEntry *File;
 
+  /// \brief Whether the module is a system module.
+  bool IsSystem;
+
   /// \brief Whether this module has been directly imported by the
   /// user.
   bool DirectlyImported;
diff --git a/include/clang/Serialization/ModuleManager.h b/include/clang/Serialization/ModuleManager.h
index ca643ba..9ee47cf 100644
--- a/include/clang/Serialization/ModuleManager.h
+++ b/include/clang/Serialization/ModuleManager.h
@@ -166,6 +166,8 @@ public:
   ///
   /// \param ImportLoc The location at which the module is imported.
   ///
+  /// \param IsSystem Whether the module is a system module.
+  ///
   /// \param ImportedBy The module that is importing this module, or NULL if
   /// this module is imported directly by the user.
   ///
@@ -186,7 +188,7 @@ public:
   /// \return A pointer to the module that corresponds to this file name,
   /// and a value indicating whether the module was loaded.
   AddModuleResult addModule(StringRef FileName, ModuleKind Type,
-                            SourceLocation ImportLoc,
+                            SourceLocation ImportLoc, bool IsSystem,
                             ModuleFile *ImportedBy, unsigned Generation,
                             off_t ExpectedSize, time_t ExpectedModTime,
                             ModuleFile *&Module,
diff --git a/lib/Frontend/ASTUnit.cpp b/lib/Frontend/ASTUnit.cpp
index 9830455..f2720f9 100644
--- a/lib/Frontend/ASTUnit.cpp
+++ b/lib/Frontend/ASTUnit.cpp
@@ -803,7 +803,7 @@ ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
                                            Counter));
 
   switch (Reader->ReadAST(Filename, serialization::MK_MainFile,
-                          SourceLocation(), ASTReader::ARR_None)) {
+                          SourceLocation(), false, ASTReader::ARR_None)) {
   case ASTReader::Success:
     break;
 
diff --git a/lib/Frontend/ChainedIncludesSource.cpp b/lib/Frontend/ChainedIncludesSource.cpp
index 442177e..0b16dfe 100644
--- a/lib/Frontend/ChainedIncludesSource.cpp
+++ b/lib/Frontend/ChainedIncludesSource.cpp
@@ -40,7 +40,7 @@ static ASTReader *createASTReader(CompilerInstance &CI,
   }
   Reader->setDeserializationListener(deserialListener);
   switch (Reader->ReadAST(pchFile, serialization::MK_PCH, SourceLocation(),
-                          ASTReader::ARR_None)) {
+                          false, ASTReader::ARR_None)) {
   case ASTReader::Success:
     // Set the predefines buffer as suggested by the PCH reader.
     PP.setPredefines(Reader->getSuggestedPredefines());
diff --git a/lib/Frontend/CompilerInstance.cpp b/lib/Frontend/CompilerInstance.cpp
index 0d2af33..1fa0a6b 100644
--- a/lib/Frontend/CompilerInstance.cpp
+++ b/lib/Frontend/CompilerInstance.cpp
@@ -254,7 +254,8 @@ void CompilerInstance::createPreprocessor() {
   // Handle generating dependencies, if requested.
   const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
   if (!DepOpts.OutputFile.empty())
-    AttachDependencyFileGen(*PP, DepOpts);
+    TheDependencyFileGenerator.reset(
+      DependencyFileGenerator::CreateAndAttachToPreprocessor(*PP, DepOpts));
   if (!DepOpts.DOTOutputFile.empty())
     AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
                              getHeaderSearchOpts().Sysroot);
@@ -329,6 +330,7 @@ CompilerInstance::createPCHExternalASTSource(StringRef Path,
                           Preamble ? serialization::MK_Preamble
                                    : serialization::MK_PCH,
                           SourceLocation(),
+                          false,
                           ASTReader::ARR_None)) {
   case ASTReader::Success:
     // Set the predefines buffer as suggested by the PCH reader. Typically, the
@@ -1174,10 +1176,13 @@ CompilerInstance::loadModule(SourceLocation ImportLoc,
         ModuleManager->StartTranslationUnit(&getASTConsumer());
     }
 
+    if (TheDependencyFileGenerator)
+      TheDependencyFileGenerator->AttachToASTReader(*ModuleManager);
+
     // Try to load the module file.
     unsigned ARRFlags = ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing;
     switch (ModuleManager->ReadAST(ModuleFileName, serialization::MK_Module,
-                                   ImportLoc, ARRFlags)) {
+                                   ImportLoc, Module->IsSystem, ARRFlags)) {
     case ASTReader::Success:
       break;
 
@@ -1224,6 +1229,7 @@ CompilerInstance::loadModule(SourceLocation ImportLoc,
       ASTReader::ASTReadResult ReadResult
         = ModuleManager->ReadAST(ModuleFileName,
                                  serialization::MK_Module, ImportLoc,
+                                 Module->IsSystem,
                                  ASTReader::ARR_Missing);
       if (ReadResult != ASTReader::Success) {
         if (ReadResult == ASTReader::Missing) {
diff --git a/lib/Frontend/DependencyFile.cpp b/lib/Frontend/DependencyFile.cpp
index 1e3aba7..6e042f0 100644
--- a/lib/Frontend/DependencyFile.cpp
+++ b/lib/Frontend/DependencyFile.cpp
@@ -20,6 +20,7 @@
 #include "clang/Lex/LexDiagnostic.h"
 #include "clang/Lex/PPCallbacks.h"
 #include "clang/Lex/Preprocessor.h"
+#include "clang/Serialization/ASTReader.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Path.h"
@@ -28,7 +29,8 @@
 using namespace clang;
 
 namespace {
-class DependencyFileCallback : public PPCallbacks {
+/// Private implementation for DependencyFileGenerator
+class DFGImpl : public PPCallbacks {
   std::vector<std::string> Files;
   llvm::StringSet<> FilesSet;
   const Preprocessor *PP;
@@ -41,12 +43,10 @@ class DependencyFileCallback : public PPCallbacks {
 private:
   bool FileMatchesDepCriteria(const char *Filename,
                               SrcMgr::CharacteristicKind FileType);
-  void AddFilename(StringRef Filename);
   void OutputDependencyFile();
 
 public:
-  DependencyFileCallback(const Preprocessor *_PP,
-                         const DependencyOutputOptions &Opts)
+  DFGImpl(const Preprocessor *_PP, const DependencyOutputOptions &Opts)
     : PP(_PP), OutputFile(Opts.OutputFile), Targets(Opts.Targets),
       IncludeSystemHeaders(Opts.IncludeSystemHeaders),
       PhonyTarget(Opts.UsePhonyTargets),
@@ -69,27 +69,51 @@ public:
   virtual void EndOfMainFile() {
     OutputDependencyFile();
   }
+
+  void AddFilename(StringRef Filename);
+  bool includeSystemHeaders() const { return IncludeSystemHeaders; }
+};
+
+class DFGASTReaderListener : public ASTReaderListener {
+  DFGImpl &Parent;
+public:
+  DFGASTReaderListener(DFGImpl &Parent)
+  : Parent(Parent) { }
+  virtual bool needsInputFileVisitation() { return true; }
+  virtual bool visitInputFile(StringRef Filename, bool isSystem);
 };
 }
 
-void clang::AttachDependencyFileGen(Preprocessor &PP,
-                                    const DependencyOutputOptions &Opts) {
+DependencyFileGenerator::DependencyFileGenerator(void *Impl)
+: Impl(Impl) { }
+
+DependencyFileGenerator *DependencyFileGenerator::CreateAndAttachToPreprocessor(
+    clang::Preprocessor &PP, const clang::DependencyOutputOptions &Opts) {
+
   if (Opts.Targets.empty()) {
     PP.getDiagnostics().Report(diag::err_fe_dependency_file_requires_MT);
-    return;
+    return NULL;
   }
 
   // Disable the "file not found" diagnostic if the -MG option was given.
   if (Opts.AddMissingHeaderDeps)
     PP.SetSuppressIncludeNotFoundError(true);
 
-  PP.addPPCallbacks(new DependencyFileCallback(&PP, Opts));
+  DFGImpl *Callback = new DFGImpl(&PP, Opts);
+  PP.addPPCallbacks(Callback); // PP owns the Callback
+  return new DependencyFileGenerator(Callback);
+}
+
+void DependencyFileGenerator::AttachToASTReader(ASTReader &R) {
+  DFGImpl *I = reinterpret_cast<DFGImpl *>(Impl);
+  assert(I && "missing implementation");
+  R.addListener(new DFGASTReaderListener(*I));
 }
 
 /// FileMatchesDepCriteria - Determine whether the given Filename should be
 /// considered as a dependency.
-bool DependencyFileCallback::FileMatchesDepCriteria(const char *Filename,
-                                          SrcMgr::CharacteristicKind FileType) {
+bool DFGImpl::FileMatchesDepCriteria(const char *Filename,
+                                     SrcMgr::CharacteristicKind FileType) {
   if (strcmp("<built-in>", Filename) == 0)
     return false;
 
@@ -99,10 +123,10 @@ bool DependencyFileCallback::FileMatchesDepCriteria(const char *Filename,
   return FileType == SrcMgr::C_User;
 }
 
-void DependencyFileCallback::FileChanged(SourceLocation Loc,
-                                         FileChangeReason Reason,
-                                         SrcMgr::CharacteristicKind FileType,
-                                         FileID PrevFID) {
+void DFGImpl::FileChanged(SourceLocation Loc,
+                          FileChangeReason Reason,
+                          SrcMgr::CharacteristicKind FileType,
+                          FileID PrevFID) {
   if (Reason != PPCallbacks::EnterFile)
     return;
 
@@ -130,15 +154,15 @@ void DependencyFileCallback::FileChanged(SourceLocation Loc,
   AddFilename(Filename);
 }
 
-void DependencyFileCallback::InclusionDirective(SourceLocation HashLoc,
-                                                const Token &IncludeTok,
-                                                StringRef FileName,
-                                                bool IsAngled,
-                                                CharSourceRange FilenameRange,
-                                                const FileEntry *File,
-                                                StringRef SearchPath,
-                                                StringRef RelativePath,
-                                                const Module *Imported) {
+void DFGImpl::InclusionDirective(SourceLocation HashLoc,
+                                 const Token &IncludeTok,
+                                 StringRef FileName,
+                                 bool IsAngled,
+                                 CharSourceRange FilenameRange,
+                                 const FileEntry *File,
+                                 StringRef SearchPath,
+                                 StringRef RelativePath,
+                                 const Module *Imported) {
   if (!File) {
     if (AddMissingHeaderDeps)
       AddFilename(FileName);
@@ -147,7 +171,7 @@ void DependencyFileCallback::InclusionDirective(SourceLocation HashLoc,
   }
 }
 
-void DependencyFileCallback::AddFilename(StringRef Filename) {
+void DFGImpl::AddFilename(StringRef Filename) {
   if (FilesSet.insert(Filename))
     Files.push_back(Filename);
 }
@@ -164,7 +188,7 @@ static void PrintFilename(raw_ostream &OS, StringRef Filename) {
   }
 }
 
-void DependencyFileCallback::OutputDependencyFile() {
+void DFGImpl::OutputDependencyFile() {
   if (SeenMissingHeader) {
     llvm::sys::fs::remove(OutputFile);
     return;
@@ -234,3 +258,10 @@ void DependencyFileCallback::OutputDependencyFile() {
   }
 }
 
+bool DFGASTReaderListener::visitInputFile(llvm::StringRef Filename,
+                                          bool IsSystem) {
+  if (!IsSystem || Parent.includeSystemHeaders())
+    Parent.AddFilename(Filename);
+  return true;
+}
+
diff --git a/lib/Serialization/ASTReader.cpp b/lib/Serialization/ASTReader.cpp
index 10a182f..f929f47 100644
--- a/lib/Serialization/ASTReader.cpp
+++ b/lib/Serialization/ASTReader.cpp
@@ -59,6 +59,52 @@ using namespace clang::serialization;
 using namespace clang::serialization::reader;
 using llvm::BitstreamCursor;
 
+
+//===----------------------------------------------------------------------===//
+// ChainedASTReaderListener implementation
+//===----------------------------------------------------------------------===//
+
+bool ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
+  return First->ReadFullVersionInformation(FullVersion) || Second->ReadFullVersionInformation(FullVersion);
+}
+bool ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
+                                                   bool Complain) {
+  return First->ReadLanguageOptions(LangOpts, Complain) || Second->ReadLanguageOptions(LangOpts, Complain);
+}
+bool ChainedASTReaderListener::ReadTargetOptions(const TargetOptions &TargetOpts,
+                                                 bool Complain) {
+  return First->ReadTargetOptions(TargetOpts, Complain) || Second->ReadTargetOptions(TargetOpts, Complain);
+}
+bool ChainedASTReaderListener::ReadDiagnosticOptions(const DiagnosticOptions &DiagOpts,
+                                                     bool Complain) {
+  return First->ReadDiagnosticOptions(DiagOpts, Complain) || Second->ReadDiagnosticOptions(DiagOpts, Complain);
+}
+bool ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
+                                                     bool Complain) {
+  return First->ReadFileSystemOptions(FSOpts, Complain) || Second->ReadFileSystemOptions(FSOpts, Complain);
+}
+
+bool ChainedASTReaderListener::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
+                                                       bool Complain) {
+  return First->ReadHeaderSearchOptions(HSOpts, Complain) || Second->ReadHeaderSearchOptions(HSOpts, Complain);
+}
+bool ChainedASTReaderListener::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
+                                                       bool Complain,
+                                                       std::string &SuggestedPredefines) {
+  return First->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines) || Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
+}
+void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
+                                           unsigned Value) {
+  First->ReadCounter(M, Value);
+  Second->ReadCounter(M, Value);
+}
+bool ChainedASTReaderListener::needsInputFileVisitation() {
+  return First->needsInputFileVisitation() || Second->needsInputFileVisitation();
+}
+bool ChainedASTReaderListener::visitInputFile(StringRef Filename, bool isSystem) {
+  return First->visitInputFile(Filename, isSystem) || Second->visitInputFile(Filename, isSystem);
+}
+
 //===----------------------------------------------------------------------===//
 // PCH validator implementation
 //===----------------------------------------------------------------------===//
@@ -1633,7 +1679,7 @@ void ASTReader::installImportedMacro(IdentifierInfo *II, MacroDirective *MD,
   PP.appendMacroDirective(II, MD);
 }
 
-InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
+InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain, bool IsSystem, bool JustVisit) {
   // If this ID is bogus, just return an empty input file.
   if (ID == 0 || ID > F.InputFilesLoaded.size())
     return InputFile();
@@ -1665,6 +1711,17 @@ InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
     // Get the file entry for this input file.
     StringRef OrigFilename = Blob;
     std::string Filename = OrigFilename;
+
+    // Visit the input file, if desired
+    bool NeedsVisitation = Listener && Listener->needsInputFileVisitation();
+    if (NeedsVisitation)
+      Listener->visitInputFile(OrigFilename, IsSystem);
+    // Potentially return early
+    if (JustVisit) {
+      assert(NeedsVisitation);
+      return InputFile();
+    }
+
     MaybeAddSystemRootToFilename(F, Filename);
     const FileEntry *File 
       = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
@@ -1827,20 +1884,26 @@ ASTReader::ReadControlBlock(ModuleFile &F,
     case llvm::BitstreamEntry::Error:
       Error("malformed block record in AST file");
       return Failure;
-    case llvm::BitstreamEntry::EndBlock:
-      // Validate all of the non-system input files.
-      if (!DisableValidation) {
+    case llvm::BitstreamEntry::EndBlock: {
+      // Validate all of the non-system input files, and possibly visit all of
+      // them with the listener.
+      bool NeedsInputVisitation = Listener && Listener->needsInputFileVisitation();
+      if (!DisableValidation || NeedsInputVisitation) {
         bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
-        // All user input files reside at the index range [0, Record[1]).
+        unsigned NumInputFiles = Record[0];
+        unsigned NumUserFiles = Record[1];
+        unsigned N = NeedsInputVisitation ? NumInputFiles : NumUserFiles;
         // Record is the one from INPUT_FILE_OFFSETS.
-        for (unsigned I = 0, N = Record[1]; I < N; ++I) {
-          InputFile IF = getInputFile(F, I+1, Complain);
-          if (!IF.getFile() || IF.isOutOfDate())
+        for (unsigned I = 0; I < N; ++I) {
+          bool IsSystem = I >= NumUserFiles;
+          bool JustVisit = DisableValidation || IsSystem;
+          InputFile IF = getInputFile(F, I+1, Complain, F.IsSystem || IsSystem, JustVisit);
+          if (!JustVisit && (!IF.getFile() || IF.isOutOfDate()))
             return OutOfDate;
         }
       }
       return Success;
-      
+    }
     case llvm::BitstreamEntry::SubBlock:
       switch (Entry.ID) {
       case INPUT_FILES_BLOCK_ID:
@@ -1915,8 +1978,8 @@ ASTReader::ReadControlBlock(ModuleFile &F,
         Idx += Length;
 
         // Load the AST file.
-        switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
-                           StoredSize, StoredModTime,
+        switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, F.IsSystem,
+                           &F, Loaded, StoredSize, StoredModTime,
                            ClientLoadCapabilities)) {
         case Failure: return Failure;
           // If we have to ignore the dependency, we'll have to ignore this too.
@@ -2921,6 +2984,7 @@ bool ASTReader::isGlobalIndexUnavailable() const {
 ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
                                             ModuleKind Type,
                                             SourceLocation ImportLoc,
+                                            bool IsSystem,
                                             unsigned ClientLoadCapabilities) {
   llvm::SaveAndRestore<SourceLocation>
     SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
@@ -2931,6 +2995,7 @@ ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
   unsigned NumModules = ModuleMgr.size();
   SmallVector<ImportedModule, 4> Loaded;
   switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
+                                                IsSystem,
                                                 /*ImportedBy=*/0, Loaded,
                                                 0, 0,
                                                 ClientLoadCapabilities)) {
@@ -3083,6 +3148,7 @@ ASTReader::ASTReadResult
 ASTReader::ReadASTCore(StringRef FileName,
                        ModuleKind Type,
                        SourceLocation ImportLoc,
+                       bool IsSystem,
                        ModuleFile *ImportedBy,
                        SmallVectorImpl<ImportedModule> &Loaded,
                        off_t ExpectedSize, time_t ExpectedModTime,
@@ -3090,7 +3156,7 @@ ASTReader::ReadASTCore(StringRef FileName,
   ModuleFile *M;
   std::string ErrorStr;
   ModuleManager::AddModuleResult AddResult
-    = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
+    = ModuleMgr.addModule(FileName, Type, ImportLoc, IsSystem, ImportedBy,
                           CurrentGeneration, ExpectedSize, ExpectedModTime,
                           M, ErrorStr);
 
diff --git a/lib/Serialization/Module.cpp b/lib/Serialization/Module.cpp
index 2eb3971..59134b8 100644
--- a/lib/Serialization/Module.cpp
+++ b/lib/Serialization/Module.cpp
@@ -21,7 +21,7 @@ using namespace serialization;
 using namespace reader;
 
 ModuleFile::ModuleFile(ModuleKind Kind, unsigned Generation)
-  : Kind(Kind), File(0), DirectlyImported(false),
+  : Kind(Kind), File(0), IsSystem(false), DirectlyImported(false),
     Generation(Generation), SizeInBits(0),
     LocalNumSLocEntries(0), SLocEntryBaseID(0),
     SLocEntryBaseOffset(0), SLocEntryOffsets(0),
diff --git a/lib/Serialization/ModuleManager.cpp b/lib/Serialization/ModuleManager.cpp
index 9c4b3d9..c5f3f2a 100644
--- a/lib/Serialization/ModuleManager.cpp
+++ b/lib/Serialization/ModuleManager.cpp
@@ -52,8 +52,8 @@ llvm::MemoryBuffer *ModuleManager::lookupBuffer(StringRef Name) {
 
 ModuleManager::AddModuleResult
 ModuleManager::addModule(StringRef FileName, ModuleKind Type,
-                         SourceLocation ImportLoc, ModuleFile *ImportedBy,
-                         unsigned Generation,
+                         SourceLocation ImportLoc, bool IsSystem,
+                         ModuleFile *ImportedBy, unsigned Generation,
                          off_t ExpectedSize, time_t ExpectedModTime,
                          ModuleFile *&Module,
                          std::string &ErrorStr) {
@@ -82,6 +82,7 @@ ModuleManager::addModule(StringRef FileName, ModuleKind Type,
     New->FileName = FileName.str();
     New->File = Entry;
     New->ImportLoc = ImportLoc;
+    New->IsSystem = IsSystem;
     Chain.push_back(New);
     NewModule = true;
     ModuleEntry = New;
diff --git a/test/Modules/dependency-gen.m b/test/Modules/dependency-gen.m
new file mode 100644
index 0000000..471ce14
--- /dev/null
+++ b/test/Modules/dependency-gen.m
@@ -0,0 +1,20 @@
+// RUN: rm -rf %t-mcp
+// RUN: mkdir -p %t-mcp
+
+// RUN: %clang_cc1 -x objective-c -dependency-file %t.d.1 -MT %s.o -I %S/Inputs -fsyntax-only -fmodules -fmodules-cache-path=%t-mcp %s
+// RUN: FileCheck %s < %t.d.1
+// CHECK: dependency-gen.m
+// CHECK: Inputs/diamond_top.h
+// CHECK: Inputs/module.map
+// CHECK-NOT: string.h
+
+
+// RUN: %clang_cc1 -x objective-c -dependency-file %t.d.2 -MT %s.o -I %S/Inputs -sys-header-deps -fsyntax-only -fmodules -fmodules-cache-path=%t-mcp %s
+// RUN: FileCheck %s -check-prefix=CHECK-SYS < %t.d.2
+// CHECK-SYS: dependency-gen.m
+// CHECK-SYS: Inputs/diamond_top.h
+// CHECK-SYS: Inputs/module.map
+// CHECK-SYS: string.h
+
+#import "diamond_top.h"
+#import "string.h"
