10#include "llvm/Support/MemoryBuffer.h"
11#include "llvm/Support/SmallVectorMemoryBuffer.h"
12#include "llvm/Support/Threading.h"
16using namespace tooling;
17using namespace dependencies;
19llvm::ErrorOr<DependencyScanningWorkerFilesystem::TentativeEntry>
20DependencyScanningWorkerFilesystem::readFile(StringRef
Filename) {
22 auto MaybeFile = getUnderlyingFS().openFileForRead(
Filename);
24 return MaybeFile.getError();
25 auto File = std::move(*MaybeFile);
27 auto MaybeStat =
File->status();
29 return MaybeStat.getError();
30 auto Stat = std::move(*MaybeStat);
32 auto MaybeBuffer =
File->getBuffer(Stat.getName());
34 return MaybeBuffer.getError();
35 auto Buffer = std::move(*MaybeBuffer);
38 if (Stat.getSize() != Buffer->getBufferSize())
39 Stat = llvm::vfs::Status::copyWithNewSize(Stat, Buffer->getBufferSize());
41 return TentativeEntry(Stat, std::move(Buffer));
46 auto &Entry = Ref.Entry;
48 if (Entry.isError() || Entry.isDirectory())
52 assert(Contents &&
"contents not initialized");
58 std::lock_guard<std::mutex> GuardLock(Contents->
ValueLock);
72 Contents->
DepDirectives.store(
new std::optional<DependencyDirectivesTy>());
81 new std::optional<DependencyDirectivesTy>(std::move(Directives)));
93 std::max(2u, llvm::hardware_concurrency().compute_thread_count() / 4);
94 CacheShards = std::make_unique<CacheShard[]>(NumShards);
100 assert(llvm::sys::path::is_absolute_gnu(
Filename));
106 llvm::sys::fs::UniqueID UID)
const {
107 auto Hash = llvm::hash_combine(UID.getDevice(), UID.getFile());
108 return CacheShards[Hash % NumShards];
114 assert(llvm::sys::path::is_absolute_gnu(
Filename));
115 std::lock_guard<std::mutex> LockGuard(
CacheLock);
122 llvm::sys::fs::UniqueID UID)
const {
123 std::lock_guard<std::mutex> LockGuard(CacheLock);
124 auto It = EntriesByUID.find(UID);
125 return It == EntriesByUID.end() ? nullptr : It->getSecond();
131 llvm::ErrorOr<llvm::vfs::Status> Stat) {
132 std::lock_guard<std::mutex> LockGuard(CacheLock);
133 auto [It, Inserted] = CacheByFilename.insert({
Filename, {
nullptr,
nullptr}});
138 assert((Inserted ||
CachedRealPath) &&
"existing file with empty pair");
147 llvm::sys::fs::UniqueID UID, llvm::vfs::Status Stat,
148 std::unique_ptr<llvm::MemoryBuffer> Contents) {
149 std::lock_guard<std::mutex> LockGuard(CacheLock);
150 auto [It, Inserted] = EntriesByUID.insert({UID,
nullptr});
151 auto &CachedEntry = It->getSecond();
155 StoredContents =
new (ContentsStorage.Allocate())
157 CachedEntry =
new (EntryStorage.Allocate())
167 std::lock_guard<std::mutex> LockGuard(CacheLock);
168 auto [It, Inserted] = CacheByFilename.insert({
Filename, {&Entry,
nullptr}});
170 if (!Inserted || !CachedEntry)
171 CachedEntry = &Entry;
178 assert(llvm::sys::path::is_absolute_gnu(
Filename));
179 std::lock_guard<std::mutex> LockGuard(CacheLock);
180 auto It = CacheByFilename.find(
Filename);
181 return It == CacheByFilename.end() ? nullptr : It->getValue().second;
186 llvm::ErrorOr<llvm::StringRef> RealPath) {
187 std::lock_guard<std::mutex> LockGuard(CacheLock);
190 if (!StoredRealPath) {
193 return RealPath.getError();
194 return RealPath->str();
197 StoredRealPath =
new (RealPathStorage.Allocate())
201 return *StoredRealPath;
204bool DependencyScanningWorkerFilesystem::shouldBypass(StringRef
Path)
const {
205 return BypassedPathPrefix &&
Path.starts_with(*BypassedPathPrefix);
212 llvm::vfs::ProxyFileSystem>(
std::move(FS)),
213 SharedCache(SharedCache),
214 WorkingDirForCacheLookup(
llvm::errc::invalid_argument) {
215 updateWorkingDirForCacheLookup();
219DependencyScanningWorkerFilesystem::getOrEmplaceSharedEntryForUID(
220 TentativeEntry TEntry) {
221 auto &Shard = SharedCache.
getShardForUID(TEntry.Status.getUniqueID());
223 std::move(TEntry.Status),
224 std::move(TEntry.Contents));
228DependencyScanningWorkerFilesystem::findEntryByFilenameWithWriteThrough(
233 if (
const auto *Entry = Shard.findEntryByFilename(
Filename))
238llvm::ErrorOr<const CachedFileSystemEntry &>
239DependencyScanningWorkerFilesystem::computeAndStoreResult(
240 StringRef OriginalFilename, StringRef FilenameForLookup) {
241 llvm::ErrorOr<llvm::vfs::Status> Stat =
242 getUnderlyingFS().status(OriginalFilename);
245 getOrEmplaceSharedEntryForFilename(FilenameForLookup, Stat.getError());
246 return insertLocalEntryForFilename(FilenameForLookup, Entry);
249 if (
const auto *Entry = findSharedEntryByUID(*Stat))
250 return insertLocalEntryForFilename(FilenameForLookup, *Entry);
253 Stat->isDirectory() ? TentativeEntry(*Stat) : readFile(OriginalFilename);
257 const auto &UIDEntry = getOrEmplaceSharedEntryForUID(std::move(*TEntry));
258 return &getOrInsertSharedEntryForFilename(FilenameForLookup, UIDEntry);
260 return &getOrEmplaceSharedEntryForFilename(FilenameForLookup,
264 return insertLocalEntryForFilename(FilenameForLookup, *SharedEntry);
267llvm::ErrorOr<EntryRef>
269 StringRef OriginalFilename) {
271 auto FilenameForLookup = tryGetFilenameForLookup(OriginalFilename, PathBuf);
272 if (!FilenameForLookup)
273 return FilenameForLookup.getError();
275 if (
const auto *Entry =
276 findEntryByFilenameWithWriteThrough(*FilenameForLookup))
278 auto MaybeEntry = computeAndStoreResult(OriginalFilename, *FilenameForLookup);
280 return MaybeEntry.getError();
284llvm::ErrorOr<llvm::vfs::Status>
290 return getUnderlyingFS().status(
Path);
295 return Result->getStatus();
305 llvm::ErrorOr<llvm::vfs::Status> Status =
status(
Path);
306 return Status && Status->exists();
313class DepScanFile final :
public llvm::vfs::File {
315 DepScanFile(std::unique_ptr<llvm::MemoryBuffer> Buffer,
316 llvm::vfs::Status Stat)
317 : Buffer(
std::move(Buffer)), Stat(
std::move(Stat)) {}
319 static llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>> create(
EntryRef Entry);
321 llvm::ErrorOr<llvm::vfs::Status> status()
override {
return Stat; }
323 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
324 getBuffer(
const Twine &Name, int64_t FileSize,
bool RequiresNullTerminator,
325 bool IsVolatile)
override {
326 return std::move(Buffer);
329 std::error_code close()
override {
return {}; }
332 std::unique_ptr<llvm::MemoryBuffer> Buffer;
333 llvm::vfs::Status Stat;
338llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>
339DepScanFile::create(
EntryRef Entry) {
340 assert(!Entry.
isError() &&
"error");
343 return std::make_error_code(std::errc::is_a_directory);
345 auto Result = std::make_unique<DepScanFile>(
346 llvm::MemoryBuffer::getMemBuffer(Entry.
getContents(),
351 return llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>(
352 std::unique_ptr<llvm::vfs::File>(std::move(
Result)));
355llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>
361 return getUnderlyingFS().openFileForRead(
Path);
366 return DepScanFile::create(
Result.get());
373 StringRef OriginalFilename =
Path.toStringRef(OwnedFilename);
375 if (shouldBypass(OriginalFilename))
376 return getUnderlyingFS().getRealPath(
Path, Output);
379 auto FilenameForLookup = tryGetFilenameForLookup(OriginalFilename, PathBuf);
380 if (!FilenameForLookup)
381 return FilenameForLookup.getError();
383 auto HandleCachedRealPath =
386 return RealPath.getError();
387 Output.assign(RealPath->begin(), RealPath->end());
392 if (
const auto *RealPath =
394 return HandleCachedRealPath(*RealPath);
398 if (
const auto *ShardRealPath =
399 Shard.findRealPathByFilename(*FilenameForLookup)) {
401 *FilenameForLookup, *ShardRealPath);
402 return HandleCachedRealPath(RealPath);
406 std::error_code EC = getUnderlyingFS().getRealPath(OriginalFilename, Output);
407 llvm::ErrorOr<llvm::StringRef> ComputedRealPath = EC;
409 ComputedRealPath = StringRef{Output.data(), Output.size()};
414 const auto &RealPath = Shard.getOrEmplaceRealPathForFilename(
415 *FilenameForLookup, ComputedRealPath);
416 return HandleCachedRealPath(
422 std::error_code EC = ProxyFileSystem::setCurrentWorkingDirectory(
Path);
423 updateWorkingDirForCacheLookup();
427void DependencyScanningWorkerFilesystem::updateWorkingDirForCacheLookup() {
428 llvm::ErrorOr<std::string> CWD =
429 getUnderlyingFS().getCurrentWorkingDirectory();
431 WorkingDirForCacheLookup = CWD.getError();
432 }
else if (!llvm::sys::path::is_absolute_gnu(*CWD)) {
433 WorkingDirForCacheLookup = llvm::errc::invalid_argument;
435 WorkingDirForCacheLookup = *CWD;
437 assert(!WorkingDirForCacheLookup ||
438 llvm::sys::path::is_absolute_gnu(*WorkingDirForCacheLookup));
441llvm::ErrorOr<StringRef>
442DependencyScanningWorkerFilesystem::tryGetFilenameForLookup(
444 StringRef FilenameForLookup;
445 if (llvm::sys::path::is_absolute_gnu(OriginalFilename)) {
446 FilenameForLookup = OriginalFilename;
447 }
else if (!WorkingDirForCacheLookup) {
448 return WorkingDirForCacheLookup.getError();
450 StringRef RelFilename = OriginalFilename;
451 RelFilename.consume_front(
"./");
452 PathBuf.assign(WorkingDirForCacheLookup->begin(),
453 WorkingDirForCacheLookup->end());
454 llvm::sys::path::append(PathBuf, RelFilename);
455 FilenameForLookup = StringRef{PathBuf.begin(), PathBuf.size()};
457 assert(llvm::sys::path::is_absolute_gnu(FilenameForLookup));
458 return FilenameForLookup;
An in-memory representation of a file system entity that is of interest to the dependency scanning fi...
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.
The JSON file list parser is used to communicate input to InstallAPI.
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::tooling::dependencies::ModuleID &ID)
Contents and directive tokens of a cached file entry.
std::mutex ValueLock
The mutex that must be locked before mutating directive tokens.
std::atomic< const std::optional< DependencyDirectivesTy > * > DepDirectives
Accessor to the directive tokens that's atomic to avoid data races.
std::unique_ptr< llvm::MemoryBuffer > Original
Owning storage for the original contents.
SmallVector< dependency_directives_scan::Token, 10 > DepDirectiveTokens