blob: 837ae7e5a5bba955a5e61045429b6c4b8dd3f4e0 [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"
Kadir Cetinkayaf693ce42020-06-04 18:26:52 +020013#include "support/FSProvider.h"
Sam McCallad97ccf2020-04-28 17:49:17 +020014#include "support/Logger.h"
15#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"
33#include "llvm/ADT/STLExtras.h"
34#include "llvm/ADT/SmallString.h"
Kadir Cetinkaya717bef62020-04-23 17:44:51 +020035#include "llvm/ADT/StringExtras.h"
Kadir Cetinkaya2214b902020-04-02 10:53:23 +020036#include "llvm/ADT/StringRef.h"
37#include "llvm/ADT/StringSet.h"
38#include "llvm/Support/Error.h"
39#include "llvm/Support/ErrorHandling.h"
40#include "llvm/Support/FormatVariadic.h"
41#include "llvm/Support/MemoryBuffer.h"
42#include "llvm/Support/Path.h"
43#include "llvm/Support/VirtualFileSystem.h"
44#include "llvm/Support/raw_ostream.h"
45#include <iterator>
46#include <memory>
47#include <string>
48#include <system_error>
49#include <utility>
50#include <vector>
Sam McCallcf3a5852019-09-04 07:35:00 +000051
52namespace clang {
53namespace clangd {
54namespace {
Kadir Cetinkaya538c2752020-05-14 12:26:47 +020055constexpr llvm::StringLiteral PreamblePatchHeaderName = "__preamble_patch__.h";
Sam McCallcf3a5852019-09-04 07:35:00 +000056
57bool compileCommandsAreEqual(const tooling::CompileCommand &LHS,
58 const tooling::CompileCommand &RHS) {
59 // We don't check for Output, it should not matter to clangd.
60 return LHS.Directory == RHS.Directory && LHS.Filename == RHS.Filename &&
61 llvm::makeArrayRef(LHS.CommandLine).equals(RHS.CommandLine);
62}
63
Sam McCallcf3a5852019-09-04 07:35:00 +000064class CppFilePreambleCallbacks : public PreambleCallbacks {
65public:
66 CppFilePreambleCallbacks(PathRef File, PreambleParsedCallback ParsedCallback)
Haojian Wu7e3c74b2019-09-24 11:14:06 +000067 : File(File), ParsedCallback(ParsedCallback) {}
Sam McCallcf3a5852019-09-04 07:35:00 +000068
69 IncludeStructure takeIncludes() { return std::move(Includes); }
70
Haojian Wu7e3c74b2019-09-24 11:14:06 +000071 MainFileMacros takeMacros() { return std::move(Macros); }
Sam McCallcf3a5852019-09-04 07:35:00 +000072
73 CanonicalIncludes takeCanonicalIncludes() { return std::move(CanonIncludes); }
74
75 void AfterExecute(CompilerInstance &CI) override {
76 if (!ParsedCallback)
77 return;
78 trace::Span Tracer("Running PreambleCallback");
79 ParsedCallback(CI.getASTContext(), CI.getPreprocessorPtr(), CanonIncludes);
80 }
81
82 void BeforeExecute(CompilerInstance &CI) override {
Ilya Biryukov8b767092019-09-09 15:32:51 +000083 CanonIncludes.addSystemHeadersMapping(CI.getLangOpts());
Haojian Wu7e3c74b2019-09-24 11:14:06 +000084 LangOpts = &CI.getLangOpts();
Sam McCallcf3a5852019-09-04 07:35:00 +000085 SourceMgr = &CI.getSourceManager();
86 }
87
88 std::unique_ptr<PPCallbacks> createPPCallbacks() override {
Haojian Wu7e3c74b2019-09-24 11:14:06 +000089 assert(SourceMgr && LangOpts &&
90 "SourceMgr and LangOpts must be set at this point");
91
Sam McCallcf3a5852019-09-04 07:35:00 +000092 return std::make_unique<PPChainedCallbacks>(
93 collectIncludeStructureCallback(*SourceMgr, &Includes),
Kadir Cetinkaya37550392020-03-01 16:05:12 +010094 std::make_unique<CollectMainFileMacros>(*SourceMgr, Macros));
Sam McCallcf3a5852019-09-04 07:35:00 +000095 }
96
97 CommentHandler *getCommentHandler() override {
98 IWYUHandler = collectIWYUHeaderMaps(&CanonIncludes);
99 return IWYUHandler.get();
100 }
101
Sam McCall4160f4c2020-06-09 15:46:35 +0200102 bool shouldSkipFunctionBody(Decl *D) override {
103 // Generally we skip function bodies in preambles for speed.
104 // We can make exceptions for functions that are cheap to parse and
105 // instantiate, widely used, and valuable (e.g. commonly produce errors).
106 if (const auto *FT = llvm::dyn_cast<clang::FunctionTemplateDecl>(D)) {
107 if (const auto *II = FT->getDeclName().getAsIdentifierInfo())
108 // std::make_unique is trivial, and we diagnose bad constructor calls.
109 if (II->isStr("make_unique") && FT->isInStdNamespace())
110 return false;
111 }
112 return true;
113 }
114
Sam McCallcf3a5852019-09-04 07:35:00 +0000115private:
116 PathRef File;
117 PreambleParsedCallback ParsedCallback;
118 IncludeStructure Includes;
119 CanonicalIncludes CanonIncludes;
Haojian Wu7e3c74b2019-09-24 11:14:06 +0000120 MainFileMacros Macros;
Sam McCallcf3a5852019-09-04 07:35:00 +0000121 std::unique_ptr<CommentHandler> IWYUHandler = nullptr;
Haojian Wu7e3c74b2019-09-24 11:14:06 +0000122 const clang::LangOptions *LangOpts = nullptr;
123 const SourceManager *SourceMgr = nullptr;
Sam McCallcf3a5852019-09-04 07:35:00 +0000124};
125
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200126// Represents directives other than includes, where basic textual information is
127// enough.
128struct TextualPPDirective {
129 unsigned DirectiveLine;
130 // Full text that's representing the directive, including the `#`.
131 std::string Text;
132
133 bool operator==(const TextualPPDirective &RHS) const {
134 return std::tie(DirectiveLine, Text) ==
135 std::tie(RHS.DirectiveLine, RHS.Text);
136 }
137};
138
Kadir Cetinkaya538c2752020-05-14 12:26:47 +0200139// Formats a PP directive consisting of Prefix (e.g. "#define ") and Body ("X
140// 10"). The formatting is copied so that the tokens in Body have PresumedLocs
141// with correct columns and lines.
142std::string spellDirective(llvm::StringRef Prefix,
143 CharSourceRange DirectiveRange,
144 const LangOptions &LangOpts, const SourceManager &SM,
145 unsigned &DirectiveLine) {
146 std::string SpelledDirective;
147 llvm::raw_string_ostream OS(SpelledDirective);
148 OS << Prefix;
149
150 // Make sure DirectiveRange is a char range and doesn't contain macro ids.
151 DirectiveRange = SM.getExpansionRange(DirectiveRange);
152 if (DirectiveRange.isTokenRange()) {
153 DirectiveRange.setEnd(
154 Lexer::getLocForEndOfToken(DirectiveRange.getEnd(), 0, SM, LangOpts));
155 }
156
157 auto DecompLoc = SM.getDecomposedLoc(DirectiveRange.getBegin());
158 DirectiveLine = SM.getLineNumber(DecompLoc.first, DecompLoc.second);
159 auto TargetColumn = SM.getColumnNumber(DecompLoc.first, DecompLoc.second) - 1;
160
161 // Pad with spaces before DirectiveRange to make sure it will be on right
162 // column when patched.
163 if (Prefix.size() <= TargetColumn) {
164 // There is enough space for Prefix and space before directive, use it.
165 // We try to squeeze the Prefix into the same line whenever we can, as
166 // putting onto a separate line won't work at the beginning of the file.
167 OS << std::string(TargetColumn - Prefix.size(), ' ');
168 } else {
169 // Prefix was longer than the space we had. We produce e.g.:
170 // #line N-1
171 // #define \
172 // X 10
173 OS << "\\\n" << std::string(TargetColumn, ' ');
174 // Decrement because we put an additional line break before
175 // DirectiveRange.begin().
176 --DirectiveLine;
177 }
178 OS << toSourceCode(SM, DirectiveRange.getAsRange());
179 return OS.str();
180}
181
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200182// Collects #define directives inside the main file.
183struct DirectiveCollector : public PPCallbacks {
184 DirectiveCollector(const Preprocessor &PP,
185 std::vector<TextualPPDirective> &TextualDirectives)
186 : LangOpts(PP.getLangOpts()), SM(PP.getSourceManager()),
187 TextualDirectives(TextualDirectives) {}
188
189 void FileChanged(SourceLocation Loc, FileChangeReason Reason,
190 SrcMgr::CharacteristicKind FileType,
191 FileID PrevFID) override {
192 InMainFile = SM.isWrittenInMainFile(Loc);
193 }
194
195 void MacroDefined(const Token &MacroNameTok,
196 const MacroDirective *MD) override {
197 if (!InMainFile)
198 return;
199 TextualDirectives.emplace_back();
200 TextualPPDirective &TD = TextualDirectives.back();
201
Kadir Cetinkaya538c2752020-05-14 12:26:47 +0200202 const auto *MI = MD->getMacroInfo();
203 TD.Text =
204 spellDirective("#define ",
205 CharSourceRange::getTokenRange(
206 MI->getDefinitionLoc(), MI->getDefinitionEndLoc()),
207 LangOpts, SM, TD.DirectiveLine);
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200208 }
209
210private:
211 bool InMainFile = true;
212 const LangOptions &LangOpts;
213 const SourceManager &SM;
214 std::vector<TextualPPDirective> &TextualDirectives;
215};
216
217struct ScannedPreamble {
218 std::vector<Inclusion> Includes;
219 std::vector<TextualPPDirective> TextualDirectives;
220};
221
222/// Scans the preprocessor directives in the preamble section of the file by
223/// running preprocessor over \p Contents. Returned includes do not contain
224/// resolved paths. \p VFS and \p Cmd is used to build the compiler invocation,
225/// which might stat/read files.
226llvm::Expected<ScannedPreamble>
227scanPreamble(llvm::StringRef Contents,
228 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
229 const tooling::CompileCommand &Cmd) {
Kadir Cetinkayaf693ce42020-06-04 18:26:52 +0200230 // FIXME: Change PreambleStatCache to operate on FileSystemProvider rather
231 // than vfs::FileSystem, that way we can just use ParseInputs without this
232 // hack.
233 auto GetFSProvider = [](llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS) {
234 class VFSProvider : public FileSystemProvider {
235 public:
236 VFSProvider(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS)
237 : VFS(std::move(FS)) {}
238 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem>
239 getFileSystem() const override {
240 return VFS;
241 }
242
243 private:
244 const llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
245 };
246 return std::make_unique<VFSProvider>(std::move(FS));
247 };
248 auto FSProvider = GetFSProvider(std::move(VFS));
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200249 // Build and run Preprocessor over the preamble.
250 ParseInputs PI;
251 PI.Contents = Contents.str();
Kadir Cetinkayaf693ce42020-06-04 18:26:52 +0200252 PI.FSProvider = FSProvider.get();
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200253 PI.CompileCommand = Cmd;
254 IgnoringDiagConsumer IgnoreDiags;
255 auto CI = buildCompilerInvocation(PI, IgnoreDiags);
256 if (!CI)
257 return llvm::createStringError(llvm::inconvertibleErrorCode(),
258 "failed to create compiler invocation");
259 CI->getDiagnosticOpts().IgnoreWarnings = true;
260 auto ContentsBuffer = llvm::MemoryBuffer::getMemBuffer(Contents);
Kadir Cetinkaya34e39eb2020-05-05 17:55:11 +0200261 // This means we're scanning (though not preprocessing) the preamble section
262 // twice. However, it's important to precisely follow the preamble bounds used
263 // elsewhere.
264 auto Bounds =
265 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
266 auto PreambleContents =
267 llvm::MemoryBuffer::getMemBufferCopy(Contents.substr(0, Bounds.Size));
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200268 auto Clang = prepareCompilerInstance(
Kadir Cetinkaya34e39eb2020-05-05 17:55:11 +0200269 std::move(CI), nullptr, std::move(PreambleContents),
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200270 // Provide an empty FS to prevent preprocessor from performing IO. This
271 // also implies missing resolved paths for includes.
272 new llvm::vfs::InMemoryFileSystem, IgnoreDiags);
273 if (Clang->getFrontendOpts().Inputs.empty())
274 return llvm::createStringError(llvm::inconvertibleErrorCode(),
275 "compiler instance had no inputs");
276 // We are only interested in main file includes.
277 Clang->getPreprocessorOpts().SingleFileParseMode = true;
Kadir Cetinkaya34e39eb2020-05-05 17:55:11 +0200278 PreprocessOnlyAction Action;
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200279 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0]))
280 return llvm::createStringError(llvm::inconvertibleErrorCode(),
281 "failed BeginSourceFile");
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200282 const auto &SM = Clang->getSourceManager();
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200283 Preprocessor &PP = Clang->getPreprocessor();
284 IncludeStructure Includes;
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200285 PP.addPPCallbacks(collectIncludeStructureCallback(SM, &Includes));
286 ScannedPreamble SP;
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200287 PP.addPPCallbacks(
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200288 std::make_unique<DirectiveCollector>(PP, SP.TextualDirectives));
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200289 if (llvm::Error Err = Action.Execute())
290 return std::move(Err);
291 Action.EndSourceFile();
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200292 SP.Includes = std::move(Includes.MainFileIncludes);
293 return SP;
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200294}
295
296const char *spellingForIncDirective(tok::PPKeywordKind IncludeDirective) {
297 switch (IncludeDirective) {
298 case tok::pp_include:
299 return "include";
300 case tok::pp_import:
301 return "import";
302 case tok::pp_include_next:
303 return "include_next";
304 default:
305 break;
306 }
307 llvm_unreachable("not an include directive");
308}
Kadir Cetinkaya538c2752020-05-14 12:26:47 +0200309
310// Checks whether \p FileName is a valid spelling of main file.
311bool isMainFile(llvm::StringRef FileName, const SourceManager &SM) {
312 auto FE = SM.getFileManager().getFile(FileName);
313 return FE && *FE == SM.getFileEntryForID(SM.getMainFileID());
314}
315
Sam McCallcf3a5852019-09-04 07:35:00 +0000316} // namespace
317
Kadir Cetinkayaecd3e672020-03-11 16:34:01 +0100318PreambleData::PreambleData(const ParseInputs &Inputs,
Sam McCall2cd33e62020-03-04 00:33:29 +0100319 PrecompiledPreamble Preamble,
Sam McCallcf3a5852019-09-04 07:35:00 +0000320 std::vector<Diag> Diags, IncludeStructure Includes,
Haojian Wu7e3c74b2019-09-24 11:14:06 +0000321 MainFileMacros Macros,
Sam McCallcf3a5852019-09-04 07:35:00 +0000322 std::unique_ptr<PreambleFileStatusCache> StatCache,
323 CanonicalIncludes CanonIncludes)
Kadir Cetinkayaecd3e672020-03-11 16:34:01 +0100324 : Version(Inputs.Version), CompileCommand(Inputs.CompileCommand),
325 Preamble(std::move(Preamble)), Diags(std::move(Diags)),
Haojian Wu7e3c74b2019-09-24 11:14:06 +0000326 Includes(std::move(Includes)), Macros(std::move(Macros)),
Sam McCallcf3a5852019-09-04 07:35:00 +0000327 StatCache(std::move(StatCache)), CanonIncludes(std::move(CanonIncludes)) {
328}
329
330std::shared_ptr<const PreambleData>
Kadir Cetinkaya276a95b2020-03-13 11:52:19 +0100331buildPreamble(PathRef FileName, CompilerInvocation CI,
Sam McCallcf3a5852019-09-04 07:35:00 +0000332 const ParseInputs &Inputs, bool StoreInMemory,
333 PreambleParsedCallback PreambleCallback) {
334 // Note that we don't need to copy the input contents, preamble can live
335 // without those.
336 auto ContentsBuffer =
337 llvm::MemoryBuffer::getMemBuffer(Inputs.Contents, FileName);
338 auto Bounds =
339 ComputePreambleBounds(*CI.getLangOpts(), ContentsBuffer.get(), 0);
340
Sam McCallcf3a5852019-09-04 07:35:00 +0000341 trace::Span Tracer("BuildPreamble");
342 SPAN_ATTACH(Tracer, "File", FileName);
343 StoreDiags PreambleDiagnostics;
344 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
345 CompilerInstance::createDiagnostics(&CI.getDiagnosticOpts(),
346 &PreambleDiagnostics, false);
347
348 // Skip function bodies when building the preamble to speed up building
349 // the preamble and make it smaller.
350 assert(!CI.getFrontendOpts().SkipFunctionBodies);
351 CI.getFrontendOpts().SkipFunctionBodies = true;
352 // We don't want to write comment locations into PCH. They are racy and slow
353 // to read back. We rely on dynamic index for the comments instead.
354 CI.getPreprocessorOpts().WriteCommentListToPCH = false;
355
356 CppFilePreambleCallbacks SerializedDeclsCollector(FileName, PreambleCallback);
Kadir Cetinkayaf693ce42020-06-04 18:26:52 +0200357 auto VFS = Inputs.FSProvider->getFileSystem();
358 if (VFS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
Sam McCallcf3a5852019-09-04 07:35:00 +0000359 log("Couldn't set working directory when building the preamble.");
360 // We proceed anyway, our lit-tests rely on results for non-existing working
361 // dirs.
362 }
363
364 llvm::SmallString<32> AbsFileName(FileName);
Kadir Cetinkayaf693ce42020-06-04 18:26:52 +0200365 VFS->makeAbsolute(AbsFileName);
Sam McCallcf3a5852019-09-04 07:35:00 +0000366 auto StatCache = std::make_unique<PreambleFileStatusCache>(AbsFileName);
367 auto BuiltPreamble = PrecompiledPreamble::Build(
368 CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine,
Kadir Cetinkayaf693ce42020-06-04 18:26:52 +0200369 StatCache->getProducingFS(VFS),
Sam McCallcf3a5852019-09-04 07:35:00 +0000370 std::make_shared<PCHContainerOperations>(), StoreInMemory,
371 SerializedDeclsCollector);
372
373 // When building the AST for the main file, we do want the function
374 // bodies.
375 CI.getFrontendOpts().SkipFunctionBodies = false;
376
377 if (BuiltPreamble) {
Sam McCall2cd33e62020-03-04 00:33:29 +0100378 vlog("Built preamble of size {0} for file {1} version {2}",
379 BuiltPreamble->getSize(), FileName, Inputs.Version);
Sam McCallcf3a5852019-09-04 07:35:00 +0000380 std::vector<Diag> Diags = PreambleDiagnostics.take();
381 return std::make_shared<PreambleData>(
Kadir Cetinkayaecd3e672020-03-11 16:34:01 +0100382 Inputs, std::move(*BuiltPreamble), std::move(Diags),
Sam McCallcf3a5852019-09-04 07:35:00 +0000383 SerializedDeclsCollector.takeIncludes(),
Haojian Wu7e3c74b2019-09-24 11:14:06 +0000384 SerializedDeclsCollector.takeMacros(), std::move(StatCache),
Sam McCallcf3a5852019-09-04 07:35:00 +0000385 SerializedDeclsCollector.takeCanonicalIncludes());
386 } else {
Adam Czachorowski55b92dc2020-03-19 15:09:28 +0100387 elog("Could not build a preamble for file {0} version {1}", FileName,
Sam McCall2cd33e62020-03-04 00:33:29 +0100388 Inputs.Version);
Sam McCallcf3a5852019-09-04 07:35:00 +0000389 return nullptr;
390 }
391}
392
Kadir Cetinkayac31367e2020-03-15 21:43:00 +0100393bool isPreambleCompatible(const PreambleData &Preamble,
394 const ParseInputs &Inputs, PathRef FileName,
395 const CompilerInvocation &CI) {
396 auto ContentsBuffer =
397 llvm::MemoryBuffer::getMemBuffer(Inputs.Contents, FileName);
398 auto Bounds =
399 ComputePreambleBounds(*CI.getLangOpts(), ContentsBuffer.get(), 0);
400 return compileCommandsAreEqual(Inputs.CompileCommand,
401 Preamble.CompileCommand) &&
402 Preamble.Preamble.CanReuse(CI, ContentsBuffer.get(), Bounds,
Kadir Cetinkayaf693ce42020-06-04 18:26:52 +0200403 Inputs.FSProvider->getFileSystem().get());
Kadir Cetinkayac31367e2020-03-15 21:43:00 +0100404}
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200405
Kadir Cetinkaya717bef62020-04-23 17:44:51 +0200406void escapeBackslashAndQuotes(llvm::StringRef Text, llvm::raw_ostream &OS) {
407 for (char C : Text) {
408 switch (C) {
409 case '\\':
410 case '"':
411 OS << '\\';
412 break;
413 default:
414 break;
415 }
416 OS << C;
417 }
418}
419
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200420PreamblePatch PreamblePatch::create(llvm::StringRef FileName,
421 const ParseInputs &Modified,
422 const PreambleData &Baseline) {
Kadir Cetinkaya20b2af32020-05-29 12:31:35 +0200423 trace::Span Tracer("CreatePreamblePatch");
424 SPAN_ATTACH(Tracer, "File", FileName);
Kadir Cetinkayab742eaa2020-04-02 10:53:45 +0200425 assert(llvm::sys::path::is_absolute(FileName) && "relative FileName!");
Kadir Cetinkayaf693ce42020-06-04 18:26:52 +0200426 auto VFS =
427 Baseline.StatCache->getConsumingFS(Modified.FSProvider->getFileSystem());
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200428 // First scan preprocessor directives in Baseline and Modified. These will be
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200429 // used to figure out newly added directives in Modified. Scanning can fail,
430 // the code just bails out and creates an empty patch in such cases, as:
431 // - If scanning for Baseline fails, no knowledge of existing includes hence
432 // patch will contain all the includes in Modified. Leading to rebuild of
433 // whole preamble, which is terribly slow.
434 // - If scanning for Modified fails, cannot figure out newly added ones so
435 // there's nothing to do but generate an empty patch.
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200436 auto BaselineScan = scanPreamble(
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200437 // Contents needs to be null-terminated.
Kadir Cetinkayaf693ce42020-06-04 18:26:52 +0200438 Baseline.Preamble.getContents().str(), VFS, Modified.CompileCommand);
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200439 if (!BaselineScan) {
440 elog("Failed to scan baseline of {0}: {1}", FileName,
441 BaselineScan.takeError());
442 return PreamblePatch::unmodified(Baseline);
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200443 }
Kadir Cetinkayaf693ce42020-06-04 18:26:52 +0200444 auto ModifiedScan =
445 scanPreamble(Modified.Contents, std::move(VFS), Modified.CompileCommand);
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200446 if (!ModifiedScan) {
447 elog("Failed to scan modified contents of {0}: {1}", FileName,
448 ModifiedScan.takeError());
449 return PreamblePatch::unmodified(Baseline);
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200450 }
Kadir Cetinkayafcde3d52020-05-14 12:20:33 +0200451
452 bool IncludesChanged = BaselineScan->Includes != ModifiedScan->Includes;
453 bool DirectivesChanged =
454 BaselineScan->TextualDirectives != ModifiedScan->TextualDirectives;
455 if (!IncludesChanged && !DirectivesChanged)
Kadir Cetinkayab742eaa2020-04-02 10:53:45 +0200456 return PreamblePatch::unmodified(Baseline);
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200457
458 PreamblePatch PP;
459 // This shouldn't coincide with any real file name.
460 llvm::SmallString<128> PatchName;
461 llvm::sys::path::append(PatchName, llvm::sys::path::parent_path(FileName),
Kadir Cetinkaya538c2752020-05-14 12:26:47 +0200462 PreamblePatchHeaderName);
Kadir Cetinkaya2214b902020-04-02 10:53:23 +0200463 PP.PatchFileName = PatchName.str().str();
464
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;
549 return PP;
550}
551
Kadir Cetinkaya538c2752020-05-14 12:26:47 +0200552SourceLocation translatePreamblePatchLocation(SourceLocation Loc,
553 const SourceManager &SM) {
554 auto DefFile = SM.getFileID(Loc);
555 if (auto *FE = SM.getFileEntryForID(DefFile)) {
556 auto IncludeLoc = SM.getIncludeLoc(DefFile);
557 // Preamble patch is included inside the builtin file.
558 if (IncludeLoc.isValid() && SM.isWrittenInBuiltinFile(IncludeLoc) &&
559 FE->getName().endswith(PreamblePatchHeaderName)) {
560 auto Presumed = SM.getPresumedLoc(Loc);
561 // Check that line directive is pointing at main file.
562 if (Presumed.isValid() && Presumed.getFileID().isInvalid() &&
563 isMainFile(Presumed.getFilename(), SM)) {
564 Loc = SM.translateLineCol(SM.getMainFileID(), Presumed.getLine(),
565 Presumed.getColumn());
566 }
567 }
568 }
569 return Loc;
570}
Sam McCallcf3a5852019-09-04 07:35:00 +0000571} // namespace clangd
572} // namespace clang