ChainedIncludesSource.cpp 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. //===- ChainedIncludesSource.cpp - Chained PCHs in Memory -------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines the ChainedIncludesSource class, which converts headers
  10. // to chained PCHs in memory, mainly used for testing.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Basic/Builtins.h"
  14. #include "clang/Basic/TargetInfo.h"
  15. #include "clang/Frontend/ASTUnit.h"
  16. #include "clang/Frontend/CompilerInstance.h"
  17. #include "clang/Frontend/TextDiagnosticPrinter.h"
  18. #include "clang/Lex/Preprocessor.h"
  19. #include "clang/Lex/PreprocessorOptions.h"
  20. #include "clang/Parse/ParseAST.h"
  21. #include "clang/Sema/MultiplexExternalSemaSource.h"
  22. #include "clang/Serialization/ASTReader.h"
  23. #include "clang/Serialization/ASTWriter.h"
  24. #include "llvm/Support/MemoryBuffer.h"
  25. using namespace clang;
  26. namespace {
  27. class ChainedIncludesSource : public ExternalSemaSource {
  28. public:
  29. ChainedIncludesSource(std::vector<std::unique_ptr<CompilerInstance>> CIs)
  30. : CIs(std::move(CIs)) {}
  31. protected:
  32. //===--------------------------------------------------------------------===//
  33. // ExternalASTSource interface.
  34. //===--------------------------------------------------------------------===//
  35. /// Return the amount of memory used by memory buffers, breaking down
  36. /// by heap-backed versus mmap'ed memory.
  37. void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override {
  38. for (unsigned i = 0, e = CIs.size(); i != e; ++i) {
  39. if (const ExternalASTSource *eSrc =
  40. CIs[i]->getASTContext().getExternalSource()) {
  41. eSrc->getMemoryBufferSizes(sizes);
  42. }
  43. }
  44. }
  45. private:
  46. std::vector<std::unique_ptr<CompilerInstance>> CIs;
  47. };
  48. } // end anonymous namespace
  49. static ASTReader *
  50. createASTReader(CompilerInstance &CI, StringRef pchFile,
  51. SmallVectorImpl<std::unique_ptr<llvm::MemoryBuffer>> &MemBufs,
  52. SmallVectorImpl<std::string> &bufNames,
  53. ASTDeserializationListener *deserialListener = nullptr) {
  54. Preprocessor &PP = CI.getPreprocessor();
  55. std::unique_ptr<ASTReader> Reader;
  56. Reader.reset(new ASTReader(
  57. PP, CI.getModuleCache(), &CI.getASTContext(), CI.getPCHContainerReader(),
  58. /*Extensions=*/{},
  59. /*isysroot=*/"", DisableValidationForModuleKind::PCH));
  60. for (unsigned ti = 0; ti < bufNames.size(); ++ti) {
  61. StringRef sr(bufNames[ti]);
  62. Reader->addInMemoryBuffer(sr, std::move(MemBufs[ti]));
  63. }
  64. Reader->setDeserializationListener(deserialListener);
  65. switch (Reader->ReadAST(pchFile, serialization::MK_PCH, SourceLocation(),
  66. ASTReader::ARR_None)) {
  67. case ASTReader::Success:
  68. // Set the predefines buffer as suggested by the PCH reader.
  69. PP.setPredefines(Reader->getSuggestedPredefines());
  70. return Reader.release();
  71. case ASTReader::Failure:
  72. case ASTReader::Missing:
  73. case ASTReader::OutOfDate:
  74. case ASTReader::VersionMismatch:
  75. case ASTReader::ConfigurationMismatch:
  76. case ASTReader::HadErrors:
  77. break;
  78. }
  79. return nullptr;
  80. }
  81. IntrusiveRefCntPtr<ExternalSemaSource> clang::createChainedIncludesSource(
  82. CompilerInstance &CI, IntrusiveRefCntPtr<ExternalSemaSource> &Reader) {
  83. std::vector<std::string> &includes = CI.getPreprocessorOpts().ChainedIncludes;
  84. assert(!includes.empty() && "No '-chain-include' in options!");
  85. std::vector<std::unique_ptr<CompilerInstance>> CIs;
  86. InputKind IK = CI.getFrontendOpts().Inputs[0].getKind();
  87. SmallVector<std::unique_ptr<llvm::MemoryBuffer>, 4> SerialBufs;
  88. SmallVector<std::string, 4> serialBufNames;
  89. for (unsigned i = 0, e = includes.size(); i != e; ++i) {
  90. bool firstInclude = (i == 0);
  91. std::unique_ptr<CompilerInvocation> CInvok;
  92. CInvok.reset(new CompilerInvocation(CI.getInvocation()));
  93. CInvok->getPreprocessorOpts().ChainedIncludes.clear();
  94. CInvok->getPreprocessorOpts().ImplicitPCHInclude.clear();
  95. CInvok->getPreprocessorOpts().DisablePCHOrModuleValidation =
  96. DisableValidationForModuleKind::PCH;
  97. CInvok->getPreprocessorOpts().Includes.clear();
  98. CInvok->getPreprocessorOpts().MacroIncludes.clear();
  99. CInvok->getPreprocessorOpts().Macros.clear();
  100. CInvok->getFrontendOpts().Inputs.clear();
  101. FrontendInputFile InputFile(includes[i], IK);
  102. CInvok->getFrontendOpts().Inputs.push_back(InputFile);
  103. TextDiagnosticPrinter *DiagClient =
  104. new TextDiagnosticPrinter(llvm::errs(), new DiagnosticOptions());
  105. IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
  106. IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
  107. new DiagnosticsEngine(DiagID, &CI.getDiagnosticOpts(), DiagClient));
  108. std::unique_ptr<CompilerInstance> Clang(
  109. new CompilerInstance(CI.getPCHContainerOperations()));
  110. Clang->setInvocation(std::move(CInvok));
  111. Clang->setDiagnostics(Diags.get());
  112. Clang->setTarget(TargetInfo::CreateTargetInfo(
  113. Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
  114. Clang->createFileManager();
  115. Clang->createSourceManager(Clang->getFileManager());
  116. Clang->createPreprocessor(TU_Prefix);
  117. Clang->getDiagnosticClient().BeginSourceFile(Clang->getLangOpts(),
  118. &Clang->getPreprocessor());
  119. Clang->createASTContext();
  120. auto Buffer = std::make_shared<PCHBuffer>();
  121. ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions;
  122. auto consumer = std::make_unique<PCHGenerator>(
  123. Clang->getPreprocessor(), Clang->getModuleCache(), "-", /*isysroot=*/"",
  124. Buffer, Extensions, /*AllowASTWithErrors=*/true);
  125. Clang->getASTContext().setASTMutationListener(
  126. consumer->GetASTMutationListener());
  127. Clang->setASTConsumer(std::move(consumer));
  128. Clang->createSema(TU_Prefix, nullptr);
  129. if (firstInclude) {
  130. Preprocessor &PP = Clang->getPreprocessor();
  131. PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
  132. PP.getLangOpts());
  133. } else {
  134. assert(!SerialBufs.empty());
  135. SmallVector<std::unique_ptr<llvm::MemoryBuffer>, 4> Bufs;
  136. // TODO: Pass through the existing MemoryBuffer instances instead of
  137. // allocating new ones.
  138. for (auto &SB : SerialBufs)
  139. Bufs.push_back(llvm::MemoryBuffer::getMemBuffer(SB->getBuffer()));
  140. std::string pchName = includes[i-1];
  141. llvm::raw_string_ostream os(pchName);
  142. os << ".pch" << i-1;
  143. serialBufNames.push_back(os.str());
  144. IntrusiveRefCntPtr<ASTReader> Reader;
  145. Reader = createASTReader(
  146. *Clang, pchName, Bufs, serialBufNames,
  147. Clang->getASTConsumer().GetASTDeserializationListener());
  148. if (!Reader)
  149. return nullptr;
  150. Clang->setASTReader(Reader);
  151. Clang->getASTContext().setExternalSource(Reader);
  152. }
  153. if (!Clang->InitializeSourceManager(InputFile))
  154. return nullptr;
  155. ParseAST(Clang->getSema());
  156. Clang->getDiagnosticClient().EndSourceFile();
  157. assert(Buffer->IsComplete && "serialization did not complete");
  158. auto &serialAST = Buffer->Data;
  159. SerialBufs.push_back(llvm::MemoryBuffer::getMemBufferCopy(
  160. StringRef(serialAST.data(), serialAST.size())));
  161. serialAST.clear();
  162. CIs.push_back(std::move(Clang));
  163. }
  164. assert(!SerialBufs.empty());
  165. std::string pchName = includes.back() + ".pch-final";
  166. serialBufNames.push_back(pchName);
  167. Reader = createASTReader(CI, pchName, SerialBufs, serialBufNames);
  168. if (!Reader)
  169. return nullptr;
  170. auto ChainedSrc =
  171. llvm::makeIntrusiveRefCnt<ChainedIncludesSource>(std::move(CIs));
  172. return llvm::makeIntrusiveRefCnt<MultiplexExternalSemaSource>(
  173. ChainedSrc.get(), Reader.get());
  174. }