xref: /llvm-project/clang/lib/Basic/FileManager.cpp (revision ee30546c007d26d9c0c6f15b0e291a8bb0e651f9)
1 //===--- FileManager.cpp - File System Probing and Caching ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the FileManager interface.
11 //
12 //===----------------------------------------------------------------------===//
13 //
14 // TODO: This should index all interesting directories with dirent calls.
15 //  getdirentries ?
16 //  opendir/readdir_r/closedir ?
17 //
18 //===----------------------------------------------------------------------===//
19 
20 #include "clang/Basic/FileManager.h"
21 #include "clang/Basic/FileSystemStatCache.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/Config/llvm-config.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/Path.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Support/system_error.h"
29 #include <map>
30 #include <set>
31 #include <string>
32 
33 // FIXME: This is terrible, we need this for ::close.
34 #if !defined(_MSC_VER) && !defined(__MINGW32__)
35 #include <unistd.h>
36 #include <sys/uio.h>
37 #else
38 #include <io.h>
39 #ifndef S_ISFIFO
40 #define S_ISFIFO(x) (0)
41 #endif
42 #endif
43 #if defined(LLVM_ON_UNIX)
44 #include <limits.h>
45 #endif
46 using namespace clang;
47 
48 // FIXME: Enhance libsystem to support inode and other fields.
49 #include <sys/stat.h>
50 
51 /// NON_EXISTENT_DIR - A special value distinct from null that is used to
52 /// represent a dir name that doesn't exist on the disk.
53 #define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1)
54 
55 /// NON_EXISTENT_FILE - A special value distinct from null that is used to
56 /// represent a filename that doesn't exist on the disk.
57 #define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1)
58 
59 
60 FileEntry::~FileEntry() {
61   // If this FileEntry owns an open file descriptor that never got used, close
62   // it.
63   if (FD != -1) ::close(FD);
64 }
65 
66 bool FileEntry::isNamedPipe() const {
67   return S_ISFIFO(FileMode);
68 }
69 
70 //===----------------------------------------------------------------------===//
71 // Windows.
72 //===----------------------------------------------------------------------===//
73 
74 #ifdef LLVM_ON_WIN32
75 
76 namespace {
77   static std::string GetFullPath(const char *relPath) {
78     char *absPathStrPtr = _fullpath(NULL, relPath, 0);
79     assert(absPathStrPtr && "_fullpath() returned NULL!");
80 
81     std::string absPath(absPathStrPtr);
82 
83     free(absPathStrPtr);
84     return absPath;
85   }
86 }
87 
88 class FileManager::UniqueDirContainer {
89   /// UniqueDirs - Cache from full path to existing directories/files.
90   ///
91   llvm::StringMap<DirectoryEntry> UniqueDirs;
92 
93 public:
94   /// getDirectory - Return an existing DirectoryEntry with the given
95   /// name if there is already one; otherwise create and return a
96   /// default-constructed DirectoryEntry.
97   DirectoryEntry &getDirectory(const char *Name,
98                                const struct stat & /*StatBuf*/) {
99     std::string FullPath(GetFullPath(Name));
100     return UniqueDirs.GetOrCreateValue(FullPath).getValue();
101   }
102 
103   size_t size() const { return UniqueDirs.size(); }
104 };
105 
106 class FileManager::UniqueFileContainer {
107   /// UniqueFiles - Cache from full path to existing directories/files.
108   ///
109   llvm::StringMap<FileEntry, llvm::BumpPtrAllocator> UniqueFiles;
110 
111 public:
112   /// getFile - Return an existing FileEntry with the given name if
113   /// there is already one; otherwise create and return a
114   /// default-constructed FileEntry.
115   FileEntry &getFile(const char *Name, const struct stat & /*StatBuf*/) {
116     std::string FullPath(GetFullPath(Name));
117 
118     // Lowercase string because Windows filesystem is case insensitive.
119     FullPath = StringRef(FullPath).lower();
120     return UniqueFiles.GetOrCreateValue(FullPath).getValue();
121   }
122 
123   size_t size() const { return UniqueFiles.size(); }
124 
125   void erase(const FileEntry *Entry) {
126     std::string FullPath(GetFullPath(Entry->getName()));
127 
128     // Lowercase string because Windows filesystem is case insensitive.
129     FullPath = StringRef(FullPath).lower();
130     UniqueFiles.erase(FullPath);
131   }
132 };
133 
134 //===----------------------------------------------------------------------===//
135 // Unix-like Systems.
136 //===----------------------------------------------------------------------===//
137 
138 #else
139 
140 class FileManager::UniqueDirContainer {
141   /// UniqueDirs - Cache from ID's to existing directories/files.
142   std::map<std::pair<dev_t, ino_t>, DirectoryEntry> UniqueDirs;
143 
144 public:
145   /// getDirectory - Return an existing DirectoryEntry with the given
146   /// ID's if there is already one; otherwise create and return a
147   /// default-constructed DirectoryEntry.
148   DirectoryEntry &getDirectory(const char * /*Name*/,
149                                const struct stat &StatBuf) {
150     return UniqueDirs[std::make_pair(StatBuf.st_dev, StatBuf.st_ino)];
151   }
152 
153   size_t size() const { return UniqueDirs.size(); }
154 };
155 
156 class FileManager::UniqueFileContainer {
157   /// UniqueFiles - Cache from ID's to existing directories/files.
158   std::set<FileEntry> UniqueFiles;
159 
160 public:
161   /// getFile - Return an existing FileEntry with the given ID's if
162   /// there is already one; otherwise create and return a
163   /// default-constructed FileEntry.
164   FileEntry &getFile(const char * /*Name*/, const struct stat &StatBuf) {
165     return
166       const_cast<FileEntry&>(
167                     *UniqueFiles.insert(FileEntry(StatBuf.st_dev,
168                                                   StatBuf.st_ino,
169                                                   StatBuf.st_mode)).first);
170   }
171 
172   size_t size() const { return UniqueFiles.size(); }
173 
174   void erase(const FileEntry *Entry) { UniqueFiles.erase(*Entry); }
175 };
176 
177 #endif
178 
179 //===----------------------------------------------------------------------===//
180 // Common logic.
181 //===----------------------------------------------------------------------===//
182 
183 FileManager::FileManager(const FileSystemOptions &FSO)
184   : FileSystemOpts(FSO),
185     UniqueRealDirs(*new UniqueDirContainer()),
186     UniqueRealFiles(*new UniqueFileContainer()),
187     SeenDirEntries(64), SeenFileEntries(64), NextFileUID(0) {
188   NumDirLookups = NumFileLookups = 0;
189   NumDirCacheMisses = NumFileCacheMisses = 0;
190 }
191 
192 FileManager::~FileManager() {
193   delete &UniqueRealDirs;
194   delete &UniqueRealFiles;
195   for (unsigned i = 0, e = VirtualFileEntries.size(); i != e; ++i)
196     delete VirtualFileEntries[i];
197   for (unsigned i = 0, e = VirtualDirectoryEntries.size(); i != e; ++i)
198     delete VirtualDirectoryEntries[i];
199 }
200 
201 void FileManager::addStatCache(FileSystemStatCache *statCache,
202                                bool AtBeginning) {
203   assert(statCache && "No stat cache provided?");
204   if (AtBeginning || StatCache.get() == 0) {
205     statCache->setNextStatCache(StatCache.take());
206     StatCache.reset(statCache);
207     return;
208   }
209 
210   FileSystemStatCache *LastCache = StatCache.get();
211   while (LastCache->getNextStatCache())
212     LastCache = LastCache->getNextStatCache();
213 
214   LastCache->setNextStatCache(statCache);
215 }
216 
217 void FileManager::removeStatCache(FileSystemStatCache *statCache) {
218   if (!statCache)
219     return;
220 
221   if (StatCache.get() == statCache) {
222     // This is the first stat cache.
223     StatCache.reset(StatCache->takeNextStatCache());
224     return;
225   }
226 
227   // Find the stat cache in the list.
228   FileSystemStatCache *PrevCache = StatCache.get();
229   while (PrevCache && PrevCache->getNextStatCache() != statCache)
230     PrevCache = PrevCache->getNextStatCache();
231 
232   assert(PrevCache && "Stat cache not found for removal");
233   PrevCache->setNextStatCache(statCache->getNextStatCache());
234 }
235 
236 void FileManager::clearStatCaches() {
237   StatCache.reset(0);
238 }
239 
240 /// \brief Retrieve the directory that the given file name resides in.
241 /// Filename can point to either a real file or a virtual file.
242 static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
243                                                   StringRef Filename,
244                                                   bool CacheFailure) {
245   if (Filename.empty())
246     return NULL;
247 
248   if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
249     return NULL;  // If Filename is a directory.
250 
251   StringRef DirName = llvm::sys::path::parent_path(Filename);
252   // Use the current directory if file has no path component.
253   if (DirName.empty())
254     DirName = ".";
255 
256   return FileMgr.getDirectory(DirName, CacheFailure);
257 }
258 
259 /// Add all ancestors of the given path (pointing to either a file or
260 /// a directory) as virtual directories.
261 void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
262   StringRef DirName = llvm::sys::path::parent_path(Path);
263   if (DirName.empty())
264     return;
265 
266   llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
267     SeenDirEntries.GetOrCreateValue(DirName);
268 
269   // When caching a virtual directory, we always cache its ancestors
270   // at the same time.  Therefore, if DirName is already in the cache,
271   // we don't need to recurse as its ancestors must also already be in
272   // the cache.
273   if (NamedDirEnt.getValue())
274     return;
275 
276   // Add the virtual directory to the cache.
277   DirectoryEntry *UDE = new DirectoryEntry;
278   UDE->Name = NamedDirEnt.getKeyData();
279   NamedDirEnt.setValue(UDE);
280   VirtualDirectoryEntries.push_back(UDE);
281 
282   // Recursively add the other ancestors.
283   addAncestorsAsVirtualDirs(DirName);
284 }
285 
286 const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
287                                                 bool CacheFailure) {
288   // stat doesn't like trailing separators except for root directory.
289   // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
290   // (though it can strip '\\')
291   if (DirName.size() > 1 &&
292       DirName != llvm::sys::path::root_path(DirName) &&
293       llvm::sys::path::is_separator(DirName.back()))
294     DirName = DirName.substr(0, DirName.size()-1);
295 #ifdef LLVM_ON_WIN32
296   // Fixing a problem with "clang C:test.c" on Windows.
297   // Stat("C:") does not recognize "C:" as a valid directory
298   std::string DirNameStr;
299   if (DirName.size() > 1 && DirName.back() == ':' &&
300       DirName.equals_lower(llvm::sys::path::root_name(DirName))) {
301     DirNameStr = DirName.str() + '.';
302     DirName = DirNameStr;
303   }
304 #endif
305 
306   ++NumDirLookups;
307   llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
308     SeenDirEntries.GetOrCreateValue(DirName);
309 
310   // See if there was already an entry in the map.  Note that the map
311   // contains both virtual and real directories.
312   if (NamedDirEnt.getValue())
313     return NamedDirEnt.getValue() == NON_EXISTENT_DIR
314               ? 0 : NamedDirEnt.getValue();
315 
316   ++NumDirCacheMisses;
317 
318   // By default, initialize it to invalid.
319   NamedDirEnt.setValue(NON_EXISTENT_DIR);
320 
321   // Get the null-terminated directory name as stored as the key of the
322   // SeenDirEntries map.
323   const char *InterndDirName = NamedDirEnt.getKeyData();
324 
325   // Check to see if the directory exists.
326   struct stat StatBuf;
327   if (getStatValue(InterndDirName, StatBuf, false, 0/*directory lookup*/)) {
328     // There's no real directory at the given path.
329     if (!CacheFailure)
330       SeenDirEntries.erase(DirName);
331     return 0;
332   }
333 
334   // It exists.  See if we have already opened a directory with the
335   // same inode (this occurs on Unix-like systems when one dir is
336   // symlinked to another, for example) or the same path (on
337   // Windows).
338   DirectoryEntry &UDE = UniqueRealDirs.getDirectory(InterndDirName, StatBuf);
339 
340   NamedDirEnt.setValue(&UDE);
341   if (!UDE.getName()) {
342     // We don't have this directory yet, add it.  We use the string
343     // key from the SeenDirEntries map as the string.
344     UDE.Name  = InterndDirName;
345   }
346 
347   return &UDE;
348 }
349 
350 const FileEntry *FileManager::getFile(StringRef Filename, bool openFile,
351                                       bool CacheFailure) {
352   ++NumFileLookups;
353 
354   // See if there is already an entry in the map.
355   llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
356     SeenFileEntries.GetOrCreateValue(Filename);
357 
358   // See if there is already an entry in the map.
359   if (NamedFileEnt.getValue())
360     return NamedFileEnt.getValue() == NON_EXISTENT_FILE
361                  ? 0 : NamedFileEnt.getValue();
362 
363   ++NumFileCacheMisses;
364 
365   // By default, initialize it to invalid.
366   NamedFileEnt.setValue(NON_EXISTENT_FILE);
367 
368   // Get the null-terminated file name as stored as the key of the
369   // SeenFileEntries map.
370   const char *InterndFileName = NamedFileEnt.getKeyData();
371 
372   // Look up the directory for the file.  When looking up something like
373   // sys/foo.h we'll discover all of the search directories that have a 'sys'
374   // subdirectory.  This will let us avoid having to waste time on known-to-fail
375   // searches when we go to find sys/bar.h, because all the search directories
376   // without a 'sys' subdir will get a cached failure result.
377   const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
378                                                        CacheFailure);
379   if (DirInfo == 0) {  // Directory doesn't exist, file can't exist.
380     if (!CacheFailure)
381       SeenFileEntries.erase(Filename);
382 
383     return 0;
384   }
385 
386   // FIXME: Use the directory info to prune this, before doing the stat syscall.
387   // FIXME: This will reduce the # syscalls.
388 
389   // Nope, there isn't.  Check to see if the file exists.
390   int FileDescriptor = -1;
391   struct stat StatBuf;
392   if (getStatValue(InterndFileName, StatBuf, true,
393                    openFile ? &FileDescriptor : 0)) {
394     // There's no real file at the given path.
395     if (!CacheFailure)
396       SeenFileEntries.erase(Filename);
397 
398     return 0;
399   }
400 
401   if (FileDescriptor != -1 && !openFile) {
402     close(FileDescriptor);
403     FileDescriptor = -1;
404   }
405 
406   // It exists.  See if we have already opened a file with the same inode.
407   // This occurs when one dir is symlinked to another, for example.
408   FileEntry &UFE = UniqueRealFiles.getFile(InterndFileName, StatBuf);
409 
410   NamedFileEnt.setValue(&UFE);
411   if (UFE.getName()) { // Already have an entry with this inode, return it.
412     // If the stat process opened the file, close it to avoid a FD leak.
413     if (FileDescriptor != -1)
414       close(FileDescriptor);
415 
416     return &UFE;
417   }
418 
419   // Otherwise, we don't have this directory yet, add it.
420   // FIXME: Change the name to be a char* that points back to the
421   // 'SeenFileEntries' key.
422   UFE.Name    = InterndFileName;
423   UFE.Size    = StatBuf.st_size;
424   UFE.ModTime = StatBuf.st_mtime;
425   UFE.Dir     = DirInfo;
426   UFE.UID     = NextFileUID++;
427   UFE.FD      = FileDescriptor;
428   return &UFE;
429 }
430 
431 const FileEntry *
432 FileManager::getVirtualFile(StringRef Filename, off_t Size,
433                             time_t ModificationTime) {
434   ++NumFileLookups;
435 
436   // See if there is already an entry in the map.
437   llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
438     SeenFileEntries.GetOrCreateValue(Filename);
439 
440   // See if there is already an entry in the map.
441   if (NamedFileEnt.getValue() && NamedFileEnt.getValue() != NON_EXISTENT_FILE)
442     return NamedFileEnt.getValue();
443 
444   ++NumFileCacheMisses;
445 
446   // By default, initialize it to invalid.
447   NamedFileEnt.setValue(NON_EXISTENT_FILE);
448 
449   addAncestorsAsVirtualDirs(Filename);
450   FileEntry *UFE = 0;
451 
452   // Now that all ancestors of Filename are in the cache, the
453   // following call is guaranteed to find the DirectoryEntry from the
454   // cache.
455   const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
456                                                        /*CacheFailure=*/true);
457   assert(DirInfo &&
458          "The directory of a virtual file should already be in the cache.");
459 
460   // Check to see if the file exists. If so, drop the virtual file
461   struct stat StatBuf;
462   const char *InterndFileName = NamedFileEnt.getKeyData();
463   if (getStatValue(InterndFileName, StatBuf, true, 0) == 0) {
464     StatBuf.st_size = Size;
465     StatBuf.st_mtime = ModificationTime;
466     UFE = &UniqueRealFiles.getFile(InterndFileName, StatBuf);
467 
468     NamedFileEnt.setValue(UFE);
469 
470     // If we had already opened this file, close it now so we don't
471     // leak the descriptor. We're not going to use the file
472     // descriptor anyway, since this is a virtual file.
473     if (UFE->FD != -1) {
474       close(UFE->FD);
475       UFE->FD = -1;
476     }
477 
478     // If we already have an entry with this inode, return it.
479     if (UFE->getName())
480       return UFE;
481   }
482 
483   if (!UFE) {
484     UFE = new FileEntry();
485     VirtualFileEntries.push_back(UFE);
486     NamedFileEnt.setValue(UFE);
487   }
488 
489   UFE->Name    = InterndFileName;
490   UFE->Size    = Size;
491   UFE->ModTime = ModificationTime;
492   UFE->Dir     = DirInfo;
493   UFE->UID     = NextFileUID++;
494   UFE->FD      = -1;
495   return UFE;
496 }
497 
498 void FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
499   StringRef pathRef(path.data(), path.size());
500 
501   if (FileSystemOpts.WorkingDir.empty()
502       || llvm::sys::path::is_absolute(pathRef))
503     return;
504 
505   SmallString<128> NewPath(FileSystemOpts.WorkingDir);
506   llvm::sys::path::append(NewPath, pathRef);
507   path = NewPath;
508 }
509 
510 llvm::MemoryBuffer *FileManager::
511 getBufferForFile(const FileEntry *Entry, std::string *ErrorStr,
512                  bool isVolatile) {
513   OwningPtr<llvm::MemoryBuffer> Result;
514   llvm::error_code ec;
515 
516   uint64_t FileSize = Entry->getSize();
517   // If there's a high enough chance that the file have changed since we
518   // got its size, force a stat before opening it.
519   if (isVolatile)
520     FileSize = -1;
521 
522   const char *Filename = Entry->getName();
523   // If the file is already open, use the open file descriptor.
524   if (Entry->FD != -1) {
525     ec = llvm::MemoryBuffer::getOpenFile(Entry->FD, Filename, Result, FileSize);
526     if (ErrorStr)
527       *ErrorStr = ec.message();
528 
529     close(Entry->FD);
530     Entry->FD = -1;
531     return Result.take();
532   }
533 
534   // Otherwise, open the file.
535 
536   if (FileSystemOpts.WorkingDir.empty()) {
537     ec = llvm::MemoryBuffer::getFile(Filename, Result, FileSize);
538     if (ec && ErrorStr)
539       *ErrorStr = ec.message();
540     return Result.take();
541   }
542 
543   SmallString<128> FilePath(Entry->getName());
544   FixupRelativePath(FilePath);
545   ec = llvm::MemoryBuffer::getFile(FilePath.str(), Result, FileSize);
546   if (ec && ErrorStr)
547     *ErrorStr = ec.message();
548   return Result.take();
549 }
550 
551 llvm::MemoryBuffer *FileManager::
552 getBufferForFile(StringRef Filename, std::string *ErrorStr) {
553   OwningPtr<llvm::MemoryBuffer> Result;
554   llvm::error_code ec;
555   if (FileSystemOpts.WorkingDir.empty()) {
556     ec = llvm::MemoryBuffer::getFile(Filename, Result);
557     if (ec && ErrorStr)
558       *ErrorStr = ec.message();
559     return Result.take();
560   }
561 
562   SmallString<128> FilePath(Filename);
563   FixupRelativePath(FilePath);
564   ec = llvm::MemoryBuffer::getFile(FilePath.c_str(), Result);
565   if (ec && ErrorStr)
566     *ErrorStr = ec.message();
567   return Result.take();
568 }
569 
570 /// getStatValue - Get the 'stat' information for the specified path,
571 /// using the cache to accelerate it if possible.  This returns true
572 /// if the path points to a virtual file or does not exist, or returns
573 /// false if it's an existent real file.  If FileDescriptor is NULL,
574 /// do directory look-up instead of file look-up.
575 bool FileManager::getStatValue(const char *Path, struct stat &StatBuf,
576                                bool isFile, int *FileDescriptor) {
577   // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
578   // absolute!
579   if (FileSystemOpts.WorkingDir.empty())
580     return FileSystemStatCache::get(Path, StatBuf, isFile, FileDescriptor,
581                                     StatCache.get());
582 
583   SmallString<128> FilePath(Path);
584   FixupRelativePath(FilePath);
585 
586   return FileSystemStatCache::get(FilePath.c_str(), StatBuf,
587                                   isFile, FileDescriptor, StatCache.get());
588 }
589 
590 bool FileManager::getNoncachedStatValue(StringRef Path,
591                                         struct stat &StatBuf) {
592   SmallString<128> FilePath(Path);
593   FixupRelativePath(FilePath);
594 
595   return ::stat(FilePath.c_str(), &StatBuf) != 0;
596 }
597 
598 void FileManager::invalidateCache(const FileEntry *Entry) {
599   assert(Entry && "Cannot invalidate a NULL FileEntry");
600 
601   SeenFileEntries.erase(Entry->getName());
602 
603   // FileEntry invalidation should not block future optimizations in the file
604   // caches. Possible alternatives are cache truncation (invalidate last N) or
605   // invalidation of the whole cache.
606   UniqueRealFiles.erase(Entry);
607 }
608 
609 
610 void FileManager::GetUniqueIDMapping(
611                    SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
612   UIDToFiles.clear();
613   UIDToFiles.resize(NextFileUID);
614 
615   // Map file entries
616   for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
617          FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
618        FE != FEEnd; ++FE)
619     if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE)
620       UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
621 
622   // Map virtual file entries
623   for (SmallVectorImpl<FileEntry *>::const_iterator
624          VFE = VirtualFileEntries.begin(), VFEEnd = VirtualFileEntries.end();
625        VFE != VFEEnd; ++VFE)
626     if (*VFE && *VFE != NON_EXISTENT_FILE)
627       UIDToFiles[(*VFE)->getUID()] = *VFE;
628 }
629 
630 void FileManager::modifyFileEntry(FileEntry *File,
631                                   off_t Size, time_t ModificationTime) {
632   File->Size = Size;
633   File->ModTime = ModificationTime;
634 }
635 
636 StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
637   // FIXME: use llvm::sys::fs::canonical() when it gets implemented
638 #ifdef LLVM_ON_UNIX
639   llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known
640     = CanonicalDirNames.find(Dir);
641   if (Known != CanonicalDirNames.end())
642     return Known->second;
643 
644   StringRef CanonicalName(Dir->getName());
645   char CanonicalNameBuf[PATH_MAX];
646   if (realpath(Dir->getName(), CanonicalNameBuf)) {
647     unsigned Len = strlen(CanonicalNameBuf);
648     char *Mem = static_cast<char *>(CanonicalNameStorage.Allocate(Len, 1));
649     memcpy(Mem, CanonicalNameBuf, Len);
650     CanonicalName = StringRef(Mem, Len);
651   }
652 
653   CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName));
654   return CanonicalName;
655 #else
656   return StringRef(Dir->getName());
657 #endif
658 }
659 
660 void FileManager::PrintStats() const {
661   llvm::errs() << "\n*** File Manager Stats:\n";
662   llvm::errs() << UniqueRealFiles.size() << " real files found, "
663                << UniqueRealDirs.size() << " real dirs found.\n";
664   llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
665                << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
666   llvm::errs() << NumDirLookups << " dir lookups, "
667                << NumDirCacheMisses << " dir cache misses.\n";
668   llvm::errs() << NumFileLookups << " file lookups, "
669                << NumFileCacheMisses << " file cache misses.\n";
670 
671   //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
672 }
673