PrecompiledPreamble.cpp 32 KB

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