blob: 8652f350a07e1c4e9e8ceedf1d86d6eb7781b382 [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"
Kadir Cetinkaya06287052020-06-17 11:53:32 +020014#include "support/ThreadsafeFS.h"
Sam McCallad97ccf2020-04-28 17:49:17 +020015#include "support/Trace.h"
Sam McCall4160f4c2020-06-09 15:46:35 +020016#include "clang/AST/DeclTemplate.h"
Kadir Cetinkaya2214b902020-04-02 10:53:23 +020017#include "clang/Basic/Diagnostic.h"
18#include "clang/Basic/LangOptions.h"
Sam McCallcf3a5852019-09-04 07:35:00 +000019#include "clang/Basic/SourceLocation.h"
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +020020#include "clang/Basic/SourceManager.h"
Kadir Cetinkaya2214b902020-04-02 10:53:23 +020021#include "clang/Basic/TokenKinds.h"
22#include "clang/Frontend/CompilerInvocation.h"
23#include "clang/Frontend/FrontendActions.h"
24#include "clang/Lex/Lexer.h"
Sam McCallcf3a5852019-09-04 07:35:00 +000025#include "clang/Lex/PPCallbacks.h"
Kadir Cetinkaya2214b902020-04-02 10:53:23 +020026#include "clang/Lex/Preprocessor.h"
Sam McCallcf3a5852019-09-04 07:35:00 +000027#include "clang/Lex/PreprocessorOptions.h"
Kadir Cetinkaya2214b902020-04-02 10:53:23 +020028#include "clang/Tooling/CompilationDatabase.h"
29#include "llvm/ADT/ArrayRef.h"
Kadir Cetinkayab742eaa2020-04-02 10:53:45 +020030#include "llvm/ADT/DenseMap.h"
31#include "llvm/ADT/DenseSet.h"
Kadir Cetinkaya2214b902020-04-02 10:53:23 +020032#include "llvm/ADT/IntrusiveRefCntPtr.h"
Kadir Cetinkaya2dc2e472020-06-16 12:16:24 +020033#include "llvm/ADT/None.h"
34#include "llvm/ADT/Optional.h"
Kadir Cetinkaya2214b902020-04-02 10:53:23 +020035#include "llvm/ADT/STLExtras.h"
36#include "llvm/ADT/SmallString.h"
Kadir Cetinkaya717bef62020-04-23 17:44:51 +020037#include "llvm/ADT/StringExtras.h"
Kadir Cetinkaya2214b902020-04-02 10:53:23 +020038#include "llvm/ADT/StringRef.h"
39#include "llvm/ADT/StringSet.h"
40#include "llvm/Support/Error.h"
41#include "llvm/Support/ErrorHandling.h"
42#include "llvm/Support/FormatVariadic.h"
43#include "llvm/Support/MemoryBuffer.h"
44#include "llvm/Support/Path.h"
45#include "llvm/Support/VirtualFileSystem.h"
46#include "llvm/Support/raw_ostream.h"
47#include <iterator>
48#include <memory>
49#include <string>
50#include <system_error>
51#include <utility>
52#include <vector>
Sam McCallcf3a5852019-09-04 07:35:00 +000053
54namespace clang {
55namespace clangd {
56namespace {
Kadir Cetinkaya538c2752020-05-14 12:26:47 +020057constexpr llvm::StringLiteral PreamblePatchHeaderName = "__preamble_patch__.h";
Sam McCallcf3a5852019-09-04 07:35:00 +000058
59bool compileCommandsAreEqual(const tooling::CompileCommand &LHS,
60 const tooling::CompileCommand &RHS) {
61 // We don't check for Output, it should not matter to clangd.
62 return LHS.Directory == RHS.Directory && LHS.Filename == RHS.Filename &&
63 llvm::makeArrayRef(LHS.CommandLine).equals(RHS.CommandLine);
64}
65
Sam McCallcf3a5852019-09-04 07:35:00 +000066class CppFilePreambleCallbacks : public PreambleCallbacks {
67public:
68 CppFilePreambleCallbacks(PathRef File, PreambleParsedCallback ParsedCallback)
Haojian Wu7e3c74b2019-09-24 11:14:06 +000069 : File(File), ParsedCallback(ParsedCallback) {}
Sam McCallcf3a5852019-09-04 07:35:00 +000070
71 IncludeStructure takeIncludes() { return std::move(Includes); }
72
Haojian Wu7e3c74b2019-09-24 11:14:06 +000073 MainFileMacros takeMacros() { return std::move(Macros); }
Sam McCallcf3a5852019-09-04 07:35:00 +000074
75 CanonicalIncludes takeCanonicalIncludes() { return std::move(CanonIncludes); }
76
77 void AfterExecute(CompilerInstance &CI) override {
78 if (!ParsedCallback)
79 return;
80 trace::Span Tracer("Running PreambleCallback");
81 ParsedCallback(CI.getASTContext(), CI.getPreprocessorPtr(), CanonIncludes);
82 }
83
84 void BeforeExecute(CompilerInstance &CI) override {
Ilya Biryukov8b767092019-09-09 15:32:51 +000085 CanonIncludes.addSystemHeadersMapping(CI.getLangOpts());
Haojian Wu7e3c74b2019-09-24 11:14:06 +000086 LangOpts = &CI.getLangOpts();
Sam McCallcf3a5852019-09-04 07:35:00 +000087 SourceMgr = &CI.getSourceManager();
88 }
89
90 std::unique_ptr<PPCallbacks> createPPCallbacks() override {
Haojian Wu7e3c74b2019-09-24 11:14:06 +000091 assert(SourceMgr && LangOpts &&
92 "SourceMgr and LangOpts must be set at this point");
93
Sam McCallcf3a5852019-09-04 07:35:00 +000094 return std::make_unique<PPChainedCallbacks>(
95 collectIncludeStructureCallback(*SourceMgr, &Includes),
Kadir Cetinkaya37550392020-03-01 16:05:12 +010096 std::make_unique<CollectMainFileMacros>(*SourceMgr, Macros));
Sam McCallcf3a5852019-09-04 07:35:00 +000097 }
98
99 CommentHandler *getCommentHandler() override {
100 IWYUHandler = collectIWYUHeaderMaps(&CanonIncludes);
101 return IWYUHandler.get();
102 }
103
Sam McCall4160f4c2020-06-09 15:46:35 +0200104 bool shouldSkipFunctionBody(Decl *D) override {
105 // Generally we skip function bodies in preambles for speed.
106 // We can make exceptions for functions that are cheap to parse and
107 // instantiate, widely used, and valuable (e.g. commonly produce errors).
108 if (const auto *FT = llvm::dyn_cast<clang::FunctionTemplateDecl>(D)) {
109 if (const auto *II = FT->getDeclName().getAsIdentifierInfo())
110 // std::make_unique is trivial, and we diagnose bad constructor calls.
111 if (II->isStr("make_unique") && FT->isInStdNamespace())
112 return false;
113 }
114 return true;
115 }
116
Sam McCallcf3a5852019-09-04 07:35:00 +0000117private:
118 PathRef File;
119 PreambleParsedCallback ParsedCallback;
120 IncludeStructure Includes;
121 CanonicalIncludes CanonIncludes;
Haojian Wu7e3c74b2019-09-24 11:14:06 +0000122 MainFileMacros Macros;
Sam McCallcf3a5852019-09-04 07:35:00 +0000123 std::unique_ptr<CommentHandler> IWYUHandler = nullptr;
Haojian Wu7e3c74b2019-09-24 11:14:06 +0000124 const clang::LangOptions *LangOpts = nullptr;
125 const SourceManager *SourceMgr = nullptr;
Sam McCallcf3a5852019-09-04 07:35:00 +0000126};
127
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200128// Represents directives other than includes, where basic textual information is
129// enough.
130struct TextualPPDirective {
131 unsigned DirectiveLine;
132 // Full text that's representing the directive, including the `#`.
133 std::string Text;
134
135 bool operator==(const TextualPPDirective &RHS) const {
136 return std::tie(DirectiveLine, Text) ==
137 std::tie(RHS.DirectiveLine, RHS.Text);
138 }
139};
140
Kadir Cetinkaya538c2752020-05-14 12:26:47 +0200141// Formats a PP directive consisting of Prefix (e.g. "#define ") and Body ("X
142// 10"). The formatting is copied so that the tokens in Body have PresumedLocs
143// with correct columns and lines.
144std::string spellDirective(llvm::StringRef Prefix,
145 CharSourceRange DirectiveRange,
146 const LangOptions &LangOpts, const SourceManager &SM,
147 unsigned &DirectiveLine) {
148 std::string SpelledDirective;
149 llvm::raw_string_ostream OS(SpelledDirective);
150 OS << Prefix;
151
152 // Make sure DirectiveRange is a char range and doesn't contain macro ids.
153 DirectiveRange = SM.getExpansionRange(DirectiveRange);
154 if (DirectiveRange.isTokenRange()) {
155 DirectiveRange.setEnd(
156 Lexer::getLocForEndOfToken(DirectiveRange.getEnd(), 0, SM, LangOpts));
157 }
158
159 auto DecompLoc = SM.getDecomposedLoc(DirectiveRange.getBegin());
160 DirectiveLine = SM.getLineNumber(DecompLoc.first, DecompLoc.second);
161 auto TargetColumn = SM.getColumnNumber(DecompLoc.first, DecompLoc.second) - 1;
162
163 // Pad with spaces before DirectiveRange to make sure it will be on right
164 // column when patched.
165 if (Prefix.size() <= TargetColumn) {
166 // There is enough space for Prefix and space before directive, use it.
167 // We try to squeeze the Prefix into the same line whenever we can, as
168 // putting onto a separate line won't work at the beginning of the file.
169 OS << std::string(TargetColumn - Prefix.size(), ' ');
170 } else {
171 // Prefix was longer than the space we had. We produce e.g.:
172 // #line N-1
173 // #define \
174 // X 10
175 OS << "\\\n" << std::string(TargetColumn, ' ');
176 // Decrement because we put an additional line break before
177 // DirectiveRange.begin().
178 --DirectiveLine;
179 }
180 OS << toSourceCode(SM, DirectiveRange.getAsRange());
181 return OS.str();
182}
183
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200184// Collects #define directives inside the main file.
185struct DirectiveCollector : public PPCallbacks {
186 DirectiveCollector(const Preprocessor &PP,
187 std::vector<TextualPPDirective> &TextualDirectives)
188 : LangOpts(PP.getLangOpts()), SM(PP.getSourceManager()),
189 TextualDirectives(TextualDirectives) {}
190
191 void FileChanged(SourceLocation Loc, FileChangeReason Reason,
192 SrcMgr::CharacteristicKind FileType,
193 FileID PrevFID) override {
194 InMainFile = SM.isWrittenInMainFile(Loc);
195 }
196
197 void MacroDefined(const Token &MacroNameTok,
198 const MacroDirective *MD) override {
199 if (!InMainFile)
200 return;
201 TextualDirectives.emplace_back();
202 TextualPPDirective &TD = TextualDirectives.back();
203
Kadir Cetinkaya538c2752020-05-14 12:26:47 +0200204 const auto *MI = MD->getMacroInfo();
205 TD.Text =
206 spellDirective("#define ",
207 CharSourceRange::getTokenRange(
208 MI->getDefinitionLoc(), MI->getDefinitionEndLoc()),
209 LangOpts, SM, TD.DirectiveLine);
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200210 }
211
212private:
213 bool InMainFile = true;
214 const LangOptions &LangOpts;
215 const SourceManager &SM;
216 std::vector<TextualPPDirective> &TextualDirectives;
217};
218
219struct ScannedPreamble {
220 std::vector<Inclusion> Includes;
221 std::vector<TextualPPDirective> TextualDirectives;
Kadir Cetinkaya4317ee22020-06-16 21:21:45 +0200222 PreambleBounds Bounds = {0, false};
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200223};
224
225/// Scans the preprocessor directives in the preamble section of the file by
226/// running preprocessor over \p Contents. Returned includes do not contain
227/// resolved paths. \p VFS and \p Cmd is used to build the compiler invocation,
228/// which might stat/read files.
229llvm::Expected<ScannedPreamble>
230scanPreamble(llvm::StringRef Contents,
231 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
232 const tooling::CompileCommand &Cmd) {
Kadir Cetinkayaf693ce42020-06-04 18:26:52 +0200233 // FIXME: Change PreambleStatCache to operate on FileSystemProvider rather
234 // than vfs::FileSystem, that way we can just use ParseInputs without this
235 // hack.
236 auto GetFSProvider = [](llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS) {
Kadir Cetinkaya06287052020-06-17 11:53:32 +0200237 class VFSProvider : public ThreadsafeFS {
Kadir Cetinkayaf693ce42020-06-04 18:26:52 +0200238 public:
239 VFSProvider(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS)
240 : VFS(std::move(FS)) {}
241 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem>
Kadir Cetinkaya06287052020-06-17 11:53:32 +0200242 view(llvm::NoneType) const override {
Kadir Cetinkayaf693ce42020-06-04 18:26:52 +0200243 return VFS;
244 }
245
246 private:
247 const llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
248 };
249 return std::make_unique<VFSProvider>(std::move(FS));
250 };
251 auto FSProvider = GetFSProvider(std::move(VFS));
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200252 // Build and run Preprocessor over the preamble.
253 ParseInputs PI;
254 PI.Contents = Contents.str();
Kadir Cetinkaya8d654df2020-06-17 18:09:54 +0200255 PI.TFS = FSProvider.get();
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200256 PI.CompileCommand = Cmd;
257 IgnoringDiagConsumer IgnoreDiags;
258 auto CI = buildCompilerInvocation(PI, IgnoreDiags);
259 if (!CI)
260 return llvm::createStringError(llvm::inconvertibleErrorCode(),
261 "failed to create compiler invocation");
262 CI->getDiagnosticOpts().IgnoreWarnings = true;
263 auto ContentsBuffer = llvm::MemoryBuffer::getMemBuffer(Contents);
Kadir Cetinkaya34e39eb2020-05-05 17:55:11 +0200264 // This means we're scanning (though not preprocessing) the preamble section
265 // twice. However, it's important to precisely follow the preamble bounds used
266 // elsewhere.
267 auto Bounds =
268 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
269 auto PreambleContents =
270 llvm::MemoryBuffer::getMemBufferCopy(Contents.substr(0, Bounds.Size));
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200271 auto Clang = prepareCompilerInstance(
Kadir Cetinkaya34e39eb2020-05-05 17:55:11 +0200272 std::move(CI), nullptr, std::move(PreambleContents),
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200273 // Provide an empty FS to prevent preprocessor from performing IO. This
274 // also implies missing resolved paths for includes.
275 new llvm::vfs::InMemoryFileSystem, IgnoreDiags);
276 if (Clang->getFrontendOpts().Inputs.empty())
277 return llvm::createStringError(llvm::inconvertibleErrorCode(),
278 "compiler instance had no inputs");
279 // We are only interested in main file includes.
280 Clang->getPreprocessorOpts().SingleFileParseMode = true;
Kadir Cetinkaya34e39eb2020-05-05 17:55:11 +0200281 PreprocessOnlyAction Action;
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200282 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0]))
283 return llvm::createStringError(llvm::inconvertibleErrorCode(),
284 "failed BeginSourceFile");
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200285 const auto &SM = Clang->getSourceManager();
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200286 Preprocessor &PP = Clang->getPreprocessor();
287 IncludeStructure Includes;
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200288 PP.addPPCallbacks(collectIncludeStructureCallback(SM, &Includes));
289 ScannedPreamble SP;
Kadir Cetinkaya4317ee22020-06-16 21:21:45 +0200290 SP.Bounds = Bounds;
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200291 PP.addPPCallbacks(
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200292 std::make_unique<DirectiveCollector>(PP, SP.TextualDirectives));
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200293 if (llvm::Error Err = Action.Execute())
294 return std::move(Err);
295 Action.EndSourceFile();
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200296 SP.Includes = std::move(Includes.MainFileIncludes);
297 return SP;
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200298}
299
300const char *spellingForIncDirective(tok::PPKeywordKind IncludeDirective) {
301 switch (IncludeDirective) {
302 case tok::pp_include:
303 return "include";
304 case tok::pp_import:
305 return "import";
306 case tok::pp_include_next:
307 return "include_next";
308 default:
309 break;
310 }
311 llvm_unreachable("not an include directive");
312}
Kadir Cetinkaya538c2752020-05-14 12:26:47 +0200313
314// Checks whether \p FileName is a valid spelling of main file.
315bool isMainFile(llvm::StringRef FileName, const SourceManager &SM) {
316 auto FE = SM.getFileManager().getFile(FileName);
317 return FE && *FE == SM.getFileEntryForID(SM.getMainFileID());
318}
319
Sam McCallcf3a5852019-09-04 07:35:00 +0000320} // namespace
321
Kadir Cetinkayaecd3e672020-03-11 16:34:01 +0100322PreambleData::PreambleData(const ParseInputs &Inputs,
Sam McCall2cd33e62020-03-04 00:33:29 +0100323 PrecompiledPreamble Preamble,
Sam McCallcf3a5852019-09-04 07:35:00 +0000324 std::vector<Diag> Diags, IncludeStructure Includes,
Haojian Wu7e3c74b2019-09-24 11:14:06 +0000325 MainFileMacros Macros,
Sam McCallcf3a5852019-09-04 07:35:00 +0000326 std::unique_ptr<PreambleFileStatusCache> StatCache,
327 CanonicalIncludes CanonIncludes)
Kadir Cetinkayaecd3e672020-03-11 16:34:01 +0100328 : Version(Inputs.Version), CompileCommand(Inputs.CompileCommand),
329 Preamble(std::move(Preamble)), Diags(std::move(Diags)),
Haojian Wu7e3c74b2019-09-24 11:14:06 +0000330 Includes(std::move(Includes)), Macros(std::move(Macros)),
Sam McCallcf3a5852019-09-04 07:35:00 +0000331 StatCache(std::move(StatCache)), CanonIncludes(std::move(CanonIncludes)) {
332}
333
334std::shared_ptr<const PreambleData>
Kadir Cetinkaya276a95b2020-03-13 11:52:19 +0100335buildPreamble(PathRef FileName, CompilerInvocation CI,
Sam McCallcf3a5852019-09-04 07:35:00 +0000336 const ParseInputs &Inputs, bool StoreInMemory,
337 PreambleParsedCallback PreambleCallback) {
338 // Note that we don't need to copy the input contents, preamble can live
339 // without those.
340 auto ContentsBuffer =
341 llvm::MemoryBuffer::getMemBuffer(Inputs.Contents, FileName);
342 auto Bounds =
343 ComputePreambleBounds(*CI.getLangOpts(), ContentsBuffer.get(), 0);
344
Sam McCallcf3a5852019-09-04 07:35:00 +0000345 trace::Span Tracer("BuildPreamble");
346 SPAN_ATTACH(Tracer, "File", FileName);
347 StoreDiags PreambleDiagnostics;
348 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
349 CompilerInstance::createDiagnostics(&CI.getDiagnosticOpts(),
350 &PreambleDiagnostics, false);
351
352 // Skip function bodies when building the preamble to speed up building
353 // the preamble and make it smaller.
354 assert(!CI.getFrontendOpts().SkipFunctionBodies);
355 CI.getFrontendOpts().SkipFunctionBodies = true;
356 // We don't want to write comment locations into PCH. They are racy and slow
357 // to read back. We rely on dynamic index for the comments instead.
358 CI.getPreprocessorOpts().WriteCommentListToPCH = false;
359
360 CppFilePreambleCallbacks SerializedDeclsCollector(FileName, PreambleCallback);
Kadir Cetinkaya8d654df2020-06-17 18:09:54 +0200361 auto VFS = Inputs.TFS->view(Inputs.CompileCommand.Directory);
Sam McCallcf3a5852019-09-04 07:35:00 +0000362 llvm::SmallString<32> AbsFileName(FileName);
Kadir Cetinkayaf693ce42020-06-04 18:26:52 +0200363 VFS->makeAbsolute(AbsFileName);
Sam McCallcf3a5852019-09-04 07:35:00 +0000364 auto StatCache = std::make_unique<PreambleFileStatusCache>(AbsFileName);
365 auto BuiltPreamble = PrecompiledPreamble::Build(
366 CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine,
Kadir Cetinkayaf693ce42020-06-04 18:26:52 +0200367 StatCache->getProducingFS(VFS),
Sam McCallcf3a5852019-09-04 07:35:00 +0000368 std::make_shared<PCHContainerOperations>(), StoreInMemory,
369 SerializedDeclsCollector);
370
371 // When building the AST for the main file, we do want the function
372 // bodies.
373 CI.getFrontendOpts().SkipFunctionBodies = false;
374
375 if (BuiltPreamble) {
Sam McCall2cd33e62020-03-04 00:33:29 +0100376 vlog("Built preamble of size {0} for file {1} version {2}",
377 BuiltPreamble->getSize(), FileName, Inputs.Version);
Sam McCallcf3a5852019-09-04 07:35:00 +0000378 std::vector<Diag> Diags = PreambleDiagnostics.take();
379 return std::make_shared<PreambleData>(
Kadir Cetinkayaecd3e672020-03-11 16:34:01 +0100380 Inputs, std::move(*BuiltPreamble), std::move(Diags),
Sam McCallcf3a5852019-09-04 07:35:00 +0000381 SerializedDeclsCollector.takeIncludes(),
Haojian Wu7e3c74b2019-09-24 11:14:06 +0000382 SerializedDeclsCollector.takeMacros(), std::move(StatCache),
Sam McCallcf3a5852019-09-04 07:35:00 +0000383 SerializedDeclsCollector.takeCanonicalIncludes());
384 } else {
Adam Czachorowski55b92dc2020-03-19 15:09:28 +0100385 elog("Could not build a preamble for file {0} version {1}", FileName,
Sam McCall2cd33e62020-03-04 00:33:29 +0100386 Inputs.Version);
Sam McCallcf3a5852019-09-04 07:35:00 +0000387 return nullptr;
388 }
389}
390
Kadir Cetinkayac31367e2020-03-15 21:43:00 +0100391bool isPreambleCompatible(const PreambleData &Preamble,
392 const ParseInputs &Inputs, PathRef FileName,
393 const CompilerInvocation &CI) {
394 auto ContentsBuffer =
395 llvm::MemoryBuffer::getMemBuffer(Inputs.Contents, FileName);
396 auto Bounds =
397 ComputePreambleBounds(*CI.getLangOpts(), ContentsBuffer.get(), 0);
Kadir Cetinkaya8d654df2020-06-17 18:09:54 +0200398 auto VFS = Inputs.TFS->view(Inputs.CompileCommand.Directory);
Kadir Cetinkayac31367e2020-03-15 21:43:00 +0100399 return compileCommandsAreEqual(Inputs.CompileCommand,
400 Preamble.CompileCommand) &&
401 Preamble.Preamble.CanReuse(CI, ContentsBuffer.get(), Bounds,
Kadir Cetinkaya37251422020-06-16 11:02:08 +0200402 VFS.get());
Kadir Cetinkayac31367e2020-03-15 21:43:00 +0100403}
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200404
Kadir Cetinkaya717bef62020-04-23 17:44:51 +0200405void escapeBackslashAndQuotes(llvm::StringRef Text, llvm::raw_ostream &OS) {
406 for (char C : Text) {
407 switch (C) {
408 case '\\':
409 case '"':
410 OS << '\\';
411 break;
412 default:
413 break;
414 }
415 OS << C;
416 }
417}
418
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200419PreamblePatch PreamblePatch::create(llvm::StringRef FileName,
420 const ParseInputs &Modified,
421 const PreambleData &Baseline) {
Kadir Cetinkaya20b2af32020-05-29 12:31:35 +0200422 trace::Span Tracer("CreatePreamblePatch");
423 SPAN_ATTACH(Tracer, "File", FileName);
Kadir Cetinkayab742eaa2020-04-02 10:53:45 +0200424 assert(llvm::sys::path::is_absolute(FileName) && "relative FileName!");
Kadir Cetinkaya2dc2e472020-06-16 12:16:24 +0200425 auto VFS = Baseline.StatCache->getConsumingFS(
Kadir Cetinkaya8d654df2020-06-17 18:09:54 +0200426 Modified.TFS->view(/*CWD=*/llvm::None));
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200427 // First scan preprocessor directives in Baseline and Modified. These will be
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200428 // used to figure out newly added directives in Modified. Scanning can fail,
429 // the code just bails out and creates an empty patch in such cases, as:
430 // - If scanning for Baseline fails, no knowledge of existing includes hence
431 // patch will contain all the includes in Modified. Leading to rebuild of
432 // whole preamble, which is terribly slow.
433 // - If scanning for Modified fails, cannot figure out newly added ones so
434 // there's nothing to do but generate an empty patch.
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200435 auto BaselineScan = scanPreamble(
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200436 // Contents needs to be null-terminated.
Kadir Cetinkayaf693ce42020-06-04 18:26:52 +0200437 Baseline.Preamble.getContents().str(), VFS, Modified.CompileCommand);
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200438 if (!BaselineScan) {
439 elog("Failed to scan baseline of {0}: {1}", FileName,
440 BaselineScan.takeError());
441 return PreamblePatch::unmodified(Baseline);
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200442 }
Kadir Cetinkayaf693ce42020-06-04 18:26:52 +0200443 auto ModifiedScan =
444 scanPreamble(Modified.Contents, std::move(VFS), Modified.CompileCommand);
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200445 if (!ModifiedScan) {
446 elog("Failed to scan modified contents of {0}: {1}", FileName,
447 ModifiedScan.takeError());
448 return PreamblePatch::unmodified(Baseline);
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200449 }
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200450
451 bool IncludesChanged = BaselineScan->Includes != ModifiedScan->Includes;
452 bool DirectivesChanged =
453 BaselineScan->TextualDirectives != ModifiedScan->TextualDirectives;
454 if (!IncludesChanged && !DirectivesChanged)
Kadir Cetinkayab742eaa2020-04-02 10:53:45 +0200455 return PreamblePatch::unmodified(Baseline);
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200456
457 PreamblePatch PP;
458 // This shouldn't coincide with any real file name.
459 llvm::SmallString<128> PatchName;
460 llvm::sys::path::append(PatchName, llvm::sys::path::parent_path(FileName),
Kadir Cetinkaya538c2752020-05-14 12:26:47 +0200461 PreamblePatchHeaderName);
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200462 PP.PatchFileName = PatchName.str().str();
Kadir Cetinkaya4317ee22020-06-16 21:21:45 +0200463 PP.ModifiedBounds = ModifiedScan->Bounds;
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200464
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200465 llvm::raw_string_ostream Patch(PP.PatchContents);
Kadir Cetinkaya717bef62020-04-23 17:44:51 +0200466 // Set default filename for subsequent #line directives
467 Patch << "#line 0 \"";
468 // FileName part of a line directive is subject to backslash escaping, which
469 // might lead to problems on windows especially.
470 escapeBackslashAndQuotes(FileName, Patch);
471 Patch << "\"\n";
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200472
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200473 if (IncludesChanged) {
474 // We are only interested in newly added includes, record the ones in
475 // Baseline for exclusion.
476 llvm::DenseMap<std::pair<tok::PPKeywordKind, llvm::StringRef>,
477 /*Resolved=*/llvm::StringRef>
478 ExistingIncludes;
479 for (const auto &Inc : Baseline.Includes.MainFileIncludes)
480 ExistingIncludes[{Inc.Directive, Inc.Written}] = Inc.Resolved;
481 // There might be includes coming from disabled regions, record these for
482 // exclusion too. note that we don't have resolved paths for those.
483 for (const auto &Inc : BaselineScan->Includes)
484 ExistingIncludes.try_emplace({Inc.Directive, Inc.Written});
485 // Calculate extra includes that needs to be inserted.
486 for (auto &Inc : ModifiedScan->Includes) {
487 auto It = ExistingIncludes.find({Inc.Directive, Inc.Written});
488 // Include already present in the baseline preamble. Set resolved path and
489 // put into preamble includes.
490 if (It != ExistingIncludes.end()) {
491 Inc.Resolved = It->second.str();
492 PP.PreambleIncludes.push_back(Inc);
493 continue;
494 }
495 // Include is new in the modified preamble. Inject it into the patch and
496 // use #line to set the presumed location to where it is spelled.
497 auto LineCol = offsetToClangLineColumn(Modified.Contents, Inc.HashOffset);
498 Patch << llvm::formatv("#line {0}\n", LineCol.first);
499 Patch << llvm::formatv(
500 "#{0} {1}\n", spellingForIncDirective(Inc.Directive), Inc.Written);
501 }
502 }
503
504 if (DirectivesChanged) {
505 // We need to patch all the directives, since they are order dependent. e.g:
506 // #define BAR(X) NEW(X) // Newly introduced in Modified
507 // #define BAR(X) OLD(X) // Exists in the Baseline
508 //
509 // If we've patched only the first directive, the macro definition would've
510 // been wrong for the rest of the file, since patch is applied after the
511 // baseline preamble.
512 //
513 // Note that we deliberately ignore conditional directives and undefs to
514 // reduce complexity. The former might cause problems because scanning is
515 // imprecise and might pick directives from disabled regions.
Kadir Cetinkaya538c2752020-05-14 12:26:47 +0200516 for (const auto &TD : ModifiedScan->TextualDirectives) {
517 Patch << "#line " << TD.DirectiveLine << '\n';
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200518 Patch << TD.Text << '\n';
Kadir Cetinkaya538c2752020-05-14 12:26:47 +0200519 }
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200520 }
521 dlog("Created preamble patch: {0}", Patch.str());
522 Patch.flush();
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200523 return PP;
524}
525
526void PreamblePatch::apply(CompilerInvocation &CI) const {
527 // No need to map an empty file.
528 if (PatchContents.empty())
529 return;
530 auto &PPOpts = CI.getPreprocessorOpts();
531 auto PatchBuffer =
532 // we copy here to ensure contents are still valid if CI outlives the
533 // PreamblePatch.
534 llvm::MemoryBuffer::getMemBufferCopy(PatchContents, PatchFileName);
535 // CI will take care of the lifetime of the buffer.
536 PPOpts.addRemappedFile(PatchFileName, PatchBuffer.release());
537 // The patch will be parsed after loading the preamble ast and before parsing
538 // the main file.
539 PPOpts.Includes.push_back(PatchFileName);
540}
541
Kadir Cetinkayab742eaa2020-04-02 10:53:45 +0200542std::vector<Inclusion> PreamblePatch::preambleIncludes() const {
543 return PreambleIncludes;
544}
545
546PreamblePatch PreamblePatch::unmodified(const PreambleData &Preamble) {
547 PreamblePatch PP;
548 PP.PreambleIncludes = Preamble.Includes.MainFileIncludes;
Kadir Cetinkaya4317ee22020-06-16 21:21:45 +0200549 PP.ModifiedBounds = Preamble.Preamble.getBounds();
Kadir Cetinkayab742eaa2020-04-02 10:53:45 +0200550 return PP;
551}
552
Kadir Cetinkaya538c2752020-05-14 12:26:47 +0200553SourceLocation translatePreamblePatchLocation(SourceLocation Loc,
554 const SourceManager &SM) {
555 auto DefFile = SM.getFileID(Loc);
556 if (auto *FE = SM.getFileEntryForID(DefFile)) {
557 auto IncludeLoc = SM.getIncludeLoc(DefFile);
558 // Preamble patch is included inside the builtin file.
559 if (IncludeLoc.isValid() && SM.isWrittenInBuiltinFile(IncludeLoc) &&
560 FE->getName().endswith(PreamblePatchHeaderName)) {
561 auto Presumed = SM.getPresumedLoc(Loc);
562 // Check that line directive is pointing at main file.
563 if (Presumed.isValid() && Presumed.getFileID().isInvalid() &&
564 isMainFile(Presumed.getFilename(), SM)) {
565 Loc = SM.translateLineCol(SM.getMainFileID(), Presumed.getLine(),
566 Presumed.getColumn());
567 }
568 }
569 }
570 return Loc;
571}
Sam McCallcf3a5852019-09-04 07:35:00 +0000572} // namespace clangd
573} // namespace clang