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.
109a7dea167SDimitry Andric   NumShards = std::max(2u, llvm::hardware_concurrency() / 4);
110a7dea167SDimitry Andric   CacheShards = std::make_unique<CacheShard[]>(NumShards);
111a7dea167SDimitry Andric }
112a7dea167SDimitry Andric 
113a7dea167SDimitry Andric /// Returns a cache entry for the corresponding key.
114a7dea167SDimitry Andric ///
115a7dea167SDimitry Andric /// A new cache entry is created if the key is not in the cache. This is a
116a7dea167SDimitry Andric /// thread safe call.
117a7dea167SDimitry Andric DependencyScanningFilesystemSharedCache::SharedFileSystemEntry &
118a7dea167SDimitry Andric DependencyScanningFilesystemSharedCache::get(StringRef Key) {
119a7dea167SDimitry Andric   CacheShard &Shard = CacheShards[llvm::hash_value(Key) % NumShards];
120a7dea167SDimitry Andric   std::unique_lock<std::mutex> LockGuard(Shard.CacheLock);
121a7dea167SDimitry Andric   auto It = Shard.Cache.try_emplace(Key);
122a7dea167SDimitry Andric   return It.first->getValue();
123a7dea167SDimitry Andric }
124a7dea167SDimitry Andric 
125*480093f4SDimitry Andric /// Whitelist file extensions that should be minimized, treating no extension as
126*480093f4SDimitry Andric /// a source file that should be minimized.
127*480093f4SDimitry Andric ///
128*480093f4SDimitry Andric /// This is kinda hacky, it would be better if we knew what kind of file Clang
129*480093f4SDimitry Andric /// was expecting instead.
130*480093f4SDimitry Andric static bool shouldMinimize(StringRef Filename) {
131*480093f4SDimitry Andric   StringRef Ext = llvm::sys::path::extension(Filename);
132*480093f4SDimitry Andric   if (Ext.empty())
133*480093f4SDimitry Andric     return true; // C++ standard library
134*480093f4SDimitry Andric   return llvm::StringSwitch<bool>(Ext)
135*480093f4SDimitry Andric     .CasesLower(".c", ".cc", ".cpp", ".c++", ".cxx", true)
136*480093f4SDimitry Andric     .CasesLower(".h", ".hh", ".hpp", ".h++", ".hxx", true)
137*480093f4SDimitry Andric     .CasesLower(".m", ".mm", true)
138*480093f4SDimitry Andric     .CasesLower(".i", ".ii", ".mi", ".mmi", true)
139*480093f4SDimitry Andric     .CasesLower(".def", ".inc", true)
140*480093f4SDimitry Andric     .Default(false);
141*480093f4SDimitry Andric }
142*480093f4SDimitry Andric 
143*480093f4SDimitry Andric 
144*480093f4SDimitry Andric static bool shouldCacheStatFailures(StringRef Filename) {
145*480093f4SDimitry Andric   StringRef Ext = llvm::sys::path::extension(Filename);
146*480093f4SDimitry Andric   if (Ext.empty())
147*480093f4SDimitry Andric     return false; // This may be the module cache directory.
148*480093f4SDimitry Andric   return shouldMinimize(Filename); // Only cache stat failures on source files.
149*480093f4SDimitry Andric }
150*480093f4SDimitry Andric 
151a7dea167SDimitry Andric llvm::ErrorOr<const CachedFileSystemEntry *>
152a7dea167SDimitry Andric DependencyScanningWorkerFilesystem::getOrCreateFileSystemEntry(
153a7dea167SDimitry Andric     const StringRef Filename) {
154a7dea167SDimitry Andric   if (const CachedFileSystemEntry *Entry = getCachedEntry(Filename)) {
155a7dea167SDimitry Andric     return Entry;
156a7dea167SDimitry Andric   }
157a7dea167SDimitry Andric 
158a7dea167SDimitry Andric   // FIXME: Handle PCM/PCH files.
159a7dea167SDimitry Andric   // FIXME: Handle module map files.
160a7dea167SDimitry Andric 
161*480093f4SDimitry Andric   bool KeepOriginalSource = IgnoredFiles.count(Filename) ||
162*480093f4SDimitry Andric                             !shouldMinimize(Filename);
163a7dea167SDimitry Andric   DependencyScanningFilesystemSharedCache::SharedFileSystemEntry
164a7dea167SDimitry Andric       &SharedCacheEntry = SharedCache.get(Filename);
165a7dea167SDimitry Andric   const CachedFileSystemEntry *Result;
166a7dea167SDimitry Andric   {
167a7dea167SDimitry Andric     std::unique_lock<std::mutex> LockGuard(SharedCacheEntry.ValueLock);
168a7dea167SDimitry Andric     CachedFileSystemEntry &CacheEntry = SharedCacheEntry.Value;
169a7dea167SDimitry Andric 
170a7dea167SDimitry Andric     if (!CacheEntry.isValid()) {
171a7dea167SDimitry Andric       llvm::vfs::FileSystem &FS = getUnderlyingFS();
172a7dea167SDimitry Andric       auto MaybeStatus = FS.status(Filename);
173*480093f4SDimitry Andric       if (!MaybeStatus) {
174*480093f4SDimitry Andric         if (!shouldCacheStatFailures(Filename))
175*480093f4SDimitry Andric           // HACK: We need to always restat non source files if the stat fails.
176*480093f4SDimitry Andric           //   This is because Clang first looks up the module cache and module
177*480093f4SDimitry Andric           //   files before building them, and then looks for them again. If we
178*480093f4SDimitry Andric           //   cache the stat failure, it won't see them the second time.
179*480093f4SDimitry Andric           return MaybeStatus.getError();
180*480093f4SDimitry Andric         else
181a7dea167SDimitry Andric           CacheEntry = CachedFileSystemEntry(MaybeStatus.getError());
182*480093f4SDimitry Andric       } else if (MaybeStatus->isDirectory())
183a7dea167SDimitry Andric         CacheEntry = CachedFileSystemEntry::createDirectoryEntry(
184a7dea167SDimitry Andric             std::move(*MaybeStatus));
185a7dea167SDimitry Andric       else
186a7dea167SDimitry Andric         CacheEntry = CachedFileSystemEntry::createFileEntry(
187a7dea167SDimitry Andric             Filename, FS, !KeepOriginalSource);
188a7dea167SDimitry Andric     }
189a7dea167SDimitry Andric 
190a7dea167SDimitry Andric     Result = &CacheEntry;
191a7dea167SDimitry Andric   }
192a7dea167SDimitry Andric 
193a7dea167SDimitry Andric   // Store the result in the local cache.
194a7dea167SDimitry Andric   setCachedEntry(Filename, Result);
195a7dea167SDimitry Andric   return Result;
196a7dea167SDimitry Andric }
197a7dea167SDimitry Andric 
198a7dea167SDimitry Andric llvm::ErrorOr<llvm::vfs::Status>
199a7dea167SDimitry Andric DependencyScanningWorkerFilesystem::status(const Twine &Path) {
200a7dea167SDimitry Andric   SmallString<256> OwnedFilename;
201a7dea167SDimitry Andric   StringRef Filename = Path.toStringRef(OwnedFilename);
202a7dea167SDimitry Andric   const llvm::ErrorOr<const CachedFileSystemEntry *> Result =
203a7dea167SDimitry Andric       getOrCreateFileSystemEntry(Filename);
204a7dea167SDimitry Andric   if (!Result)
205a7dea167SDimitry Andric     return Result.getError();
206a7dea167SDimitry Andric   return (*Result)->getStatus();
207a7dea167SDimitry Andric }
208a7dea167SDimitry Andric 
209a7dea167SDimitry Andric namespace {
210a7dea167SDimitry Andric 
211a7dea167SDimitry Andric /// The VFS that is used by clang consumes the \c CachedFileSystemEntry using
212a7dea167SDimitry Andric /// this subclass.
213a7dea167SDimitry Andric class MinimizedVFSFile final : public llvm::vfs::File {
214a7dea167SDimitry Andric public:
215a7dea167SDimitry Andric   MinimizedVFSFile(std::unique_ptr<llvm::MemoryBuffer> Buffer,
216a7dea167SDimitry Andric                    llvm::vfs::Status Stat)
217a7dea167SDimitry Andric       : Buffer(std::move(Buffer)), Stat(std::move(Stat)) {}
218a7dea167SDimitry Andric 
219a7dea167SDimitry Andric   llvm::ErrorOr<llvm::vfs::Status> status() override { return Stat; }
220a7dea167SDimitry Andric 
221a7dea167SDimitry Andric   const llvm::MemoryBuffer *getBufferPtr() const { return Buffer.get(); }
222a7dea167SDimitry Andric 
223a7dea167SDimitry Andric   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
224a7dea167SDimitry Andric   getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
225a7dea167SDimitry Andric             bool IsVolatile) override {
226a7dea167SDimitry Andric     return std::move(Buffer);
227a7dea167SDimitry Andric   }
228a7dea167SDimitry Andric 
229a7dea167SDimitry Andric   std::error_code close() override { return {}; }
230a7dea167SDimitry Andric 
231a7dea167SDimitry Andric private:
232a7dea167SDimitry Andric   std::unique_ptr<llvm::MemoryBuffer> Buffer;
233a7dea167SDimitry Andric   llvm::vfs::Status Stat;
234a7dea167SDimitry Andric };
235a7dea167SDimitry Andric 
236a7dea167SDimitry Andric llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>
237a7dea167SDimitry Andric createFile(const CachedFileSystemEntry *Entry,
238a7dea167SDimitry Andric            ExcludedPreprocessorDirectiveSkipMapping *PPSkipMappings) {
239a7dea167SDimitry Andric   if (Entry->isDirectory())
240a7dea167SDimitry Andric     return llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>(
241a7dea167SDimitry Andric         std::make_error_code(std::errc::is_a_directory));
242a7dea167SDimitry Andric   llvm::ErrorOr<StringRef> Contents = Entry->getContents();
243a7dea167SDimitry Andric   if (!Contents)
244a7dea167SDimitry Andric     return Contents.getError();
245a7dea167SDimitry Andric   auto Result = std::make_unique<MinimizedVFSFile>(
246a7dea167SDimitry Andric       llvm::MemoryBuffer::getMemBuffer(*Contents, Entry->getName(),
247a7dea167SDimitry Andric                                        /*RequiresNullTerminator=*/false),
248a7dea167SDimitry Andric       *Entry->getStatus());
249a7dea167SDimitry Andric   if (!Entry->getPPSkippedRangeMapping().empty() && PPSkipMappings)
250a7dea167SDimitry Andric     (*PPSkipMappings)[Result->getBufferPtr()] =
251a7dea167SDimitry Andric         &Entry->getPPSkippedRangeMapping();
252a7dea167SDimitry Andric   return llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>(
253a7dea167SDimitry Andric       std::unique_ptr<llvm::vfs::File>(std::move(Result)));
254a7dea167SDimitry Andric }
255a7dea167SDimitry Andric 
256a7dea167SDimitry Andric } // end anonymous namespace
257a7dea167SDimitry Andric 
258a7dea167SDimitry Andric llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>
259a7dea167SDimitry Andric DependencyScanningWorkerFilesystem::openFileForRead(const Twine &Path) {
260a7dea167SDimitry Andric   SmallString<256> OwnedFilename;
261a7dea167SDimitry Andric   StringRef Filename = Path.toStringRef(OwnedFilename);
262a7dea167SDimitry Andric 
263a7dea167SDimitry Andric   const llvm::ErrorOr<const CachedFileSystemEntry *> Result =
264a7dea167SDimitry Andric       getOrCreateFileSystemEntry(Filename);
265a7dea167SDimitry Andric   if (!Result)
266a7dea167SDimitry Andric     return Result.getError();
267a7dea167SDimitry Andric   return createFile(Result.get(), PPSkipMappings);
268a7dea167SDimitry Andric }
269