1 //===--- FileIndex.cpp - Indexes for files. ------------------------ C++-*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "FileIndex.h" 10 #include "CollectMacros.h" 11 #include "ParsedAST.h" 12 #include "SymbolCollector.h" 13 #include "index/CanonicalIncludes.h" 14 #include "index/Index.h" 15 #include "index/MemIndex.h" 16 #include "index/Merge.h" 17 #include "index/Ref.h" 18 #include "index/Relation.h" 19 #include "index/Serialization.h" 20 #include "index/Symbol.h" 21 #include "index/SymbolID.h" 22 #include "index/SymbolOrigin.h" 23 #include "index/dex/Dex.h" 24 #include "support/Logger.h" 25 #include "support/Path.h" 26 #include "clang/AST/ASTContext.h" 27 #include "clang/Index/IndexingAction.h" 28 #include "clang/Index/IndexingOptions.h" 29 #include "clang/Lex/MacroInfo.h" 30 #include "clang/Lex/Preprocessor.h" 31 #include "llvm/ADT/DenseMap.h" 32 #include "llvm/ADT/STLExtras.h" 33 #include "llvm/ADT/StringMap.h" 34 #include "llvm/ADT/StringRef.h" 35 #include "llvm/Support/Error.h" 36 #include <memory> 37 #include <tuple> 38 #include <utility> 39 #include <vector> 40 41 namespace clang { 42 namespace clangd { 43 namespace { 44 45 SlabTuple indexSymbols(ASTContext &AST, std::shared_ptr<Preprocessor> PP, 46 llvm::ArrayRef<Decl *> DeclsToIndex, 47 const MainFileMacros *MacroRefsToIndex, 48 const CanonicalIncludes &Includes, bool IsIndexMainAST, 49 llvm::StringRef Version) { 50 SymbolCollector::Options CollectorOpts; 51 CollectorOpts.CollectIncludePath = true; 52 CollectorOpts.Includes = &Includes; 53 CollectorOpts.CountReferences = false; 54 CollectorOpts.Origin = SymbolOrigin::Dynamic; 55 56 index::IndexingOptions IndexOpts; 57 // We only need declarations, because we don't count references. 58 IndexOpts.SystemSymbolFilter = 59 index::IndexingOptions::SystemSymbolFilterKind::DeclarationsOnly; 60 IndexOpts.IndexFunctionLocals = false; 61 if (IsIndexMainAST) { 62 // We only collect refs when indexing main AST. 63 CollectorOpts.RefFilter = RefKind::All; 64 // Comments for main file can always be obtained from sema, do not store 65 // them in the index. 66 CollectorOpts.StoreAllDocumentation = false; 67 } else { 68 IndexOpts.IndexMacrosInPreprocessor = true; 69 CollectorOpts.CollectMacro = true; 70 CollectorOpts.StoreAllDocumentation = true; 71 } 72 73 SymbolCollector Collector(std::move(CollectorOpts)); 74 Collector.setPreprocessor(PP); 75 if (MacroRefsToIndex) 76 Collector.handleMacros(*MacroRefsToIndex); 77 index::indexTopLevelDecls(AST, *PP, DeclsToIndex, Collector, IndexOpts); 78 79 const auto &SM = AST.getSourceManager(); 80 const auto *MainFileEntry = SM.getFileEntryForID(SM.getMainFileID()); 81 std::string FileName = 82 std::string(MainFileEntry ? MainFileEntry->getName() : ""); 83 84 auto Syms = Collector.takeSymbols(); 85 auto Refs = Collector.takeRefs(); 86 auto Relations = Collector.takeRelations(); 87 88 vlog("indexed {0} AST for {1} version {2}:\n" 89 " symbol slab: {3} symbols, {4} bytes\n" 90 " ref slab: {5} symbols, {6} refs, {7} bytes\n" 91 " relations slab: {8} relations, {9} bytes", 92 IsIndexMainAST ? "file" : "preamble", FileName, Version, Syms.size(), 93 Syms.bytes(), Refs.size(), Refs.numRefs(), Refs.bytes(), 94 Relations.size(), Relations.bytes()); 95 return std::make_tuple(std::move(Syms), std::move(Refs), 96 std::move(Relations)); 97 } 98 99 // Resolves URI to file paths with cache. 100 class URIToFileCache { 101 public: 102 URIToFileCache(PathRef HintPath) : HintPath(HintPath) {} 103 104 llvm::StringRef operator[](llvm::StringRef FileURI) { 105 if (FileURI.empty()) 106 return ""; 107 auto I = URIToPathCache.try_emplace(FileURI); 108 if (I.second) { 109 I.first->second = llvm::cantFail(URI::resolve(FileURI, HintPath), 110 "Failed to resolve URI"); 111 } 112 return I.first->second; 113 } 114 115 private: 116 PathRef HintPath; 117 llvm::StringMap<std::string> URIToPathCache; 118 }; 119 120 // We keep only the node "U" and its edges. Any node other than "U" will be 121 // empty in the resultant graph. 122 IncludeGraph getSubGraph(llvm::StringRef URI, const IncludeGraph &FullGraph) { 123 IncludeGraph IG; 124 125 auto Entry = IG.try_emplace(URI).first; 126 auto &Node = Entry->getValue(); 127 Node = FullGraph.lookup(Entry->getKey()); 128 Node.URI = Entry->getKey(); 129 130 // URIs inside nodes must point into the keys of the same IncludeGraph. 131 for (auto &Include : Node.DirectIncludes) { 132 auto I = IG.try_emplace(Include).first; 133 I->getValue().URI = I->getKey(); 134 Include = I->getKey(); 135 } 136 return IG; 137 } 138 } // namespace 139 140 FileShardedIndex::FileShardedIndex(IndexFileIn Input, PathRef HintPath) 141 : Index(std::move(Input)) { 142 URIToFileCache UriToFile(HintPath); 143 // Used to build RelationSlabs. 144 llvm::DenseMap<SymbolID, FileShard *> SymbolIDToFile; 145 146 // Attribute each Symbol to both their declaration and definition locations. 147 if (Index.Symbols) { 148 for (const auto &S : *Index.Symbols) { 149 auto File = UriToFile[S.CanonicalDeclaration.FileURI]; 150 auto It = Shards.try_emplace(File); 151 It.first->getValue().Symbols.insert(&S); 152 SymbolIDToFile[S.ID] = &It.first->getValue(); 153 // Only bother if definition file is different than declaration file. 154 if (S.Definition && 155 S.Definition.FileURI != S.CanonicalDeclaration.FileURI) { 156 auto File = UriToFile[S.Definition.FileURI]; 157 auto It = Shards.try_emplace(File); 158 It.first->getValue().Symbols.insert(&S); 159 } 160 } 161 } 162 // Attribute references into each file they occured in. 163 if (Index.Refs) { 164 for (const auto &SymRefs : *Index.Refs) { 165 for (const auto &R : SymRefs.second) { 166 auto File = UriToFile[R.Location.FileURI]; 167 const auto It = Shards.try_emplace(File); 168 It.first->getValue().Refs.insert(&R); 169 RefToSymID[&R] = SymRefs.first; 170 } 171 } 172 } 173 // Attribute relations to the file declaraing their Subject as Object might 174 // not have been indexed, see SymbolCollector::processRelations for details. 175 if (Index.Relations) { 176 for (const auto &R : *Index.Relations) { 177 // FIXME: RelationSlab shouldn't contain dangling relations. 178 if (auto *File = SymbolIDToFile.lookup(R.Subject)) 179 File->Relations.insert(&R); 180 } 181 } 182 // Store only the direct includes of a file in a shard. 183 if (Index.Sources) { 184 const auto &FullGraph = *Index.Sources; 185 for (const auto &It : FullGraph) { 186 auto File = UriToFile[It.first()]; 187 auto ShardIt = Shards.try_emplace(File); 188 ShardIt.first->getValue().IG = getSubGraph(It.first(), FullGraph); 189 } 190 } 191 } 192 std::vector<PathRef> FileShardedIndex::getAllFiles() const { 193 // It should be enough to construct a vector with {Shards.keys().begin(), 194 // Shards.keys().end()} but MSVC fails to compile that. 195 std::vector<PathRef> Result; 196 Result.reserve(Shards.size()); 197 for (PathRef Key : Shards.keys()) 198 Result.push_back(Key); 199 return Result; 200 } 201 202 IndexFileIn FileShardedIndex::getShard(PathRef File) const { 203 auto It = Shards.find(File); 204 assert(It != Shards.end() && "received unknown file"); 205 206 IndexFileIn IF; 207 IF.Sources = It->getValue().IG; 208 IF.Cmd = Index.Cmd; 209 210 SymbolSlab::Builder SymB; 211 for (const auto *S : It->getValue().Symbols) 212 SymB.insert(*S); 213 IF.Symbols = std::move(SymB).build(); 214 215 RefSlab::Builder RefB; 216 for (const auto *Ref : It->getValue().Refs) { 217 auto SID = RefToSymID.lookup(Ref); 218 RefB.insert(SID, *Ref); 219 } 220 IF.Refs = std::move(RefB).build(); 221 222 RelationSlab::Builder RelB; 223 for (const auto *Rel : It->getValue().Relations) { 224 RelB.insert(*Rel); 225 } 226 IF.Relations = std::move(RelB).build(); 227 return IF; 228 } 229 230 SlabTuple indexMainDecls(ParsedAST &AST) { 231 return indexSymbols(AST.getASTContext(), AST.getPreprocessorPtr(), 232 AST.getLocalTopLevelDecls(), &AST.getMacros(), 233 AST.getCanonicalIncludes(), 234 /*IsIndexMainAST=*/true, AST.version()); 235 } 236 237 SlabTuple indexHeaderSymbols(llvm::StringRef Version, ASTContext &AST, 238 std::shared_ptr<Preprocessor> PP, 239 const CanonicalIncludes &Includes) { 240 std::vector<Decl *> DeclsToIndex( 241 AST.getTranslationUnitDecl()->decls().begin(), 242 AST.getTranslationUnitDecl()->decls().end()); 243 return indexSymbols(AST, std::move(PP), DeclsToIndex, 244 /*MainFileMacros=*/nullptr, Includes, 245 /*IsIndexMainAST=*/false, Version); 246 } 247 248 void FileSymbols::update(PathRef Path, std::unique_ptr<SymbolSlab> Symbols, 249 std::unique_ptr<RefSlab> Refs, 250 std::unique_ptr<RelationSlab> Relations, 251 bool CountReferences) { 252 std::lock_guard<std::mutex> Lock(Mutex); 253 if (!Symbols) 254 FileToSymbols.erase(Path); 255 else 256 FileToSymbols[Path] = std::move(Symbols); 257 if (!Refs) { 258 FileToRefs.erase(Path); 259 } else { 260 RefSlabAndCountReferences Item; 261 Item.CountReferences = CountReferences; 262 Item.Slab = std::move(Refs); 263 FileToRefs[Path] = std::move(Item); 264 } 265 if (!Relations) 266 FileToRelations.erase(Path); 267 else 268 FileToRelations[Path] = std::move(Relations); 269 } 270 271 std::unique_ptr<SymbolIndex> 272 FileSymbols::buildIndex(IndexType Type, DuplicateHandling DuplicateHandle) { 273 std::vector<std::shared_ptr<SymbolSlab>> SymbolSlabs; 274 std::vector<std::shared_ptr<RefSlab>> RefSlabs; 275 std::vector<std::shared_ptr<RelationSlab>> RelationSlabs; 276 std::vector<RefSlab *> MainFileRefs; 277 { 278 std::lock_guard<std::mutex> Lock(Mutex); 279 for (const auto &FileAndSymbols : FileToSymbols) 280 SymbolSlabs.push_back(FileAndSymbols.second); 281 for (const auto &FileAndRefs : FileToRefs) { 282 RefSlabs.push_back(FileAndRefs.second.Slab); 283 if (FileAndRefs.second.CountReferences) 284 MainFileRefs.push_back(RefSlabs.back().get()); 285 } 286 for (const auto &FileAndRelations : FileToRelations) 287 RelationSlabs.push_back(FileAndRelations.second); 288 } 289 std::vector<const Symbol *> AllSymbols; 290 std::vector<Symbol> SymsStorage; 291 switch (DuplicateHandle) { 292 case DuplicateHandling::Merge: { 293 llvm::DenseMap<SymbolID, Symbol> Merged; 294 for (const auto &Slab : SymbolSlabs) { 295 for (const auto &Sym : *Slab) { 296 assert(Sym.References == 0 && 297 "Symbol with non-zero references sent to FileSymbols"); 298 auto I = Merged.try_emplace(Sym.ID, Sym); 299 if (!I.second) 300 I.first->second = mergeSymbol(I.first->second, Sym); 301 } 302 } 303 for (const RefSlab *Refs : MainFileRefs) 304 for (const auto &Sym : *Refs) { 305 auto It = Merged.find(Sym.first); 306 // This might happen while background-index is still running. 307 if (It == Merged.end()) 308 continue; 309 It->getSecond().References += Sym.second.size(); 310 } 311 SymsStorage.reserve(Merged.size()); 312 for (auto &Sym : Merged) { 313 SymsStorage.push_back(std::move(Sym.second)); 314 AllSymbols.push_back(&SymsStorage.back()); 315 } 316 break; 317 } 318 case DuplicateHandling::PickOne: { 319 llvm::DenseSet<SymbolID> AddedSymbols; 320 for (const auto &Slab : SymbolSlabs) 321 for (const auto &Sym : *Slab) { 322 assert(Sym.References == 0 && 323 "Symbol with non-zero references sent to FileSymbols"); 324 if (AddedSymbols.insert(Sym.ID).second) 325 AllSymbols.push_back(&Sym); 326 } 327 break; 328 } 329 } 330 331 std::vector<Ref> RefsStorage; // Contiguous ranges for each SymbolID. 332 llvm::DenseMap<SymbolID, llvm::ArrayRef<Ref>> AllRefs; 333 { 334 llvm::DenseMap<SymbolID, llvm::SmallVector<Ref, 4>> MergedRefs; 335 size_t Count = 0; 336 for (const auto &RefSlab : RefSlabs) 337 for (const auto &Sym : *RefSlab) { 338 MergedRefs[Sym.first].append(Sym.second.begin(), Sym.second.end()); 339 Count += Sym.second.size(); 340 } 341 RefsStorage.reserve(Count); 342 AllRefs.reserve(MergedRefs.size()); 343 for (auto &Sym : MergedRefs) { 344 auto &SymRefs = Sym.second; 345 // Sorting isn't required, but yields more stable results over rebuilds. 346 llvm::sort(SymRefs); 347 llvm::copy(SymRefs, back_inserter(RefsStorage)); 348 AllRefs.try_emplace( 349 Sym.first, 350 llvm::ArrayRef<Ref>(&RefsStorage[RefsStorage.size() - SymRefs.size()], 351 SymRefs.size())); 352 } 353 } 354 355 std::vector<Relation> AllRelations; 356 for (const auto &RelationSlab : RelationSlabs) { 357 for (const auto &R : *RelationSlab) 358 AllRelations.push_back(R); 359 } 360 361 size_t StorageSize = 362 RefsStorage.size() * sizeof(Ref) + SymsStorage.size() * sizeof(Symbol); 363 for (const auto &Slab : SymbolSlabs) 364 StorageSize += Slab->bytes(); 365 for (const auto &RefSlab : RefSlabs) 366 StorageSize += RefSlab->bytes(); 367 for (const auto &RelationSlab : RelationSlabs) 368 StorageSize += RelationSlab->bytes(); 369 370 // Index must keep the slabs and contiguous ranges alive. 371 switch (Type) { 372 case IndexType::Light: 373 return std::make_unique<MemIndex>( 374 llvm::make_pointee_range(AllSymbols), std::move(AllRefs), 375 std::move(AllRelations), 376 std::make_tuple(std::move(SymbolSlabs), std::move(RefSlabs), 377 std::move(RefsStorage), std::move(SymsStorage)), 378 StorageSize); 379 case IndexType::Heavy: 380 return std::make_unique<dex::Dex>( 381 llvm::make_pointee_range(AllSymbols), std::move(AllRefs), 382 std::move(AllRelations), 383 std::make_tuple(std::move(SymbolSlabs), std::move(RefSlabs), 384 std::move(RefsStorage), std::move(SymsStorage)), 385 StorageSize); 386 } 387 llvm_unreachable("Unknown clangd::IndexType"); 388 } 389 390 FileIndex::FileIndex(bool UseDex) 391 : MergedIndex(&MainFileIndex, &PreambleIndex), UseDex(UseDex), 392 PreambleIndex(std::make_unique<MemIndex>()), 393 MainFileIndex(std::make_unique<MemIndex>()) {} 394 395 void FileIndex::updatePreamble(PathRef Path, llvm::StringRef Version, 396 ASTContext &AST, 397 std::shared_ptr<Preprocessor> PP, 398 const CanonicalIncludes &Includes) { 399 IndexFileIn IF; 400 std::tie(IF.Symbols, std::ignore, IF.Relations) = 401 indexHeaderSymbols(Version, AST, std::move(PP), Includes); 402 FileShardedIndex ShardedIndex(std::move(IF), Path); 403 for (PathRef File : ShardedIndex.getAllFiles()) { 404 auto IF = ShardedIndex.getShard(File); 405 PreambleSymbols.update( 406 File, std::make_unique<SymbolSlab>(std::move(*IF.Symbols)), 407 std::make_unique<RefSlab>(), 408 std::make_unique<RelationSlab>(std::move(*IF.Relations)), 409 /*CountReferences=*/false); 410 } 411 PreambleIndex.reset( 412 PreambleSymbols.buildIndex(UseDex ? IndexType::Heavy : IndexType::Light, 413 DuplicateHandling::PickOne)); 414 vlog("Build dynamic index for header symbols with estimated memory usage of " 415 "{0} bytes", 416 PreambleIndex.estimateMemoryUsage()); 417 } 418 419 void FileIndex::updateMain(PathRef Path, ParsedAST &AST) { 420 auto Contents = indexMainDecls(AST); 421 MainFileSymbols.update( 422 Path, std::make_unique<SymbolSlab>(std::move(std::get<0>(Contents))), 423 std::make_unique<RefSlab>(std::move(std::get<1>(Contents))), 424 std::make_unique<RelationSlab>(std::move(std::get<2>(Contents))), 425 /*CountReferences=*/true); 426 MainFileIndex.reset( 427 MainFileSymbols.buildIndex(IndexType::Light, DuplicateHandling::Merge)); 428 vlog("Build dynamic index for main-file symbols with estimated memory usage " 429 "of {0} bytes", 430 MainFileIndex.estimateMemoryUsage()); 431 } 432 433 } // namespace clangd 434 } // namespace clang 435