1a7dea167SDimitry Andric //===- DependencyScanningFilesystem.cpp - clang-scan-deps fs --------------===// 2a7dea167SDimitry Andric // 3a7dea167SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4a7dea167SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 5a7dea167SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6a7dea167SDimitry Andric // 7a7dea167SDimitry Andric //===----------------------------------------------------------------------===// 8a7dea167SDimitry Andric 9a7dea167SDimitry Andric #include "clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h" 10a7dea167SDimitry Andric #include "clang/Lex/DependencyDirectivesSourceMinimizer.h" 11a7dea167SDimitry Andric #include "llvm/Support/MemoryBuffer.h" 12a7dea167SDimitry Andric #include "llvm/Support/Threading.h" 13a7dea167SDimitry Andric 14a7dea167SDimitry Andric using namespace clang; 15a7dea167SDimitry Andric using namespace tooling; 16a7dea167SDimitry Andric using namespace dependencies; 17a7dea167SDimitry Andric 18a7dea167SDimitry Andric CachedFileSystemEntry CachedFileSystemEntry::createFileEntry( 19a7dea167SDimitry Andric StringRef Filename, llvm::vfs::FileSystem &FS, bool Minimize) { 20a7dea167SDimitry Andric // Load the file and its content from the file system. 21a7dea167SDimitry Andric llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>> MaybeFile = 22a7dea167SDimitry Andric FS.openFileForRead(Filename); 23a7dea167SDimitry Andric if (!MaybeFile) 24a7dea167SDimitry Andric return MaybeFile.getError(); 25a7dea167SDimitry Andric llvm::ErrorOr<llvm::vfs::Status> Stat = (*MaybeFile)->status(); 26a7dea167SDimitry Andric if (!Stat) 27a7dea167SDimitry Andric return Stat.getError(); 28a7dea167SDimitry Andric 29a7dea167SDimitry Andric llvm::vfs::File &F = **MaybeFile; 30a7dea167SDimitry Andric llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MaybeBuffer = 31a7dea167SDimitry Andric F.getBuffer(Stat->getName()); 32a7dea167SDimitry Andric if (!MaybeBuffer) 33a7dea167SDimitry Andric return MaybeBuffer.getError(); 34a7dea167SDimitry Andric 35a7dea167SDimitry Andric llvm::SmallString<1024> MinimizedFileContents; 36a7dea167SDimitry Andric // Minimize the file down to directives that might affect the dependencies. 37a7dea167SDimitry Andric const auto &Buffer = *MaybeBuffer; 38a7dea167SDimitry Andric SmallVector<minimize_source_to_dependency_directives::Token, 64> Tokens; 39a7dea167SDimitry Andric if (!Minimize || minimizeSourceToDependencyDirectives( 40a7dea167SDimitry Andric Buffer->getBuffer(), MinimizedFileContents, Tokens)) { 41a7dea167SDimitry Andric // Use the original file unless requested otherwise, or 42a7dea167SDimitry Andric // if the minimization failed. 43a7dea167SDimitry Andric // FIXME: Propage the diagnostic if desired by the client. 44a7dea167SDimitry Andric CachedFileSystemEntry Result; 45a7dea167SDimitry Andric Result.MaybeStat = std::move(*Stat); 46a7dea167SDimitry Andric Result.Contents.reserve(Buffer->getBufferSize() + 1); 47a7dea167SDimitry Andric Result.Contents.append(Buffer->getBufferStart(), Buffer->getBufferEnd()); 48a7dea167SDimitry Andric // Implicitly null terminate the contents for Clang's lexer. 49a7dea167SDimitry Andric Result.Contents.push_back('\0'); 50a7dea167SDimitry Andric Result.Contents.pop_back(); 51a7dea167SDimitry Andric return Result; 52a7dea167SDimitry Andric } 53a7dea167SDimitry Andric 54a7dea167SDimitry Andric CachedFileSystemEntry Result; 55a7dea167SDimitry Andric size_t Size = MinimizedFileContents.size(); 56a7dea167SDimitry Andric Result.MaybeStat = llvm::vfs::Status(Stat->getName(), Stat->getUniqueID(), 57a7dea167SDimitry Andric Stat->getLastModificationTime(), 58a7dea167SDimitry Andric Stat->getUser(), Stat->getGroup(), Size, 59a7dea167SDimitry Andric Stat->getType(), Stat->getPermissions()); 60a7dea167SDimitry Andric // The contents produced by the minimizer must be null terminated. 61a7dea167SDimitry Andric assert(MinimizedFileContents.data()[MinimizedFileContents.size()] == '\0' && 62a7dea167SDimitry Andric "not null terminated contents"); 63a7dea167SDimitry Andric // Even though there's an implicit null terminator in the minimized contents, 64a7dea167SDimitry Andric // we want to temporarily make it explicit. This will ensure that the 65a7dea167SDimitry Andric // std::move will preserve it even if it needs to do a copy if the 66a7dea167SDimitry Andric // SmallString still has the small capacity. 67a7dea167SDimitry Andric MinimizedFileContents.push_back('\0'); 68a7dea167SDimitry Andric Result.Contents = std::move(MinimizedFileContents); 69a7dea167SDimitry Andric // Now make the null terminator implicit again, so that Clang's lexer can find 70a7dea167SDimitry Andric // it right where the buffer ends. 71a7dea167SDimitry Andric Result.Contents.pop_back(); 72a7dea167SDimitry Andric 73a7dea167SDimitry Andric // Compute the skipped PP ranges that speedup skipping over inactive 74a7dea167SDimitry Andric // preprocessor blocks. 75a7dea167SDimitry Andric llvm::SmallVector<minimize_source_to_dependency_directives::SkippedRange, 32> 76a7dea167SDimitry Andric SkippedRanges; 77a7dea167SDimitry Andric minimize_source_to_dependency_directives::computeSkippedRanges(Tokens, 78a7dea167SDimitry Andric SkippedRanges); 79a7dea167SDimitry Andric PreprocessorSkippedRangeMapping Mapping; 80a7dea167SDimitry Andric for (const auto &Range : SkippedRanges) { 81a7dea167SDimitry Andric if (Range.Length < 16) { 82a7dea167SDimitry Andric // Ignore small ranges as non-profitable. 83a7dea167SDimitry Andric // FIXME: This is a heuristic, its worth investigating the tradeoffs 84a7dea167SDimitry Andric // when it should be applied. 85a7dea167SDimitry Andric continue; 86a7dea167SDimitry Andric } 87a7dea167SDimitry Andric Mapping[Range.Offset] = Range.Length; 88a7dea167SDimitry Andric } 89a7dea167SDimitry Andric Result.PPSkippedRangeMapping = std::move(Mapping); 90a7dea167SDimitry Andric 91a7dea167SDimitry Andric return Result; 92a7dea167SDimitry Andric } 93a7dea167SDimitry Andric 94a7dea167SDimitry Andric CachedFileSystemEntry 95a7dea167SDimitry Andric CachedFileSystemEntry::createDirectoryEntry(llvm::vfs::Status &&Stat) { 96a7dea167SDimitry Andric assert(Stat.isDirectory() && "not a directory!"); 97a7dea167SDimitry Andric auto Result = CachedFileSystemEntry(); 98a7dea167SDimitry Andric Result.MaybeStat = std::move(Stat); 99a7dea167SDimitry Andric return Result; 100a7dea167SDimitry Andric } 101a7dea167SDimitry Andric 102a7dea167SDimitry Andric DependencyScanningFilesystemSharedCache:: 103a7dea167SDimitry Andric DependencyScanningFilesystemSharedCache() { 104a7dea167SDimitry Andric // This heuristic was chosen using a empirical testing on a 105a7dea167SDimitry Andric // reasonably high core machine (iMacPro 18 cores / 36 threads). The cache 106a7dea167SDimitry Andric // sharding gives a performance edge by reducing the lock contention. 107a7dea167SDimitry Andric // FIXME: A better heuristic might also consider the OS to account for 108a7dea167SDimitry Andric // the different cost of lock contention on different OSes. 109*5ffd83dbSDimitry Andric NumShards = 110*5ffd83dbSDimitry Andric std::max(2u, llvm::hardware_concurrency().compute_thread_count() / 4); 111a7dea167SDimitry Andric CacheShards = std::make_unique<CacheShard[]>(NumShards); 112a7dea167SDimitry Andric } 113a7dea167SDimitry Andric 114a7dea167SDimitry Andric /// Returns a cache entry for the corresponding key. 115a7dea167SDimitry Andric /// 116a7dea167SDimitry Andric /// A new cache entry is created if the key is not in the cache. This is a 117a7dea167SDimitry Andric /// thread safe call. 118a7dea167SDimitry Andric DependencyScanningFilesystemSharedCache::SharedFileSystemEntry & 119a7dea167SDimitry Andric DependencyScanningFilesystemSharedCache::get(StringRef Key) { 120a7dea167SDimitry Andric CacheShard &Shard = CacheShards[llvm::hash_value(Key) % NumShards]; 121a7dea167SDimitry Andric std::unique_lock<std::mutex> LockGuard(Shard.CacheLock); 122a7dea167SDimitry Andric auto It = Shard.Cache.try_emplace(Key); 123a7dea167SDimitry Andric return It.first->getValue(); 124a7dea167SDimitry Andric } 125a7dea167SDimitry Andric 126480093f4SDimitry Andric /// Whitelist file extensions that should be minimized, treating no extension as 127480093f4SDimitry Andric /// a source file that should be minimized. 128480093f4SDimitry Andric /// 129480093f4SDimitry Andric /// This is kinda hacky, it would be better if we knew what kind of file Clang 130480093f4SDimitry Andric /// was expecting instead. 131480093f4SDimitry Andric static bool shouldMinimize(StringRef Filename) { 132480093f4SDimitry Andric StringRef Ext = llvm::sys::path::extension(Filename); 133480093f4SDimitry Andric if (Ext.empty()) 134480093f4SDimitry Andric return true; // C++ standard library 135480093f4SDimitry Andric return llvm::StringSwitch<bool>(Ext) 136480093f4SDimitry Andric .CasesLower(".c", ".cc", ".cpp", ".c++", ".cxx", true) 137480093f4SDimitry Andric .CasesLower(".h", ".hh", ".hpp", ".h++", ".hxx", true) 138480093f4SDimitry Andric .CasesLower(".m", ".mm", true) 139480093f4SDimitry Andric .CasesLower(".i", ".ii", ".mi", ".mmi", true) 140480093f4SDimitry Andric .CasesLower(".def", ".inc", true) 141480093f4SDimitry Andric .Default(false); 142480093f4SDimitry Andric } 143480093f4SDimitry Andric 144480093f4SDimitry Andric 145480093f4SDimitry Andric static bool shouldCacheStatFailures(StringRef Filename) { 146480093f4SDimitry Andric StringRef Ext = llvm::sys::path::extension(Filename); 147480093f4SDimitry Andric if (Ext.empty()) 148480093f4SDimitry Andric return false; // This may be the module cache directory. 149480093f4SDimitry Andric return shouldMinimize(Filename); // Only cache stat failures on source files. 150480093f4SDimitry Andric } 151480093f4SDimitry Andric 152a7dea167SDimitry Andric llvm::ErrorOr<const CachedFileSystemEntry *> 153a7dea167SDimitry Andric DependencyScanningWorkerFilesystem::getOrCreateFileSystemEntry( 154a7dea167SDimitry Andric const StringRef Filename) { 155a7dea167SDimitry Andric if (const CachedFileSystemEntry *Entry = getCachedEntry(Filename)) { 156a7dea167SDimitry Andric return Entry; 157a7dea167SDimitry Andric } 158a7dea167SDimitry Andric 159a7dea167SDimitry Andric // FIXME: Handle PCM/PCH files. 160a7dea167SDimitry Andric // FIXME: Handle module map files. 161a7dea167SDimitry Andric 162480093f4SDimitry Andric bool KeepOriginalSource = IgnoredFiles.count(Filename) || 163480093f4SDimitry Andric !shouldMinimize(Filename); 164a7dea167SDimitry Andric DependencyScanningFilesystemSharedCache::SharedFileSystemEntry 165a7dea167SDimitry Andric &SharedCacheEntry = SharedCache.get(Filename); 166a7dea167SDimitry Andric const CachedFileSystemEntry *Result; 167a7dea167SDimitry Andric { 168a7dea167SDimitry Andric std::unique_lock<std::mutex> LockGuard(SharedCacheEntry.ValueLock); 169a7dea167SDimitry Andric CachedFileSystemEntry &CacheEntry = SharedCacheEntry.Value; 170a7dea167SDimitry Andric 171a7dea167SDimitry Andric if (!CacheEntry.isValid()) { 172a7dea167SDimitry Andric llvm::vfs::FileSystem &FS = getUnderlyingFS(); 173a7dea167SDimitry Andric auto MaybeStatus = FS.status(Filename); 174480093f4SDimitry Andric if (!MaybeStatus) { 175480093f4SDimitry Andric if (!shouldCacheStatFailures(Filename)) 176480093f4SDimitry Andric // HACK: We need to always restat non source files if the stat fails. 177480093f4SDimitry Andric // This is because Clang first looks up the module cache and module 178480093f4SDimitry Andric // files before building them, and then looks for them again. If we 179480093f4SDimitry Andric // cache the stat failure, it won't see them the second time. 180480093f4SDimitry Andric return MaybeStatus.getError(); 181480093f4SDimitry Andric else 182a7dea167SDimitry Andric CacheEntry = CachedFileSystemEntry(MaybeStatus.getError()); 183480093f4SDimitry Andric } else if (MaybeStatus->isDirectory()) 184a7dea167SDimitry Andric CacheEntry = CachedFileSystemEntry::createDirectoryEntry( 185a7dea167SDimitry Andric std::move(*MaybeStatus)); 186a7dea167SDimitry Andric else 187a7dea167SDimitry Andric CacheEntry = CachedFileSystemEntry::createFileEntry( 188a7dea167SDimitry Andric Filename, FS, !KeepOriginalSource); 189a7dea167SDimitry Andric } 190a7dea167SDimitry Andric 191a7dea167SDimitry Andric Result = &CacheEntry; 192a7dea167SDimitry Andric } 193a7dea167SDimitry Andric 194a7dea167SDimitry Andric // Store the result in the local cache. 195a7dea167SDimitry Andric setCachedEntry(Filename, Result); 196a7dea167SDimitry Andric return Result; 197a7dea167SDimitry Andric } 198a7dea167SDimitry Andric 199a7dea167SDimitry Andric llvm::ErrorOr<llvm::vfs::Status> 200a7dea167SDimitry Andric DependencyScanningWorkerFilesystem::status(const Twine &Path) { 201a7dea167SDimitry Andric SmallString<256> OwnedFilename; 202a7dea167SDimitry Andric StringRef Filename = Path.toStringRef(OwnedFilename); 203a7dea167SDimitry Andric const llvm::ErrorOr<const CachedFileSystemEntry *> Result = 204a7dea167SDimitry Andric getOrCreateFileSystemEntry(Filename); 205a7dea167SDimitry Andric if (!Result) 206a7dea167SDimitry Andric return Result.getError(); 207a7dea167SDimitry Andric return (*Result)->getStatus(); 208a7dea167SDimitry Andric } 209a7dea167SDimitry Andric 210a7dea167SDimitry Andric namespace { 211a7dea167SDimitry Andric 212a7dea167SDimitry Andric /// The VFS that is used by clang consumes the \c CachedFileSystemEntry using 213a7dea167SDimitry Andric /// this subclass. 214a7dea167SDimitry Andric class MinimizedVFSFile final : public llvm::vfs::File { 215a7dea167SDimitry Andric public: 216a7dea167SDimitry Andric MinimizedVFSFile(std::unique_ptr<llvm::MemoryBuffer> Buffer, 217a7dea167SDimitry Andric llvm::vfs::Status Stat) 218a7dea167SDimitry Andric : Buffer(std::move(Buffer)), Stat(std::move(Stat)) {} 219a7dea167SDimitry Andric 220a7dea167SDimitry Andric llvm::ErrorOr<llvm::vfs::Status> status() override { return Stat; } 221a7dea167SDimitry Andric 222a7dea167SDimitry Andric const llvm::MemoryBuffer *getBufferPtr() const { return Buffer.get(); } 223a7dea167SDimitry Andric 224a7dea167SDimitry Andric llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 225a7dea167SDimitry Andric getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator, 226a7dea167SDimitry Andric bool IsVolatile) override { 227a7dea167SDimitry Andric return std::move(Buffer); 228a7dea167SDimitry Andric } 229a7dea167SDimitry Andric 230a7dea167SDimitry Andric std::error_code close() override { return {}; } 231a7dea167SDimitry Andric 232a7dea167SDimitry Andric private: 233a7dea167SDimitry Andric std::unique_ptr<llvm::MemoryBuffer> Buffer; 234a7dea167SDimitry Andric llvm::vfs::Status Stat; 235a7dea167SDimitry Andric }; 236a7dea167SDimitry Andric 237a7dea167SDimitry Andric llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>> 238a7dea167SDimitry Andric createFile(const CachedFileSystemEntry *Entry, 239a7dea167SDimitry Andric ExcludedPreprocessorDirectiveSkipMapping *PPSkipMappings) { 240a7dea167SDimitry Andric if (Entry->isDirectory()) 241a7dea167SDimitry Andric return llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>( 242a7dea167SDimitry Andric std::make_error_code(std::errc::is_a_directory)); 243a7dea167SDimitry Andric llvm::ErrorOr<StringRef> Contents = Entry->getContents(); 244a7dea167SDimitry Andric if (!Contents) 245a7dea167SDimitry Andric return Contents.getError(); 246a7dea167SDimitry Andric auto Result = std::make_unique<MinimizedVFSFile>( 247a7dea167SDimitry Andric llvm::MemoryBuffer::getMemBuffer(*Contents, Entry->getName(), 248a7dea167SDimitry Andric /*RequiresNullTerminator=*/false), 249a7dea167SDimitry Andric *Entry->getStatus()); 250a7dea167SDimitry Andric if (!Entry->getPPSkippedRangeMapping().empty() && PPSkipMappings) 251a7dea167SDimitry Andric (*PPSkipMappings)[Result->getBufferPtr()] = 252a7dea167SDimitry Andric &Entry->getPPSkippedRangeMapping(); 253a7dea167SDimitry Andric return llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>( 254a7dea167SDimitry Andric std::unique_ptr<llvm::vfs::File>(std::move(Result))); 255a7dea167SDimitry Andric } 256a7dea167SDimitry Andric 257a7dea167SDimitry Andric } // end anonymous namespace 258a7dea167SDimitry Andric 259a7dea167SDimitry Andric llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>> 260a7dea167SDimitry Andric DependencyScanningWorkerFilesystem::openFileForRead(const Twine &Path) { 261a7dea167SDimitry Andric SmallString<256> OwnedFilename; 262a7dea167SDimitry Andric StringRef Filename = Path.toStringRef(OwnedFilename); 263a7dea167SDimitry Andric 264a7dea167SDimitry Andric const llvm::ErrorOr<const CachedFileSystemEntry *> Result = 265a7dea167SDimitry Andric getOrCreateFileSystemEntry(Filename); 266a7dea167SDimitry Andric if (!Result) 267a7dea167SDimitry Andric return Result.getError(); 268a7dea167SDimitry Andric return createFile(Result.get(), PPSkipMappings); 269a7dea167SDimitry Andric } 270