xref: /openbsd-src/gnu/llvm/clang/lib/Frontend/PrecompiledPreamble.cpp (revision 12c855180aad702bbcca06e0398d774beeafb155)
1e5dd7070Spatrick //===--- PrecompiledPreamble.cpp - Build precompiled preambles --*- C++ -*-===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick // Helper class to build precompiled preamble.
10e5dd7070Spatrick //
11e5dd7070Spatrick //===----------------------------------------------------------------------===//
12e5dd7070Spatrick 
13e5dd7070Spatrick #include "clang/Frontend/PrecompiledPreamble.h"
14ec727ea7Spatrick #include "clang/Basic/FileManager.h"
15e5dd7070Spatrick #include "clang/Basic/LangStandard.h"
16e5dd7070Spatrick #include "clang/Frontend/CompilerInstance.h"
17e5dd7070Spatrick #include "clang/Frontend/CompilerInvocation.h"
18e5dd7070Spatrick #include "clang/Frontend/FrontendActions.h"
19e5dd7070Spatrick #include "clang/Frontend/FrontendOptions.h"
20ec727ea7Spatrick #include "clang/Lex/HeaderSearch.h"
21e5dd7070Spatrick #include "clang/Lex/Lexer.h"
22e5dd7070Spatrick #include "clang/Lex/Preprocessor.h"
23e5dd7070Spatrick #include "clang/Lex/PreprocessorOptions.h"
24e5dd7070Spatrick #include "clang/Serialization/ASTWriter.h"
25ec727ea7Spatrick #include "llvm/ADT/SmallString.h"
26e5dd7070Spatrick #include "llvm/ADT/StringSet.h"
27ec727ea7Spatrick #include "llvm/ADT/iterator_range.h"
28e5dd7070Spatrick #include "llvm/Config/llvm-config.h"
29e5dd7070Spatrick #include "llvm/Support/CrashRecoveryContext.h"
30e5dd7070Spatrick #include "llvm/Support/FileSystem.h"
31ec727ea7Spatrick #include "llvm/Support/Path.h"
32e5dd7070Spatrick #include "llvm/Support/Process.h"
33e5dd7070Spatrick #include "llvm/Support/VirtualFileSystem.h"
34e5dd7070Spatrick #include <limits>
35e5dd7070Spatrick #include <mutex>
36e5dd7070Spatrick #include <utility>
37e5dd7070Spatrick 
38e5dd7070Spatrick using namespace clang;
39e5dd7070Spatrick 
40e5dd7070Spatrick namespace {
41e5dd7070Spatrick 
getInMemoryPreamblePath()42e5dd7070Spatrick StringRef getInMemoryPreamblePath() {
43e5dd7070Spatrick #if defined(LLVM_ON_UNIX)
44e5dd7070Spatrick   return "/__clang_tmp/___clang_inmemory_preamble___";
45e5dd7070Spatrick #elif defined(_WIN32)
46e5dd7070Spatrick   return "C:\\__clang_tmp\\___clang_inmemory_preamble___";
47e5dd7070Spatrick #else
48e5dd7070Spatrick #warning "Unknown platform. Defaulting to UNIX-style paths for in-memory PCHs"
49e5dd7070Spatrick   return "/__clang_tmp/___clang_inmemory_preamble___";
50e5dd7070Spatrick #endif
51e5dd7070Spatrick }
52e5dd7070Spatrick 
53e5dd7070Spatrick IntrusiveRefCntPtr<llvm::vfs::FileSystem>
createVFSOverlayForPreamblePCH(StringRef PCHFilename,std::unique_ptr<llvm::MemoryBuffer> PCHBuffer,IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)54e5dd7070Spatrick createVFSOverlayForPreamblePCH(StringRef PCHFilename,
55e5dd7070Spatrick                                std::unique_ptr<llvm::MemoryBuffer> PCHBuffer,
56e5dd7070Spatrick                                IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
57e5dd7070Spatrick   // We want only the PCH file from the real filesystem to be available,
58e5dd7070Spatrick   // so we create an in-memory VFS with just that and overlay it on top.
59e5dd7070Spatrick   IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> PCHFS(
60e5dd7070Spatrick       new llvm::vfs::InMemoryFileSystem());
61e5dd7070Spatrick   PCHFS->addFile(PCHFilename, 0, std::move(PCHBuffer));
62e5dd7070Spatrick   IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> Overlay(
63e5dd7070Spatrick       new llvm::vfs::OverlayFileSystem(VFS));
64e5dd7070Spatrick   Overlay->pushOverlay(PCHFS);
65e5dd7070Spatrick   return Overlay;
66e5dd7070Spatrick }
67e5dd7070Spatrick 
68e5dd7070Spatrick class PreambleDependencyCollector : public DependencyCollector {
69e5dd7070Spatrick public:
70e5dd7070Spatrick   // We want to collect all dependencies for correctness. Avoiding the real
71e5dd7070Spatrick   // system dependencies (e.g. stl from /usr/lib) would probably be a good idea,
72e5dd7070Spatrick   // but there is no way to distinguish between those and the ones that can be
73e5dd7070Spatrick   // spuriously added by '-isystem' (e.g. to suppress warnings from those
74e5dd7070Spatrick   // headers).
needSystemDependencies()75e5dd7070Spatrick   bool needSystemDependencies() override { return true; }
76e5dd7070Spatrick };
77e5dd7070Spatrick 
78ec727ea7Spatrick // Collects files whose existence would invalidate the preamble.
79ec727ea7Spatrick // Collecting *all* of these would make validating it too slow though, so we
80ec727ea7Spatrick // just find all the candidates for 'file not found' diagnostics.
81ec727ea7Spatrick //
82ec727ea7Spatrick // A caveat that may be significant for generated files: we'll omit files under
83ec727ea7Spatrick // search path entries whose roots don't exist when the preamble is built.
84ec727ea7Spatrick // These are pruned by InitHeaderSearch and so we don't see the search path.
85ec727ea7Spatrick // It would be nice to include them but we don't want to duplicate all the rest
86ec727ea7Spatrick // of the InitHeaderSearch logic to reconstruct them.
87ec727ea7Spatrick class MissingFileCollector : public PPCallbacks {
88ec727ea7Spatrick   llvm::StringSet<> &Out;
89ec727ea7Spatrick   const HeaderSearch &Search;
90ec727ea7Spatrick   const SourceManager &SM;
91ec727ea7Spatrick 
92ec727ea7Spatrick public:
MissingFileCollector(llvm::StringSet<> & Out,const HeaderSearch & Search,const SourceManager & SM)93ec727ea7Spatrick   MissingFileCollector(llvm::StringSet<> &Out, const HeaderSearch &Search,
94ec727ea7Spatrick                        const SourceManager &SM)
95ec727ea7Spatrick       : Out(Out), Search(Search), SM(SM) {}
96ec727ea7Spatrick 
InclusionDirective(SourceLocation HashLoc,const Token & IncludeTok,StringRef FileName,bool IsAngled,CharSourceRange FilenameRange,OptionalFileEntryRef File,StringRef SearchPath,StringRef RelativePath,const Module * Imported,SrcMgr::CharacteristicKind FileType)97ec727ea7Spatrick   void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
98ec727ea7Spatrick                           StringRef FileName, bool IsAngled,
99*12c85518Srobert                           CharSourceRange FilenameRange,
100*12c85518Srobert                           OptionalFileEntryRef File, StringRef SearchPath,
101*12c85518Srobert                           StringRef RelativePath, const Module *Imported,
102ec727ea7Spatrick                           SrcMgr::CharacteristicKind FileType) override {
103*12c85518Srobert     // File is std::nullopt if it wasn't found.
104ec727ea7Spatrick     // (We have some false negatives if PP recovered e.g. <foo> -> "foo")
105*12c85518Srobert     if (File)
106ec727ea7Spatrick       return;
107ec727ea7Spatrick 
108ec727ea7Spatrick     // If it's a rare absolute include, we know the full path already.
109ec727ea7Spatrick     if (llvm::sys::path::is_absolute(FileName)) {
110ec727ea7Spatrick       Out.insert(FileName);
111ec727ea7Spatrick       return;
112ec727ea7Spatrick     }
113ec727ea7Spatrick 
114ec727ea7Spatrick     // Reconstruct the filenames that would satisfy this directive...
115ec727ea7Spatrick     llvm::SmallString<256> Buf;
116ec727ea7Spatrick     auto NotFoundRelativeTo = [&](const DirectoryEntry *DE) {
117ec727ea7Spatrick       Buf = DE->getName();
118ec727ea7Spatrick       llvm::sys::path::append(Buf, FileName);
119ec727ea7Spatrick       llvm::sys::path::remove_dots(Buf, /*remove_dot_dot=*/true);
120ec727ea7Spatrick       Out.insert(Buf);
121ec727ea7Spatrick     };
122ec727ea7Spatrick     // ...relative to the including file.
123ec727ea7Spatrick     if (!IsAngled) {
124ec727ea7Spatrick       if (const FileEntry *IncludingFile =
125ec727ea7Spatrick               SM.getFileEntryForID(SM.getFileID(IncludeTok.getLocation())))
126ec727ea7Spatrick         if (IncludingFile->getDir())
127ec727ea7Spatrick           NotFoundRelativeTo(IncludingFile->getDir());
128ec727ea7Spatrick     }
129ec727ea7Spatrick     // ...relative to the search paths.
130ec727ea7Spatrick     for (const auto &Dir : llvm::make_range(
131ec727ea7Spatrick              IsAngled ? Search.angled_dir_begin() : Search.search_dir_begin(),
132ec727ea7Spatrick              Search.search_dir_end())) {
133ec727ea7Spatrick       // No support for frameworks or header maps yet.
134ec727ea7Spatrick       if (Dir.isNormalDir())
135ec727ea7Spatrick         NotFoundRelativeTo(Dir.getDir());
136ec727ea7Spatrick     }
137ec727ea7Spatrick   }
138ec727ea7Spatrick };
139ec727ea7Spatrick 
140e5dd7070Spatrick /// Keeps a track of files to be deleted in destructor.
141e5dd7070Spatrick class TemporaryFiles {
142e5dd7070Spatrick public:
143e5dd7070Spatrick   // A static instance to be used by all clients.
144e5dd7070Spatrick   static TemporaryFiles &getInstance();
145e5dd7070Spatrick 
146e5dd7070Spatrick private:
147e5dd7070Spatrick   // Disallow constructing the class directly.
148e5dd7070Spatrick   TemporaryFiles() = default;
149e5dd7070Spatrick   // Disallow copy.
150e5dd7070Spatrick   TemporaryFiles(const TemporaryFiles &) = delete;
151e5dd7070Spatrick 
152e5dd7070Spatrick public:
153e5dd7070Spatrick   ~TemporaryFiles();
154e5dd7070Spatrick 
155e5dd7070Spatrick   /// Adds \p File to a set of tracked files.
156e5dd7070Spatrick   void addFile(StringRef File);
157e5dd7070Spatrick 
158e5dd7070Spatrick   /// Remove \p File from disk and from the set of tracked files.
159e5dd7070Spatrick   void removeFile(StringRef File);
160e5dd7070Spatrick 
161e5dd7070Spatrick private:
162e5dd7070Spatrick   std::mutex Mutex;
163e5dd7070Spatrick   llvm::StringSet<> Files;
164e5dd7070Spatrick };
165e5dd7070Spatrick 
getInstance()166e5dd7070Spatrick TemporaryFiles &TemporaryFiles::getInstance() {
167e5dd7070Spatrick   static TemporaryFiles Instance;
168e5dd7070Spatrick   return Instance;
169e5dd7070Spatrick }
170e5dd7070Spatrick 
~TemporaryFiles()171e5dd7070Spatrick TemporaryFiles::~TemporaryFiles() {
172e5dd7070Spatrick   std::lock_guard<std::mutex> Guard(Mutex);
173e5dd7070Spatrick   for (const auto &File : Files)
174e5dd7070Spatrick     llvm::sys::fs::remove(File.getKey());
175e5dd7070Spatrick }
176e5dd7070Spatrick 
addFile(StringRef File)177e5dd7070Spatrick void TemporaryFiles::addFile(StringRef File) {
178e5dd7070Spatrick   std::lock_guard<std::mutex> Guard(Mutex);
179e5dd7070Spatrick   auto IsInserted = Files.insert(File).second;
180e5dd7070Spatrick   (void)IsInserted;
181e5dd7070Spatrick   assert(IsInserted && "File has already been added");
182e5dd7070Spatrick }
183e5dd7070Spatrick 
removeFile(StringRef File)184e5dd7070Spatrick void TemporaryFiles::removeFile(StringRef File) {
185e5dd7070Spatrick   std::lock_guard<std::mutex> Guard(Mutex);
186e5dd7070Spatrick   auto WasPresent = Files.erase(File);
187e5dd7070Spatrick   (void)WasPresent;
188e5dd7070Spatrick   assert(WasPresent && "File was not tracked");
189e5dd7070Spatrick   llvm::sys::fs::remove(File);
190e5dd7070Spatrick }
191e5dd7070Spatrick 
192*12c85518Srobert // A temp file that would be deleted on destructor call. If destructor is not
193*12c85518Srobert // called for any reason, the file will be deleted at static objects'
194*12c85518Srobert // destruction.
195*12c85518Srobert // An assertion will fire if two TempPCHFiles are created with the same name,
196*12c85518Srobert // so it's not intended to be used outside preamble-handling.
197*12c85518Srobert class TempPCHFile {
198*12c85518Srobert public:
199*12c85518Srobert   // A main method used to construct TempPCHFile.
create()200*12c85518Srobert   static std::unique_ptr<TempPCHFile> create() {
201*12c85518Srobert     // FIXME: This is a hack so that we can override the preamble file during
202*12c85518Srobert     // crash-recovery testing, which is the only case where the preamble files
203*12c85518Srobert     // are not necessarily cleaned up.
204*12c85518Srobert     if (const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE"))
205*12c85518Srobert       return std::unique_ptr<TempPCHFile>(new TempPCHFile(TmpFile));
206*12c85518Srobert 
207*12c85518Srobert     llvm::SmallString<64> File;
208*12c85518Srobert     // Using a version of createTemporaryFile with a file descriptor guarantees
209*12c85518Srobert     // that we would never get a race condition in a multi-threaded setting
210*12c85518Srobert     // (i.e., multiple threads getting the same temporary path).
211*12c85518Srobert     int FD;
212*12c85518Srobert     if (auto EC =
213*12c85518Srobert             llvm::sys::fs::createTemporaryFile("preamble", "pch", FD, File))
214*12c85518Srobert       return nullptr;
215*12c85518Srobert     // We only needed to make sure the file exists, close the file right away.
216*12c85518Srobert     llvm::sys::Process::SafelyCloseFileDescriptor(FD);
217*12c85518Srobert     return std::unique_ptr<TempPCHFile>(new TempPCHFile(File.str().str()));
218*12c85518Srobert   }
219*12c85518Srobert 
220*12c85518Srobert   TempPCHFile &operator=(const TempPCHFile &) = delete;
221*12c85518Srobert   TempPCHFile(const TempPCHFile &) = delete;
~TempPCHFile()222*12c85518Srobert   ~TempPCHFile() { TemporaryFiles::getInstance().removeFile(FilePath); };
223*12c85518Srobert 
224*12c85518Srobert   /// A path where temporary file is stored.
getFilePath() const225*12c85518Srobert   llvm::StringRef getFilePath() const { return FilePath; };
226*12c85518Srobert 
227*12c85518Srobert private:
TempPCHFile(std::string FilePath)228*12c85518Srobert   TempPCHFile(std::string FilePath) : FilePath(std::move(FilePath)) {
229*12c85518Srobert     TemporaryFiles::getInstance().addFile(this->FilePath);
230*12c85518Srobert   }
231*12c85518Srobert 
232*12c85518Srobert   std::string FilePath;
233*12c85518Srobert };
234*12c85518Srobert 
235e5dd7070Spatrick class PrecompilePreambleAction : public ASTFrontendAction {
236e5dd7070Spatrick public:
PrecompilePreambleAction(std::shared_ptr<PCHBuffer> Buffer,bool WritePCHFile,PreambleCallbacks & Callbacks)237*12c85518Srobert   PrecompilePreambleAction(std::shared_ptr<PCHBuffer> Buffer, bool WritePCHFile,
238e5dd7070Spatrick                            PreambleCallbacks &Callbacks)
239*12c85518Srobert       : Buffer(std::move(Buffer)), WritePCHFile(WritePCHFile),
240*12c85518Srobert         Callbacks(Callbacks) {}
241e5dd7070Spatrick 
242e5dd7070Spatrick   std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
243e5dd7070Spatrick                                                  StringRef InFile) override;
244e5dd7070Spatrick 
hasEmittedPreamblePCH() const245e5dd7070Spatrick   bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
246e5dd7070Spatrick 
setEmittedPreamblePCH(ASTWriter & Writer)247e5dd7070Spatrick   void setEmittedPreamblePCH(ASTWriter &Writer) {
248*12c85518Srobert     if (FileOS) {
249*12c85518Srobert       *FileOS << Buffer->Data;
250*12c85518Srobert       // Make sure it hits disk now.
251*12c85518Srobert       FileOS.reset();
252*12c85518Srobert     }
253*12c85518Srobert 
254e5dd7070Spatrick     this->HasEmittedPreamblePCH = true;
255e5dd7070Spatrick     Callbacks.AfterPCHEmitted(Writer);
256e5dd7070Spatrick   }
257e5dd7070Spatrick 
BeginSourceFileAction(CompilerInstance & CI)258a9ac8606Spatrick   bool BeginSourceFileAction(CompilerInstance &CI) override {
259a9ac8606Spatrick     assert(CI.getLangOpts().CompilingPCH);
260a9ac8606Spatrick     return ASTFrontendAction::BeginSourceFileAction(CI);
261a9ac8606Spatrick   }
262a9ac8606Spatrick 
shouldEraseOutputFiles()263e5dd7070Spatrick   bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
hasCodeCompletionSupport() const264e5dd7070Spatrick   bool hasCodeCompletionSupport() const override { return false; }
hasASTFileSupport() const265e5dd7070Spatrick   bool hasASTFileSupport() const override { return false; }
getTranslationUnitKind()266e5dd7070Spatrick   TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
267e5dd7070Spatrick 
268e5dd7070Spatrick private:
269e5dd7070Spatrick   friend class PrecompilePreambleConsumer;
270e5dd7070Spatrick 
271e5dd7070Spatrick   bool HasEmittedPreamblePCH = false;
272*12c85518Srobert   std::shared_ptr<PCHBuffer> Buffer;
273*12c85518Srobert   bool WritePCHFile; // otherwise the PCH is written into the PCHBuffer only.
274*12c85518Srobert   std::unique_ptr<llvm::raw_pwrite_stream> FileOS; // null if in-memory
275e5dd7070Spatrick   PreambleCallbacks &Callbacks;
276e5dd7070Spatrick };
277e5dd7070Spatrick 
278e5dd7070Spatrick class PrecompilePreambleConsumer : public PCHGenerator {
279e5dd7070Spatrick public:
PrecompilePreambleConsumer(PrecompilePreambleAction & Action,const Preprocessor & PP,InMemoryModuleCache & ModuleCache,StringRef isysroot,std::shared_ptr<PCHBuffer> Buffer)280e5dd7070Spatrick   PrecompilePreambleConsumer(PrecompilePreambleAction &Action,
281e5dd7070Spatrick                              const Preprocessor &PP,
282e5dd7070Spatrick                              InMemoryModuleCache &ModuleCache,
283e5dd7070Spatrick                              StringRef isysroot,
284*12c85518Srobert                              std::shared_ptr<PCHBuffer> Buffer)
285*12c85518Srobert       : PCHGenerator(PP, ModuleCache, "", isysroot, std::move(Buffer),
286e5dd7070Spatrick                      ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
287e5dd7070Spatrick                      /*AllowASTWithErrors=*/true),
288*12c85518Srobert         Action(Action) {}
289e5dd7070Spatrick 
HandleTopLevelDecl(DeclGroupRef DG)290e5dd7070Spatrick   bool HandleTopLevelDecl(DeclGroupRef DG) override {
291e5dd7070Spatrick     Action.Callbacks.HandleTopLevelDecl(DG);
292e5dd7070Spatrick     return true;
293e5dd7070Spatrick   }
294e5dd7070Spatrick 
HandleTranslationUnit(ASTContext & Ctx)295e5dd7070Spatrick   void HandleTranslationUnit(ASTContext &Ctx) override {
296e5dd7070Spatrick     PCHGenerator::HandleTranslationUnit(Ctx);
297e5dd7070Spatrick     if (!hasEmittedPCH())
298e5dd7070Spatrick       return;
299e5dd7070Spatrick     Action.setEmittedPreamblePCH(getWriter());
300e5dd7070Spatrick   }
301e5dd7070Spatrick 
shouldSkipFunctionBody(Decl * D)302ec727ea7Spatrick   bool shouldSkipFunctionBody(Decl *D) override {
303ec727ea7Spatrick     return Action.Callbacks.shouldSkipFunctionBody(D);
304ec727ea7Spatrick   }
305ec727ea7Spatrick 
306e5dd7070Spatrick private:
307e5dd7070Spatrick   PrecompilePreambleAction &Action;
308e5dd7070Spatrick };
309e5dd7070Spatrick 
310e5dd7070Spatrick std::unique_ptr<ASTConsumer>
CreateASTConsumer(CompilerInstance & CI,StringRef InFile)311e5dd7070Spatrick PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
312e5dd7070Spatrick                                             StringRef InFile) {
313e5dd7070Spatrick   std::string Sysroot;
314e5dd7070Spatrick   if (!GeneratePCHAction::ComputeASTConsumerArguments(CI, Sysroot))
315e5dd7070Spatrick     return nullptr;
316e5dd7070Spatrick 
317*12c85518Srobert   if (WritePCHFile) {
318*12c85518Srobert     std::string OutputFile; // unused
319*12c85518Srobert     FileOS = GeneratePCHAction::CreateOutputFile(CI, InFile, OutputFile);
320*12c85518Srobert     if (!FileOS)
321e5dd7070Spatrick       return nullptr;
322*12c85518Srobert   }
323e5dd7070Spatrick 
324e5dd7070Spatrick   if (!CI.getFrontendOpts().RelocatablePCH)
325e5dd7070Spatrick     Sysroot.clear();
326e5dd7070Spatrick 
327e5dd7070Spatrick   return std::make_unique<PrecompilePreambleConsumer>(
328*12c85518Srobert       *this, CI.getPreprocessor(), CI.getModuleCache(), Sysroot, Buffer);
329e5dd7070Spatrick }
330e5dd7070Spatrick 
moveOnNoError(llvm::ErrorOr<T> Val,T & Output)331e5dd7070Spatrick template <class T> bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
332e5dd7070Spatrick   if (!Val)
333e5dd7070Spatrick     return false;
334e5dd7070Spatrick   Output = std::move(*Val);
335e5dd7070Spatrick   return true;
336e5dd7070Spatrick }
337e5dd7070Spatrick 
338e5dd7070Spatrick } // namespace
339e5dd7070Spatrick 
ComputePreambleBounds(const LangOptions & LangOpts,const llvm::MemoryBufferRef & Buffer,unsigned MaxLines)340e5dd7070Spatrick PreambleBounds clang::ComputePreambleBounds(const LangOptions &LangOpts,
341a9ac8606Spatrick                                             const llvm::MemoryBufferRef &Buffer,
342e5dd7070Spatrick                                             unsigned MaxLines) {
343a9ac8606Spatrick   return Lexer::ComputePreamble(Buffer.getBuffer(), LangOpts, MaxLines);
344e5dd7070Spatrick }
345e5dd7070Spatrick 
346*12c85518Srobert class PrecompiledPreamble::PCHStorage {
347*12c85518Srobert public:
file(std::unique_ptr<TempPCHFile> File)348*12c85518Srobert   static std::unique_ptr<PCHStorage> file(std::unique_ptr<TempPCHFile> File) {
349*12c85518Srobert     assert(File);
350*12c85518Srobert     std::unique_ptr<PCHStorage> S(new PCHStorage());
351*12c85518Srobert     S->File = std::move(File);
352*12c85518Srobert     return S;
353*12c85518Srobert   }
inMemory(std::shared_ptr<PCHBuffer> Buf)354*12c85518Srobert   static std::unique_ptr<PCHStorage> inMemory(std::shared_ptr<PCHBuffer> Buf) {
355*12c85518Srobert     std::unique_ptr<PCHStorage> S(new PCHStorage());
356*12c85518Srobert     S->Memory = std::move(Buf);
357*12c85518Srobert     return S;
358*12c85518Srobert   }
359*12c85518Srobert 
360*12c85518Srobert   enum class Kind { InMemory, TempFile };
getKind() const361*12c85518Srobert   Kind getKind() const {
362*12c85518Srobert     if (Memory)
363*12c85518Srobert       return Kind::InMemory;
364*12c85518Srobert     if (File)
365*12c85518Srobert       return Kind::TempFile;
366*12c85518Srobert     llvm_unreachable("Neither Memory nor File?");
367*12c85518Srobert   }
filePath() const368*12c85518Srobert   llvm::StringRef filePath() const {
369*12c85518Srobert     assert(getKind() == Kind::TempFile);
370*12c85518Srobert     return File->getFilePath();
371*12c85518Srobert   }
memoryContents() const372*12c85518Srobert   llvm::StringRef memoryContents() const {
373*12c85518Srobert     assert(getKind() == Kind::InMemory);
374*12c85518Srobert     return StringRef(Memory->Data.data(), Memory->Data.size());
375*12c85518Srobert   }
376*12c85518Srobert 
377*12c85518Srobert   // Shrink in-memory buffers to fit.
378*12c85518Srobert   // This incurs a copy, but preambles tend to be long-lived.
379*12c85518Srobert   // Only safe to call once nothing can alias the buffer.
shrink()380*12c85518Srobert   void shrink() {
381*12c85518Srobert     if (!Memory)
382*12c85518Srobert       return;
383*12c85518Srobert     Memory->Data = decltype(Memory->Data)(Memory->Data);
384*12c85518Srobert   }
385*12c85518Srobert 
386*12c85518Srobert private:
387*12c85518Srobert   PCHStorage() = default;
388*12c85518Srobert   PCHStorage(const PCHStorage &) = delete;
389*12c85518Srobert   PCHStorage &operator=(const PCHStorage &) = delete;
390*12c85518Srobert 
391*12c85518Srobert   std::shared_ptr<PCHBuffer> Memory;
392*12c85518Srobert   std::unique_ptr<TempPCHFile> File;
393*12c85518Srobert };
394*12c85518Srobert 
395*12c85518Srobert PrecompiledPreamble::~PrecompiledPreamble() = default;
396*12c85518Srobert PrecompiledPreamble::PrecompiledPreamble(PrecompiledPreamble &&) = default;
397*12c85518Srobert PrecompiledPreamble &
398*12c85518Srobert PrecompiledPreamble::operator=(PrecompiledPreamble &&) = default;
399*12c85518Srobert 
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)400e5dd7070Spatrick llvm::ErrorOr<PrecompiledPreamble> PrecompiledPreamble::Build(
401e5dd7070Spatrick     const CompilerInvocation &Invocation,
402e5dd7070Spatrick     const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds,
403e5dd7070Spatrick     DiagnosticsEngine &Diagnostics,
404e5dd7070Spatrick     IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
405e5dd7070Spatrick     std::shared_ptr<PCHContainerOperations> PCHContainerOps, bool StoreInMemory,
406e5dd7070Spatrick     PreambleCallbacks &Callbacks) {
407e5dd7070Spatrick   assert(VFS && "VFS is null");
408e5dd7070Spatrick 
409e5dd7070Spatrick   auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
410e5dd7070Spatrick   FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
411e5dd7070Spatrick   PreprocessorOptions &PreprocessorOpts =
412e5dd7070Spatrick       PreambleInvocation->getPreprocessorOpts();
413e5dd7070Spatrick 
414*12c85518Srobert   std::shared_ptr<PCHBuffer> Buffer = std::make_shared<PCHBuffer>();
415*12c85518Srobert   std::unique_ptr<PCHStorage> Storage;
416*12c85518Srobert   if (StoreInMemory) {
417*12c85518Srobert     Storage = PCHStorage::inMemory(Buffer);
418*12c85518Srobert   } else {
419e5dd7070Spatrick     // Create a temporary file for the precompiled preamble. In rare
420e5dd7070Spatrick     // circumstances, this can fail.
421*12c85518Srobert     std::unique_ptr<TempPCHFile> PreamblePCHFile = TempPCHFile::create();
422e5dd7070Spatrick     if (!PreamblePCHFile)
423e5dd7070Spatrick       return BuildPreambleError::CouldntCreateTempFile;
424*12c85518Srobert     Storage = PCHStorage::file(std::move(PreamblePCHFile));
425e5dd7070Spatrick   }
426e5dd7070Spatrick 
427e5dd7070Spatrick   // Save the preamble text for later; we'll need to compare against it for
428e5dd7070Spatrick   // subsequent reparses.
429e5dd7070Spatrick   std::vector<char> PreambleBytes(MainFileBuffer->getBufferStart(),
430e5dd7070Spatrick                                   MainFileBuffer->getBufferStart() +
431e5dd7070Spatrick                                       Bounds.Size);
432e5dd7070Spatrick   bool PreambleEndsAtStartOfLine = Bounds.PreambleEndsAtStartOfLine;
433e5dd7070Spatrick 
434e5dd7070Spatrick   // Tell the compiler invocation to generate a temporary precompiled header.
435e5dd7070Spatrick   FrontendOpts.ProgramAction = frontend::GeneratePCH;
436*12c85518Srobert   FrontendOpts.OutputFile = std::string(
437*12c85518Srobert       StoreInMemory ? getInMemoryPreamblePath() : Storage->filePath());
438e5dd7070Spatrick   PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
439e5dd7070Spatrick   PreprocessorOpts.PrecompiledPreambleBytes.second = false;
440e5dd7070Spatrick   // Inform preprocessor to record conditional stack when building the preamble.
441e5dd7070Spatrick   PreprocessorOpts.GeneratePreamble = true;
442e5dd7070Spatrick 
443e5dd7070Spatrick   // Create the compiler instance to use for building the precompiled preamble.
444e5dd7070Spatrick   std::unique_ptr<CompilerInstance> Clang(
445e5dd7070Spatrick       new CompilerInstance(std::move(PCHContainerOps)));
446e5dd7070Spatrick 
447e5dd7070Spatrick   // Recover resources if we crash before exiting this method.
448e5dd7070Spatrick   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
449e5dd7070Spatrick       Clang.get());
450e5dd7070Spatrick 
451e5dd7070Spatrick   Clang->setInvocation(std::move(PreambleInvocation));
452e5dd7070Spatrick   Clang->setDiagnostics(&Diagnostics);
453e5dd7070Spatrick 
454e5dd7070Spatrick   // Create the target instance.
455a9ac8606Spatrick   if (!Clang->createTarget())
456e5dd7070Spatrick     return BuildPreambleError::CouldntCreateTargetInfo;
457e5dd7070Spatrick 
458e5dd7070Spatrick   if (Clang->getFrontendOpts().Inputs.size() != 1 ||
459e5dd7070Spatrick       Clang->getFrontendOpts().Inputs[0].getKind().getFormat() !=
460e5dd7070Spatrick           InputKind::Source ||
461e5dd7070Spatrick       Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() ==
462e5dd7070Spatrick           Language::LLVM_IR) {
463e5dd7070Spatrick     return BuildPreambleError::BadInputs;
464e5dd7070Spatrick   }
465e5dd7070Spatrick 
466e5dd7070Spatrick   // Clear out old caches and data.
467e5dd7070Spatrick   Diagnostics.Reset();
468e5dd7070Spatrick   ProcessWarningOptions(Diagnostics, Clang->getDiagnosticOpts());
469e5dd7070Spatrick 
470e5dd7070Spatrick   VFS =
471e5dd7070Spatrick       createVFSFromCompilerInvocation(Clang->getInvocation(), Diagnostics, VFS);
472e5dd7070Spatrick 
473e5dd7070Spatrick   // Create a file manager object to provide access to and cache the filesystem.
474e5dd7070Spatrick   Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
475e5dd7070Spatrick 
476e5dd7070Spatrick   // Create the source manager.
477e5dd7070Spatrick   Clang->setSourceManager(
478e5dd7070Spatrick       new SourceManager(Diagnostics, Clang->getFileManager()));
479e5dd7070Spatrick 
480e5dd7070Spatrick   auto PreambleDepCollector = std::make_shared<PreambleDependencyCollector>();
481e5dd7070Spatrick   Clang->addDependencyCollector(PreambleDepCollector);
482e5dd7070Spatrick 
483a9ac8606Spatrick   Clang->getLangOpts().CompilingPCH = true;
484a9ac8606Spatrick 
485e5dd7070Spatrick   // Remap the main source file to the preamble buffer.
486e5dd7070Spatrick   StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
487e5dd7070Spatrick   auto PreambleInputBuffer = llvm::MemoryBuffer::getMemBufferCopy(
488e5dd7070Spatrick       MainFileBuffer->getBuffer().slice(0, Bounds.Size), MainFilePath);
489e5dd7070Spatrick   if (PreprocessorOpts.RetainRemappedFileBuffers) {
490e5dd7070Spatrick     // MainFileBuffer will be deleted by unique_ptr after leaving the method.
491e5dd7070Spatrick     PreprocessorOpts.addRemappedFile(MainFilePath, PreambleInputBuffer.get());
492e5dd7070Spatrick   } else {
493e5dd7070Spatrick     // In that case, remapped buffer will be deleted by CompilerInstance on
494e5dd7070Spatrick     // BeginSourceFile, so we call release() to avoid double deletion.
495e5dd7070Spatrick     PreprocessorOpts.addRemappedFile(MainFilePath,
496e5dd7070Spatrick                                      PreambleInputBuffer.release());
497e5dd7070Spatrick   }
498e5dd7070Spatrick 
499*12c85518Srobert   auto Act = std::make_unique<PrecompilePreambleAction>(
500*12c85518Srobert       std::move(Buffer),
501*12c85518Srobert       /*WritePCHFile=*/Storage->getKind() == PCHStorage::Kind::TempFile,
502*12c85518Srobert       Callbacks);
503e5dd7070Spatrick   if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
504e5dd7070Spatrick     return BuildPreambleError::BeginSourceFileFailed;
505e5dd7070Spatrick 
506*12c85518Srobert   // Performed after BeginSourceFile to ensure Clang->Preprocessor can be
507*12c85518Srobert   // referenced in the callback.
508*12c85518Srobert   Callbacks.BeforeExecute(*Clang);
509*12c85518Srobert 
510e5dd7070Spatrick   std::unique_ptr<PPCallbacks> DelegatedPPCallbacks =
511e5dd7070Spatrick       Callbacks.createPPCallbacks();
512e5dd7070Spatrick   if (DelegatedPPCallbacks)
513e5dd7070Spatrick     Clang->getPreprocessor().addPPCallbacks(std::move(DelegatedPPCallbacks));
514e5dd7070Spatrick   if (auto CommentHandler = Callbacks.getCommentHandler())
515e5dd7070Spatrick     Clang->getPreprocessor().addCommentHandler(CommentHandler);
516ec727ea7Spatrick   llvm::StringSet<> MissingFiles;
517ec727ea7Spatrick   Clang->getPreprocessor().addPPCallbacks(
518ec727ea7Spatrick       std::make_unique<MissingFileCollector>(
519ec727ea7Spatrick           MissingFiles, Clang->getPreprocessor().getHeaderSearchInfo(),
520ec727ea7Spatrick           Clang->getSourceManager()));
521e5dd7070Spatrick 
522e5dd7070Spatrick   if (llvm::Error Err = Act->Execute())
523e5dd7070Spatrick     return errorToErrorCode(std::move(Err));
524e5dd7070Spatrick 
525e5dd7070Spatrick   // Run the callbacks.
526e5dd7070Spatrick   Callbacks.AfterExecute(*Clang);
527e5dd7070Spatrick 
528e5dd7070Spatrick   Act->EndSourceFile();
529e5dd7070Spatrick 
530e5dd7070Spatrick   if (!Act->hasEmittedPreamblePCH())
531e5dd7070Spatrick     return BuildPreambleError::CouldntEmitPCH;
532*12c85518Srobert   Act.reset(); // Frees the PCH buffer, unless Storage keeps it in memory.
533e5dd7070Spatrick 
534e5dd7070Spatrick   // Keep track of all of the files that the source manager knows about,
535e5dd7070Spatrick   // so we can verify whether they have changed or not.
536e5dd7070Spatrick   llvm::StringMap<PrecompiledPreamble::PreambleFileHash> FilesInPreamble;
537e5dd7070Spatrick 
538e5dd7070Spatrick   SourceManager &SourceMgr = Clang->getSourceManager();
539e5dd7070Spatrick   for (auto &Filename : PreambleDepCollector->getDependencies()) {
540e5dd7070Spatrick     auto FileOrErr = Clang->getFileManager().getFile(Filename);
541e5dd7070Spatrick     if (!FileOrErr ||
542e5dd7070Spatrick         *FileOrErr == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
543e5dd7070Spatrick       continue;
544e5dd7070Spatrick     auto File = *FileOrErr;
545e5dd7070Spatrick     if (time_t ModTime = File->getModificationTime()) {
546e5dd7070Spatrick       FilesInPreamble[File->getName()] =
547e5dd7070Spatrick           PrecompiledPreamble::PreambleFileHash::createForFile(File->getSize(),
548e5dd7070Spatrick                                                                ModTime);
549e5dd7070Spatrick     } else {
550a9ac8606Spatrick       llvm::MemoryBufferRef Buffer =
551a9ac8606Spatrick           SourceMgr.getMemoryBufferForFileOrFake(File);
552e5dd7070Spatrick       FilesInPreamble[File->getName()] =
553e5dd7070Spatrick           PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(Buffer);
554e5dd7070Spatrick     }
555e5dd7070Spatrick   }
556e5dd7070Spatrick 
557*12c85518Srobert   // Shrinking the storage requires extra temporary memory.
558*12c85518Srobert   // Destroying clang first reduces peak memory usage.
559*12c85518Srobert   CICleanup.unregister();
560*12c85518Srobert   Clang.reset();
561*12c85518Srobert   Storage->shrink();
562ec727ea7Spatrick   return PrecompiledPreamble(
563ec727ea7Spatrick       std::move(Storage), std::move(PreambleBytes), PreambleEndsAtStartOfLine,
564ec727ea7Spatrick       std::move(FilesInPreamble), std::move(MissingFiles));
565e5dd7070Spatrick }
566e5dd7070Spatrick 
getBounds() const567e5dd7070Spatrick PreambleBounds PrecompiledPreamble::getBounds() const {
568e5dd7070Spatrick   return PreambleBounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
569e5dd7070Spatrick }
570e5dd7070Spatrick 
getSize() const571e5dd7070Spatrick std::size_t PrecompiledPreamble::getSize() const {
572*12c85518Srobert   switch (Storage->getKind()) {
573e5dd7070Spatrick   case PCHStorage::Kind::InMemory:
574*12c85518Srobert     return Storage->memoryContents().size();
575e5dd7070Spatrick   case PCHStorage::Kind::TempFile: {
576e5dd7070Spatrick     uint64_t Result;
577*12c85518Srobert     if (llvm::sys::fs::file_size(Storage->filePath(), Result))
578e5dd7070Spatrick       return 0;
579e5dd7070Spatrick 
580e5dd7070Spatrick     assert(Result <= std::numeric_limits<std::size_t>::max() &&
581e5dd7070Spatrick            "file size did not fit into size_t");
582e5dd7070Spatrick     return Result;
583e5dd7070Spatrick   }
584e5dd7070Spatrick   }
585e5dd7070Spatrick   llvm_unreachable("Unhandled storage kind");
586e5dd7070Spatrick }
587e5dd7070Spatrick 
CanReuse(const CompilerInvocation & Invocation,const llvm::MemoryBufferRef & MainFileBuffer,PreambleBounds Bounds,llvm::vfs::FileSystem & VFS) const588e5dd7070Spatrick bool PrecompiledPreamble::CanReuse(const CompilerInvocation &Invocation,
589a9ac8606Spatrick                                    const llvm::MemoryBufferRef &MainFileBuffer,
590e5dd7070Spatrick                                    PreambleBounds Bounds,
591a9ac8606Spatrick                                    llvm::vfs::FileSystem &VFS) const {
592e5dd7070Spatrick 
593e5dd7070Spatrick   assert(
594a9ac8606Spatrick       Bounds.Size <= MainFileBuffer.getBufferSize() &&
595e5dd7070Spatrick       "Buffer is too large. Bounds were calculated from a different buffer?");
596e5dd7070Spatrick 
597e5dd7070Spatrick   auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
598e5dd7070Spatrick   PreprocessorOptions &PreprocessorOpts =
599e5dd7070Spatrick       PreambleInvocation->getPreprocessorOpts();
600e5dd7070Spatrick 
601e5dd7070Spatrick   // We've previously computed a preamble. Check whether we have the same
602e5dd7070Spatrick   // preamble now that we did before, and that there's enough space in
603e5dd7070Spatrick   // the main-file buffer within the precompiled preamble to fit the
604e5dd7070Spatrick   // new main file.
605e5dd7070Spatrick   if (PreambleBytes.size() != Bounds.Size ||
606e5dd7070Spatrick       PreambleEndsAtStartOfLine != Bounds.PreambleEndsAtStartOfLine ||
607e5dd7070Spatrick       !std::equal(PreambleBytes.begin(), PreambleBytes.end(),
608a9ac8606Spatrick                   MainFileBuffer.getBuffer().begin()))
609e5dd7070Spatrick     return false;
610e5dd7070Spatrick   // The preamble has not changed. We may be able to re-use the precompiled
611e5dd7070Spatrick   // preamble.
612e5dd7070Spatrick 
613e5dd7070Spatrick   // Check that none of the files used by the preamble have changed.
614e5dd7070Spatrick   // First, make a record of those files that have been overridden via
615e5dd7070Spatrick   // remapping or unsaved_files.
616e5dd7070Spatrick   std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
617ec727ea7Spatrick   llvm::StringSet<> OverriddenAbsPaths; // Either by buffers or files.
618e5dd7070Spatrick   for (const auto &R : PreprocessorOpts.RemappedFiles) {
619e5dd7070Spatrick     llvm::vfs::Status Status;
620a9ac8606Spatrick     if (!moveOnNoError(VFS.status(R.second), Status)) {
621e5dd7070Spatrick       // If we can't stat the file we're remapping to, assume that something
622e5dd7070Spatrick       // horrible happened.
623e5dd7070Spatrick       return false;
624e5dd7070Spatrick     }
625ec727ea7Spatrick     // If a mapped file was previously missing, then it has changed.
626ec727ea7Spatrick     llvm::SmallString<128> MappedPath(R.first);
627a9ac8606Spatrick     if (!VFS.makeAbsolute(MappedPath))
628ec727ea7Spatrick       OverriddenAbsPaths.insert(MappedPath);
629e5dd7070Spatrick 
630e5dd7070Spatrick     OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
631e5dd7070Spatrick         Status.getSize(), llvm::sys::toTimeT(Status.getLastModificationTime()));
632e5dd7070Spatrick   }
633e5dd7070Spatrick 
634e5dd7070Spatrick   // OverridenFileBuffers tracks only the files not found in VFS.
635e5dd7070Spatrick   llvm::StringMap<PreambleFileHash> OverridenFileBuffers;
636e5dd7070Spatrick   for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
637e5dd7070Spatrick     const PrecompiledPreamble::PreambleFileHash PreambleHash =
638a9ac8606Spatrick         PreambleFileHash::createForMemoryBuffer(RB.second->getMemBufferRef());
639e5dd7070Spatrick     llvm::vfs::Status Status;
640a9ac8606Spatrick     if (moveOnNoError(VFS.status(RB.first), Status))
641e5dd7070Spatrick       OverriddenFiles[Status.getUniqueID()] = PreambleHash;
642e5dd7070Spatrick     else
643e5dd7070Spatrick       OverridenFileBuffers[RB.first] = PreambleHash;
644ec727ea7Spatrick 
645ec727ea7Spatrick     llvm::SmallString<128> MappedPath(RB.first);
646a9ac8606Spatrick     if (!VFS.makeAbsolute(MappedPath))
647ec727ea7Spatrick       OverriddenAbsPaths.insert(MappedPath);
648e5dd7070Spatrick   }
649e5dd7070Spatrick 
650e5dd7070Spatrick   // Check whether anything has changed.
651e5dd7070Spatrick   for (const auto &F : FilesInPreamble) {
652e5dd7070Spatrick     auto OverridenFileBuffer = OverridenFileBuffers.find(F.first());
653e5dd7070Spatrick     if (OverridenFileBuffer != OverridenFileBuffers.end()) {
654e5dd7070Spatrick       // The file's buffer was remapped and the file was not found in VFS.
655e5dd7070Spatrick       // Check whether it matches up with the previous mapping.
656e5dd7070Spatrick       if (OverridenFileBuffer->second != F.second)
657e5dd7070Spatrick         return false;
658e5dd7070Spatrick       continue;
659e5dd7070Spatrick     }
660e5dd7070Spatrick 
661e5dd7070Spatrick     llvm::vfs::Status Status;
662a9ac8606Spatrick     if (!moveOnNoError(VFS.status(F.first()), Status)) {
663e5dd7070Spatrick       // If the file's buffer is not remapped and we can't stat it,
664e5dd7070Spatrick       // assume that something horrible happened.
665e5dd7070Spatrick       return false;
666e5dd7070Spatrick     }
667e5dd7070Spatrick 
668e5dd7070Spatrick     std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden =
669e5dd7070Spatrick         OverriddenFiles.find(Status.getUniqueID());
670e5dd7070Spatrick     if (Overridden != OverriddenFiles.end()) {
671e5dd7070Spatrick       // This file was remapped; check whether the newly-mapped file
672e5dd7070Spatrick       // matches up with the previous mapping.
673e5dd7070Spatrick       if (Overridden->second != F.second)
674e5dd7070Spatrick         return false;
675e5dd7070Spatrick       continue;
676e5dd7070Spatrick     }
677e5dd7070Spatrick 
678e5dd7070Spatrick     // Neither the file's buffer nor the file itself was remapped;
679e5dd7070Spatrick     // check whether it has changed on disk.
680e5dd7070Spatrick     if (Status.getSize() != uint64_t(F.second.Size) ||
681e5dd7070Spatrick         llvm::sys::toTimeT(Status.getLastModificationTime()) !=
682e5dd7070Spatrick             F.second.ModTime)
683e5dd7070Spatrick       return false;
684e5dd7070Spatrick   }
685ec727ea7Spatrick   for (const auto &F : MissingFiles) {
686ec727ea7Spatrick     // A missing file may be "provided" by an override buffer or file.
687ec727ea7Spatrick     if (OverriddenAbsPaths.count(F.getKey()))
688ec727ea7Spatrick       return false;
689ec727ea7Spatrick     // If a file previously recorded as missing exists as a regular file, then
690ec727ea7Spatrick     // consider the preamble out-of-date.
691a9ac8606Spatrick     if (auto Status = VFS.status(F.getKey())) {
692ec727ea7Spatrick       if (Status->isRegularFile())
693ec727ea7Spatrick         return false;
694ec727ea7Spatrick     }
695ec727ea7Spatrick   }
696e5dd7070Spatrick   return true;
697e5dd7070Spatrick }
698e5dd7070Spatrick 
AddImplicitPreamble(CompilerInvocation & CI,IntrusiveRefCntPtr<llvm::vfs::FileSystem> & VFS,llvm::MemoryBuffer * MainFileBuffer) const699e5dd7070Spatrick void PrecompiledPreamble::AddImplicitPreamble(
700e5dd7070Spatrick     CompilerInvocation &CI, IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
701e5dd7070Spatrick     llvm::MemoryBuffer *MainFileBuffer) const {
702e5dd7070Spatrick   PreambleBounds Bounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
703e5dd7070Spatrick   configurePreamble(Bounds, CI, VFS, MainFileBuffer);
704e5dd7070Spatrick }
705e5dd7070Spatrick 
OverridePreamble(CompilerInvocation & CI,IntrusiveRefCntPtr<llvm::vfs::FileSystem> & VFS,llvm::MemoryBuffer * MainFileBuffer) const706e5dd7070Spatrick void PrecompiledPreamble::OverridePreamble(
707e5dd7070Spatrick     CompilerInvocation &CI, IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
708e5dd7070Spatrick     llvm::MemoryBuffer *MainFileBuffer) const {
709a9ac8606Spatrick   auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), *MainFileBuffer, 0);
710e5dd7070Spatrick   configurePreamble(Bounds, CI, VFS, MainFileBuffer);
711e5dd7070Spatrick }
712e5dd7070Spatrick 
PrecompiledPreamble(std::unique_ptr<PCHStorage> Storage,std::vector<char> PreambleBytes,bool PreambleEndsAtStartOfLine,llvm::StringMap<PreambleFileHash> FilesInPreamble,llvm::StringSet<> MissingFiles)713e5dd7070Spatrick PrecompiledPreamble::PrecompiledPreamble(
714*12c85518Srobert     std::unique_ptr<PCHStorage> Storage, std::vector<char> PreambleBytes,
715e5dd7070Spatrick     bool PreambleEndsAtStartOfLine,
716ec727ea7Spatrick     llvm::StringMap<PreambleFileHash> FilesInPreamble,
717ec727ea7Spatrick     llvm::StringSet<> MissingFiles)
718e5dd7070Spatrick     : Storage(std::move(Storage)), FilesInPreamble(std::move(FilesInPreamble)),
719ec727ea7Spatrick       MissingFiles(std::move(MissingFiles)),
720e5dd7070Spatrick       PreambleBytes(std::move(PreambleBytes)),
721e5dd7070Spatrick       PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {
722*12c85518Srobert   assert(this->Storage != nullptr);
723e5dd7070Spatrick }
724e5dd7070Spatrick 
725e5dd7070Spatrick PrecompiledPreamble::PreambleFileHash
createForFile(off_t Size,time_t ModTime)726e5dd7070Spatrick PrecompiledPreamble::PreambleFileHash::createForFile(off_t Size,
727e5dd7070Spatrick                                                      time_t ModTime) {
728e5dd7070Spatrick   PreambleFileHash Result;
729e5dd7070Spatrick   Result.Size = Size;
730e5dd7070Spatrick   Result.ModTime = ModTime;
731e5dd7070Spatrick   Result.MD5 = {};
732e5dd7070Spatrick   return Result;
733e5dd7070Spatrick }
734e5dd7070Spatrick 
735e5dd7070Spatrick PrecompiledPreamble::PreambleFileHash
createForMemoryBuffer(const llvm::MemoryBufferRef & Buffer)736e5dd7070Spatrick PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(
737a9ac8606Spatrick     const llvm::MemoryBufferRef &Buffer) {
738e5dd7070Spatrick   PreambleFileHash Result;
739a9ac8606Spatrick   Result.Size = Buffer.getBufferSize();
740e5dd7070Spatrick   Result.ModTime = 0;
741e5dd7070Spatrick 
742e5dd7070Spatrick   llvm::MD5 MD5Ctx;
743a9ac8606Spatrick   MD5Ctx.update(Buffer.getBuffer().data());
744e5dd7070Spatrick   MD5Ctx.final(Result.MD5);
745e5dd7070Spatrick 
746e5dd7070Spatrick   return Result;
747e5dd7070Spatrick }
748e5dd7070Spatrick 
configurePreamble(PreambleBounds Bounds,CompilerInvocation & CI,IntrusiveRefCntPtr<llvm::vfs::FileSystem> & VFS,llvm::MemoryBuffer * MainFileBuffer) const749e5dd7070Spatrick void PrecompiledPreamble::configurePreamble(
750e5dd7070Spatrick     PreambleBounds Bounds, CompilerInvocation &CI,
751e5dd7070Spatrick     IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
752e5dd7070Spatrick     llvm::MemoryBuffer *MainFileBuffer) const {
753e5dd7070Spatrick   assert(VFS);
754e5dd7070Spatrick 
755e5dd7070Spatrick   auto &PreprocessorOpts = CI.getPreprocessorOpts();
756e5dd7070Spatrick 
757e5dd7070Spatrick   // Remap main file to point to MainFileBuffer.
758e5dd7070Spatrick   auto MainFilePath = CI.getFrontendOpts().Inputs[0].getFile();
759e5dd7070Spatrick   PreprocessorOpts.addRemappedFile(MainFilePath, MainFileBuffer);
760e5dd7070Spatrick 
761e5dd7070Spatrick   // Configure ImpicitPCHInclude.
762e5dd7070Spatrick   PreprocessorOpts.PrecompiledPreambleBytes.first = Bounds.Size;
763e5dd7070Spatrick   PreprocessorOpts.PrecompiledPreambleBytes.second =
764e5dd7070Spatrick       Bounds.PreambleEndsAtStartOfLine;
765a9ac8606Spatrick   PreprocessorOpts.DisablePCHOrModuleValidation =
766a9ac8606Spatrick       DisableValidationForModuleKind::PCH;
767e5dd7070Spatrick 
768*12c85518Srobert   // Don't bother generating the long version of the predefines buffer.
769*12c85518Srobert   // The preamble is going to overwrite it anyway.
770*12c85518Srobert   PreprocessorOpts.UsePredefines = false;
771*12c85518Srobert 
772*12c85518Srobert   setupPreambleStorage(*Storage, PreprocessorOpts, VFS);
773e5dd7070Spatrick }
774e5dd7070Spatrick 
setupPreambleStorage(const PCHStorage & Storage,PreprocessorOptions & PreprocessorOpts,IntrusiveRefCntPtr<llvm::vfs::FileSystem> & VFS)775e5dd7070Spatrick void PrecompiledPreamble::setupPreambleStorage(
776e5dd7070Spatrick     const PCHStorage &Storage, PreprocessorOptions &PreprocessorOpts,
777e5dd7070Spatrick     IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS) {
778e5dd7070Spatrick   if (Storage.getKind() == PCHStorage::Kind::TempFile) {
779*12c85518Srobert     llvm::StringRef PCHPath = Storage.filePath();
780*12c85518Srobert     PreprocessorOpts.ImplicitPCHInclude = PCHPath.str();
781e5dd7070Spatrick 
782e5dd7070Spatrick     // Make sure we can access the PCH file even if we're using a VFS
783e5dd7070Spatrick     IntrusiveRefCntPtr<llvm::vfs::FileSystem> RealFS =
784e5dd7070Spatrick         llvm::vfs::getRealFileSystem();
785e5dd7070Spatrick     if (VFS == RealFS || VFS->exists(PCHPath))
786e5dd7070Spatrick       return;
787e5dd7070Spatrick     auto Buf = RealFS->getBufferForFile(PCHPath);
788e5dd7070Spatrick     if (!Buf) {
789e5dd7070Spatrick       // We can't read the file even from RealFS, this is clearly an error,
790e5dd7070Spatrick       // but we'll just leave the current VFS as is and let clang's code
791e5dd7070Spatrick       // figure out what to do with missing PCH.
792e5dd7070Spatrick       return;
793e5dd7070Spatrick     }
794e5dd7070Spatrick 
795e5dd7070Spatrick     // We have a slight inconsistency here -- we're using the VFS to
796e5dd7070Spatrick     // read files, but the PCH was generated in the real file system.
797e5dd7070Spatrick     VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(*Buf), VFS);
798e5dd7070Spatrick   } else {
799e5dd7070Spatrick     assert(Storage.getKind() == PCHStorage::Kind::InMemory);
800e5dd7070Spatrick     // For in-memory preamble, we have to provide a VFS overlay that makes it
801e5dd7070Spatrick     // accessible.
802e5dd7070Spatrick     StringRef PCHPath = getInMemoryPreamblePath();
803ec727ea7Spatrick     PreprocessorOpts.ImplicitPCHInclude = std::string(PCHPath);
804e5dd7070Spatrick 
805*12c85518Srobert     auto Buf = llvm::MemoryBuffer::getMemBuffer(
806*12c85518Srobert         Storage.memoryContents(), PCHPath, /*RequiresNullTerminator=*/false);
807e5dd7070Spatrick     VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(Buf), VFS);
808e5dd7070Spatrick   }
809e5dd7070Spatrick }
810e5dd7070Spatrick 
BeforeExecute(CompilerInstance & CI)811e5dd7070Spatrick void PreambleCallbacks::BeforeExecute(CompilerInstance &CI) {}
AfterExecute(CompilerInstance & CI)812e5dd7070Spatrick void PreambleCallbacks::AfterExecute(CompilerInstance &CI) {}
AfterPCHEmitted(ASTWriter & Writer)813e5dd7070Spatrick void PreambleCallbacks::AfterPCHEmitted(ASTWriter &Writer) {}
HandleTopLevelDecl(DeclGroupRef DG)814e5dd7070Spatrick void PreambleCallbacks::HandleTopLevelDecl(DeclGroupRef DG) {}
createPPCallbacks()815e5dd7070Spatrick std::unique_ptr<PPCallbacks> PreambleCallbacks::createPPCallbacks() {
816e5dd7070Spatrick   return nullptr;
817e5dd7070Spatrick }
getCommentHandler()818e5dd7070Spatrick CommentHandler *PreambleCallbacks::getCommentHandler() { return nullptr; }
819e5dd7070Spatrick 
820e5dd7070Spatrick static llvm::ManagedStatic<BuildPreambleErrorCategory> BuildPreambleErrCategory;
821e5dd7070Spatrick 
make_error_code(BuildPreambleError Error)822e5dd7070Spatrick std::error_code clang::make_error_code(BuildPreambleError Error) {
823e5dd7070Spatrick   return std::error_code(static_cast<int>(Error), *BuildPreambleErrCategory);
824e5dd7070Spatrick }
825e5dd7070Spatrick 
name() const826e5dd7070Spatrick const char *BuildPreambleErrorCategory::name() const noexcept {
827e5dd7070Spatrick   return "build-preamble.error";
828e5dd7070Spatrick }
829e5dd7070Spatrick 
message(int condition) const830e5dd7070Spatrick std::string BuildPreambleErrorCategory::message(int condition) const {
831e5dd7070Spatrick   switch (static_cast<BuildPreambleError>(condition)) {
832e5dd7070Spatrick   case BuildPreambleError::CouldntCreateTempFile:
833e5dd7070Spatrick     return "Could not create temporary file for PCH";
834e5dd7070Spatrick   case BuildPreambleError::CouldntCreateTargetInfo:
835e5dd7070Spatrick     return "CreateTargetInfo() return null";
836e5dd7070Spatrick   case BuildPreambleError::BeginSourceFileFailed:
837e5dd7070Spatrick     return "BeginSourceFile() return an error";
838e5dd7070Spatrick   case BuildPreambleError::CouldntEmitPCH:
839e5dd7070Spatrick     return "Could not emit PCH";
840e5dd7070Spatrick   case BuildPreambleError::BadInputs:
841e5dd7070Spatrick     return "Command line arguments must contain exactly one source file";
842e5dd7070Spatrick   }
843e5dd7070Spatrick   llvm_unreachable("unexpected BuildPreambleError");
844e5dd7070Spatrick }
845