clang 23.0.0git
ChainedIncludesSource.cpp
Go to the documentation of this file.
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
27#include "llvm/Support/MemoryBuffer.h"
28
29using namespace clang;
30
31namespace {
32class ChainedIncludesSource : public ExternalSemaSource {
33public:
34 ChainedIncludesSource(std::vector<std::unique_ptr<CompilerInstance>> CIs)
35 : CIs(std::move(CIs)) {}
36
37protected:
38 //===--------------------------------------------------------------------===//
39 // ExternalASTSource interface.
40 //===--------------------------------------------------------------------===//
41
42 /// Return the amount of memory used by memory buffers, breaking down
43 /// by heap-backed versus mmap'ed memory.
44 void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override {
45 for (unsigned i = 0, e = CIs.size(); i != e; ++i) {
46 if (const ExternalASTSource *eSrc =
47 CIs[i]->getASTContext().getExternalSource()) {
48 eSrc->getMemoryBufferSizes(sizes);
49 }
50 }
51 }
52
53private:
54 std::vector<std::unique_ptr<CompilerInstance>> CIs;
55};
56} // end anonymous namespace
57
59createASTReader(CompilerInstance &CI, StringRef pchFile,
60 SmallVectorImpl<std::unique_ptr<llvm::MemoryBuffer>> &MemBufs,
62 ASTDeserializationListener *deserialListener = nullptr) {
64 auto Reader = llvm::makeIntrusiveRefCnt<ASTReader>(
66 CI.getCodeGenOpts(),
67 /*Extensions=*/ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
69 for (unsigned ti = 0; ti < bufNames.size(); ++ti) {
70 off_t MemBufSize = MemBufs[ti]->getBufferSize();
72 bufNames[ti], std::move(MemBufs[ti]), MemBufSize, /*ModTime=*/0);
73 }
74 Reader->setDeserializationListener(deserialListener);
75 switch (Reader->ReadAST(ModuleFileName::makeInMemory(pchFile),
79 // Set the predefines buffer as suggested by the PCH reader.
80 PP.setPredefines(Reader->getSuggestedPredefines());
81 return Reader;
82
89 break;
90 }
91 return nullptr;
92}
93
97
98 std::vector<std::string> &includes = CI.getPreprocessorOpts().ChainedIncludes;
99 assert(!includes.empty() && "No '-chain-include' in options!");
100
101 std::vector<std::unique_ptr<CompilerInstance>> CIs;
102 InputKind IK = CI.getFrontendOpts().Inputs[0].getKind();
103
105 SmallVector<std::string, 4> serialBufNames;
106
107 for (unsigned i = 0, e = includes.size(); i != e; ++i) {
108 bool firstInclude = (i == 0);
109 std::unique_ptr<CompilerInvocation> CInvok;
110 CInvok.reset(new CompilerInvocation(CI.getInvocation()));
111
112 CInvok->getPreprocessorOpts().ChainedIncludes.clear();
113 CInvok->getPreprocessorOpts().ImplicitPCHInclude.clear();
114 CInvok->getPreprocessorOpts().DisablePCHOrModuleValidation =
116 CInvok->getPreprocessorOpts().Includes.clear();
117 CInvok->getPreprocessorOpts().MacroIncludes.clear();
118 CInvok->getPreprocessorOpts().Macros.clear();
119
120 CInvok->getFrontendOpts().Inputs.clear();
121 FrontendInputFile InputFile(includes[i], IK);
122 CInvok->getFrontendOpts().Inputs.push_back(InputFile);
123
124 TextDiagnosticPrinter *DiagClient =
125 new TextDiagnosticPrinter(llvm::errs(), CI.getDiagnosticOpts());
126 auto Diags = llvm::makeIntrusiveRefCnt<DiagnosticsEngine>(
127 DiagnosticIDs::create(), CI.getDiagnosticOpts(), DiagClient);
128
129 auto Clang = std::make_unique<CompilerInstance>(
130 std::move(CInvok), CI.getPCHContainerOperations());
131 // Inherit the VFS as-is: code below does not make changes to the VFS or to
132 // the VFS-affecting options.
133 Clang->setVirtualFileSystem(CI.getVirtualFileSystemPtr());
134 Clang->setDiagnostics(Diags);
135 Clang->setTarget(TargetInfo::CreateTargetInfo(
136 Clang->getDiagnostics(), Clang->getInvocation().getTargetOpts()));
137 Clang->createFileManager();
138 Clang->createSourceManager();
139 Clang->createPreprocessor(TU_Prefix);
140 Clang->getDiagnosticClient().BeginSourceFile(Clang->getLangOpts(),
141 &Clang->getPreprocessor());
142 Clang->createASTContext();
143
144 auto Buffer = std::make_shared<PCHBuffer>();
146 auto consumer = std::make_unique<PCHGenerator>(
147 Clang->getPreprocessor(), Clang->getModuleCache(), "-", /*isysroot=*/"",
148 Buffer, Clang->getCodeGenOpts(), Extensions,
149 /*AllowASTWithErrors=*/true);
150 Clang->getASTContext().setASTMutationListener(
151 consumer->GetASTMutationListener());
152 Clang->setASTConsumer(std::move(consumer));
153 Clang->createSema(TU_Prefix, nullptr);
154
155 if (firstInclude) {
156 Preprocessor &PP = Clang->getPreprocessor();
158 PP.getLangOpts());
159 } else {
160 assert(!SerialBufs.empty());
162 // TODO: Pass through the existing MemoryBuffer instances instead of
163 // allocating new ones.
164 for (auto &SB : SerialBufs)
165 Bufs.push_back(llvm::MemoryBuffer::getMemBuffer(SB->getBuffer()));
166 std::string pchName = includes[i-1];
167 llvm::raw_string_ostream os(pchName);
168 os << ".pch" << i-1;
169 serialBufNames.push_back(pchName);
170
172 Reader = createASTReader(
173 *Clang, pchName, Bufs, serialBufNames,
174 Clang->getASTConsumer().GetASTDeserializationListener());
175 if (!Reader)
176 return nullptr;
177 Clang->setASTReader(Reader);
178 Clang->getASTContext().setExternalSource(Reader);
179 }
180
181 if (!Clang->InitializeSourceManager(InputFile))
182 return nullptr;
183
184 ParseAST(Clang->getSema());
185 Clang->getDiagnosticClient().EndSourceFile();
186 assert(Buffer->IsComplete && "serialization did not complete");
187 auto &serialAST = Buffer->Data;
188 SerialBufs.push_back(llvm::MemoryBuffer::getMemBufferCopy(
189 StringRef(serialAST.data(), serialAST.size())));
190 serialAST.clear();
191 CIs.push_back(std::move(Clang));
192 }
193
194 assert(!SerialBufs.empty());
195 std::string pchName = includes.back() + ".pch-final";
196 serialBufNames.push_back(pchName);
197 OutReader = createASTReader(CI, pchName, SerialBufs, serialBufNames);
198 if (!OutReader)
199 return nullptr;
200
201 auto ChainedSrc =
202 llvm::makeIntrusiveRefCnt<ChainedIncludesSource>(std::move(CIs));
203 return llvm::makeIntrusiveRefCnt<MultiplexExternalSemaSource>(
204 std::move(ChainedSrc), OutReader);
205}
Defines enum values for all the target-independent builtin functions.
static llvm::IntrusiveRefCntPtr< ASTReader > createASTReader(CompilerInstance &CI, StringRef pchFile, SmallVectorImpl< std::unique_ptr< llvm::MemoryBuffer > > &MemBufs, SmallVectorImpl< std::string > &bufNames, ASTDeserializationListener *deserialListener=nullptr)
Defines the clang::Preprocessor interface.
@ ARR_None
The client can't handle any AST loading failures.
Definition ASTReader.h:1821
@ Success
The control block was read successfully.
Definition ASTReader.h:450
@ ConfigurationMismatch
The AST file was written with a different language/target configuration.
Definition ASTReader.h:467
@ OutOfDate
The AST file is out-of-date relative to its input files, and needs to be regenerated.
Definition ASTReader.h:460
@ Failure
The AST file itself appears corrupted.
Definition ASTReader.h:453
@ VersionMismatch
The AST file was written by a different version of Clang.
Definition ASTReader.h:463
@ HadErrors
The AST file has errors.
Definition ASTReader.h:470
@ Missing
The AST file was missing.
Definition ASTReader.h:456
void initializeBuiltins(IdentifierTable &Table, const LangOptions &LangOpts)
Mark the identifiers for all the builtins with their appropriate builtin ID # and mark any non-portab...
Definition Builtins.cpp:296
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
const PCHContainerReader & getPCHContainerReader() const
Return the appropriate PCHContainerReader depending on the current CodeGenOptions.
ModuleCache & getModuleCache() const
Preprocessor & getPreprocessor() const
Return the current preprocessor.
ASTContext & getASTContext() const
IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
FrontendOptions & getFrontendOpts()
CompilerInvocation & getInvocation()
PreprocessorOptions & getPreprocessorOpts()
std::shared_ptr< PCHContainerOperations > getPCHContainerOperations() const
DiagnosticOptions & getDiagnosticOpts()
CodeGenOptions & getCodeGenOpts()
Helper class for holding the data necessary to invoke the compiler.
static llvm::IntrusiveRefCntPtr< DiagnosticIDs > create()
An abstract interface that should be implemented by external AST sources that also provide informatio...
An input file for the front end.
SmallVector< FrontendInputFile, 0 > Inputs
The input files and their types.
llvm::MemoryBuffer & addBuiltPCM(llvm::StringRef Filename, std::unique_ptr< llvm::MemoryBuffer > Buffer, off_t Size, time_t ModTime)
Store a just-built PCM under the Filename.
The kind of a file that we've been handed as an input.
virtual InMemoryModuleCache & getInMemoryModuleCache()=0
Returns this process's view of the module cache.
static ModuleFileName makeInMemory(StringRef Name)
Creates a file name for an in-memory module.
Definition Module.h:134
std::vector< std::string > ChainedIncludes
Headers that will be converted to chained PCHs in memory.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
void setPredefines(std::string P)
Set the predefines for this Preprocessor.
IdentifierTable & getIdentifierTable()
Builtin::Context & getBuiltinInfo()
const LangOptions & getLangOpts() const
Encodes a location in the source.
static TargetInfo * CreateTargetInfo(DiagnosticsEngine &Diags, TargetOptions &Opts)
Construct a target for the given options.
Definition Targets.cpp:840
Defines the clang::TargetInfo interface.
@ MK_PCH
File is a PCH file treated as such.
Definition ModuleFile.h:52
The JSON file list parser is used to communicate input to InstallAPI.
void ParseAST(Preprocessor &pp, ASTConsumer *C, ASTContext &Ctx, bool PrintStats=false, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr, bool SkipFunctionBodies=false)
Parse the entire file specified, notifying the ASTConsumer as the file is parsed.
Definition ParseAST.cpp:99
IntrusiveRefCntPtr< ExternalSemaSource > createChainedIncludesSource(CompilerInstance &CI, IntrusiveRefCntPtr< ASTReader > &OutReader)
The ChainedIncludesSource class converts headers to chained PCHs in memory, mainly for testing.
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
@ PCH
Disable validation for a precompiled header and the modules it depends on.