blob: d3eaa92d4c1ac4ec9f60c6c03dbe4a89787e4b92 [file] [log] [blame]
Sam McCallcf3a5852019-09-04 07:35:00 +00001//===--- Preamble.cpp - Reusing expensive parts of the AST ----------------===//
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#include "Preamble.h"
Kadir Cetinkayaecd3e672020-03-11 16:34:01 +010010#include "Compiler.h"
Kadir Cetinkaya2214b902020-04-02 10:53:23 +020011#include "Headers.h"
Kadir Cetinkaya717bef62020-04-23 17:44:51 +020012#include "SourceCode.h"
Sam McCallad97ccf2020-04-28 17:49:17 +020013#include "support/Logger.h"
14#include "support/Trace.h"
Kadir Cetinkaya2214b902020-04-02 10:53:23 +020015#include "clang/Basic/Diagnostic.h"
16#include "clang/Basic/LangOptions.h"
Sam McCallcf3a5852019-09-04 07:35:00 +000017#include "clang/Basic/SourceLocation.h"
Kadir Cetinkaya2214b902020-04-02 10:53:23 +020018#include "clang/Basic/TokenKinds.h"
19#include "clang/Frontend/CompilerInvocation.h"
20#include "clang/Frontend/FrontendActions.h"
21#include "clang/Lex/Lexer.h"
Sam McCallcf3a5852019-09-04 07:35:00 +000022#include "clang/Lex/PPCallbacks.h"
Kadir Cetinkaya2214b902020-04-02 10:53:23 +020023#include "clang/Lex/Preprocessor.h"
Sam McCallcf3a5852019-09-04 07:35:00 +000024#include "clang/Lex/PreprocessorOptions.h"
Kadir Cetinkaya2214b902020-04-02 10:53:23 +020025#include "clang/Tooling/CompilationDatabase.h"
26#include "llvm/ADT/ArrayRef.h"
27#include "llvm/ADT/IntrusiveRefCntPtr.h"
28#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/SmallString.h"
Kadir Cetinkaya717bef62020-04-23 17:44:51 +020030#include "llvm/ADT/StringExtras.h"
Kadir Cetinkaya2214b902020-04-02 10:53:23 +020031#include "llvm/ADT/StringRef.h"
32#include "llvm/ADT/StringSet.h"
33#include "llvm/Support/Error.h"
34#include "llvm/Support/ErrorHandling.h"
35#include "llvm/Support/FormatVariadic.h"
36#include "llvm/Support/MemoryBuffer.h"
37#include "llvm/Support/Path.h"
38#include "llvm/Support/VirtualFileSystem.h"
39#include "llvm/Support/raw_ostream.h"
40#include <iterator>
41#include <memory>
42#include <string>
43#include <system_error>
44#include <utility>
45#include <vector>
Sam McCallcf3a5852019-09-04 07:35:00 +000046
47namespace clang {
48namespace clangd {
49namespace {
50
51bool compileCommandsAreEqual(const tooling::CompileCommand &LHS,
52 const tooling::CompileCommand &RHS) {
53 // We don't check for Output, it should not matter to clangd.
54 return LHS.Directory == RHS.Directory && LHS.Filename == RHS.Filename &&
55 llvm::makeArrayRef(LHS.CommandLine).equals(RHS.CommandLine);
56}
57
Sam McCallcf3a5852019-09-04 07:35:00 +000058class CppFilePreambleCallbacks : public PreambleCallbacks {
59public:
60 CppFilePreambleCallbacks(PathRef File, PreambleParsedCallback ParsedCallback)
Haojian Wu7e3c74b2019-09-24 11:14:06 +000061 : File(File), ParsedCallback(ParsedCallback) {}
Sam McCallcf3a5852019-09-04 07:35:00 +000062
63 IncludeStructure takeIncludes() { return std::move(Includes); }
64
Haojian Wu7e3c74b2019-09-24 11:14:06 +000065 MainFileMacros takeMacros() { return std::move(Macros); }
Sam McCallcf3a5852019-09-04 07:35:00 +000066
67 CanonicalIncludes takeCanonicalIncludes() { return std::move(CanonIncludes); }
68
69 void AfterExecute(CompilerInstance &CI) override {
70 if (!ParsedCallback)
71 return;
72 trace::Span Tracer("Running PreambleCallback");
73 ParsedCallback(CI.getASTContext(), CI.getPreprocessorPtr(), CanonIncludes);
74 }
75
76 void BeforeExecute(CompilerInstance &CI) override {
Ilya Biryukov8b767092019-09-09 15:32:51 +000077 CanonIncludes.addSystemHeadersMapping(CI.getLangOpts());
Haojian Wu7e3c74b2019-09-24 11:14:06 +000078 LangOpts = &CI.getLangOpts();
Sam McCallcf3a5852019-09-04 07:35:00 +000079 SourceMgr = &CI.getSourceManager();
80 }
81
82 std::unique_ptr<PPCallbacks> createPPCallbacks() override {
Haojian Wu7e3c74b2019-09-24 11:14:06 +000083 assert(SourceMgr && LangOpts &&
84 "SourceMgr and LangOpts must be set at this point");
85
Sam McCallcf3a5852019-09-04 07:35:00 +000086 return std::make_unique<PPChainedCallbacks>(
87 collectIncludeStructureCallback(*SourceMgr, &Includes),
Kadir Cetinkaya37550392020-03-01 16:05:12 +010088 std::make_unique<CollectMainFileMacros>(*SourceMgr, Macros));
Sam McCallcf3a5852019-09-04 07:35:00 +000089 }
90
91 CommentHandler *getCommentHandler() override {
92 IWYUHandler = collectIWYUHeaderMaps(&CanonIncludes);
93 return IWYUHandler.get();
94 }
95
96private:
97 PathRef File;
98 PreambleParsedCallback ParsedCallback;
99 IncludeStructure Includes;
100 CanonicalIncludes CanonIncludes;
Haojian Wu7e3c74b2019-09-24 11:14:06 +0000101 MainFileMacros Macros;
Sam McCallcf3a5852019-09-04 07:35:00 +0000102 std::unique_ptr<CommentHandler> IWYUHandler = nullptr;
Haojian Wu7e3c74b2019-09-24 11:14:06 +0000103 const clang::LangOptions *LangOpts = nullptr;
104 const SourceManager *SourceMgr = nullptr;
Sam McCallcf3a5852019-09-04 07:35:00 +0000105};
106
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200107/// Gets the includes in the preamble section of the file by running
108/// preprocessor over \p Contents. Returned includes do not contain resolved
109/// paths. \p VFS and \p Cmd is used to build the compiler invocation, which
110/// might stat/read files.
111llvm::Expected<std::vector<Inclusion>>
112scanPreambleIncludes(llvm::StringRef Contents,
113 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
114 const tooling::CompileCommand &Cmd) {
115 // Build and run Preprocessor over the preamble.
116 ParseInputs PI;
117 PI.Contents = Contents.str();
118 PI.FS = std::move(VFS);
119 PI.CompileCommand = Cmd;
120 IgnoringDiagConsumer IgnoreDiags;
121 auto CI = buildCompilerInvocation(PI, IgnoreDiags);
122 if (!CI)
123 return llvm::createStringError(llvm::inconvertibleErrorCode(),
124 "failed to create compiler invocation");
125 CI->getDiagnosticOpts().IgnoreWarnings = true;
126 auto ContentsBuffer = llvm::MemoryBuffer::getMemBuffer(Contents);
Kadir Cetinkaya34e39eb2020-05-05 17:55:11 +0200127 // This means we're scanning (though not preprocessing) the preamble section
128 // twice. However, it's important to precisely follow the preamble bounds used
129 // elsewhere.
130 auto Bounds =
131 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
132 auto PreambleContents =
133 llvm::MemoryBuffer::getMemBufferCopy(Contents.substr(0, Bounds.Size));
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200134 auto Clang = prepareCompilerInstance(
Kadir Cetinkaya34e39eb2020-05-05 17:55:11 +0200135 std::move(CI), nullptr, std::move(PreambleContents),
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200136 // Provide an empty FS to prevent preprocessor from performing IO. This
137 // also implies missing resolved paths for includes.
138 new llvm::vfs::InMemoryFileSystem, IgnoreDiags);
139 if (Clang->getFrontendOpts().Inputs.empty())
140 return llvm::createStringError(llvm::inconvertibleErrorCode(),
141 "compiler instance had no inputs");
142 // We are only interested in main file includes.
143 Clang->getPreprocessorOpts().SingleFileParseMode = true;
Kadir Cetinkaya34e39eb2020-05-05 17:55:11 +0200144 PreprocessOnlyAction Action;
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200145 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0]))
146 return llvm::createStringError(llvm::inconvertibleErrorCode(),
147 "failed BeginSourceFile");
148 Preprocessor &PP = Clang->getPreprocessor();
149 IncludeStructure Includes;
150 PP.addPPCallbacks(
151 collectIncludeStructureCallback(Clang->getSourceManager(), &Includes));
152 if (llvm::Error Err = Action.Execute())
153 return std::move(Err);
154 Action.EndSourceFile();
155 return Includes.MainFileIncludes;
156}
157
158const char *spellingForIncDirective(tok::PPKeywordKind IncludeDirective) {
159 switch (IncludeDirective) {
160 case tok::pp_include:
161 return "include";
162 case tok::pp_import:
163 return "import";
164 case tok::pp_include_next:
165 return "include_next";
166 default:
167 break;
168 }
169 llvm_unreachable("not an include directive");
170}
Sam McCallcf3a5852019-09-04 07:35:00 +0000171} // namespace
172
Kadir Cetinkayaecd3e672020-03-11 16:34:01 +0100173PreambleData::PreambleData(const ParseInputs &Inputs,
Sam McCall2cd33e62020-03-04 00:33:29 +0100174 PrecompiledPreamble Preamble,
Sam McCallcf3a5852019-09-04 07:35:00 +0000175 std::vector<Diag> Diags, IncludeStructure Includes,
Haojian Wu7e3c74b2019-09-24 11:14:06 +0000176 MainFileMacros Macros,
Sam McCallcf3a5852019-09-04 07:35:00 +0000177 std::unique_ptr<PreambleFileStatusCache> StatCache,
178 CanonicalIncludes CanonIncludes)
Kadir Cetinkayaecd3e672020-03-11 16:34:01 +0100179 : Version(Inputs.Version), CompileCommand(Inputs.CompileCommand),
180 Preamble(std::move(Preamble)), Diags(std::move(Diags)),
Haojian Wu7e3c74b2019-09-24 11:14:06 +0000181 Includes(std::move(Includes)), Macros(std::move(Macros)),
Sam McCallcf3a5852019-09-04 07:35:00 +0000182 StatCache(std::move(StatCache)), CanonIncludes(std::move(CanonIncludes)) {
183}
184
185std::shared_ptr<const PreambleData>
Kadir Cetinkaya276a95b2020-03-13 11:52:19 +0100186buildPreamble(PathRef FileName, CompilerInvocation CI,
Sam McCallcf3a5852019-09-04 07:35:00 +0000187 const ParseInputs &Inputs, bool StoreInMemory,
188 PreambleParsedCallback PreambleCallback) {
189 // Note that we don't need to copy the input contents, preamble can live
190 // without those.
191 auto ContentsBuffer =
192 llvm::MemoryBuffer::getMemBuffer(Inputs.Contents, FileName);
193 auto Bounds =
194 ComputePreambleBounds(*CI.getLangOpts(), ContentsBuffer.get(), 0);
195
Sam McCallcf3a5852019-09-04 07:35:00 +0000196 trace::Span Tracer("BuildPreamble");
197 SPAN_ATTACH(Tracer, "File", FileName);
198 StoreDiags PreambleDiagnostics;
199 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
200 CompilerInstance::createDiagnostics(&CI.getDiagnosticOpts(),
201 &PreambleDiagnostics, false);
202
203 // Skip function bodies when building the preamble to speed up building
204 // the preamble and make it smaller.
205 assert(!CI.getFrontendOpts().SkipFunctionBodies);
206 CI.getFrontendOpts().SkipFunctionBodies = true;
207 // We don't want to write comment locations into PCH. They are racy and slow
208 // to read back. We rely on dynamic index for the comments instead.
209 CI.getPreprocessorOpts().WriteCommentListToPCH = false;
210
211 CppFilePreambleCallbacks SerializedDeclsCollector(FileName, PreambleCallback);
212 if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
213 log("Couldn't set working directory when building the preamble.");
214 // We proceed anyway, our lit-tests rely on results for non-existing working
215 // dirs.
216 }
217
218 llvm::SmallString<32> AbsFileName(FileName);
219 Inputs.FS->makeAbsolute(AbsFileName);
220 auto StatCache = std::make_unique<PreambleFileStatusCache>(AbsFileName);
221 auto BuiltPreamble = PrecompiledPreamble::Build(
222 CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine,
223 StatCache->getProducingFS(Inputs.FS),
224 std::make_shared<PCHContainerOperations>(), StoreInMemory,
225 SerializedDeclsCollector);
226
227 // When building the AST for the main file, we do want the function
228 // bodies.
229 CI.getFrontendOpts().SkipFunctionBodies = false;
230
231 if (BuiltPreamble) {
Sam McCall2cd33e62020-03-04 00:33:29 +0100232 vlog("Built preamble of size {0} for file {1} version {2}",
233 BuiltPreamble->getSize(), FileName, Inputs.Version);
Sam McCallcf3a5852019-09-04 07:35:00 +0000234 std::vector<Diag> Diags = PreambleDiagnostics.take();
235 return std::make_shared<PreambleData>(
Kadir Cetinkayaecd3e672020-03-11 16:34:01 +0100236 Inputs, std::move(*BuiltPreamble), std::move(Diags),
Sam McCallcf3a5852019-09-04 07:35:00 +0000237 SerializedDeclsCollector.takeIncludes(),
Haojian Wu7e3c74b2019-09-24 11:14:06 +0000238 SerializedDeclsCollector.takeMacros(), std::move(StatCache),
Sam McCallcf3a5852019-09-04 07:35:00 +0000239 SerializedDeclsCollector.takeCanonicalIncludes());
240 } else {
Adam Czachorowski55b92dc2020-03-19 15:09:28 +0100241 elog("Could not build a preamble for file {0} version {1}", FileName,
Sam McCall2cd33e62020-03-04 00:33:29 +0100242 Inputs.Version);
Sam McCallcf3a5852019-09-04 07:35:00 +0000243 return nullptr;
244 }
245}
246
Kadir Cetinkayac31367e2020-03-15 21:43:00 +0100247bool isPreambleCompatible(const PreambleData &Preamble,
248 const ParseInputs &Inputs, PathRef FileName,
249 const CompilerInvocation &CI) {
250 auto ContentsBuffer =
251 llvm::MemoryBuffer::getMemBuffer(Inputs.Contents, FileName);
252 auto Bounds =
253 ComputePreambleBounds(*CI.getLangOpts(), ContentsBuffer.get(), 0);
254 return compileCommandsAreEqual(Inputs.CompileCommand,
255 Preamble.CompileCommand) &&
256 Preamble.Preamble.CanReuse(CI, ContentsBuffer.get(), Bounds,
257 Inputs.FS.get());
258}
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200259
Kadir Cetinkaya717bef62020-04-23 17:44:51 +0200260void escapeBackslashAndQuotes(llvm::StringRef Text, llvm::raw_ostream &OS) {
261 for (char C : Text) {
262 switch (C) {
263 case '\\':
264 case '"':
265 OS << '\\';
266 break;
267 default:
268 break;
269 }
270 OS << C;
271 }
272}
273
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200274PreamblePatch PreamblePatch::create(llvm::StringRef FileName,
275 const ParseInputs &Modified,
276 const PreambleData &Baseline) {
277 // First scan the include directives in Baseline and Modified. These will be
278 // used to figure out newly added directives in Modified. Scanning can fail,
279 // the code just bails out and creates an empty patch in such cases, as:
280 // - If scanning for Baseline fails, no knowledge of existing includes hence
281 // patch will contain all the includes in Modified. Leading to rebuild of
282 // whole preamble, which is terribly slow.
283 // - If scanning for Modified fails, cannot figure out newly added ones so
284 // there's nothing to do but generate an empty patch.
285 auto BaselineIncludes = scanPreambleIncludes(
286 // Contents needs to be null-terminated.
287 Baseline.Preamble.getContents().str(),
288 Baseline.StatCache->getConsumingFS(Modified.FS), Modified.CompileCommand);
289 if (!BaselineIncludes) {
290 elog("Failed to scan includes for baseline of {0}: {1}", FileName,
291 BaselineIncludes.takeError());
292 return {};
293 }
294 auto ModifiedIncludes = scanPreambleIncludes(
295 Modified.Contents, Baseline.StatCache->getConsumingFS(Modified.FS),
296 Modified.CompileCommand);
297 if (!ModifiedIncludes) {
298 elog("Failed to scan includes for modified contents of {0}: {1}", FileName,
299 ModifiedIncludes.takeError());
300 return {};
301 }
Kadir Cetinkaya717bef62020-04-23 17:44:51 +0200302 // No patch needed if includes are equal.
303 if (*BaselineIncludes == *ModifiedIncludes)
304 return {};
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200305
306 PreamblePatch PP;
307 // This shouldn't coincide with any real file name.
308 llvm::SmallString<128> PatchName;
309 llvm::sys::path::append(PatchName, llvm::sys::path::parent_path(FileName),
310 "__preamble_patch__.h");
311 PP.PatchFileName = PatchName.str().str();
312
313 // We are only interested in newly added includes, record the ones in Baseline
314 // for exclusion.
315 llvm::DenseSet<std::pair<tok::PPKeywordKind, llvm::StringRef>>
316 ExistingIncludes;
317 for (const auto &Inc : *BaselineIncludes)
318 ExistingIncludes.insert({Inc.Directive, Inc.Written});
319 // Calculate extra includes that needs to be inserted.
320 llvm::raw_string_ostream Patch(PP.PatchContents);
Kadir Cetinkaya717bef62020-04-23 17:44:51 +0200321 // Set default filename for subsequent #line directives
322 Patch << "#line 0 \"";
323 // FileName part of a line directive is subject to backslash escaping, which
324 // might lead to problems on windows especially.
325 escapeBackslashAndQuotes(FileName, Patch);
326 Patch << "\"\n";
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200327 for (const auto &Inc : *ModifiedIncludes) {
328 if (ExistingIncludes.count({Inc.Directive, Inc.Written}))
329 continue;
Kadir Cetinkaya717bef62020-04-23 17:44:51 +0200330 // Include is new in the modified preamble. Inject it into the patch and use
331 // #line to set the presumed location to where it is spelled.
332 auto LineCol = offsetToClangLineColumn(Modified.Contents, Inc.HashOffset);
333 Patch << llvm::formatv("#line {0}\n", LineCol.first);
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200334 Patch << llvm::formatv("#{0} {1}\n", spellingForIncDirective(Inc.Directive),
335 Inc.Written);
336 }
337 Patch.flush();
338
339 // FIXME: Handle more directives, e.g. define/undef.
340 return PP;
341}
342
343void PreamblePatch::apply(CompilerInvocation &CI) const {
344 // No need to map an empty file.
345 if (PatchContents.empty())
346 return;
347 auto &PPOpts = CI.getPreprocessorOpts();
348 auto PatchBuffer =
349 // we copy here to ensure contents are still valid if CI outlives the
350 // PreamblePatch.
351 llvm::MemoryBuffer::getMemBufferCopy(PatchContents, PatchFileName);
352 // CI will take care of the lifetime of the buffer.
353 PPOpts.addRemappedFile(PatchFileName, PatchBuffer.release());
354 // The patch will be parsed after loading the preamble ast and before parsing
355 // the main file.
356 PPOpts.Includes.push_back(PatchFileName);
357}
358
Sam McCallcf3a5852019-09-04 07:35:00 +0000359} // namespace clangd
360} // namespace clang