diff --git a/clang-tools-extra/clangd/index/FileIndex.cpp b/clang-tools-extra/clangd/index/FileIndex.cpp --- a/clang-tools-extra/clangd/index/FileIndex.cpp +++ b/clang-tools-extra/clangd/index/FileIndex.cpp @@ -32,6 +32,7 @@ #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/ScopeExit.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Error.h" @@ -40,11 +41,17 @@ #include #include #include +#include namespace clang { namespace clangd { namespace { +void trimMemory() { + if (malloc_trim(0)) + vlog("Trimmed memory"); +} + SlabTuple indexSymbols(ASTContext &AST, std::shared_ptr PP, llvm::ArrayRef DeclsToIndex, const MainFileMacros *MacroRefsToIndex, @@ -263,6 +270,10 @@ std::unique_ptr FileSymbols::buildIndex(IndexType Type, DuplicateHandling DuplicateHandle, size_t *Version) { + // Building the index often leaves a lof of freed but unreleased memory + // (at the OS level): manually trim the memory after the index is built + auto _ = llvm::make_scope_exit(trimMemory); + std::vector> SymbolSlabs; std::vector> RefSlabs; std::vector> RelationSlabs;