xref: /llvm-project/clang/lib/Basic/FileManager.cpp (revision 739d4bf8f43d0a5a3a99e07b1647ded1ce1d81b3)
1 //===--- FileManager.cpp - File System Probing and Caching ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements the FileManager interface.
10 //
11 //===----------------------------------------------------------------------===//
12 //
13 // TODO: This should index all interesting directories with dirent calls.
14 //  getdirentries ?
15 //  opendir/readdir_r/closedir ?
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "clang/Basic/FileManager.h"
20 #include "clang/Basic/FileSystemStatCache.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Config/llvm-config.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include <algorithm>
30 #include <cassert>
31 #include <climits>
32 #include <cstdint>
33 #include <cstdlib>
34 #include <string>
35 #include <utility>
36 
37 using namespace clang;
38 
39 #define DEBUG_TYPE "file-search"
40 
41 ALWAYS_ENABLED_STATISTIC(NumDirLookups, "Number of directory lookups.");
42 ALWAYS_ENABLED_STATISTIC(NumFileLookups, "Number of file lookups.");
43 ALWAYS_ENABLED_STATISTIC(NumDirCacheMisses,
44                          "Number of directory cache misses.");
45 ALWAYS_ENABLED_STATISTIC(NumFileCacheMisses, "Number of file cache misses.");
46 
47 //===----------------------------------------------------------------------===//
48 // Common logic.
49 //===----------------------------------------------------------------------===//
50 
51 FileManager::FileManager(const FileSystemOptions &FSO,
52                          IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS)
53     : FS(std::move(FS)), FileSystemOpts(FSO), SeenDirEntries(64),
54       SeenFileEntries(64), NextFileUID(0) {
55   // If the caller doesn't provide a virtual file system, just grab the real
56   // file system.
57   if (!this->FS)
58     this->FS = llvm::vfs::getRealFileSystem();
59 }
60 
61 FileManager::~FileManager() = default;
62 
63 void FileManager::setStatCache(std::unique_ptr<FileSystemStatCache> statCache) {
64   assert(statCache && "No stat cache provided?");
65   StatCache = std::move(statCache);
66 }
67 
68 void FileManager::clearStatCache() { StatCache.reset(); }
69 
70 /// Retrieve the directory that the given file name resides in.
71 /// Filename can point to either a real file or a virtual file.
72 static llvm::ErrorOr<const DirectoryEntry *>
73 getDirectoryFromFile(FileManager &FileMgr, StringRef Filename,
74                      bool CacheFailure) {
75   if (Filename.empty())
76     return std::errc::no_such_file_or_directory;
77 
78   if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
79     return std::errc::is_a_directory;
80 
81   StringRef DirName = llvm::sys::path::parent_path(Filename);
82   // Use the current directory if file has no path component.
83   if (DirName.empty())
84     DirName = ".";
85 
86   return FileMgr.getDirectory(DirName, CacheFailure);
87 }
88 
89 /// Add all ancestors of the given path (pointing to either a file or
90 /// a directory) as virtual directories.
91 void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
92   StringRef DirName = llvm::sys::path::parent_path(Path);
93   if (DirName.empty())
94     DirName = ".";
95 
96   auto &NamedDirEnt = *SeenDirEntries.insert(
97         {DirName, std::errc::no_such_file_or_directory}).first;
98 
99   // When caching a virtual directory, we always cache its ancestors
100   // at the same time.  Therefore, if DirName is already in the cache,
101   // we don't need to recurse as its ancestors must also already be in
102   // the cache (or it's a known non-virtual directory).
103   if (NamedDirEnt.second)
104     return;
105 
106   // Add the virtual directory to the cache.
107   auto UDE = std::make_unique<DirectoryEntry>();
108   UDE->Name = NamedDirEnt.first();
109   NamedDirEnt.second = *UDE.get();
110   VirtualDirectoryEntries.push_back(std::move(UDE));
111 
112   // Recursively add the other ancestors.
113   addAncestorsAsVirtualDirs(DirName);
114 }
115 
116 llvm::Expected<DirectoryEntryRef>
117 FileManager::getDirectoryRef(StringRef DirName, bool CacheFailure) {
118   // stat doesn't like trailing separators except for root directory.
119   // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
120   // (though it can strip '\\')
121   if (DirName.size() > 1 &&
122       DirName != llvm::sys::path::root_path(DirName) &&
123       llvm::sys::path::is_separator(DirName.back()))
124     DirName = DirName.substr(0, DirName.size()-1);
125 #ifdef _WIN32
126   // Fixing a problem with "clang C:test.c" on Windows.
127   // Stat("C:") does not recognize "C:" as a valid directory
128   std::string DirNameStr;
129   if (DirName.size() > 1 && DirName.back() == ':' &&
130       DirName.equals_lower(llvm::sys::path::root_name(DirName))) {
131     DirNameStr = DirName.str() + '.';
132     DirName = DirNameStr;
133   }
134 #endif
135 
136   ++NumDirLookups;
137 
138   // See if there was already an entry in the map.  Note that the map
139   // contains both virtual and real directories.
140   auto SeenDirInsertResult =
141       SeenDirEntries.insert({DirName, std::errc::no_such_file_or_directory});
142   if (!SeenDirInsertResult.second) {
143     if (SeenDirInsertResult.first->second)
144       return DirectoryEntryRef(&*SeenDirInsertResult.first);
145     return llvm::errorCodeToError(SeenDirInsertResult.first->second.getError());
146   }
147 
148   // We've not seen this before. Fill it in.
149   ++NumDirCacheMisses;
150   auto &NamedDirEnt = *SeenDirInsertResult.first;
151   assert(!NamedDirEnt.second && "should be newly-created");
152 
153   // Get the null-terminated directory name as stored as the key of the
154   // SeenDirEntries map.
155   StringRef InterndDirName = NamedDirEnt.first();
156 
157   // Check to see if the directory exists.
158   llvm::vfs::Status Status;
159   auto statError = getStatValue(InterndDirName, Status, false,
160                                 nullptr /*directory lookup*/);
161   if (statError) {
162     // There's no real directory at the given path.
163     if (CacheFailure)
164       NamedDirEnt.second = statError;
165     else
166       SeenDirEntries.erase(DirName);
167     return llvm::errorCodeToError(statError);
168   }
169 
170   // It exists.  See if we have already opened a directory with the
171   // same inode (this occurs on Unix-like systems when one dir is
172   // symlinked to another, for example) or the same path (on
173   // Windows).
174   DirectoryEntry &UDE = UniqueRealDirs[Status.getUniqueID()];
175 
176   NamedDirEnt.second = UDE;
177   if (UDE.getName().empty()) {
178     // We don't have this directory yet, add it.  We use the string
179     // key from the SeenDirEntries map as the string.
180     UDE.Name  = InterndDirName;
181   }
182 
183   return DirectoryEntryRef(&NamedDirEnt);
184 }
185 
186 llvm::ErrorOr<const DirectoryEntry *>
187 FileManager::getDirectory(StringRef DirName, bool CacheFailure) {
188   auto Result = getDirectoryRef(DirName, CacheFailure);
189   if (Result)
190     return &Result->getDirEntry();
191   return llvm::errorToErrorCode(Result.takeError());
192 }
193 
194 llvm::ErrorOr<const FileEntry *>
195 FileManager::getFile(StringRef Filename, bool openFile, bool CacheFailure) {
196   auto Result = getFileRef(Filename, openFile, CacheFailure);
197   if (Result)
198     return &Result->getFileEntry();
199   return llvm::errorToErrorCode(Result.takeError());
200 }
201 
202 llvm::Expected<FileEntryRef>
203 FileManager::getFileRef(StringRef Filename, bool openFile, bool CacheFailure) {
204   ++NumFileLookups;
205 
206   // See if there is already an entry in the map.
207   auto SeenFileInsertResult =
208       SeenFileEntries.insert({Filename, std::errc::no_such_file_or_directory});
209   if (!SeenFileInsertResult.second) {
210     if (!SeenFileInsertResult.first->second)
211       return llvm::errorCodeToError(
212           SeenFileInsertResult.first->second.getError());
213     // Construct and return and FileEntryRef, unless it's a redirect to another
214     // filename.
215     FileEntryRef::MapValue Value = *SeenFileInsertResult.first->second;
216     if (LLVM_LIKELY(Value.V.is<FileEntry *>()))
217       return FileEntryRef(*SeenFileInsertResult.first);
218     return FileEntryRef(*reinterpret_cast<const FileEntryRef::MapEntry *>(
219         Value.V.get<const void *>()));
220   }
221 
222   // We've not seen this before. Fill it in.
223   ++NumFileCacheMisses;
224   auto *NamedFileEnt = &*SeenFileInsertResult.first;
225   assert(!NamedFileEnt->second && "should be newly-created");
226 
227   // Get the null-terminated file name as stored as the key of the
228   // SeenFileEntries map.
229   StringRef InterndFileName = NamedFileEnt->first();
230 
231   // Look up the directory for the file.  When looking up something like
232   // sys/foo.h we'll discover all of the search directories that have a 'sys'
233   // subdirectory.  This will let us avoid having to waste time on known-to-fail
234   // searches when we go to find sys/bar.h, because all the search directories
235   // without a 'sys' subdir will get a cached failure result.
236   auto DirInfoOrErr = getDirectoryFromFile(*this, Filename, CacheFailure);
237   if (!DirInfoOrErr) { // Directory doesn't exist, file can't exist.
238     if (CacheFailure)
239       NamedFileEnt->second = DirInfoOrErr.getError();
240     else
241       SeenFileEntries.erase(Filename);
242 
243     return llvm::errorCodeToError(DirInfoOrErr.getError());
244   }
245   const DirectoryEntry *DirInfo = *DirInfoOrErr;
246 
247   // FIXME: Use the directory info to prune this, before doing the stat syscall.
248   // FIXME: This will reduce the # syscalls.
249 
250   // Check to see if the file exists.
251   std::unique_ptr<llvm::vfs::File> F;
252   llvm::vfs::Status Status;
253   auto statError = getStatValue(InterndFileName, Status, true,
254                                 openFile ? &F : nullptr);
255   if (statError) {
256     // There's no real file at the given path.
257     if (CacheFailure)
258       NamedFileEnt->second = statError;
259     else
260       SeenFileEntries.erase(Filename);
261 
262     return llvm::errorCodeToError(statError);
263   }
264 
265   assert((openFile || !F) && "undesired open file");
266 
267   // It exists.  See if we have already opened a file with the same inode.
268   // This occurs when one dir is symlinked to another, for example.
269   FileEntry &UFE = UniqueRealFiles[Status.getUniqueID()];
270 
271   if (Status.getName() == Filename) {
272     // The name matches. Set the FileEntry.
273     NamedFileEnt->second = FileEntryRef::MapValue(UFE);
274   } else {
275     // Name mismatch. We need a redirect. First grab the actual entry we want
276     // to return.
277     auto &Redirection =
278         *SeenFileEntries.insert({Status.getName(), FileEntryRef::MapValue(UFE)})
279              .first;
280     assert(Redirection.second->V.is<FileEntry *>() &&
281            "filename redirected to a non-canonical filename?");
282     assert(Redirection.second->V.get<FileEntry *>() == &UFE &&
283            "filename from getStatValue() refers to wrong file");
284 
285     // Cache the redirection in the previously-inserted entry, still available
286     // in the tentative return value.
287     NamedFileEnt->second = FileEntryRef::MapValue(Redirection);
288 
289     // Fix the tentative return value.
290     NamedFileEnt = &Redirection;
291   }
292 
293   FileEntryRef ReturnedRef(*NamedFileEnt);
294   if (UFE.isValid()) { // Already have an entry with this inode, return it.
295 
296     // FIXME: this hack ensures that if we look up a file by a virtual path in
297     // the VFS that the getDir() will have the virtual path, even if we found
298     // the file by a 'real' path first. This is required in order to find a
299     // module's structure when its headers/module map are mapped in the VFS.
300     // We should remove this as soon as we can properly support a file having
301     // multiple names.
302     if (DirInfo != UFE.Dir && Status.IsVFSMapped)
303       UFE.Dir = DirInfo;
304 
305     // Always update LastRef to the last name by which a file was accessed.
306     // FIXME: Neither this nor always using the first reference is correct; we
307     // want to switch towards a design where we return a FileName object that
308     // encapsulates both the name by which the file was accessed and the
309     // corresponding FileEntry.
310     // FIXME: LastRef should be removed from FileEntry once all clients adopt
311     // FileEntryRef.
312     UFE.LastRef = ReturnedRef;
313 
314     return ReturnedRef;
315   }
316 
317   // Otherwise, we don't have this file yet, add it.
318   UFE.LastRef = ReturnedRef;
319   UFE.Size    = Status.getSize();
320   UFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
321   UFE.Dir     = DirInfo;
322   UFE.UID     = NextFileUID++;
323   UFE.UniqueID = Status.getUniqueID();
324   UFE.IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
325   UFE.File = std::move(F);
326   UFE.IsValid = true;
327 
328   if (UFE.File) {
329     if (auto PathName = UFE.File->getName())
330       fillRealPathName(&UFE, *PathName);
331   } else if (!openFile) {
332     // We should still fill the path even if we aren't opening the file.
333     fillRealPathName(&UFE, InterndFileName);
334   }
335   return ReturnedRef;
336 }
337 
338 const FileEntry *
339 FileManager::getVirtualFile(StringRef Filename, off_t Size,
340                             time_t ModificationTime) {
341   ++NumFileLookups;
342 
343   // See if there is already an entry in the map for an existing file.
344   auto &NamedFileEnt = *SeenFileEntries.insert(
345       {Filename, std::errc::no_such_file_or_directory}).first;
346   if (NamedFileEnt.second) {
347     FileEntryRef::MapValue Value = *NamedFileEnt.second;
348     FileEntry *FE;
349     if (LLVM_LIKELY(FE = Value.V.dyn_cast<FileEntry *>()))
350       return FE;
351     return &FileEntryRef(*reinterpret_cast<const FileEntryRef::MapEntry *>(
352                              Value.V.get<const void *>()))
353                 .getFileEntry();
354   }
355 
356   // We've not seen this before, or the file is cached as non-existent.
357   ++NumFileCacheMisses;
358   addAncestorsAsVirtualDirs(Filename);
359   FileEntry *UFE = nullptr;
360 
361   // Now that all ancestors of Filename are in the cache, the
362   // following call is guaranteed to find the DirectoryEntry from the
363   // cache.
364   auto DirInfo = getDirectoryFromFile(*this, Filename, /*CacheFailure=*/true);
365   assert(DirInfo &&
366          "The directory of a virtual file should already be in the cache.");
367 
368   // Check to see if the file exists. If so, drop the virtual file
369   llvm::vfs::Status Status;
370   const char *InterndFileName = NamedFileEnt.first().data();
371   if (!getStatValue(InterndFileName, Status, true, nullptr)) {
372     UFE = &UniqueRealFiles[Status.getUniqueID()];
373     Status = llvm::vfs::Status(
374       Status.getName(), Status.getUniqueID(),
375       llvm::sys::toTimePoint(ModificationTime),
376       Status.getUser(), Status.getGroup(), Size,
377       Status.getType(), Status.getPermissions());
378 
379     NamedFileEnt.second = FileEntryRef::MapValue(*UFE);
380 
381     // If we had already opened this file, close it now so we don't
382     // leak the descriptor. We're not going to use the file
383     // descriptor anyway, since this is a virtual file.
384     if (UFE->File)
385       UFE->closeFile();
386 
387     // If we already have an entry with this inode, return it.
388     //
389     // FIXME: Surely this should add a reference by the new name, and return
390     // it instead...
391     if (UFE->isValid())
392       return UFE;
393 
394     UFE->UniqueID = Status.getUniqueID();
395     UFE->IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
396     fillRealPathName(UFE, Status.getName());
397   } else {
398     VirtualFileEntries.push_back(std::make_unique<FileEntry>());
399     UFE = VirtualFileEntries.back().get();
400     NamedFileEnt.second = FileEntryRef::MapValue(*UFE);
401   }
402 
403   UFE->LastRef = FileEntryRef(NamedFileEnt);
404   UFE->Size    = Size;
405   UFE->ModTime = ModificationTime;
406   UFE->Dir     = *DirInfo;
407   UFE->UID     = NextFileUID++;
408   UFE->IsValid = true;
409   UFE->File.reset();
410   return UFE;
411 }
412 
413 llvm::Optional<FileEntryRef> FileManager::getBypassFile(FileEntryRef VF) {
414   // Stat of the file and return nullptr if it doesn't exist.
415   llvm::vfs::Status Status;
416   if (getStatValue(VF.getName(), Status, /*isFile=*/true, /*F=*/nullptr))
417     return None;
418 
419   if (!SeenBypassFileEntries)
420     SeenBypassFileEntries = std::make_unique<
421         llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>>>();
422 
423   // If we've already bypassed just use the existing one.
424   auto Insertion = SeenBypassFileEntries->insert(
425       {VF.getName(), std::errc::no_such_file_or_directory});
426   if (!Insertion.second)
427     return FileEntryRef(*Insertion.first);
428 
429   // Fill in the new entry from the stat.
430   BypassFileEntries.push_back(std::make_unique<FileEntry>());
431   const FileEntry &VFE = VF.getFileEntry();
432   FileEntry &BFE = *BypassFileEntries.back();
433   Insertion.first->second = FileEntryRef::MapValue(BFE);
434   BFE.LastRef = FileEntryRef(*Insertion.first);
435   BFE.Size = Status.getSize();
436   BFE.Dir = VFE.Dir;
437   BFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
438   BFE.UID = NextFileUID++;
439   BFE.IsValid = true;
440 
441   // Save the entry in the bypass table and return.
442   return FileEntryRef(*Insertion.first);
443 }
444 
445 bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
446   StringRef pathRef(path.data(), path.size());
447 
448   if (FileSystemOpts.WorkingDir.empty()
449       || llvm::sys::path::is_absolute(pathRef))
450     return false;
451 
452   SmallString<128> NewPath(FileSystemOpts.WorkingDir);
453   llvm::sys::path::append(NewPath, pathRef);
454   path = NewPath;
455   return true;
456 }
457 
458 bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const {
459   bool Changed = FixupRelativePath(Path);
460 
461   if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
462     FS->makeAbsolute(Path);
463     Changed = true;
464   }
465 
466   return Changed;
467 }
468 
469 void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) {
470   llvm::SmallString<128> AbsPath(FileName);
471   // This is not the same as `VFS::getRealPath()`, which resolves symlinks
472   // but can be very expensive on real file systems.
473   // FIXME: the semantic of RealPathName is unclear, and the name might be
474   // misleading. We need to clean up the interface here.
475   makeAbsolutePath(AbsPath);
476   llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true);
477   UFE->RealPathName = std::string(AbsPath.str());
478 }
479 
480 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
481 FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile,
482                               bool RequiresNullTerminator) {
483   uint64_t FileSize = Entry->getSize();
484   // If there's a high enough chance that the file have changed since we
485   // got its size, force a stat before opening it.
486   if (isVolatile)
487     FileSize = -1;
488 
489   StringRef Filename = Entry->getName();
490   // If the file is already open, use the open file descriptor.
491   if (Entry->File) {
492     auto Result = Entry->File->getBuffer(Filename, FileSize,
493                                          RequiresNullTerminator, isVolatile);
494     Entry->closeFile();
495     return Result;
496   }
497 
498   // Otherwise, open the file.
499   return getBufferForFileImpl(Filename, FileSize, isVolatile,
500                               RequiresNullTerminator);
501 }
502 
503 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
504 FileManager::getBufferForFileImpl(StringRef Filename, int64_t FileSize,
505                                   bool isVolatile,
506                                   bool RequiresNullTerminator) {
507   if (FileSystemOpts.WorkingDir.empty())
508     return FS->getBufferForFile(Filename, FileSize, RequiresNullTerminator,
509                                 isVolatile);
510 
511   SmallString<128> FilePath(Filename);
512   FixupRelativePath(FilePath);
513   return FS->getBufferForFile(FilePath, FileSize, RequiresNullTerminator,
514                               isVolatile);
515 }
516 
517 /// getStatValue - Get the 'stat' information for the specified path,
518 /// using the cache to accelerate it if possible.  This returns true
519 /// if the path points to a virtual file or does not exist, or returns
520 /// false if it's an existent real file.  If FileDescriptor is NULL,
521 /// do directory look-up instead of file look-up.
522 std::error_code
523 FileManager::getStatValue(StringRef Path, llvm::vfs::Status &Status,
524                           bool isFile, std::unique_ptr<llvm::vfs::File> *F) {
525   // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
526   // absolute!
527   if (FileSystemOpts.WorkingDir.empty())
528     return FileSystemStatCache::get(Path, Status, isFile, F,
529                                     StatCache.get(), *FS);
530 
531   SmallString<128> FilePath(Path);
532   FixupRelativePath(FilePath);
533 
534   return FileSystemStatCache::get(FilePath.c_str(), Status, isFile, F,
535                                   StatCache.get(), *FS);
536 }
537 
538 std::error_code
539 FileManager::getNoncachedStatValue(StringRef Path,
540                                    llvm::vfs::Status &Result) {
541   SmallString<128> FilePath(Path);
542   FixupRelativePath(FilePath);
543 
544   llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str());
545   if (!S)
546     return S.getError();
547   Result = *S;
548   return std::error_code();
549 }
550 
551 void FileManager::GetUniqueIDMapping(
552                    SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
553   UIDToFiles.clear();
554   UIDToFiles.resize(NextFileUID);
555 
556   // Map file entries
557   for (llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>,
558                        llvm::BumpPtrAllocator>::const_iterator
559            FE = SeenFileEntries.begin(),
560            FEEnd = SeenFileEntries.end();
561        FE != FEEnd; ++FE)
562     if (llvm::ErrorOr<FileEntryRef::MapValue> Entry = FE->getValue()) {
563       if (const auto *FE = Entry->V.dyn_cast<FileEntry *>())
564         UIDToFiles[FE->getUID()] = FE;
565     }
566 
567   // Map virtual file entries
568   for (const auto &VFE : VirtualFileEntries)
569     UIDToFiles[VFE->getUID()] = VFE.get();
570 }
571 
572 StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
573   llvm::DenseMap<const void *, llvm::StringRef>::iterator Known
574     = CanonicalNames.find(Dir);
575   if (Known != CanonicalNames.end())
576     return Known->second;
577 
578   StringRef CanonicalName(Dir->getName());
579 
580   SmallString<4096> CanonicalNameBuf;
581   if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf))
582     CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
583 
584   CanonicalNames.insert({Dir, CanonicalName});
585   return CanonicalName;
586 }
587 
588 StringRef FileManager::getCanonicalName(const FileEntry *File) {
589   llvm::DenseMap<const void *, llvm::StringRef>::iterator Known
590     = CanonicalNames.find(File);
591   if (Known != CanonicalNames.end())
592     return Known->second;
593 
594   StringRef CanonicalName(File->getName());
595 
596   SmallString<4096> CanonicalNameBuf;
597   if (!FS->getRealPath(File->getName(), CanonicalNameBuf))
598     CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
599 
600   CanonicalNames.insert({File, CanonicalName});
601   return CanonicalName;
602 }
603 
604 void FileManager::PrintStats() const {
605   llvm::errs() << "\n*** File Manager Stats:\n";
606   llvm::errs() << UniqueRealFiles.size() << " real files found, "
607                << UniqueRealDirs.size() << " real dirs found.\n";
608   llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
609                << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
610   llvm::errs() << NumDirLookups << " dir lookups, "
611                << NumDirCacheMisses << " dir cache misses.\n";
612   llvm::errs() << NumFileLookups << " file lookups, "
613                << NumFileCacheMisses << " file cache misses.\n";
614 
615   //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
616 }
617