1 //===--- PrecompiledPreamble.cpp - Build precompiled preambles --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Helper class to build precompiled preamble.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Frontend/PrecompiledPreamble.h"
15 #include "clang/AST/DeclObjC.h"
16 #include "clang/Basic/TargetInfo.h"
17 #include "clang/Basic/VirtualFileSystem.h"
18 #include "clang/Frontend/CompilerInstance.h"
19 #include "clang/Frontend/CompilerInvocation.h"
20 #include "clang/Frontend/FrontendActions.h"
21 #include "clang/Frontend/FrontendOptions.h"
22 #include "clang/Lex/Lexer.h"
23 #include "clang/Lex/PreprocessorOptions.h"
24 #include "clang/Serialization/ASTWriter.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSet.h"
27 #include "llvm/Config/llvm-config.h"
28 #include "llvm/Support/CrashRecoveryContext.h"
29 #include "llvm/Support/FileSystem.h"
30 #include "llvm/Support/Mutex.h"
31 #include "llvm/Support/MutexGuard.h"
32 #include "llvm/Support/Process.h"
36 using namespace clang;
40 StringRef getInMemoryPreamblePath() {
41 #if defined(LLVM_ON_UNIX)
42 return "/__clang_tmp/___clang_inmemory_preamble___";
44 return "C:\\__clang_tmp\\___clang_inmemory_preamble___";
46 #warning "Unknown platform. Defaulting to UNIX-style paths for in-memory PCHs"
47 return "/__clang_tmp/___clang_inmemory_preamble___";
51 IntrusiveRefCntPtr<vfs::FileSystem>
52 createVFSOverlayForPreamblePCH(StringRef PCHFilename,
53 std::unique_ptr<llvm::MemoryBuffer> PCHBuffer,
54 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
55 // We want only the PCH file from the real filesystem to be available,
56 // so we create an in-memory VFS with just that and overlay it on top.
57 IntrusiveRefCntPtr<vfs::InMemoryFileSystem> PCHFS(
58 new vfs::InMemoryFileSystem());
59 PCHFS->addFile(PCHFilename, 0, std::move(PCHBuffer));
60 IntrusiveRefCntPtr<vfs::OverlayFileSystem> Overlay(
61 new vfs::OverlayFileSystem(VFS));
62 Overlay->pushOverlay(PCHFS);
66 class PreambleDependencyCollector : public DependencyCollector {
68 // We want to collect all dependencies for correctness. Avoiding the real
69 // system dependencies (e.g. stl from /usr/lib) would probably be a good idea,
70 // but there is no way to distinguish between those and the ones that can be
71 // spuriously added by '-isystem' (e.g. to suppress warnings from those
73 bool needSystemDependencies() override { return true; }
76 /// Keeps a track of files to be deleted in destructor.
77 class TemporaryFiles {
79 // A static instance to be used by all clients.
80 static TemporaryFiles &getInstance();
83 // Disallow constructing the class directly.
84 TemporaryFiles() = default;
86 TemporaryFiles(const TemporaryFiles &) = delete;
91 /// Adds \p File to a set of tracked files.
92 void addFile(StringRef File);
94 /// Remove \p File from disk and from the set of tracked files.
95 void removeFile(StringRef File);
98 llvm::sys::SmartMutex<false> Mutex;
99 llvm::StringSet<> Files;
102 TemporaryFiles &TemporaryFiles::getInstance() {
103 static TemporaryFiles Instance;
107 TemporaryFiles::~TemporaryFiles() {
108 llvm::MutexGuard Guard(Mutex);
109 for (const auto &File : Files)
110 llvm::sys::fs::remove(File.getKey());
113 void TemporaryFiles::addFile(StringRef File) {
114 llvm::MutexGuard Guard(Mutex);
115 auto IsInserted = Files.insert(File).second;
117 assert(IsInserted && "File has already been added");
120 void TemporaryFiles::removeFile(StringRef File) {
121 llvm::MutexGuard Guard(Mutex);
122 auto WasPresent = Files.erase(File);
124 assert(WasPresent && "File was not tracked");
125 llvm::sys::fs::remove(File);
128 class PrecompilePreambleAction : public ASTFrontendAction {
130 PrecompilePreambleAction(std::string *InMemStorage,
131 PreambleCallbacks &Callbacks)
132 : InMemStorage(InMemStorage), Callbacks(Callbacks) {}
134 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
135 StringRef InFile) override;
137 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
139 void setEmittedPreamblePCH(ASTWriter &Writer) {
140 this->HasEmittedPreamblePCH = true;
141 Callbacks.AfterPCHEmitted(Writer);
144 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
145 bool hasCodeCompletionSupport() const override { return false; }
146 bool hasASTFileSupport() const override { return false; }
147 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
150 friend class PrecompilePreambleConsumer;
152 bool HasEmittedPreamblePCH = false;
153 std::string *InMemStorage;
154 PreambleCallbacks &Callbacks;
157 class PrecompilePreambleConsumer : public PCHGenerator {
159 PrecompilePreambleConsumer(PrecompilePreambleAction &Action,
160 const Preprocessor &PP, StringRef isysroot,
161 std::unique_ptr<raw_ostream> Out)
162 : PCHGenerator(PP, "", isysroot, std::make_shared<PCHBuffer>(),
163 ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
164 /*AllowASTWithErrors=*/true),
165 Action(Action), Out(std::move(Out)) {}
167 bool HandleTopLevelDecl(DeclGroupRef DG) override {
168 Action.Callbacks.HandleTopLevelDecl(DG);
172 void HandleTranslationUnit(ASTContext &Ctx) override {
173 PCHGenerator::HandleTranslationUnit(Ctx);
174 if (!hasEmittedPCH())
177 // Write the generated bitstream to "Out".
179 // Make sure it hits disk now.
182 llvm::SmallVector<char, 0> Empty;
183 getPCH() = std::move(Empty);
185 Action.setEmittedPreamblePCH(getWriter());
189 PrecompilePreambleAction &Action;
190 std::unique_ptr<raw_ostream> Out;
193 std::unique_ptr<ASTConsumer>
194 PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
197 if (!GeneratePCHAction::ComputeASTConsumerArguments(CI, Sysroot))
200 std::unique_ptr<llvm::raw_ostream> OS;
202 OS = llvm::make_unique<llvm::raw_string_ostream>(*InMemStorage);
204 std::string OutputFile;
205 OS = GeneratePCHAction::CreateOutputFile(CI, InFile, OutputFile);
210 if (!CI.getFrontendOpts().RelocatablePCH)
213 return llvm::make_unique<PrecompilePreambleConsumer>(
214 *this, CI.getPreprocessor(), Sysroot, std::move(OS));
217 template <class T> bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
220 Output = std::move(*Val);
226 PreambleBounds clang::ComputePreambleBounds(const LangOptions &LangOpts,
227 llvm::MemoryBuffer *Buffer,
229 return Lexer::ComputePreamble(Buffer->getBuffer(), LangOpts, MaxLines);
232 llvm::ErrorOr<PrecompiledPreamble> PrecompiledPreamble::Build(
233 const CompilerInvocation &Invocation,
234 const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds,
235 DiagnosticsEngine &Diagnostics, IntrusiveRefCntPtr<vfs::FileSystem> VFS,
236 std::shared_ptr<PCHContainerOperations> PCHContainerOps, bool StoreInMemory,
237 PreambleCallbacks &Callbacks) {
238 assert(VFS && "VFS is null");
241 return BuildPreambleError::PreambleIsEmpty;
243 auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
244 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
245 PreprocessorOptions &PreprocessorOpts =
246 PreambleInvocation->getPreprocessorOpts();
248 llvm::Optional<TempPCHFile> TempFile;
249 if (!StoreInMemory) {
250 // Create a temporary file for the precompiled preamble. In rare
251 // circumstances, this can fail.
252 llvm::ErrorOr<PrecompiledPreamble::TempPCHFile> PreamblePCHFile =
253 PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile();
254 if (!PreamblePCHFile)
255 return BuildPreambleError::CouldntCreateTempFile;
256 TempFile = std::move(*PreamblePCHFile);
259 PCHStorage Storage = StoreInMemory ? PCHStorage(InMemoryPreamble())
260 : PCHStorage(std::move(*TempFile));
262 // Save the preamble text for later; we'll need to compare against it for
263 // subsequent reparses.
264 std::vector<char> PreambleBytes(MainFileBuffer->getBufferStart(),
265 MainFileBuffer->getBufferStart() +
267 bool PreambleEndsAtStartOfLine = Bounds.PreambleEndsAtStartOfLine;
269 // Tell the compiler invocation to generate a temporary precompiled header.
270 FrontendOpts.ProgramAction = frontend::GeneratePCH;
271 FrontendOpts.OutputFile = StoreInMemory ? getInMemoryPreamblePath()
272 : Storage.asFile().getFilePath();
273 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
274 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
275 // Inform preprocessor to record conditional stack when building the preamble.
276 PreprocessorOpts.GeneratePreamble = true;
278 // Create the compiler instance to use for building the precompiled preamble.
279 std::unique_ptr<CompilerInstance> Clang(
280 new CompilerInstance(std::move(PCHContainerOps)));
282 // Recover resources if we crash before exiting this method.
283 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
286 Clang->setInvocation(std::move(PreambleInvocation));
287 Clang->setDiagnostics(&Diagnostics);
289 // Create the target instance.
290 Clang->setTarget(TargetInfo::CreateTargetInfo(
291 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
292 if (!Clang->hasTarget())
293 return BuildPreambleError::CouldntCreateTargetInfo;
295 // Inform the target of the language options.
297 // FIXME: We shouldn't need to do this, the target should be immutable once
298 // created. This complexity should be lifted elsewhere.
299 Clang->getTarget().adjust(Clang->getLangOpts());
301 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
302 "Invocation must have exactly one source file!");
303 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
305 "FIXME: AST inputs not yet supported here!");
306 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
307 InputKind::LLVM_IR &&
308 "IR inputs not support here!");
310 // Clear out old caches and data.
312 ProcessWarningOptions(Diagnostics, Clang->getDiagnosticOpts());
315 createVFSFromCompilerInvocation(Clang->getInvocation(), Diagnostics, VFS);
317 // Create a file manager object to provide access to and cache the filesystem.
318 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
320 // Create the source manager.
321 Clang->setSourceManager(
322 new SourceManager(Diagnostics, Clang->getFileManager()));
324 auto PreambleDepCollector = std::make_shared<PreambleDependencyCollector>();
325 Clang->addDependencyCollector(PreambleDepCollector);
327 // Remap the main source file to the preamble buffer.
328 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
329 auto PreambleInputBuffer = llvm::MemoryBuffer::getMemBufferCopy(
330 MainFileBuffer->getBuffer().slice(0, Bounds.Size), MainFilePath);
331 if (PreprocessorOpts.RetainRemappedFileBuffers) {
332 // MainFileBuffer will be deleted by unique_ptr after leaving the method.
333 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleInputBuffer.get());
335 // In that case, remapped buffer will be deleted by CompilerInstance on
336 // BeginSourceFile, so we call release() to avoid double deletion.
337 PreprocessorOpts.addRemappedFile(MainFilePath,
338 PreambleInputBuffer.release());
341 std::unique_ptr<PrecompilePreambleAction> Act;
342 Act.reset(new PrecompilePreambleAction(
343 StoreInMemory ? &Storage.asMemory().Data : nullptr, Callbacks));
344 Callbacks.BeforeExecute(*Clang);
345 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
346 return BuildPreambleError::BeginSourceFileFailed;
348 std::unique_ptr<PPCallbacks> DelegatedPPCallbacks =
349 Callbacks.createPPCallbacks();
350 if (DelegatedPPCallbacks)
351 Clang->getPreprocessor().addPPCallbacks(std::move(DelegatedPPCallbacks));
355 // Run the callbacks.
356 Callbacks.AfterExecute(*Clang);
358 Act->EndSourceFile();
360 if (!Act->hasEmittedPreamblePCH())
361 return BuildPreambleError::CouldntEmitPCH;
363 // Keep track of all of the files that the source manager knows about,
364 // so we can verify whether they have changed or not.
365 llvm::StringMap<PrecompiledPreamble::PreambleFileHash> FilesInPreamble;
367 SourceManager &SourceMgr = Clang->getSourceManager();
368 for (auto &Filename : PreambleDepCollector->getDependencies()) {
369 const FileEntry *File = Clang->getFileManager().getFile(Filename);
370 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
372 if (time_t ModTime = File->getModificationTime()) {
373 FilesInPreamble[File->getName()] =
374 PrecompiledPreamble::PreambleFileHash::createForFile(File->getSize(),
377 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
378 FilesInPreamble[File->getName()] =
379 PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(Buffer);
383 return PrecompiledPreamble(std::move(Storage), std::move(PreambleBytes),
384 PreambleEndsAtStartOfLine,
385 std::move(FilesInPreamble));
388 PreambleBounds PrecompiledPreamble::getBounds() const {
389 return PreambleBounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
392 std::size_t PrecompiledPreamble::getSize() const {
393 switch (Storage.getKind()) {
394 case PCHStorage::Kind::Empty:
395 assert(false && "Calling getSize() on invalid PrecompiledPreamble. "
396 "Was it std::moved?");
398 case PCHStorage::Kind::InMemory:
399 return Storage.asMemory().Data.size();
400 case PCHStorage::Kind::TempFile: {
402 if (llvm::sys::fs::file_size(Storage.asFile().getFilePath(), Result))
405 assert(Result <= std::numeric_limits<std::size_t>::max() &&
406 "file size did not fit into size_t");
410 llvm_unreachable("Unhandled storage kind");
413 bool PrecompiledPreamble::CanReuse(const CompilerInvocation &Invocation,
414 const llvm::MemoryBuffer *MainFileBuffer,
415 PreambleBounds Bounds,
416 vfs::FileSystem *VFS) const {
419 Bounds.Size <= MainFileBuffer->getBufferSize() &&
420 "Buffer is too large. Bounds were calculated from a different buffer?");
422 auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
423 PreprocessorOptions &PreprocessorOpts =
424 PreambleInvocation->getPreprocessorOpts();
429 // We've previously computed a preamble. Check whether we have the same
430 // preamble now that we did before, and that there's enough space in
431 // the main-file buffer within the precompiled preamble to fit the
433 if (PreambleBytes.size() != Bounds.Size ||
434 PreambleEndsAtStartOfLine != Bounds.PreambleEndsAtStartOfLine ||
435 memcmp(PreambleBytes.data(), MainFileBuffer->getBufferStart(),
438 // The preamble has not changed. We may be able to re-use the precompiled
441 // Check that none of the files used by the preamble have changed.
442 // First, make a record of those files that have been overridden via
443 // remapping or unsaved_files.
444 std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
445 for (const auto &R : PreprocessorOpts.RemappedFiles) {
447 if (!moveOnNoError(VFS->status(R.second), Status)) {
448 // If we can't stat the file we're remapping to, assume that something
449 // horrible happened.
453 OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
454 Status.getSize(), llvm::sys::toTimeT(Status.getLastModificationTime()));
457 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
459 if (!moveOnNoError(VFS->status(RB.first), Status))
462 OverriddenFiles[Status.getUniqueID()] =
463 PreambleFileHash::createForMemoryBuffer(RB.second);
466 // Check whether anything has changed.
467 for (const auto &F : FilesInPreamble) {
469 if (!moveOnNoError(VFS->status(F.first()), Status)) {
470 // If we can't stat the file, assume that something horrible happened.
474 std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden =
475 OverriddenFiles.find(Status.getUniqueID());
476 if (Overridden != OverriddenFiles.end()) {
477 // This file was remapped; check whether the newly-mapped file
478 // matches up with the previous mapping.
479 if (Overridden->second != F.second)
484 // The file was not remapped; check whether it has changed on disk.
485 if (Status.getSize() != uint64_t(F.second.Size) ||
486 llvm::sys::toTimeT(Status.getLastModificationTime()) !=
493 void PrecompiledPreamble::AddImplicitPreamble(
494 CompilerInvocation &CI, IntrusiveRefCntPtr<vfs::FileSystem> &VFS,
495 llvm::MemoryBuffer *MainFileBuffer) const {
496 PreambleBounds Bounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
497 configurePreamble(Bounds, CI, VFS, MainFileBuffer);
500 void PrecompiledPreamble::OverridePreamble(
501 CompilerInvocation &CI, IntrusiveRefCntPtr<vfs::FileSystem> &VFS,
502 llvm::MemoryBuffer *MainFileBuffer) const {
503 auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), MainFileBuffer, 0);
504 configurePreamble(Bounds, CI, VFS, MainFileBuffer);
507 PrecompiledPreamble::PrecompiledPreamble(
508 PCHStorage Storage, std::vector<char> PreambleBytes,
509 bool PreambleEndsAtStartOfLine,
510 llvm::StringMap<PreambleFileHash> FilesInPreamble)
511 : Storage(std::move(Storage)), FilesInPreamble(std::move(FilesInPreamble)),
512 PreambleBytes(std::move(PreambleBytes)),
513 PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {
514 assert(this->Storage.getKind() != PCHStorage::Kind::Empty);
517 llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
518 PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile() {
519 // FIXME: This is a hack so that we can override the preamble file during
520 // crash-recovery testing, which is the only case where the preamble files
521 // are not necessarily cleaned up.
522 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
524 return TempPCHFile::createFromCustomPath(TmpFile);
525 return TempPCHFile::createInSystemTempDir("preamble", "pch");
528 llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
529 PrecompiledPreamble::TempPCHFile::createInSystemTempDir(const Twine &Prefix,
531 llvm::SmallString<64> File;
532 // Using a version of createTemporaryFile with a file descriptor guarantees
533 // that we would never get a race condition in a multi-threaded setting
534 // (i.e., multiple threads getting the same temporary path).
536 auto EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, FD, File);
539 // We only needed to make sure the file exists, close the file right away.
540 llvm::sys::Process::SafelyCloseFileDescriptor(FD);
541 return TempPCHFile(std::move(File).str());
544 llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
545 PrecompiledPreamble::TempPCHFile::createFromCustomPath(const Twine &Path) {
546 return TempPCHFile(Path.str());
549 PrecompiledPreamble::TempPCHFile::TempPCHFile(std::string FilePath)
550 : FilePath(std::move(FilePath)) {
551 TemporaryFiles::getInstance().addFile(*this->FilePath);
554 PrecompiledPreamble::TempPCHFile::TempPCHFile(TempPCHFile &&Other) {
555 FilePath = std::move(Other.FilePath);
556 Other.FilePath = None;
559 PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::TempPCHFile::
560 operator=(TempPCHFile &&Other) {
561 RemoveFileIfPresent();
563 FilePath = std::move(Other.FilePath);
564 Other.FilePath = None;
568 PrecompiledPreamble::TempPCHFile::~TempPCHFile() { RemoveFileIfPresent(); }
570 void PrecompiledPreamble::TempPCHFile::RemoveFileIfPresent() {
572 TemporaryFiles::getInstance().removeFile(*FilePath);
577 llvm::StringRef PrecompiledPreamble::TempPCHFile::getFilePath() const {
578 assert(FilePath && "TempPCHFile doesn't have a FilePath. Had it been moved?");
582 PrecompiledPreamble::PCHStorage::PCHStorage(TempPCHFile File)
583 : StorageKind(Kind::TempFile) {
584 new (&asFile()) TempPCHFile(std::move(File));
587 PrecompiledPreamble::PCHStorage::PCHStorage(InMemoryPreamble Memory)
588 : StorageKind(Kind::InMemory) {
589 new (&asMemory()) InMemoryPreamble(std::move(Memory));
592 PrecompiledPreamble::PCHStorage::PCHStorage(PCHStorage &&Other) : PCHStorage() {
593 *this = std::move(Other);
596 PrecompiledPreamble::PCHStorage &PrecompiledPreamble::PCHStorage::
597 operator=(PCHStorage &&Other) {
600 StorageKind = Other.StorageKind;
601 switch (StorageKind) {
606 new (&asFile()) TempPCHFile(std::move(Other.asFile()));
609 new (&asMemory()) InMemoryPreamble(std::move(Other.asMemory()));
617 PrecompiledPreamble::PCHStorage::~PCHStorage() { destroy(); }
619 PrecompiledPreamble::PCHStorage::Kind
620 PrecompiledPreamble::PCHStorage::getKind() const {
624 PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::PCHStorage::asFile() {
625 assert(getKind() == Kind::TempFile);
626 return *reinterpret_cast<TempPCHFile *>(Storage.buffer);
629 const PrecompiledPreamble::TempPCHFile &
630 PrecompiledPreamble::PCHStorage::asFile() const {
631 return const_cast<PCHStorage *>(this)->asFile();
634 PrecompiledPreamble::InMemoryPreamble &
635 PrecompiledPreamble::PCHStorage::asMemory() {
636 assert(getKind() == Kind::InMemory);
637 return *reinterpret_cast<InMemoryPreamble *>(Storage.buffer);
640 const PrecompiledPreamble::InMemoryPreamble &
641 PrecompiledPreamble::PCHStorage::asMemory() const {
642 return const_cast<PCHStorage *>(this)->asMemory();
645 void PrecompiledPreamble::PCHStorage::destroy() {
646 switch (StorageKind) {
650 asFile().~TempPCHFile();
653 asMemory().~InMemoryPreamble();
658 void PrecompiledPreamble::PCHStorage::setEmpty() {
660 StorageKind = Kind::Empty;
663 PrecompiledPreamble::PreambleFileHash
664 PrecompiledPreamble::PreambleFileHash::createForFile(off_t Size,
666 PreambleFileHash Result;
668 Result.ModTime = ModTime;
673 PrecompiledPreamble::PreambleFileHash
674 PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(
675 const llvm::MemoryBuffer *Buffer) {
676 PreambleFileHash Result;
677 Result.Size = Buffer->getBufferSize();
681 MD5Ctx.update(Buffer->getBuffer().data());
682 MD5Ctx.final(Result.MD5);
687 void PrecompiledPreamble::configurePreamble(
688 PreambleBounds Bounds, CompilerInvocation &CI,
689 IntrusiveRefCntPtr<vfs::FileSystem> &VFS,
690 llvm::MemoryBuffer *MainFileBuffer) const {
693 auto &PreprocessorOpts = CI.getPreprocessorOpts();
695 // Remap main file to point to MainFileBuffer.
696 auto MainFilePath = CI.getFrontendOpts().Inputs[0].getFile();
697 PreprocessorOpts.addRemappedFile(MainFilePath, MainFileBuffer);
699 // Configure ImpicitPCHInclude.
700 PreprocessorOpts.PrecompiledPreambleBytes.first = Bounds.Size;
701 PreprocessorOpts.PrecompiledPreambleBytes.second =
702 Bounds.PreambleEndsAtStartOfLine;
703 PreprocessorOpts.DisablePCHValidation = true;
705 setupPreambleStorage(Storage, PreprocessorOpts, VFS);
708 void PrecompiledPreamble::setupPreambleStorage(
709 const PCHStorage &Storage, PreprocessorOptions &PreprocessorOpts,
710 IntrusiveRefCntPtr<vfs::FileSystem> &VFS) {
711 if (Storage.getKind() == PCHStorage::Kind::TempFile) {
712 const TempPCHFile &PCHFile = Storage.asFile();
713 PreprocessorOpts.ImplicitPCHInclude = PCHFile.getFilePath();
715 // Make sure we can access the PCH file even if we're using a VFS
716 IntrusiveRefCntPtr<vfs::FileSystem> RealFS = vfs::getRealFileSystem();
717 auto PCHPath = PCHFile.getFilePath();
718 if (VFS == RealFS || VFS->exists(PCHPath))
720 auto Buf = RealFS->getBufferForFile(PCHPath);
722 // We can't read the file even from RealFS, this is clearly an error,
723 // but we'll just leave the current VFS as is and let clang's code
724 // figure out what to do with missing PCH.
728 // We have a slight inconsistency here -- we're using the VFS to
729 // read files, but the PCH was generated in the real file system.
730 VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(*Buf), VFS);
732 assert(Storage.getKind() == PCHStorage::Kind::InMemory);
733 // For in-memory preamble, we have to provide a VFS overlay that makes it
735 StringRef PCHPath = getInMemoryPreamblePath();
736 PreprocessorOpts.ImplicitPCHInclude = PCHPath;
738 auto Buf = llvm::MemoryBuffer::getMemBuffer(Storage.asMemory().Data);
739 VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(Buf), VFS);
743 void PreambleCallbacks::BeforeExecute(CompilerInstance &CI) {}
744 void PreambleCallbacks::AfterExecute(CompilerInstance &CI) {}
745 void PreambleCallbacks::AfterPCHEmitted(ASTWriter &Writer) {}
746 void PreambleCallbacks::HandleTopLevelDecl(DeclGroupRef DG) {}
747 std::unique_ptr<PPCallbacks> PreambleCallbacks::createPPCallbacks() {
751 std::error_code clang::make_error_code(BuildPreambleError Error) {
752 return std::error_code(static_cast<int>(Error), BuildPreambleErrorCategory());
755 const char *BuildPreambleErrorCategory::name() const noexcept {
756 return "build-preamble.error";
759 std::string BuildPreambleErrorCategory::message(int condition) const {
760 switch (static_cast<BuildPreambleError>(condition)) {
761 case BuildPreambleError::PreambleIsEmpty:
762 return "Preamble is empty";
763 case BuildPreambleError::CouldntCreateTempFile:
764 return "Could not create temporary file for PCH";
765 case BuildPreambleError::CouldntCreateTargetInfo:
766 return "CreateTargetInfo() return null";
767 case BuildPreambleError::BeginSourceFileFailed:
768 return "BeginSourceFile() return an error";
769 case BuildPreambleError::CouldntEmitPCH:
770 return "Could not emit PCH";
772 llvm_unreachable("unexpected BuildPreambleError");