blob: ed06607ef3cbaff5f24b00504bb0bb85d8e236db [file] [log] [blame]
Ilya Biryukov38d79772017-05-16 09:38:59 +00001//===--- ClangdUnit.cpp -----------------------------------------*- 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#include "ClangdUnit.h"
Sam McCall98775c52017-12-04 13:49:59 +000011#include "Compiler.h"
Ilya Biryukov83ca8a22017-09-20 10:46:58 +000012#include "Logger.h"
Sam McCall8567cb32017-11-02 09:21:51 +000013#include "Trace.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000014#include "clang/Frontend/CompilerInstance.h"
15#include "clang/Frontend/CompilerInvocation.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000016#include "clang/Frontend/FrontendActions.h"
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000017#include "clang/Frontend/Utils.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000018#include "clang/Index/IndexDataConsumer.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000019#include "clang/Index/IndexingAction.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000020#include "clang/Lex/Lexer.h"
21#include "clang/Lex/MacroInfo.h"
22#include "clang/Lex/Preprocessor.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000023#include "clang/Sema/Sema.h"
24#include "clang/Serialization/ASTWriter.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000025#include "clang/Tooling/CompilationDatabase.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000026#include "llvm/ADT/ArrayRef.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/Support/CrashRecoveryContext.h"
Krasimir Georgieva1de3c92017-06-15 09:11:57 +000029#include "llvm/Support/Format.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000030#include <algorithm>
Ilya Biryukov02d58702017-08-01 15:51:38 +000031#include <chrono>
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000032
Ilya Biryukov38d79772017-05-16 09:38:59 +000033using namespace clang::clangd;
34using namespace clang;
35
Ilya Biryukov04db3682017-07-21 13:29:29 +000036namespace {
37
Ilya Biryukovdf842342018-01-25 14:32:21 +000038template <class T> std::size_t getUsedBytes(const std::vector<T> &Vec) {
39 return Vec.capacity() * sizeof(T);
40}
41
Ilya Biryukov04db3682017-07-21 13:29:29 +000042class DeclTrackingASTConsumer : public ASTConsumer {
43public:
44 DeclTrackingASTConsumer(std::vector<const Decl *> &TopLevelDecls)
45 : TopLevelDecls(TopLevelDecls) {}
46
47 bool HandleTopLevelDecl(DeclGroupRef DG) override {
48 for (const Decl *D : DG) {
49 // ObjCMethodDecl are not actually top-level decls.
50 if (isa<ObjCMethodDecl>(D))
51 continue;
52
53 TopLevelDecls.push_back(D);
54 }
55 return true;
56 }
57
58private:
59 std::vector<const Decl *> &TopLevelDecls;
60};
61
62class ClangdFrontendAction : public SyntaxOnlyAction {
63public:
64 std::vector<const Decl *> takeTopLevelDecls() {
65 return std::move(TopLevelDecls);
66 }
67
68protected:
69 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
70 StringRef InFile) override {
71 return llvm::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls);
72 }
73
74private:
75 std::vector<const Decl *> TopLevelDecls;
76};
77
Ilya Biryukov02d58702017-08-01 15:51:38 +000078class CppFilePreambleCallbacks : public PreambleCallbacks {
Ilya Biryukov04db3682017-07-21 13:29:29 +000079public:
80 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
81 return std::move(TopLevelDeclIDs);
82 }
83
84 void AfterPCHEmitted(ASTWriter &Writer) override {
85 TopLevelDeclIDs.reserve(TopLevelDecls.size());
86 for (Decl *D : TopLevelDecls) {
87 // Invalid top-level decls may not have been serialized.
88 if (D->isInvalidDecl())
89 continue;
90 TopLevelDeclIDs.push_back(Writer.getDeclID(D));
91 }
92 }
93
94 void HandleTopLevelDecl(DeclGroupRef DG) override {
95 for (Decl *D : DG) {
96 if (isa<ObjCMethodDecl>(D))
97 continue;
98 TopLevelDecls.push_back(D);
99 }
100 }
101
102private:
103 std::vector<Decl *> TopLevelDecls;
104 std::vector<serialization::DeclID> TopLevelDeclIDs;
105};
106
107/// Convert from clang diagnostic level to LSP severity.
108static int getSeverity(DiagnosticsEngine::Level L) {
109 switch (L) {
110 case DiagnosticsEngine::Remark:
111 return 4;
112 case DiagnosticsEngine::Note:
113 return 3;
114 case DiagnosticsEngine::Warning:
115 return 2;
116 case DiagnosticsEngine::Fatal:
117 case DiagnosticsEngine::Error:
118 return 1;
119 case DiagnosticsEngine::Ignored:
120 return 0;
121 }
122 llvm_unreachable("Unknown diagnostic level!");
123}
124
Sam McCall8111d3b2017-12-13 08:48:42 +0000125// Checks whether a location is within a half-open range.
126// Note that clang also uses closed source ranges, which this can't handle!
127bool locationInRange(SourceLocation L, CharSourceRange R,
128 const SourceManager &M) {
129 assert(R.isCharRange());
130 if (!R.isValid() || M.getFileID(R.getBegin()) != M.getFileID(R.getEnd()) ||
131 M.getFileID(R.getBegin()) != M.getFileID(L))
132 return false;
133 return L != R.getEnd() && M.isPointWithin(L, R.getBegin(), R.getEnd());
134}
135
136// Converts a half-open clang source range to an LSP range.
137// Note that clang also uses closed source ranges, which this can't handle!
138Range toRange(CharSourceRange R, const SourceManager &M) {
139 // Clang is 1-based, LSP uses 0-based indexes.
140 return {{static_cast<int>(M.getSpellingLineNumber(R.getBegin())) - 1,
141 static_cast<int>(M.getSpellingColumnNumber(R.getBegin())) - 1},
142 {static_cast<int>(M.getSpellingLineNumber(R.getEnd())) - 1,
143 static_cast<int>(M.getSpellingColumnNumber(R.getEnd())) - 1}};
144}
145
146// Clang diags have a location (shown as ^) and 0 or more ranges (~~~~).
147// LSP needs a single range.
148Range diagnosticRange(const clang::Diagnostic &D, const LangOptions &L) {
149 auto &M = D.getSourceManager();
150 auto Loc = M.getFileLoc(D.getLocation());
151 // Accept the first range that contains the location.
152 for (const auto &CR : D.getRanges()) {
153 auto R = Lexer::makeFileCharRange(CR, M, L);
154 if (locationInRange(Loc, R, M))
155 return toRange(R, M);
156 }
157 // The range may be given as a fixit hint instead.
158 for (const auto &F : D.getFixItHints()) {
159 auto R = Lexer::makeFileCharRange(F.RemoveRange, M, L);
160 if (locationInRange(Loc, R, M))
161 return toRange(R, M);
162 }
163 // If no suitable range is found, just use the token at the location.
164 auto R = Lexer::makeFileCharRange(CharSourceRange::getTokenRange(Loc), M, L);
165 if (!R.isValid()) // Fall back to location only, let the editor deal with it.
166 R = CharSourceRange::getCharRange(Loc);
167 return toRange(R, M);
168}
169
170TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M,
171 const LangOptions &L) {
172 TextEdit Result;
173 Result.range = toRange(Lexer::makeFileCharRange(FixIt.RemoveRange, M, L), M);
174 Result.newText = FixIt.CodeToInsert;
175 return Result;
176}
177
178llvm::Optional<DiagWithFixIts> toClangdDiag(const clang::Diagnostic &D,
179 DiagnosticsEngine::Level Level,
180 const LangOptions &LangOpts) {
181 if (!D.hasSourceManager() || !D.getLocation().isValid() ||
182 !D.getSourceManager().isInMainFile(D.getLocation()))
Ilya Biryukov04db3682017-07-21 13:29:29 +0000183 return llvm::None;
184
Sam McCall8111d3b2017-12-13 08:48:42 +0000185 DiagWithFixIts Result;
186 Result.Diag.range = diagnosticRange(D, LangOpts);
187 Result.Diag.severity = getSeverity(Level);
188 SmallString<64> Message;
189 D.FormatDiagnostic(Message);
190 Result.Diag.message = Message.str();
191 for (const FixItHint &Fix : D.getFixItHints())
192 Result.FixIts.push_back(toTextEdit(Fix, D.getSourceManager(), LangOpts));
193 return std::move(Result);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000194}
195
196class StoreDiagsConsumer : public DiagnosticConsumer {
197public:
198 StoreDiagsConsumer(std::vector<DiagWithFixIts> &Output) : Output(Output) {}
199
Sam McCall8111d3b2017-12-13 08:48:42 +0000200 // Track language options in case we need to expand token ranges.
201 void BeginSourceFile(const LangOptions &Opts, const Preprocessor *) override {
202 LangOpts = Opts;
203 }
204
205 void EndSourceFile() override { LangOpts = llvm::None; }
206
Ilya Biryukov04db3682017-07-21 13:29:29 +0000207 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
208 const clang::Diagnostic &Info) override {
209 DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
210
Sam McCall8111d3b2017-12-13 08:48:42 +0000211 if (LangOpts)
212 if (auto D = toClangdDiag(Info, DiagLevel, *LangOpts))
213 Output.push_back(std::move(*D));
Ilya Biryukov04db3682017-07-21 13:29:29 +0000214 }
215
216private:
217 std::vector<DiagWithFixIts> &Output;
Sam McCall8111d3b2017-12-13 08:48:42 +0000218 llvm::Optional<LangOptions> LangOpts;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000219};
220
Ilya Biryukov02d58702017-08-01 15:51:38 +0000221template <class T> bool futureIsReady(std::shared_future<T> const &Future) {
222 return Future.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
223}
224
Ilya Biryukov04db3682017-07-21 13:29:29 +0000225} // namespace
226
Ilya Biryukov02d58702017-08-01 15:51:38 +0000227void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
228 AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000229}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000230
Ilya Biryukov02d58702017-08-01 15:51:38 +0000231llvm::Optional<ParsedAST>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000232ParsedAST::Build(const Context &Ctx,
233 std::unique_ptr<clang::CompilerInvocation> CI,
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000234 std::shared_ptr<const PreambleData> Preamble,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000235 std::unique_ptr<llvm::MemoryBuffer> Buffer,
236 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000237 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000238
239 std::vector<DiagWithFixIts> ASTDiags;
240 StoreDiagsConsumer UnitDiagsConsumer(/*ref*/ ASTDiags);
241
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000242 const PrecompiledPreamble *PreamblePCH =
243 Preamble ? &Preamble->Preamble : nullptr;
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000244 auto Clang = prepareCompilerInstance(
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000245 std::move(CI), PreamblePCH, std::move(Buffer), std::move(PCHs),
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000246 std::move(VFS), /*ref*/ UnitDiagsConsumer);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000247
248 // Recover resources if we crash before exiting this method.
249 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
250 Clang.get());
251
252 auto Action = llvm::make_unique<ClangdFrontendAction>();
Ilya Biryukove5128f72017-09-20 07:24:15 +0000253 const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
254 if (!Action->BeginSourceFile(*Clang, MainInput)) {
Ilya Biryukov940901e2017-12-13 12:51:22 +0000255 log(Ctx, "BeginSourceFile() failed when building AST for " +
256 MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000257 return llvm::None;
258 }
Ilya Biryukove5128f72017-09-20 07:24:15 +0000259 if (!Action->Execute())
Ilya Biryukov940901e2017-12-13 12:51:22 +0000260 log(Ctx, "Execute() failed when building AST for " + MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000261
262 // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
263 // has a longer lifetime.
Sam McCall98775c52017-12-04 13:49:59 +0000264 Clang->getDiagnostics().setClient(new IgnoreDiagnostics);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000265
266 std::vector<const Decl *> ParsedDecls = Action->takeTopLevelDecls();
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000267 return ParsedAST(std::move(Preamble), std::move(Clang), std::move(Action),
268 std::move(ParsedDecls), std::move(ASTDiags));
Ilya Biryukov04db3682017-07-21 13:29:29 +0000269}
270
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000271namespace {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000272
273SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000274 const FileEntry *FE, Position Pos) {
275 SourceLocation InputLoc =
276 Mgr.translateFileLineCol(FE, Pos.line + 1, Pos.character + 1);
277 return Mgr.getMacroArgExpandedLocation(InputLoc);
278}
279
Ilya Biryukov02d58702017-08-01 15:51:38 +0000280} // namespace
Ilya Biryukov04db3682017-07-21 13:29:29 +0000281
Ilya Biryukov02d58702017-08-01 15:51:38 +0000282void ParsedAST::ensurePreambleDeclsDeserialized() {
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000283 if (PreambleDeclsDeserialized || !Preamble)
Ilya Biryukov04db3682017-07-21 13:29:29 +0000284 return;
285
286 std::vector<const Decl *> Resolved;
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000287 Resolved.reserve(Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000288
289 ExternalASTSource &Source = *getASTContext().getExternalSource();
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000290 for (serialization::DeclID TopLevelDecl : Preamble->TopLevelDeclIDs) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000291 // Resolve the declaration ID to an actual declaration, possibly
292 // deserializing the declaration in the process.
293 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
294 Resolved.push_back(D);
295 }
296
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000297 TopLevelDecls.reserve(TopLevelDecls.size() +
298 Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000299 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
300
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000301 PreambleDeclsDeserialized = true;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000302}
303
Ilya Biryukov02d58702017-08-01 15:51:38 +0000304ParsedAST::ParsedAST(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000305
Ilya Biryukov02d58702017-08-01 15:51:38 +0000306ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000307
Ilya Biryukov02d58702017-08-01 15:51:38 +0000308ParsedAST::~ParsedAST() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000309 if (Action) {
310 Action->EndSourceFile();
311 }
312}
313
Ilya Biryukov02d58702017-08-01 15:51:38 +0000314ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
315
316const ASTContext &ParsedAST::getASTContext() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000317 return Clang->getASTContext();
318}
319
Ilya Biryukov02d58702017-08-01 15:51:38 +0000320Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000321
Eric Liu76f6b442018-01-09 17:32:00 +0000322std::shared_ptr<Preprocessor> ParsedAST::getPreprocessorPtr() {
323 return Clang->getPreprocessorPtr();
324}
325
Ilya Biryukov02d58702017-08-01 15:51:38 +0000326const Preprocessor &ParsedAST::getPreprocessor() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000327 return Clang->getPreprocessor();
328}
329
Ilya Biryukov02d58702017-08-01 15:51:38 +0000330ArrayRef<const Decl *> ParsedAST::getTopLevelDecls() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000331 ensurePreambleDeclsDeserialized();
332 return TopLevelDecls;
333}
334
Ilya Biryukov02d58702017-08-01 15:51:38 +0000335const std::vector<DiagWithFixIts> &ParsedAST::getDiagnostics() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000336 return Diags;
337}
338
Ilya Biryukovdf842342018-01-25 14:32:21 +0000339std::size_t ParsedAST::getUsedBytes() const {
340 auto &AST = getASTContext();
341 // FIXME(ibiryukov): we do not account for the dynamically allocated part of
342 // SmallVector<FixIt> inside each Diag.
343 return AST.getASTAllocatedMemory() + AST.getSideTableAllocatedMemory() +
344 ::getUsedBytes(TopLevelDecls) + ::getUsedBytes(Diags);
345}
346
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000347PreambleData::PreambleData(PrecompiledPreamble Preamble,
348 std::vector<serialization::DeclID> TopLevelDeclIDs,
349 std::vector<DiagWithFixIts> Diags)
350 : Preamble(std::move(Preamble)),
351 TopLevelDeclIDs(std::move(TopLevelDeclIDs)), Diags(std::move(Diags)) {}
352
353ParsedAST::ParsedAST(std::shared_ptr<const PreambleData> Preamble,
354 std::unique_ptr<CompilerInstance> Clang,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000355 std::unique_ptr<FrontendAction> Action,
356 std::vector<const Decl *> TopLevelDecls,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000357 std::vector<DiagWithFixIts> Diags)
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000358 : Preamble(std::move(Preamble)), Clang(std::move(Clang)),
359 Action(std::move(Action)), Diags(std::move(Diags)),
360 TopLevelDecls(std::move(TopLevelDecls)),
361 PreambleDeclsDeserialized(false) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000362 assert(this->Clang);
363 assert(this->Action);
364}
365
Ilya Biryukov02d58702017-08-01 15:51:38 +0000366ParsedASTWrapper::ParsedASTWrapper(ParsedASTWrapper &&Wrapper)
367 : AST(std::move(Wrapper.AST)) {}
368
369ParsedASTWrapper::ParsedASTWrapper(llvm::Optional<ParsedAST> AST)
370 : AST(std::move(AST)) {}
371
Ilya Biryukov02d58702017-08-01 15:51:38 +0000372std::shared_ptr<CppFile>
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000373CppFile::Create(PathRef FileName, bool StorePreamblesInMemory,
Eric Liubfac8f72017-12-19 18:00:37 +0000374 std::shared_ptr<PCHContainerOperations> PCHs,
375 ASTParsedCallback ASTCallback) {
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000376 return std::shared_ptr<CppFile>(new CppFile(FileName, StorePreamblesInMemory,
377 std::move(PCHs),
378 std::move(ASTCallback)));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000379}
380
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000381CppFile::CppFile(PathRef FileName, bool StorePreamblesInMemory,
Eric Liubfac8f72017-12-19 18:00:37 +0000382 std::shared_ptr<PCHContainerOperations> PCHs,
383 ASTParsedCallback ASTCallback)
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000384 : FileName(FileName), StorePreamblesInMemory(StorePreamblesInMemory),
Ilya Biryukovdf842342018-01-25 14:32:21 +0000385 RebuildCounter(0), RebuildInProgress(false), ASTMemUsage(0),
386 PreambleMemUsage(0), PCHs(std::move(PCHs)),
Eric Liubfac8f72017-12-19 18:00:37 +0000387 ASTCallback(std::move(ASTCallback)) {
Ilya Biryukov940901e2017-12-13 12:51:22 +0000388 // FIXME(ibiryukov): we should pass a proper Context here.
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000389 log(Context::empty(), "Created CppFile for " + FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000390
391 std::lock_guard<std::mutex> Lock(Mutex);
392 LatestAvailablePreamble = nullptr;
393 PreamblePromise.set_value(nullptr);
394 PreambleFuture = PreamblePromise.get_future();
395
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000396 ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000397 ASTFuture = ASTPromise.get_future();
398}
399
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000400void CppFile::cancelRebuild() { deferCancelRebuild()(); }
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000401
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000402UniqueFunction<void()> CppFile::deferCancelRebuild() {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000403 std::unique_lock<std::mutex> Lock(Mutex);
404 // Cancel an ongoing rebuild, if any, and wait for it to finish.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000405 unsigned RequestRebuildCounter = ++this->RebuildCounter;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000406 // Rebuild asserts that futures aren't ready if rebuild is cancelled.
407 // We want to keep this invariant.
408 if (futureIsReady(PreambleFuture)) {
409 PreamblePromise = std::promise<std::shared_ptr<const PreambleData>>();
410 PreambleFuture = PreamblePromise.get_future();
411 }
412 if (futureIsReady(ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000413 ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000414 ASTFuture = ASTPromise.get_future();
415 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000416
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000417 Lock.unlock();
418 // Notify about changes to RebuildCounter.
419 RebuildCond.notify_all();
420
421 std::shared_ptr<CppFile> That = shared_from_this();
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000422 return [That, RequestRebuildCounter]() {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000423 std::unique_lock<std::mutex> Lock(That->Mutex);
424 CppFile *This = &*That;
425 This->RebuildCond.wait(Lock, [This, RequestRebuildCounter]() {
426 return !This->RebuildInProgress ||
427 This->RebuildCounter != RequestRebuildCounter;
428 });
429
430 // This computation got cancelled itself, do nothing.
431 if (This->RebuildCounter != RequestRebuildCounter)
432 return;
433
434 // Set empty results for Promises.
Ilya Biryukovdf842342018-01-25 14:32:21 +0000435 That->PreambleMemUsage = 0;
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000436 That->PreamblePromise.set_value(nullptr);
Ilya Biryukovdf842342018-01-25 14:32:21 +0000437 That->ASTMemUsage = 0;
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000438 That->ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000439 };
Ilya Biryukov02d58702017-08-01 15:51:38 +0000440}
441
442llvm::Optional<std::vector<DiagWithFixIts>>
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000443CppFile::rebuild(const Context &Ctx, ParseInputs &&Inputs) {
444 return deferRebuild(std::move(Inputs))(Ctx);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000445}
446
Ilya Biryukov940901e2017-12-13 12:51:22 +0000447UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>(const Context &)>
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000448CppFile::deferRebuild(ParseInputs &&Inputs) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000449 std::shared_ptr<const PreambleData> OldPreamble;
450 std::shared_ptr<PCHContainerOperations> PCHs;
451 unsigned RequestRebuildCounter;
452 {
453 std::unique_lock<std::mutex> Lock(Mutex);
454 // Increase RebuildCounter to cancel all ongoing FinishRebuild operations.
455 // They will try to exit as early as possible and won't call set_value on
456 // our promises.
457 RequestRebuildCounter = ++this->RebuildCounter;
458 PCHs = this->PCHs;
459
460 // Remember the preamble to be used during rebuild.
461 OldPreamble = this->LatestAvailablePreamble;
462 // Setup std::promises and std::futures for Preamble and AST. Corresponding
463 // futures will wait until the rebuild process is finished.
464 if (futureIsReady(this->PreambleFuture)) {
465 this->PreamblePromise =
466 std::promise<std::shared_ptr<const PreambleData>>();
467 this->PreambleFuture = this->PreamblePromise.get_future();
468 }
469 if (futureIsReady(this->ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000470 this->ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000471 this->ASTFuture = this->ASTPromise.get_future();
472 }
473 } // unlock Mutex.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000474 // Notify about changes to RebuildCounter.
475 RebuildCond.notify_all();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000476
477 // A helper to function to finish the rebuild. May be run on a different
478 // thread.
479
480 // Don't let this CppFile die before rebuild is finished.
481 std::shared_ptr<CppFile> That = shared_from_this();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000482 auto FinishRebuild =
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000483 [OldPreamble, RequestRebuildCounter, PCHs,
484 That](ParseInputs Inputs,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000485 const Context &Ctx) mutable /* to allow changing OldPreamble. */
Ilya Biryukov02d58702017-08-01 15:51:38 +0000486 -> llvm::Optional<std::vector<DiagWithFixIts>> {
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000487 log(Context::empty(),
488 "Rebuilding file " + That->FileName + " with command [" +
489 Inputs.CompileCommand.Directory + "] " +
490 llvm::join(Inputs.CompileCommand.CommandLine, " "));
491
Ilya Biryukov02d58702017-08-01 15:51:38 +0000492 // Only one execution of this method is possible at a time.
493 // RebuildGuard will wait for any ongoing rebuilds to finish and will put us
494 // into a state for doing a rebuild.
495 RebuildGuard Rebuild(*That, RequestRebuildCounter);
496 if (Rebuild.wasCancelledBeforeConstruction())
497 return llvm::None;
498
499 std::vector<const char *> ArgStrs;
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000500 for (const auto &S : Inputs.CompileCommand.CommandLine)
Ilya Biryukov02d58702017-08-01 15:51:38 +0000501 ArgStrs.push_back(S.c_str());
502
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000503 Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000504
505 std::unique_ptr<CompilerInvocation> CI;
506 {
507 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
508 // reporting them.
Sam McCall98775c52017-12-04 13:49:59 +0000509 IgnoreDiagnostics IgnoreDiagnostics;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000510 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
511 CompilerInstance::createDiagnostics(new DiagnosticOptions,
Sam McCall98775c52017-12-04 13:49:59 +0000512 &IgnoreDiagnostics, false);
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000513 CI = createInvocationFromCommandLine(ArgStrs, CommandLineDiagsEngine,
514 Inputs.FS);
Sam McCall98775c52017-12-04 13:49:59 +0000515 // createInvocationFromCommandLine sets DisableFree.
516 CI->getFrontendOpts().DisableFree = false;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000517 }
518 assert(CI && "Couldn't create CompilerInvocation");
519
520 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000521 llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents, That->FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000522
523 // A helper function to rebuild the preamble or reuse the existing one. Does
Ilya Biryukov11a02522017-11-17 19:05:56 +0000524 // not mutate any fields of CppFile, only does the actual computation.
525 // Lamdba is marked mutable to call reset() on OldPreamble.
526 auto DoRebuildPreamble =
527 [&]() mutable -> std::shared_ptr<const PreambleData> {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000528 auto Bounds =
529 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000530 if (OldPreamble &&
531 OldPreamble->Preamble.CanReuse(*CI, ContentsBuffer.get(), Bounds,
532 Inputs.FS.get())) {
Ilya Biryukoveaeea042017-12-21 14:05:28 +0000533 log(Ctx, "Reusing preamble for file " + Twine(That->FileName));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000534 return OldPreamble;
535 }
Ilya Biryukoveaeea042017-12-21 14:05:28 +0000536 log(Ctx, "Premble for file " + Twine(That->FileName) +
537 " cannot be reused. Attempting to rebuild it.");
538 // We won't need the OldPreamble anymore, release it so it can be
539 // deleted (if there are no other references to it).
Ilya Biryukov11a02522017-11-17 19:05:56 +0000540 OldPreamble.reset();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000541
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000542 trace::Span Tracer(Ctx, "Preamble");
Sam McCall9cfd9c92017-11-23 17:12:04 +0000543 SPAN_ATTACH(Tracer, "File", That->FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000544 std::vector<DiagWithFixIts> PreambleDiags;
545 StoreDiagsConsumer PreambleDiagnosticsConsumer(/*ref*/ PreambleDiags);
546 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
547 CompilerInstance::createDiagnostics(
548 &CI->getDiagnosticOpts(), &PreambleDiagnosticsConsumer, false);
Ilya Biryukovda8daa32017-12-28 13:10:15 +0000549
550 // Skip function bodies when building the preamble to speed up building
551 // the preamble and make it smaller.
552 assert(!CI->getFrontendOpts().SkipFunctionBodies);
553 CI->getFrontendOpts().SkipFunctionBodies = true;
554
Ilya Biryukov02d58702017-08-01 15:51:38 +0000555 CppFilePreambleCallbacks SerializedDeclsCollector;
556 auto BuiltPreamble = PrecompiledPreamble::Build(
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000557 *CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine, Inputs.FS,
558 PCHs,
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000559 /*StoreInMemory=*/That->StorePreamblesInMemory,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000560 SerializedDeclsCollector);
561
Ilya Biryukovda8daa32017-12-28 13:10:15 +0000562 // When building the AST for the main file, we do want the function
563 // bodies.
564 CI->getFrontendOpts().SkipFunctionBodies = false;
565
Ilya Biryukov02d58702017-08-01 15:51:38 +0000566 if (BuiltPreamble) {
Ilya Biryukoveaeea042017-12-21 14:05:28 +0000567 log(Ctx, "Built preamble of size " + Twine(BuiltPreamble->getSize()) +
568 " for file " + Twine(That->FileName));
569
Ilya Biryukov02d58702017-08-01 15:51:38 +0000570 return std::make_shared<PreambleData>(
571 std::move(*BuiltPreamble),
572 SerializedDeclsCollector.takeTopLevelDeclIDs(),
573 std::move(PreambleDiags));
574 } else {
Ilya Biryukoveaeea042017-12-21 14:05:28 +0000575 log(Ctx,
576 "Could not build a preamble for file " + Twine(That->FileName));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000577 return nullptr;
578 }
579 };
580
581 // Compute updated Preamble.
582 std::shared_ptr<const PreambleData> NewPreamble = DoRebuildPreamble();
583 // Publish the new Preamble.
584 {
585 std::lock_guard<std::mutex> Lock(That->Mutex);
586 // We always set LatestAvailablePreamble to the new value, hoping that it
587 // will still be usable in the further requests.
588 That->LatestAvailablePreamble = NewPreamble;
589 if (RequestRebuildCounter != That->RebuildCounter)
590 return llvm::None; // Our rebuild request was cancelled, do nothing.
Ilya Biryukovdf842342018-01-25 14:32:21 +0000591 That->PreambleMemUsage =
592 NewPreamble ? NewPreamble->Preamble.getSize() : 0;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000593 That->PreamblePromise.set_value(NewPreamble);
594 } // unlock Mutex
595
596 // Prepare the Preamble and supplementary data for rebuilding AST.
Ilya Biryukov02d58702017-08-01 15:51:38 +0000597 std::vector<DiagWithFixIts> Diagnostics;
598 if (NewPreamble) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000599 Diagnostics.insert(Diagnostics.begin(), NewPreamble->Diags.begin(),
600 NewPreamble->Diags.end());
601 }
602
603 // Compute updated AST.
Sam McCall8567cb32017-11-02 09:21:51 +0000604 llvm::Optional<ParsedAST> NewAST;
605 {
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000606 trace::Span Tracer(Ctx, "Build");
Sam McCall9cfd9c92017-11-23 17:12:04 +0000607 SPAN_ATTACH(Tracer, "File", That->FileName);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000608 NewAST = ParsedAST::Build(Ctx, std::move(CI), std::move(NewPreamble),
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000609 std::move(ContentsBuffer), PCHs, Inputs.FS);
Sam McCall8567cb32017-11-02 09:21:51 +0000610 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000611
612 if (NewAST) {
613 Diagnostics.insert(Diagnostics.end(), NewAST->getDiagnostics().begin(),
614 NewAST->getDiagnostics().end());
Eric Liubfac8f72017-12-19 18:00:37 +0000615 if (That->ASTCallback)
616 That->ASTCallback(Ctx, That->FileName, NewAST.getPointer());
Ilya Biryukov02d58702017-08-01 15:51:38 +0000617 } else {
618 // Don't report even Preamble diagnostics if we coulnd't build AST.
619 Diagnostics.clear();
620 }
621
622 // Publish the new AST.
623 {
624 std::lock_guard<std::mutex> Lock(That->Mutex);
625 if (RequestRebuildCounter != That->RebuildCounter)
626 return Diagnostics; // Our rebuild request was cancelled, don't set
627 // ASTPromise.
628
Ilya Biryukovdf842342018-01-25 14:32:21 +0000629 That->ASTMemUsage = NewAST ? NewAST->getUsedBytes() : 0;
Ilya Biryukov574b7532017-08-02 09:08:39 +0000630 That->ASTPromise.set_value(
631 std::make_shared<ParsedASTWrapper>(std::move(NewAST)));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000632 } // unlock Mutex
633
634 return Diagnostics;
635 };
636
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000637 return BindWithForward(FinishRebuild, std::move(Inputs));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000638}
639
640std::shared_future<std::shared_ptr<const PreambleData>>
641CppFile::getPreamble() const {
642 std::lock_guard<std::mutex> Lock(Mutex);
643 return PreambleFuture;
644}
645
646std::shared_ptr<const PreambleData> CppFile::getPossiblyStalePreamble() const {
647 std::lock_guard<std::mutex> Lock(Mutex);
648 return LatestAvailablePreamble;
649}
650
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000651std::shared_future<std::shared_ptr<ParsedASTWrapper>> CppFile::getAST() const {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000652 std::lock_guard<std::mutex> Lock(Mutex);
653 return ASTFuture;
654}
655
Ilya Biryukovdf842342018-01-25 14:32:21 +0000656std::size_t CppFile::getUsedBytes() const {
657 std::lock_guard<std::mutex> Lock(Mutex);
658 // FIXME: We should not store extra size fields. When we store AST and
659 // Preamble directly, not inside futures, we could compute the sizes from the
660 // stored AST and the preamble in this function directly.
661 return ASTMemUsage + PreambleMemUsage;
662}
663
Ilya Biryukov02d58702017-08-01 15:51:38 +0000664CppFile::RebuildGuard::RebuildGuard(CppFile &File,
665 unsigned RequestRebuildCounter)
666 : File(File), RequestRebuildCounter(RequestRebuildCounter) {
667 std::unique_lock<std::mutex> Lock(File.Mutex);
668 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
669 if (WasCancelledBeforeConstruction)
670 return;
671
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000672 File.RebuildCond.wait(Lock, [&File, RequestRebuildCounter]() {
673 return !File.RebuildInProgress ||
674 File.RebuildCounter != RequestRebuildCounter;
675 });
Ilya Biryukov02d58702017-08-01 15:51:38 +0000676
677 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
678 if (WasCancelledBeforeConstruction)
679 return;
680
681 File.RebuildInProgress = true;
682}
683
684bool CppFile::RebuildGuard::wasCancelledBeforeConstruction() const {
685 return WasCancelledBeforeConstruction;
686}
687
688CppFile::RebuildGuard::~RebuildGuard() {
689 if (WasCancelledBeforeConstruction)
690 return;
691
692 std::unique_lock<std::mutex> Lock(File.Mutex);
693 assert(File.RebuildInProgress);
694 File.RebuildInProgress = false;
695
696 if (File.RebuildCounter == RequestRebuildCounter) {
697 // Our rebuild request was successful.
698 assert(futureIsReady(File.ASTFuture));
699 assert(futureIsReady(File.PreambleFuture));
700 } else {
701 // Our rebuild request was cancelled, because further reparse was requested.
702 assert(!futureIsReady(File.ASTFuture));
703 assert(!futureIsReady(File.PreambleFuture));
704 }
705
706 Lock.unlock();
707 File.RebuildCond.notify_all();
708}
Haojian Wu345099c2017-11-09 11:30:04 +0000709
710SourceLocation clangd::getBeginningOfIdentifier(ParsedAST &Unit,
711 const Position &Pos,
712 const FileEntry *FE) {
713 // The language server protocol uses zero-based line and column numbers.
714 // Clang uses one-based numbers.
715
716 const ASTContext &AST = Unit.getASTContext();
717 const SourceManager &SourceMgr = AST.getSourceManager();
718
719 SourceLocation InputLocation =
720 getMacroArgExpandedLocation(SourceMgr, FE, Pos);
721 if (Pos.character == 0) {
722 return InputLocation;
723 }
724
725 // This handle cases where the position is in the middle of a token or right
726 // after the end of a token. In theory we could just use GetBeginningOfToken
727 // to find the start of the token at the input position, but this doesn't
728 // work when right after the end, i.e. foo|.
729 // So try to go back by one and see if we're still inside the an identifier
730 // token. If so, Take the beginning of this token.
731 // (It should be the same identifier because you can't have two adjacent
732 // identifiers without another token in between.)
733 SourceLocation PeekBeforeLocation = getMacroArgExpandedLocation(
734 SourceMgr, FE, Position{Pos.line, Pos.character - 1});
735 Token Result;
736 if (Lexer::getRawToken(PeekBeforeLocation, Result, SourceMgr,
737 AST.getLangOpts(), false)) {
738 // getRawToken failed, just use InputLocation.
739 return InputLocation;
740 }
741
742 if (Result.is(tok::raw_identifier)) {
743 return Lexer::GetBeginningOfToken(PeekBeforeLocation, SourceMgr,
744 AST.getLangOpts());
745 }
746
747 return InputLocation;
748}