11#include "llvm/Support/MemoryBuffer.h"
12#include "llvm/Support/Threading.h"
18llvm::ErrorOr<DependencyScanningWorkerFilesystem::TentativeEntry>
19DependencyScanningWorkerFilesystem::readFile(StringRef Filename) {
21 auto MaybeFile = getUnderlyingFS().openFileForRead(Filename);
23 return MaybeFile.getError();
24 auto File = std::move(*MaybeFile);
26 auto MaybeStat =
File->status();
28 return MaybeStat.getError();
29 auto Stat = std::move(*MaybeStat);
31 auto MaybeBuffer =
File->getBuffer(Stat.getName());
33 return MaybeBuffer.getError();
34 auto Buffer = std::move(*MaybeBuffer);
37 if (Stat.getSize() != Buffer->getBufferSize())
38 Stat = llvm::vfs::Status::copyWithNewSize(Stat, Buffer->getBufferSize());
40 return TentativeEntry(Stat, std::move(Buffer));
45 auto &Entry = Ref.Entry;
47 if (Entry.isError() || Entry.isDirectory())
51 assert(Contents &&
"contents not initialized");
57 std::lock_guard<std::mutex> GuardLock(Contents->
ValueLock);
71 Contents->
DepDirectives.store(
new std::optional<DependencyDirectivesTy>());
80 new std::optional<DependencyDirectivesTy>(std::move(Directives)));
92 std::max(2u, llvm::hardware_concurrency().compute_thread_count() / 4);
93 CacheShards = std::make_unique<CacheShard[]>(NumShards);
98 StringRef Filename)
const {
99 assert(llvm::sys::path::is_absolute_gnu(Filename));
105 llvm::sys::fs::UniqueID UID)
const {
106 auto Hash = llvm::hash_combine(UID.getDevice(), UID.getFile());
107 return CacheShards[Hash % NumShards];
110std::vector<DependencyScanningFilesystemSharedCache::OutOfDateEntry>
112 llvm::vfs::FileSystem &UnderlyingFS)
const {
114 std::vector<OutOfDateEntry> InvalidDiagInfo;
115 for (
unsigned i = 0; i < NumShards; i++) {
117 std::lock_guard<std::mutex> LockGuard(Shard.
CacheLock);
120 llvm::ErrorOr<llvm::vfs::Status> Status = UnderlyingFS.status(Path);
127 InvalidDiagInfo.emplace_back(Path.data());
129 llvm::vfs::Status CachedStatus = Entry->
getStatus();
130 if (Status->getType() == llvm::sys::fs::file_type::regular_file &&
131 Status->getType() == CachedStatus.getType()) {
139 uint64_t CachedSize = CachedStatus.getSize();
140 uint64_t ActualSize = Status->getSize();
141 if (CachedSize != ActualSize) {
144 InvalidDiagInfo.emplace_back(Path.data(), CachedSize, ActualSize);
151 return InvalidDiagInfo;
156 StringRef Filename)
const {
157 assert(llvm::sys::path::is_absolute_gnu(Filename));
158 std::lock_guard<std::mutex> LockGuard(
CacheLock);
165 llvm::sys::fs::UniqueID UID)
const {
166 std::lock_guard<std::mutex> LockGuard(
CacheLock);
174 llvm::ErrorOr<llvm::vfs::Status> Stat) {
175 std::lock_guard<std::mutex> LockGuard(
CacheLock);
176 auto [It, Inserted] =
CacheByFilename.insert({Filename, {
nullptr,
nullptr}});
181 assert((Inserted ||
CachedRealPath) &&
"existing file with empty pair");
190 llvm::sys::fs::UniqueID UID, llvm::vfs::Status Stat,
191 std::unique_ptr<llvm::MemoryBuffer> Contents) {
192 std::lock_guard<std::mutex> LockGuard(
CacheLock);
194 auto &CachedEntry = It->getSecond();
210 std::lock_guard<std::mutex> LockGuard(
CacheLock);
211 auto [It, Inserted] =
CacheByFilename.insert({Filename, {&Entry,
nullptr}});
213 if (!Inserted || !CachedEntry)
214 CachedEntry = &Entry;
220 StringRef Filename)
const {
221 assert(llvm::sys::path::is_absolute_gnu(Filename));
222 std::lock_guard<std::mutex> LockGuard(
CacheLock);
229 llvm::ErrorOr<llvm::StringRef> RealPath) {
230 std::lock_guard<std::mutex> LockGuard(
CacheLock);
233 if (!StoredRealPath) {
236 return RealPath.getError();
237 return RealPath->str();
244 return *StoredRealPath;
252 Service(Service), WorkingDirForCacheLookup(
llvm::errc::invalid_argument) {
253 updateWorkingDirForCacheLookup();
257DependencyScanningWorkerFilesystem::getOrEmplaceSharedEntryForUID(
258 TentativeEntry TEntry) {
262 std::move(TEntry.Status),
263 std::move(TEntry.Contents));
267DependencyScanningWorkerFilesystem::findEntryByFilenameWithWriteThrough(
268 StringRef Filename) {
272 if (
const auto *Entry = Shard.findEntryByFilename(Filename))
278DependencyScanningWorkerFilesystem::findSharedEntryByUID(
279 llvm::vfs::Status Stat)
const {
286DependencyScanningWorkerFilesystem::getOrEmplaceSharedEntryForFilename(
287 StringRef Filename, std::error_code EC) {
288 return Service.getSharedCache()
289 .getShardForFilename(Filename)
290 .getOrEmplaceEntryForFilename(Filename, EC);
294DependencyScanningWorkerFilesystem::getOrInsertSharedEntryForFilename(
296 return Service.getSharedCache()
297 .getShardForFilename(Filename)
298 .getOrInsertEntryForFilename(Filename, Entry);
301llvm::ErrorOr<const CachedFileSystemEntry &>
302DependencyScanningWorkerFilesystem::computeAndStoreResult(
303 StringRef OriginalFilename, StringRef FilenameForLookup) {
304 llvm::ErrorOr<llvm::vfs::Status> Stat =
305 getUnderlyingFS().status(OriginalFilename);
307 if (!Service.getOpts().CacheNegativeStats ||
309 return Stat.getError();
312 getOrEmplaceSharedEntryForFilename(FilenameForLookup, Stat.getError());
313 return insertLocalEntryForFilename(FilenameForLookup, Entry);
316 if (
const auto *Entry = findSharedEntryByUID(*Stat))
317 return insertLocalEntryForFilename(FilenameForLookup, *Entry);
320 Stat->isDirectory() ? TentativeEntry(*Stat) : readFile(OriginalFilename);
322 const CachedFileSystemEntry *SharedEntry = [&]() {
324 const auto &UIDEntry = getOrEmplaceSharedEntryForUID(std::move(*TEntry));
325 return &getOrInsertSharedEntryForFilename(FilenameForLookup, UIDEntry);
327 return &getOrEmplaceSharedEntryForFilename(FilenameForLookup,
331 return insertLocalEntryForFilename(FilenameForLookup, *SharedEntry);
334llvm::ErrorOr<EntryRef>
336 StringRef OriginalFilename) {
338 auto FilenameForLookup = tryGetFilenameForLookup(OriginalFilename, PathBuf);
339 if (!FilenameForLookup)
340 return FilenameForLookup.getError();
342 if (
const auto *Entry =
343 findEntryByFilenameWithWriteThrough(*FilenameForLookup))
345 auto MaybeEntry = computeAndStoreResult(OriginalFilename, *FilenameForLookup);
347 return MaybeEntry.getError();
351llvm::ErrorOr<llvm::vfs::Status>
354 StringRef Filename = Path.toStringRef(OwnedFilename);
359 return Result->getStatus();
369 llvm::ErrorOr<llvm::vfs::Status> Status =
status(Path);
370 return Status && Status->exists();
377class DepScanFile final :
public llvm::vfs::File {
379 DepScanFile(std::unique_ptr<llvm::MemoryBuffer> Buffer,
380 llvm::vfs::Status Stat)
381 : Buffer(
std::move(Buffer)), Stat(
std::move(Stat)) {}
383 static llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>> create(
EntryRef Entry);
385 llvm::ErrorOr<llvm::vfs::Status> status()
override {
return Stat; }
387 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
388 getBuffer(
const Twine &Name, int64_t FileSize,
bool RequiresNullTerminator,
389 bool IsVolatile)
override {
390 return llvm::MemoryBuffer::getMemBuffer(Buffer->getMemBufferRef(),
391 RequiresNullTerminator);
394 std::error_code close()
override {
return {}; }
397 std::unique_ptr<llvm::MemoryBuffer> Buffer;
398 llvm::vfs::Status Stat;
403llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>
404DepScanFile::create(
EntryRef Entry) {
405 assert(!Entry.
isError() &&
"error");
408 return std::make_error_code(std::errc::is_a_directory);
410 auto Result = std::make_unique<DepScanFile>(
411 llvm::MemoryBuffer::getMemBuffer(Entry.
getContents(),
416 return llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>(
417 std::unique_ptr<llvm::vfs::File>(std::move(
Result)));
420llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>
423 StringRef Filename = Path.toStringRef(OwnedFilename);
428 return DepScanFile::create(
Result.get());
435 StringRef OriginalFilename = Path.toStringRef(OwnedFilename);
438 auto FilenameForLookup = tryGetFilenameForLookup(OriginalFilename, PathBuf);
439 if (!FilenameForLookup)
440 return FilenameForLookup.getError();
442 auto HandleCachedRealPath =
445 return RealPath.getError();
446 Output.assign(RealPath->begin(), RealPath->end());
451 if (
const auto *RealPath =
452 LocalCache.findRealPathByFilename(*FilenameForLookup))
453 return HandleCachedRealPath(*RealPath);
457 Service.getSharedCache().getShardForFilename(*FilenameForLookup);
458 if (
const auto *ShardRealPath =
459 Shard.findRealPathByFilename(*FilenameForLookup)) {
460 const auto &RealPath = LocalCache.insertRealPathForFilename(
461 *FilenameForLookup, *ShardRealPath);
462 return HandleCachedRealPath(RealPath);
466 std::error_code EC = getUnderlyingFS().getRealPath(OriginalFilename, Output);
467 llvm::ErrorOr<llvm::StringRef> ComputedRealPath = EC;
469 ComputedRealPath = StringRef{Output.data(), Output.size()};
474 const auto &RealPath = Shard.getOrEmplaceRealPathForFilename(
475 *FilenameForLookup, ComputedRealPath);
476 return HandleCachedRealPath(
477 LocalCache.insertRealPathForFilename(*FilenameForLookup, RealPath));
482 std::error_code EC = ProxyFileSystem::setCurrentWorkingDirectory(Path);
483 updateWorkingDirForCacheLookup();
487void DependencyScanningWorkerFilesystem::updateWorkingDirForCacheLookup() {
488 llvm::ErrorOr<std::string> CWD =
489 getUnderlyingFS().getCurrentWorkingDirectory();
491 WorkingDirForCacheLookup = CWD.getError();
492 }
else if (!llvm::sys::path::is_absolute_gnu(*CWD)) {
493 WorkingDirForCacheLookup = llvm::errc::invalid_argument;
495 WorkingDirForCacheLookup = *CWD;
497 assert(!WorkingDirForCacheLookup ||
498 llvm::sys::path::is_absolute_gnu(*WorkingDirForCacheLookup));
501llvm::ErrorOr<StringRef>
502DependencyScanningWorkerFilesystem::tryGetFilenameForLookup(
503 StringRef OriginalFilename, llvm::SmallVectorImpl<char> &PathBuf)
const {
504 StringRef FilenameForLookup;
505 if (llvm::sys::path::is_absolute_gnu(OriginalFilename)) {
506 FilenameForLookup = OriginalFilename;
507 }
else if (!WorkingDirForCacheLookup) {
508 return WorkingDirForCacheLookup.getError();
510 StringRef RelFilename = OriginalFilename;
511 RelFilename.consume_front(
"./");
512 PathBuf.assign(WorkingDirForCacheLookup->begin(),
513 WorkingDirForCacheLookup->end());
514 llvm::sys::path::append(PathBuf, RelFilename);
515 FilenameForLookup = StringRef{PathBuf.begin(), PathBuf.size()};
517 assert(llvm::sys::path::is_absolute_gnu(FilenameForLookup));
518 return FilenameForLookup;
An in-memory representation of a file system entity that is of interest to the dependency scanning fi...
llvm::vfs::Status getStatus() const
std::error_code getError() const
const CachedFileSystemEntry & insertEntryForFilename(StringRef Filename, const CachedFileSystemEntry &Entry)
Associates the given entry with the filename and returns the given entry pointer (for convenience).
const CachedFileSystemEntry * findEntryByFilename(StringRef Filename) const
Returns entry associated with the filename or nullptr if none is found.
CacheShard & getShardForUID(llvm::sys::fs::UniqueID UID) const
CacheShard & getShardForFilename(StringRef Filename) const
Returns shard for the given key.
std::vector< OutOfDateEntry > getOutOfDateEntries(llvm::vfs::FileSystem &UnderlyingFS) const
Visits all cached entries and re-stat an entry using UnderlyingFS to check if the cache contains out-...
DependencyScanningFilesystemSharedCache()
The dependency scanning service contains shared configuration and state that is used by the individua...
DependencyScanningFilesystemSharedCache & getSharedCache()
std::error_code getRealPath(const Twine &Path, SmallVectorImpl< char > &Output) override
bool ensureDirectiveTokensArePopulated(EntryRef Entry)
Ensure the directive tokens are populated for this file entry.
bool exists(const Twine &Path) override
Check whether Path exists.
DependencyScanningWorkerFilesystem(DependencyScanningService &Service, IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS)
llvm::ErrorOr< EntryRef > getOrCreateFileSystemEntry(StringRef Filename)
Returns entry for the given filename.
llvm::ErrorOr< std::unique_ptr< llvm::vfs::File > > openFileForRead(const Twine &Path) override
std::error_code setCurrentWorkingDirectory(const Twine &Path) override
llvm::ErrorOr< llvm::vfs::Status > status(const Twine &Path) override
Reference to a CachedFileSystemEntry.
llvm::vfs::Status getStatus() const
StringRef getContents() const
llvm::ErrorOr< EntryRef > unwrapError() const
If the cached entry represents an error, promotes it into ErrorOr.
llvm::ErrorOr< std::string > CachedRealPath
bool shouldCacheNegativeStatsForPath(StringRef Path)
The JSON file list parser is used to communicate input to InstallAPI.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool scanSourceForDependencyDirectives(StringRef Input, SmallVectorImpl< dependency_directives_scan::Token > &Tokens, SmallVectorImpl< dependency_directives_scan::Directive > &Directives, DiagnosticsEngine *Diags=nullptr, SourceLocation InputSourceLoc=SourceLocation())
Scan the input for the preprocessor directives that might have an effect on the dependencies for a co...
@ Result
The result type of a method or function.
Diagnostic wrappers for TextAPI types for error reporting.
hash_code hash_value(const clang::dependencies::ModuleID &ID)
Contents and directive tokens of a cached file entry.
std::unique_ptr< llvm::MemoryBuffer > Original
Owning storage for the original contents.
SmallVector< dependency_directives_scan::Token, 10 > DepDirectiveTokens
std::atomic< const std::optional< DependencyDirectivesTy > * > DepDirectives
Accessor to the directive tokens that's atomic to avoid data races.
std::mutex ValueLock
The mutex that must be locked before mutating directive tokens.
const CachedFileSystemEntry & getOrEmplaceEntryForUID(llvm::sys::fs::UniqueID UID, llvm::vfs::Status Stat, std::unique_ptr< llvm::MemoryBuffer > Contents)
Returns entry associated with the unique ID if there is some.
llvm::SpecificBumpPtrAllocator< CachedFileSystemEntry > EntryStorage
The backing storage for cached entries.
llvm::SpecificBumpPtrAllocator< CachedFileContents > ContentsStorage
The backing storage for cached contents.
llvm::SpecificBumpPtrAllocator< CachedRealPath > RealPathStorage
The backing storage for cached real paths.
const CachedFileSystemEntry * findEntryByUID(llvm::sys::fs::UniqueID UID) const
Returns entry associated with the unique ID or nullptr if none is found.
const CachedRealPath * findRealPathByFilename(StringRef Filename) const
Returns the real path associated with the filename or nullptr if none is found.
std::mutex CacheLock
The mutex that needs to be locked before mutation of any member.
const CachedFileSystemEntry & getOrInsertEntryForFilename(StringRef Filename, const CachedFileSystemEntry &Entry)
Returns entry associated with the filename if there is some.
const CachedFileSystemEntry * findEntryByFilename(StringRef Filename) const
Returns entry associated with the filename or nullptr if none is found.
const CachedFileSystemEntry & getOrEmplaceEntryForFilename(StringRef Filename, llvm::ErrorOr< llvm::vfs::Status > Stat)
Returns entry associated with the filename if there is some.
llvm::StringMap< std::pair< const CachedFileSystemEntry *, const CachedRealPath * >, llvm::BumpPtrAllocator > CacheByFilename
Map from filenames to cached entries and real paths.
const CachedRealPath & getOrEmplaceRealPathForFilename(StringRef Filename, llvm::ErrorOr< StringRef > RealPath)
Returns the real path associated with the filename if there is some.
llvm::DenseMap< llvm::sys::fs::UniqueID, const CachedFileSystemEntry * > EntriesByUID
Map from unique IDs to cached entries.