2018-02-08 15:37:35 +08:00
|
|
|
//===--- TUScheduler.cpp -----------------------------------------*-C++-*-===//
|
|
|
|
//
|
2019-01-19 16:50:56 +08:00
|
|
|
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
|
|
|
|
// See https://llvm.org/LICENSE.txt for license information.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
2018-02-08 15:37:35 +08:00
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
2020-03-16 04:43:00 +08:00
|
|
|
// TUScheduler manages a worker per active file. This ASTWorker processes
|
|
|
|
// updates (modifications to file contents) and reads (actions performed on
|
|
|
|
// preamble/AST) to the file.
|
2018-02-08 15:37:35 +08:00
|
|
|
//
|
2020-03-16 04:43:00 +08:00
|
|
|
// Each ASTWorker owns a dedicated thread to process updates and reads to the
|
|
|
|
// relevant file. Any request gets queued in FIFO order to be processed by that
|
|
|
|
// thread.
|
2018-02-08 15:37:35 +08:00
|
|
|
//
|
2020-03-16 04:43:00 +08:00
|
|
|
// An update request replaces current praser inputs to ensure any subsequent
|
|
|
|
// read sees the version of the file they were requested. It will also issue a
|
|
|
|
// build for new inputs.
|
2018-02-08 15:37:35 +08:00
|
|
|
//
|
2020-03-16 04:43:00 +08:00
|
|
|
// ASTWorker processes the file in two parts, a preamble and a main-file
|
|
|
|
// section. A preamble can be reused between multiple versions of the file until
|
|
|
|
// invalidated by a modification to a header, compile commands or modification
|
|
|
|
// to relevant part of the current file. Such a preamble is called compatible.
|
|
|
|
// An update is considered dead if no read was issued for that version and
|
|
|
|
// diagnostics weren't requested by client or could be generated for a later
|
|
|
|
// version of the file. ASTWorker eliminates such requests as they are
|
|
|
|
// redundant.
|
2018-02-08 15:37:35 +08:00
|
|
|
//
|
2020-03-16 04:43:00 +08:00
|
|
|
// In the presence of stale (non-compatible) preambles, ASTWorker won't publish
|
|
|
|
// diagnostics for update requests. Read requests will be served with ASTs build
|
|
|
|
// with stale preambles, unless the read is picky and requires a compatible
|
|
|
|
// preamble. In such cases it will block until new preamble is built.
|
|
|
|
//
|
|
|
|
// ASTWorker owns a PreambleThread for building preambles. If the preamble gets
|
|
|
|
// invalidated by an update request, a new build will be requested on
|
|
|
|
// PreambleThread. Since PreambleThread only receives requests for newer
|
|
|
|
// versions of the file, in case of multiple requests it will only build the
|
|
|
|
// last one and skip requests in between. Unless client force requested
|
|
|
|
// diagnostics(WantDiagnostics::Yes).
|
|
|
|
//
|
|
|
|
// When a new preamble is built, a "golden" AST is immediately built from that
|
|
|
|
// version of the file. This ensures diagnostics get updated even if the queue
|
|
|
|
// is full.
|
|
|
|
//
|
|
|
|
// Some read requests might just need preamble. Since preambles can be read
|
|
|
|
// concurrently, ASTWorker runs these requests on their own thread. These
|
|
|
|
// requests will receive latest build preamble, which might possibly be stale.
|
2018-02-08 15:37:35 +08:00
|
|
|
|
2018-01-31 16:51:16 +08:00
|
|
|
#include "TUScheduler.h"
|
[clangd] Respect task cancellation in TUScheduler.
Summary:
- Reads are never executed if canceled before ready-to run.
In practice, we finalize cancelled reads eagerly and out-of-order.
- Cancelled reads don't prevent prior updates from being elided, as they don't
actually depend on the result of the update.
- Updates are downgraded from WantDiagnostics::Yes to WantDiagnostics::Auto when
cancelled, which allows them to be elided when all dependent reads are
cancelled and there are subsequent writes. (e.g. when the queue is backed up
with cancelled requests).
The queue operations aren't optimal (we scan the whole queue for cancelled
tasks every time the scheduler runs, and check cancellation twice in the end).
However I believe these costs are still trivial in practice (compared to any
AST operation) and the logic can be cleanly separated from the rest of the
scheduler.
Reviewers: ilya-biryukov
Subscribers: javed.absar, ioeric, MaskRay, jkorous, arphaman, kadircet, cfe-commits
Differential Revision: https://reviews.llvm.org/D54746
llvm-svn: 347450
2018-11-22 18:22:16 +08:00
|
|
|
#include "Cancellation.h"
|
2019-04-15 20:32:28 +08:00
|
|
|
#include "Compiler.h"
|
2019-10-23 16:18:09 +08:00
|
|
|
#include "Context.h"
|
[clangd] Surface errors from command-line parsing
Summary:
Those errors are exposed at the first character of a file,
for a lack of a better place.
Previously, all errors were stored inside the AST and report
accordingly. However, errors in command-line argument parsing could
result in failure to produce the AST, so we need an alternative ways to
report those errors.
We take the following approach in this patch:
- buildCompilerInvocation() now requires an explicit DiagnosticConsumer.
- TUScheduler and TestTU now collect the diagnostics produced when
parsing command line arguments.
If pasing of the AST failed, diagnostics are reported via a new
ParsingCallbacks::onFailedAST method.
If parsing of the AST succeeded, any errors produced during
command-line parsing are stored alongside the AST inside the
ParsedAST instance and reported as previously by calling the
ParsingCallbacks::onMainAST method;
- The client code that uses ClangdServer's DiagnosticConsumer
does not need to change, it will receive new diagnostics in the
onDiagnosticsReady() callback
Errors produced when parsing command-line arguments are collected using
the same StoreDiags class that is used to collect all other errors. They
are recognized by their location being invalid. IIUC, the location is
invalid as there is no source manager at this point, it is created at a
later stage.
Although technically we might also get diagnostics that mention the
command-line arguments FileID with after the source manager was created
(and they have valid source locations), we choose to not handle those
and they are dropped as not coming from the main file. AFAICT, those
diagnostics should always be notes, therefore it's safe to drop them
without loosing too much information.
Reviewers: kadircet
Reviewed By: kadircet
Subscribers: nridge, javed.absar, MaskRay, jkorous, arphaman, cfe-commits, gribozavr
Tags: #clang
Differential Revision: https://reviews.llvm.org/D66759
llvm-svn: 370177
2019-08-28 17:24:55 +08:00
|
|
|
#include "Diagnostics.h"
|
2019-04-15 20:32:28 +08:00
|
|
|
#include "GlobalCompilationDatabase.h"
|
2018-02-08 15:37:35 +08:00
|
|
|
#include "Logger.h"
|
2019-09-04 17:46:06 +08:00
|
|
|
#include "ParsedAST.h"
|
2020-03-13 18:52:19 +08:00
|
|
|
#include "Path.h"
|
2019-09-04 15:35:00 +08:00
|
|
|
#include "Preamble.h"
|
2020-03-13 18:52:19 +08:00
|
|
|
#include "Threading.h"
|
2018-02-19 17:56:28 +08:00
|
|
|
#include "Trace.h"
|
2019-02-05 00:19:57 +08:00
|
|
|
#include "index/CanonicalIncludes.h"
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
#include "clang/Frontend/CompilerInvocation.h"
|
2019-04-15 20:32:28 +08:00
|
|
|
#include "clang/Tooling/CompilationDatabase.h"
|
2020-03-16 04:43:00 +08:00
|
|
|
#include "llvm/ADT/FunctionExtras.h"
|
|
|
|
#include "llvm/ADT/None.h"
|
[clangd] Add fallback mode for code completion when compile command or preamble is not ready.
Summary:
When calling TUScehduler::runWithPreamble (e.g. in code compleiton), allow
entering a fallback mode when compile command or preamble is not ready, instead of
waiting. This allows clangd to perform naive code completion e.g. using identifiers
in the current file or symbols in the index.
This patch simply returns empty result for code completion in fallback mode. Identifier-based
plus more advanced index-based completion will be added in followup patches.
Reviewers: ilya-biryukov, sammccall
Reviewed By: sammccall
Subscribers: sammccall, javed.absar, MaskRay, jkorous, arphaman, kadircet, jdoerfert, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D59811
llvm-svn: 357916
2019-04-08 22:53:16 +08:00
|
|
|
#include "llvm/ADT/Optional.h"
|
2020-03-18 02:08:23 +08:00
|
|
|
#include "llvm/ADT/STLExtras.h"
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
#include "llvm/ADT/ScopeExit.h"
|
2020-03-18 02:08:23 +08:00
|
|
|
#include "llvm/ADT/SmallVector.h"
|
|
|
|
#include "llvm/ADT/StringExtras.h"
|
2020-03-13 18:52:19 +08:00
|
|
|
#include "llvm/ADT/StringRef.h"
|
2018-01-31 16:51:16 +08:00
|
|
|
#include "llvm/Support/Errc.h"
|
2020-03-18 02:08:23 +08:00
|
|
|
#include "llvm/Support/ErrorHandling.h"
|
2020-03-16 04:43:00 +08:00
|
|
|
#include "llvm/Support/FormatVariadic.h"
|
2018-02-19 17:56:28 +08:00
|
|
|
#include "llvm/Support/Path.h"
|
clangd: use -j for background index pool
Summary:
clangd supports a -j option to limit the amount of threads to use for parsing
TUs. However, when using -background-index (the default in later versions of
clangd), the parallelism used by clangd defaults to the hardware_parallelisn,
i.e. number of physical cores.
On shared hardware environments, with large projects, this can significantly
affect performance with no way to tune it down.
This change makes the -j parameter apply equally to parsing and background
index. It's not perfect, because the total number of threads is 2x the -j value,
which may still be unexpected. But at least this change allows users to prevent
clangd using all CPU cores.
Reviewers: kadircet, sammccall
Reviewed By: sammccall
Subscribers: javed.absar, jfb, sammccall, ilya-biryukov, MaskRay, jkorous, arphaman, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D66031
llvm-svn: 368498
2019-08-10 07:03:32 +08:00
|
|
|
#include "llvm/Support/Threading.h"
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
#include <algorithm>
|
2020-03-16 04:43:00 +08:00
|
|
|
#include <chrono>
|
|
|
|
#include <functional>
|
2018-02-08 15:37:35 +08:00
|
|
|
#include <memory>
|
2020-02-04 22:41:39 +08:00
|
|
|
#include <mutex>
|
2018-02-08 15:37:35 +08:00
|
|
|
#include <queue>
|
2020-03-18 02:08:23 +08:00
|
|
|
#include <string>
|
2018-02-09 18:17:23 +08:00
|
|
|
#include <thread>
|
2020-03-16 04:43:00 +08:00
|
|
|
#include <type_traits>
|
|
|
|
#include <utility>
|
|
|
|
#include <vector>
|
2018-01-31 16:51:16 +08:00
|
|
|
|
|
|
|
namespace clang {
|
|
|
|
namespace clangd {
|
2018-03-02 16:56:37 +08:00
|
|
|
using std::chrono::steady_clock;
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
|
|
|
|
namespace {
|
|
|
|
class ASTWorker;
|
2019-01-25 23:14:03 +08:00
|
|
|
} // namespace
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
|
2018-08-09 17:25:26 +08:00
|
|
|
static clang::clangd::Key<std::string> kFileBeingProcessed;
|
2018-08-09 17:05:45 +08:00
|
|
|
|
2019-01-07 23:45:19 +08:00
|
|
|
llvm::Optional<llvm::StringRef> TUScheduler::getFileBeingProcessedInContext() {
|
2018-08-09 17:05:45 +08:00
|
|
|
if (auto *File = Context::current().get(kFileBeingProcessed))
|
2019-01-07 23:45:19 +08:00
|
|
|
return llvm::StringRef(*File);
|
2018-10-20 23:30:37 +08:00
|
|
|
return None;
|
2018-08-09 17:05:45 +08:00
|
|
|
}
|
|
|
|
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
/// An LRU cache of idle ASTs.
|
|
|
|
/// Because we want to limit the overall number of these we retain, the cache
|
|
|
|
/// owns ASTs (and may evict them) while their workers are idle.
|
|
|
|
/// Workers borrow ASTs when active, and return them when done.
|
|
|
|
class TUScheduler::ASTCache {
|
|
|
|
public:
|
|
|
|
using Key = const ASTWorker *;
|
|
|
|
|
|
|
|
ASTCache(unsigned MaxRetainedASTs) : MaxRetainedASTs(MaxRetainedASTs) {}
|
|
|
|
|
|
|
|
/// Returns result of getUsedBytes() for the AST cached by \p K.
|
|
|
|
/// If no AST is cached, 0 is returned.
|
2018-06-01 22:44:57 +08:00
|
|
|
std::size_t getUsedBytes(Key K) {
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
std::lock_guard<std::mutex> Lock(Mut);
|
|
|
|
auto It = findByKey(K);
|
|
|
|
if (It == LRU.end() || !It->second)
|
|
|
|
return 0;
|
|
|
|
return It->second->getUsedBytes();
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Store the value in the pool, possibly removing the last used AST.
|
|
|
|
/// The value should not be in the pool when this function is called.
|
|
|
|
void put(Key K, std::unique_ptr<ParsedAST> V) {
|
|
|
|
std::unique_lock<std::mutex> Lock(Mut);
|
|
|
|
assert(findByKey(K) == LRU.end());
|
|
|
|
|
|
|
|
LRU.insert(LRU.begin(), {K, std::move(V)});
|
|
|
|
if (LRU.size() <= MaxRetainedASTs)
|
|
|
|
return;
|
|
|
|
// We're past the limit, remove the last element.
|
|
|
|
std::unique_ptr<ParsedAST> ForCleanup = std::move(LRU.back().second);
|
|
|
|
LRU.pop_back();
|
|
|
|
// Run the expensive destructor outside the lock.
|
|
|
|
Lock.unlock();
|
|
|
|
ForCleanup.reset();
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the cached value for \p K, or llvm::None if the value is not in
|
|
|
|
/// the cache anymore. If nullptr was cached for \p K, this function will
|
|
|
|
/// return a null unique_ptr wrapped into an optional.
|
2019-01-07 23:45:19 +08:00
|
|
|
llvm::Optional<std::unique_ptr<ParsedAST>> take(Key K) {
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
std::unique_lock<std::mutex> Lock(Mut);
|
|
|
|
auto Existing = findByKey(K);
|
|
|
|
if (Existing == LRU.end())
|
2018-10-20 23:30:37 +08:00
|
|
|
return None;
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
std::unique_ptr<ParsedAST> V = std::move(Existing->second);
|
|
|
|
LRU.erase(Existing);
|
2018-06-01 20:03:16 +08:00
|
|
|
// GCC 4.8 fails to compile `return V;`, as it tries to call the copy
|
|
|
|
// constructor of unique_ptr, so we call the move ctor explicitly to avoid
|
|
|
|
// this miscompile.
|
2019-01-07 23:45:19 +08:00
|
|
|
return llvm::Optional<std::unique_ptr<ParsedAST>>(std::move(V));
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
using KVPair = std::pair<Key, std::unique_ptr<ParsedAST>>;
|
|
|
|
|
|
|
|
std::vector<KVPair>::iterator findByKey(Key K) {
|
2018-10-07 22:49:41 +08:00
|
|
|
return llvm::find_if(LRU, [K](const KVPair &P) { return P.first == K; });
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
std::mutex Mut;
|
|
|
|
unsigned MaxRetainedASTs;
|
|
|
|
/// Items sorted in LRU order, i.e. first item is the most recently accessed
|
|
|
|
/// one.
|
|
|
|
std::vector<KVPair> LRU; /* GUARDED_BY(Mut) */
|
|
|
|
};
|
|
|
|
|
2018-02-08 15:37:35 +08:00
|
|
|
namespace {
|
2020-03-18 02:08:23 +08:00
|
|
|
/// Threadsafe manager for updating a TUStatus and emitting it after each
|
|
|
|
/// update.
|
|
|
|
class SynchronizedTUStatus {
|
|
|
|
public:
|
|
|
|
SynchronizedTUStatus(PathRef FileName, ParsingCallbacks &Callbacks)
|
|
|
|
: FileName(FileName), Callbacks(Callbacks) {}
|
|
|
|
|
|
|
|
void update(llvm::function_ref<void(TUStatus &)> Mutator) {
|
|
|
|
std::lock_guard<std::mutex> Lock(StatusMu);
|
|
|
|
Mutator(Status);
|
|
|
|
emitStatusLocked();
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Prevents emitting of further updates.
|
|
|
|
void stop() {
|
|
|
|
std::lock_guard<std::mutex> Lock(StatusMu);
|
|
|
|
CanPublish = false;
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
void emitStatusLocked() {
|
|
|
|
if (CanPublish)
|
|
|
|
Callbacks.onFileUpdated(FileName, Status);
|
|
|
|
}
|
|
|
|
|
|
|
|
const Path FileName;
|
|
|
|
|
|
|
|
std::mutex StatusMu;
|
|
|
|
TUStatus Status;
|
|
|
|
bool CanPublish = true;
|
|
|
|
ParsingCallbacks &Callbacks;
|
|
|
|
};
|
|
|
|
|
2020-03-16 04:43:00 +08:00
|
|
|
/// Responsible for building preambles. Whenever the thread is idle and the
|
|
|
|
/// preamble is outdated, it starts to build a fresh preamble from the latest
|
|
|
|
/// inputs. If RunSync is true, preambles are built synchronously in update()
|
|
|
|
/// instead.
|
2020-03-13 18:52:19 +08:00
|
|
|
class PreambleThread {
|
|
|
|
public:
|
|
|
|
PreambleThread(llvm::StringRef FileName, ParsingCallbacks &Callbacks,
|
2020-03-18 02:08:23 +08:00
|
|
|
bool StorePreambleInMemory, bool RunSync,
|
2020-03-16 04:43:00 +08:00
|
|
|
SynchronizedTUStatus &Status, ASTWorker &AW)
|
2020-03-13 18:52:19 +08:00
|
|
|
: FileName(FileName), Callbacks(Callbacks),
|
2020-03-16 04:43:00 +08:00
|
|
|
StoreInMemory(StorePreambleInMemory), RunSync(RunSync), Status(Status),
|
|
|
|
ASTPeer(AW) {}
|
2020-03-13 18:52:19 +08:00
|
|
|
|
|
|
|
/// It isn't guaranteed that each requested version will be built. If there
|
|
|
|
/// are multiple update requests while building a preamble, only the last one
|
|
|
|
/// will be built.
|
2020-03-16 04:43:00 +08:00
|
|
|
void update(std::unique_ptr<CompilerInvocation> CI, ParseInputs PI,
|
|
|
|
std::vector<Diag> CIDiags, WantDiagnostics WantDiags) {
|
|
|
|
Request Req = {std::move(CI), std::move(PI), std::move(CIDiags), WantDiags,
|
|
|
|
Context::current().clone()};
|
2020-03-13 18:52:19 +08:00
|
|
|
if (RunSync) {
|
|
|
|
build(std::move(Req));
|
2020-03-18 02:08:23 +08:00
|
|
|
Status.update([](TUStatus &Status) {
|
|
|
|
Status.PreambleActivity = PreambleAction::Idle;
|
|
|
|
});
|
2020-03-13 18:52:19 +08:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
{
|
|
|
|
std::lock_guard<std::mutex> Lock(Mutex);
|
2020-03-16 04:43:00 +08:00
|
|
|
// If shutdown is issued, don't bother building.
|
|
|
|
if (Done)
|
|
|
|
return;
|
2020-03-13 18:52:19 +08:00
|
|
|
NextReq = std::move(Req);
|
|
|
|
}
|
|
|
|
// Let the worker thread know there's a request, notify_one is safe as there
|
|
|
|
// should be a single worker thread waiting on it.
|
|
|
|
ReqCV.notify_all();
|
|
|
|
}
|
|
|
|
|
|
|
|
void run() {
|
|
|
|
while (true) {
|
|
|
|
{
|
|
|
|
std::unique_lock<std::mutex> Lock(Mutex);
|
|
|
|
assert(!CurrentReq && "Already processing a request?");
|
|
|
|
// Wait until stop is called or there is a request.
|
|
|
|
ReqCV.wait(Lock, [this] { return NextReq || Done; });
|
|
|
|
if (Done)
|
|
|
|
break;
|
|
|
|
CurrentReq = std::move(*NextReq);
|
|
|
|
NextReq.reset();
|
|
|
|
}
|
2020-03-16 04:43:00 +08:00
|
|
|
|
|
|
|
WithContext Guard(std::move(CurrentReq->Ctx));
|
2020-03-13 18:52:19 +08:00
|
|
|
// Build the preamble and let the waiters know about it.
|
|
|
|
build(std::move(*CurrentReq));
|
2020-03-18 02:08:23 +08:00
|
|
|
bool IsEmpty = false;
|
2020-03-13 18:52:19 +08:00
|
|
|
{
|
|
|
|
std::lock_guard<std::mutex> Lock(Mutex);
|
|
|
|
CurrentReq.reset();
|
2020-03-18 02:08:23 +08:00
|
|
|
IsEmpty = !NextReq.hasValue();
|
|
|
|
}
|
|
|
|
if (IsEmpty) {
|
|
|
|
// We don't perform this above, before waiting for a request to make
|
|
|
|
// tests more deterministic. As there can be a race between this thread
|
|
|
|
// and client thread(clangdserver).
|
|
|
|
Status.update([](TUStatus &Status) {
|
|
|
|
Status.PreambleActivity = PreambleAction::Idle;
|
|
|
|
});
|
2020-03-13 18:52:19 +08:00
|
|
|
}
|
|
|
|
ReqCV.notify_all();
|
|
|
|
}
|
2020-03-16 04:43:00 +08:00
|
|
|
dlog("Preamble worker for {0} stopped", FileName);
|
2020-03-13 18:52:19 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Signals the run loop to exit.
|
|
|
|
void stop() {
|
2020-03-16 04:43:00 +08:00
|
|
|
dlog("Preamble worker for {0} received stop", FileName);
|
2020-03-13 18:52:19 +08:00
|
|
|
{
|
|
|
|
std::lock_guard<std::mutex> Lock(Mutex);
|
|
|
|
Done = true;
|
2020-03-16 04:43:00 +08:00
|
|
|
NextReq.reset();
|
2020-03-13 18:52:19 +08:00
|
|
|
}
|
|
|
|
// Let the worker thread know that it should stop.
|
|
|
|
ReqCV.notify_all();
|
|
|
|
}
|
|
|
|
|
|
|
|
bool blockUntilIdle(Deadline Timeout) const {
|
|
|
|
std::unique_lock<std::mutex> Lock(Mutex);
|
|
|
|
return wait(Lock, ReqCV, Timeout, [&] { return !NextReq && !CurrentReq; });
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
/// Holds inputs required for building a preamble. CI is guaranteed to be
|
|
|
|
/// non-null.
|
|
|
|
struct Request {
|
|
|
|
std::unique_ptr<CompilerInvocation> CI;
|
|
|
|
ParseInputs Inputs;
|
2020-03-16 04:43:00 +08:00
|
|
|
std::vector<Diag> CIDiags;
|
|
|
|
WantDiagnostics WantDiags;
|
|
|
|
Context Ctx;
|
2020-03-13 18:52:19 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
bool isDone() {
|
|
|
|
std::lock_guard<std::mutex> Lock(Mutex);
|
|
|
|
return Done;
|
|
|
|
}
|
|
|
|
|
2020-03-16 04:43:00 +08:00
|
|
|
/// Builds a preamble for \p Req, might reuse LatestBuild if possible.
|
|
|
|
/// Notifies ASTWorker after build finishes.
|
|
|
|
void build(Request Req);
|
2020-03-13 18:52:19 +08:00
|
|
|
|
|
|
|
mutable std::mutex Mutex;
|
|
|
|
bool Done = false; /* GUARDED_BY(Mutex) */
|
|
|
|
llvm::Optional<Request> NextReq; /* GUARDED_BY(Mutex) */
|
|
|
|
llvm::Optional<Request> CurrentReq; /* GUARDED_BY(Mutex) */
|
|
|
|
// Signaled whenever a thread populates NextReq or worker thread builds a
|
|
|
|
// Preamble.
|
2020-03-16 04:43:00 +08:00
|
|
|
mutable std::condition_variable ReqCV; /* GUARDED_BY(Mutex) */
|
|
|
|
// Accessed only by preamble thread.
|
|
|
|
std::shared_ptr<const PreambleData> LatestBuild;
|
2020-03-13 18:52:19 +08:00
|
|
|
|
|
|
|
const Path FileName;
|
|
|
|
ParsingCallbacks &Callbacks;
|
|
|
|
const bool StoreInMemory;
|
|
|
|
const bool RunSync;
|
2020-03-18 02:08:23 +08:00
|
|
|
|
|
|
|
SynchronizedTUStatus &Status;
|
2020-03-16 04:43:00 +08:00
|
|
|
ASTWorker &ASTPeer;
|
2020-03-13 18:52:19 +08:00
|
|
|
};
|
|
|
|
|
2018-02-08 15:37:35 +08:00
|
|
|
class ASTWorkerHandle;
|
|
|
|
|
|
|
|
/// Owns one instance of the AST, schedules updates and reads of it.
|
|
|
|
/// Also responsible for building and providing access to the preamble.
|
|
|
|
/// Each ASTWorker processes the async requests sent to it on a separate
|
|
|
|
/// dedicated thread.
|
|
|
|
/// The ASTWorker that manages the AST is shared by both the processing thread
|
|
|
|
/// and the TUScheduler. The TUScheduler should discard an ASTWorker when
|
|
|
|
/// remove() is called, but its thread may be busy and we don't want to block.
|
|
|
|
/// So the workers are accessed via an ASTWorkerHandle. Destroying the handle
|
|
|
|
/// signals the worker to exit its run loop and gives up shared ownership of the
|
|
|
|
/// worker.
|
|
|
|
class ASTWorker {
|
|
|
|
friend class ASTWorkerHandle;
|
2019-04-15 20:32:28 +08:00
|
|
|
ASTWorker(PathRef FileName, const GlobalCompilationDatabase &CDB,
|
|
|
|
TUScheduler::ASTCache &LRUCache, Semaphore &Barrier, bool RunSync,
|
2020-02-04 22:41:39 +08:00
|
|
|
DebouncePolicy UpdateDebounce, bool StorePreamblesInMemory,
|
2019-04-15 20:32:28 +08:00
|
|
|
ParsingCallbacks &Callbacks);
|
2018-02-08 15:37:35 +08:00
|
|
|
|
|
|
|
public:
|
|
|
|
/// Create a new ASTWorker and return a handle to it.
|
|
|
|
/// The processing thread is spawned using \p Tasks. However, when \p Tasks
|
|
|
|
/// is null, all requests will be processed on the calling thread
|
|
|
|
/// synchronously instead. \p Barrier is acquired when processing each
|
2018-09-14 08:56:11 +08:00
|
|
|
/// request, it is used to limit the number of actively running threads.
|
2019-04-15 20:32:28 +08:00
|
|
|
static ASTWorkerHandle
|
|
|
|
create(PathRef FileName, const GlobalCompilationDatabase &CDB,
|
|
|
|
TUScheduler::ASTCache &IdleASTs, AsyncTaskRunner *Tasks,
|
2020-02-04 22:41:39 +08:00
|
|
|
Semaphore &Barrier, DebouncePolicy UpdateDebounce,
|
2019-04-15 20:32:28 +08:00
|
|
|
bool StorePreamblesInMemory, ParsingCallbacks &Callbacks);
|
2018-02-08 15:37:35 +08:00
|
|
|
~ASTWorker();
|
|
|
|
|
2018-11-23 01:27:08 +08:00
|
|
|
void update(ParseInputs Inputs, WantDiagnostics);
|
2019-01-07 23:45:19 +08:00
|
|
|
void
|
|
|
|
runWithAST(llvm::StringRef Name,
|
[clangd] Cancel certain operations if the file changes before we start.
Summary:
Otherwise they can force us to build lots of snapshots that we don't need.
Particularly, try to do this for operations that are frequently
generated by editors without explicit user interaction, and where
editing the file makes the result less useful. (Code action
enumeration is a good example).
https://github.com/clangd/clangd/issues/298
This doesn't return the "right" LSP error code (ContentModified) to the client,
we need to teach the cancellation API to distinguish between different causes.
Reviewers: kadircet
Subscribers: ilya-biryukov, javed.absar, MaskRay, jkorous, arphaman, jfb, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D75602
2020-03-04 21:04:17 +08:00
|
|
|
llvm::unique_function<void(llvm::Expected<InputsAndAST>)> Action,
|
|
|
|
TUScheduler::ASTActionInvalidation);
|
2018-02-13 16:59:23 +08:00
|
|
|
bool blockUntilIdle(Deadline Timeout) const;
|
2018-02-08 15:37:35 +08:00
|
|
|
|
|
|
|
std::shared_ptr<const PreambleData> getPossiblyStalePreamble() const;
|
[clangd] Add fallback mode for code completion when compile command or preamble is not ready.
Summary:
When calling TUScehduler::runWithPreamble (e.g. in code compleiton), allow
entering a fallback mode when compile command or preamble is not ready, instead of
waiting. This allows clangd to perform naive code completion e.g. using identifiers
in the current file or symbols in the index.
This patch simply returns empty result for code completion in fallback mode. Identifier-based
plus more advanced index-based completion will be added in followup patches.
Reviewers: ilya-biryukov, sammccall
Reviewed By: sammccall
Subscribers: sammccall, javed.absar, MaskRay, jkorous, arphaman, kadircet, jdoerfert, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D59811
llvm-svn: 357916
2019-04-08 22:53:16 +08:00
|
|
|
|
2020-03-16 04:43:00 +08:00
|
|
|
/// Used to inform ASTWorker about a new preamble build by PreambleThread.
|
|
|
|
/// Diagnostics are only published through this callback. This ensures they
|
|
|
|
/// are always for newer versions of the file, as the callback gets called in
|
|
|
|
/// the same order as update requests.
|
|
|
|
void updatePreamble(std::unique_ptr<CompilerInvocation> CI, ParseInputs PI,
|
|
|
|
std::shared_ptr<const PreambleData> Preamble,
|
|
|
|
std::vector<Diag> CIDiags, WantDiagnostics WantDiags);
|
|
|
|
|
2018-08-30 23:07:34 +08:00
|
|
|
/// Obtain a preamble reflecting all updates so far. Threadsafe.
|
|
|
|
/// It may be delivered immediately, or later on the worker thread.
|
|
|
|
void getCurrentPreamble(
|
2019-01-07 23:45:19 +08:00
|
|
|
llvm::unique_function<void(std::shared_ptr<const PreambleData>)>);
|
2019-04-15 20:32:28 +08:00
|
|
|
/// Returns compile command from the current file inputs.
|
|
|
|
tooling::CompileCommand getCurrentCompileCommand() const;
|
|
|
|
|
2018-07-09 18:45:33 +08:00
|
|
|
/// Wait for the first build of preamble to finish. Preamble itself can be
|
2018-09-14 08:56:11 +08:00
|
|
|
/// accessed via getPossiblyStalePreamble(). Note that this function will
|
2018-07-09 18:45:33 +08:00
|
|
|
/// return after an unsuccessful build of the preamble too, i.e. result of
|
|
|
|
/// getPossiblyStalePreamble() can be null even after this function returns.
|
|
|
|
void waitForFirstPreamble() const;
|
|
|
|
|
2018-02-08 15:37:35 +08:00
|
|
|
std::size_t getUsedBytes() const;
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
bool isASTCached() const;
|
2018-02-08 15:37:35 +08:00
|
|
|
|
|
|
|
private:
|
2020-03-16 04:43:00 +08:00
|
|
|
/// Publishes diagnostics for \p Inputs. It will build an AST or reuse the
|
|
|
|
/// cached one if applicable. Assumes LatestPreamble is compatible for \p
|
|
|
|
/// Inputs.
|
|
|
|
void generateDiagnostics(std::unique_ptr<CompilerInvocation> Invocation,
|
|
|
|
ParseInputs Inputs, std::vector<Diag> CIDiags);
|
|
|
|
|
2018-02-08 15:37:35 +08:00
|
|
|
// Must be called exactly once on processing thread. Will return after
|
|
|
|
// stop() is called on a separate thread and all pending requests are
|
|
|
|
// processed.
|
|
|
|
void run();
|
|
|
|
/// Signal that run() should finish processing pending requests and exit.
|
|
|
|
void stop();
|
|
|
|
/// Adds a new task to the end of the request queue.
|
2019-01-07 23:45:19 +08:00
|
|
|
void startTask(llvm::StringRef Name, llvm::unique_function<void()> Task,
|
[clangd] Cancel certain operations if the file changes before we start.
Summary:
Otherwise they can force us to build lots of snapshots that we don't need.
Particularly, try to do this for operations that are frequently
generated by editors without explicit user interaction, and where
editing the file makes the result less useful. (Code action
enumeration is a good example).
https://github.com/clangd/clangd/issues/298
This doesn't return the "right" LSP error code (ContentModified) to the client,
we need to teach the cancellation API to distinguish between different causes.
Reviewers: kadircet
Subscribers: ilya-biryukov, javed.absar, MaskRay, jkorous, arphaman, jfb, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D75602
2020-03-04 21:04:17 +08:00
|
|
|
llvm::Optional<WantDiagnostics> UpdateType,
|
|
|
|
TUScheduler::ASTActionInvalidation);
|
2018-12-06 17:41:04 +08:00
|
|
|
|
2018-03-02 16:56:37 +08:00
|
|
|
/// Determines the next action to perform.
|
2018-09-14 08:56:11 +08:00
|
|
|
/// All actions that should never run are discarded.
|
2018-03-02 16:56:37 +08:00
|
|
|
/// Returns a deadline for the next action. If it's expired, run now.
|
|
|
|
/// scheduleLocked() is called again at the deadline, or if requests arrive.
|
|
|
|
Deadline scheduleLocked();
|
2018-02-22 21:11:12 +08:00
|
|
|
/// Should the first task in the queue be skipped instead of run?
|
|
|
|
bool shouldSkipHeadLocked() const;
|
2019-04-15 20:32:28 +08:00
|
|
|
/// This is private because `FileInputs.FS` is not thread-safe and thus not
|
|
|
|
/// safe to share. Callers should make sure not to expose `FS` via a public
|
|
|
|
/// interface.
|
|
|
|
std::shared_ptr<const ParseInputs> getCurrentFileInputs() const;
|
2018-02-08 15:37:35 +08:00
|
|
|
|
2018-02-19 17:56:28 +08:00
|
|
|
struct Request {
|
2019-01-07 23:45:19 +08:00
|
|
|
llvm::unique_function<void()> Action;
|
2018-02-19 17:56:28 +08:00
|
|
|
std::string Name;
|
2018-03-02 16:56:37 +08:00
|
|
|
steady_clock::time_point AddTime;
|
2018-02-19 17:56:28 +08:00
|
|
|
Context Ctx;
|
2019-01-07 23:45:19 +08:00
|
|
|
llvm::Optional<WantDiagnostics> UpdateType;
|
[clangd] Cancel certain operations if the file changes before we start.
Summary:
Otherwise they can force us to build lots of snapshots that we don't need.
Particularly, try to do this for operations that are frequently
generated by editors without explicit user interaction, and where
editing the file makes the result less useful. (Code action
enumeration is a good example).
https://github.com/clangd/clangd/issues/298
This doesn't return the "right" LSP error code (ContentModified) to the client,
we need to teach the cancellation API to distinguish between different causes.
Reviewers: kadircet
Subscribers: ilya-biryukov, javed.absar, MaskRay, jkorous, arphaman, jfb, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D75602
2020-03-04 21:04:17 +08:00
|
|
|
TUScheduler::ASTActionInvalidation InvalidationPolicy;
|
|
|
|
Canceler Invalidate;
|
2018-02-19 17:56:28 +08:00
|
|
|
};
|
2018-02-08 15:37:35 +08:00
|
|
|
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
/// Handles retention of ASTs.
|
|
|
|
TUScheduler::ASTCache &IdleASTs;
|
2018-02-08 15:37:35 +08:00
|
|
|
const bool RunSync;
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
/// Time to wait after an update to see whether another update obsoletes it.
|
2020-02-04 22:41:39 +08:00
|
|
|
const DebouncePolicy UpdateDebounce;
|
2018-09-14 08:56:11 +08:00
|
|
|
/// File that ASTWorker is responsible for.
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
const Path FileName;
|
2019-04-15 20:32:28 +08:00
|
|
|
const GlobalCompilationDatabase &CDB;
|
2018-11-23 01:27:08 +08:00
|
|
|
/// Callback invoked when preamble or main file AST is built.
|
[clangd] Add callbacks on parsed AST in addition to parsed preambles
Summary:
Will be used for updating the dynamic index on updates to the open files.
Currently we collect only information coming from the preamble
AST. This has a bunch of limitations:
- Dynamic index misses important information from the body of the
file, e.g. locations of definitions.
- XRefs cannot be collected at all, since we can only obtain full
information for the current file (preamble is parsed with skipped
function bodies, therefore not reliable).
This patch only adds the new callback, actually updates to the index
will be done in a follow-up patch.
Reviewers: hokein
Reviewed By: hokein
Subscribers: kadircet, javed.absar, ioeric, MaskRay, jkorous, arphaman, cfe-commits
Differential Revision: https://reviews.llvm.org/D50847
llvm-svn: 340401
2018-08-22 19:39:16 +08:00
|
|
|
ParsingCallbacks &Callbacks;
|
2020-03-16 04:43:00 +08:00
|
|
|
/// Latest build preamble for current TU.
|
|
|
|
std::shared_ptr<const PreambleData> LatestPreamble;
|
|
|
|
Notification BuiltFirstPreamble;
|
2018-03-02 16:56:37 +08:00
|
|
|
|
2018-02-08 15:37:35 +08:00
|
|
|
Semaphore &Barrier;
|
2019-07-19 21:51:01 +08:00
|
|
|
/// Whether the 'onMainAST' callback ran for the current FileInputs.
|
|
|
|
bool RanASTCallback = false;
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
/// Guards members used by both TUScheduler and the worker thread.
|
2018-02-08 15:37:35 +08:00
|
|
|
mutable std::mutex Mutex;
|
2019-04-15 20:32:28 +08:00
|
|
|
/// File inputs, currently being used by the worker.
|
|
|
|
/// Inputs are written and read by the worker thread, compile command can also
|
|
|
|
/// be consumed by clients of ASTWorker.
|
2020-03-13 18:52:19 +08:00
|
|
|
std::shared_ptr<const ParseInputs> FileInputs; /* GUARDED_BY(Mutex) */
|
2020-02-04 22:41:39 +08:00
|
|
|
/// Times of recent AST rebuilds, used for UpdateDebounce computation.
|
|
|
|
llvm::SmallVector<DebouncePolicy::clock::duration, 8>
|
|
|
|
RebuildTimes; /* GUARDED_BY(Mutex) */
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
/// Set to true to signal run() to finish processing.
|
2020-03-10 23:52:31 +08:00
|
|
|
bool Done; /* GUARDED_BY(Mutex) */
|
|
|
|
std::deque<Request> Requests; /* GUARDED_BY(Mutex) */
|
2020-03-16 04:43:00 +08:00
|
|
|
std::queue<Request> PreambleRequests; /* GUARDED_BY(Mutex) */
|
2020-03-10 23:52:31 +08:00
|
|
|
llvm::Optional<Request> CurrentRequest; /* GUARDED_BY(Mutex) */
|
2018-02-13 16:59:23 +08:00
|
|
|
mutable std::condition_variable RequestsCV;
|
2019-07-19 21:51:01 +08:00
|
|
|
/// Guards the callback that publishes results of AST-related computations
|
|
|
|
/// (diagnostics, highlightings) and file statuses.
|
|
|
|
std::mutex PublishMu;
|
|
|
|
// Used to prevent remove document + add document races that lead to
|
|
|
|
// out-of-order callbacks for publishing results of onMainAST callback.
|
|
|
|
//
|
[clangd] Cleanup: make diagnostics callbacks from TUScheduler non-racy
Summary:
Previously, removeDoc followed by an addDoc to TUScheduler resulted in
racy diagnostic responses, i.e. the old dianostics could be delivered
to the client after the new ones by TUScheduler.
To workaround this, we tracked a version number in ClangdServer and
discarded stale diagnostics. After this commit, the TUScheduler will
stop delivering diagnostics for removed files and the workaround in
ClangdServer is not required anymore.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: javed.absar, ioeric, MaskRay, jkorous, arphaman, jfb, kadircet, cfe-commits
Differential Revision: https://reviews.llvm.org/D54829
llvm-svn: 347468
2018-11-22 23:39:54 +08:00
|
|
|
// The lifetime of the old/new ASTWorkers will overlap, but their handles
|
|
|
|
// don't. When the old handle is destroyed, the old worker will stop reporting
|
2019-07-19 21:51:01 +08:00
|
|
|
// any results to the user.
|
|
|
|
bool CanPublishResults = true; /* GUARDED_BY(PublishMu) */
|
2020-03-13 18:52:19 +08:00
|
|
|
|
2020-03-18 02:08:23 +08:00
|
|
|
SynchronizedTUStatus Status;
|
2020-03-16 04:43:00 +08:00
|
|
|
PreambleThread PreamblePeer;
|
2018-02-08 15:37:35 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
/// A smart-pointer-like class that points to an active ASTWorker.
|
|
|
|
/// In destructor, signals to the underlying ASTWorker that no new requests will
|
|
|
|
/// be sent and the processing loop may exit (after running all pending
|
|
|
|
/// requests).
|
|
|
|
class ASTWorkerHandle {
|
|
|
|
friend class ASTWorker;
|
|
|
|
ASTWorkerHandle(std::shared_ptr<ASTWorker> Worker)
|
|
|
|
: Worker(std::move(Worker)) {
|
|
|
|
assert(this->Worker);
|
|
|
|
}
|
|
|
|
|
|
|
|
public:
|
|
|
|
ASTWorkerHandle(const ASTWorkerHandle &) = delete;
|
|
|
|
ASTWorkerHandle &operator=(const ASTWorkerHandle &) = delete;
|
|
|
|
ASTWorkerHandle(ASTWorkerHandle &&) = default;
|
|
|
|
ASTWorkerHandle &operator=(ASTWorkerHandle &&) = default;
|
|
|
|
|
|
|
|
~ASTWorkerHandle() {
|
|
|
|
if (Worker)
|
|
|
|
Worker->stop();
|
|
|
|
}
|
|
|
|
|
|
|
|
ASTWorker &operator*() {
|
|
|
|
assert(Worker && "Handle was moved from");
|
|
|
|
return *Worker;
|
|
|
|
}
|
|
|
|
|
|
|
|
ASTWorker *operator->() {
|
|
|
|
assert(Worker && "Handle was moved from");
|
|
|
|
return Worker.get();
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns an owning reference to the underlying ASTWorker that can outlive
|
|
|
|
/// the ASTWorkerHandle. However, no new requests to an active ASTWorker can
|
|
|
|
/// be schedule via the returned reference, i.e. only reads of the preamble
|
|
|
|
/// are possible.
|
|
|
|
std::shared_ptr<const ASTWorker> lock() { return Worker; }
|
|
|
|
|
|
|
|
private:
|
|
|
|
std::shared_ptr<ASTWorker> Worker;
|
|
|
|
};
|
|
|
|
|
2019-04-15 20:32:28 +08:00
|
|
|
ASTWorkerHandle
|
|
|
|
ASTWorker::create(PathRef FileName, const GlobalCompilationDatabase &CDB,
|
|
|
|
TUScheduler::ASTCache &IdleASTs, AsyncTaskRunner *Tasks,
|
2020-02-04 22:41:39 +08:00
|
|
|
Semaphore &Barrier, DebouncePolicy UpdateDebounce,
|
2019-04-15 20:32:28 +08:00
|
|
|
bool StorePreamblesInMemory, ParsingCallbacks &Callbacks) {
|
2019-04-04 20:56:03 +08:00
|
|
|
std::shared_ptr<ASTWorker> Worker(
|
2019-04-15 20:32:28 +08:00
|
|
|
new ASTWorker(FileName, CDB, IdleASTs, Barrier, /*RunSync=*/!Tasks,
|
2019-04-04 20:56:03 +08:00
|
|
|
UpdateDebounce, StorePreamblesInMemory, Callbacks));
|
2020-03-13 18:52:19 +08:00
|
|
|
if (Tasks) {
|
|
|
|
Tasks->runAsync("ASTWorker:" + llvm::sys::path::filename(FileName),
|
2018-02-19 17:56:28 +08:00
|
|
|
[Worker]() { Worker->run(); });
|
2020-03-13 18:52:19 +08:00
|
|
|
Tasks->runAsync("PreambleWorker:" + llvm::sys::path::filename(FileName),
|
2020-03-16 04:43:00 +08:00
|
|
|
[Worker]() { Worker->PreamblePeer.run(); });
|
2020-03-13 18:52:19 +08:00
|
|
|
}
|
2018-02-08 15:37:35 +08:00
|
|
|
|
|
|
|
return ASTWorkerHandle(std::move(Worker));
|
|
|
|
}
|
|
|
|
|
2019-04-15 20:32:28 +08:00
|
|
|
ASTWorker::ASTWorker(PathRef FileName, const GlobalCompilationDatabase &CDB,
|
|
|
|
TUScheduler::ASTCache &LRUCache, Semaphore &Barrier,
|
2020-02-04 22:41:39 +08:00
|
|
|
bool RunSync, DebouncePolicy UpdateDebounce,
|
[clangd] Add callbacks on parsed AST in addition to parsed preambles
Summary:
Will be used for updating the dynamic index on updates to the open files.
Currently we collect only information coming from the preamble
AST. This has a bunch of limitations:
- Dynamic index misses important information from the body of the
file, e.g. locations of definitions.
- XRefs cannot be collected at all, since we can only obtain full
information for the current file (preamble is parsed with skipped
function bodies, therefore not reliable).
This patch only adds the new callback, actually updates to the index
will be done in a follow-up patch.
Reviewers: hokein
Reviewed By: hokein
Subscribers: kadircet, javed.absar, ioeric, MaskRay, jkorous, arphaman, cfe-commits
Differential Revision: https://reviews.llvm.org/D50847
llvm-svn: 340401
2018-08-22 19:39:16 +08:00
|
|
|
bool StorePreamblesInMemory, ParsingCallbacks &Callbacks)
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
: IdleASTs(LRUCache), RunSync(RunSync), UpdateDebounce(UpdateDebounce),
|
2020-03-18 02:08:23 +08:00
|
|
|
FileName(FileName), CDB(CDB), Callbacks(Callbacks), Barrier(Barrier),
|
|
|
|
Done(false), Status(FileName, Callbacks),
|
2020-03-16 04:43:00 +08:00
|
|
|
PreamblePeer(FileName, Callbacks, StorePreamblesInMemory,
|
|
|
|
// FIXME: Run PreamblePeer asynchronously once ast patching
|
|
|
|
// is available.
|
|
|
|
/*RunSync=*/true, Status, *this) {
|
2019-04-15 20:32:28 +08:00
|
|
|
auto Inputs = std::make_shared<ParseInputs>();
|
|
|
|
// Set a fallback command because compile command can be accessed before
|
|
|
|
// `Inputs` is initialized. Other fields are only used after initialization
|
|
|
|
// from client inputs.
|
|
|
|
Inputs->CompileCommand = CDB.getFallbackCommand(FileName);
|
|
|
|
FileInputs = std::move(Inputs);
|
|
|
|
}
|
2018-02-08 15:37:35 +08:00
|
|
|
|
|
|
|
ASTWorker::~ASTWorker() {
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
// Make sure we remove the cached AST, if any.
|
|
|
|
IdleASTs.take(this);
|
2018-02-08 15:37:35 +08:00
|
|
|
#ifndef NDEBUG
|
|
|
|
std::lock_guard<std::mutex> Lock(Mutex);
|
|
|
|
assert(Done && "handle was not destroyed");
|
2020-03-10 23:52:31 +08:00
|
|
|
assert(Requests.empty() && !CurrentRequest &&
|
|
|
|
"unprocessed requests when destroying ASTWorker");
|
2018-02-08 15:37:35 +08:00
|
|
|
#endif
|
|
|
|
}
|
|
|
|
|
2018-11-23 01:27:08 +08:00
|
|
|
void ASTWorker::update(ParseInputs Inputs, WantDiagnostics WantDiags) {
|
[clangd] Track document versions, include them with diags, enhance logs
Summary:
This ties to an LSP feature (diagnostic versioning) but really a lot
of the value is in being able to log what's happening with file versions
and queues more descriptively and clearly.
As such it's fairly invasive, for a logging patch :-\
Key decisions:
- at the LSP layer, we don't reqire the client to provide versions (LSP
makes it mandatory but we never enforced it). If not provided,
versions start at 0 and increment. DraftStore handles this.
- don't propagate magically using contexts, but rather manually:
addDocument -> ParseInputs -> (ParsedAST, Preamble, various callbacks)
Context-propagation would hide the versions from ClangdServer, which
would make producing good log messages hard
- within ClangdServer, treat versions as opaque and unordered.
std::string is a convenient type for this, and allows richer versions
for embedders. They're "mandatory" but "null" is a reasonable default.
Subscribers: ilya-biryukov, javed.absar, MaskRay, jkorous, arphaman, kadircet, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D75582
2020-03-04 07:33:29 +08:00
|
|
|
std::string TaskName = llvm::formatv("Update ({0})", Inputs.Version);
|
2018-11-23 01:27:08 +08:00
|
|
|
auto Task = [=]() mutable {
|
2019-04-15 20:32:28 +08:00
|
|
|
// Get the actual command as `Inputs` does not have a command.
|
|
|
|
// FIXME: some build systems like Bazel will take time to preparing
|
|
|
|
// environment to build the file, it would be nice if we could emit a
|
|
|
|
// "PreparingBuild" status to inform users, it is non-trivial given the
|
|
|
|
// current implementation.
|
|
|
|
if (auto Cmd = CDB.getCompileCommand(FileName))
|
|
|
|
Inputs.CompileCommand = *Cmd;
|
|
|
|
else
|
|
|
|
// FIXME: consider using old command if it's not a fallback one.
|
|
|
|
Inputs.CompileCommand = CDB.getFallbackCommand(FileName);
|
2020-03-16 04:43:00 +08:00
|
|
|
|
2018-07-26 17:21:07 +08:00
|
|
|
bool InputsAreTheSame =
|
2020-03-16 04:43:00 +08:00
|
|
|
std::tie(FileInputs->CompileCommand, FileInputs->Contents) ==
|
2018-07-26 17:21:07 +08:00
|
|
|
std::tie(Inputs.CompileCommand, Inputs.Contents);
|
2020-03-16 04:43:00 +08:00
|
|
|
// Cached AST is invalidated.
|
|
|
|
if (!InputsAreTheSame) {
|
|
|
|
IdleASTs.take(this);
|
|
|
|
RanASTCallback = false;
|
|
|
|
}
|
2018-07-26 17:21:07 +08:00
|
|
|
|
2020-03-16 04:43:00 +08:00
|
|
|
// Update current inputs so that subsequent reads can see them.
|
2019-04-15 20:32:28 +08:00
|
|
|
{
|
|
|
|
std::lock_guard<std::mutex> Lock(Mutex);
|
|
|
|
FileInputs = std::make_shared<ParseInputs>(Inputs);
|
|
|
|
}
|
2020-03-16 04:43:00 +08:00
|
|
|
|
[clangd] Track document versions, include them with diags, enhance logs
Summary:
This ties to an LSP feature (diagnostic versioning) but really a lot
of the value is in being able to log what's happening with file versions
and queues more descriptively and clearly.
As such it's fairly invasive, for a logging patch :-\
Key decisions:
- at the LSP layer, we don't reqire the client to provide versions (LSP
makes it mandatory but we never enforced it). If not provided,
versions start at 0 and increment. DraftStore handles this.
- don't propagate magically using contexts, but rather manually:
addDocument -> ParseInputs -> (ParsedAST, Preamble, various callbacks)
Context-propagation would hide the versions from ClangdServer, which
would make producing good log messages hard
- within ClangdServer, treat versions as opaque and unordered.
std::string is a convenient type for this, and allows richer versions
for embedders. They're "mandatory" but "null" is a reasonable default.
Subscribers: ilya-biryukov, javed.absar, MaskRay, jkorous, arphaman, kadircet, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D75582
2020-03-04 07:33:29 +08:00
|
|
|
log("ASTWorker building file {0} version {1} with command {2}\n[{3}]\n{4}",
|
|
|
|
FileName, Inputs.Version, Inputs.CompileCommand.Heuristic,
|
[clangd] Upgrade logging facilities with levels and formatv.
Summary:
log() is split into four functions:
- elog()/log()/vlog() have different severity levels, allowing filtering
- dlog() is a lazy macro which uses LLVM_DEBUG - it logs to the logger, but
conditionally based on -debug-only flag and is omitted in release builds
All logging functions use formatv-style format strings now, e.g:
log("Could not resolve URI {0}: {1}", URI, Result.takeError());
Existing log sites have been split between elog/log/vlog by best guess.
This includes a workaround for passing Error to formatv that can be
simplified when D49170 or similar lands.
Subscribers: ilya-biryukov, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D49008
llvm-svn: 336785
2018-07-11 18:35:11 +08:00
|
|
|
Inputs.CompileCommand.Directory,
|
2019-01-07 23:45:19 +08:00
|
|
|
llvm::join(Inputs.CompileCommand.CommandLine, " "));
|
2020-03-16 04:43:00 +08:00
|
|
|
|
[clangd] Surface errors from command-line parsing
Summary:
Those errors are exposed at the first character of a file,
for a lack of a better place.
Previously, all errors were stored inside the AST and report
accordingly. However, errors in command-line argument parsing could
result in failure to produce the AST, so we need an alternative ways to
report those errors.
We take the following approach in this patch:
- buildCompilerInvocation() now requires an explicit DiagnosticConsumer.
- TUScheduler and TestTU now collect the diagnostics produced when
parsing command line arguments.
If pasing of the AST failed, diagnostics are reported via a new
ParsingCallbacks::onFailedAST method.
If parsing of the AST succeeded, any errors produced during
command-line parsing are stored alongside the AST inside the
ParsedAST instance and reported as previously by calling the
ParsingCallbacks::onMainAST method;
- The client code that uses ClangdServer's DiagnosticConsumer
does not need to change, it will receive new diagnostics in the
onDiagnosticsReady() callback
Errors produced when parsing command-line arguments are collected using
the same StoreDiags class that is used to collect all other errors. They
are recognized by their location being invalid. IIUC, the location is
invalid as there is no source manager at this point, it is created at a
later stage.
Although technically we might also get diagnostics that mention the
command-line arguments FileID with after the source manager was created
(and they have valid source locations), we choose to not handle those
and they are dropped as not coming from the main file. AFAICT, those
diagnostics should always be notes, therefore it's safe to drop them
without loosing too much information.
Reviewers: kadircet
Reviewed By: kadircet
Subscribers: nridge, javed.absar, MaskRay, jkorous, arphaman, cfe-commits, gribozavr
Tags: #clang
Differential Revision: https://reviews.llvm.org/D66759
llvm-svn: 370177
2019-08-28 17:24:55 +08:00
|
|
|
StoreDiags CompilerInvocationDiagConsumer;
|
2019-11-29 02:22:50 +08:00
|
|
|
std::vector<std::string> CC1Args;
|
2019-11-29 19:05:00 +08:00
|
|
|
std::unique_ptr<CompilerInvocation> Invocation = buildCompilerInvocation(
|
|
|
|
Inputs, CompilerInvocationDiagConsumer, &CC1Args);
|
2019-11-29 02:22:50 +08:00
|
|
|
// Log cc1 args even (especially!) if creating invocation failed.
|
|
|
|
if (!CC1Args.empty())
|
2019-11-29 19:05:00 +08:00
|
|
|
vlog("Driver produced command: cc1 {0}", llvm::join(CC1Args, " "));
|
[clangd] Surface errors from command-line parsing
Summary:
Those errors are exposed at the first character of a file,
for a lack of a better place.
Previously, all errors were stored inside the AST and report
accordingly. However, errors in command-line argument parsing could
result in failure to produce the AST, so we need an alternative ways to
report those errors.
We take the following approach in this patch:
- buildCompilerInvocation() now requires an explicit DiagnosticConsumer.
- TUScheduler and TestTU now collect the diagnostics produced when
parsing command line arguments.
If pasing of the AST failed, diagnostics are reported via a new
ParsingCallbacks::onFailedAST method.
If parsing of the AST succeeded, any errors produced during
command-line parsing are stored alongside the AST inside the
ParsedAST instance and reported as previously by calling the
ParsingCallbacks::onMainAST method;
- The client code that uses ClangdServer's DiagnosticConsumer
does not need to change, it will receive new diagnostics in the
onDiagnosticsReady() callback
Errors produced when parsing command-line arguments are collected using
the same StoreDiags class that is used to collect all other errors. They
are recognized by their location being invalid. IIUC, the location is
invalid as there is no source manager at this point, it is created at a
later stage.
Although technically we might also get diagnostics that mention the
command-line arguments FileID with after the source manager was created
(and they have valid source locations), we choose to not handle those
and they are dropped as not coming from the main file. AFAICT, those
diagnostics should always be notes, therefore it's safe to drop them
without loosing too much information.
Reviewers: kadircet
Reviewed By: kadircet
Subscribers: nridge, javed.absar, MaskRay, jkorous, arphaman, cfe-commits, gribozavr
Tags: #clang
Differential Revision: https://reviews.llvm.org/D66759
llvm-svn: 370177
2019-08-28 17:24:55 +08:00
|
|
|
std::vector<Diag> CompilerInvocationDiags =
|
|
|
|
CompilerInvocationDiagConsumer.take();
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
if (!Invocation) {
|
[clangd] Upgrade logging facilities with levels and formatv.
Summary:
log() is split into four functions:
- elog()/log()/vlog() have different severity levels, allowing filtering
- dlog() is a lazy macro which uses LLVM_DEBUG - it logs to the logger, but
conditionally based on -debug-only flag and is omitted in release builds
All logging functions use formatv-style format strings now, e.g:
log("Could not resolve URI {0}: {1}", URI, Result.takeError());
Existing log sites have been split between elog/log/vlog by best guess.
This includes a workaround for passing Error to formatv that can be
simplified when D49170 or similar lands.
Subscribers: ilya-biryukov, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D49008
llvm-svn: 336785
2018-07-11 18:35:11 +08:00
|
|
|
elog("Could not build CompilerInvocation for file {0}", FileName);
|
2018-07-30 23:30:45 +08:00
|
|
|
// Remove the old AST if it's still in cache.
|
|
|
|
IdleASTs.take(this);
|
2020-03-16 04:43:00 +08:00
|
|
|
RanASTCallback = false;
|
[clangd] Surface errors from command-line parsing
Summary:
Those errors are exposed at the first character of a file,
for a lack of a better place.
Previously, all errors were stored inside the AST and report
accordingly. However, errors in command-line argument parsing could
result in failure to produce the AST, so we need an alternative ways to
report those errors.
We take the following approach in this patch:
- buildCompilerInvocation() now requires an explicit DiagnosticConsumer.
- TUScheduler and TestTU now collect the diagnostics produced when
parsing command line arguments.
If pasing of the AST failed, diagnostics are reported via a new
ParsingCallbacks::onFailedAST method.
If parsing of the AST succeeded, any errors produced during
command-line parsing are stored alongside the AST inside the
ParsedAST instance and reported as previously by calling the
ParsingCallbacks::onMainAST method;
- The client code that uses ClangdServer's DiagnosticConsumer
does not need to change, it will receive new diagnostics in the
onDiagnosticsReady() callback
Errors produced when parsing command-line arguments are collected using
the same StoreDiags class that is used to collect all other errors. They
are recognized by their location being invalid. IIUC, the location is
invalid as there is no source manager at this point, it is created at a
later stage.
Although technically we might also get diagnostics that mention the
command-line arguments FileID with after the source manager was created
(and they have valid source locations), we choose to not handle those
and they are dropped as not coming from the main file. AFAICT, those
diagnostics should always be notes, therefore it's safe to drop them
without loosing too much information.
Reviewers: kadircet
Reviewed By: kadircet
Subscribers: nridge, javed.absar, MaskRay, jkorous, arphaman, cfe-commits, gribozavr
Tags: #clang
Differential Revision: https://reviews.llvm.org/D66759
llvm-svn: 370177
2019-08-28 17:24:55 +08:00
|
|
|
// Report the diagnostics we collected when parsing the command line.
|
[clangd] Track document versions, include them with diags, enhance logs
Summary:
This ties to an LSP feature (diagnostic versioning) but really a lot
of the value is in being able to log what's happening with file versions
and queues more descriptively and clearly.
As such it's fairly invasive, for a logging patch :-\
Key decisions:
- at the LSP layer, we don't reqire the client to provide versions (LSP
makes it mandatory but we never enforced it). If not provided,
versions start at 0 and increment. DraftStore handles this.
- don't propagate magically using contexts, but rather manually:
addDocument -> ParseInputs -> (ParsedAST, Preamble, various callbacks)
Context-propagation would hide the versions from ClangdServer, which
would make producing good log messages hard
- within ClangdServer, treat versions as opaque and unordered.
std::string is a convenient type for this, and allows richer versions
for embedders. They're "mandatory" but "null" is a reasonable default.
Subscribers: ilya-biryukov, javed.absar, MaskRay, jkorous, arphaman, kadircet, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D75582
2020-03-04 07:33:29 +08:00
|
|
|
Callbacks.onFailedAST(FileName, Inputs.Version,
|
2020-03-16 04:43:00 +08:00
|
|
|
std::move(CompilerInvocationDiags),
|
|
|
|
[&](llvm::function_ref<void()> Publish) {
|
|
|
|
// Ensure we only publish results from the worker
|
|
|
|
// if the file was not removed, making sure there
|
|
|
|
// are not race conditions.
|
|
|
|
std::lock_guard<std::mutex> Lock(PublishMu);
|
|
|
|
if (CanPublishResults)
|
|
|
|
Publish();
|
|
|
|
});
|
|
|
|
// Make sure anyone waiting for the preamble gets notified it could not be
|
|
|
|
// built.
|
|
|
|
BuiltFirstPreamble.notify();
|
2018-07-31 21:45:37 +08:00
|
|
|
return;
|
[clangd] Cleanup: make diagnostics callbacks from TUScheduler non-racy
Summary:
Previously, removeDoc followed by an addDoc to TUScheduler resulted in
racy diagnostic responses, i.e. the old dianostics could be delivered
to the client after the new ones by TUScheduler.
To workaround this, we tracked a version number in ClangdServer and
discarded stale diagnostics. After this commit, the TUScheduler will
stop delivering diagnostics for removed files and the workaround in
ClangdServer is not required anymore.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: javed.absar, ioeric, MaskRay, jkorous, arphaman, jfb, kadircet, cfe-commits
Differential Revision: https://reviews.llvm.org/D54829
llvm-svn: 347468
2018-11-22 23:39:54 +08:00
|
|
|
}
|
|
|
|
|
2020-03-16 04:43:00 +08:00
|
|
|
PreamblePeer.update(std::move(Invocation), std::move(Inputs),
|
|
|
|
std::move(CompilerInvocationDiags), WantDiags);
|
|
|
|
return;
|
2018-02-08 15:37:35 +08:00
|
|
|
};
|
[clangd] Cancel certain operations if the file changes before we start.
Summary:
Otherwise they can force us to build lots of snapshots that we don't need.
Particularly, try to do this for operations that are frequently
generated by editors without explicit user interaction, and where
editing the file makes the result less useful. (Code action
enumeration is a good example).
https://github.com/clangd/clangd/issues/298
This doesn't return the "right" LSP error code (ContentModified) to the client,
we need to teach the cancellation API to distinguish between different causes.
Reviewers: kadircet
Subscribers: ilya-biryukov, javed.absar, MaskRay, jkorous, arphaman, jfb, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D75602
2020-03-04 21:04:17 +08:00
|
|
|
startTask(TaskName, std::move(Task), WantDiags, TUScheduler::NoInvalidation);
|
2018-02-08 15:37:35 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
void ASTWorker::runWithAST(
|
2019-01-07 23:45:19 +08:00
|
|
|
llvm::StringRef Name,
|
[clangd] Cancel certain operations if the file changes before we start.
Summary:
Otherwise they can force us to build lots of snapshots that we don't need.
Particularly, try to do this for operations that are frequently
generated by editors without explicit user interaction, and where
editing the file makes the result less useful. (Code action
enumeration is a good example).
https://github.com/clangd/clangd/issues/298
This doesn't return the "right" LSP error code (ContentModified) to the client,
we need to teach the cancellation API to distinguish between different causes.
Reviewers: kadircet
Subscribers: ilya-biryukov, javed.absar, MaskRay, jkorous, arphaman, jfb, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D75602
2020-03-04 21:04:17 +08:00
|
|
|
llvm::unique_function<void(llvm::Expected<InputsAndAST>)> Action,
|
|
|
|
TUScheduler::ASTActionInvalidation Invalidation) {
|
2019-08-15 22:16:06 +08:00
|
|
|
auto Task = [=, Action = std::move(Action)]() mutable {
|
[clangd] Respect task cancellation in TUScheduler.
Summary:
- Reads are never executed if canceled before ready-to run.
In practice, we finalize cancelled reads eagerly and out-of-order.
- Cancelled reads don't prevent prior updates from being elided, as they don't
actually depend on the result of the update.
- Updates are downgraded from WantDiagnostics::Yes to WantDiagnostics::Auto when
cancelled, which allows them to be elided when all dependent reads are
cancelled and there are subsequent writes. (e.g. when the queue is backed up
with cancelled requests).
The queue operations aren't optimal (we scan the whole queue for cancelled
tasks every time the scheduler runs, and check cancellation twice in the end).
However I believe these costs are still trivial in practice (compared to any
AST operation) and the logic can be cleanly separated from the rest of the
scheduler.
Reviewers: ilya-biryukov
Subscribers: javed.absar, ioeric, MaskRay, jkorous, arphaman, kadircet, cfe-commits
Differential Revision: https://reviews.llvm.org/D54746
llvm-svn: 347450
2018-11-22 18:22:16 +08:00
|
|
|
if (isCancelled())
|
2019-01-07 23:45:19 +08:00
|
|
|
return Action(llvm::make_error<CancelledError>());
|
|
|
|
llvm::Optional<std::unique_ptr<ParsedAST>> AST = IdleASTs.take(this);
|
2019-04-15 20:32:28 +08:00
|
|
|
auto CurrentInputs = getCurrentFileInputs();
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
if (!AST) {
|
[clangd] Surface errors from command-line parsing
Summary:
Those errors are exposed at the first character of a file,
for a lack of a better place.
Previously, all errors were stored inside the AST and report
accordingly. However, errors in command-line argument parsing could
result in failure to produce the AST, so we need an alternative ways to
report those errors.
We take the following approach in this patch:
- buildCompilerInvocation() now requires an explicit DiagnosticConsumer.
- TUScheduler and TestTU now collect the diagnostics produced when
parsing command line arguments.
If pasing of the AST failed, diagnostics are reported via a new
ParsingCallbacks::onFailedAST method.
If parsing of the AST succeeded, any errors produced during
command-line parsing are stored alongside the AST inside the
ParsedAST instance and reported as previously by calling the
ParsingCallbacks::onMainAST method;
- The client code that uses ClangdServer's DiagnosticConsumer
does not need to change, it will receive new diagnostics in the
onDiagnosticsReady() callback
Errors produced when parsing command-line arguments are collected using
the same StoreDiags class that is used to collect all other errors. They
are recognized by their location being invalid. IIUC, the location is
invalid as there is no source manager at this point, it is created at a
later stage.
Although technically we might also get diagnostics that mention the
command-line arguments FileID with after the source manager was created
(and they have valid source locations), we choose to not handle those
and they are dropped as not coming from the main file. AFAICT, those
diagnostics should always be notes, therefore it's safe to drop them
without loosing too much information.
Reviewers: kadircet
Reviewed By: kadircet
Subscribers: nridge, javed.absar, MaskRay, jkorous, arphaman, cfe-commits, gribozavr
Tags: #clang
Differential Revision: https://reviews.llvm.org/D66759
llvm-svn: 370177
2019-08-28 17:24:55 +08:00
|
|
|
StoreDiags CompilerInvocationDiagConsumer;
|
|
|
|
std::unique_ptr<CompilerInvocation> Invocation = buildCompilerInvocation(
|
|
|
|
*CurrentInputs, CompilerInvocationDiagConsumer);
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
// Try rebuilding the AST.
|
[clangd] Track document versions, include them with diags, enhance logs
Summary:
This ties to an LSP feature (diagnostic versioning) but really a lot
of the value is in being able to log what's happening with file versions
and queues more descriptively and clearly.
As such it's fairly invasive, for a logging patch :-\
Key decisions:
- at the LSP layer, we don't reqire the client to provide versions (LSP
makes it mandatory but we never enforced it). If not provided,
versions start at 0 and increment. DraftStore handles this.
- don't propagate magically using contexts, but rather manually:
addDocument -> ParseInputs -> (ParsedAST, Preamble, various callbacks)
Context-propagation would hide the versions from ClangdServer, which
would make producing good log messages hard
- within ClangdServer, treat versions as opaque and unordered.
std::string is a convenient type for this, and allows richer versions
for embedders. They're "mandatory" but "null" is a reasonable default.
Subscribers: ilya-biryukov, javed.absar, MaskRay, jkorous, arphaman, kadircet, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D75582
2020-03-04 07:33:29 +08:00
|
|
|
vlog("ASTWorker rebuilding evicted AST to run {0}: {1} version {2}", Name,
|
|
|
|
FileName, CurrentInputs->Version);
|
2020-03-16 04:43:00 +08:00
|
|
|
// FIXME: We might need to build a patched ast once preamble thread starts
|
|
|
|
// running async. Currently getPossiblyStalePreamble below will always
|
|
|
|
// return a compatible preamble as ASTWorker::update blocks.
|
2019-01-07 23:45:19 +08:00
|
|
|
llvm::Optional<ParsedAST> NewAST =
|
2020-04-02 22:51:59 +08:00
|
|
|
Invocation ? buildAST(FileName, std::move(Invocation),
|
|
|
|
CompilerInvocationDiagConsumer.take(),
|
|
|
|
*CurrentInputs, getPossiblyStalePreamble())
|
|
|
|
: None;
|
2019-08-15 07:52:23 +08:00
|
|
|
AST = NewAST ? std::make_unique<ParsedAST>(std::move(*NewAST)) : nullptr;
|
2018-02-09 18:17:23 +08:00
|
|
|
}
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
// Make sure we put the AST back into the LRU cache.
|
2019-01-07 23:45:19 +08:00
|
|
|
auto _ = llvm::make_scope_exit(
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
[&AST, this]() { IdleASTs.put(this, std::move(*AST)); });
|
|
|
|
// Run the user-provided action.
|
|
|
|
if (!*AST)
|
2019-01-07 23:45:19 +08:00
|
|
|
return Action(llvm::make_error<llvm::StringError>(
|
|
|
|
"invalid AST", llvm::errc::invalid_argument));
|
[clangd] Track document versions, include them with diags, enhance logs
Summary:
This ties to an LSP feature (diagnostic versioning) but really a lot
of the value is in being able to log what's happening with file versions
and queues more descriptively and clearly.
As such it's fairly invasive, for a logging patch :-\
Key decisions:
- at the LSP layer, we don't reqire the client to provide versions (LSP
makes it mandatory but we never enforced it). If not provided,
versions start at 0 and increment. DraftStore handles this.
- don't propagate magically using contexts, but rather manually:
addDocument -> ParseInputs -> (ParsedAST, Preamble, various callbacks)
Context-propagation would hide the versions from ClangdServer, which
would make producing good log messages hard
- within ClangdServer, treat versions as opaque and unordered.
std::string is a convenient type for this, and allows richer versions
for embedders. They're "mandatory" but "null" is a reasonable default.
Subscribers: ilya-biryukov, javed.absar, MaskRay, jkorous, arphaman, kadircet, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D75582
2020-03-04 07:33:29 +08:00
|
|
|
vlog("ASTWorker running {0} on version {2} of {1}", Name, FileName,
|
|
|
|
CurrentInputs->Version);
|
2019-04-15 20:32:28 +08:00
|
|
|
Action(InputsAndAST{*CurrentInputs, **AST});
|
2018-02-08 15:37:35 +08:00
|
|
|
};
|
[clangd] Cancel certain operations if the file changes before we start.
Summary:
Otherwise they can force us to build lots of snapshots that we don't need.
Particularly, try to do this for operations that are frequently
generated by editors without explicit user interaction, and where
editing the file makes the result less useful. (Code action
enumeration is a good example).
https://github.com/clangd/clangd/issues/298
This doesn't return the "right" LSP error code (ContentModified) to the client,
we need to teach the cancellation API to distinguish between different causes.
Reviewers: kadircet
Subscribers: ilya-biryukov, javed.absar, MaskRay, jkorous, arphaman, jfb, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D75602
2020-03-04 21:04:17 +08:00
|
|
|
startTask(Name, std::move(Task), /*UpdateType=*/None, Invalidation);
|
2018-02-08 15:37:35 +08:00
|
|
|
}
|
|
|
|
|
2020-03-16 04:43:00 +08:00
|
|
|
void PreambleThread::build(Request Req) {
|
|
|
|
assert(Req.CI && "Got preamble request with null compiler invocation");
|
|
|
|
const ParseInputs &Inputs = Req.Inputs;
|
|
|
|
|
|
|
|
Status.update([&](TUStatus &Status) {
|
|
|
|
Status.PreambleActivity = PreambleAction::Building;
|
|
|
|
});
|
|
|
|
auto _ = llvm::make_scope_exit([this, &Req] {
|
|
|
|
ASTPeer.updatePreamble(std::move(Req.CI), std::move(Req.Inputs),
|
|
|
|
LatestBuild, std::move(Req.CIDiags),
|
|
|
|
std::move(Req.WantDiags));
|
|
|
|
});
|
|
|
|
|
|
|
|
if (!LatestBuild || Inputs.ForceRebuild) {
|
|
|
|
vlog("Building first preamble for {0} version {1}", FileName,
|
|
|
|
Inputs.Version);
|
|
|
|
} else if (isPreambleCompatible(*LatestBuild, Inputs, FileName, *Req.CI)) {
|
|
|
|
vlog("Reusing preamble version {0} for version {1} of {2}",
|
|
|
|
LatestBuild->Version, Inputs.Version, FileName);
|
|
|
|
return;
|
|
|
|
} else {
|
|
|
|
vlog("Rebuilding invalidated preamble for {0} version {1} (previous was "
|
|
|
|
"version {2})",
|
|
|
|
FileName, Inputs.Version, LatestBuild->Version);
|
|
|
|
}
|
|
|
|
|
|
|
|
LatestBuild = clang::clangd::buildPreamble(
|
|
|
|
FileName, *Req.CI, Inputs, StoreInMemory,
|
|
|
|
[this, Version(Inputs.Version)](ASTContext &Ctx,
|
|
|
|
std::shared_ptr<clang::Preprocessor> PP,
|
|
|
|
const CanonicalIncludes &CanonIncludes) {
|
|
|
|
Callbacks.onPreambleAST(FileName, Version, Ctx, std::move(PP),
|
|
|
|
CanonIncludes);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
void ASTWorker::updatePreamble(std::unique_ptr<CompilerInvocation> CI,
|
|
|
|
ParseInputs PI,
|
|
|
|
std::shared_ptr<const PreambleData> Preamble,
|
|
|
|
std::vector<Diag> CIDiags,
|
|
|
|
WantDiagnostics WantDiags) {
|
|
|
|
std::string TaskName = llvm::formatv("Build AST for ({0})", PI.Version);
|
|
|
|
// Store preamble and build diagnostics with new preamble if requested.
|
|
|
|
auto Task = [this, Preamble = std::move(Preamble), CI = std::move(CI),
|
|
|
|
PI = std::move(PI), CIDiags = std::move(CIDiags),
|
|
|
|
WantDiags = std::move(WantDiags)]() mutable {
|
|
|
|
// Update the preamble inside ASTWorker queue to ensure atomicity. As a task
|
|
|
|
// running inside ASTWorker assumes internals won't change until it
|
|
|
|
// finishes.
|
|
|
|
if (Preamble != LatestPreamble) {
|
|
|
|
// Cached AST is no longer valid.
|
|
|
|
IdleASTs.take(this);
|
|
|
|
RanASTCallback = false;
|
|
|
|
std::lock_guard<std::mutex> Lock(Mutex);
|
|
|
|
// LatestPreamble might be the last reference to old preamble, do not
|
|
|
|
// trigger destructor while holding the lock.
|
|
|
|
std::swap(LatestPreamble, Preamble);
|
|
|
|
}
|
|
|
|
// Give up our ownership to old preamble before starting expensive AST
|
|
|
|
// build.
|
|
|
|
Preamble.reset();
|
|
|
|
BuiltFirstPreamble.notify();
|
|
|
|
// We only need to build the AST if diagnostics were requested.
|
|
|
|
if (WantDiags == WantDiagnostics::No)
|
|
|
|
return;
|
|
|
|
// Report diagnostics with the new preamble to ensure progress. Otherwise
|
|
|
|
// diagnostics might get stale indefinitely if user keeps invalidating the
|
|
|
|
// preamble.
|
|
|
|
generateDiagnostics(std::move(CI), std::move(PI), std::move(CIDiags));
|
|
|
|
};
|
|
|
|
if (RunSync) {
|
|
|
|
Task();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
{
|
|
|
|
std::lock_guard<std::mutex> Lock(Mutex);
|
|
|
|
PreambleRequests.push({std::move(Task), std::move(TaskName),
|
|
|
|
steady_clock::now(), Context::current().clone(),
|
|
|
|
llvm::None, TUScheduler::NoInvalidation, nullptr});
|
|
|
|
}
|
|
|
|
RequestsCV.notify_all();
|
|
|
|
}
|
|
|
|
|
|
|
|
void ASTWorker::generateDiagnostics(
|
|
|
|
std::unique_ptr<CompilerInvocation> Invocation, ParseInputs Inputs,
|
|
|
|
std::vector<Diag> CIDiags) {
|
|
|
|
assert(Invocation);
|
|
|
|
// No need to rebuild the AST if we won't send the diagnostics.
|
|
|
|
{
|
|
|
|
std::lock_guard<std::mutex> Lock(PublishMu);
|
|
|
|
if (!CanPublishResults)
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
// Used to check whether we can update AST cache.
|
|
|
|
bool InputsAreLatest =
|
|
|
|
std::tie(FileInputs->CompileCommand, FileInputs->Contents) ==
|
|
|
|
std::tie(Inputs.CompileCommand, Inputs.Contents);
|
|
|
|
// Take a shortcut and don't report the diagnostics, since they should be the
|
|
|
|
// same. All the clients should handle the lack of OnUpdated() call anyway to
|
|
|
|
// handle empty result from buildAST.
|
|
|
|
// FIXME: the AST could actually change if non-preamble includes changed,
|
|
|
|
// but we choose to ignore it.
|
|
|
|
if (InputsAreLatest && RanASTCallback)
|
|
|
|
return;
|
|
|
|
|
|
|
|
// Get the AST for diagnostics, either build it or use the cached one.
|
|
|
|
std::string TaskName = llvm::formatv("Build AST ({0})", Inputs.Version);
|
|
|
|
Status.update([&](TUStatus &Status) {
|
|
|
|
Status.ASTActivity.K = ASTAction::Building;
|
|
|
|
Status.ASTActivity.Name = std::move(TaskName);
|
|
|
|
});
|
|
|
|
// We might be able to reuse the last we've built for a read request.
|
|
|
|
// FIXME: It might be better to not reuse this AST. That way queued AST builds
|
|
|
|
// won't be required for diags.
|
|
|
|
llvm::Optional<std::unique_ptr<ParsedAST>> AST = IdleASTs.take(this);
|
|
|
|
if (!AST) {
|
|
|
|
auto RebuildStartTime = DebouncePolicy::clock::now();
|
|
|
|
llvm::Optional<ParsedAST> NewAST = buildAST(
|
|
|
|
FileName, std::move(Invocation), CIDiags, Inputs, LatestPreamble);
|
|
|
|
auto RebuildDuration = DebouncePolicy::clock::now() - RebuildStartTime;
|
|
|
|
// Try to record the AST-build time, to inform future update debouncing.
|
|
|
|
// This is best-effort only: if the lock is held, don't bother.
|
|
|
|
std::unique_lock<std::mutex> Lock(Mutex, std::try_to_lock);
|
|
|
|
if (Lock.owns_lock()) {
|
|
|
|
// Do not let RebuildTimes grow beyond its small-size (i.e.
|
|
|
|
// capacity).
|
|
|
|
if (RebuildTimes.size() == RebuildTimes.capacity())
|
|
|
|
RebuildTimes.erase(RebuildTimes.begin());
|
|
|
|
RebuildTimes.push_back(RebuildDuration);
|
|
|
|
Lock.unlock();
|
|
|
|
}
|
|
|
|
Status.update([&](TUStatus &Status) {
|
|
|
|
Status.Details.ReuseAST = false;
|
|
|
|
Status.Details.BuildFailed = !NewAST.hasValue();
|
|
|
|
});
|
|
|
|
AST = NewAST ? std::make_unique<ParsedAST>(std::move(*NewAST)) : nullptr;
|
|
|
|
} else {
|
|
|
|
assert(InputsAreLatest && !RanASTCallback &&
|
|
|
|
"forgot to invalidate cached ast?");
|
|
|
|
log("Skipping rebuild of the AST for {0}, inputs are the same.", FileName);
|
|
|
|
Status.update([](TUStatus &Status) {
|
|
|
|
Status.Details.ReuseAST = true;
|
|
|
|
Status.Details.BuildFailed = false;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// Publish diagnostics.
|
|
|
|
auto RunPublish = [&](llvm::function_ref<void()> Publish) {
|
|
|
|
// Ensure we only publish results from the worker if the file was not
|
|
|
|
// removed, making sure there are not race conditions.
|
|
|
|
std::lock_guard<std::mutex> Lock(PublishMu);
|
|
|
|
if (CanPublishResults)
|
|
|
|
Publish();
|
|
|
|
};
|
|
|
|
if (*AST) {
|
|
|
|
trace::Span Span("Running main AST callback");
|
|
|
|
Callbacks.onMainAST(FileName, **AST, RunPublish);
|
|
|
|
} else {
|
|
|
|
// Failed to build the AST, at least report diagnostics from the
|
|
|
|
// command line if there were any.
|
|
|
|
// FIXME: we might have got more errors while trying to build the
|
|
|
|
// AST, surface them too.
|
|
|
|
Callbacks.onFailedAST(FileName, Inputs.Version, CIDiags, RunPublish);
|
|
|
|
}
|
|
|
|
|
|
|
|
// AST might've been built for an older version of the source, as ASTWorker
|
|
|
|
// queue raced ahead while we were waiting on the preamble. In that case the
|
|
|
|
// queue can't reuse the AST.
|
|
|
|
if (InputsAreLatest) {
|
|
|
|
RanASTCallback = *AST != nullptr;
|
|
|
|
IdleASTs.put(this, std::move(*AST));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-08 15:37:35 +08:00
|
|
|
std::shared_ptr<const PreambleData>
|
|
|
|
ASTWorker::getPossiblyStalePreamble() const {
|
2020-03-16 04:43:00 +08:00
|
|
|
std::lock_guard<std::mutex> Lock(Mutex);
|
|
|
|
return LatestPreamble;
|
2018-02-08 15:37:35 +08:00
|
|
|
}
|
|
|
|
|
2018-08-30 23:07:34 +08:00
|
|
|
void ASTWorker::getCurrentPreamble(
|
2019-01-07 23:45:19 +08:00
|
|
|
llvm::unique_function<void(std::shared_ptr<const PreambleData>)> Callback) {
|
2018-08-30 23:07:34 +08:00
|
|
|
// We could just call startTask() to throw the read on the queue, knowing
|
|
|
|
// it will run after any updates. But we know this task is cheap, so to
|
|
|
|
// improve latency we cheat: insert it on the queue after the last update.
|
|
|
|
std::unique_lock<std::mutex> Lock(Mutex);
|
|
|
|
auto LastUpdate =
|
|
|
|
std::find_if(Requests.rbegin(), Requests.rend(),
|
|
|
|
[](const Request &R) { return R.UpdateType.hasValue(); });
|
2020-03-10 23:52:31 +08:00
|
|
|
// If there were no writes in the queue, and CurrentRequest is not a write,
|
|
|
|
// the preamble is ready now.
|
|
|
|
if (LastUpdate == Requests.rend() &&
|
|
|
|
(!CurrentRequest || CurrentRequest->UpdateType.hasValue())) {
|
2018-08-30 23:07:34 +08:00
|
|
|
Lock.unlock();
|
|
|
|
return Callback(getPossiblyStalePreamble());
|
|
|
|
}
|
|
|
|
assert(!RunSync && "Running synchronously, but queue is non-empty!");
|
|
|
|
Requests.insert(LastUpdate.base(),
|
2019-08-15 22:16:06 +08:00
|
|
|
Request{[Callback = std::move(Callback), this]() mutable {
|
|
|
|
Callback(getPossiblyStalePreamble());
|
|
|
|
},
|
2018-08-30 23:07:34 +08:00
|
|
|
"GetPreamble", steady_clock::now(),
|
|
|
|
Context::current().clone(),
|
[clangd] Cancel certain operations if the file changes before we start.
Summary:
Otherwise they can force us to build lots of snapshots that we don't need.
Particularly, try to do this for operations that are frequently
generated by editors without explicit user interaction, and where
editing the file makes the result less useful. (Code action
enumeration is a good example).
https://github.com/clangd/clangd/issues/298
This doesn't return the "right" LSP error code (ContentModified) to the client,
we need to teach the cancellation API to distinguish between different causes.
Reviewers: kadircet
Subscribers: ilya-biryukov, javed.absar, MaskRay, jkorous, arphaman, jfb, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D75602
2020-03-04 21:04:17 +08:00
|
|
|
/*UpdateType=*/None,
|
|
|
|
/*InvalidationPolicy=*/TUScheduler::NoInvalidation,
|
|
|
|
/*Invalidate=*/nullptr});
|
2018-08-30 23:07:34 +08:00
|
|
|
Lock.unlock();
|
|
|
|
RequestsCV.notify_all();
|
|
|
|
}
|
|
|
|
|
2020-03-16 04:43:00 +08:00
|
|
|
void ASTWorker::waitForFirstPreamble() const { BuiltFirstPreamble.wait(); }
|
2018-07-09 18:45:33 +08:00
|
|
|
|
2019-04-15 20:32:28 +08:00
|
|
|
std::shared_ptr<const ParseInputs> ASTWorker::getCurrentFileInputs() const {
|
|
|
|
std::unique_lock<std::mutex> Lock(Mutex);
|
|
|
|
return FileInputs;
|
|
|
|
}
|
|
|
|
|
|
|
|
tooling::CompileCommand ASTWorker::getCurrentCompileCommand() const {
|
|
|
|
std::unique_lock<std::mutex> Lock(Mutex);
|
|
|
|
return FileInputs->CompileCommand;
|
|
|
|
}
|
|
|
|
|
2018-02-08 15:37:35 +08:00
|
|
|
std::size_t ASTWorker::getUsedBytes() const {
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
// Note that we don't report the size of ASTs currently used for processing
|
|
|
|
// the in-flight requests. We used this information for debugging purposes
|
|
|
|
// only, so this should be fine.
|
|
|
|
std::size_t Result = IdleASTs.getUsedBytes(this);
|
|
|
|
if (auto Preamble = getPossiblyStalePreamble())
|
|
|
|
Result += Preamble->Preamble.getSize();
|
|
|
|
return Result;
|
2018-02-08 15:37:35 +08:00
|
|
|
}
|
|
|
|
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
bool ASTWorker::isASTCached() const { return IdleASTs.getUsedBytes(this) != 0; }
|
|
|
|
|
2018-02-08 15:37:35 +08:00
|
|
|
void ASTWorker::stop() {
|
[clangd] Cleanup: make diagnostics callbacks from TUScheduler non-racy
Summary:
Previously, removeDoc followed by an addDoc to TUScheduler resulted in
racy diagnostic responses, i.e. the old dianostics could be delivered
to the client after the new ones by TUScheduler.
To workaround this, we tracked a version number in ClangdServer and
discarded stale diagnostics. After this commit, the TUScheduler will
stop delivering diagnostics for removed files and the workaround in
ClangdServer is not required anymore.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: javed.absar, ioeric, MaskRay, jkorous, arphaman, jfb, kadircet, cfe-commits
Differential Revision: https://reviews.llvm.org/D54829
llvm-svn: 347468
2018-11-22 23:39:54 +08:00
|
|
|
{
|
2019-07-19 21:51:01 +08:00
|
|
|
std::lock_guard<std::mutex> Lock(PublishMu);
|
|
|
|
CanPublishResults = false;
|
[clangd] Cleanup: make diagnostics callbacks from TUScheduler non-racy
Summary:
Previously, removeDoc followed by an addDoc to TUScheduler resulted in
racy diagnostic responses, i.e. the old dianostics could be delivered
to the client after the new ones by TUScheduler.
To workaround this, we tracked a version number in ClangdServer and
discarded stale diagnostics. After this commit, the TUScheduler will
stop delivering diagnostics for removed files and the workaround in
ClangdServer is not required anymore.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: javed.absar, ioeric, MaskRay, jkorous, arphaman, jfb, kadircet, cfe-commits
Differential Revision: https://reviews.llvm.org/D54829
llvm-svn: 347468
2018-11-22 23:39:54 +08:00
|
|
|
}
|
2018-02-08 15:37:35 +08:00
|
|
|
{
|
|
|
|
std::lock_guard<std::mutex> Lock(Mutex);
|
|
|
|
assert(!Done && "stop() called twice");
|
|
|
|
Done = true;
|
|
|
|
}
|
2020-03-16 04:43:00 +08:00
|
|
|
// We are no longer going to build any preambles, let the waiters know that.
|
|
|
|
BuiltFirstPreamble.notify();
|
|
|
|
PreamblePeer.stop();
|
2020-03-18 02:08:23 +08:00
|
|
|
Status.stop();
|
2018-02-13 16:59:23 +08:00
|
|
|
RequestsCV.notify_all();
|
2018-02-08 15:37:35 +08:00
|
|
|
}
|
|
|
|
|
2019-01-07 23:45:19 +08:00
|
|
|
void ASTWorker::startTask(llvm::StringRef Name,
|
|
|
|
llvm::unique_function<void()> Task,
|
[clangd] Cancel certain operations if the file changes before we start.
Summary:
Otherwise they can force us to build lots of snapshots that we don't need.
Particularly, try to do this for operations that are frequently
generated by editors without explicit user interaction, and where
editing the file makes the result less useful. (Code action
enumeration is a good example).
https://github.com/clangd/clangd/issues/298
This doesn't return the "right" LSP error code (ContentModified) to the client,
we need to teach the cancellation API to distinguish between different causes.
Reviewers: kadircet
Subscribers: ilya-biryukov, javed.absar, MaskRay, jkorous, arphaman, jfb, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D75602
2020-03-04 21:04:17 +08:00
|
|
|
llvm::Optional<WantDiagnostics> UpdateType,
|
|
|
|
TUScheduler::ASTActionInvalidation Invalidation) {
|
2018-02-08 15:37:35 +08:00
|
|
|
if (RunSync) {
|
|
|
|
assert(!Done && "running a task after stop()");
|
2019-01-07 23:45:19 +08:00
|
|
|
trace::Span Tracer(Name + ":" + llvm::sys::path::filename(FileName));
|
2018-02-08 15:37:35 +08:00
|
|
|
Task();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
{
|
|
|
|
std::lock_guard<std::mutex> Lock(Mutex);
|
|
|
|
assert(!Done && "running a task after stop()");
|
[clangd] Cancel certain operations if the file changes before we start.
Summary:
Otherwise they can force us to build lots of snapshots that we don't need.
Particularly, try to do this for operations that are frequently
generated by editors without explicit user interaction, and where
editing the file makes the result less useful. (Code action
enumeration is a good example).
https://github.com/clangd/clangd/issues/298
This doesn't return the "right" LSP error code (ContentModified) to the client,
we need to teach the cancellation API to distinguish between different causes.
Reviewers: kadircet
Subscribers: ilya-biryukov, javed.absar, MaskRay, jkorous, arphaman, jfb, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D75602
2020-03-04 21:04:17 +08:00
|
|
|
// Cancel any requests invalidated by this request.
|
|
|
|
if (UpdateType) {
|
|
|
|
for (auto &R : llvm::reverse(Requests)) {
|
|
|
|
if (R.InvalidationPolicy == TUScheduler::InvalidateOnUpdate)
|
|
|
|
R.Invalidate();
|
|
|
|
if (R.UpdateType)
|
|
|
|
break; // Older requests were already invalidated by the older update.
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Allow this request to be cancelled if invalidated.
|
|
|
|
Context Ctx = Context::current().derive(kFileBeingProcessed, FileName);
|
|
|
|
Canceler Invalidate = nullptr;
|
|
|
|
if (Invalidation) {
|
|
|
|
WithContext WC(std::move(Ctx));
|
|
|
|
std::tie(Ctx, Invalidate) = cancelableTask();
|
|
|
|
}
|
|
|
|
Requests.push_back({std::move(Task), std::string(Name), steady_clock::now(),
|
|
|
|
std::move(Ctx), UpdateType, Invalidation,
|
|
|
|
std::move(Invalidate)});
|
2018-02-22 21:11:12 +08:00
|
|
|
}
|
2018-02-13 16:59:23 +08:00
|
|
|
RequestsCV.notify_all();
|
2018-02-08 15:37:35 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
void ASTWorker::run() {
|
|
|
|
while (true) {
|
|
|
|
{
|
|
|
|
std::unique_lock<std::mutex> Lock(Mutex);
|
2020-03-10 23:52:31 +08:00
|
|
|
assert(!CurrentRequest && "A task is already running, multiple workers?");
|
2018-03-02 16:56:37 +08:00
|
|
|
for (auto Wait = scheduleLocked(); !Wait.expired();
|
|
|
|
Wait = scheduleLocked()) {
|
2020-03-16 04:43:00 +08:00
|
|
|
assert(PreambleRequests.empty() &&
|
|
|
|
"Preamble updates should be scheduled immediately");
|
2018-03-02 16:56:37 +08:00
|
|
|
if (Done) {
|
|
|
|
if (Requests.empty())
|
|
|
|
return;
|
|
|
|
else // Even though Done is set, finish pending requests.
|
|
|
|
break; // However, skip delays to shutdown fast.
|
|
|
|
}
|
|
|
|
|
|
|
|
// Tracing: we have a next request, attribute this sleep to it.
|
2019-01-07 23:45:19 +08:00
|
|
|
llvm::Optional<WithContext> Ctx;
|
|
|
|
llvm::Optional<trace::Span> Tracer;
|
2018-03-02 16:56:37 +08:00
|
|
|
if (!Requests.empty()) {
|
|
|
|
Ctx.emplace(Requests.front().Ctx.clone());
|
|
|
|
Tracer.emplace("Debounce");
|
|
|
|
SPAN_ATTACH(*Tracer, "next_request", Requests.front().Name);
|
2018-12-06 17:41:04 +08:00
|
|
|
if (!(Wait == Deadline::infinity())) {
|
2020-03-18 02:08:23 +08:00
|
|
|
Status.update([&](TUStatus &Status) {
|
|
|
|
Status.ASTActivity.K = ASTAction::Queued;
|
|
|
|
Status.ASTActivity.Name = Requests.front().Name;
|
|
|
|
});
|
2018-03-02 16:56:37 +08:00
|
|
|
SPAN_ATTACH(*Tracer, "sleep_ms",
|
|
|
|
std::chrono::duration_cast<std::chrono::milliseconds>(
|
|
|
|
Wait.time() - steady_clock::now())
|
|
|
|
.count());
|
2018-12-06 17:41:04 +08:00
|
|
|
}
|
2018-03-02 16:56:37 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
wait(Lock, RequestsCV, Wait);
|
2018-02-08 15:37:35 +08:00
|
|
|
}
|
2020-03-16 04:43:00 +08:00
|
|
|
// Any request in ReceivedPreambles is at least as old as the
|
|
|
|
// Requests.front(), so prefer them first to preserve LSP order.
|
|
|
|
if (!PreambleRequests.empty()) {
|
|
|
|
CurrentRequest = std::move(PreambleRequests.front());
|
|
|
|
PreambleRequests.pop();
|
|
|
|
} else {
|
|
|
|
CurrentRequest = std::move(Requests.front());
|
|
|
|
Requests.pop_front();
|
|
|
|
}
|
2018-02-08 15:37:35 +08:00
|
|
|
} // unlock Mutex
|
|
|
|
|
2020-03-10 23:52:31 +08:00
|
|
|
// It is safe to perform reads to CurrentRequest without holding the lock as
|
|
|
|
// only writer is also this thread.
|
2018-02-19 17:56:28 +08:00
|
|
|
{
|
2018-12-13 21:09:50 +08:00
|
|
|
std::unique_lock<Semaphore> Lock(Barrier, std::try_to_lock);
|
|
|
|
if (!Lock.owns_lock()) {
|
2020-03-18 02:08:23 +08:00
|
|
|
Status.update([&](TUStatus &Status) {
|
|
|
|
Status.ASTActivity.K = ASTAction::Queued;
|
|
|
|
Status.ASTActivity.Name = CurrentRequest->Name;
|
|
|
|
});
|
2018-12-13 21:09:50 +08:00
|
|
|
Lock.lock();
|
|
|
|
}
|
2020-03-10 23:52:31 +08:00
|
|
|
WithContext Guard(std::move(CurrentRequest->Ctx));
|
|
|
|
trace::Span Tracer(CurrentRequest->Name);
|
2020-03-18 02:08:23 +08:00
|
|
|
Status.update([&](TUStatus &Status) {
|
|
|
|
Status.ASTActivity.K = ASTAction::RunningAction;
|
|
|
|
Status.ASTActivity.Name = CurrentRequest->Name;
|
|
|
|
});
|
2020-03-10 23:52:31 +08:00
|
|
|
CurrentRequest->Action();
|
2018-02-19 17:56:28 +08:00
|
|
|
}
|
2018-02-13 16:59:23 +08:00
|
|
|
|
2018-12-06 17:41:04 +08:00
|
|
|
bool IsEmpty = false;
|
2018-02-13 16:59:23 +08:00
|
|
|
{
|
|
|
|
std::lock_guard<std::mutex> Lock(Mutex);
|
2020-03-10 23:52:31 +08:00
|
|
|
CurrentRequest.reset();
|
2020-03-16 04:43:00 +08:00
|
|
|
IsEmpty = Requests.empty() && PreambleRequests.empty();
|
2018-02-13 16:59:23 +08:00
|
|
|
}
|
2020-03-18 02:08:23 +08:00
|
|
|
if (IsEmpty) {
|
|
|
|
Status.update([&](TUStatus &Status) {
|
|
|
|
Status.ASTActivity.K = ASTAction::Idle;
|
|
|
|
Status.ASTActivity.Name = "";
|
|
|
|
});
|
|
|
|
}
|
2018-02-13 16:59:23 +08:00
|
|
|
RequestsCV.notify_all();
|
2018-02-08 15:37:35 +08:00
|
|
|
}
|
|
|
|
}
|
2018-02-13 16:59:23 +08:00
|
|
|
|
2018-03-02 16:56:37 +08:00
|
|
|
Deadline ASTWorker::scheduleLocked() {
|
2020-03-16 04:43:00 +08:00
|
|
|
// Process new preambles immediately.
|
|
|
|
if (!PreambleRequests.empty())
|
|
|
|
return Deadline::zero();
|
2018-03-02 16:56:37 +08:00
|
|
|
if (Requests.empty())
|
|
|
|
return Deadline::infinity(); // Wait for new requests.
|
[clangd] Respect task cancellation in TUScheduler.
Summary:
- Reads are never executed if canceled before ready-to run.
In practice, we finalize cancelled reads eagerly and out-of-order.
- Cancelled reads don't prevent prior updates from being elided, as they don't
actually depend on the result of the update.
- Updates are downgraded from WantDiagnostics::Yes to WantDiagnostics::Auto when
cancelled, which allows them to be elided when all dependent reads are
cancelled and there are subsequent writes. (e.g. when the queue is backed up
with cancelled requests).
The queue operations aren't optimal (we scan the whole queue for cancelled
tasks every time the scheduler runs, and check cancellation twice in the end).
However I believe these costs are still trivial in practice (compared to any
AST operation) and the logic can be cleanly separated from the rest of the
scheduler.
Reviewers: ilya-biryukov
Subscribers: javed.absar, ioeric, MaskRay, jkorous, arphaman, kadircet, cfe-commits
Differential Revision: https://reviews.llvm.org/D54746
llvm-svn: 347450
2018-11-22 18:22:16 +08:00
|
|
|
// Handle cancelled requests first so the rest of the scheduler doesn't.
|
|
|
|
for (auto I = Requests.begin(), E = Requests.end(); I != E; ++I) {
|
|
|
|
if (!isCancelled(I->Ctx)) {
|
|
|
|
// Cancellations after the first read don't affect current scheduling.
|
|
|
|
if (I->UpdateType == None)
|
|
|
|
break;
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
// Cancelled reads are moved to the front of the queue and run immediately.
|
|
|
|
if (I->UpdateType == None) {
|
|
|
|
Request R = std::move(*I);
|
|
|
|
Requests.erase(I);
|
|
|
|
Requests.push_front(std::move(R));
|
|
|
|
return Deadline::zero();
|
|
|
|
}
|
|
|
|
// Cancelled updates are downgraded to auto-diagnostics, and may be elided.
|
|
|
|
if (I->UpdateType == WantDiagnostics::Yes)
|
|
|
|
I->UpdateType = WantDiagnostics::Auto;
|
|
|
|
}
|
|
|
|
|
[clangd] Track document versions, include them with diags, enhance logs
Summary:
This ties to an LSP feature (diagnostic versioning) but really a lot
of the value is in being able to log what's happening with file versions
and queues more descriptively and clearly.
As such it's fairly invasive, for a logging patch :-\
Key decisions:
- at the LSP layer, we don't reqire the client to provide versions (LSP
makes it mandatory but we never enforced it). If not provided,
versions start at 0 and increment. DraftStore handles this.
- don't propagate magically using contexts, but rather manually:
addDocument -> ParseInputs -> (ParsedAST, Preamble, various callbacks)
Context-propagation would hide the versions from ClangdServer, which
would make producing good log messages hard
- within ClangdServer, treat versions as opaque and unordered.
std::string is a convenient type for this, and allows richer versions
for embedders. They're "mandatory" but "null" is a reasonable default.
Subscribers: ilya-biryukov, javed.absar, MaskRay, jkorous, arphaman, kadircet, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D75582
2020-03-04 07:33:29 +08:00
|
|
|
while (shouldSkipHeadLocked()) {
|
|
|
|
vlog("ASTWorker skipping {0} for {1}", Requests.front().Name, FileName);
|
2018-03-02 16:56:37 +08:00
|
|
|
Requests.pop_front();
|
[clangd] Track document versions, include them with diags, enhance logs
Summary:
This ties to an LSP feature (diagnostic versioning) but really a lot
of the value is in being able to log what's happening with file versions
and queues more descriptively and clearly.
As such it's fairly invasive, for a logging patch :-\
Key decisions:
- at the LSP layer, we don't reqire the client to provide versions (LSP
makes it mandatory but we never enforced it). If not provided,
versions start at 0 and increment. DraftStore handles this.
- don't propagate magically using contexts, but rather manually:
addDocument -> ParseInputs -> (ParsedAST, Preamble, various callbacks)
Context-propagation would hide the versions from ClangdServer, which
would make producing good log messages hard
- within ClangdServer, treat versions as opaque and unordered.
std::string is a convenient type for this, and allows richer versions
for embedders. They're "mandatory" but "null" is a reasonable default.
Subscribers: ilya-biryukov, javed.absar, MaskRay, jkorous, arphaman, kadircet, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D75582
2020-03-04 07:33:29 +08:00
|
|
|
}
|
2018-03-02 16:56:37 +08:00
|
|
|
assert(!Requests.empty() && "skipped the whole queue");
|
|
|
|
// Some updates aren't dead yet, but never end up being used.
|
|
|
|
// e.g. the first keystroke is live until obsoleted by the second.
|
2020-02-04 22:41:39 +08:00
|
|
|
// We debounce "maybe-unused" writes, sleeping in case they become dead.
|
2018-03-02 16:56:37 +08:00
|
|
|
// But don't delay reads (including updates where diagnostics are needed).
|
|
|
|
for (const auto &R : Requests)
|
|
|
|
if (R.UpdateType == None || R.UpdateType == WantDiagnostics::Yes)
|
|
|
|
return Deadline::zero();
|
|
|
|
// Front request needs to be debounced, so determine when we're ready.
|
2020-02-04 22:41:39 +08:00
|
|
|
Deadline D(Requests.front().AddTime + UpdateDebounce.compute(RebuildTimes));
|
2018-03-02 16:56:37 +08:00
|
|
|
return D;
|
|
|
|
}
|
|
|
|
|
2018-02-22 21:11:12 +08:00
|
|
|
// Returns true if Requests.front() is a dead update that can be skipped.
|
|
|
|
bool ASTWorker::shouldSkipHeadLocked() const {
|
|
|
|
assert(!Requests.empty());
|
|
|
|
auto Next = Requests.begin();
|
|
|
|
auto UpdateType = Next->UpdateType;
|
|
|
|
if (!UpdateType) // Only skip updates.
|
|
|
|
return false;
|
|
|
|
++Next;
|
|
|
|
// An update is live if its AST might still be read.
|
|
|
|
// That is, if it's not immediately followed by another update.
|
|
|
|
if (Next == Requests.end() || !Next->UpdateType)
|
|
|
|
return false;
|
|
|
|
// The other way an update can be live is if its diagnostics might be used.
|
|
|
|
switch (*UpdateType) {
|
|
|
|
case WantDiagnostics::Yes:
|
|
|
|
return false; // Always used.
|
|
|
|
case WantDiagnostics::No:
|
|
|
|
return true; // Always dead.
|
|
|
|
case WantDiagnostics::Auto:
|
|
|
|
// Used unless followed by an update that generates diagnostics.
|
|
|
|
for (; Next != Requests.end(); ++Next)
|
|
|
|
if (Next->UpdateType == WantDiagnostics::Yes ||
|
|
|
|
Next->UpdateType == WantDiagnostics::Auto)
|
|
|
|
return true; // Prefer later diagnostics.
|
|
|
|
return false;
|
|
|
|
}
|
2018-02-23 00:12:27 +08:00
|
|
|
llvm_unreachable("Unknown WantDiagnostics");
|
2018-02-22 21:11:12 +08:00
|
|
|
}
|
|
|
|
|
2018-02-13 16:59:23 +08:00
|
|
|
bool ASTWorker::blockUntilIdle(Deadline Timeout) const {
|
|
|
|
std::unique_lock<std::mutex> Lock(Mutex);
|
2020-03-16 04:43:00 +08:00
|
|
|
return wait(Lock, RequestsCV, Timeout, [&] {
|
|
|
|
return PreambleRequests.empty() && Requests.empty() && !CurrentRequest;
|
|
|
|
});
|
2018-02-13 16:59:23 +08:00
|
|
|
}
|
|
|
|
|
2018-12-20 23:39:12 +08:00
|
|
|
// Render a TUAction to a user-facing string representation.
|
|
|
|
// TUAction represents clangd-internal states, we don't intend to expose them
|
|
|
|
// to users (say C++ programmers) directly to avoid confusion, we use terms that
|
|
|
|
// are familiar by C++ programmers.
|
2020-03-18 02:08:23 +08:00
|
|
|
std::string renderTUAction(const PreambleAction PA, const ASTAction &AA) {
|
|
|
|
llvm::SmallVector<std::string, 2> Result;
|
|
|
|
switch (PA) {
|
|
|
|
case PreambleAction::Building:
|
|
|
|
Result.push_back("parsing includes");
|
2018-12-20 23:39:12 +08:00
|
|
|
break;
|
2020-03-18 02:08:23 +08:00
|
|
|
case PreambleAction::Idle:
|
|
|
|
// We handle idle specially below.
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
switch (AA.K) {
|
|
|
|
case ASTAction::Queued:
|
|
|
|
Result.push_back("file is queued");
|
2018-12-20 23:39:12 +08:00
|
|
|
break;
|
2020-03-18 02:08:23 +08:00
|
|
|
case ASTAction::RunningAction:
|
|
|
|
Result.push_back("running " + AA.Name);
|
2018-12-20 23:39:12 +08:00
|
|
|
break;
|
2020-03-18 02:08:23 +08:00
|
|
|
case ASTAction::Building:
|
|
|
|
Result.push_back("parsing main file");
|
2018-12-20 23:39:12 +08:00
|
|
|
break;
|
2020-03-18 02:08:23 +08:00
|
|
|
case ASTAction::Idle:
|
|
|
|
// We handle idle specially below.
|
2018-12-20 23:39:12 +08:00
|
|
|
break;
|
|
|
|
}
|
2020-03-18 02:08:23 +08:00
|
|
|
if (Result.empty())
|
|
|
|
return "idle";
|
|
|
|
return llvm::join(Result, ",");
|
2018-12-20 23:39:12 +08:00
|
|
|
}
|
|
|
|
|
2018-02-08 15:37:35 +08:00
|
|
|
} // namespace
|
|
|
|
|
2018-01-31 16:51:16 +08:00
|
|
|
unsigned getDefaultAsyncThreadsCount() {
|
[Support] On Windows, ensure hardware_concurrency() extends to all CPU sockets and all NUMA groups
The goal of this patch is to maximize CPU utilization on multi-socket or high core count systems, so that parallel computations such as LLD/ThinLTO can use all hardware threads in the system. Before this patch, on Windows, a maximum of 64 hardware threads could be used at most, in some cases dispatched only on one CPU socket.
== Background ==
Windows doesn't have a flat cpu_set_t like Linux. Instead, it projects hardware CPUs (or NUMA nodes) to applications through a concept of "processor groups". A "processor" is the smallest unit of execution on a CPU, that is, an hyper-thread if SMT is active; a core otherwise. There's a limit of 32-bit processors on older 32-bit versions of Windows, which later was raised to 64-processors with 64-bit versions of Windows. This limit comes from the affinity mask, which historically is represented by the sizeof(void*). Consequently, the concept of "processor groups" was introduced for dealing with systems with more than 64 hyper-threads.
By default, the Windows OS assigns only one "processor group" to each starting application, in a round-robin manner. If the application wants to use more processors, it needs to programmatically enable it, by assigning threads to other "processor groups". This also means that affinity cannot cross "processor group" boundaries; one can only specify a "preferred" group on start-up, but the application is free to allocate more groups if it wants to.
This creates a peculiar situation, where newer CPUs like the AMD EPYC 7702P (64-cores, 128-hyperthreads) are projected by the OS as two (2) "processor groups". This means that by default, an application can only use half of the cores. This situation could only get worse in the years to come, as dies with more cores will appear on the market.
== The problem ==
The heavyweight_hardware_concurrency() API was introduced so that only *one hardware thread per core* was used. Once that API returns, that original intention is lost, only the number of threads is retained. Consider a situation, on Windows, where the system has 2 CPU sockets, 18 cores each, each core having 2 hyper-threads, for a total of 72 hyper-threads. Both heavyweight_hardware_concurrency() and hardware_concurrency() currently return 36, because on Windows they are simply wrappers over std::thread::hardware_concurrency() -- which can only return processors from the current "processor group".
== The changes in this patch ==
To solve this situation, we capture (and retain) the initial intention until the point of usage, through a new ThreadPoolStrategy class. The number of threads to use is deferred as late as possible, until the moment where the std::threads are created (ThreadPool in the case of ThinLTO).
When using hardware_concurrency(), setting ThreadCount to 0 now means to use all the possible hardware CPU (SMT) threads. Providing a ThreadCount above to the maximum number of threads will have no effect, the maximum will be used instead.
The heavyweight_hardware_concurrency() is similar to hardware_concurrency(), except that only one thread per hardware *core* will be used.
When LLVM_ENABLE_THREADS is OFF, the threading APIs will always return 1, to ensure any caller loops will be exercised at least once.
Differential Revision: https://reviews.llvm.org/D71775
2020-02-14 11:49:57 +08:00
|
|
|
return llvm::heavyweight_hardware_concurrency().compute_thread_count();
|
2018-01-31 16:51:16 +08:00
|
|
|
}
|
|
|
|
|
2018-12-20 23:39:12 +08:00
|
|
|
FileStatus TUStatus::render(PathRef File) const {
|
|
|
|
FileStatus FStatus;
|
|
|
|
FStatus.uri = URIForFile::canonicalize(File, /*TUPath=*/File);
|
2020-03-18 02:08:23 +08:00
|
|
|
FStatus.state = renderTUAction(PreambleActivity, ASTActivity);
|
2018-12-20 23:39:12 +08:00
|
|
|
return FStatus;
|
|
|
|
}
|
|
|
|
|
2018-02-08 15:37:35 +08:00
|
|
|
struct TUScheduler::FileData {
|
|
|
|
/// Latest inputs, passed to TUScheduler::update().
|
2018-03-15 01:46:52 +08:00
|
|
|
std::string Contents;
|
2018-02-08 15:37:35 +08:00
|
|
|
ASTWorkerHandle Worker;
|
|
|
|
};
|
|
|
|
|
2019-04-15 20:32:28 +08:00
|
|
|
TUScheduler::TUScheduler(const GlobalCompilationDatabase &CDB,
|
2020-02-03 18:18:13 +08:00
|
|
|
const Options &Opts,
|
|
|
|
std::unique_ptr<ParsingCallbacks> Callbacks)
|
|
|
|
: CDB(CDB), StorePreamblesInMemory(Opts.StorePreamblesInMemory),
|
2018-09-04 00:37:59 +08:00
|
|
|
Callbacks(Callbacks ? move(Callbacks)
|
2019-08-15 07:52:23 +08:00
|
|
|
: std::make_unique<ParsingCallbacks>()),
|
2020-02-03 18:18:13 +08:00
|
|
|
Barrier(Opts.AsyncThreadsCount),
|
|
|
|
IdleASTs(
|
|
|
|
std::make_unique<ASTCache>(Opts.RetentionPolicy.MaxRetainedASTs)),
|
|
|
|
UpdateDebounce(Opts.UpdateDebounce) {
|
|
|
|
if (0 < Opts.AsyncThreadsCount) {
|
2018-02-13 16:59:23 +08:00
|
|
|
PreambleTasks.emplace();
|
|
|
|
WorkerThreads.emplace();
|
|
|
|
}
|
2018-02-08 15:37:35 +08:00
|
|
|
}
|
2018-01-31 16:51:16 +08:00
|
|
|
|
2018-02-08 15:37:35 +08:00
|
|
|
TUScheduler::~TUScheduler() {
|
|
|
|
// Notify all workers that they need to stop.
|
|
|
|
Files.clear();
|
|
|
|
|
|
|
|
// Wait for all in-flight tasks to finish.
|
2018-02-13 16:59:23 +08:00
|
|
|
if (PreambleTasks)
|
|
|
|
PreambleTasks->wait();
|
|
|
|
if (WorkerThreads)
|
|
|
|
WorkerThreads->wait();
|
|
|
|
}
|
|
|
|
|
|
|
|
bool TUScheduler::blockUntilIdle(Deadline D) const {
|
|
|
|
for (auto &File : Files)
|
|
|
|
if (!File.getValue()->Worker->blockUntilIdle(D))
|
|
|
|
return false;
|
|
|
|
if (PreambleTasks)
|
|
|
|
if (!PreambleTasks->wait(D))
|
|
|
|
return false;
|
|
|
|
return true;
|
2018-02-08 15:37:35 +08:00
|
|
|
}
|
2018-01-31 16:51:16 +08:00
|
|
|
|
2019-07-12 18:18:42 +08:00
|
|
|
bool TUScheduler::update(PathRef File, ParseInputs Inputs,
|
2018-11-23 01:27:08 +08:00
|
|
|
WantDiagnostics WantDiags) {
|
2018-02-08 15:37:35 +08:00
|
|
|
std::unique_ptr<FileData> &FD = Files[File];
|
2019-07-12 18:18:42 +08:00
|
|
|
bool NewFile = FD == nullptr;
|
2018-02-08 15:37:35 +08:00
|
|
|
if (!FD) {
|
|
|
|
// Create a new worker to process the AST-related tasks.
|
2018-07-26 20:05:31 +08:00
|
|
|
ASTWorkerHandle Worker = ASTWorker::create(
|
2019-04-15 20:32:28 +08:00
|
|
|
File, CDB, *IdleASTs,
|
|
|
|
WorkerThreads ? WorkerThreads.getPointer() : nullptr, Barrier,
|
|
|
|
UpdateDebounce, StorePreamblesInMemory, *Callbacks);
|
|
|
|
FD = std::unique_ptr<FileData>(
|
|
|
|
new FileData{Inputs.Contents, std::move(Worker)});
|
2018-02-08 15:37:35 +08:00
|
|
|
} else {
|
2018-03-15 01:46:52 +08:00
|
|
|
FD->Contents = Inputs.Contents;
|
2018-01-31 16:51:16 +08:00
|
|
|
}
|
2018-11-23 01:27:08 +08:00
|
|
|
FD->Worker->update(std::move(Inputs), WantDiags);
|
2019-07-12 18:18:42 +08:00
|
|
|
return NewFile;
|
2018-02-08 15:37:35 +08:00
|
|
|
}
|
2018-02-07 03:22:40 +08:00
|
|
|
|
2018-02-08 15:37:35 +08:00
|
|
|
void TUScheduler::remove(PathRef File) {
|
|
|
|
bool Removed = Files.erase(File);
|
|
|
|
if (!Removed)
|
[clangd] Upgrade logging facilities with levels and formatv.
Summary:
log() is split into four functions:
- elog()/log()/vlog() have different severity levels, allowing filtering
- dlog() is a lazy macro which uses LLVM_DEBUG - it logs to the logger, but
conditionally based on -debug-only flag and is omitted in release builds
All logging functions use formatv-style format strings now, e.g:
log("Could not resolve URI {0}: {1}", URI, Result.takeError());
Existing log sites have been split between elog/log/vlog by best guess.
This includes a workaround for passing Error to formatv that can be
simplified when D49170 or similar lands.
Subscribers: ilya-biryukov, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D49008
llvm-svn: 336785
2018-07-11 18:35:11 +08:00
|
|
|
elog("Trying to remove file from TUScheduler that is not tracked: {0}",
|
|
|
|
File);
|
2018-01-31 16:51:16 +08:00
|
|
|
}
|
|
|
|
|
2019-10-23 20:40:20 +08:00
|
|
|
llvm::StringMap<std::string> TUScheduler::getAllFileContents() const {
|
|
|
|
llvm::StringMap<std::string> Results;
|
|
|
|
for (auto &It : Files)
|
|
|
|
Results.try_emplace(It.getKey(), It.getValue()->Contents);
|
|
|
|
return Results;
|
|
|
|
}
|
|
|
|
|
2019-01-07 23:45:19 +08:00
|
|
|
void TUScheduler::run(llvm::StringRef Name,
|
|
|
|
llvm::unique_function<void()> Action) {
|
2018-10-25 22:19:14 +08:00
|
|
|
if (!PreambleTasks)
|
|
|
|
return Action();
|
2020-02-03 18:31:51 +08:00
|
|
|
PreambleTasks->runAsync(Name, [this, Ctx = Context::current().clone(),
|
2019-10-23 16:18:09 +08:00
|
|
|
Action = std::move(Action)]() mutable {
|
2020-02-03 18:31:51 +08:00
|
|
|
std::lock_guard<Semaphore> BarrierLock(Barrier);
|
2019-10-23 16:18:09 +08:00
|
|
|
WithContext WC(std::move(Ctx));
|
|
|
|
Action();
|
|
|
|
});
|
2018-10-25 22:19:14 +08:00
|
|
|
}
|
|
|
|
|
2018-01-31 16:51:16 +08:00
|
|
|
void TUScheduler::runWithAST(
|
2019-01-07 23:45:19 +08:00
|
|
|
llvm::StringRef Name, PathRef File,
|
[clangd] Cancel certain operations if the file changes before we start.
Summary:
Otherwise they can force us to build lots of snapshots that we don't need.
Particularly, try to do this for operations that are frequently
generated by editors without explicit user interaction, and where
editing the file makes the result less useful. (Code action
enumeration is a good example).
https://github.com/clangd/clangd/issues/298
This doesn't return the "right" LSP error code (ContentModified) to the client,
we need to teach the cancellation API to distinguish between different causes.
Reviewers: kadircet
Subscribers: ilya-biryukov, javed.absar, MaskRay, jkorous, arphaman, jfb, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D75602
2020-03-04 21:04:17 +08:00
|
|
|
llvm::unique_function<void(llvm::Expected<InputsAndAST>)> Action,
|
|
|
|
TUScheduler::ASTActionInvalidation Invalidation) {
|
2018-02-08 15:37:35 +08:00
|
|
|
auto It = Files.find(File);
|
|
|
|
if (It == Files.end()) {
|
2019-01-07 23:45:19 +08:00
|
|
|
Action(llvm::make_error<LSPError>(
|
|
|
|
"trying to get AST for non-added document", ErrorCode::InvalidParams));
|
2018-01-31 16:51:16 +08:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
[clangd] Cancel certain operations if the file changes before we start.
Summary:
Otherwise they can force us to build lots of snapshots that we don't need.
Particularly, try to do this for operations that are frequently
generated by editors without explicit user interaction, and where
editing the file makes the result less useful. (Code action
enumeration is a good example).
https://github.com/clangd/clangd/issues/298
This doesn't return the "right" LSP error code (ContentModified) to the client,
we need to teach the cancellation API to distinguish between different causes.
Reviewers: kadircet
Subscribers: ilya-biryukov, javed.absar, MaskRay, jkorous, arphaman, jfb, usaxena95, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D75602
2020-03-04 21:04:17 +08:00
|
|
|
It->second->Worker->runWithAST(Name, std::move(Action), Invalidation);
|
2018-01-31 16:51:16 +08:00
|
|
|
}
|
|
|
|
|
[clangd] Add fallback mode for code completion when compile command or preamble is not ready.
Summary:
When calling TUScehduler::runWithPreamble (e.g. in code compleiton), allow
entering a fallback mode when compile command or preamble is not ready, instead of
waiting. This allows clangd to perform naive code completion e.g. using identifiers
in the current file or symbols in the index.
This patch simply returns empty result for code completion in fallback mode. Identifier-based
plus more advanced index-based completion will be added in followup patches.
Reviewers: ilya-biryukov, sammccall
Reviewed By: sammccall
Subscribers: sammccall, javed.absar, MaskRay, jkorous, arphaman, kadircet, jdoerfert, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D59811
llvm-svn: 357916
2019-04-08 22:53:16 +08:00
|
|
|
void TUScheduler::runWithPreamble(llvm::StringRef Name, PathRef File,
|
|
|
|
PreambleConsistency Consistency,
|
|
|
|
Callback<InputsAndPreamble> Action) {
|
2018-02-08 15:37:35 +08:00
|
|
|
auto It = Files.find(File);
|
|
|
|
if (It == Files.end()) {
|
2019-01-07 23:45:19 +08:00
|
|
|
Action(llvm::make_error<LSPError>(
|
|
|
|
"trying to get preamble for non-added document",
|
|
|
|
ErrorCode::InvalidParams));
|
2018-01-31 16:51:16 +08:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2018-02-13 16:59:23 +08:00
|
|
|
if (!PreambleTasks) {
|
2018-02-19 17:56:28 +08:00
|
|
|
trace::Span Tracer(Name);
|
|
|
|
SPAN_ATTACH(Tracer, "file", File);
|
2018-02-08 15:37:35 +08:00
|
|
|
std::shared_ptr<const PreambleData> Preamble =
|
|
|
|
It->second->Worker->getPossiblyStalePreamble();
|
2019-04-15 20:32:28 +08:00
|
|
|
Action(InputsAndPreamble{It->second->Contents,
|
|
|
|
It->second->Worker->getCurrentCompileCommand(),
|
2018-03-15 01:46:52 +08:00
|
|
|
Preamble.get()});
|
2018-02-08 15:37:35 +08:00
|
|
|
return;
|
|
|
|
}
|
2018-01-31 16:51:16 +08:00
|
|
|
|
2018-08-30 23:07:34 +08:00
|
|
|
// Future is populated if the task needs a specific preamble.
|
|
|
|
std::future<std::shared_ptr<const PreambleData>> ConsistentPreamble;
|
2020-03-16 04:43:00 +08:00
|
|
|
// FIXME: Currently this only holds because ASTWorker blocks after issuing a
|
|
|
|
// preamble build. Get rid of consistent reads or make them build on the
|
|
|
|
// calling thread instead.
|
2018-08-30 23:07:34 +08:00
|
|
|
if (Consistency == Consistent) {
|
|
|
|
std::promise<std::shared_ptr<const PreambleData>> Promise;
|
|
|
|
ConsistentPreamble = Promise.get_future();
|
2019-08-15 22:16:06 +08:00
|
|
|
It->second->Worker->getCurrentPreamble(
|
|
|
|
[Promise = std::move(Promise)](
|
|
|
|
std::shared_ptr<const PreambleData> Preamble) mutable {
|
2018-08-30 23:07:34 +08:00
|
|
|
Promise.set_value(std::move(Preamble));
|
2019-08-15 22:16:06 +08:00
|
|
|
});
|
2018-08-30 23:07:34 +08:00
|
|
|
}
|
|
|
|
|
2018-02-08 15:37:35 +08:00
|
|
|
std::shared_ptr<const ASTWorker> Worker = It->second->Worker.lock();
|
2020-01-29 03:23:46 +08:00
|
|
|
auto Task =
|
|
|
|
[Worker, Consistency, Name = Name.str(), File = File.str(),
|
|
|
|
Contents = It->second->Contents,
|
|
|
|
Command = Worker->getCurrentCompileCommand(),
|
|
|
|
Ctx = Context::current().derive(kFileBeingProcessed, std::string(File)),
|
|
|
|
ConsistentPreamble = std::move(ConsistentPreamble),
|
|
|
|
Action = std::move(Action), this]() mutable {
|
|
|
|
std::shared_ptr<const PreambleData> Preamble;
|
|
|
|
if (ConsistentPreamble.valid()) {
|
|
|
|
Preamble = ConsistentPreamble.get();
|
|
|
|
} else {
|
|
|
|
if (Consistency != PreambleConsistency::StaleOrAbsent) {
|
|
|
|
// Wait until the preamble is built for the first time, if preamble
|
|
|
|
// is required. This avoids extra work of processing the preamble
|
|
|
|
// headers in parallel multiple times.
|
|
|
|
Worker->waitForFirstPreamble();
|
|
|
|
}
|
|
|
|
Preamble = Worker->getPossiblyStalePreamble();
|
|
|
|
}
|
2018-07-09 18:45:33 +08:00
|
|
|
|
2020-01-29 03:23:46 +08:00
|
|
|
std::lock_guard<Semaphore> BarrierLock(Barrier);
|
|
|
|
WithContext Guard(std::move(Ctx));
|
|
|
|
trace::Span Tracer(Name);
|
|
|
|
SPAN_ATTACH(Tracer, "file", File);
|
|
|
|
Action(InputsAndPreamble{Contents, Command, Preamble.get()});
|
|
|
|
};
|
2018-01-31 16:51:16 +08:00
|
|
|
|
2019-08-15 22:16:06 +08:00
|
|
|
PreambleTasks->runAsync("task:" + llvm::sys::path::filename(File),
|
|
|
|
std::move(Task));
|
2018-01-31 16:51:16 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
std::vector<std::pair<Path, std::size_t>>
|
|
|
|
TUScheduler::getUsedBytesPerFile() const {
|
2018-02-08 15:37:35 +08:00
|
|
|
std::vector<std::pair<Path, std::size_t>> Result;
|
|
|
|
Result.reserve(Files.size());
|
|
|
|
for (auto &&PathAndFile : Files)
|
2020-01-29 03:23:46 +08:00
|
|
|
Result.push_back({std::string(PathAndFile.first()),
|
|
|
|
PathAndFile.second->Worker->getUsedBytes()});
|
2018-02-08 15:37:35 +08:00
|
|
|
return Result;
|
2018-01-31 16:51:16 +08:00
|
|
|
}
|
2018-02-08 15:37:35 +08:00
|
|
|
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
std::vector<Path> TUScheduler::getFilesWithCachedAST() const {
|
|
|
|
std::vector<Path> Result;
|
|
|
|
for (auto &&PathAndFile : Files) {
|
|
|
|
if (!PathAndFile.second->Worker->isASTCached())
|
|
|
|
continue;
|
2020-01-29 03:23:46 +08:00
|
|
|
Result.push_back(std::string(PathAndFile.first()));
|
[clangd] Keep only a limited number of idle ASTs in memory
Summary:
After this commit, clangd will only keep the last 3 accessed ASTs in
memory. Preambles for each of the opened files are still kept in
memory to make completion and AST rebuilds fast.
AST rebuilds are usually fast enough, but having the last ASTs in
memory still considerably improves latency of operations like
findDefinition and documeneHighlight, which are often sent multiple
times a second when moving around the code. So keeping some of the last
accessed ASTs in memory seems like a reasonable tradeoff.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: malaperle, arphaman, klimek, javed.absar, ioeric, MaskRay, jkorous, cfe-commits
Differential Revision: https://reviews.llvm.org/D47063
llvm-svn: 333737
2018-06-01 18:08:43 +08:00
|
|
|
}
|
|
|
|
return Result;
|
|
|
|
}
|
|
|
|
|
2020-02-04 22:41:39 +08:00
|
|
|
DebouncePolicy::clock::duration
|
|
|
|
DebouncePolicy::compute(llvm::ArrayRef<clock::duration> History) const {
|
|
|
|
assert(Min <= Max && "Invalid policy");
|
|
|
|
if (History.empty())
|
|
|
|
return Max; // Arbitrary.
|
|
|
|
|
|
|
|
// Base the result on the median rebuild.
|
|
|
|
// nth_element needs a mutable array, take the chance to bound the data size.
|
|
|
|
History = History.take_back(15);
|
|
|
|
llvm::SmallVector<clock::duration, 15> Recent(History.begin(), History.end());
|
|
|
|
auto Median = Recent.begin() + Recent.size() / 2;
|
|
|
|
std::nth_element(Recent.begin(), Median, Recent.end());
|
|
|
|
|
|
|
|
clock::duration Target =
|
|
|
|
std::chrono::duration_cast<clock::duration>(RebuildRatio * *Median);
|
|
|
|
if (Target > Max)
|
|
|
|
return Max;
|
|
|
|
if (Target < Min)
|
|
|
|
return Min;
|
|
|
|
return Target;
|
|
|
|
}
|
|
|
|
|
|
|
|
DebouncePolicy DebouncePolicy::fixed(clock::duration T) {
|
|
|
|
DebouncePolicy P;
|
|
|
|
P.Min = P.Max = T;
|
|
|
|
return P;
|
|
|
|
}
|
|
|
|
|
2018-01-31 16:51:16 +08:00
|
|
|
} // namespace clangd
|
|
|
|
} // namespace clang
|