blob: 1d6781970c47dd1c6df90a2d8fe2566cb3d65f46 [file] [log] [blame]
Sam McCall8dc9dbb2018-10-15 13:34:10 +00001//===-- Background.cpp - Build an index in a background thread ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "index/Background.h"
11#include "ClangdUnit.h"
12#include "Compiler.h"
13#include "Logger.h"
Kadir Cetinkayad08eab42018-11-27 16:08:53 +000014#include "SourceCode.h"
Kadir Cetinkaya6675be82018-10-30 12:13:27 +000015#include "Threading.h"
Sam McCall8dc9dbb2018-10-15 13:34:10 +000016#include "Trace.h"
Eric Liuad588af2018-11-06 10:55:21 +000017#include "URI.h"
Sam McCall8dc9dbb2018-10-15 13:34:10 +000018#include "index/IndexAction.h"
19#include "index/MemIndex.h"
20#include "index/Serialization.h"
Eric Liuad588af2018-11-06 10:55:21 +000021#include "index/SymbolCollector.h"
22#include "clang/Basic/SourceLocation.h"
23#include "clang/Basic/SourceManager.h"
24#include "llvm/ADT/STLExtras.h"
Kadir Cetinkaya375c54f2018-12-17 12:30:27 +000025#include "llvm/ADT/ScopeExit.h"
Eric Liuad588af2018-11-06 10:55:21 +000026#include "llvm/ADT/StringMap.h"
27#include "llvm/ADT/StringRef.h"
Sam McCall8dc9dbb2018-10-15 13:34:10 +000028#include "llvm/Support/SHA1.h"
Kadir Cetinkaya06553bf2018-11-16 09:03:56 +000029
Eric Liu667e8ef2018-12-18 15:39:33 +000030#include <chrono>
Kadir Cetinkaya06553bf2018-11-16 09:03:56 +000031#include <memory>
Sam McCall7d0e4842018-11-26 13:35:02 +000032#include <numeric>
Kadir Cetinkaya06553bf2018-11-16 09:03:56 +000033#include <queue>
Sam McCall8dc9dbb2018-10-15 13:34:10 +000034#include <random>
Eric Liuad588af2018-11-06 10:55:21 +000035#include <string>
Eric Liu667e8ef2018-12-18 15:39:33 +000036#include <thread>
Sam McCall8dc9dbb2018-10-15 13:34:10 +000037
38using namespace llvm;
39namespace clang {
40namespace clangd {
Kadir Cetinkaya219c0fa2018-12-04 11:31:57 +000041namespace {
42// Resolves URI to file paths with cache.
43class URIToFileCache {
44public:
45 URIToFileCache(llvm::StringRef HintPath) : HintPath(HintPath) {}
46
47 llvm::StringRef resolve(llvm::StringRef FileURI) {
48 auto I = URIToPathCache.try_emplace(FileURI);
49 if (I.second) {
50 auto U = URI::parse(FileURI);
51 if (!U) {
52 elog("Failed to parse URI {0}: {1}", FileURI, U.takeError());
53 assert(false && "Failed to parse URI");
54 return "";
55 }
56 auto Path = URI::resolve(*U, HintPath);
57 if (!Path) {
58 elog("Failed to resolve URI {0}: {1}", FileURI, Path.takeError());
59 assert(false && "Failed to resolve URI");
60 return "";
61 }
62 I.first->second = *Path;
63 }
64 return I.first->second;
65 }
66
67private:
68 std::string HintPath;
69 llvm::StringMap<std::string> URIToPathCache;
70};
71
72// We keep only the node "U" and its edges. Any node other than "U" will be
73// empty in the resultant graph.
74IncludeGraph getSubGraph(const URI &U, const IncludeGraph &FullGraph) {
75 IncludeGraph IG;
76
77 std::string FileURI = U.toString();
78 auto Entry = IG.try_emplace(FileURI).first;
79 auto &Node = Entry->getValue();
80 Node = FullGraph.lookup(Entry->getKey());
81 Node.URI = Entry->getKey();
82
83 // URIs inside nodes must point into the keys of the same IncludeGraph.
84 for (auto &Include : Node.DirectIncludes) {
85 auto I = IG.try_emplace(Include).first;
86 I->getValue().URI = I->getKey();
87 Include = I->getKey();
88 }
89
90 return IG;
91}
Haojian Wu9d0d9f82018-12-13 13:07:29 +000092
93// Creates a filter to not collect index results from files with unchanged
94// digests.
95// \p FileDigests contains file digests for the current indexed files, and all
96// changed files will be added to \p FilesToUpdate.
97decltype(SymbolCollector::Options::FileFilter)
98createFileFilter(const llvm::StringMap<FileDigest> &FileDigests,
99 llvm::StringMap<FileDigest> &FilesToUpdate) {
100 return [&FileDigests, &FilesToUpdate](const SourceManager &SM, FileID FID) {
101 StringRef Path;
102 if (const auto *F = SM.getFileEntryForID(FID))
103 Path = F->getName();
104 if (Path.empty())
105 return false; // Skip invalid files.
106 SmallString<128> AbsPath(Path);
107 if (std::error_code EC =
108 SM.getFileManager().getVirtualFileSystem()->makeAbsolute(AbsPath)) {
109 elog("Warning: could not make absolute file: {0}", EC.message());
110 return false; // Skip files without absolute path.
111 }
112 sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true);
113 auto Digest = digestFile(SM, FID);
114 if (!Digest)
115 return false;
116 auto D = FileDigests.find(AbsPath);
117 if (D != FileDigests.end() && D->second == Digest)
118 return false; // Skip files that haven't changed.
119
120 FilesToUpdate[AbsPath] = *Digest;
121 return true;
122 };
123}
124
Kadir Cetinkaya219c0fa2018-12-04 11:31:57 +0000125} // namespace
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000126
Kadir Cetinkaya06553bf2018-11-16 09:03:56 +0000127BackgroundIndex::BackgroundIndex(
128 Context BackgroundContext, StringRef ResourceDir,
Sam McCall6e2d2a32018-11-26 09:51:50 +0000129 const FileSystemProvider &FSProvider, const GlobalCompilationDatabase &CDB,
Eric Liu667e8ef2018-12-18 15:39:33 +0000130 BackgroundIndexStorage::Factory IndexStorageFactory,
131 size_t BuildIndexPeriodMs, size_t ThreadPoolSize)
Sam McCallc008af62018-10-20 15:30:37 +0000132 : SwapIndex(make_unique<MemIndex>()), ResourceDir(ResourceDir),
Sam McCall6e2d2a32018-11-26 09:51:50 +0000133 FSProvider(FSProvider), CDB(CDB),
134 BackgroundContext(std::move(BackgroundContext)),
Eric Liu667e8ef2018-12-18 15:39:33 +0000135 BuildIndexPeriodMs(BuildIndexPeriodMs),
136 SymbolsUpdatedSinceLastIndex(false),
Sam McCall6e2d2a32018-11-26 09:51:50 +0000137 IndexStorageFactory(std::move(IndexStorageFactory)),
138 CommandsChanged(
139 CDB.watch([&](const std::vector<std::string> &ChangedFiles) {
140 enqueue(ChangedFiles);
141 })) {
Kadir Cetinkaya6675be82018-10-30 12:13:27 +0000142 assert(ThreadPoolSize > 0 && "Thread pool size can't be zero.");
Haojian Wu1bf52c52018-11-16 09:41:14 +0000143 assert(this->IndexStorageFactory && "Storage factory can not be null!");
Kadir Cetinkaya375c54f2018-12-17 12:30:27 +0000144 while (ThreadPoolSize--)
Kadir Cetinkaya6675be82018-10-30 12:13:27 +0000145 ThreadPool.emplace_back([this] { run(); });
Eric Liu667e8ef2018-12-18 15:39:33 +0000146 if (BuildIndexPeriodMs > 0) {
147 log("BackgroundIndex: build symbol index periodically every {0} ms.",
148 BuildIndexPeriodMs);
149 ThreadPool.emplace_back([this] { buildIndex(); });
150 }
Kadir Cetinkaya6675be82018-10-30 12:13:27 +0000151}
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000152
153BackgroundIndex::~BackgroundIndex() {
154 stop();
Kadir Cetinkaya6675be82018-10-30 12:13:27 +0000155 for (auto &Thread : ThreadPool)
156 Thread.join();
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000157}
158
159void BackgroundIndex::stop() {
160 {
Eric Liu667e8ef2018-12-18 15:39:33 +0000161 std::lock_guard<std::mutex> QueueLock(QueueMu);
162 std::lock_guard<std::mutex> IndexLock(IndexMu);
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000163 ShouldStop = true;
164 }
165 QueueCV.notify_all();
Eric Liu667e8ef2018-12-18 15:39:33 +0000166 IndexCV.notify_all();
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000167}
168
169void BackgroundIndex::run() {
Kadir Cetinkaya6675be82018-10-30 12:13:27 +0000170 WithContext Background(BackgroundContext.clone());
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000171 while (true) {
Sam McCallc008af62018-10-20 15:30:37 +0000172 Optional<Task> Task;
Kadir Cetinkaya375c54f2018-12-17 12:30:27 +0000173 ThreadPriority Priority;
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000174 {
175 std::unique_lock<std::mutex> Lock(QueueMu);
176 QueueCV.wait(Lock, [&] { return ShouldStop || !Queue.empty(); });
177 if (ShouldStop) {
178 Queue.clear();
179 QueueCV.notify_all();
180 return;
181 }
182 ++NumActiveTasks;
Kadir Cetinkaya375c54f2018-12-17 12:30:27 +0000183 std::tie(Task, Priority) = std::move(Queue.front());
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000184 Queue.pop_front();
185 }
Kadir Cetinkaya375c54f2018-12-17 12:30:27 +0000186
187 if (Priority != ThreadPriority::Normal)
188 setCurrentThreadPriority(Priority);
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000189 (*Task)();
Kadir Cetinkaya375c54f2018-12-17 12:30:27 +0000190 if (Priority != ThreadPriority::Normal)
191 setCurrentThreadPriority(ThreadPriority::Normal);
192
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000193 {
194 std::unique_lock<std::mutex> Lock(QueueMu);
195 assert(NumActiveTasks > 0 && "before decrementing");
196 --NumActiveTasks;
197 }
198 QueueCV.notify_all();
199 }
200}
201
Sam McCall422c8282018-11-26 16:00:11 +0000202bool BackgroundIndex::blockUntilIdleForTest(
203 llvm::Optional<double> TimeoutSeconds) {
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000204 std::unique_lock<std::mutex> Lock(QueueMu);
Sam McCall422c8282018-11-26 16:00:11 +0000205 return wait(Lock, QueueCV, timeoutSeconds(TimeoutSeconds),
206 [&] { return Queue.empty() && NumActiveTasks == 0; });
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000207}
208
Sam McCall6e2d2a32018-11-26 09:51:50 +0000209void BackgroundIndex::enqueue(const std::vector<std::string> &ChangedFiles) {
Kadir Cetinkaya375c54f2018-12-17 12:30:27 +0000210 enqueueTask(
211 [this, ChangedFiles] {
212 trace::Span Tracer("BackgroundIndexEnqueue");
213 // We're doing this asynchronously, because we'll read shards here too.
214 // FIXME: read shards here too.
Sam McCall6e2d2a32018-11-26 09:51:50 +0000215
Kadir Cetinkaya375c54f2018-12-17 12:30:27 +0000216 log("Enqueueing {0} commands for indexing", ChangedFiles.size());
217 SPAN_ATTACH(Tracer, "files", int64_t(ChangedFiles.size()));
Sam McCall6e2d2a32018-11-26 09:51:50 +0000218
Kadir Cetinkaya375c54f2018-12-17 12:30:27 +0000219 // We shuffle the files because processing them in a random order should
220 // quickly give us good coverage of headers in the project.
221 std::vector<unsigned> Permutation(ChangedFiles.size());
222 std::iota(Permutation.begin(), Permutation.end(), 0);
223 std::mt19937 Generator(std::random_device{}());
224 std::shuffle(Permutation.begin(), Permutation.end(), Generator);
Sam McCall6e2d2a32018-11-26 09:51:50 +0000225
Kadir Cetinkaya375c54f2018-12-17 12:30:27 +0000226 for (const unsigned I : Permutation)
227 enqueue(ChangedFiles[I]);
228 },
229 ThreadPriority::Normal);
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000230}
231
Sam McCall6e2d2a32018-11-26 09:51:50 +0000232void BackgroundIndex::enqueue(const std::string &File) {
233 ProjectInfo Project;
234 if (auto Cmd = CDB.getCompileCommand(File, &Project)) {
235 auto *Storage = IndexStorageFactory(Project.SourceRoot);
Kadir Cetinkaya375c54f2018-12-17 12:30:27 +0000236 // Set priority to low, since background indexing is a long running
237 // task we do not want to eat up cpu when there are any other high
238 // priority threads.
Sam McCall6e2d2a32018-11-26 09:51:50 +0000239 enqueueTask(Bind(
Kadir Cetinkaya375c54f2018-12-17 12:30:27 +0000240 [this, File, Storage](tooling::CompileCommand Cmd) {
241 Cmd.CommandLine.push_back("-resource-dir=" + ResourceDir);
242 if (auto Error = index(std::move(Cmd), Storage))
243 log("Indexing {0} failed: {1}", File, std::move(Error));
244 },
245 std::move(*Cmd)),
246 ThreadPriority::Low);
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000247 }
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000248}
249
Kadir Cetinkaya375c54f2018-12-17 12:30:27 +0000250void BackgroundIndex::enqueueTask(Task T, ThreadPriority Priority) {
Sam McCall6e2d2a32018-11-26 09:51:50 +0000251 {
252 std::lock_guard<std::mutex> Lock(QueueMu);
Kadir Cetinkaya375c54f2018-12-17 12:30:27 +0000253 auto I = Queue.end();
254 // We first store the tasks with Normal priority in the front of the queue.
255 // Then we store low priority tasks. Normal priority tasks are pretty rare,
256 // they should not grow beyond single-digit numbers, so it is OK to do
257 // linear search and insert after that.
258 if (Priority == ThreadPriority::Normal) {
259 I = llvm::find_if(Queue, [](const std::pair<Task, ThreadPriority> &Elem) {
260 return Elem.second == ThreadPriority::Low;
261 });
262 }
263 Queue.insert(I, {std::move(T), Priority});
Sam McCall6e2d2a32018-11-26 09:51:50 +0000264 }
265 QueueCV.notify_all();
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000266}
267
Eric Liuad588af2018-11-06 10:55:21 +0000268/// Given index results from a TU, only update files in \p FilesToUpdate.
Kadir Cetinkayad08eab42018-11-27 16:08:53 +0000269void BackgroundIndex::update(StringRef MainFile, IndexFileIn Index,
Kadir Cetinkaya06553bf2018-11-16 09:03:56 +0000270 const StringMap<FileDigest> &FilesToUpdate,
271 BackgroundIndexStorage *IndexStorage) {
Eric Liuad588af2018-11-06 10:55:21 +0000272 // Partition symbols/references into files.
273 struct File {
274 DenseSet<const Symbol *> Symbols;
275 DenseSet<const Ref *> Refs;
276 };
277 StringMap<File> Files;
278 URIToFileCache URICache(MainFile);
Kadir Cetinkayad08eab42018-11-27 16:08:53 +0000279 for (const auto &Sym : *Index.Symbols) {
Eric Liuad588af2018-11-06 10:55:21 +0000280 if (Sym.CanonicalDeclaration) {
281 auto DeclPath = URICache.resolve(Sym.CanonicalDeclaration.FileURI);
282 if (FilesToUpdate.count(DeclPath) != 0)
283 Files[DeclPath].Symbols.insert(&Sym);
284 }
285 // For symbols with different declaration and definition locations, we store
286 // the full symbol in both the header file and the implementation file, so
287 // that merging can tell the preferred symbols (from canonical headers) from
288 // other symbols (e.g. forward declarations).
289 if (Sym.Definition &&
290 Sym.Definition.FileURI != Sym.CanonicalDeclaration.FileURI) {
291 auto DefPath = URICache.resolve(Sym.Definition.FileURI);
292 if (FilesToUpdate.count(DefPath) != 0)
293 Files[DefPath].Symbols.insert(&Sym);
294 }
295 }
296 DenseMap<const Ref *, SymbolID> RefToIDs;
Kadir Cetinkayad08eab42018-11-27 16:08:53 +0000297 for (const auto &SymRefs : *Index.Refs) {
Eric Liuad588af2018-11-06 10:55:21 +0000298 for (const auto &R : SymRefs.second) {
299 auto Path = URICache.resolve(R.Location.FileURI);
300 if (FilesToUpdate.count(Path) != 0) {
301 auto &F = Files[Path];
302 RefToIDs[&R] = SymRefs.first;
303 F.Refs.insert(&R);
304 }
305 }
306 }
307
308 // Build and store new slabs for each updated file.
309 for (const auto &F : Files) {
310 StringRef Path = F.first();
311 vlog("Update symbols in {0}", Path);
312 SymbolSlab::Builder Syms;
313 RefSlab::Builder Refs;
314 for (const auto *S : F.second.Symbols)
315 Syms.insert(*S);
316 for (const auto *R : F.second.Refs)
317 Refs.insert(RefToIDs[R], *R);
318
Kadir Cetinkaya06553bf2018-11-16 09:03:56 +0000319 auto SS = llvm::make_unique<SymbolSlab>(std::move(Syms).build());
320 auto RS = llvm::make_unique<RefSlab>(std::move(Refs).build());
Kadir Cetinkaya219c0fa2018-12-04 11:31:57 +0000321 auto IG = llvm::make_unique<IncludeGraph>(
322 getSubGraph(URI::create(Path), Index.Sources.getValue()));
Kadir Cetinkaya06553bf2018-11-16 09:03:56 +0000323
324 auto Hash = FilesToUpdate.lookup(Path);
325 // We need to store shards before updating the index, since the latter
326 // consumes slabs.
Kadir Cetinkaya06553bf2018-11-16 09:03:56 +0000327 if (IndexStorage) {
328 IndexFileOut Shard;
329 Shard.Symbols = SS.get();
330 Shard.Refs = RS.get();
Kadir Cetinkaya219c0fa2018-12-04 11:31:57 +0000331 Shard.Sources = IG.get();
Kadir Cetinkayad08eab42018-11-27 16:08:53 +0000332
Kadir Cetinkaya06553bf2018-11-16 09:03:56 +0000333 if (auto Error = IndexStorage->storeShard(Path, Shard))
334 elog("Failed to write background-index shard for file {0}: {1}", Path,
335 std::move(Error));
336 }
337
Eric Liuad588af2018-11-06 10:55:21 +0000338 std::lock_guard<std::mutex> Lock(DigestsMu);
339 // This can override a newer version that is added in another thread,
340 // if this thread sees the older version but finishes later. This should be
341 // rare in practice.
Kadir Cetinkaya06553bf2018-11-16 09:03:56 +0000342 IndexedFileDigests[Path] = Hash;
343 IndexedSymbols.update(Path, std::move(SS), std::move(RS));
Eric Liuad588af2018-11-06 10:55:21 +0000344 }
345}
346
Eric Liu667e8ef2018-12-18 15:39:33 +0000347void BackgroundIndex::buildIndex() {
348 assert(BuildIndexPeriodMs > 0);
349 while (true) {
350 {
351 std::unique_lock<std::mutex> Lock(IndexMu);
352 if (ShouldStop) // Avoid waiting if stopped.
353 break;
354 // Wait until this is notified to stop or `BuildIndexPeriodMs` has past.
355 IndexCV.wait_for(Lock, std::chrono::milliseconds(BuildIndexPeriodMs));
356 if (ShouldStop) // Avoid rebuilding index if stopped.
357 break;
358 }
359 if (!SymbolsUpdatedSinceLastIndex.exchange(false))
360 continue;
361 // There can be symbol update right after the flag is reset above and before
362 // index is rebuilt below. The new index would contain the updated symbols
363 // but the flag would still be true. This is fine as we would simply run an
364 // extra index build.
365 reset(
366 IndexedSymbols.buildIndex(IndexType::Heavy, DuplicateHandling::Merge));
367 log("BackgroundIndex: rebuilt symbol index.");
368 }
369}
370
Kadir Cetinkaya06553bf2018-11-16 09:03:56 +0000371Error BackgroundIndex::index(tooling::CompileCommand Cmd,
372 BackgroundIndexStorage *IndexStorage) {
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000373 trace::Span Tracer("BackgroundIndex");
374 SPAN_ATTACH(Tracer, "file", Cmd.Filename);
Kadir Cetinkayaed18e782018-11-15 10:34:39 +0000375 SmallString<128> AbsolutePath;
376 if (sys::path::is_absolute(Cmd.Filename)) {
377 AbsolutePath = Cmd.Filename;
378 } else {
379 AbsolutePath = Cmd.Directory;
380 sys::path::append(AbsolutePath, Cmd.Filename);
381 }
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000382
383 auto FS = FSProvider.getFileSystem();
384 auto Buf = FS->getBufferForFile(AbsolutePath);
385 if (!Buf)
386 return errorCodeToError(Buf.getError());
Eric Liuad588af2018-11-06 10:55:21 +0000387 auto Hash = digest(Buf->get()->getBuffer());
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000388
Eric Liuad588af2018-11-06 10:55:21 +0000389 // Take a snapshot of the digests to avoid locking for each file in the TU.
390 llvm::StringMap<FileDigest> DigestsSnapshot;
391 {
392 std::lock_guard<std::mutex> Lock(DigestsMu);
393 if (IndexedFileDigests.lookup(AbsolutePath) == Hash) {
394 vlog("No need to index {0}, already up to date", AbsolutePath);
395 return Error::success();
396 }
397
398 DigestsSnapshot = IndexedFileDigests;
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000399 }
400
Eric Liu667e8ef2018-12-18 15:39:33 +0000401 log("Indexing {0} (digest:={1})", Cmd.Filename, toHex(Hash));
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000402 ParseInputs Inputs;
403 Inputs.FS = std::move(FS);
404 Inputs.FS->setCurrentWorkingDirectory(Cmd.Directory);
405 Inputs.CompileCommand = std::move(Cmd);
406 auto CI = buildCompilerInvocation(Inputs);
407 if (!CI)
Sam McCallc008af62018-10-20 15:30:37 +0000408 return createStringError(inconvertibleErrorCode(),
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000409 "Couldn't build compiler invocation");
410 IgnoreDiagnostics IgnoreDiags;
411 auto Clang = prepareCompilerInstance(
412 std::move(CI), /*Preamble=*/nullptr, std::move(*Buf),
413 std::make_shared<PCHContainerOperations>(), Inputs.FS, IgnoreDiags);
414 if (!Clang)
Sam McCallc008af62018-10-20 15:30:37 +0000415 return createStringError(inconvertibleErrorCode(),
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000416 "Couldn't build compiler instance");
417
418 SymbolCollector::Options IndexOpts;
Eric Liuad588af2018-11-06 10:55:21 +0000419 StringMap<FileDigest> FilesToUpdate;
420 IndexOpts.FileFilter = createFileFilter(DigestsSnapshot, FilesToUpdate);
Kadir Cetinkaya219c0fa2018-12-04 11:31:57 +0000421 IndexFileIn Index;
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000422 auto Action = createStaticIndexingAction(
Kadir Cetinkaya219c0fa2018-12-04 11:31:57 +0000423 IndexOpts, [&](SymbolSlab S) { Index.Symbols = std::move(S); },
424 [&](RefSlab R) { Index.Refs = std::move(R); },
425 [&](IncludeGraph IG) { Index.Sources = std::move(IG); });
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000426
427 // We're going to run clang here, and it could potentially crash.
428 // We could use CrashRecoveryContext to try to make indexing crashes nonfatal,
429 // but the leaky "recovery" is pretty scary too in a long-running process.
430 // If crashes are a real problem, maybe we should fork a child process.
431
432 const FrontendInputFile &Input = Clang->getFrontendOpts().Inputs.front();
433 if (!Action->BeginSourceFile(*Clang, Input))
Sam McCallc008af62018-10-20 15:30:37 +0000434 return createStringError(inconvertibleErrorCode(),
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000435 "BeginSourceFile() failed");
436 if (!Action->Execute())
Sam McCallc008af62018-10-20 15:30:37 +0000437 return createStringError(inconvertibleErrorCode(), "Execute() failed");
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000438 Action->EndSourceFile();
Haojian Wud5a78e62018-12-14 12:39:08 +0000439 if (Clang->hasDiagnostics() &&
440 Clang->getDiagnostics().hasUncompilableErrorOccurred()) {
441 return createStringError(inconvertibleErrorCode(),
442 "IndexingAction failed: has uncompilable errors");
443 }
444
445 assert(Index.Symbols && Index.Refs && Index.Sources
446 && "Symbols, Refs and Sources must be set.");
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000447
Kadir Cetinkaya219c0fa2018-12-04 11:31:57 +0000448 log("Indexed {0} ({1} symbols, {2} refs, {3} files)",
449 Inputs.CompileCommand.Filename, Index.Symbols->size(),
450 Index.Refs->numRefs(), Index.Sources->size());
451 SPAN_ATTACH(Tracer, "symbols", int(Index.Symbols->size()));
452 SPAN_ATTACH(Tracer, "refs", int(Index.Refs->numRefs()));
453 SPAN_ATTACH(Tracer, "sources", int(Index.Sources->size()));
Kadir Cetinkayad08eab42018-11-27 16:08:53 +0000454
455 update(AbsolutePath, std::move(Index), FilesToUpdate, IndexStorage);
Eric Liuad588af2018-11-06 10:55:21 +0000456 {
457 // Make sure hash for the main file is always updated even if there is no
458 // index data in it.
459 std::lock_guard<std::mutex> Lock(DigestsMu);
460 IndexedFileDigests[AbsolutePath] = Hash;
461 }
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000462
Eric Liu667e8ef2018-12-18 15:39:33 +0000463 if (BuildIndexPeriodMs > 0)
464 SymbolsUpdatedSinceLastIndex = true;
465 else
466 reset(
467 IndexedSymbols.buildIndex(IndexType::Light, DuplicateHandling::Merge));
Eric Liuad588af2018-11-06 10:55:21 +0000468
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000469 return Error::success();
470}
471
Sam McCall8dc9dbb2018-10-15 13:34:10 +0000472} // namespace clangd
473} // namespace clang