1200b3289SIlya Biryukov //===--- PrecompiledPreamble.cpp - Build precompiled preambles --*- C++ -*-===//
2200b3289SIlya Biryukov //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6200b3289SIlya Biryukov //
7200b3289SIlya Biryukov //===----------------------------------------------------------------------===//
8200b3289SIlya Biryukov //
9200b3289SIlya Biryukov // Helper class to build precompiled preamble.
10200b3289SIlya Biryukov //
11200b3289SIlya Biryukov //===----------------------------------------------------------------------===//
12200b3289SIlya Biryukov
13200b3289SIlya Biryukov #include "clang/Frontend/PrecompiledPreamble.h"
14e08464fbSReid Kleckner #include "clang/Basic/FileManager.h"
1509d890d7SRainer Orth #include "clang/Basic/LangStandard.h"
16200b3289SIlya Biryukov #include "clang/Frontend/CompilerInstance.h"
17200b3289SIlya Biryukov #include "clang/Frontend/CompilerInvocation.h"
18200b3289SIlya Biryukov #include "clang/Frontend/FrontendActions.h"
19200b3289SIlya Biryukov #include "clang/Frontend/FrontendOptions.h"
20615673f3SSam McCall #include "clang/Lex/HeaderSearch.h"
21200b3289SIlya Biryukov #include "clang/Lex/Lexer.h"
229e012e8bSKadir Cetinkaya #include "clang/Lex/Preprocessor.h"
23200b3289SIlya Biryukov #include "clang/Lex/PreprocessorOptions.h"
24200b3289SIlya Biryukov #include "clang/Serialization/ASTWriter.h"
25615673f3SSam McCall #include "llvm/ADT/SmallString.h"
26200b3289SIlya Biryukov #include "llvm/ADT/StringSet.h"
27615673f3SSam McCall #include "llvm/ADT/iterator_range.h"
28dd9ea751SIlya Biryukov #include "llvm/Config/llvm-config.h"
29200b3289SIlya Biryukov #include "llvm/Support/CrashRecoveryContext.h"
30200b3289SIlya Biryukov #include "llvm/Support/FileSystem.h"
31615673f3SSam McCall #include "llvm/Support/Path.h"
32b88de416SIlya Biryukov #include "llvm/Support/Process.h"
33fc51490bSJonas Devlieghere #include "llvm/Support/VirtualFileSystem.h"
34923e3388SIlya Biryukov #include <limits>
353d5360a4SBenjamin Kramer #include <mutex>
36417085acSIlya Biryukov #include <utility>
37417085acSIlya Biryukov
38200b3289SIlya Biryukov using namespace clang;
39200b3289SIlya Biryukov
40200b3289SIlya Biryukov namespace {
41200b3289SIlya Biryukov
getInMemoryPreamblePath()42417085acSIlya Biryukov StringRef getInMemoryPreamblePath() {
43417085acSIlya Biryukov #if defined(LLVM_ON_UNIX)
44417085acSIlya Biryukov return "/__clang_tmp/___clang_inmemory_preamble___";
451865df49SNico Weber #elif defined(_WIN32)
46417085acSIlya Biryukov return "C:\\__clang_tmp\\___clang_inmemory_preamble___";
47417085acSIlya Biryukov #else
48417085acSIlya Biryukov #warning "Unknown platform. Defaulting to UNIX-style paths for in-memory PCHs"
49417085acSIlya Biryukov return "/__clang_tmp/___clang_inmemory_preamble___";
50417085acSIlya Biryukov #endif
51417085acSIlya Biryukov }
52417085acSIlya Biryukov
53fc51490bSJonas Devlieghere IntrusiveRefCntPtr<llvm::vfs::FileSystem>
createVFSOverlayForPreamblePCH(StringRef PCHFilename,std::unique_ptr<llvm::MemoryBuffer> PCHBuffer,IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)54417085acSIlya Biryukov createVFSOverlayForPreamblePCH(StringRef PCHFilename,
55417085acSIlya Biryukov std::unique_ptr<llvm::MemoryBuffer> PCHBuffer,
56fc51490bSJonas Devlieghere IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
57417085acSIlya Biryukov // We want only the PCH file from the real filesystem to be available,
58417085acSIlya Biryukov // so we create an in-memory VFS with just that and overlay it on top.
59fc51490bSJonas Devlieghere IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> PCHFS(
60fc51490bSJonas Devlieghere new llvm::vfs::InMemoryFileSystem());
61417085acSIlya Biryukov PCHFS->addFile(PCHFilename, 0, std::move(PCHBuffer));
62fc51490bSJonas Devlieghere IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> Overlay(
63fc51490bSJonas Devlieghere new llvm::vfs::OverlayFileSystem(VFS));
64417085acSIlya Biryukov Overlay->pushOverlay(PCHFS);
65417085acSIlya Biryukov return Overlay;
66417085acSIlya Biryukov }
67417085acSIlya Biryukov
68e5801b02SIlya Biryukov class PreambleDependencyCollector : public DependencyCollector {
69e5801b02SIlya Biryukov public:
70e5801b02SIlya Biryukov // We want to collect all dependencies for correctness. Avoiding the real
71e5801b02SIlya Biryukov // system dependencies (e.g. stl from /usr/lib) would probably be a good idea,
72e5801b02SIlya Biryukov // but there is no way to distinguish between those and the ones that can be
73e5801b02SIlya Biryukov // spuriously added by '-isystem' (e.g. to suppress warnings from those
74e5801b02SIlya Biryukov // headers).
needSystemDependencies()75e5801b02SIlya Biryukov bool needSystemDependencies() override { return true; }
76e5801b02SIlya Biryukov };
77e5801b02SIlya Biryukov
78615673f3SSam McCall // Collects files whose existence would invalidate the preamble.
79615673f3SSam McCall // Collecting *all* of these would make validating it too slow though, so we
80615673f3SSam McCall // just find all the candidates for 'file not found' diagnostics.
81615673f3SSam McCall //
82615673f3SSam McCall // A caveat that may be significant for generated files: we'll omit files under
83615673f3SSam McCall // search path entries whose roots don't exist when the preamble is built.
84615673f3SSam McCall // These are pruned by InitHeaderSearch and so we don't see the search path.
85615673f3SSam McCall // It would be nice to include them but we don't want to duplicate all the rest
86615673f3SSam McCall // of the InitHeaderSearch logic to reconstruct them.
87615673f3SSam McCall class MissingFileCollector : public PPCallbacks {
88615673f3SSam McCall llvm::StringSet<> &Out;
89615673f3SSam McCall const HeaderSearch &Search;
90615673f3SSam McCall const SourceManager &SM;
91615673f3SSam McCall
92615673f3SSam McCall public:
MissingFileCollector(llvm::StringSet<> & Out,const HeaderSearch & Search,const SourceManager & SM)93615673f3SSam McCall MissingFileCollector(llvm::StringSet<> &Out, const HeaderSearch &Search,
94615673f3SSam McCall const SourceManager &SM)
95615673f3SSam McCall : Out(Out), Search(Search), SM(SM) {}
96615673f3SSam McCall
InclusionDirective(SourceLocation HashLoc,const Token & IncludeTok,StringRef FileName,bool IsAngled,CharSourceRange FilenameRange,Optional<FileEntryRef> File,StringRef SearchPath,StringRef RelativePath,const Module * Imported,SrcMgr::CharacteristicKind FileType)97615673f3SSam McCall void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
98615673f3SSam McCall StringRef FileName, bool IsAngled,
99d79ad2f1SJan Svoboda CharSourceRange FilenameRange,
100d79ad2f1SJan Svoboda Optional<FileEntryRef> File, StringRef SearchPath,
101d79ad2f1SJan Svoboda StringRef RelativePath, const Module *Imported,
102615673f3SSam McCall SrcMgr::CharacteristicKind FileType) override {
103d79ad2f1SJan Svoboda // File is None if it wasn't found.
104615673f3SSam McCall // (We have some false negatives if PP recovered e.g. <foo> -> "foo")
105d79ad2f1SJan Svoboda if (File)
106615673f3SSam McCall return;
107615673f3SSam McCall
108615673f3SSam McCall // If it's a rare absolute include, we know the full path already.
109615673f3SSam McCall if (llvm::sys::path::is_absolute(FileName)) {
110615673f3SSam McCall Out.insert(FileName);
111615673f3SSam McCall return;
112615673f3SSam McCall }
113615673f3SSam McCall
114615673f3SSam McCall // Reconstruct the filenames that would satisfy this directive...
115615673f3SSam McCall llvm::SmallString<256> Buf;
116615673f3SSam McCall auto NotFoundRelativeTo = [&](const DirectoryEntry *DE) {
117615673f3SSam McCall Buf = DE->getName();
118615673f3SSam McCall llvm::sys::path::append(Buf, FileName);
119615673f3SSam McCall llvm::sys::path::remove_dots(Buf, /*remove_dot_dot=*/true);
120615673f3SSam McCall Out.insert(Buf);
121615673f3SSam McCall };
122615673f3SSam McCall // ...relative to the including file.
123615673f3SSam McCall if (!IsAngled) {
124615673f3SSam McCall if (const FileEntry *IncludingFile =
125615673f3SSam McCall SM.getFileEntryForID(SM.getFileID(IncludeTok.getLocation())))
126615673f3SSam McCall if (IncludingFile->getDir())
127615673f3SSam McCall NotFoundRelativeTo(IncludingFile->getDir());
128615673f3SSam McCall }
129615673f3SSam McCall // ...relative to the search paths.
130615673f3SSam McCall for (const auto &Dir : llvm::make_range(
131615673f3SSam McCall IsAngled ? Search.angled_dir_begin() : Search.search_dir_begin(),
132615673f3SSam McCall Search.search_dir_end())) {
133615673f3SSam McCall // No support for frameworks or header maps yet.
134615673f3SSam McCall if (Dir.isNormalDir())
135615673f3SSam McCall NotFoundRelativeTo(Dir.getDir());
136615673f3SSam McCall }
137615673f3SSam McCall }
138615673f3SSam McCall };
139615673f3SSam McCall
140200b3289SIlya Biryukov /// Keeps a track of files to be deleted in destructor.
141200b3289SIlya Biryukov class TemporaryFiles {
142200b3289SIlya Biryukov public:
143200b3289SIlya Biryukov // A static instance to be used by all clients.
144200b3289SIlya Biryukov static TemporaryFiles &getInstance();
145200b3289SIlya Biryukov
146200b3289SIlya Biryukov private:
147200b3289SIlya Biryukov // Disallow constructing the class directly.
148200b3289SIlya Biryukov TemporaryFiles() = default;
149200b3289SIlya Biryukov // Disallow copy.
150200b3289SIlya Biryukov TemporaryFiles(const TemporaryFiles &) = delete;
151200b3289SIlya Biryukov
152200b3289SIlya Biryukov public:
153200b3289SIlya Biryukov ~TemporaryFiles();
154200b3289SIlya Biryukov
155200b3289SIlya Biryukov /// Adds \p File to a set of tracked files.
156200b3289SIlya Biryukov void addFile(StringRef File);
157200b3289SIlya Biryukov
158200b3289SIlya Biryukov /// Remove \p File from disk and from the set of tracked files.
159200b3289SIlya Biryukov void removeFile(StringRef File);
160200b3289SIlya Biryukov
161200b3289SIlya Biryukov private:
162762bc335SBenjamin Kramer std::mutex Mutex;
163200b3289SIlya Biryukov llvm::StringSet<> Files;
164200b3289SIlya Biryukov };
165200b3289SIlya Biryukov
getInstance()166200b3289SIlya Biryukov TemporaryFiles &TemporaryFiles::getInstance() {
167200b3289SIlya Biryukov static TemporaryFiles Instance;
168200b3289SIlya Biryukov return Instance;
169200b3289SIlya Biryukov }
170200b3289SIlya Biryukov
~TemporaryFiles()171200b3289SIlya Biryukov TemporaryFiles::~TemporaryFiles() {
172762bc335SBenjamin Kramer std::lock_guard<std::mutex> Guard(Mutex);
173200b3289SIlya Biryukov for (const auto &File : Files)
174200b3289SIlya Biryukov llvm::sys::fs::remove(File.getKey());
175200b3289SIlya Biryukov }
176200b3289SIlya Biryukov
addFile(StringRef File)177200b3289SIlya Biryukov void TemporaryFiles::addFile(StringRef File) {
178762bc335SBenjamin Kramer std::lock_guard<std::mutex> Guard(Mutex);
179200b3289SIlya Biryukov auto IsInserted = Files.insert(File).second;
18053dd644cSHaojian Wu (void)IsInserted;
181200b3289SIlya Biryukov assert(IsInserted && "File has already been added");
182200b3289SIlya Biryukov }
183200b3289SIlya Biryukov
removeFile(StringRef File)184200b3289SIlya Biryukov void TemporaryFiles::removeFile(StringRef File) {
185762bc335SBenjamin Kramer std::lock_guard<std::mutex> Guard(Mutex);
186200b3289SIlya Biryukov auto WasPresent = Files.erase(File);
18753dd644cSHaojian Wu (void)WasPresent;
188200b3289SIlya Biryukov assert(WasPresent && "File was not tracked");
189200b3289SIlya Biryukov llvm::sys::fs::remove(File);
190200b3289SIlya Biryukov }
191200b3289SIlya Biryukov
192af3fb071SSam McCall // A temp file that would be deleted on destructor call. If destructor is not
193af3fb071SSam McCall // called for any reason, the file will be deleted at static objects'
194af3fb071SSam McCall // destruction.
195af3fb071SSam McCall // An assertion will fire if two TempPCHFiles are created with the same name,
196af3fb071SSam McCall // so it's not intended to be used outside preamble-handling.
197af3fb071SSam McCall class TempPCHFile {
198af3fb071SSam McCall public:
199af3fb071SSam McCall // A main method used to construct TempPCHFile.
create()200af3fb071SSam McCall static std::unique_ptr<TempPCHFile> create() {
201af3fb071SSam McCall // FIXME: This is a hack so that we can override the preamble file during
202af3fb071SSam McCall // crash-recovery testing, which is the only case where the preamble files
203af3fb071SSam McCall // are not necessarily cleaned up.
204af3fb071SSam McCall if (const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE"))
205af3fb071SSam McCall return std::unique_ptr<TempPCHFile>(new TempPCHFile(TmpFile));
206af3fb071SSam McCall
207af3fb071SSam McCall llvm::SmallString<64> File;
208af3fb071SSam McCall // Using a version of createTemporaryFile with a file descriptor guarantees
209af3fb071SSam McCall // that we would never get a race condition in a multi-threaded setting
210af3fb071SSam McCall // (i.e., multiple threads getting the same temporary path).
211af3fb071SSam McCall int FD;
212af3fb071SSam McCall if (auto EC =
213af3fb071SSam McCall llvm::sys::fs::createTemporaryFile("preamble", "pch", FD, File))
214af3fb071SSam McCall return nullptr;
215af3fb071SSam McCall // We only needed to make sure the file exists, close the file right away.
216af3fb071SSam McCall llvm::sys::Process::SafelyCloseFileDescriptor(FD);
217af3fb071SSam McCall return std::unique_ptr<TempPCHFile>(new TempPCHFile(File.str().str()));
218af3fb071SSam McCall }
219af3fb071SSam McCall
220af3fb071SSam McCall TempPCHFile &operator=(const TempPCHFile &) = delete;
221af3fb071SSam McCall TempPCHFile(const TempPCHFile &) = delete;
~TempPCHFile()222af3fb071SSam McCall ~TempPCHFile() { TemporaryFiles::getInstance().removeFile(FilePath); };
223af3fb071SSam McCall
224af3fb071SSam McCall /// A path where temporary file is stored.
getFilePath() const225af3fb071SSam McCall llvm::StringRef getFilePath() const { return FilePath; };
226af3fb071SSam McCall
227af3fb071SSam McCall private:
TempPCHFile(std::string FilePath)228af3fb071SSam McCall TempPCHFile(std::string FilePath) : FilePath(std::move(FilePath)) {
229af3fb071SSam McCall TemporaryFiles::getInstance().addFile(this->FilePath);
230af3fb071SSam McCall }
231af3fb071SSam McCall
232af3fb071SSam McCall std::string FilePath;
233af3fb071SSam McCall };
234af3fb071SSam McCall
235200b3289SIlya Biryukov class PrecompilePreambleAction : public ASTFrontendAction {
236200b3289SIlya Biryukov public:
PrecompilePreambleAction(std::shared_ptr<PCHBuffer> Buffer,bool WritePCHFile,PreambleCallbacks & Callbacks)237e80ee182SSam McCall PrecompilePreambleAction(std::shared_ptr<PCHBuffer> Buffer, bool WritePCHFile,
238417085acSIlya Biryukov PreambleCallbacks &Callbacks)
239e80ee182SSam McCall : Buffer(std::move(Buffer)), WritePCHFile(WritePCHFile),
240e80ee182SSam McCall Callbacks(Callbacks) {}
241200b3289SIlya Biryukov
242200b3289SIlya Biryukov std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
243200b3289SIlya Biryukov StringRef InFile) override;
244200b3289SIlya Biryukov
hasEmittedPreamblePCH() const245200b3289SIlya Biryukov bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
246200b3289SIlya Biryukov
setEmittedPreamblePCH(ASTWriter & Writer)247200b3289SIlya Biryukov void setEmittedPreamblePCH(ASTWriter &Writer) {
248e80ee182SSam McCall if (FileOS) {
249e80ee182SSam McCall *FileOS << Buffer->Data;
250e80ee182SSam McCall // Make sure it hits disk now.
2512d133867SDuncan P. N. Exon Smith FileOS.reset();
252e80ee182SSam McCall }
253e80ee182SSam McCall
254200b3289SIlya Biryukov this->HasEmittedPreamblePCH = true;
255200b3289SIlya Biryukov Callbacks.AfterPCHEmitted(Writer);
256200b3289SIlya Biryukov }
257200b3289SIlya Biryukov
BeginSourceFileAction(CompilerInstance & CI)258e2d61ae5SAdam Czachorowski bool BeginSourceFileAction(CompilerInstance &CI) override {
259e2d61ae5SAdam Czachorowski assert(CI.getLangOpts().CompilingPCH);
260e2d61ae5SAdam Czachorowski return ASTFrontendAction::BeginSourceFileAction(CI);
261e2d61ae5SAdam Czachorowski }
262e2d61ae5SAdam Czachorowski
shouldEraseOutputFiles()263200b3289SIlya Biryukov bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
hasCodeCompletionSupport() const264200b3289SIlya Biryukov bool hasCodeCompletionSupport() const override { return false; }
hasASTFileSupport() const265200b3289SIlya Biryukov bool hasASTFileSupport() const override { return false; }
getTranslationUnitKind()266200b3289SIlya Biryukov TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
267200b3289SIlya Biryukov
268200b3289SIlya Biryukov private:
269200b3289SIlya Biryukov friend class PrecompilePreambleConsumer;
270200b3289SIlya Biryukov
271200b3289SIlya Biryukov bool HasEmittedPreamblePCH = false;
272e80ee182SSam McCall std::shared_ptr<PCHBuffer> Buffer;
273e80ee182SSam McCall bool WritePCHFile; // otherwise the PCH is written into the PCHBuffer only.
274e80ee182SSam McCall std::unique_ptr<llvm::raw_pwrite_stream> FileOS; // null if in-memory
275200b3289SIlya Biryukov PreambleCallbacks &Callbacks;
276200b3289SIlya Biryukov };
277200b3289SIlya Biryukov
278200b3289SIlya Biryukov class PrecompilePreambleConsumer : public PCHGenerator {
279200b3289SIlya Biryukov public:
PrecompilePreambleConsumer(PrecompilePreambleAction & Action,const Preprocessor & PP,InMemoryModuleCache & ModuleCache,StringRef isysroot,std::shared_ptr<PCHBuffer> Buffer)280200b3289SIlya Biryukov PrecompilePreambleConsumer(PrecompilePreambleAction &Action,
2818bef5cd4SDuncan P. N. Exon Smith const Preprocessor &PP,
2828bef5cd4SDuncan P. N. Exon Smith InMemoryModuleCache &ModuleCache,
2838bef5cd4SDuncan P. N. Exon Smith StringRef isysroot,
284e80ee182SSam McCall std::shared_ptr<PCHBuffer> Buffer)
285e80ee182SSam McCall : PCHGenerator(PP, ModuleCache, "", isysroot, std::move(Buffer),
286200b3289SIlya Biryukov ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
287200b3289SIlya Biryukov /*AllowASTWithErrors=*/true),
288e80ee182SSam McCall Action(Action) {}
289200b3289SIlya Biryukov
HandleTopLevelDecl(DeclGroupRef DG)290200b3289SIlya Biryukov bool HandleTopLevelDecl(DeclGroupRef DG) override {
291200b3289SIlya Biryukov Action.Callbacks.HandleTopLevelDecl(DG);
292200b3289SIlya Biryukov return true;
293200b3289SIlya Biryukov }
294200b3289SIlya Biryukov
HandleTranslationUnit(ASTContext & Ctx)295200b3289SIlya Biryukov void HandleTranslationUnit(ASTContext &Ctx) override {
296200b3289SIlya Biryukov PCHGenerator::HandleTranslationUnit(Ctx);
297200b3289SIlya Biryukov if (!hasEmittedPCH())
298200b3289SIlya Biryukov return;
299200b3289SIlya Biryukov Action.setEmittedPreamblePCH(getWriter());
300200b3289SIlya Biryukov }
301200b3289SIlya Biryukov
shouldSkipFunctionBody(Decl * D)3024160f4c3SSam McCall bool shouldSkipFunctionBody(Decl *D) override {
3034160f4c3SSam McCall return Action.Callbacks.shouldSkipFunctionBody(D);
3044160f4c3SSam McCall }
3054160f4c3SSam McCall
306200b3289SIlya Biryukov private:
307200b3289SIlya Biryukov PrecompilePreambleAction &Action;
308200b3289SIlya Biryukov };
309200b3289SIlya Biryukov
310200b3289SIlya Biryukov std::unique_ptr<ASTConsumer>
CreateASTConsumer(CompilerInstance & CI,StringRef InFile)311200b3289SIlya Biryukov PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
312200b3289SIlya Biryukov StringRef InFile) {
313200b3289SIlya Biryukov std::string Sysroot;
314417085acSIlya Biryukov if (!GeneratePCHAction::ComputeASTConsumerArguments(CI, Sysroot))
315417085acSIlya Biryukov return nullptr;
316417085acSIlya Biryukov
317e80ee182SSam McCall if (WritePCHFile) {
318e80ee182SSam McCall std::string OutputFile; // unused
319e80ee182SSam McCall FileOS = GeneratePCHAction::CreateOutputFile(CI, InFile, OutputFile);
320e80ee182SSam McCall if (!FileOS)
321eadf3527SSam McCall return nullptr;
322e80ee182SSam McCall }
323200b3289SIlya Biryukov
324200b3289SIlya Biryukov if (!CI.getFrontendOpts().RelocatablePCH)
325200b3289SIlya Biryukov Sysroot.clear();
326200b3289SIlya Biryukov
3272b3d49b6SJonas Devlieghere return std::make_unique<PrecompilePreambleConsumer>(
328e80ee182SSam McCall *this, CI.getPreprocessor(), CI.getModuleCache(), Sysroot, Buffer);
329200b3289SIlya Biryukov }
330200b3289SIlya Biryukov
moveOnNoError(llvm::ErrorOr<T> Val,T & Output)331200b3289SIlya Biryukov template <class T> bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
332200b3289SIlya Biryukov if (!Val)
333200b3289SIlya Biryukov return false;
334200b3289SIlya Biryukov Output = std::move(*Val);
335200b3289SIlya Biryukov return true;
336200b3289SIlya Biryukov }
337200b3289SIlya Biryukov
338200b3289SIlya Biryukov } // namespace
339200b3289SIlya Biryukov
ComputePreambleBounds(const LangOptions & LangOpts,const llvm::MemoryBufferRef & Buffer,unsigned MaxLines)340200b3289SIlya Biryukov PreambleBounds clang::ComputePreambleBounds(const LangOptions &LangOpts,
3414c55c3b6SDuncan P. N. Exon Smith const llvm::MemoryBufferRef &Buffer,
342200b3289SIlya Biryukov unsigned MaxLines) {
3434c55c3b6SDuncan P. N. Exon Smith return Lexer::ComputePreamble(Buffer.getBuffer(), LangOpts, MaxLines);
344200b3289SIlya Biryukov }
345200b3289SIlya Biryukov
346af3fb071SSam McCall class PrecompiledPreamble::PCHStorage {
347af3fb071SSam McCall public:
file(std::unique_ptr<TempPCHFile> File)348af3fb071SSam McCall static std::unique_ptr<PCHStorage> file(std::unique_ptr<TempPCHFile> File) {
349af3fb071SSam McCall assert(File);
350af3fb071SSam McCall std::unique_ptr<PCHStorage> S(new PCHStorage());
351af3fb071SSam McCall S->File = std::move(File);
352af3fb071SSam McCall return S;
353af3fb071SSam McCall }
inMemory(std::shared_ptr<PCHBuffer> Buf)354e80ee182SSam McCall static std::unique_ptr<PCHStorage> inMemory(std::shared_ptr<PCHBuffer> Buf) {
355af3fb071SSam McCall std::unique_ptr<PCHStorage> S(new PCHStorage());
356e80ee182SSam McCall S->Memory = std::move(Buf);
357af3fb071SSam McCall return S;
358af3fb071SSam McCall }
359af3fb071SSam McCall
360af3fb071SSam McCall enum class Kind { InMemory, TempFile };
getKind() const361af3fb071SSam McCall Kind getKind() const {
362af3fb071SSam McCall if (Memory)
363af3fb071SSam McCall return Kind::InMemory;
364af3fb071SSam McCall if (File)
365af3fb071SSam McCall return Kind::TempFile;
366af3fb071SSam McCall llvm_unreachable("Neither Memory nor File?");
367af3fb071SSam McCall }
filePath() const368af3fb071SSam McCall llvm::StringRef filePath() const {
369af3fb071SSam McCall assert(getKind() == Kind::TempFile);
370af3fb071SSam McCall return File->getFilePath();
371af3fb071SSam McCall }
memoryContents() const372af3fb071SSam McCall llvm::StringRef memoryContents() const {
373af3fb071SSam McCall assert(getKind() == Kind::InMemory);
374e80ee182SSam McCall return StringRef(Memory->Data.data(), Memory->Data.size());
375af3fb071SSam McCall }
376af3fb071SSam McCall
37700f0c805SSam McCall // Shrink in-memory buffers to fit.
37800f0c805SSam McCall // This incurs a copy, but preambles tend to be long-lived.
37900f0c805SSam McCall // Only safe to call once nothing can alias the buffer.
shrink()38000f0c805SSam McCall void shrink() {
38100f0c805SSam McCall if (!Memory)
38200f0c805SSam McCall return;
38300f0c805SSam McCall Memory->Data = decltype(Memory->Data)(Memory->Data);
38400f0c805SSam McCall }
38500f0c805SSam McCall
386af3fb071SSam McCall private:
387af3fb071SSam McCall PCHStorage() = default;
388af3fb071SSam McCall PCHStorage(const PCHStorage &) = delete;
389af3fb071SSam McCall PCHStorage &operator=(const PCHStorage &) = delete;
390af3fb071SSam McCall
391e80ee182SSam McCall std::shared_ptr<PCHBuffer> Memory;
392af3fb071SSam McCall std::unique_ptr<TempPCHFile> File;
393af3fb071SSam McCall };
394af3fb071SSam McCall
395af3fb071SSam McCall PrecompiledPreamble::~PrecompiledPreamble() = default;
396af3fb071SSam McCall PrecompiledPreamble::PrecompiledPreamble(PrecompiledPreamble &&) = default;
397af3fb071SSam McCall PrecompiledPreamble &
398af3fb071SSam McCall PrecompiledPreamble::operator=(PrecompiledPreamble &&) = default;
399af3fb071SSam McCall
Build(const CompilerInvocation & Invocation,const llvm::MemoryBuffer * MainFileBuffer,PreambleBounds Bounds,DiagnosticsEngine & Diagnostics,IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,std::shared_ptr<PCHContainerOperations> PCHContainerOps,bool StoreInMemory,PreambleCallbacks & Callbacks)400200b3289SIlya Biryukov llvm::ErrorOr<PrecompiledPreamble> PrecompiledPreamble::Build(
401200b3289SIlya Biryukov const CompilerInvocation &Invocation,
402200b3289SIlya Biryukov const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds,
403fc51490bSJonas Devlieghere DiagnosticsEngine &Diagnostics,
404fc51490bSJonas Devlieghere IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
405417085acSIlya Biryukov std::shared_ptr<PCHContainerOperations> PCHContainerOps, bool StoreInMemory,
406200b3289SIlya Biryukov PreambleCallbacks &Callbacks) {
407200b3289SIlya Biryukov assert(VFS && "VFS is null");
408200b3289SIlya Biryukov
409200b3289SIlya Biryukov auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
410200b3289SIlya Biryukov FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
411200b3289SIlya Biryukov PreprocessorOptions &PreprocessorOpts =
412200b3289SIlya Biryukov PreambleInvocation->getPreprocessorOpts();
413200b3289SIlya Biryukov
414e80ee182SSam McCall std::shared_ptr<PCHBuffer> Buffer = std::make_shared<PCHBuffer>();
415af3fb071SSam McCall std::unique_ptr<PCHStorage> Storage;
416af3fb071SSam McCall if (StoreInMemory) {
417e80ee182SSam McCall Storage = PCHStorage::inMemory(Buffer);
418af3fb071SSam McCall } else {
419200b3289SIlya Biryukov // Create a temporary file for the precompiled preamble. In rare
420200b3289SIlya Biryukov // circumstances, this can fail.
421af3fb071SSam McCall std::unique_ptr<TempPCHFile> PreamblePCHFile = TempPCHFile::create();
422200b3289SIlya Biryukov if (!PreamblePCHFile)
423200b3289SIlya Biryukov return BuildPreambleError::CouldntCreateTempFile;
424af3fb071SSam McCall Storage = PCHStorage::file(std::move(PreamblePCHFile));
425417085acSIlya Biryukov }
426417085acSIlya Biryukov
427200b3289SIlya Biryukov // Save the preamble text for later; we'll need to compare against it for
428200b3289SIlya Biryukov // subsequent reparses.
429200b3289SIlya Biryukov std::vector<char> PreambleBytes(MainFileBuffer->getBufferStart(),
430200b3289SIlya Biryukov MainFileBuffer->getBufferStart() +
431200b3289SIlya Biryukov Bounds.Size);
432200b3289SIlya Biryukov bool PreambleEndsAtStartOfLine = Bounds.PreambleEndsAtStartOfLine;
433200b3289SIlya Biryukov
434200b3289SIlya Biryukov // Tell the compiler invocation to generate a temporary precompiled header.
435200b3289SIlya Biryukov FrontendOpts.ProgramAction = frontend::GeneratePCH;
436af3fb071SSam McCall FrontendOpts.OutputFile = std::string(
437af3fb071SSam McCall StoreInMemory ? getInMemoryPreamblePath() : Storage->filePath());
438200b3289SIlya Biryukov PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
439200b3289SIlya Biryukov PreprocessorOpts.PrecompiledPreambleBytes.second = false;
440eb1ec876SIlya Biryukov // Inform preprocessor to record conditional stack when building the preamble.
441eb1ec876SIlya Biryukov PreprocessorOpts.GeneratePreamble = true;
442200b3289SIlya Biryukov
443200b3289SIlya Biryukov // Create the compiler instance to use for building the precompiled preamble.
444200b3289SIlya Biryukov std::unique_ptr<CompilerInstance> Clang(
445200b3289SIlya Biryukov new CompilerInstance(std::move(PCHContainerOps)));
446200b3289SIlya Biryukov
447200b3289SIlya Biryukov // Recover resources if we crash before exiting this method.
448200b3289SIlya Biryukov llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
449200b3289SIlya Biryukov Clang.get());
450200b3289SIlya Biryukov
451200b3289SIlya Biryukov Clang->setInvocation(std::move(PreambleInvocation));
452200b3289SIlya Biryukov Clang->setDiagnostics(&Diagnostics);
453200b3289SIlya Biryukov
454200b3289SIlya Biryukov // Create the target instance.
45514a7296cSoToToT if (!Clang->createTarget())
456200b3289SIlya Biryukov return BuildPreambleError::CouldntCreateTargetInfo;
457200b3289SIlya Biryukov
4582917526fSIlya Biryukov if (Clang->getFrontendOpts().Inputs.size() != 1 ||
4592917526fSIlya Biryukov Clang->getFrontendOpts().Inputs[0].getKind().getFormat() !=
4602917526fSIlya Biryukov InputKind::Source ||
4612917526fSIlya Biryukov Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() ==
46209d890d7SRainer Orth Language::LLVM_IR) {
4632917526fSIlya Biryukov return BuildPreambleError::BadInputs;
4642917526fSIlya Biryukov }
465200b3289SIlya Biryukov
466200b3289SIlya Biryukov // Clear out old caches and data.
467200b3289SIlya Biryukov Diagnostics.Reset();
468200b3289SIlya Biryukov ProcessWarningOptions(Diagnostics, Clang->getDiagnosticOpts());
469200b3289SIlya Biryukov
470200b3289SIlya Biryukov VFS =
471200b3289SIlya Biryukov createVFSFromCompilerInvocation(Clang->getInvocation(), Diagnostics, VFS);
472200b3289SIlya Biryukov
473200b3289SIlya Biryukov // Create a file manager object to provide access to and cache the filesystem.
474200b3289SIlya Biryukov Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
475200b3289SIlya Biryukov
476200b3289SIlya Biryukov // Create the source manager.
477200b3289SIlya Biryukov Clang->setSourceManager(
478200b3289SIlya Biryukov new SourceManager(Diagnostics, Clang->getFileManager()));
479200b3289SIlya Biryukov
480e5801b02SIlya Biryukov auto PreambleDepCollector = std::make_shared<PreambleDependencyCollector>();
481200b3289SIlya Biryukov Clang->addDependencyCollector(PreambleDepCollector);
482200b3289SIlya Biryukov
483e2d61ae5SAdam Czachorowski Clang->getLangOpts().CompilingPCH = true;
484e2d61ae5SAdam Czachorowski
485200b3289SIlya Biryukov // Remap the main source file to the preamble buffer.
486200b3289SIlya Biryukov StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
487200b3289SIlya Biryukov auto PreambleInputBuffer = llvm::MemoryBuffer::getMemBufferCopy(
488200b3289SIlya Biryukov MainFileBuffer->getBuffer().slice(0, Bounds.Size), MainFilePath);
489200b3289SIlya Biryukov if (PreprocessorOpts.RetainRemappedFileBuffers) {
490200b3289SIlya Biryukov // MainFileBuffer will be deleted by unique_ptr after leaving the method.
491200b3289SIlya Biryukov PreprocessorOpts.addRemappedFile(MainFilePath, PreambleInputBuffer.get());
492200b3289SIlya Biryukov } else {
493200b3289SIlya Biryukov // In that case, remapped buffer will be deleted by CompilerInstance on
494200b3289SIlya Biryukov // BeginSourceFile, so we call release() to avoid double deletion.
495200b3289SIlya Biryukov PreprocessorOpts.addRemappedFile(MainFilePath,
496200b3289SIlya Biryukov PreambleInputBuffer.release());
497200b3289SIlya Biryukov }
498200b3289SIlya Biryukov
499e80ee182SSam McCall auto Act = std::make_unique<PrecompilePreambleAction>(
500e80ee182SSam McCall std::move(Buffer),
501e80ee182SSam McCall /*WritePCHFile=*/Storage->getKind() == PCHStorage::Kind::TempFile,
502e80ee182SSam McCall Callbacks);
503200b3289SIlya Biryukov if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
504200b3289SIlya Biryukov return BuildPreambleError::BeginSourceFileFailed;
505200b3289SIlya Biryukov
506bad89777SKirill Bobyrev // Performed after BeginSourceFile to ensure Clang->Preprocessor can be
507bad89777SKirill Bobyrev // referenced in the callback.
508bad89777SKirill Bobyrev Callbacks.BeforeExecute(*Clang);
509bad89777SKirill Bobyrev
51041e90bcbSIlya Biryukov std::unique_ptr<PPCallbacks> DelegatedPPCallbacks =
51141e90bcbSIlya Biryukov Callbacks.createPPCallbacks();
51241e90bcbSIlya Biryukov if (DelegatedPPCallbacks)
51341e90bcbSIlya Biryukov Clang->getPreprocessor().addPPCallbacks(std::move(DelegatedPPCallbacks));
5149e012e8bSKadir Cetinkaya if (auto CommentHandler = Callbacks.getCommentHandler())
5159e012e8bSKadir Cetinkaya Clang->getPreprocessor().addCommentHandler(CommentHandler);
516615673f3SSam McCall llvm::StringSet<> MissingFiles;
517615673f3SSam McCall Clang->getPreprocessor().addPPCallbacks(
518615673f3SSam McCall std::make_unique<MissingFileCollector>(
519615673f3SSam McCall MissingFiles, Clang->getPreprocessor().getHeaderSearchInfo(),
520615673f3SSam McCall Clang->getSourceManager()));
52141e90bcbSIlya Biryukov
5220e828958SJF Bastien if (llvm::Error Err = Act->Execute())
5230e828958SJF Bastien return errorToErrorCode(std::move(Err));
524200b3289SIlya Biryukov
525200b3289SIlya Biryukov // Run the callbacks.
526200b3289SIlya Biryukov Callbacks.AfterExecute(*Clang);
527200b3289SIlya Biryukov
528200b3289SIlya Biryukov Act->EndSourceFile();
529200b3289SIlya Biryukov
530200b3289SIlya Biryukov if (!Act->hasEmittedPreamblePCH())
531200b3289SIlya Biryukov return BuildPreambleError::CouldntEmitPCH;
53200f0c805SSam McCall Act.reset(); // Frees the PCH buffer, unless Storage keeps it in memory.
533200b3289SIlya Biryukov
534200b3289SIlya Biryukov // Keep track of all of the files that the source manager knows about,
535200b3289SIlya Biryukov // so we can verify whether they have changed or not.
536200b3289SIlya Biryukov llvm::StringMap<PrecompiledPreamble::PreambleFileHash> FilesInPreamble;
537200b3289SIlya Biryukov
538200b3289SIlya Biryukov SourceManager &SourceMgr = Clang->getSourceManager();
539200b3289SIlya Biryukov for (auto &Filename : PreambleDepCollector->getDependencies()) {
5408d323d15SHarlan Haskins auto FileOrErr = Clang->getFileManager().getFile(Filename);
5418d323d15SHarlan Haskins if (!FileOrErr ||
5428d323d15SHarlan Haskins *FileOrErr == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
543200b3289SIlya Biryukov continue;
5448d323d15SHarlan Haskins auto File = *FileOrErr;
545200b3289SIlya Biryukov if (time_t ModTime = File->getModificationTime()) {
546200b3289SIlya Biryukov FilesInPreamble[File->getName()] =
547200b3289SIlya Biryukov PrecompiledPreamble::PreambleFileHash::createForFile(File->getSize(),
548200b3289SIlya Biryukov ModTime);
549200b3289SIlya Biryukov } else {
5502dc7e0c6SDuncan P. N. Exon Smith llvm::MemoryBufferRef Buffer =
5512dc7e0c6SDuncan P. N. Exon Smith SourceMgr.getMemoryBufferForFileOrFake(File);
552200b3289SIlya Biryukov FilesInPreamble[File->getName()] =
553200b3289SIlya Biryukov PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(Buffer);
554200b3289SIlya Biryukov }
555200b3289SIlya Biryukov }
556200b3289SIlya Biryukov
55700f0c805SSam McCall // Shrinking the storage requires extra temporary memory.
55800f0c805SSam McCall // Destroying clang first reduces peak memory usage.
55900f0c805SSam McCall CICleanup.unregister();
56000f0c805SSam McCall Clang.reset();
56100f0c805SSam McCall Storage->shrink();
562615673f3SSam McCall return PrecompiledPreamble(
563615673f3SSam McCall std::move(Storage), std::move(PreambleBytes), PreambleEndsAtStartOfLine,
564615673f3SSam McCall std::move(FilesInPreamble), std::move(MissingFiles));
565200b3289SIlya Biryukov }
566200b3289SIlya Biryukov
getBounds() const567200b3289SIlya Biryukov PreambleBounds PrecompiledPreamble::getBounds() const {
568200b3289SIlya Biryukov return PreambleBounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
569200b3289SIlya Biryukov }
570200b3289SIlya Biryukov
getSize() const571923e3388SIlya Biryukov std::size_t PrecompiledPreamble::getSize() const {
572af3fb071SSam McCall switch (Storage->getKind()) {
573923e3388SIlya Biryukov case PCHStorage::Kind::InMemory:
574af3fb071SSam McCall return Storage->memoryContents().size();
575923e3388SIlya Biryukov case PCHStorage::Kind::TempFile: {
576923e3388SIlya Biryukov uint64_t Result;
577af3fb071SSam McCall if (llvm::sys::fs::file_size(Storage->filePath(), Result))
578923e3388SIlya Biryukov return 0;
579923e3388SIlya Biryukov
580923e3388SIlya Biryukov assert(Result <= std::numeric_limits<std::size_t>::max() &&
581923e3388SIlya Biryukov "file size did not fit into size_t");
582923e3388SIlya Biryukov return Result;
583923e3388SIlya Biryukov }
584923e3388SIlya Biryukov }
585923e3388SIlya Biryukov llvm_unreachable("Unhandled storage kind");
586923e3388SIlya Biryukov }
587923e3388SIlya Biryukov
CanReuse(const CompilerInvocation & Invocation,const llvm::MemoryBufferRef & MainFileBuffer,PreambleBounds Bounds,llvm::vfs::FileSystem & VFS) const588200b3289SIlya Biryukov bool PrecompiledPreamble::CanReuse(const CompilerInvocation &Invocation,
589f4d02fbeSDuncan P. N. Exon Smith const llvm::MemoryBufferRef &MainFileBuffer,
590200b3289SIlya Biryukov PreambleBounds Bounds,
591f4d02fbeSDuncan P. N. Exon Smith llvm::vfs::FileSystem &VFS) const {
592200b3289SIlya Biryukov
593200b3289SIlya Biryukov assert(
594f4d02fbeSDuncan P. N. Exon Smith Bounds.Size <= MainFileBuffer.getBufferSize() &&
595200b3289SIlya Biryukov "Buffer is too large. Bounds were calculated from a different buffer?");
596200b3289SIlya Biryukov
597200b3289SIlya Biryukov auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
598200b3289SIlya Biryukov PreprocessorOptions &PreprocessorOpts =
599200b3289SIlya Biryukov PreambleInvocation->getPreprocessorOpts();
600200b3289SIlya Biryukov
601200b3289SIlya Biryukov // We've previously computed a preamble. Check whether we have the same
602200b3289SIlya Biryukov // preamble now that we did before, and that there's enough space in
603200b3289SIlya Biryukov // the main-file buffer within the precompiled preamble to fit the
604200b3289SIlya Biryukov // new main file.
605200b3289SIlya Biryukov if (PreambleBytes.size() != Bounds.Size ||
606200b3289SIlya Biryukov PreambleEndsAtStartOfLine != Bounds.PreambleEndsAtStartOfLine ||
607a3b34574SHaojian Wu !std::equal(PreambleBytes.begin(), PreambleBytes.end(),
608f4d02fbeSDuncan P. N. Exon Smith MainFileBuffer.getBuffer().begin()))
609200b3289SIlya Biryukov return false;
610200b3289SIlya Biryukov // The preamble has not changed. We may be able to re-use the precompiled
611200b3289SIlya Biryukov // preamble.
612200b3289SIlya Biryukov
613200b3289SIlya Biryukov // Check that none of the files used by the preamble have changed.
614200b3289SIlya Biryukov // First, make a record of those files that have been overridden via
615200b3289SIlya Biryukov // remapping or unsaved_files.
616200b3289SIlya Biryukov std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
617615673f3SSam McCall llvm::StringSet<> OverriddenAbsPaths; // Either by buffers or files.
618200b3289SIlya Biryukov for (const auto &R : PreprocessorOpts.RemappedFiles) {
619fc51490bSJonas Devlieghere llvm::vfs::Status Status;
620f4d02fbeSDuncan P. N. Exon Smith if (!moveOnNoError(VFS.status(R.second), Status)) {
621200b3289SIlya Biryukov // If we can't stat the file we're remapping to, assume that something
622200b3289SIlya Biryukov // horrible happened.
623200b3289SIlya Biryukov return false;
624200b3289SIlya Biryukov }
625615673f3SSam McCall // If a mapped file was previously missing, then it has changed.
626615673f3SSam McCall llvm::SmallString<128> MappedPath(R.first);
627f4d02fbeSDuncan P. N. Exon Smith if (!VFS.makeAbsolute(MappedPath))
628615673f3SSam McCall OverriddenAbsPaths.insert(MappedPath);
629200b3289SIlya Biryukov
630200b3289SIlya Biryukov OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
631200b3289SIlya Biryukov Status.getSize(), llvm::sys::toTimeT(Status.getLastModificationTime()));
632200b3289SIlya Biryukov }
633200b3289SIlya Biryukov
634295c19e9SNikolai Kosjar // OverridenFileBuffers tracks only the files not found in VFS.
635295c19e9SNikolai Kosjar llvm::StringMap<PreambleFileHash> OverridenFileBuffers;
636200b3289SIlya Biryukov for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
637295c19e9SNikolai Kosjar const PrecompiledPreamble::PreambleFileHash PreambleHash =
6382dc7e0c6SDuncan P. N. Exon Smith PreambleFileHash::createForMemoryBuffer(RB.second->getMemBufferRef());
639295c19e9SNikolai Kosjar llvm::vfs::Status Status;
640f4d02fbeSDuncan P. N. Exon Smith if (moveOnNoError(VFS.status(RB.first), Status))
641295c19e9SNikolai Kosjar OverriddenFiles[Status.getUniqueID()] = PreambleHash;
642295c19e9SNikolai Kosjar else
643295c19e9SNikolai Kosjar OverridenFileBuffers[RB.first] = PreambleHash;
644615673f3SSam McCall
645615673f3SSam McCall llvm::SmallString<128> MappedPath(RB.first);
646f4d02fbeSDuncan P. N. Exon Smith if (!VFS.makeAbsolute(MappedPath))
647615673f3SSam McCall OverriddenAbsPaths.insert(MappedPath);
648200b3289SIlya Biryukov }
649200b3289SIlya Biryukov
650200b3289SIlya Biryukov // Check whether anything has changed.
651200b3289SIlya Biryukov for (const auto &F : FilesInPreamble) {
652295c19e9SNikolai Kosjar auto OverridenFileBuffer = OverridenFileBuffers.find(F.first());
653295c19e9SNikolai Kosjar if (OverridenFileBuffer != OverridenFileBuffers.end()) {
654295c19e9SNikolai Kosjar // The file's buffer was remapped and the file was not found in VFS.
655295c19e9SNikolai Kosjar // Check whether it matches up with the previous mapping.
656295c19e9SNikolai Kosjar if (OverridenFileBuffer->second != F.second)
657295c19e9SNikolai Kosjar return false;
658295c19e9SNikolai Kosjar continue;
659295c19e9SNikolai Kosjar }
660295c19e9SNikolai Kosjar
661fc51490bSJonas Devlieghere llvm::vfs::Status Status;
662f4d02fbeSDuncan P. N. Exon Smith if (!moveOnNoError(VFS.status(F.first()), Status)) {
663295c19e9SNikolai Kosjar // If the file's buffer is not remapped and we can't stat it,
664295c19e9SNikolai Kosjar // assume that something horrible happened.
665200b3289SIlya Biryukov return false;
666200b3289SIlya Biryukov }
667200b3289SIlya Biryukov
668200b3289SIlya Biryukov std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden =
669200b3289SIlya Biryukov OverriddenFiles.find(Status.getUniqueID());
670200b3289SIlya Biryukov if (Overridden != OverriddenFiles.end()) {
671200b3289SIlya Biryukov // This file was remapped; check whether the newly-mapped file
672200b3289SIlya Biryukov // matches up with the previous mapping.
673200b3289SIlya Biryukov if (Overridden->second != F.second)
674200b3289SIlya Biryukov return false;
675200b3289SIlya Biryukov continue;
676200b3289SIlya Biryukov }
677200b3289SIlya Biryukov
678295c19e9SNikolai Kosjar // Neither the file's buffer nor the file itself was remapped;
679295c19e9SNikolai Kosjar // check whether it has changed on disk.
680200b3289SIlya Biryukov if (Status.getSize() != uint64_t(F.second.Size) ||
681200b3289SIlya Biryukov llvm::sys::toTimeT(Status.getLastModificationTime()) !=
682200b3289SIlya Biryukov F.second.ModTime)
683200b3289SIlya Biryukov return false;
684200b3289SIlya Biryukov }
685615673f3SSam McCall for (const auto &F : MissingFiles) {
686615673f3SSam McCall // A missing file may be "provided" by an override buffer or file.
687615673f3SSam McCall if (OverriddenAbsPaths.count(F.getKey()))
688615673f3SSam McCall return false;
689615673f3SSam McCall // If a file previously recorded as missing exists as a regular file, then
690615673f3SSam McCall // consider the preamble out-of-date.
691f4d02fbeSDuncan P. N. Exon Smith if (auto Status = VFS.status(F.getKey())) {
692615673f3SSam McCall if (Status->isRegularFile())
693615673f3SSam McCall return false;
694615673f3SSam McCall }
695615673f3SSam McCall }
696200b3289SIlya Biryukov return true;
697200b3289SIlya Biryukov }
698200b3289SIlya Biryukov
AddImplicitPreamble(CompilerInvocation & CI,IntrusiveRefCntPtr<llvm::vfs::FileSystem> & VFS,llvm::MemoryBuffer * MainFileBuffer) const699200b3289SIlya Biryukov void PrecompiledPreamble::AddImplicitPreamble(
700fc51490bSJonas Devlieghere CompilerInvocation &CI, IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
701417085acSIlya Biryukov llvm::MemoryBuffer *MainFileBuffer) const {
7024a8f7533SIlya Biryukov PreambleBounds Bounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
7034a8f7533SIlya Biryukov configurePreamble(Bounds, CI, VFS, MainFileBuffer);
7044a8f7533SIlya Biryukov }
705200b3289SIlya Biryukov
OverridePreamble(CompilerInvocation & CI,IntrusiveRefCntPtr<llvm::vfs::FileSystem> & VFS,llvm::MemoryBuffer * MainFileBuffer) const7064a8f7533SIlya Biryukov void PrecompiledPreamble::OverridePreamble(
707fc51490bSJonas Devlieghere CompilerInvocation &CI, IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
7084a8f7533SIlya Biryukov llvm::MemoryBuffer *MainFileBuffer) const {
7094c55c3b6SDuncan P. N. Exon Smith auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), *MainFileBuffer, 0);
7104a8f7533SIlya Biryukov configurePreamble(Bounds, CI, VFS, MainFileBuffer);
711200b3289SIlya Biryukov }
712200b3289SIlya Biryukov
PrecompiledPreamble(std::unique_ptr<PCHStorage> Storage,std::vector<char> PreambleBytes,bool PreambleEndsAtStartOfLine,llvm::StringMap<PreambleFileHash> FilesInPreamble,llvm::StringSet<> MissingFiles)713200b3289SIlya Biryukov PrecompiledPreamble::PrecompiledPreamble(
714af3fb071SSam McCall std::unique_ptr<PCHStorage> Storage, std::vector<char> PreambleBytes,
715200b3289SIlya Biryukov bool PreambleEndsAtStartOfLine,
716615673f3SSam McCall llvm::StringMap<PreambleFileHash> FilesInPreamble,
717615673f3SSam McCall llvm::StringSet<> MissingFiles)
718417085acSIlya Biryukov : Storage(std::move(Storage)), FilesInPreamble(std::move(FilesInPreamble)),
719615673f3SSam McCall MissingFiles(std::move(MissingFiles)),
720200b3289SIlya Biryukov PreambleBytes(std::move(PreambleBytes)),
721417085acSIlya Biryukov PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {
722af3fb071SSam McCall assert(this->Storage != nullptr);
723417085acSIlya Biryukov }
724417085acSIlya Biryukov
725200b3289SIlya Biryukov PrecompiledPreamble::PreambleFileHash
createForFile(off_t Size,time_t ModTime)726200b3289SIlya Biryukov PrecompiledPreamble::PreambleFileHash::createForFile(off_t Size,
727200b3289SIlya Biryukov time_t ModTime) {
728200b3289SIlya Biryukov PreambleFileHash Result;
729200b3289SIlya Biryukov Result.Size = Size;
730200b3289SIlya Biryukov Result.ModTime = ModTime;
731200b3289SIlya Biryukov Result.MD5 = {};
732200b3289SIlya Biryukov return Result;
733200b3289SIlya Biryukov }
734200b3289SIlya Biryukov
735200b3289SIlya Biryukov PrecompiledPreamble::PreambleFileHash
createForMemoryBuffer(const llvm::MemoryBufferRef & Buffer)736200b3289SIlya Biryukov PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(
7372dc7e0c6SDuncan P. N. Exon Smith const llvm::MemoryBufferRef &Buffer) {
738200b3289SIlya Biryukov PreambleFileHash Result;
7392dc7e0c6SDuncan P. N. Exon Smith Result.Size = Buffer.getBufferSize();
740200b3289SIlya Biryukov Result.ModTime = 0;
741200b3289SIlya Biryukov
742200b3289SIlya Biryukov llvm::MD5 MD5Ctx;
7432dc7e0c6SDuncan P. N. Exon Smith MD5Ctx.update(Buffer.getBuffer().data());
744200b3289SIlya Biryukov MD5Ctx.final(Result.MD5);
745200b3289SIlya Biryukov
746200b3289SIlya Biryukov return Result;
747200b3289SIlya Biryukov }
748200b3289SIlya Biryukov
configurePreamble(PreambleBounds Bounds,CompilerInvocation & CI,IntrusiveRefCntPtr<llvm::vfs::FileSystem> & VFS,llvm::MemoryBuffer * MainFileBuffer) const7494a8f7533SIlya Biryukov void PrecompiledPreamble::configurePreamble(
7504a8f7533SIlya Biryukov PreambleBounds Bounds, CompilerInvocation &CI,
751fc51490bSJonas Devlieghere IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
7524a8f7533SIlya Biryukov llvm::MemoryBuffer *MainFileBuffer) const {
7534a8f7533SIlya Biryukov assert(VFS);
7544a8f7533SIlya Biryukov
7554a8f7533SIlya Biryukov auto &PreprocessorOpts = CI.getPreprocessorOpts();
7564a8f7533SIlya Biryukov
7574a8f7533SIlya Biryukov // Remap main file to point to MainFileBuffer.
7584a8f7533SIlya Biryukov auto MainFilePath = CI.getFrontendOpts().Inputs[0].getFile();
7594a8f7533SIlya Biryukov PreprocessorOpts.addRemappedFile(MainFilePath, MainFileBuffer);
7604a8f7533SIlya Biryukov
7614a8f7533SIlya Biryukov // Configure ImpicitPCHInclude.
7624a8f7533SIlya Biryukov PreprocessorOpts.PrecompiledPreambleBytes.first = Bounds.Size;
7634a8f7533SIlya Biryukov PreprocessorOpts.PrecompiledPreambleBytes.second =
7644a8f7533SIlya Biryukov Bounds.PreambleEndsAtStartOfLine;
765b0e89906SArgyrios Kyrtzidis PreprocessorOpts.DisablePCHOrModuleValidation =
766b0e89906SArgyrios Kyrtzidis DisableValidationForModuleKind::PCH;
7674a8f7533SIlya Biryukov
768*0195163dSSam McCall // Don't bother generating the long version of the predefines buffer.
769*0195163dSSam McCall // The preamble is going to overwrite it anyway.
770*0195163dSSam McCall PreprocessorOpts.UsePredefines = false;
771*0195163dSSam McCall
772af3fb071SSam McCall setupPreambleStorage(*Storage, PreprocessorOpts, VFS);
7734a8f7533SIlya Biryukov }
7744a8f7533SIlya Biryukov
setupPreambleStorage(const PCHStorage & Storage,PreprocessorOptions & PreprocessorOpts,IntrusiveRefCntPtr<llvm::vfs::FileSystem> & VFS)775417085acSIlya Biryukov void PrecompiledPreamble::setupPreambleStorage(
776417085acSIlya Biryukov const PCHStorage &Storage, PreprocessorOptions &PreprocessorOpts,
777fc51490bSJonas Devlieghere IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS) {
778417085acSIlya Biryukov if (Storage.getKind() == PCHStorage::Kind::TempFile) {
779af3fb071SSam McCall llvm::StringRef PCHPath = Storage.filePath();
780af3fb071SSam McCall PreprocessorOpts.ImplicitPCHInclude = PCHPath.str();
781417085acSIlya Biryukov
782417085acSIlya Biryukov // Make sure we can access the PCH file even if we're using a VFS
783fc51490bSJonas Devlieghere IntrusiveRefCntPtr<llvm::vfs::FileSystem> RealFS =
784fc51490bSJonas Devlieghere llvm::vfs::getRealFileSystem();
785417085acSIlya Biryukov if (VFS == RealFS || VFS->exists(PCHPath))
786417085acSIlya Biryukov return;
787417085acSIlya Biryukov auto Buf = RealFS->getBufferForFile(PCHPath);
788417085acSIlya Biryukov if (!Buf) {
789417085acSIlya Biryukov // We can't read the file even from RealFS, this is clearly an error,
790417085acSIlya Biryukov // but we'll just leave the current VFS as is and let clang's code
791417085acSIlya Biryukov // figure out what to do with missing PCH.
792417085acSIlya Biryukov return;
793417085acSIlya Biryukov }
794417085acSIlya Biryukov
795417085acSIlya Biryukov // We have a slight inconsistency here -- we're using the VFS to
796417085acSIlya Biryukov // read files, but the PCH was generated in the real file system.
797417085acSIlya Biryukov VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(*Buf), VFS);
798417085acSIlya Biryukov } else {
799417085acSIlya Biryukov assert(Storage.getKind() == PCHStorage::Kind::InMemory);
800417085acSIlya Biryukov // For in-memory preamble, we have to provide a VFS overlay that makes it
801417085acSIlya Biryukov // accessible.
802417085acSIlya Biryukov StringRef PCHPath = getInMemoryPreamblePath();
803adcd0268SBenjamin Kramer PreprocessorOpts.ImplicitPCHInclude = std::string(PCHPath);
804417085acSIlya Biryukov
805e80ee182SSam McCall auto Buf = llvm::MemoryBuffer::getMemBuffer(
806e80ee182SSam McCall Storage.memoryContents(), PCHPath, /*RequiresNullTerminator=*/false);
807417085acSIlya Biryukov VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(Buf), VFS);
808417085acSIlya Biryukov }
809417085acSIlya Biryukov }
810417085acSIlya Biryukov
BeforeExecute(CompilerInstance & CI)8111f8647d1SIlya Biryukov void PreambleCallbacks::BeforeExecute(CompilerInstance &CI) {}
AfterExecute(CompilerInstance & CI)812200b3289SIlya Biryukov void PreambleCallbacks::AfterExecute(CompilerInstance &CI) {}
AfterPCHEmitted(ASTWriter & Writer)813200b3289SIlya Biryukov void PreambleCallbacks::AfterPCHEmitted(ASTWriter &Writer) {}
HandleTopLevelDecl(DeclGroupRef DG)814200b3289SIlya Biryukov void PreambleCallbacks::HandleTopLevelDecl(DeclGroupRef DG) {}
createPPCallbacks()81541e90bcbSIlya Biryukov std::unique_ptr<PPCallbacks> PreambleCallbacks::createPPCallbacks() {
81641e90bcbSIlya Biryukov return nullptr;
81741e90bcbSIlya Biryukov }
getCommentHandler()8189e012e8bSKadir Cetinkaya CommentHandler *PreambleCallbacks::getCommentHandler() { return nullptr; }
819200b3289SIlya Biryukov
82051c9349aSAlexandre Ganea static llvm::ManagedStatic<BuildPreambleErrorCategory> BuildPreambleErrCategory;
82151c9349aSAlexandre Ganea
make_error_code(BuildPreambleError Error)822200b3289SIlya Biryukov std::error_code clang::make_error_code(BuildPreambleError Error) {
82351c9349aSAlexandre Ganea return std::error_code(static_cast<int>(Error), *BuildPreambleErrCategory);
824200b3289SIlya Biryukov }
825200b3289SIlya Biryukov
name() const826200b3289SIlya Biryukov const char *BuildPreambleErrorCategory::name() const noexcept {
827200b3289SIlya Biryukov return "build-preamble.error";
828200b3289SIlya Biryukov }
829200b3289SIlya Biryukov
message(int condition) const830200b3289SIlya Biryukov std::string BuildPreambleErrorCategory::message(int condition) const {
831200b3289SIlya Biryukov switch (static_cast<BuildPreambleError>(condition)) {
832200b3289SIlya Biryukov case BuildPreambleError::CouldntCreateTempFile:
833200b3289SIlya Biryukov return "Could not create temporary file for PCH";
834200b3289SIlya Biryukov case BuildPreambleError::CouldntCreateTargetInfo:
835200b3289SIlya Biryukov return "CreateTargetInfo() return null";
836200b3289SIlya Biryukov case BuildPreambleError::BeginSourceFileFailed:
837200b3289SIlya Biryukov return "BeginSourceFile() return an error";
838200b3289SIlya Biryukov case BuildPreambleError::CouldntEmitPCH:
839200b3289SIlya Biryukov return "Could not emit PCH";
8402917526fSIlya Biryukov case BuildPreambleError::BadInputs:
8412917526fSIlya Biryukov return "Command line arguments must contain exactly one source file";
842200b3289SIlya Biryukov }
843200b3289SIlya Biryukov llvm_unreachable("unexpected BuildPreambleError");
844200b3289SIlya Biryukov }
845