106f32e7eSjoerg //===--- PrecompiledPreamble.cpp - Build precompiled preambles --*- C++ -*-===//
206f32e7eSjoerg //
306f32e7eSjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
406f32e7eSjoerg // See https://llvm.org/LICENSE.txt for license information.
506f32e7eSjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
606f32e7eSjoerg //
706f32e7eSjoerg //===----------------------------------------------------------------------===//
806f32e7eSjoerg //
906f32e7eSjoerg // Helper class to build precompiled preamble.
1006f32e7eSjoerg //
1106f32e7eSjoerg //===----------------------------------------------------------------------===//
1206f32e7eSjoerg 
1306f32e7eSjoerg #include "clang/Frontend/PrecompiledPreamble.h"
1406f32e7eSjoerg #include "clang/AST/DeclObjC.h"
15*13fbcb42Sjoerg #include "clang/Basic/FileManager.h"
1606f32e7eSjoerg #include "clang/Basic/LangStandard.h"
1706f32e7eSjoerg #include "clang/Basic/TargetInfo.h"
1806f32e7eSjoerg #include "clang/Frontend/CompilerInstance.h"
1906f32e7eSjoerg #include "clang/Frontend/CompilerInvocation.h"
2006f32e7eSjoerg #include "clang/Frontend/FrontendActions.h"
2106f32e7eSjoerg #include "clang/Frontend/FrontendOptions.h"
22*13fbcb42Sjoerg #include "clang/Lex/HeaderSearch.h"
2306f32e7eSjoerg #include "clang/Lex/Lexer.h"
2406f32e7eSjoerg #include "clang/Lex/Preprocessor.h"
2506f32e7eSjoerg #include "clang/Lex/PreprocessorOptions.h"
2606f32e7eSjoerg #include "clang/Serialization/ASTWriter.h"
27*13fbcb42Sjoerg #include "llvm/ADT/SmallString.h"
2806f32e7eSjoerg #include "llvm/ADT/StringExtras.h"
2906f32e7eSjoerg #include "llvm/ADT/StringSet.h"
30*13fbcb42Sjoerg #include "llvm/ADT/iterator_range.h"
3106f32e7eSjoerg #include "llvm/Config/llvm-config.h"
3206f32e7eSjoerg #include "llvm/Support/CrashRecoveryContext.h"
3306f32e7eSjoerg #include "llvm/Support/FileSystem.h"
34*13fbcb42Sjoerg #include "llvm/Support/Path.h"
3506f32e7eSjoerg #include "llvm/Support/Process.h"
3606f32e7eSjoerg #include "llvm/Support/VirtualFileSystem.h"
3706f32e7eSjoerg #include <limits>
3806f32e7eSjoerg #include <mutex>
3906f32e7eSjoerg #include <utility>
4006f32e7eSjoerg 
4106f32e7eSjoerg using namespace clang;
4206f32e7eSjoerg 
4306f32e7eSjoerg namespace {
4406f32e7eSjoerg 
getInMemoryPreamblePath()4506f32e7eSjoerg StringRef getInMemoryPreamblePath() {
4606f32e7eSjoerg #if defined(LLVM_ON_UNIX)
4706f32e7eSjoerg   return "/__clang_tmp/___clang_inmemory_preamble___";
4806f32e7eSjoerg #elif defined(_WIN32)
4906f32e7eSjoerg   return "C:\\__clang_tmp\\___clang_inmemory_preamble___";
5006f32e7eSjoerg #else
5106f32e7eSjoerg #warning "Unknown platform. Defaulting to UNIX-style paths for in-memory PCHs"
5206f32e7eSjoerg   return "/__clang_tmp/___clang_inmemory_preamble___";
5306f32e7eSjoerg #endif
5406f32e7eSjoerg }
5506f32e7eSjoerg 
5606f32e7eSjoerg IntrusiveRefCntPtr<llvm::vfs::FileSystem>
createVFSOverlayForPreamblePCH(StringRef PCHFilename,std::unique_ptr<llvm::MemoryBuffer> PCHBuffer,IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)5706f32e7eSjoerg createVFSOverlayForPreamblePCH(StringRef PCHFilename,
5806f32e7eSjoerg                                std::unique_ptr<llvm::MemoryBuffer> PCHBuffer,
5906f32e7eSjoerg                                IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
6006f32e7eSjoerg   // We want only the PCH file from the real filesystem to be available,
6106f32e7eSjoerg   // so we create an in-memory VFS with just that and overlay it on top.
6206f32e7eSjoerg   IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> PCHFS(
6306f32e7eSjoerg       new llvm::vfs::InMemoryFileSystem());
6406f32e7eSjoerg   PCHFS->addFile(PCHFilename, 0, std::move(PCHBuffer));
6506f32e7eSjoerg   IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> Overlay(
6606f32e7eSjoerg       new llvm::vfs::OverlayFileSystem(VFS));
6706f32e7eSjoerg   Overlay->pushOverlay(PCHFS);
6806f32e7eSjoerg   return Overlay;
6906f32e7eSjoerg }
7006f32e7eSjoerg 
7106f32e7eSjoerg class PreambleDependencyCollector : public DependencyCollector {
7206f32e7eSjoerg public:
7306f32e7eSjoerg   // We want to collect all dependencies for correctness. Avoiding the real
7406f32e7eSjoerg   // system dependencies (e.g. stl from /usr/lib) would probably be a good idea,
7506f32e7eSjoerg   // but there is no way to distinguish between those and the ones that can be
7606f32e7eSjoerg   // spuriously added by '-isystem' (e.g. to suppress warnings from those
7706f32e7eSjoerg   // headers).
needSystemDependencies()7806f32e7eSjoerg   bool needSystemDependencies() override { return true; }
7906f32e7eSjoerg };
8006f32e7eSjoerg 
81*13fbcb42Sjoerg // Collects files whose existence would invalidate the preamble.
82*13fbcb42Sjoerg // Collecting *all* of these would make validating it too slow though, so we
83*13fbcb42Sjoerg // just find all the candidates for 'file not found' diagnostics.
84*13fbcb42Sjoerg //
85*13fbcb42Sjoerg // A caveat that may be significant for generated files: we'll omit files under
86*13fbcb42Sjoerg // search path entries whose roots don't exist when the preamble is built.
87*13fbcb42Sjoerg // These are pruned by InitHeaderSearch and so we don't see the search path.
88*13fbcb42Sjoerg // It would be nice to include them but we don't want to duplicate all the rest
89*13fbcb42Sjoerg // of the InitHeaderSearch logic to reconstruct them.
90*13fbcb42Sjoerg class MissingFileCollector : public PPCallbacks {
91*13fbcb42Sjoerg   llvm::StringSet<> &Out;
92*13fbcb42Sjoerg   const HeaderSearch &Search;
93*13fbcb42Sjoerg   const SourceManager &SM;
94*13fbcb42Sjoerg 
95*13fbcb42Sjoerg public:
MissingFileCollector(llvm::StringSet<> & Out,const HeaderSearch & Search,const SourceManager & SM)96*13fbcb42Sjoerg   MissingFileCollector(llvm::StringSet<> &Out, const HeaderSearch &Search,
97*13fbcb42Sjoerg                        const SourceManager &SM)
98*13fbcb42Sjoerg       : Out(Out), Search(Search), SM(SM) {}
99*13fbcb42Sjoerg 
InclusionDirective(SourceLocation HashLoc,const Token & IncludeTok,StringRef FileName,bool IsAngled,CharSourceRange FilenameRange,const FileEntry * File,StringRef SearchPath,StringRef RelativePath,const Module * Imported,SrcMgr::CharacteristicKind FileType)100*13fbcb42Sjoerg   void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
101*13fbcb42Sjoerg                           StringRef FileName, bool IsAngled,
102*13fbcb42Sjoerg                           CharSourceRange FilenameRange, const FileEntry *File,
103*13fbcb42Sjoerg                           StringRef SearchPath, StringRef RelativePath,
104*13fbcb42Sjoerg                           const Module *Imported,
105*13fbcb42Sjoerg                           SrcMgr::CharacteristicKind FileType) override {
106*13fbcb42Sjoerg     // File is null if it wasn't found.
107*13fbcb42Sjoerg     // (We have some false negatives if PP recovered e.g. <foo> -> "foo")
108*13fbcb42Sjoerg     if (File != nullptr)
109*13fbcb42Sjoerg       return;
110*13fbcb42Sjoerg 
111*13fbcb42Sjoerg     // If it's a rare absolute include, we know the full path already.
112*13fbcb42Sjoerg     if (llvm::sys::path::is_absolute(FileName)) {
113*13fbcb42Sjoerg       Out.insert(FileName);
114*13fbcb42Sjoerg       return;
115*13fbcb42Sjoerg     }
116*13fbcb42Sjoerg 
117*13fbcb42Sjoerg     // Reconstruct the filenames that would satisfy this directive...
118*13fbcb42Sjoerg     llvm::SmallString<256> Buf;
119*13fbcb42Sjoerg     auto NotFoundRelativeTo = [&](const DirectoryEntry *DE) {
120*13fbcb42Sjoerg       Buf = DE->getName();
121*13fbcb42Sjoerg       llvm::sys::path::append(Buf, FileName);
122*13fbcb42Sjoerg       llvm::sys::path::remove_dots(Buf, /*remove_dot_dot=*/true);
123*13fbcb42Sjoerg       Out.insert(Buf);
124*13fbcb42Sjoerg     };
125*13fbcb42Sjoerg     // ...relative to the including file.
126*13fbcb42Sjoerg     if (!IsAngled) {
127*13fbcb42Sjoerg       if (const FileEntry *IncludingFile =
128*13fbcb42Sjoerg               SM.getFileEntryForID(SM.getFileID(IncludeTok.getLocation())))
129*13fbcb42Sjoerg         if (IncludingFile->getDir())
130*13fbcb42Sjoerg           NotFoundRelativeTo(IncludingFile->getDir());
131*13fbcb42Sjoerg     }
132*13fbcb42Sjoerg     // ...relative to the search paths.
133*13fbcb42Sjoerg     for (const auto &Dir : llvm::make_range(
134*13fbcb42Sjoerg              IsAngled ? Search.angled_dir_begin() : Search.search_dir_begin(),
135*13fbcb42Sjoerg              Search.search_dir_end())) {
136*13fbcb42Sjoerg       // No support for frameworks or header maps yet.
137*13fbcb42Sjoerg       if (Dir.isNormalDir())
138*13fbcb42Sjoerg         NotFoundRelativeTo(Dir.getDir());
139*13fbcb42Sjoerg     }
140*13fbcb42Sjoerg   }
141*13fbcb42Sjoerg };
142*13fbcb42Sjoerg 
14306f32e7eSjoerg /// Keeps a track of files to be deleted in destructor.
14406f32e7eSjoerg class TemporaryFiles {
14506f32e7eSjoerg public:
14606f32e7eSjoerg   // A static instance to be used by all clients.
14706f32e7eSjoerg   static TemporaryFiles &getInstance();
14806f32e7eSjoerg 
14906f32e7eSjoerg private:
15006f32e7eSjoerg   // Disallow constructing the class directly.
15106f32e7eSjoerg   TemporaryFiles() = default;
15206f32e7eSjoerg   // Disallow copy.
15306f32e7eSjoerg   TemporaryFiles(const TemporaryFiles &) = delete;
15406f32e7eSjoerg 
15506f32e7eSjoerg public:
15606f32e7eSjoerg   ~TemporaryFiles();
15706f32e7eSjoerg 
15806f32e7eSjoerg   /// Adds \p File to a set of tracked files.
15906f32e7eSjoerg   void addFile(StringRef File);
16006f32e7eSjoerg 
16106f32e7eSjoerg   /// Remove \p File from disk and from the set of tracked files.
16206f32e7eSjoerg   void removeFile(StringRef File);
16306f32e7eSjoerg 
16406f32e7eSjoerg private:
16506f32e7eSjoerg   std::mutex Mutex;
16606f32e7eSjoerg   llvm::StringSet<> Files;
16706f32e7eSjoerg };
16806f32e7eSjoerg 
getInstance()16906f32e7eSjoerg TemporaryFiles &TemporaryFiles::getInstance() {
17006f32e7eSjoerg   static TemporaryFiles Instance;
17106f32e7eSjoerg   return Instance;
17206f32e7eSjoerg }
17306f32e7eSjoerg 
~TemporaryFiles()17406f32e7eSjoerg TemporaryFiles::~TemporaryFiles() {
17506f32e7eSjoerg   std::lock_guard<std::mutex> Guard(Mutex);
17606f32e7eSjoerg   for (const auto &File : Files)
17706f32e7eSjoerg     llvm::sys::fs::remove(File.getKey());
17806f32e7eSjoerg }
17906f32e7eSjoerg 
addFile(StringRef File)18006f32e7eSjoerg void TemporaryFiles::addFile(StringRef File) {
18106f32e7eSjoerg   std::lock_guard<std::mutex> Guard(Mutex);
18206f32e7eSjoerg   auto IsInserted = Files.insert(File).second;
18306f32e7eSjoerg   (void)IsInserted;
18406f32e7eSjoerg   assert(IsInserted && "File has already been added");
18506f32e7eSjoerg }
18606f32e7eSjoerg 
removeFile(StringRef File)18706f32e7eSjoerg void TemporaryFiles::removeFile(StringRef File) {
18806f32e7eSjoerg   std::lock_guard<std::mutex> Guard(Mutex);
18906f32e7eSjoerg   auto WasPresent = Files.erase(File);
19006f32e7eSjoerg   (void)WasPresent;
19106f32e7eSjoerg   assert(WasPresent && "File was not tracked");
19206f32e7eSjoerg   llvm::sys::fs::remove(File);
19306f32e7eSjoerg }
19406f32e7eSjoerg 
19506f32e7eSjoerg class PrecompilePreambleAction : public ASTFrontendAction {
19606f32e7eSjoerg public:
PrecompilePreambleAction(std::string * InMemStorage,PreambleCallbacks & Callbacks)19706f32e7eSjoerg   PrecompilePreambleAction(std::string *InMemStorage,
19806f32e7eSjoerg                            PreambleCallbacks &Callbacks)
19906f32e7eSjoerg       : InMemStorage(InMemStorage), Callbacks(Callbacks) {}
20006f32e7eSjoerg 
20106f32e7eSjoerg   std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
20206f32e7eSjoerg                                                  StringRef InFile) override;
20306f32e7eSjoerg 
hasEmittedPreamblePCH() const20406f32e7eSjoerg   bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
20506f32e7eSjoerg 
setEmittedPreamblePCH(ASTWriter & Writer)20606f32e7eSjoerg   void setEmittedPreamblePCH(ASTWriter &Writer) {
20706f32e7eSjoerg     this->HasEmittedPreamblePCH = true;
20806f32e7eSjoerg     Callbacks.AfterPCHEmitted(Writer);
20906f32e7eSjoerg   }
21006f32e7eSjoerg 
BeginSourceFileAction(CompilerInstance & CI)211*13fbcb42Sjoerg   bool BeginSourceFileAction(CompilerInstance &CI) override {
212*13fbcb42Sjoerg     assert(CI.getLangOpts().CompilingPCH);
213*13fbcb42Sjoerg     return ASTFrontendAction::BeginSourceFileAction(CI);
214*13fbcb42Sjoerg   }
215*13fbcb42Sjoerg 
shouldEraseOutputFiles()21606f32e7eSjoerg   bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
hasCodeCompletionSupport() const21706f32e7eSjoerg   bool hasCodeCompletionSupport() const override { return false; }
hasASTFileSupport() const21806f32e7eSjoerg   bool hasASTFileSupport() const override { return false; }
getTranslationUnitKind()21906f32e7eSjoerg   TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
22006f32e7eSjoerg 
22106f32e7eSjoerg private:
22206f32e7eSjoerg   friend class PrecompilePreambleConsumer;
22306f32e7eSjoerg 
22406f32e7eSjoerg   bool HasEmittedPreamblePCH = false;
22506f32e7eSjoerg   std::string *InMemStorage;
22606f32e7eSjoerg   PreambleCallbacks &Callbacks;
22706f32e7eSjoerg };
22806f32e7eSjoerg 
22906f32e7eSjoerg class PrecompilePreambleConsumer : public PCHGenerator {
23006f32e7eSjoerg public:
PrecompilePreambleConsumer(PrecompilePreambleAction & Action,const Preprocessor & PP,InMemoryModuleCache & ModuleCache,StringRef isysroot,std::unique_ptr<raw_ostream> Out)23106f32e7eSjoerg   PrecompilePreambleConsumer(PrecompilePreambleAction &Action,
23206f32e7eSjoerg                              const Preprocessor &PP,
23306f32e7eSjoerg                              InMemoryModuleCache &ModuleCache,
23406f32e7eSjoerg                              StringRef isysroot,
23506f32e7eSjoerg                              std::unique_ptr<raw_ostream> Out)
23606f32e7eSjoerg       : PCHGenerator(PP, ModuleCache, "", isysroot,
23706f32e7eSjoerg                      std::make_shared<PCHBuffer>(),
23806f32e7eSjoerg                      ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
23906f32e7eSjoerg                      /*AllowASTWithErrors=*/true),
24006f32e7eSjoerg         Action(Action), Out(std::move(Out)) {}
24106f32e7eSjoerg 
HandleTopLevelDecl(DeclGroupRef DG)24206f32e7eSjoerg   bool HandleTopLevelDecl(DeclGroupRef DG) override {
24306f32e7eSjoerg     Action.Callbacks.HandleTopLevelDecl(DG);
24406f32e7eSjoerg     return true;
24506f32e7eSjoerg   }
24606f32e7eSjoerg 
HandleTranslationUnit(ASTContext & Ctx)24706f32e7eSjoerg   void HandleTranslationUnit(ASTContext &Ctx) override {
24806f32e7eSjoerg     PCHGenerator::HandleTranslationUnit(Ctx);
24906f32e7eSjoerg     if (!hasEmittedPCH())
25006f32e7eSjoerg       return;
25106f32e7eSjoerg 
25206f32e7eSjoerg     // Write the generated bitstream to "Out".
25306f32e7eSjoerg     *Out << getPCH();
25406f32e7eSjoerg     // Make sure it hits disk now.
25506f32e7eSjoerg     Out->flush();
25606f32e7eSjoerg     // Free the buffer.
25706f32e7eSjoerg     llvm::SmallVector<char, 0> Empty;
25806f32e7eSjoerg     getPCH() = std::move(Empty);
25906f32e7eSjoerg 
26006f32e7eSjoerg     Action.setEmittedPreamblePCH(getWriter());
26106f32e7eSjoerg   }
26206f32e7eSjoerg 
shouldSkipFunctionBody(Decl * D)263*13fbcb42Sjoerg   bool shouldSkipFunctionBody(Decl *D) override {
264*13fbcb42Sjoerg     return Action.Callbacks.shouldSkipFunctionBody(D);
265*13fbcb42Sjoerg   }
266*13fbcb42Sjoerg 
26706f32e7eSjoerg private:
26806f32e7eSjoerg   PrecompilePreambleAction &Action;
26906f32e7eSjoerg   std::unique_ptr<raw_ostream> Out;
27006f32e7eSjoerg };
27106f32e7eSjoerg 
27206f32e7eSjoerg std::unique_ptr<ASTConsumer>
CreateASTConsumer(CompilerInstance & CI,StringRef InFile)27306f32e7eSjoerg PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
27406f32e7eSjoerg                                             StringRef InFile) {
27506f32e7eSjoerg   std::string Sysroot;
27606f32e7eSjoerg   if (!GeneratePCHAction::ComputeASTConsumerArguments(CI, Sysroot))
27706f32e7eSjoerg     return nullptr;
27806f32e7eSjoerg 
27906f32e7eSjoerg   std::unique_ptr<llvm::raw_ostream> OS;
28006f32e7eSjoerg   if (InMemStorage) {
28106f32e7eSjoerg     OS = std::make_unique<llvm::raw_string_ostream>(*InMemStorage);
28206f32e7eSjoerg   } else {
28306f32e7eSjoerg     std::string OutputFile;
28406f32e7eSjoerg     OS = GeneratePCHAction::CreateOutputFile(CI, InFile, OutputFile);
28506f32e7eSjoerg   }
28606f32e7eSjoerg   if (!OS)
28706f32e7eSjoerg     return nullptr;
28806f32e7eSjoerg 
28906f32e7eSjoerg   if (!CI.getFrontendOpts().RelocatablePCH)
29006f32e7eSjoerg     Sysroot.clear();
29106f32e7eSjoerg 
29206f32e7eSjoerg   return std::make_unique<PrecompilePreambleConsumer>(
29306f32e7eSjoerg       *this, CI.getPreprocessor(), CI.getModuleCache(), Sysroot, std::move(OS));
29406f32e7eSjoerg }
29506f32e7eSjoerg 
moveOnNoError(llvm::ErrorOr<T> Val,T & Output)29606f32e7eSjoerg template <class T> bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
29706f32e7eSjoerg   if (!Val)
29806f32e7eSjoerg     return false;
29906f32e7eSjoerg   Output = std::move(*Val);
30006f32e7eSjoerg   return true;
30106f32e7eSjoerg }
30206f32e7eSjoerg 
30306f32e7eSjoerg } // namespace
30406f32e7eSjoerg 
ComputePreambleBounds(const LangOptions & LangOpts,const llvm::MemoryBufferRef & Buffer,unsigned MaxLines)30506f32e7eSjoerg PreambleBounds clang::ComputePreambleBounds(const LangOptions &LangOpts,
306*13fbcb42Sjoerg                                             const llvm::MemoryBufferRef &Buffer,
30706f32e7eSjoerg                                             unsigned MaxLines) {
308*13fbcb42Sjoerg   return Lexer::ComputePreamble(Buffer.getBuffer(), LangOpts, MaxLines);
30906f32e7eSjoerg }
31006f32e7eSjoerg 
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)31106f32e7eSjoerg llvm::ErrorOr<PrecompiledPreamble> PrecompiledPreamble::Build(
31206f32e7eSjoerg     const CompilerInvocation &Invocation,
31306f32e7eSjoerg     const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds,
31406f32e7eSjoerg     DiagnosticsEngine &Diagnostics,
31506f32e7eSjoerg     IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
31606f32e7eSjoerg     std::shared_ptr<PCHContainerOperations> PCHContainerOps, bool StoreInMemory,
31706f32e7eSjoerg     PreambleCallbacks &Callbacks) {
31806f32e7eSjoerg   assert(VFS && "VFS is null");
31906f32e7eSjoerg 
32006f32e7eSjoerg   auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
32106f32e7eSjoerg   FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
32206f32e7eSjoerg   PreprocessorOptions &PreprocessorOpts =
32306f32e7eSjoerg       PreambleInvocation->getPreprocessorOpts();
32406f32e7eSjoerg 
32506f32e7eSjoerg   llvm::Optional<TempPCHFile> TempFile;
32606f32e7eSjoerg   if (!StoreInMemory) {
32706f32e7eSjoerg     // Create a temporary file for the precompiled preamble. In rare
32806f32e7eSjoerg     // circumstances, this can fail.
32906f32e7eSjoerg     llvm::ErrorOr<PrecompiledPreamble::TempPCHFile> PreamblePCHFile =
33006f32e7eSjoerg         PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile();
33106f32e7eSjoerg     if (!PreamblePCHFile)
33206f32e7eSjoerg       return BuildPreambleError::CouldntCreateTempFile;
33306f32e7eSjoerg     TempFile = std::move(*PreamblePCHFile);
33406f32e7eSjoerg   }
33506f32e7eSjoerg 
33606f32e7eSjoerg   PCHStorage Storage = StoreInMemory ? PCHStorage(InMemoryPreamble())
33706f32e7eSjoerg                                      : PCHStorage(std::move(*TempFile));
33806f32e7eSjoerg 
33906f32e7eSjoerg   // Save the preamble text for later; we'll need to compare against it for
34006f32e7eSjoerg   // subsequent reparses.
34106f32e7eSjoerg   std::vector<char> PreambleBytes(MainFileBuffer->getBufferStart(),
34206f32e7eSjoerg                                   MainFileBuffer->getBufferStart() +
34306f32e7eSjoerg                                       Bounds.Size);
34406f32e7eSjoerg   bool PreambleEndsAtStartOfLine = Bounds.PreambleEndsAtStartOfLine;
34506f32e7eSjoerg 
34606f32e7eSjoerg   // Tell the compiler invocation to generate a temporary precompiled header.
34706f32e7eSjoerg   FrontendOpts.ProgramAction = frontend::GeneratePCH;
348*13fbcb42Sjoerg   FrontendOpts.OutputFile =
349*13fbcb42Sjoerg       std::string(StoreInMemory ? getInMemoryPreamblePath()
350*13fbcb42Sjoerg                                 : Storage.asFile().getFilePath());
35106f32e7eSjoerg   PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
35206f32e7eSjoerg   PreprocessorOpts.PrecompiledPreambleBytes.second = false;
35306f32e7eSjoerg   // Inform preprocessor to record conditional stack when building the preamble.
35406f32e7eSjoerg   PreprocessorOpts.GeneratePreamble = true;
35506f32e7eSjoerg 
35606f32e7eSjoerg   // Create the compiler instance to use for building the precompiled preamble.
35706f32e7eSjoerg   std::unique_ptr<CompilerInstance> Clang(
35806f32e7eSjoerg       new CompilerInstance(std::move(PCHContainerOps)));
35906f32e7eSjoerg 
36006f32e7eSjoerg   // Recover resources if we crash before exiting this method.
36106f32e7eSjoerg   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
36206f32e7eSjoerg       Clang.get());
36306f32e7eSjoerg 
36406f32e7eSjoerg   Clang->setInvocation(std::move(PreambleInvocation));
36506f32e7eSjoerg   Clang->setDiagnostics(&Diagnostics);
36606f32e7eSjoerg 
36706f32e7eSjoerg   // Create the target instance.
368*13fbcb42Sjoerg   if (!Clang->createTarget())
36906f32e7eSjoerg     return BuildPreambleError::CouldntCreateTargetInfo;
37006f32e7eSjoerg 
37106f32e7eSjoerg   if (Clang->getFrontendOpts().Inputs.size() != 1 ||
37206f32e7eSjoerg       Clang->getFrontendOpts().Inputs[0].getKind().getFormat() !=
37306f32e7eSjoerg           InputKind::Source ||
37406f32e7eSjoerg       Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() ==
37506f32e7eSjoerg           Language::LLVM_IR) {
37606f32e7eSjoerg     return BuildPreambleError::BadInputs;
37706f32e7eSjoerg   }
37806f32e7eSjoerg 
37906f32e7eSjoerg   // Clear out old caches and data.
38006f32e7eSjoerg   Diagnostics.Reset();
38106f32e7eSjoerg   ProcessWarningOptions(Diagnostics, Clang->getDiagnosticOpts());
38206f32e7eSjoerg 
38306f32e7eSjoerg   VFS =
38406f32e7eSjoerg       createVFSFromCompilerInvocation(Clang->getInvocation(), Diagnostics, VFS);
38506f32e7eSjoerg 
38606f32e7eSjoerg   // Create a file manager object to provide access to and cache the filesystem.
38706f32e7eSjoerg   Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
38806f32e7eSjoerg 
38906f32e7eSjoerg   // Create the source manager.
39006f32e7eSjoerg   Clang->setSourceManager(
39106f32e7eSjoerg       new SourceManager(Diagnostics, Clang->getFileManager()));
39206f32e7eSjoerg 
39306f32e7eSjoerg   auto PreambleDepCollector = std::make_shared<PreambleDependencyCollector>();
39406f32e7eSjoerg   Clang->addDependencyCollector(PreambleDepCollector);
39506f32e7eSjoerg 
396*13fbcb42Sjoerg   Clang->getLangOpts().CompilingPCH = true;
397*13fbcb42Sjoerg 
39806f32e7eSjoerg   // Remap the main source file to the preamble buffer.
39906f32e7eSjoerg   StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
40006f32e7eSjoerg   auto PreambleInputBuffer = llvm::MemoryBuffer::getMemBufferCopy(
40106f32e7eSjoerg       MainFileBuffer->getBuffer().slice(0, Bounds.Size), MainFilePath);
40206f32e7eSjoerg   if (PreprocessorOpts.RetainRemappedFileBuffers) {
40306f32e7eSjoerg     // MainFileBuffer will be deleted by unique_ptr after leaving the method.
40406f32e7eSjoerg     PreprocessorOpts.addRemappedFile(MainFilePath, PreambleInputBuffer.get());
40506f32e7eSjoerg   } else {
40606f32e7eSjoerg     // In that case, remapped buffer will be deleted by CompilerInstance on
40706f32e7eSjoerg     // BeginSourceFile, so we call release() to avoid double deletion.
40806f32e7eSjoerg     PreprocessorOpts.addRemappedFile(MainFilePath,
40906f32e7eSjoerg                                      PreambleInputBuffer.release());
41006f32e7eSjoerg   }
41106f32e7eSjoerg 
41206f32e7eSjoerg   std::unique_ptr<PrecompilePreambleAction> Act;
41306f32e7eSjoerg   Act.reset(new PrecompilePreambleAction(
41406f32e7eSjoerg       StoreInMemory ? &Storage.asMemory().Data : nullptr, Callbacks));
41506f32e7eSjoerg   Callbacks.BeforeExecute(*Clang);
41606f32e7eSjoerg   if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
41706f32e7eSjoerg     return BuildPreambleError::BeginSourceFileFailed;
41806f32e7eSjoerg 
41906f32e7eSjoerg   std::unique_ptr<PPCallbacks> DelegatedPPCallbacks =
42006f32e7eSjoerg       Callbacks.createPPCallbacks();
42106f32e7eSjoerg   if (DelegatedPPCallbacks)
42206f32e7eSjoerg     Clang->getPreprocessor().addPPCallbacks(std::move(DelegatedPPCallbacks));
42306f32e7eSjoerg   if (auto CommentHandler = Callbacks.getCommentHandler())
42406f32e7eSjoerg     Clang->getPreprocessor().addCommentHandler(CommentHandler);
425*13fbcb42Sjoerg   llvm::StringSet<> MissingFiles;
426*13fbcb42Sjoerg   Clang->getPreprocessor().addPPCallbacks(
427*13fbcb42Sjoerg       std::make_unique<MissingFileCollector>(
428*13fbcb42Sjoerg           MissingFiles, Clang->getPreprocessor().getHeaderSearchInfo(),
429*13fbcb42Sjoerg           Clang->getSourceManager()));
43006f32e7eSjoerg 
43106f32e7eSjoerg   if (llvm::Error Err = Act->Execute())
43206f32e7eSjoerg     return errorToErrorCode(std::move(Err));
43306f32e7eSjoerg 
43406f32e7eSjoerg   // Run the callbacks.
43506f32e7eSjoerg   Callbacks.AfterExecute(*Clang);
43606f32e7eSjoerg 
43706f32e7eSjoerg   Act->EndSourceFile();
43806f32e7eSjoerg 
43906f32e7eSjoerg   if (!Act->hasEmittedPreamblePCH())
44006f32e7eSjoerg     return BuildPreambleError::CouldntEmitPCH;
44106f32e7eSjoerg 
44206f32e7eSjoerg   // Keep track of all of the files that the source manager knows about,
44306f32e7eSjoerg   // so we can verify whether they have changed or not.
44406f32e7eSjoerg   llvm::StringMap<PrecompiledPreamble::PreambleFileHash> FilesInPreamble;
44506f32e7eSjoerg 
44606f32e7eSjoerg   SourceManager &SourceMgr = Clang->getSourceManager();
44706f32e7eSjoerg   for (auto &Filename : PreambleDepCollector->getDependencies()) {
44806f32e7eSjoerg     auto FileOrErr = Clang->getFileManager().getFile(Filename);
44906f32e7eSjoerg     if (!FileOrErr ||
45006f32e7eSjoerg         *FileOrErr == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
45106f32e7eSjoerg       continue;
45206f32e7eSjoerg     auto File = *FileOrErr;
45306f32e7eSjoerg     if (time_t ModTime = File->getModificationTime()) {
45406f32e7eSjoerg       FilesInPreamble[File->getName()] =
45506f32e7eSjoerg           PrecompiledPreamble::PreambleFileHash::createForFile(File->getSize(),
45606f32e7eSjoerg                                                                ModTime);
45706f32e7eSjoerg     } else {
458*13fbcb42Sjoerg       llvm::MemoryBufferRef Buffer =
459*13fbcb42Sjoerg           SourceMgr.getMemoryBufferForFileOrFake(File);
46006f32e7eSjoerg       FilesInPreamble[File->getName()] =
46106f32e7eSjoerg           PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(Buffer);
46206f32e7eSjoerg     }
46306f32e7eSjoerg   }
46406f32e7eSjoerg 
465*13fbcb42Sjoerg   return PrecompiledPreamble(
466*13fbcb42Sjoerg       std::move(Storage), std::move(PreambleBytes), PreambleEndsAtStartOfLine,
467*13fbcb42Sjoerg       std::move(FilesInPreamble), std::move(MissingFiles));
46806f32e7eSjoerg }
46906f32e7eSjoerg 
getBounds() const47006f32e7eSjoerg PreambleBounds PrecompiledPreamble::getBounds() const {
47106f32e7eSjoerg   return PreambleBounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
47206f32e7eSjoerg }
47306f32e7eSjoerg 
getSize() const47406f32e7eSjoerg std::size_t PrecompiledPreamble::getSize() const {
47506f32e7eSjoerg   switch (Storage.getKind()) {
47606f32e7eSjoerg   case PCHStorage::Kind::Empty:
47706f32e7eSjoerg     assert(false && "Calling getSize() on invalid PrecompiledPreamble. "
47806f32e7eSjoerg                     "Was it std::moved?");
47906f32e7eSjoerg     return 0;
48006f32e7eSjoerg   case PCHStorage::Kind::InMemory:
48106f32e7eSjoerg     return Storage.asMemory().Data.size();
48206f32e7eSjoerg   case PCHStorage::Kind::TempFile: {
48306f32e7eSjoerg     uint64_t Result;
48406f32e7eSjoerg     if (llvm::sys::fs::file_size(Storage.asFile().getFilePath(), Result))
48506f32e7eSjoerg       return 0;
48606f32e7eSjoerg 
48706f32e7eSjoerg     assert(Result <= std::numeric_limits<std::size_t>::max() &&
48806f32e7eSjoerg            "file size did not fit into size_t");
48906f32e7eSjoerg     return Result;
49006f32e7eSjoerg   }
49106f32e7eSjoerg   }
49206f32e7eSjoerg   llvm_unreachable("Unhandled storage kind");
49306f32e7eSjoerg }
49406f32e7eSjoerg 
CanReuse(const CompilerInvocation & Invocation,const llvm::MemoryBufferRef & MainFileBuffer,PreambleBounds Bounds,llvm::vfs::FileSystem & VFS) const49506f32e7eSjoerg bool PrecompiledPreamble::CanReuse(const CompilerInvocation &Invocation,
496*13fbcb42Sjoerg                                    const llvm::MemoryBufferRef &MainFileBuffer,
49706f32e7eSjoerg                                    PreambleBounds Bounds,
498*13fbcb42Sjoerg                                    llvm::vfs::FileSystem &VFS) const {
49906f32e7eSjoerg 
50006f32e7eSjoerg   assert(
501*13fbcb42Sjoerg       Bounds.Size <= MainFileBuffer.getBufferSize() &&
50206f32e7eSjoerg       "Buffer is too large. Bounds were calculated from a different buffer?");
50306f32e7eSjoerg 
50406f32e7eSjoerg   auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
50506f32e7eSjoerg   PreprocessorOptions &PreprocessorOpts =
50606f32e7eSjoerg       PreambleInvocation->getPreprocessorOpts();
50706f32e7eSjoerg 
50806f32e7eSjoerg   // We've previously computed a preamble. Check whether we have the same
50906f32e7eSjoerg   // preamble now that we did before, and that there's enough space in
51006f32e7eSjoerg   // the main-file buffer within the precompiled preamble to fit the
51106f32e7eSjoerg   // new main file.
51206f32e7eSjoerg   if (PreambleBytes.size() != Bounds.Size ||
51306f32e7eSjoerg       PreambleEndsAtStartOfLine != Bounds.PreambleEndsAtStartOfLine ||
51406f32e7eSjoerg       !std::equal(PreambleBytes.begin(), PreambleBytes.end(),
515*13fbcb42Sjoerg                   MainFileBuffer.getBuffer().begin()))
51606f32e7eSjoerg     return false;
51706f32e7eSjoerg   // The preamble has not changed. We may be able to re-use the precompiled
51806f32e7eSjoerg   // preamble.
51906f32e7eSjoerg 
52006f32e7eSjoerg   // Check that none of the files used by the preamble have changed.
52106f32e7eSjoerg   // First, make a record of those files that have been overridden via
52206f32e7eSjoerg   // remapping or unsaved_files.
52306f32e7eSjoerg   std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
524*13fbcb42Sjoerg   llvm::StringSet<> OverriddenAbsPaths; // Either by buffers or files.
52506f32e7eSjoerg   for (const auto &R : PreprocessorOpts.RemappedFiles) {
52606f32e7eSjoerg     llvm::vfs::Status Status;
527*13fbcb42Sjoerg     if (!moveOnNoError(VFS.status(R.second), Status)) {
52806f32e7eSjoerg       // If we can't stat the file we're remapping to, assume that something
52906f32e7eSjoerg       // horrible happened.
53006f32e7eSjoerg       return false;
53106f32e7eSjoerg     }
532*13fbcb42Sjoerg     // If a mapped file was previously missing, then it has changed.
533*13fbcb42Sjoerg     llvm::SmallString<128> MappedPath(R.first);
534*13fbcb42Sjoerg     if (!VFS.makeAbsolute(MappedPath))
535*13fbcb42Sjoerg       OverriddenAbsPaths.insert(MappedPath);
53606f32e7eSjoerg 
53706f32e7eSjoerg     OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
53806f32e7eSjoerg         Status.getSize(), llvm::sys::toTimeT(Status.getLastModificationTime()));
53906f32e7eSjoerg   }
54006f32e7eSjoerg 
54106f32e7eSjoerg   // OverridenFileBuffers tracks only the files not found in VFS.
54206f32e7eSjoerg   llvm::StringMap<PreambleFileHash> OverridenFileBuffers;
54306f32e7eSjoerg   for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
54406f32e7eSjoerg     const PrecompiledPreamble::PreambleFileHash PreambleHash =
545*13fbcb42Sjoerg         PreambleFileHash::createForMemoryBuffer(RB.second->getMemBufferRef());
54606f32e7eSjoerg     llvm::vfs::Status Status;
547*13fbcb42Sjoerg     if (moveOnNoError(VFS.status(RB.first), Status))
54806f32e7eSjoerg       OverriddenFiles[Status.getUniqueID()] = PreambleHash;
54906f32e7eSjoerg     else
55006f32e7eSjoerg       OverridenFileBuffers[RB.first] = PreambleHash;
551*13fbcb42Sjoerg 
552*13fbcb42Sjoerg     llvm::SmallString<128> MappedPath(RB.first);
553*13fbcb42Sjoerg     if (!VFS.makeAbsolute(MappedPath))
554*13fbcb42Sjoerg       OverriddenAbsPaths.insert(MappedPath);
55506f32e7eSjoerg   }
55606f32e7eSjoerg 
55706f32e7eSjoerg   // Check whether anything has changed.
55806f32e7eSjoerg   for (const auto &F : FilesInPreamble) {
55906f32e7eSjoerg     auto OverridenFileBuffer = OverridenFileBuffers.find(F.first());
56006f32e7eSjoerg     if (OverridenFileBuffer != OverridenFileBuffers.end()) {
56106f32e7eSjoerg       // The file's buffer was remapped and the file was not found in VFS.
56206f32e7eSjoerg       // Check whether it matches up with the previous mapping.
56306f32e7eSjoerg       if (OverridenFileBuffer->second != F.second)
56406f32e7eSjoerg         return false;
56506f32e7eSjoerg       continue;
56606f32e7eSjoerg     }
56706f32e7eSjoerg 
56806f32e7eSjoerg     llvm::vfs::Status Status;
569*13fbcb42Sjoerg     if (!moveOnNoError(VFS.status(F.first()), Status)) {
57006f32e7eSjoerg       // If the file's buffer is not remapped and we can't stat it,
57106f32e7eSjoerg       // assume that something horrible happened.
57206f32e7eSjoerg       return false;
57306f32e7eSjoerg     }
57406f32e7eSjoerg 
57506f32e7eSjoerg     std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden =
57606f32e7eSjoerg         OverriddenFiles.find(Status.getUniqueID());
57706f32e7eSjoerg     if (Overridden != OverriddenFiles.end()) {
57806f32e7eSjoerg       // This file was remapped; check whether the newly-mapped file
57906f32e7eSjoerg       // matches up with the previous mapping.
58006f32e7eSjoerg       if (Overridden->second != F.second)
58106f32e7eSjoerg         return false;
58206f32e7eSjoerg       continue;
58306f32e7eSjoerg     }
58406f32e7eSjoerg 
58506f32e7eSjoerg     // Neither the file's buffer nor the file itself was remapped;
58606f32e7eSjoerg     // check whether it has changed on disk.
58706f32e7eSjoerg     if (Status.getSize() != uint64_t(F.second.Size) ||
58806f32e7eSjoerg         llvm::sys::toTimeT(Status.getLastModificationTime()) !=
58906f32e7eSjoerg             F.second.ModTime)
59006f32e7eSjoerg       return false;
59106f32e7eSjoerg   }
592*13fbcb42Sjoerg   for (const auto &F : MissingFiles) {
593*13fbcb42Sjoerg     // A missing file may be "provided" by an override buffer or file.
594*13fbcb42Sjoerg     if (OverriddenAbsPaths.count(F.getKey()))
595*13fbcb42Sjoerg       return false;
596*13fbcb42Sjoerg     // If a file previously recorded as missing exists as a regular file, then
597*13fbcb42Sjoerg     // consider the preamble out-of-date.
598*13fbcb42Sjoerg     if (auto Status = VFS.status(F.getKey())) {
599*13fbcb42Sjoerg       if (Status->isRegularFile())
600*13fbcb42Sjoerg         return false;
601*13fbcb42Sjoerg     }
602*13fbcb42Sjoerg   }
60306f32e7eSjoerg   return true;
60406f32e7eSjoerg }
60506f32e7eSjoerg 
AddImplicitPreamble(CompilerInvocation & CI,IntrusiveRefCntPtr<llvm::vfs::FileSystem> & VFS,llvm::MemoryBuffer * MainFileBuffer) const60606f32e7eSjoerg void PrecompiledPreamble::AddImplicitPreamble(
60706f32e7eSjoerg     CompilerInvocation &CI, IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
60806f32e7eSjoerg     llvm::MemoryBuffer *MainFileBuffer) const {
60906f32e7eSjoerg   PreambleBounds Bounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
61006f32e7eSjoerg   configurePreamble(Bounds, CI, VFS, MainFileBuffer);
61106f32e7eSjoerg }
61206f32e7eSjoerg 
OverridePreamble(CompilerInvocation & CI,IntrusiveRefCntPtr<llvm::vfs::FileSystem> & VFS,llvm::MemoryBuffer * MainFileBuffer) const61306f32e7eSjoerg void PrecompiledPreamble::OverridePreamble(
61406f32e7eSjoerg     CompilerInvocation &CI, IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
61506f32e7eSjoerg     llvm::MemoryBuffer *MainFileBuffer) const {
616*13fbcb42Sjoerg   auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), *MainFileBuffer, 0);
61706f32e7eSjoerg   configurePreamble(Bounds, CI, VFS, MainFileBuffer);
61806f32e7eSjoerg }
61906f32e7eSjoerg 
PrecompiledPreamble(PCHStorage Storage,std::vector<char> PreambleBytes,bool PreambleEndsAtStartOfLine,llvm::StringMap<PreambleFileHash> FilesInPreamble,llvm::StringSet<> MissingFiles)62006f32e7eSjoerg PrecompiledPreamble::PrecompiledPreamble(
62106f32e7eSjoerg     PCHStorage Storage, std::vector<char> PreambleBytes,
62206f32e7eSjoerg     bool PreambleEndsAtStartOfLine,
623*13fbcb42Sjoerg     llvm::StringMap<PreambleFileHash> FilesInPreamble,
624*13fbcb42Sjoerg     llvm::StringSet<> MissingFiles)
62506f32e7eSjoerg     : Storage(std::move(Storage)), FilesInPreamble(std::move(FilesInPreamble)),
626*13fbcb42Sjoerg       MissingFiles(std::move(MissingFiles)),
62706f32e7eSjoerg       PreambleBytes(std::move(PreambleBytes)),
62806f32e7eSjoerg       PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {
62906f32e7eSjoerg   assert(this->Storage.getKind() != PCHStorage::Kind::Empty);
63006f32e7eSjoerg }
63106f32e7eSjoerg 
63206f32e7eSjoerg llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
CreateNewPreamblePCHFile()63306f32e7eSjoerg PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile() {
63406f32e7eSjoerg   // FIXME: This is a hack so that we can override the preamble file during
63506f32e7eSjoerg   // crash-recovery testing, which is the only case where the preamble files
63606f32e7eSjoerg   // are not necessarily cleaned up.
637*13fbcb42Sjoerg   if (const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE"))
638*13fbcb42Sjoerg     return TempPCHFile(TmpFile);
63906f32e7eSjoerg 
64006f32e7eSjoerg   llvm::SmallString<64> File;
64106f32e7eSjoerg   // Using a version of createTemporaryFile with a file descriptor guarantees
64206f32e7eSjoerg   // that we would never get a race condition in a multi-threaded setting
64306f32e7eSjoerg   // (i.e., multiple threads getting the same temporary path).
64406f32e7eSjoerg   int FD;
645*13fbcb42Sjoerg   auto EC = llvm::sys::fs::createTemporaryFile("preamble", "pch", FD, File);
64606f32e7eSjoerg   if (EC)
64706f32e7eSjoerg     return EC;
64806f32e7eSjoerg   // We only needed to make sure the file exists, close the file right away.
64906f32e7eSjoerg   llvm::sys::Process::SafelyCloseFileDescriptor(FD);
650*13fbcb42Sjoerg   return TempPCHFile(std::string(std::move(File).str()));
65106f32e7eSjoerg }
65206f32e7eSjoerg 
TempPCHFile(std::string FilePath)65306f32e7eSjoerg PrecompiledPreamble::TempPCHFile::TempPCHFile(std::string FilePath)
65406f32e7eSjoerg     : FilePath(std::move(FilePath)) {
65506f32e7eSjoerg   TemporaryFiles::getInstance().addFile(*this->FilePath);
65606f32e7eSjoerg }
65706f32e7eSjoerg 
TempPCHFile(TempPCHFile && Other)65806f32e7eSjoerg PrecompiledPreamble::TempPCHFile::TempPCHFile(TempPCHFile &&Other) {
65906f32e7eSjoerg   FilePath = std::move(Other.FilePath);
66006f32e7eSjoerg   Other.FilePath = None;
66106f32e7eSjoerg }
66206f32e7eSjoerg 
66306f32e7eSjoerg PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::TempPCHFile::
operator =(TempPCHFile && Other)66406f32e7eSjoerg operator=(TempPCHFile &&Other) {
66506f32e7eSjoerg   RemoveFileIfPresent();
66606f32e7eSjoerg 
66706f32e7eSjoerg   FilePath = std::move(Other.FilePath);
66806f32e7eSjoerg   Other.FilePath = None;
66906f32e7eSjoerg   return *this;
67006f32e7eSjoerg }
67106f32e7eSjoerg 
~TempPCHFile()67206f32e7eSjoerg PrecompiledPreamble::TempPCHFile::~TempPCHFile() { RemoveFileIfPresent(); }
67306f32e7eSjoerg 
RemoveFileIfPresent()67406f32e7eSjoerg void PrecompiledPreamble::TempPCHFile::RemoveFileIfPresent() {
67506f32e7eSjoerg   if (FilePath) {
67606f32e7eSjoerg     TemporaryFiles::getInstance().removeFile(*FilePath);
67706f32e7eSjoerg     FilePath = None;
67806f32e7eSjoerg   }
67906f32e7eSjoerg }
68006f32e7eSjoerg 
getFilePath() const68106f32e7eSjoerg llvm::StringRef PrecompiledPreamble::TempPCHFile::getFilePath() const {
68206f32e7eSjoerg   assert(FilePath && "TempPCHFile doesn't have a FilePath. Had it been moved?");
68306f32e7eSjoerg   return *FilePath;
68406f32e7eSjoerg }
68506f32e7eSjoerg 
PCHStorage(TempPCHFile File)68606f32e7eSjoerg PrecompiledPreamble::PCHStorage::PCHStorage(TempPCHFile File)
68706f32e7eSjoerg     : StorageKind(Kind::TempFile) {
68806f32e7eSjoerg   new (&asFile()) TempPCHFile(std::move(File));
68906f32e7eSjoerg }
69006f32e7eSjoerg 
PCHStorage(InMemoryPreamble Memory)69106f32e7eSjoerg PrecompiledPreamble::PCHStorage::PCHStorage(InMemoryPreamble Memory)
69206f32e7eSjoerg     : StorageKind(Kind::InMemory) {
69306f32e7eSjoerg   new (&asMemory()) InMemoryPreamble(std::move(Memory));
69406f32e7eSjoerg }
69506f32e7eSjoerg 
PCHStorage(PCHStorage && Other)69606f32e7eSjoerg PrecompiledPreamble::PCHStorage::PCHStorage(PCHStorage &&Other) : PCHStorage() {
69706f32e7eSjoerg   *this = std::move(Other);
69806f32e7eSjoerg }
69906f32e7eSjoerg 
70006f32e7eSjoerg PrecompiledPreamble::PCHStorage &PrecompiledPreamble::PCHStorage::
operator =(PCHStorage && Other)70106f32e7eSjoerg operator=(PCHStorage &&Other) {
70206f32e7eSjoerg   destroy();
70306f32e7eSjoerg 
70406f32e7eSjoerg   StorageKind = Other.StorageKind;
70506f32e7eSjoerg   switch (StorageKind) {
70606f32e7eSjoerg   case Kind::Empty:
70706f32e7eSjoerg     // do nothing;
70806f32e7eSjoerg     break;
70906f32e7eSjoerg   case Kind::TempFile:
71006f32e7eSjoerg     new (&asFile()) TempPCHFile(std::move(Other.asFile()));
71106f32e7eSjoerg     break;
71206f32e7eSjoerg   case Kind::InMemory:
71306f32e7eSjoerg     new (&asMemory()) InMemoryPreamble(std::move(Other.asMemory()));
71406f32e7eSjoerg     break;
71506f32e7eSjoerg   }
71606f32e7eSjoerg 
71706f32e7eSjoerg   Other.setEmpty();
71806f32e7eSjoerg   return *this;
71906f32e7eSjoerg }
72006f32e7eSjoerg 
~PCHStorage()72106f32e7eSjoerg PrecompiledPreamble::PCHStorage::~PCHStorage() { destroy(); }
72206f32e7eSjoerg 
72306f32e7eSjoerg PrecompiledPreamble::PCHStorage::Kind
getKind() const72406f32e7eSjoerg PrecompiledPreamble::PCHStorage::getKind() const {
72506f32e7eSjoerg   return StorageKind;
72606f32e7eSjoerg }
72706f32e7eSjoerg 
asFile()72806f32e7eSjoerg PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::PCHStorage::asFile() {
72906f32e7eSjoerg   assert(getKind() == Kind::TempFile);
730*13fbcb42Sjoerg   return *reinterpret_cast<TempPCHFile *>(&Storage);
73106f32e7eSjoerg }
73206f32e7eSjoerg 
73306f32e7eSjoerg const PrecompiledPreamble::TempPCHFile &
asFile() const73406f32e7eSjoerg PrecompiledPreamble::PCHStorage::asFile() const {
73506f32e7eSjoerg   return const_cast<PCHStorage *>(this)->asFile();
73606f32e7eSjoerg }
73706f32e7eSjoerg 
73806f32e7eSjoerg PrecompiledPreamble::InMemoryPreamble &
asMemory()73906f32e7eSjoerg PrecompiledPreamble::PCHStorage::asMemory() {
74006f32e7eSjoerg   assert(getKind() == Kind::InMemory);
741*13fbcb42Sjoerg   return *reinterpret_cast<InMemoryPreamble *>(&Storage);
74206f32e7eSjoerg }
74306f32e7eSjoerg 
74406f32e7eSjoerg const PrecompiledPreamble::InMemoryPreamble &
asMemory() const74506f32e7eSjoerg PrecompiledPreamble::PCHStorage::asMemory() const {
74606f32e7eSjoerg   return const_cast<PCHStorage *>(this)->asMemory();
74706f32e7eSjoerg }
74806f32e7eSjoerg 
destroy()74906f32e7eSjoerg void PrecompiledPreamble::PCHStorage::destroy() {
75006f32e7eSjoerg   switch (StorageKind) {
75106f32e7eSjoerg   case Kind::Empty:
75206f32e7eSjoerg     return;
75306f32e7eSjoerg   case Kind::TempFile:
75406f32e7eSjoerg     asFile().~TempPCHFile();
75506f32e7eSjoerg     return;
75606f32e7eSjoerg   case Kind::InMemory:
75706f32e7eSjoerg     asMemory().~InMemoryPreamble();
75806f32e7eSjoerg     return;
75906f32e7eSjoerg   }
76006f32e7eSjoerg }
76106f32e7eSjoerg 
setEmpty()76206f32e7eSjoerg void PrecompiledPreamble::PCHStorage::setEmpty() {
76306f32e7eSjoerg   destroy();
76406f32e7eSjoerg   StorageKind = Kind::Empty;
76506f32e7eSjoerg }
76606f32e7eSjoerg 
76706f32e7eSjoerg PrecompiledPreamble::PreambleFileHash
createForFile(off_t Size,time_t ModTime)76806f32e7eSjoerg PrecompiledPreamble::PreambleFileHash::createForFile(off_t Size,
76906f32e7eSjoerg                                                      time_t ModTime) {
77006f32e7eSjoerg   PreambleFileHash Result;
77106f32e7eSjoerg   Result.Size = Size;
77206f32e7eSjoerg   Result.ModTime = ModTime;
77306f32e7eSjoerg   Result.MD5 = {};
77406f32e7eSjoerg   return Result;
77506f32e7eSjoerg }
77606f32e7eSjoerg 
77706f32e7eSjoerg PrecompiledPreamble::PreambleFileHash
createForMemoryBuffer(const llvm::MemoryBufferRef & Buffer)77806f32e7eSjoerg PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(
779*13fbcb42Sjoerg     const llvm::MemoryBufferRef &Buffer) {
78006f32e7eSjoerg   PreambleFileHash Result;
781*13fbcb42Sjoerg   Result.Size = Buffer.getBufferSize();
78206f32e7eSjoerg   Result.ModTime = 0;
78306f32e7eSjoerg 
78406f32e7eSjoerg   llvm::MD5 MD5Ctx;
785*13fbcb42Sjoerg   MD5Ctx.update(Buffer.getBuffer().data());
78606f32e7eSjoerg   MD5Ctx.final(Result.MD5);
78706f32e7eSjoerg 
78806f32e7eSjoerg   return Result;
78906f32e7eSjoerg }
79006f32e7eSjoerg 
configurePreamble(PreambleBounds Bounds,CompilerInvocation & CI,IntrusiveRefCntPtr<llvm::vfs::FileSystem> & VFS,llvm::MemoryBuffer * MainFileBuffer) const79106f32e7eSjoerg void PrecompiledPreamble::configurePreamble(
79206f32e7eSjoerg     PreambleBounds Bounds, CompilerInvocation &CI,
79306f32e7eSjoerg     IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
79406f32e7eSjoerg     llvm::MemoryBuffer *MainFileBuffer) const {
79506f32e7eSjoerg   assert(VFS);
79606f32e7eSjoerg 
79706f32e7eSjoerg   auto &PreprocessorOpts = CI.getPreprocessorOpts();
79806f32e7eSjoerg 
79906f32e7eSjoerg   // Remap main file to point to MainFileBuffer.
80006f32e7eSjoerg   auto MainFilePath = CI.getFrontendOpts().Inputs[0].getFile();
80106f32e7eSjoerg   PreprocessorOpts.addRemappedFile(MainFilePath, MainFileBuffer);
80206f32e7eSjoerg 
80306f32e7eSjoerg   // Configure ImpicitPCHInclude.
80406f32e7eSjoerg   PreprocessorOpts.PrecompiledPreambleBytes.first = Bounds.Size;
80506f32e7eSjoerg   PreprocessorOpts.PrecompiledPreambleBytes.second =
80606f32e7eSjoerg       Bounds.PreambleEndsAtStartOfLine;
807*13fbcb42Sjoerg   PreprocessorOpts.DisablePCHOrModuleValidation =
808*13fbcb42Sjoerg       DisableValidationForModuleKind::PCH;
80906f32e7eSjoerg 
81006f32e7eSjoerg   setupPreambleStorage(Storage, PreprocessorOpts, VFS);
81106f32e7eSjoerg }
81206f32e7eSjoerg 
setupPreambleStorage(const PCHStorage & Storage,PreprocessorOptions & PreprocessorOpts,IntrusiveRefCntPtr<llvm::vfs::FileSystem> & VFS)81306f32e7eSjoerg void PrecompiledPreamble::setupPreambleStorage(
81406f32e7eSjoerg     const PCHStorage &Storage, PreprocessorOptions &PreprocessorOpts,
81506f32e7eSjoerg     IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS) {
81606f32e7eSjoerg   if (Storage.getKind() == PCHStorage::Kind::TempFile) {
81706f32e7eSjoerg     const TempPCHFile &PCHFile = Storage.asFile();
818*13fbcb42Sjoerg     PreprocessorOpts.ImplicitPCHInclude = std::string(PCHFile.getFilePath());
81906f32e7eSjoerg 
82006f32e7eSjoerg     // Make sure we can access the PCH file even if we're using a VFS
82106f32e7eSjoerg     IntrusiveRefCntPtr<llvm::vfs::FileSystem> RealFS =
82206f32e7eSjoerg         llvm::vfs::getRealFileSystem();
82306f32e7eSjoerg     auto PCHPath = PCHFile.getFilePath();
82406f32e7eSjoerg     if (VFS == RealFS || VFS->exists(PCHPath))
82506f32e7eSjoerg       return;
82606f32e7eSjoerg     auto Buf = RealFS->getBufferForFile(PCHPath);
82706f32e7eSjoerg     if (!Buf) {
82806f32e7eSjoerg       // We can't read the file even from RealFS, this is clearly an error,
82906f32e7eSjoerg       // but we'll just leave the current VFS as is and let clang's code
83006f32e7eSjoerg       // figure out what to do with missing PCH.
83106f32e7eSjoerg       return;
83206f32e7eSjoerg     }
83306f32e7eSjoerg 
83406f32e7eSjoerg     // We have a slight inconsistency here -- we're using the VFS to
83506f32e7eSjoerg     // read files, but the PCH was generated in the real file system.
83606f32e7eSjoerg     VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(*Buf), VFS);
83706f32e7eSjoerg   } else {
83806f32e7eSjoerg     assert(Storage.getKind() == PCHStorage::Kind::InMemory);
83906f32e7eSjoerg     // For in-memory preamble, we have to provide a VFS overlay that makes it
84006f32e7eSjoerg     // accessible.
84106f32e7eSjoerg     StringRef PCHPath = getInMemoryPreamblePath();
842*13fbcb42Sjoerg     PreprocessorOpts.ImplicitPCHInclude = std::string(PCHPath);
84306f32e7eSjoerg 
84406f32e7eSjoerg     auto Buf = llvm::MemoryBuffer::getMemBuffer(Storage.asMemory().Data);
84506f32e7eSjoerg     VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(Buf), VFS);
84606f32e7eSjoerg   }
84706f32e7eSjoerg }
84806f32e7eSjoerg 
BeforeExecute(CompilerInstance & CI)84906f32e7eSjoerg void PreambleCallbacks::BeforeExecute(CompilerInstance &CI) {}
AfterExecute(CompilerInstance & CI)85006f32e7eSjoerg void PreambleCallbacks::AfterExecute(CompilerInstance &CI) {}
AfterPCHEmitted(ASTWriter & Writer)85106f32e7eSjoerg void PreambleCallbacks::AfterPCHEmitted(ASTWriter &Writer) {}
HandleTopLevelDecl(DeclGroupRef DG)85206f32e7eSjoerg void PreambleCallbacks::HandleTopLevelDecl(DeclGroupRef DG) {}
createPPCallbacks()85306f32e7eSjoerg std::unique_ptr<PPCallbacks> PreambleCallbacks::createPPCallbacks() {
85406f32e7eSjoerg   return nullptr;
85506f32e7eSjoerg }
getCommentHandler()85606f32e7eSjoerg CommentHandler *PreambleCallbacks::getCommentHandler() { return nullptr; }
85706f32e7eSjoerg 
85806f32e7eSjoerg static llvm::ManagedStatic<BuildPreambleErrorCategory> BuildPreambleErrCategory;
85906f32e7eSjoerg 
make_error_code(BuildPreambleError Error)86006f32e7eSjoerg std::error_code clang::make_error_code(BuildPreambleError Error) {
86106f32e7eSjoerg   return std::error_code(static_cast<int>(Error), *BuildPreambleErrCategory);
86206f32e7eSjoerg }
86306f32e7eSjoerg 
name() const86406f32e7eSjoerg const char *BuildPreambleErrorCategory::name() const noexcept {
86506f32e7eSjoerg   return "build-preamble.error";
86606f32e7eSjoerg }
86706f32e7eSjoerg 
message(int condition) const86806f32e7eSjoerg std::string BuildPreambleErrorCategory::message(int condition) const {
86906f32e7eSjoerg   switch (static_cast<BuildPreambleError>(condition)) {
87006f32e7eSjoerg   case BuildPreambleError::CouldntCreateTempFile:
87106f32e7eSjoerg     return "Could not create temporary file for PCH";
87206f32e7eSjoerg   case BuildPreambleError::CouldntCreateTargetInfo:
87306f32e7eSjoerg     return "CreateTargetInfo() return null";
87406f32e7eSjoerg   case BuildPreambleError::BeginSourceFileFailed:
87506f32e7eSjoerg     return "BeginSourceFile() return an error";
87606f32e7eSjoerg   case BuildPreambleError::CouldntEmitPCH:
87706f32e7eSjoerg     return "Could not emit PCH";
87806f32e7eSjoerg   case BuildPreambleError::BadInputs:
87906f32e7eSjoerg     return "Command line arguments must contain exactly one source file";
88006f32e7eSjoerg   }
88106f32e7eSjoerg   llvm_unreachable("unexpected BuildPreambleError");
88206f32e7eSjoerg }
883