clang  8.0.0svn
PrecompiledPreamble.cpp
Go to the documentation of this file.
1 //===--- PrecompiledPreamble.cpp - Build precompiled preambles --*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Helper class to build precompiled preamble.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "clang/AST/DeclObjC.h"
16 #include "clang/Basic/TargetInfo.h"
21 #include "clang/Lex/Lexer.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSet.h"
26 #include "llvm/Config/llvm-config.h"
27 #include "llvm/Support/CrashRecoveryContext.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/Mutex.h"
30 #include "llvm/Support/MutexGuard.h"
31 #include "llvm/Support/Process.h"
32 #include "llvm/Support/VirtualFileSystem.h"
33 #include <limits>
34 #include <utility>
35 
36 using namespace clang;
37 
38 namespace {
39 
40 StringRef getInMemoryPreamblePath() {
41 #if defined(LLVM_ON_UNIX)
42  return "/__clang_tmp/___clang_inmemory_preamble___";
43 #elif defined(_WIN32)
44  return "C:\\__clang_tmp\\___clang_inmemory_preamble___";
45 #else
46 #warning "Unknown platform. Defaulting to UNIX-style paths for in-memory PCHs"
47  return "/__clang_tmp/___clang_inmemory_preamble___";
48 #endif
49 }
50 
52 createVFSOverlayForPreamblePCH(StringRef PCHFilename,
53  std::unique_ptr<llvm::MemoryBuffer> PCHBuffer,
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.
58  new llvm::vfs::InMemoryFileSystem());
59  PCHFS->addFile(PCHFilename, 0, std::move(PCHBuffer));
61  new llvm::vfs::OverlayFileSystem(VFS));
62  Overlay->pushOverlay(PCHFS);
63  return Overlay;
64 }
65 
66 class PreambleDependencyCollector : public DependencyCollector {
67 public:
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
72  // headers).
73  bool needSystemDependencies() override { return true; }
74 };
75 
76 /// Keeps a track of files to be deleted in destructor.
77 class TemporaryFiles {
78 public:
79  // A static instance to be used by all clients.
80  static TemporaryFiles &getInstance();
81 
82 private:
83  // Disallow constructing the class directly.
84  TemporaryFiles() = default;
85  // Disallow copy.
86  TemporaryFiles(const TemporaryFiles &) = delete;
87 
88 public:
89  ~TemporaryFiles();
90 
91  /// Adds \p File to a set of tracked files.
92  void addFile(StringRef File);
93 
94  /// Remove \p File from disk and from the set of tracked files.
95  void removeFile(StringRef File);
96 
97 private:
98  llvm::sys::SmartMutex<false> Mutex;
99  llvm::StringSet<> Files;
100 };
101 
102 TemporaryFiles &TemporaryFiles::getInstance() {
103  static TemporaryFiles Instance;
104  return Instance;
105 }
106 
107 TemporaryFiles::~TemporaryFiles() {
108  llvm::MutexGuard Guard(Mutex);
109  for (const auto &File : Files)
110  llvm::sys::fs::remove(File.getKey());
111 }
112 
113 void TemporaryFiles::addFile(StringRef File) {
114  llvm::MutexGuard Guard(Mutex);
115  auto IsInserted = Files.insert(File).second;
116  (void)IsInserted;
117  assert(IsInserted && "File has already been added");
118 }
119 
120 void TemporaryFiles::removeFile(StringRef File) {
121  llvm::MutexGuard Guard(Mutex);
122  auto WasPresent = Files.erase(File);
123  (void)WasPresent;
124  assert(WasPresent && "File was not tracked");
125  llvm::sys::fs::remove(File);
126 }
127 
128 class PrecompilePreambleAction : public ASTFrontendAction {
129 public:
130  PrecompilePreambleAction(std::string *InMemStorage,
131  PreambleCallbacks &Callbacks)
132  : InMemStorage(InMemStorage), Callbacks(Callbacks) {}
133 
134  std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
135  StringRef InFile) override;
136 
137  bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
138 
139  void setEmittedPreamblePCH(ASTWriter &Writer) {
140  this->HasEmittedPreamblePCH = true;
141  Callbacks.AfterPCHEmitted(Writer);
142  }
143 
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; }
148 
149 private:
150  friend class PrecompilePreambleConsumer;
151 
152  bool HasEmittedPreamblePCH = false;
153  std::string *InMemStorage;
154  PreambleCallbacks &Callbacks;
155 };
156 
157 class PrecompilePreambleConsumer : public PCHGenerator {
158 public:
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)) {}
166 
167  bool HandleTopLevelDecl(DeclGroupRef DG) override {
168  Action.Callbacks.HandleTopLevelDecl(DG);
169  return true;
170  }
171 
172  void HandleTranslationUnit(ASTContext &Ctx) override {
174  if (!hasEmittedPCH())
175  return;
176 
177  // Write the generated bitstream to "Out".
178  *Out << getPCH();
179  // Make sure it hits disk now.
180  Out->flush();
181  // Free the buffer.
183  getPCH() = std::move(Empty);
184 
185  Action.setEmittedPreamblePCH(getWriter());
186  }
187 
188 private:
189  PrecompilePreambleAction &Action;
190  std::unique_ptr<raw_ostream> Out;
191 };
192 
193 std::unique_ptr<ASTConsumer>
194 PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
195  StringRef InFile) {
196  std::string Sysroot;
198  return nullptr;
199 
200  std::unique_ptr<llvm::raw_ostream> OS;
201  if (InMemStorage) {
202  OS = llvm::make_unique<llvm::raw_string_ostream>(*InMemStorage);
203  } else {
204  std::string OutputFile;
205  OS = GeneratePCHAction::CreateOutputFile(CI, InFile, OutputFile);
206  }
207  if (!OS)
208  return nullptr;
209 
211  Sysroot.clear();
212 
213  return llvm::make_unique<PrecompilePreambleConsumer>(
214  *this, CI.getPreprocessor(), Sysroot, std::move(OS));
215 }
216 
217 template <class T> bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
218  if (!Val)
219  return false;
220  Output = std::move(*Val);
221  return true;
222 }
223 
224 } // namespace
225 
227  llvm::MemoryBuffer *Buffer,
228  unsigned MaxLines) {
229  return Lexer::ComputePreamble(Buffer->getBuffer(), LangOpts, MaxLines);
230 }
231 
232 llvm::ErrorOr<PrecompiledPreamble> PrecompiledPreamble::Build(
233  const CompilerInvocation &Invocation,
234  const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds,
235  DiagnosticsEngine &Diagnostics,
237  std::shared_ptr<PCHContainerOperations> PCHContainerOps, bool StoreInMemory,
238  PreambleCallbacks &Callbacks) {
239  assert(VFS && "VFS is null");
240 
241  auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
242  FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
243  PreprocessorOptions &PreprocessorOpts =
244  PreambleInvocation->getPreprocessorOpts();
245 
247  if (!StoreInMemory) {
248  // Create a temporary file for the precompiled preamble. In rare
249  // circumstances, this can fail.
250  llvm::ErrorOr<PrecompiledPreamble::TempPCHFile> PreamblePCHFile =
251  PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile();
252  if (!PreamblePCHFile)
254  TempFile = std::move(*PreamblePCHFile);
255  }
256 
257  PCHStorage Storage = StoreInMemory ? PCHStorage(InMemoryPreamble())
258  : PCHStorage(std::move(*TempFile));
259 
260  // Save the preamble text for later; we'll need to compare against it for
261  // subsequent reparses.
262  std::vector<char> PreambleBytes(MainFileBuffer->getBufferStart(),
263  MainFileBuffer->getBufferStart() +
264  Bounds.Size);
265  bool PreambleEndsAtStartOfLine = Bounds.PreambleEndsAtStartOfLine;
266 
267  // Tell the compiler invocation to generate a temporary precompiled header.
268  FrontendOpts.ProgramAction = frontend::GeneratePCH;
269  FrontendOpts.OutputFile = StoreInMemory ? getInMemoryPreamblePath()
270  : Storage.asFile().getFilePath();
271  PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
272  PreprocessorOpts.PrecompiledPreambleBytes.second = false;
273  // Inform preprocessor to record conditional stack when building the preamble.
274  PreprocessorOpts.GeneratePreamble = true;
275 
276  // Create the compiler instance to use for building the precompiled preamble.
277  std::unique_ptr<CompilerInstance> Clang(
278  new CompilerInstance(std::move(PCHContainerOps)));
279 
280  // Recover resources if we crash before exiting this method.
281  llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
282  Clang.get());
283 
284  Clang->setInvocation(std::move(PreambleInvocation));
285  Clang->setDiagnostics(&Diagnostics);
286 
287  // Create the target instance.
288  Clang->setTarget(TargetInfo::CreateTargetInfo(
289  Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
290  if (!Clang->hasTarget())
292 
293  // Inform the target of the language options.
294  //
295  // FIXME: We shouldn't need to do this, the target should be immutable once
296  // created. This complexity should be lifted elsewhere.
297  Clang->getTarget().adjust(Clang->getLangOpts());
298 
299  assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
300  "Invocation must have exactly one source file!");
301  assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
303  "FIXME: AST inputs not yet supported here!");
304  assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
306  "IR inputs not support here!");
307 
308  // Clear out old caches and data.
309  Diagnostics.Reset();
310  ProcessWarningOptions(Diagnostics, Clang->getDiagnosticOpts());
311 
312  VFS =
313  createVFSFromCompilerInvocation(Clang->getInvocation(), Diagnostics, VFS);
314 
315  // Create a file manager object to provide access to and cache the filesystem.
316  Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
317 
318  // Create the source manager.
319  Clang->setSourceManager(
320  new SourceManager(Diagnostics, Clang->getFileManager()));
321 
322  auto PreambleDepCollector = std::make_shared<PreambleDependencyCollector>();
323  Clang->addDependencyCollector(PreambleDepCollector);
324 
325  // Remap the main source file to the preamble buffer.
326  StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
327  auto PreambleInputBuffer = llvm::MemoryBuffer::getMemBufferCopy(
328  MainFileBuffer->getBuffer().slice(0, Bounds.Size), MainFilePath);
329  if (PreprocessorOpts.RetainRemappedFileBuffers) {
330  // MainFileBuffer will be deleted by unique_ptr after leaving the method.
331  PreprocessorOpts.addRemappedFile(MainFilePath, PreambleInputBuffer.get());
332  } else {
333  // In that case, remapped buffer will be deleted by CompilerInstance on
334  // BeginSourceFile, so we call release() to avoid double deletion.
335  PreprocessorOpts.addRemappedFile(MainFilePath,
336  PreambleInputBuffer.release());
337  }
338 
339  std::unique_ptr<PrecompilePreambleAction> Act;
340  Act.reset(new PrecompilePreambleAction(
341  StoreInMemory ? &Storage.asMemory().Data : nullptr, Callbacks));
342  Callbacks.BeforeExecute(*Clang);
343  if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
345 
346  std::unique_ptr<PPCallbacks> DelegatedPPCallbacks =
347  Callbacks.createPPCallbacks();
348  if (DelegatedPPCallbacks)
349  Clang->getPreprocessor().addPPCallbacks(std::move(DelegatedPPCallbacks));
350 
351  Act->Execute();
352 
353  // Run the callbacks.
354  Callbacks.AfterExecute(*Clang);
355 
356  Act->EndSourceFile();
357 
358  if (!Act->hasEmittedPreamblePCH())
360 
361  // Keep track of all of the files that the source manager knows about,
362  // so we can verify whether they have changed or not.
363  llvm::StringMap<PrecompiledPreamble::PreambleFileHash> FilesInPreamble;
364 
365  SourceManager &SourceMgr = Clang->getSourceManager();
366  for (auto &Filename : PreambleDepCollector->getDependencies()) {
367  const FileEntry *File = Clang->getFileManager().getFile(Filename);
368  if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
369  continue;
370  if (time_t ModTime = File->getModificationTime()) {
371  FilesInPreamble[File->getName()] =
372  PrecompiledPreamble::PreambleFileHash::createForFile(File->getSize(),
373  ModTime);
374  } else {
375  llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
376  FilesInPreamble[File->getName()] =
377  PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(Buffer);
378  }
379  }
380 
381  return PrecompiledPreamble(std::move(Storage), std::move(PreambleBytes),
382  PreambleEndsAtStartOfLine,
383  std::move(FilesInPreamble));
384 }
385 
387  return PreambleBounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
388 }
389 
391  switch (Storage.getKind()) {
392  case PCHStorage::Kind::Empty:
393  assert(false && "Calling getSize() on invalid PrecompiledPreamble. "
394  "Was it std::moved?");
395  return 0;
396  case PCHStorage::Kind::InMemory:
397  return Storage.asMemory().Data.size();
398  case PCHStorage::Kind::TempFile: {
399  uint64_t Result;
400  if (llvm::sys::fs::file_size(Storage.asFile().getFilePath(), Result))
401  return 0;
402 
403  assert(Result <= std::numeric_limits<std::size_t>::max() &&
404  "file size did not fit into size_t");
405  return Result;
406  }
407  }
408  llvm_unreachable("Unhandled storage kind");
409 }
410 
412  const llvm::MemoryBuffer *MainFileBuffer,
413  PreambleBounds Bounds,
414  llvm::vfs::FileSystem *VFS) const {
415 
416  assert(
417  Bounds.Size <= MainFileBuffer->getBufferSize() &&
418  "Buffer is too large. Bounds were calculated from a different buffer?");
419 
420  auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
421  PreprocessorOptions &PreprocessorOpts =
422  PreambleInvocation->getPreprocessorOpts();
423 
424  // We've previously computed a preamble. Check whether we have the same
425  // preamble now that we did before, and that there's enough space in
426  // the main-file buffer within the precompiled preamble to fit the
427  // new main file.
428  if (PreambleBytes.size() != Bounds.Size ||
429  PreambleEndsAtStartOfLine != Bounds.PreambleEndsAtStartOfLine ||
430  !std::equal(PreambleBytes.begin(), PreambleBytes.end(),
431  MainFileBuffer->getBuffer().begin()))
432  return false;
433  // The preamble has not changed. We may be able to re-use the precompiled
434  // preamble.
435 
436  // Check that none of the files used by the preamble have changed.
437  // First, make a record of those files that have been overridden via
438  // remapping or unsaved_files.
439  std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
440  for (const auto &R : PreprocessorOpts.RemappedFiles) {
441  llvm::vfs::Status Status;
442  if (!moveOnNoError(VFS->status(R.second), Status)) {
443  // If we can't stat the file we're remapping to, assume that something
444  // horrible happened.
445  return false;
446  }
447 
448  OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
449  Status.getSize(), llvm::sys::toTimeT(Status.getLastModificationTime()));
450  }
451 
452  for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
453  llvm::vfs::Status Status;
454  if (!moveOnNoError(VFS->status(RB.first), Status))
455  return false;
456 
457  OverriddenFiles[Status.getUniqueID()] =
458  PreambleFileHash::createForMemoryBuffer(RB.second);
459  }
460 
461  // Check whether anything has changed.
462  for (const auto &F : FilesInPreamble) {
463  llvm::vfs::Status Status;
464  if (!moveOnNoError(VFS->status(F.first()), Status)) {
465  // If we can't stat the file, assume that something horrible happened.
466  return false;
467  }
468 
469  std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden =
470  OverriddenFiles.find(Status.getUniqueID());
471  if (Overridden != OverriddenFiles.end()) {
472  // This file was remapped; check whether the newly-mapped file
473  // matches up with the previous mapping.
474  if (Overridden->second != F.second)
475  return false;
476  continue;
477  }
478 
479  // The file was not remapped; check whether it has changed on disk.
480  if (Status.getSize() != uint64_t(F.second.Size) ||
481  llvm::sys::toTimeT(Status.getLastModificationTime()) !=
482  F.second.ModTime)
483  return false;
484  }
485  return true;
486 }
487 
490  llvm::MemoryBuffer *MainFileBuffer) const {
491  PreambleBounds Bounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
492  configurePreamble(Bounds, CI, VFS, MainFileBuffer);
493 }
494 
497  llvm::MemoryBuffer *MainFileBuffer) const {
498  auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), MainFileBuffer, 0);
499  configurePreamble(Bounds, CI, VFS, MainFileBuffer);
500 }
501 
503  PCHStorage Storage, std::vector<char> PreambleBytes,
504  bool PreambleEndsAtStartOfLine,
505  llvm::StringMap<PreambleFileHash> FilesInPreamble)
506  : Storage(std::move(Storage)), FilesInPreamble(std::move(FilesInPreamble)),
507  PreambleBytes(std::move(PreambleBytes)),
508  PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {
509  assert(this->Storage.getKind() != PCHStorage::Kind::Empty);
510 }
511 
512 llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
513 PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile() {
514  // FIXME: This is a hack so that we can override the preamble file during
515  // crash-recovery testing, which is the only case where the preamble files
516  // are not necessarily cleaned up.
517  const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
518  if (TmpFile)
519  return TempPCHFile::createFromCustomPath(TmpFile);
520  return TempPCHFile::createInSystemTempDir("preamble", "pch");
521 }
522 
523 llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
524 PrecompiledPreamble::TempPCHFile::createInSystemTempDir(const Twine &Prefix,
525  StringRef Suffix) {
527  // Using a version of createTemporaryFile with a file descriptor guarantees
528  // that we would never get a race condition in a multi-threaded setting
529  // (i.e., multiple threads getting the same temporary path).
530  int FD;
531  auto EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, FD, File);
532  if (EC)
533  return EC;
534  // We only needed to make sure the file exists, close the file right away.
535  llvm::sys::Process::SafelyCloseFileDescriptor(FD);
536  return TempPCHFile(std::move(File).str());
537 }
538 
539 llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
540 PrecompiledPreamble::TempPCHFile::createFromCustomPath(const Twine &Path) {
541  return TempPCHFile(Path.str());
542 }
543 
544 PrecompiledPreamble::TempPCHFile::TempPCHFile(std::string FilePath)
545  : FilePath(std::move(FilePath)) {
546  TemporaryFiles::getInstance().addFile(*this->FilePath);
547 }
548 
549 PrecompiledPreamble::TempPCHFile::TempPCHFile(TempPCHFile &&Other) {
550  FilePath = std::move(Other.FilePath);
551  Other.FilePath = None;
552 }
553 
554 PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::TempPCHFile::
555 operator=(TempPCHFile &&Other) {
556  RemoveFileIfPresent();
557 
558  FilePath = std::move(Other.FilePath);
559  Other.FilePath = None;
560  return *this;
561 }
562 
563 PrecompiledPreamble::TempPCHFile::~TempPCHFile() { RemoveFileIfPresent(); }
564 
565 void PrecompiledPreamble::TempPCHFile::RemoveFileIfPresent() {
566  if (FilePath) {
567  TemporaryFiles::getInstance().removeFile(*FilePath);
568  FilePath = None;
569  }
570 }
571 
572 llvm::StringRef PrecompiledPreamble::TempPCHFile::getFilePath() const {
573  assert(FilePath && "TempPCHFile doesn't have a FilePath. Had it been moved?");
574  return *FilePath;
575 }
576 
577 PrecompiledPreamble::PCHStorage::PCHStorage(TempPCHFile File)
578  : StorageKind(Kind::TempFile) {
579  new (&asFile()) TempPCHFile(std::move(File));
580 }
581 
582 PrecompiledPreamble::PCHStorage::PCHStorage(InMemoryPreamble Memory)
583  : StorageKind(Kind::InMemory) {
584  new (&asMemory()) InMemoryPreamble(std::move(Memory));
585 }
586 
587 PrecompiledPreamble::PCHStorage::PCHStorage(PCHStorage &&Other) : PCHStorage() {
588  *this = std::move(Other);
589 }
590 
591 PrecompiledPreamble::PCHStorage &PrecompiledPreamble::PCHStorage::
592 operator=(PCHStorage &&Other) {
593  destroy();
594 
595  StorageKind = Other.StorageKind;
596  switch (StorageKind) {
597  case Kind::Empty:
598  // do nothing;
599  break;
600  case Kind::TempFile:
601  new (&asFile()) TempPCHFile(std::move(Other.asFile()));
602  break;
603  case Kind::InMemory:
604  new (&asMemory()) InMemoryPreamble(std::move(Other.asMemory()));
605  break;
606  }
607 
608  Other.setEmpty();
609  return *this;
610 }
611 
612 PrecompiledPreamble::PCHStorage::~PCHStorage() { destroy(); }
613 
614 PrecompiledPreamble::PCHStorage::Kind
616  return StorageKind;
617 }
618 
619 PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::PCHStorage::asFile() {
620  assert(getKind() == Kind::TempFile);
621  return *reinterpret_cast<TempPCHFile *>(Storage.buffer);
622 }
623 
624 const PrecompiledPreamble::TempPCHFile &
625 PrecompiledPreamble::PCHStorage::asFile() const {
626  return const_cast<PCHStorage *>(this)->asFile();
627 }
628 
629 PrecompiledPreamble::InMemoryPreamble &
630 PrecompiledPreamble::PCHStorage::asMemory() {
631  assert(getKind() == Kind::InMemory);
632  return *reinterpret_cast<InMemoryPreamble *>(Storage.buffer);
633 }
634 
635 const PrecompiledPreamble::InMemoryPreamble &
636 PrecompiledPreamble::PCHStorage::asMemory() const {
637  return const_cast<PCHStorage *>(this)->asMemory();
638 }
639 
640 void PrecompiledPreamble::PCHStorage::destroy() {
641  switch (StorageKind) {
642  case Kind::Empty:
643  return;
644  case Kind::TempFile:
645  asFile().~TempPCHFile();
646  return;
647  case Kind::InMemory:
648  asMemory().~InMemoryPreamble();
649  return;
650  }
651 }
652 
653 void PrecompiledPreamble::PCHStorage::setEmpty() {
654  destroy();
655  StorageKind = Kind::Empty;
656 }
657 
658 PrecompiledPreamble::PreambleFileHash
659 PrecompiledPreamble::PreambleFileHash::createForFile(off_t Size,
660  time_t ModTime) {
661  PreambleFileHash Result;
662  Result.Size = Size;
663  Result.ModTime = ModTime;
664  Result.MD5 = {};
665  return Result;
666 }
667 
668 PrecompiledPreamble::PreambleFileHash
669 PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(
670  const llvm::MemoryBuffer *Buffer) {
671  PreambleFileHash Result;
672  Result.Size = Buffer->getBufferSize();
673  Result.ModTime = 0;
674 
675  llvm::MD5 MD5Ctx;
676  MD5Ctx.update(Buffer->getBuffer().data());
677  MD5Ctx.final(Result.MD5);
678 
679  return Result;
680 }
681 
682 void PrecompiledPreamble::configurePreamble(
685  llvm::MemoryBuffer *MainFileBuffer) const {
686  assert(VFS);
687 
688  auto &PreprocessorOpts = CI.getPreprocessorOpts();
689 
690  // Remap main file to point to MainFileBuffer.
691  auto MainFilePath = CI.getFrontendOpts().Inputs[0].getFile();
692  PreprocessorOpts.addRemappedFile(MainFilePath, MainFileBuffer);
693 
694  // Configure ImpicitPCHInclude.
695  PreprocessorOpts.PrecompiledPreambleBytes.first = Bounds.Size;
696  PreprocessorOpts.PrecompiledPreambleBytes.second =
698  PreprocessorOpts.DisablePCHValidation = true;
699 
700  setupPreambleStorage(Storage, PreprocessorOpts, VFS);
701 }
702 
703 void PrecompiledPreamble::setupPreambleStorage(
704  const PCHStorage &Storage, PreprocessorOptions &PreprocessorOpts,
706  if (Storage.getKind() == PCHStorage::Kind::TempFile) {
707  const TempPCHFile &PCHFile = Storage.asFile();
708  PreprocessorOpts.ImplicitPCHInclude = PCHFile.getFilePath();
709 
710  // Make sure we can access the PCH file even if we're using a VFS
712  llvm::vfs::getRealFileSystem();
713  auto PCHPath = PCHFile.getFilePath();
714  if (VFS == RealFS || VFS->exists(PCHPath))
715  return;
716  auto Buf = RealFS->getBufferForFile(PCHPath);
717  if (!Buf) {
718  // We can't read the file even from RealFS, this is clearly an error,
719  // but we'll just leave the current VFS as is and let clang's code
720  // figure out what to do with missing PCH.
721  return;
722  }
723 
724  // We have a slight inconsistency here -- we're using the VFS to
725  // read files, but the PCH was generated in the real file system.
726  VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(*Buf), VFS);
727  } else {
728  assert(Storage.getKind() == PCHStorage::Kind::InMemory);
729  // For in-memory preamble, we have to provide a VFS overlay that makes it
730  // accessible.
731  StringRef PCHPath = getInMemoryPreamblePath();
732  PreprocessorOpts.ImplicitPCHInclude = PCHPath;
733 
734  auto Buf = llvm::MemoryBuffer::getMemBuffer(Storage.asMemory().Data);
735  VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(Buf), VFS);
736  }
737 }
738 
743 std::unique_ptr<PPCallbacks> PreambleCallbacks::createPPCallbacks() {
744  return nullptr;
745 }
746 
747 static llvm::ManagedStatic<BuildPreambleErrorCategory> BuildPreambleErrCategory;
748 
750  return std::error_code(static_cast<int>(Error), *BuildPreambleErrCategory);
751 }
752 
753 const char *BuildPreambleErrorCategory::name() const noexcept {
754  return "build-preamble.error";
755 }
756 
757 std::string BuildPreambleErrorCategory::message(int condition) const {
758  switch (static_cast<BuildPreambleError>(condition)) {
760  return "Could not create temporary file for PCH";
762  return "CreateTargetInfo() return null";
764  return "BeginSourceFile() return an error";
766  return "Could not emit PCH";
767  }
768  llvm_unreachable("unexpected BuildPreambleError");
769 }
std::size_t getSize() const
Returns the size, in bytes, that preamble takes on disk or in memory.
Describes the bounds (start, size) of the preamble and a flag required by PreprocessorOptions::Precom...
Definition: Lexer.h:59
Implements support for file system lookup, file system caching, and directory search management...
Definition: FileManager.h:117
__SIZE_TYPE__ size_t
The unsigned integer type of the result of the sizeof operator.
Definition: opencl-c.h:60
time_t getModificationTime() const
Definition: FileManager.h:92
bool CanReuse(const CompilerInvocation &Invocation, const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds, llvm::vfs::FileSystem *VFS) const
Check whether PrecompiledPreamble can be reused for the new contents(MainFileBuffer) of the main file...
An interface for collecting the dependencies of a compilation.
Definition: Utils.h:83
The translation unit is a prefix to a translation unit, and is not complete.
Definition: LangOptions.h:335
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
void addRemappedFile(StringRef From, StringRef To)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:154
void HandleTranslationUnit(ASTContext &Ctx) override
HandleTranslationUnit - This method is called when the ASTs for entire translation unit have been par...
Definition: GeneratePCH.cpp:40
Definition: Format.h:2073
static bool moveOnNoError(llvm::ErrorOr< T > Val, T &Output)
Definition: ASTUnit.cpp:147
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:50
unsigned RelocatablePCH
When generating PCH files, instruct the AST writer to create relocatable PCH files.
static bool ComputeASTConsumerArguments(CompilerInstance &CI, std::string &Sysroot)
Compute the AST consumer arguments that will be used to create the PCHGenerator instance returned by ...
static llvm::ManagedStatic< BuildPreambleErrorCategory > BuildPreambleErrCategory
std::error_code make_error_code(BuildPreambleError Error)
FrontendOptions & getFrontendOpts()
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:149
bool RetainRemappedFileBuffers
Whether the compiler instance should retain (i.e., not free) the buffers associated with remapped fil...
void OverridePreamble(CompilerInvocation &CI, IntrusiveRefCntPtr< llvm::vfs::FileSystem > &VFS, llvm::MemoryBuffer *MainFileBuffer) const
Configure CI to use this preamble.
void Reset()
Reset the state of the diagnostic object to its initial configuration.
Definition: Diagnostic.cpp:114
FrontendOptions & getFrontendOpts()
bool PreambleEndsAtStartOfLine
Whether the preamble ends at the start of a new line.
Definition: Lexer.h:67
A set of callbacks to gather useful information while building a preamble.
return Out str()
StringRef Filename
Definition: Format.cpp:1620
const char * name() const noexcept override
PreambleBounds getBounds() const
PreambleBounds used to build the preamble.
void AddImplicitPreamble(CompilerInvocation &CI, IntrusiveRefCntPtr< llvm::vfs::FileSystem > &VFS, llvm::MemoryBuffer *MainFileBuffer) const
Changes options inside CI to use PCH from this preamble.
static PreambleBounds ComputePreamble(StringRef Buffer, const LangOptions &LangOpts, unsigned MaxLines=0)
Compute the preamble of the given file.
Definition: Lexer.cpp:574
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
static TargetInfo * CreateTargetInfo(DiagnosticsEngine &Diags, const std::shared_ptr< TargetOptions > &Opts)
Construct a target for the given options.
Definition: Targets.cpp:596
bool GeneratePreamble
True indicates that a preamble is being generated.
PreambleBounds ComputePreambleBounds(const LangOptions &LangOpts, llvm::MemoryBuffer *Buffer, unsigned MaxLines)
Runs lexer to compute suggested preamble bounds.
The result type of a method or function.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
StringRef getName() const
Definition: FileManager.h:85
std::string ImplicitPCHInclude
The implicit PCH included at the start of the translation unit, or empty.
LLVM IR: we accept this so that we can run the optimizer on it, and compile it to assembly or object ...
std::vector< FrontendInputFile > Inputs
The input files and their types.
Cached information about one file (either on disk or in the virtual file system). ...
Definition: FileManager.h:60
void ProcessWarningOptions(DiagnosticsEngine &Diags, const DiagnosticOptions &Opts, bool ReportDiags=true)
ProcessWarningOptions - Initialize the diagnostic client and process the warning options specified on...
Definition: Warnings.cpp:44
Abstract base class to use for AST consumer-based frontend actions.
virtual void BeforeExecute(CompilerInstance &CI)
Called before FrontendAction::BeginSourceFile.
virtual void AfterPCHEmitted(ASTWriter &Writer)
Called after PCH has been emitted.
llvm::MemoryBuffer * getMemoryBufferForFile(const FileEntry *File, bool *Invalid=nullptr)
Retrieve the memory buffer associated with the given file.
PrecompiledPreamble(PrecompiledPreamble &&)=default
std::string message(int condition) const override
Dataflow Directional Tag Classes.
A class holding a PCH and all information to check whether it is valid to reuse the PCH for the subse...
PreprocessorOptions & getPreprocessorOpts()
off_t getSize() const
Definition: FileManager.h:88
IntrusiveRefCntPtr< llvm::vfs::FileSystem > createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags)
FileID getMainFileID() const
Returns the FileID of the main source file.
Helper class for holding the data necessary to invoke the compiler.
FrontendOptions - Options for controlling the behavior of the frontend.
virtual void AfterExecute(CompilerInstance &CI)
Called after FrontendAction::Execute(), but before FrontendAction::EndSourceFile().
static llvm::ErrorOr< PrecompiledPreamble > 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)
Try to build PrecompiledPreamble for Invocation.
unsigned Size
Size of the preamble in bytes.
Definition: Lexer.h:61
Generate pre-compiled header.
Preprocessor & getPreprocessor() const
Return the current preprocessor.
TranslationUnitKind
Describes the kind of translation unit being processed.
Definition: LangOptions.h:329
Writes an AST file containing the contents of a translation unit.
Definition: ASTWriter.h:104
std::pair< unsigned, bool > PrecompiledPreambleBytes
If non-zero, the implicit PCH include is actually a precompiled preamble that covers this number of b...
Defines the clang::TargetInfo interface.
__DEVICE__ int max(int __a, int __b)
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:954
An abstract superclass that describes a custom extension to the module/precompiled header file format...
AST and semantic-analysis consumer that generates a precompiled header from the parsed source code...
Definition: ASTWriter.h:968
static std::unique_ptr< llvm::raw_pwrite_stream > CreateOutputFile(CompilerInstance &CI, StringRef InFile, std::string &OutputFile)
Creates file to write the PCH into and returns a stream to write it into.
#define true
Definition: stdbool.h:32
virtual void HandleTopLevelDecl(DeclGroupRef DG)
Called for each TopLevelDecl.
This class handles loading and caching of source files into memory.
virtual std::unique_ptr< PPCallbacks > createPPCallbacks()
Creates wrapper class for PPCallbacks so we can also process information about includes that are insi...
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:127