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
14#include "clang/Basic/Builtins.h"
15#include "clang/Basic/TargetInfo.h"
16#include "clang/Frontend/ASTUnit.h"
17#include "clang/Frontend/CompilerInstance.h"
18#include "clang/Frontend/TextDiagnosticPrinter.h"
19#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/PreprocessorOptions.h"
21#include "clang/Parse/ParseAST.h"
22#include "clang/Sema/MultiplexExternalSemaSource.h"
23#include "clang/Serialization/ASTReader.h"
24#include "clang/Serialization/ASTWriter.h"
25#include "llvm/Support/MemoryBuffer.h"
26
27using namespace clang;
28
29namespace {
30class ChainedIncludesSource : public ExternalSemaSource {
31public:
32 ChainedIncludesSource(std::vector<std::unique_ptr<CompilerInstance>> CIs)
33 : CIs(std::move(CIs)) {}
34
35protected:
36 //===--------------------------------------------------------------------===//
37 // ExternalASTSource interface.
38 //===--------------------------------------------------------------------===//
39
40 /// Return the amount of memory used by memory buffers, breaking down
41 /// by heap-backed versus mmap'ed memory.
42 void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override {
43 for (unsigned i = 0, e = CIs.size(); i != e; ++i) {
44 if (const ExternalASTSource *eSrc =
45 CIs[i]->getASTContext().getExternalSource()) {
46 eSrc->getMemoryBufferSizes(sizes);
47 }
48 }
49 }
50
51private:
52 std::vector<std::unique_ptr<CompilerInstance>> CIs;
53};
54} // end anonymous namespace
55
56static llvm::IntrusiveRefCntPtr<ASTReader>
57createASTReader(CompilerInstance &CI, StringRef pchFile,
58 SmallVectorImpl<std::unique_ptr<llvm::MemoryBuffer>> &MemBufs,
59 SmallVectorImpl<std::string> &bufNames,
60 ASTDeserializationListener *deserialListener = nullptr) {
61 Preprocessor &PP = CI.getPreprocessor();
62 auto Reader = llvm::makeIntrusiveRefCnt<ASTReader>(
63 A&: PP, A&: CI.getModuleCache(), A: &CI.getASTContext(), A: CI.getPCHContainerReader(),
64 A&: CI.getCodeGenOpts(),
65 /*Extensions=*/A: ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
66 /*isysroot=*/A: "", A: DisableValidationForModuleKind::PCH);
67 for (unsigned ti = 0; ti < bufNames.size(); ++ti) {
68 StringRef sr(bufNames[ti]);
69 Reader->addInMemoryBuffer(FileName&: sr, Buffer: std::move(MemBufs[ti]));
70 }
71 Reader->setDeserializationListener(Listener: deserialListener);
72 switch (Reader->ReadAST(FileName: pchFile, Type: serialization::MK_PCH, ImportLoc: SourceLocation(),
73 ClientLoadCapabilities: ASTReader::ARR_None)) {
74 case ASTReader::Success:
75 // Set the predefines buffer as suggested by the PCH reader.
76 PP.setPredefines(Reader->getSuggestedPredefines());
77 return Reader;
78
79 case ASTReader::Failure:
80 case ASTReader::Missing:
81 case ASTReader::OutOfDate:
82 case ASTReader::VersionMismatch:
83 case ASTReader::ConfigurationMismatch:
84 case ASTReader::HadErrors:
85 break;
86 }
87 return nullptr;
88}
89
90IntrusiveRefCntPtr<ExternalSemaSource>
91clang::createChainedIncludesSource(CompilerInstance &CI,
92 IntrusiveRefCntPtr<ASTReader> &OutReader) {
93
94 std::vector<std::string> &includes = CI.getPreprocessorOpts().ChainedIncludes;
95 assert(!includes.empty() && "No '-chain-include' in options!");
96
97 std::vector<std::unique_ptr<CompilerInstance>> CIs;
98 InputKind IK = CI.getFrontendOpts().Inputs[0].getKind();
99
100 SmallVector<std::unique_ptr<llvm::MemoryBuffer>, 4> SerialBufs;
101 SmallVector<std::string, 4> serialBufNames;
102
103 for (unsigned i = 0, e = includes.size(); i != e; ++i) {
104 bool firstInclude = (i == 0);
105 std::unique_ptr<CompilerInvocation> CInvok;
106 CInvok.reset(p: new CompilerInvocation(CI.getInvocation()));
107
108 CInvok->getPreprocessorOpts().ChainedIncludes.clear();
109 CInvok->getPreprocessorOpts().ImplicitPCHInclude.clear();
110 CInvok->getPreprocessorOpts().DisablePCHOrModuleValidation =
111 DisableValidationForModuleKind::PCH;
112 CInvok->getPreprocessorOpts().Includes.clear();
113 CInvok->getPreprocessorOpts().MacroIncludes.clear();
114 CInvok->getPreprocessorOpts().Macros.clear();
115
116 CInvok->getFrontendOpts().Inputs.clear();
117 FrontendInputFile InputFile(includes[i], IK);
118 CInvok->getFrontendOpts().Inputs.push_back(Elt: InputFile);
119
120 TextDiagnosticPrinter *DiagClient =
121 new TextDiagnosticPrinter(llvm::errs(), CI.getDiagnosticOpts());
122 auto Diags = llvm::makeIntrusiveRefCnt<DiagnosticsEngine>(
123 A: DiagnosticIDs::create(), A&: CI.getDiagnosticOpts(), A&: DiagClient);
124
125 auto Clang = std::make_unique<CompilerInstance>(
126 args: std::move(CInvok), args: CI.getPCHContainerOperations());
127 // Inherit the VFS as-is: code below does not make changes to the VFS or to
128 // the VFS-affecting options.
129 Clang->setVirtualFileSystem(CI.getVirtualFileSystemPtr());
130 Clang->setDiagnostics(Diags);
131 Clang->setTarget(TargetInfo::CreateTargetInfo(
132 Diags&: Clang->getDiagnostics(), Opts&: Clang->getInvocation().getTargetOpts()));
133 Clang->createFileManager();
134 Clang->createSourceManager();
135 Clang->createPreprocessor(TUKind: TU_Prefix);
136 Clang->getDiagnosticClient().BeginSourceFile(LangOpts: Clang->getLangOpts(),
137 PP: &Clang->getPreprocessor());
138 Clang->createASTContext();
139
140 auto Buffer = std::make_shared<PCHBuffer>();
141 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions;
142 auto consumer = std::make_unique<PCHGenerator>(
143 args&: Clang->getPreprocessor(), args&: Clang->getModuleCache(), args: "-", /*isysroot=*/args: "",
144 args&: Buffer, args&: Clang->getCodeGenOpts(), args&: Extensions,
145 /*AllowASTWithErrors=*/args: true);
146 Clang->getASTContext().setASTMutationListener(
147 consumer->GetASTMutationListener());
148 Clang->setASTConsumer(std::move(consumer));
149 Clang->createSema(TUKind: TU_Prefix, CompletionConsumer: nullptr);
150
151 if (firstInclude) {
152 Preprocessor &PP = Clang->getPreprocessor();
153 PP.getBuiltinInfo().initializeBuiltins(Table&: PP.getIdentifierTable(),
154 LangOpts: PP.getLangOpts());
155 } else {
156 assert(!SerialBufs.empty());
157 SmallVector<std::unique_ptr<llvm::MemoryBuffer>, 4> Bufs;
158 // TODO: Pass through the existing MemoryBuffer instances instead of
159 // allocating new ones.
160 for (auto &SB : SerialBufs)
161 Bufs.push_back(Elt: llvm::MemoryBuffer::getMemBuffer(InputData: SB->getBuffer()));
162 std::string pchName = includes[i-1];
163 llvm::raw_string_ostream os(pchName);
164 os << ".pch" << i-1;
165 serialBufNames.push_back(Elt: pchName);
166
167 IntrusiveRefCntPtr<ASTReader> Reader;
168 Reader = createASTReader(
169 CI&: *Clang, pchFile: pchName, MemBufs&: Bufs, bufNames&: serialBufNames,
170 deserialListener: Clang->getASTConsumer().GetASTDeserializationListener());
171 if (!Reader)
172 return nullptr;
173 Clang->setASTReader(Reader);
174 Clang->getASTContext().setExternalSource(Reader);
175 }
176
177 if (!Clang->InitializeSourceManager(Input: InputFile))
178 return nullptr;
179
180 ParseAST(S&: Clang->getSema());
181 Clang->getDiagnosticClient().EndSourceFile();
182 assert(Buffer->IsComplete && "serialization did not complete");
183 auto &serialAST = Buffer->Data;
184 SerialBufs.push_back(Elt: llvm::MemoryBuffer::getMemBufferCopy(
185 InputData: StringRef(serialAST.data(), serialAST.size())));
186 serialAST.clear();
187 CIs.push_back(x: std::move(Clang));
188 }
189
190 assert(!SerialBufs.empty());
191 std::string pchName = includes.back() + ".pch-final";
192 serialBufNames.push_back(Elt: pchName);
193 OutReader = createASTReader(CI, pchFile: pchName, MemBufs&: SerialBufs, bufNames&: serialBufNames);
194 if (!OutReader)
195 return nullptr;
196
197 auto ChainedSrc =
198 llvm::makeIntrusiveRefCnt<ChainedIncludesSource>(A: std::move(CIs));
199 return llvm::makeIntrusiveRefCnt<MultiplexExternalSemaSource>(
200 A: std::move(ChainedSrc), A&: OutReader);
201}
202