blob: 385e48a41057e10bcef7a2c1e3250fc941f35e56 [file] [log] [blame]
Ilya Biryukov200b3282017-06-21 10:24:58 +00001//===--- 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
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/Support/CrashRecoveryContext.h"
28#include "llvm/Support/FileSystem.h"
29#include "llvm/Support/Mutex.h"
30#include "llvm/Support/MutexGuard.h"
31
32using namespace clang;
33
34namespace {
35
36/// Keeps a track of files to be deleted in destructor.
37class TemporaryFiles {
38public:
39 // A static instance to be used by all clients.
40 static TemporaryFiles &getInstance();
41
42private:
43 // Disallow constructing the class directly.
44 TemporaryFiles() = default;
45 // Disallow copy.
46 TemporaryFiles(const TemporaryFiles &) = delete;
47
48public:
49 ~TemporaryFiles();
50
51 /// Adds \p File to a set of tracked files.
52 void addFile(StringRef File);
53
54 /// Remove \p File from disk and from the set of tracked files.
55 void removeFile(StringRef File);
56
57private:
58 llvm::sys::SmartMutex<false> Mutex;
59 llvm::StringSet<> Files;
60};
61
62TemporaryFiles &TemporaryFiles::getInstance() {
63 static TemporaryFiles Instance;
64 return Instance;
65}
66
67TemporaryFiles::~TemporaryFiles() {
68 llvm::MutexGuard Guard(Mutex);
69 for (const auto &File : Files)
70 llvm::sys::fs::remove(File.getKey());
71}
72
73void TemporaryFiles::addFile(StringRef File) {
74 llvm::MutexGuard Guard(Mutex);
75 auto IsInserted = Files.insert(File).second;
76 assert(IsInserted && "File has already been added");
77}
78
79void TemporaryFiles::removeFile(StringRef File) {
80 llvm::MutexGuard Guard(Mutex);
81 auto WasPresent = Files.erase(File);
82 assert(WasPresent && "File was not tracked");
83 llvm::sys::fs::remove(File);
84}
85
86class PreambleMacroCallbacks : public PPCallbacks {
87public:
88 PreambleMacroCallbacks(PreambleCallbacks &Callbacks) : Callbacks(Callbacks) {}
89
90 void MacroDefined(const Token &MacroNameTok,
91 const MacroDirective *MD) override {
92 Callbacks.HandleMacroDefined(MacroNameTok, MD);
93 }
94
95private:
96 PreambleCallbacks &Callbacks;
97};
98
99class PrecompilePreambleAction : public ASTFrontendAction {
100public:
101 PrecompilePreambleAction(PreambleCallbacks &Callbacks)
102 : Callbacks(Callbacks) {}
103
104 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
105 StringRef InFile) override;
106
107 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
108
109 void setEmittedPreamblePCH(ASTWriter &Writer) {
110 this->HasEmittedPreamblePCH = true;
111 Callbacks.AfterPCHEmitted(Writer);
112 }
113
114 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
115 bool hasCodeCompletionSupport() const override { return false; }
116 bool hasASTFileSupport() const override { return false; }
117 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
118
119private:
120 friend class PrecompilePreambleConsumer;
121
122 bool HasEmittedPreamblePCH = false;
123 PreambleCallbacks &Callbacks;
124};
125
126class PrecompilePreambleConsumer : public PCHGenerator {
127public:
128 PrecompilePreambleConsumer(PrecompilePreambleAction &Action,
129 const Preprocessor &PP, StringRef isysroot,
130 std::unique_ptr<raw_ostream> Out)
131 : PCHGenerator(PP, "", isysroot, std::make_shared<PCHBuffer>(),
132 ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
133 /*AllowASTWithErrors=*/true),
134 Action(Action), Out(std::move(Out)) {}
135
136 bool HandleTopLevelDecl(DeclGroupRef DG) override {
137 Action.Callbacks.HandleTopLevelDecl(DG);
138 return true;
139 }
140
141 void HandleTranslationUnit(ASTContext &Ctx) override {
142 PCHGenerator::HandleTranslationUnit(Ctx);
143 if (!hasEmittedPCH())
144 return;
145
146 // Write the generated bitstream to "Out".
147 *Out << getPCH();
148 // Make sure it hits disk now.
149 Out->flush();
150 // Free the buffer.
151 llvm::SmallVector<char, 0> Empty;
152 getPCH() = std::move(Empty);
153
154 Action.setEmittedPreamblePCH(getWriter());
155 }
156
157private:
158 PrecompilePreambleAction &Action;
159 std::unique_ptr<raw_ostream> Out;
160};
161
162std::unique_ptr<ASTConsumer>
163PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
164
165 StringRef InFile) {
166 std::string Sysroot;
167 std::string OutputFile;
168 std::unique_ptr<raw_ostream> OS =
169 GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
170 OutputFile);
171 if (!OS)
172 return nullptr;
173
174 if (!CI.getFrontendOpts().RelocatablePCH)
175 Sysroot.clear();
176
177 CI.getPreprocessor().addPPCallbacks(
178 llvm::make_unique<PreambleMacroCallbacks>(Callbacks));
179 return llvm::make_unique<PrecompilePreambleConsumer>(
180 *this, CI.getPreprocessor(), Sysroot, std::move(OS));
181}
182
183template <class T> bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
184 if (!Val)
185 return false;
186 Output = std::move(*Val);
187 return true;
188}
189
190} // namespace
191
192PreambleBounds clang::ComputePreambleBounds(const LangOptions &LangOpts,
193 llvm::MemoryBuffer *Buffer,
194 unsigned MaxLines) {
195 auto Pre = Lexer::ComputePreamble(Buffer->getBuffer(), LangOpts, MaxLines);
196 return PreambleBounds(Pre.first, Pre.second);
197}
198
199llvm::ErrorOr<PrecompiledPreamble> PrecompiledPreamble::Build(
200 const CompilerInvocation &Invocation,
201 const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds,
202 DiagnosticsEngine &Diagnostics, IntrusiveRefCntPtr<vfs::FileSystem> VFS,
203 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
204 PreambleCallbacks &Callbacks) {
205 assert(VFS && "VFS is null");
206
207 if (!Bounds.Size)
208 return BuildPreambleError::PreambleIsEmpty;
209
210 auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
211 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
212 PreprocessorOptions &PreprocessorOpts =
213 PreambleInvocation->getPreprocessorOpts();
214
215 // Create a temporary file for the precompiled preamble. In rare
216 // circumstances, this can fail.
217 llvm::ErrorOr<PrecompiledPreamble::TempPCHFile> PreamblePCHFile =
218 PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile();
219 if (!PreamblePCHFile)
220 return BuildPreambleError::CouldntCreateTempFile;
221
222 // Save the preamble text for later; we'll need to compare against it for
223 // subsequent reparses.
224 std::vector<char> PreambleBytes(MainFileBuffer->getBufferStart(),
225 MainFileBuffer->getBufferStart() +
226 Bounds.Size);
227 bool PreambleEndsAtStartOfLine = Bounds.PreambleEndsAtStartOfLine;
228
229 // Tell the compiler invocation to generate a temporary precompiled header.
230 FrontendOpts.ProgramAction = frontend::GeneratePCH;
231 // FIXME: Generate the precompiled header into memory?
232 FrontendOpts.OutputFile = PreamblePCHFile->getFilePath();
233 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
234 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
235
236 // Create the compiler instance to use for building the precompiled preamble.
237 std::unique_ptr<CompilerInstance> Clang(
238 new CompilerInstance(std::move(PCHContainerOps)));
239
240 // Recover resources if we crash before exiting this method.
241 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
242 Clang.get());
243
244 Clang->setInvocation(std::move(PreambleInvocation));
245 Clang->setDiagnostics(&Diagnostics);
246
247 // Create the target instance.
248 Clang->setTarget(TargetInfo::CreateTargetInfo(
249 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
250 if (!Clang->hasTarget())
251 return BuildPreambleError::CouldntCreateTargetInfo;
252
253 // Inform the target of the language options.
254 //
255 // FIXME: We shouldn't need to do this, the target should be immutable once
256 // created. This complexity should be lifted elsewhere.
257 Clang->getTarget().adjust(Clang->getLangOpts());
258
259 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
260 "Invocation must have exactly one source file!");
261 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
262 InputKind::Source &&
263 "FIXME: AST inputs not yet supported here!");
264 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
265 InputKind::LLVM_IR &&
266 "IR inputs not support here!");
267
268 // Clear out old caches and data.
269 Diagnostics.Reset();
270 ProcessWarningOptions(Diagnostics, Clang->getDiagnosticOpts());
271
272 VFS =
273 createVFSFromCompilerInvocation(Clang->getInvocation(), Diagnostics, VFS);
274 if (!VFS)
275 return BuildPreambleError::CouldntCreateVFSOverlay;
276
277 // Create a file manager object to provide access to and cache the filesystem.
278 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
279
280 // Create the source manager.
281 Clang->setSourceManager(
282 new SourceManager(Diagnostics, Clang->getFileManager()));
283
284 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
285 Clang->addDependencyCollector(PreambleDepCollector);
286
287 // Remap the main source file to the preamble buffer.
288 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
289 auto PreambleInputBuffer = llvm::MemoryBuffer::getMemBufferCopy(
290 MainFileBuffer->getBuffer().slice(0, Bounds.Size), MainFilePath);
291 if (PreprocessorOpts.RetainRemappedFileBuffers) {
292 // MainFileBuffer will be deleted by unique_ptr after leaving the method.
293 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleInputBuffer.get());
294 } else {
295 // In that case, remapped buffer will be deleted by CompilerInstance on
296 // BeginSourceFile, so we call release() to avoid double deletion.
297 PreprocessorOpts.addRemappedFile(MainFilePath,
298 PreambleInputBuffer.release());
299 }
300
301 std::unique_ptr<PrecompilePreambleAction> Act;
302 Act.reset(new PrecompilePreambleAction(Callbacks));
303 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
304 return BuildPreambleError::BeginSourceFileFailed;
305
306 Act->Execute();
307
308 // Run the callbacks.
309 Callbacks.AfterExecute(*Clang);
310
311 Act->EndSourceFile();
312
313 if (!Act->hasEmittedPreamblePCH())
314 return BuildPreambleError::CouldntEmitPCH;
315
316 // Keep track of all of the files that the source manager knows about,
317 // so we can verify whether they have changed or not.
318 llvm::StringMap<PrecompiledPreamble::PreambleFileHash> FilesInPreamble;
319
320 SourceManager &SourceMgr = Clang->getSourceManager();
321 for (auto &Filename : PreambleDepCollector->getDependencies()) {
322 const FileEntry *File = Clang->getFileManager().getFile(Filename);
323 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
324 continue;
325 if (time_t ModTime = File->getModificationTime()) {
326 FilesInPreamble[File->getName()] =
327 PrecompiledPreamble::PreambleFileHash::createForFile(File->getSize(),
328 ModTime);
329 } else {
330 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
331 FilesInPreamble[File->getName()] =
332 PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(Buffer);
333 }
334 }
335
336 return PrecompiledPreamble(
337 std::move(*PreamblePCHFile), std::move(PreambleBytes),
338 PreambleEndsAtStartOfLine, std::move(FilesInPreamble));
339}
340
341PreambleBounds PrecompiledPreamble::getBounds() const {
342 return PreambleBounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
343}
344
345bool PrecompiledPreamble::CanReuse(const CompilerInvocation &Invocation,
346 const llvm::MemoryBuffer *MainFileBuffer,
347 PreambleBounds Bounds,
348 vfs::FileSystem *VFS) const {
349
350 assert(
351 Bounds.Size <= MainFileBuffer->getBufferSize() &&
352 "Buffer is too large. Bounds were calculated from a different buffer?");
353
354 auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
355 PreprocessorOptions &PreprocessorOpts =
356 PreambleInvocation->getPreprocessorOpts();
357
358 if (!Bounds.Size)
359 return false;
360
361 // We've previously computed a preamble. Check whether we have the same
362 // preamble now that we did before, and that there's enough space in
363 // the main-file buffer within the precompiled preamble to fit the
364 // new main file.
365 if (PreambleBytes.size() != Bounds.Size ||
366 PreambleEndsAtStartOfLine != Bounds.PreambleEndsAtStartOfLine ||
367 memcmp(PreambleBytes.data(), MainFileBuffer->getBufferStart(),
368 Bounds.Size) != 0)
369 return false;
370 // The preamble has not changed. We may be able to re-use the precompiled
371 // preamble.
372
373 // Check that none of the files used by the preamble have changed.
374 // First, make a record of those files that have been overridden via
375 // remapping or unsaved_files.
376 std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
377 for (const auto &R : PreprocessorOpts.RemappedFiles) {
378 vfs::Status Status;
379 if (!moveOnNoError(VFS->status(R.second), Status)) {
380 // If we can't stat the file we're remapping to, assume that something
381 // horrible happened.
382 return false;
383 }
384
385 OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
386 Status.getSize(), llvm::sys::toTimeT(Status.getLastModificationTime()));
387 }
388
389 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
390 vfs::Status Status;
391 if (!moveOnNoError(VFS->status(RB.first), Status))
392 return false;
393
394 OverriddenFiles[Status.getUniqueID()] =
395 PreambleFileHash::createForMemoryBuffer(RB.second);
396 }
397
398 // Check whether anything has changed.
399 for (const auto &F : FilesInPreamble) {
400 vfs::Status Status;
401 if (!moveOnNoError(VFS->status(F.first()), Status)) {
402 // If we can't stat the file, assume that something horrible happened.
403 return false;
404 }
405
406 std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden =
407 OverriddenFiles.find(Status.getUniqueID());
408 if (Overridden != OverriddenFiles.end()) {
409 // This file was remapped; check whether the newly-mapped file
410 // matches up with the previous mapping.
411 if (Overridden->second != F.second)
412 return false;
413 continue;
414 }
415
416 // The file was not remapped; check whether it has changed on disk.
417 if (Status.getSize() != uint64_t(F.second.Size) ||
418 llvm::sys::toTimeT(Status.getLastModificationTime()) !=
419 F.second.ModTime)
420 return false;
421 }
422 return true;
423}
424
425void PrecompiledPreamble::AddImplicitPreamble(
426 CompilerInvocation &CI, llvm::MemoryBuffer *MainFileBuffer) const {
427 auto &PreprocessorOpts = CI.getPreprocessorOpts();
428
429 // Configure ImpicitPCHInclude.
430 PreprocessorOpts.PrecompiledPreambleBytes.first = PreambleBytes.size();
431 PreprocessorOpts.PrecompiledPreambleBytes.second = PreambleEndsAtStartOfLine;
432 PreprocessorOpts.ImplicitPCHInclude = PCHFile.getFilePath();
433 PreprocessorOpts.DisablePCHValidation = true;
434
435 // Remap main file to point to MainFileBuffer.
436 auto MainFilePath = CI.getFrontendOpts().Inputs[0].getFile();
437 PreprocessorOpts.addRemappedFile(MainFilePath, MainFileBuffer);
438}
439
440PrecompiledPreamble::PrecompiledPreamble(
441 TempPCHFile PCHFile, std::vector<char> PreambleBytes,
442 bool PreambleEndsAtStartOfLine,
443 llvm::StringMap<PreambleFileHash> FilesInPreamble)
444 : PCHFile(std::move(PCHFile)), FilesInPreamble(FilesInPreamble),
445 PreambleBytes(std::move(PreambleBytes)),
446 PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {}
447
448llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
449PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile() {
450 // FIXME: This is a hack so that we can override the preamble file during
451 // crash-recovery testing, which is the only case where the preamble files
452 // are not necessarily cleaned up.
453 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
454 if (TmpFile)
455 return TempPCHFile::createFromCustomPath(TmpFile);
456 return TempPCHFile::createInSystemTempDir("preamble", "pch");
457}
458
459llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
460PrecompiledPreamble::TempPCHFile::createInSystemTempDir(const Twine &Prefix,
461 StringRef Suffix) {
462 llvm::SmallString<64> File;
463 auto EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, /*ref*/ File);
464 if (EC)
465 return EC;
466 return TempPCHFile(std::move(File).str());
467}
468
469llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
470PrecompiledPreamble::TempPCHFile::createFromCustomPath(const Twine &Path) {
471 return TempPCHFile(Path.str());
472}
473
474PrecompiledPreamble::TempPCHFile::TempPCHFile(std::string FilePath)
475 : FilePath(std::move(FilePath)) {
476 TemporaryFiles::getInstance().addFile(*this->FilePath);
477}
478
479PrecompiledPreamble::TempPCHFile::TempPCHFile(TempPCHFile &&Other) {
480 FilePath = std::move(Other.FilePath);
481 Other.FilePath = None;
482}
483
484PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::TempPCHFile::
485operator=(TempPCHFile &&Other) {
486 RemoveFileIfPresent();
487
488 FilePath = std::move(Other.FilePath);
489 Other.FilePath = None;
490 return *this;
491}
492
493PrecompiledPreamble::TempPCHFile::~TempPCHFile() { RemoveFileIfPresent(); }
494
495void PrecompiledPreamble::TempPCHFile::RemoveFileIfPresent() {
496 if (FilePath) {
497 TemporaryFiles::getInstance().removeFile(*FilePath);
498 FilePath = None;
499 }
500}
501
502llvm::StringRef PrecompiledPreamble::TempPCHFile::getFilePath() const {
503 assert(FilePath && "TempPCHFile doesn't have a FilePath. Had it been moved?");
504 return *FilePath;
505}
506
507PrecompiledPreamble::PreambleFileHash
508PrecompiledPreamble::PreambleFileHash::createForFile(off_t Size,
509 time_t ModTime) {
510 PreambleFileHash Result;
511 Result.Size = Size;
512 Result.ModTime = ModTime;
513 Result.MD5 = {};
514 return Result;
515}
516
517PrecompiledPreamble::PreambleFileHash
518PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(
519 const llvm::MemoryBuffer *Buffer) {
520 PreambleFileHash Result;
521 Result.Size = Buffer->getBufferSize();
522 Result.ModTime = 0;
523
524 llvm::MD5 MD5Ctx;
525 MD5Ctx.update(Buffer->getBuffer().data());
526 MD5Ctx.final(Result.MD5);
527
528 return Result;
529}
530
531void PreambleCallbacks::AfterExecute(CompilerInstance &CI) {}
532void PreambleCallbacks::AfterPCHEmitted(ASTWriter &Writer) {}
533void PreambleCallbacks::HandleTopLevelDecl(DeclGroupRef DG) {}
534void PreambleCallbacks::HandleMacroDefined(const Token &MacroNameTok,
535 const MacroDirective *MD) {}
536
537std::error_code clang::make_error_code(BuildPreambleError Error) {
538 return std::error_code(static_cast<int>(Error), BuildPreambleErrorCategory());
539}
540
541const char *BuildPreambleErrorCategory::name() const noexcept {
542 return "build-preamble.error";
543}
544
545std::string BuildPreambleErrorCategory::message(int condition) const {
546 switch (static_cast<BuildPreambleError>(condition)) {
547 case BuildPreambleError::PreambleIsEmpty:
548 return "Preamble is empty";
549 case BuildPreambleError::CouldntCreateTempFile:
550 return "Could not create temporary file for PCH";
551 case BuildPreambleError::CouldntCreateTargetInfo:
552 return "CreateTargetInfo() return null";
553 case BuildPreambleError::CouldntCreateVFSOverlay:
554 return "Could not create VFS Overlay";
555 case BuildPreambleError::BeginSourceFileFailed:
556 return "BeginSourceFile() return an error";
557 case BuildPreambleError::CouldntEmitPCH:
558 return "Could not emit PCH";
559 }
560 llvm_unreachable("unexpected BuildPreambleError");
561}