Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 1 | //===-- 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 Cetinkaya | d08eab4 | 2018-11-27 16:08:53 +0000 | [diff] [blame] | 14 | #include "SourceCode.h" |
Kadir Cetinkaya | 6675be8 | 2018-10-30 12:13:27 +0000 | [diff] [blame] | 15 | #include "Threading.h" |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 16 | #include "Trace.h" |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 17 | #include "URI.h" |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 18 | #include "index/IndexAction.h" |
| 19 | #include "index/MemIndex.h" |
| 20 | #include "index/Serialization.h" |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 21 | #include "index/SymbolCollector.h" |
| 22 | #include "clang/Basic/SourceLocation.h" |
| 23 | #include "clang/Basic/SourceManager.h" |
| 24 | #include "llvm/ADT/STLExtras.h" |
Kadir Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 25 | #include "llvm/ADT/ScopeExit.h" |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 26 | #include "llvm/ADT/StringMap.h" |
| 27 | #include "llvm/ADT/StringRef.h" |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 28 | #include "llvm/Support/SHA1.h" |
Kadir Cetinkaya | 06553bf | 2018-11-16 09:03:56 +0000 | [diff] [blame] | 29 | |
Eric Liu | 667e8ef | 2018-12-18 15:39:33 +0000 | [diff] [blame^] | 30 | #include <chrono> |
Kadir Cetinkaya | 06553bf | 2018-11-16 09:03:56 +0000 | [diff] [blame] | 31 | #include <memory> |
Sam McCall | 7d0e484 | 2018-11-26 13:35:02 +0000 | [diff] [blame] | 32 | #include <numeric> |
Kadir Cetinkaya | 06553bf | 2018-11-16 09:03:56 +0000 | [diff] [blame] | 33 | #include <queue> |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 34 | #include <random> |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 35 | #include <string> |
Eric Liu | 667e8ef | 2018-12-18 15:39:33 +0000 | [diff] [blame^] | 36 | #include <thread> |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 37 | |
| 38 | using namespace llvm; |
| 39 | namespace clang { |
| 40 | namespace clangd { |
Kadir Cetinkaya | 219c0fa | 2018-12-04 11:31:57 +0000 | [diff] [blame] | 41 | namespace { |
| 42 | // Resolves URI to file paths with cache. |
| 43 | class URIToFileCache { |
| 44 | public: |
| 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 | |
| 67 | private: |
| 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. |
| 74 | IncludeGraph 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 Wu | 9d0d9f8 | 2018-12-13 13:07:29 +0000 | [diff] [blame] | 92 | |
| 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. |
| 97 | decltype(SymbolCollector::Options::FileFilter) |
| 98 | createFileFilter(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 Cetinkaya | 219c0fa | 2018-12-04 11:31:57 +0000 | [diff] [blame] | 125 | } // namespace |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 126 | |
Kadir Cetinkaya | 06553bf | 2018-11-16 09:03:56 +0000 | [diff] [blame] | 127 | BackgroundIndex::BackgroundIndex( |
| 128 | Context BackgroundContext, StringRef ResourceDir, |
Sam McCall | 6e2d2a3 | 2018-11-26 09:51:50 +0000 | [diff] [blame] | 129 | const FileSystemProvider &FSProvider, const GlobalCompilationDatabase &CDB, |
Eric Liu | 667e8ef | 2018-12-18 15:39:33 +0000 | [diff] [blame^] | 130 | BackgroundIndexStorage::Factory IndexStorageFactory, |
| 131 | size_t BuildIndexPeriodMs, size_t ThreadPoolSize) |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame] | 132 | : SwapIndex(make_unique<MemIndex>()), ResourceDir(ResourceDir), |
Sam McCall | 6e2d2a3 | 2018-11-26 09:51:50 +0000 | [diff] [blame] | 133 | FSProvider(FSProvider), CDB(CDB), |
| 134 | BackgroundContext(std::move(BackgroundContext)), |
Eric Liu | 667e8ef | 2018-12-18 15:39:33 +0000 | [diff] [blame^] | 135 | BuildIndexPeriodMs(BuildIndexPeriodMs), |
| 136 | SymbolsUpdatedSinceLastIndex(false), |
Sam McCall | 6e2d2a3 | 2018-11-26 09:51:50 +0000 | [diff] [blame] | 137 | IndexStorageFactory(std::move(IndexStorageFactory)), |
| 138 | CommandsChanged( |
| 139 | CDB.watch([&](const std::vector<std::string> &ChangedFiles) { |
| 140 | enqueue(ChangedFiles); |
| 141 | })) { |
Kadir Cetinkaya | 6675be8 | 2018-10-30 12:13:27 +0000 | [diff] [blame] | 142 | assert(ThreadPoolSize > 0 && "Thread pool size can't be zero."); |
Haojian Wu | 1bf52c5 | 2018-11-16 09:41:14 +0000 | [diff] [blame] | 143 | assert(this->IndexStorageFactory && "Storage factory can not be null!"); |
Kadir Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 144 | while (ThreadPoolSize--) |
Kadir Cetinkaya | 6675be8 | 2018-10-30 12:13:27 +0000 | [diff] [blame] | 145 | ThreadPool.emplace_back([this] { run(); }); |
Eric Liu | 667e8ef | 2018-12-18 15:39:33 +0000 | [diff] [blame^] | 146 | if (BuildIndexPeriodMs > 0) { |
| 147 | log("BackgroundIndex: build symbol index periodically every {0} ms.", |
| 148 | BuildIndexPeriodMs); |
| 149 | ThreadPool.emplace_back([this] { buildIndex(); }); |
| 150 | } |
Kadir Cetinkaya | 6675be8 | 2018-10-30 12:13:27 +0000 | [diff] [blame] | 151 | } |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 152 | |
| 153 | BackgroundIndex::~BackgroundIndex() { |
| 154 | stop(); |
Kadir Cetinkaya | 6675be8 | 2018-10-30 12:13:27 +0000 | [diff] [blame] | 155 | for (auto &Thread : ThreadPool) |
| 156 | Thread.join(); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 157 | } |
| 158 | |
| 159 | void BackgroundIndex::stop() { |
| 160 | { |
Eric Liu | 667e8ef | 2018-12-18 15:39:33 +0000 | [diff] [blame^] | 161 | std::lock_guard<std::mutex> QueueLock(QueueMu); |
| 162 | std::lock_guard<std::mutex> IndexLock(IndexMu); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 163 | ShouldStop = true; |
| 164 | } |
| 165 | QueueCV.notify_all(); |
Eric Liu | 667e8ef | 2018-12-18 15:39:33 +0000 | [diff] [blame^] | 166 | IndexCV.notify_all(); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 167 | } |
| 168 | |
| 169 | void BackgroundIndex::run() { |
Kadir Cetinkaya | 6675be8 | 2018-10-30 12:13:27 +0000 | [diff] [blame] | 170 | WithContext Background(BackgroundContext.clone()); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 171 | while (true) { |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame] | 172 | Optional<Task> Task; |
Kadir Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 173 | ThreadPriority Priority; |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 174 | { |
| 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 Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 183 | std::tie(Task, Priority) = std::move(Queue.front()); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 184 | Queue.pop_front(); |
| 185 | } |
Kadir Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 186 | |
| 187 | if (Priority != ThreadPriority::Normal) |
| 188 | setCurrentThreadPriority(Priority); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 189 | (*Task)(); |
Kadir Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 190 | if (Priority != ThreadPriority::Normal) |
| 191 | setCurrentThreadPriority(ThreadPriority::Normal); |
| 192 | |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 193 | { |
| 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 McCall | 422c828 | 2018-11-26 16:00:11 +0000 | [diff] [blame] | 202 | bool BackgroundIndex::blockUntilIdleForTest( |
| 203 | llvm::Optional<double> TimeoutSeconds) { |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 204 | std::unique_lock<std::mutex> Lock(QueueMu); |
Sam McCall | 422c828 | 2018-11-26 16:00:11 +0000 | [diff] [blame] | 205 | return wait(Lock, QueueCV, timeoutSeconds(TimeoutSeconds), |
| 206 | [&] { return Queue.empty() && NumActiveTasks == 0; }); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 207 | } |
| 208 | |
Sam McCall | 6e2d2a3 | 2018-11-26 09:51:50 +0000 | [diff] [blame] | 209 | void BackgroundIndex::enqueue(const std::vector<std::string> &ChangedFiles) { |
Kadir Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 210 | 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 McCall | 6e2d2a3 | 2018-11-26 09:51:50 +0000 | [diff] [blame] | 215 | |
Kadir Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 216 | log("Enqueueing {0} commands for indexing", ChangedFiles.size()); |
| 217 | SPAN_ATTACH(Tracer, "files", int64_t(ChangedFiles.size())); |
Sam McCall | 6e2d2a3 | 2018-11-26 09:51:50 +0000 | [diff] [blame] | 218 | |
Kadir Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 219 | // 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 McCall | 6e2d2a3 | 2018-11-26 09:51:50 +0000 | [diff] [blame] | 225 | |
Kadir Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 226 | for (const unsigned I : Permutation) |
| 227 | enqueue(ChangedFiles[I]); |
| 228 | }, |
| 229 | ThreadPriority::Normal); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 230 | } |
| 231 | |
Sam McCall | 6e2d2a3 | 2018-11-26 09:51:50 +0000 | [diff] [blame] | 232 | void BackgroundIndex::enqueue(const std::string &File) { |
| 233 | ProjectInfo Project; |
| 234 | if (auto Cmd = CDB.getCompileCommand(File, &Project)) { |
| 235 | auto *Storage = IndexStorageFactory(Project.SourceRoot); |
Kadir Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 236 | // 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 McCall | 6e2d2a3 | 2018-11-26 09:51:50 +0000 | [diff] [blame] | 239 | enqueueTask(Bind( |
Kadir Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 240 | [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 McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 247 | } |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 248 | } |
| 249 | |
Kadir Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 250 | void BackgroundIndex::enqueueTask(Task T, ThreadPriority Priority) { |
Sam McCall | 6e2d2a3 | 2018-11-26 09:51:50 +0000 | [diff] [blame] | 251 | { |
| 252 | std::lock_guard<std::mutex> Lock(QueueMu); |
Kadir Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 253 | 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 McCall | 6e2d2a3 | 2018-11-26 09:51:50 +0000 | [diff] [blame] | 264 | } |
| 265 | QueueCV.notify_all(); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 266 | } |
| 267 | |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 268 | /// Given index results from a TU, only update files in \p FilesToUpdate. |
Kadir Cetinkaya | d08eab4 | 2018-11-27 16:08:53 +0000 | [diff] [blame] | 269 | void BackgroundIndex::update(StringRef MainFile, IndexFileIn Index, |
Kadir Cetinkaya | 06553bf | 2018-11-16 09:03:56 +0000 | [diff] [blame] | 270 | const StringMap<FileDigest> &FilesToUpdate, |
| 271 | BackgroundIndexStorage *IndexStorage) { |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 272 | // 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 Cetinkaya | d08eab4 | 2018-11-27 16:08:53 +0000 | [diff] [blame] | 279 | for (const auto &Sym : *Index.Symbols) { |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 280 | 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 Cetinkaya | d08eab4 | 2018-11-27 16:08:53 +0000 | [diff] [blame] | 297 | for (const auto &SymRefs : *Index.Refs) { |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 298 | 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 Cetinkaya | 06553bf | 2018-11-16 09:03:56 +0000 | [diff] [blame] | 319 | auto SS = llvm::make_unique<SymbolSlab>(std::move(Syms).build()); |
| 320 | auto RS = llvm::make_unique<RefSlab>(std::move(Refs).build()); |
Kadir Cetinkaya | 219c0fa | 2018-12-04 11:31:57 +0000 | [diff] [blame] | 321 | auto IG = llvm::make_unique<IncludeGraph>( |
| 322 | getSubGraph(URI::create(Path), Index.Sources.getValue())); |
Kadir Cetinkaya | 06553bf | 2018-11-16 09:03:56 +0000 | [diff] [blame] | 323 | |
| 324 | auto Hash = FilesToUpdate.lookup(Path); |
| 325 | // We need to store shards before updating the index, since the latter |
| 326 | // consumes slabs. |
Kadir Cetinkaya | 06553bf | 2018-11-16 09:03:56 +0000 | [diff] [blame] | 327 | if (IndexStorage) { |
| 328 | IndexFileOut Shard; |
| 329 | Shard.Symbols = SS.get(); |
| 330 | Shard.Refs = RS.get(); |
Kadir Cetinkaya | 219c0fa | 2018-12-04 11:31:57 +0000 | [diff] [blame] | 331 | Shard.Sources = IG.get(); |
Kadir Cetinkaya | d08eab4 | 2018-11-27 16:08:53 +0000 | [diff] [blame] | 332 | |
Kadir Cetinkaya | 06553bf | 2018-11-16 09:03:56 +0000 | [diff] [blame] | 333 | 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 Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 338 | 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 Cetinkaya | 06553bf | 2018-11-16 09:03:56 +0000 | [diff] [blame] | 342 | IndexedFileDigests[Path] = Hash; |
| 343 | IndexedSymbols.update(Path, std::move(SS), std::move(RS)); |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 344 | } |
| 345 | } |
| 346 | |
Eric Liu | 667e8ef | 2018-12-18 15:39:33 +0000 | [diff] [blame^] | 347 | void 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 Cetinkaya | 06553bf | 2018-11-16 09:03:56 +0000 | [diff] [blame] | 371 | Error BackgroundIndex::index(tooling::CompileCommand Cmd, |
| 372 | BackgroundIndexStorage *IndexStorage) { |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 373 | trace::Span Tracer("BackgroundIndex"); |
| 374 | SPAN_ATTACH(Tracer, "file", Cmd.Filename); |
Kadir Cetinkaya | ed18e78 | 2018-11-15 10:34:39 +0000 | [diff] [blame] | 375 | 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 McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 382 | |
| 383 | auto FS = FSProvider.getFileSystem(); |
| 384 | auto Buf = FS->getBufferForFile(AbsolutePath); |
| 385 | if (!Buf) |
| 386 | return errorCodeToError(Buf.getError()); |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 387 | auto Hash = digest(Buf->get()->getBuffer()); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 388 | |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 389 | // 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 McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 399 | } |
| 400 | |
Eric Liu | 667e8ef | 2018-12-18 15:39:33 +0000 | [diff] [blame^] | 401 | log("Indexing {0} (digest:={1})", Cmd.Filename, toHex(Hash)); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 402 | 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 McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame] | 408 | return createStringError(inconvertibleErrorCode(), |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 409 | "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 McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame] | 415 | return createStringError(inconvertibleErrorCode(), |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 416 | "Couldn't build compiler instance"); |
| 417 | |
| 418 | SymbolCollector::Options IndexOpts; |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 419 | StringMap<FileDigest> FilesToUpdate; |
| 420 | IndexOpts.FileFilter = createFileFilter(DigestsSnapshot, FilesToUpdate); |
Kadir Cetinkaya | 219c0fa | 2018-12-04 11:31:57 +0000 | [diff] [blame] | 421 | IndexFileIn Index; |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 422 | auto Action = createStaticIndexingAction( |
Kadir Cetinkaya | 219c0fa | 2018-12-04 11:31:57 +0000 | [diff] [blame] | 423 | 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 McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 426 | |
| 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 McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame] | 434 | return createStringError(inconvertibleErrorCode(), |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 435 | "BeginSourceFile() failed"); |
| 436 | if (!Action->Execute()) |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame] | 437 | return createStringError(inconvertibleErrorCode(), "Execute() failed"); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 438 | Action->EndSourceFile(); |
Haojian Wu | d5a78e6 | 2018-12-14 12:39:08 +0000 | [diff] [blame] | 439 | 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 McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 447 | |
Kadir Cetinkaya | 219c0fa | 2018-12-04 11:31:57 +0000 | [diff] [blame] | 448 | 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 Cetinkaya | d08eab4 | 2018-11-27 16:08:53 +0000 | [diff] [blame] | 454 | |
| 455 | update(AbsolutePath, std::move(Index), FilesToUpdate, IndexStorage); |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 456 | { |
| 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 McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 462 | |
Eric Liu | 667e8ef | 2018-12-18 15:39:33 +0000 | [diff] [blame^] | 463 | if (BuildIndexPeriodMs > 0) |
| 464 | SymbolsUpdatedSinceLastIndex = true; |
| 465 | else |
| 466 | reset( |
| 467 | IndexedSymbols.buildIndex(IndexType::Light, DuplicateHandling::Merge)); |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 468 | |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 469 | return Error::success(); |
| 470 | } |
| 471 | |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 472 | } // namespace clangd |
| 473 | } // namespace clang |