1 //===--- HeaderSearch.cpp - Resolve Header File Locations ---===//
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 DirectoryLookup and HeaderSearch interfaces.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Lex/HeaderSearch.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/IdentifierTable.h"
17 #include "clang/Lex/HeaderMap.h"
18 #include "clang/Lex/HeaderSearchOptions.h"
19 #include "clang/Lex/LexDiagnostic.h"
20 #include "clang/Lex/Lexer.h"
21 #include "llvm/ADT/APInt.h"
22 #include "llvm/ADT/Hashing.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/Support/Capacity.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/Path.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <cstdio>
29 #if defined(LLVM_ON_UNIX)
30 #include <limits.h>
31 #endif
32 using namespace clang;
33 
34 const IdentifierInfo *
35 HeaderFileInfo::getControllingMacro(ExternalIdentifierLookup *External) {
36   if (ControllingMacro)
37     return ControllingMacro;
38 
39   if (!ControllingMacroID || !External)
40     return nullptr;
41 
42   ControllingMacro = External->GetIdentifier(ControllingMacroID);
43   return ControllingMacro;
44 }
45 
46 ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
47 
48 HeaderSearch::HeaderSearch(IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts,
49                            SourceManager &SourceMgr, DiagnosticsEngine &Diags,
50                            const LangOptions &LangOpts,
51                            const TargetInfo *Target)
52     : HSOpts(HSOpts), Diags(Diags), FileMgr(SourceMgr.getFileManager()),
53       FrameworkMap(64), ModMap(SourceMgr, Diags, LangOpts, Target, *this) {
54   AngledDirIdx = 0;
55   SystemDirIdx = 0;
56   NoCurDirSearch = false;
57 
58   ExternalLookup = nullptr;
59   ExternalSource = nullptr;
60   NumIncluded = 0;
61   NumMultiIncludeFileOptzn = 0;
62   NumFrameworkLookups = NumSubFrameworkLookups = 0;
63 
64   EnabledModules = LangOpts.Modules;
65 }
66 
67 HeaderSearch::~HeaderSearch() {
68   // Delete headermaps.
69   for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
70     delete HeaderMaps[i].second;
71 }
72 
73 void HeaderSearch::PrintStats() {
74   fprintf(stderr, "\n*** HeaderSearch Stats:\n");
75   fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
76   unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
77   for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
78     NumOnceOnlyFiles += FileInfo[i].isImport;
79     if (MaxNumIncludes < FileInfo[i].NumIncludes)
80       MaxNumIncludes = FileInfo[i].NumIncludes;
81     NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
82   }
83   fprintf(stderr, "  %d #import/#pragma once files.\n", NumOnceOnlyFiles);
84   fprintf(stderr, "  %d included exactly once.\n", NumSingleIncludedFiles);
85   fprintf(stderr, "  %d max times a file is included.\n", MaxNumIncludes);
86 
87   fprintf(stderr, "  %d #include/#include_next/#import.\n", NumIncluded);
88   fprintf(stderr, "    %d #includes skipped due to"
89           " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
90 
91   fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
92   fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
93 }
94 
95 /// CreateHeaderMap - This method returns a HeaderMap for the specified
96 /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
97 const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
98   // We expect the number of headermaps to be small, and almost always empty.
99   // If it ever grows, use of a linear search should be re-evaluated.
100   if (!HeaderMaps.empty()) {
101     for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
102       // Pointer equality comparison of FileEntries works because they are
103       // already uniqued by inode.
104       if (HeaderMaps[i].first == FE)
105         return HeaderMaps[i].second;
106   }
107 
108   if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
109     HeaderMaps.push_back(std::make_pair(FE, HM));
110     return HM;
111   }
112 
113   return nullptr;
114 }
115 
116 std::string HeaderSearch::getModuleFileName(Module *Module) {
117   const FileEntry *ModuleMap =
118       getModuleMap().getModuleMapFileForUniquing(Module);
119   return getModuleFileName(Module->Name, ModuleMap->getName());
120 }
121 
122 std::string HeaderSearch::getModuleFileName(StringRef ModuleName,
123                                             StringRef ModuleMapPath) {
124   // If we don't have a module cache path, we can't do anything.
125   if (ModuleCachePath.empty())
126     return std::string();
127 
128   SmallString<256> Result(ModuleCachePath);
129   llvm::sys::fs::make_absolute(Result);
130 
131   if (HSOpts->DisableModuleHash) {
132     llvm::sys::path::append(Result, ModuleName + ".pcm");
133   } else {
134     // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
135     // be globally unique to this particular module. To avoid false-negatives
136     // on case-insensitive filesystems, we use lower-case, which is safe because
137     // to cause a collision the modules must have the same name, which is an
138     // error if they are imported in the same translation.
139     SmallString<256> AbsModuleMapPath(ModuleMapPath);
140     llvm::sys::fs::make_absolute(AbsModuleMapPath);
141     llvm::APInt Code(64, llvm::hash_value(AbsModuleMapPath.str().lower()));
142     SmallString<128> HashStr;
143     Code.toStringUnsigned(HashStr, /*Radix*/36);
144     llvm::sys::path::append(Result, ModuleName + "-" + HashStr.str() + ".pcm");
145   }
146   return Result.str().str();
147 }
148 
149 Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
150   // Look in the module map to determine if there is a module by this name.
151   Module *Module = ModMap.findModule(ModuleName);
152   if (Module || !AllowSearch)
153     return Module;
154 
155   // Look through the various header search paths to load any available module
156   // maps, searching for a module map that describes this module.
157   for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
158     if (SearchDirs[Idx].isFramework()) {
159       // Search for or infer a module map for a framework.
160       SmallString<128> FrameworkDirName;
161       FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
162       llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework");
163       if (const DirectoryEntry *FrameworkDir
164             = FileMgr.getDirectory(FrameworkDirName)) {
165         bool IsSystem
166           = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
167         Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
168         if (Module)
169           break;
170       }
171     }
172 
173     // FIXME: Figure out how header maps and module maps will work together.
174 
175     // Only deal with normal search directories.
176     if (!SearchDirs[Idx].isNormalDir())
177       continue;
178 
179     bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
180     // Search for a module map file in this directory.
181     if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
182                           /*IsFramework*/false) == LMM_NewlyLoaded) {
183       // We just loaded a module map file; check whether the module is
184       // available now.
185       Module = ModMap.findModule(ModuleName);
186       if (Module)
187         break;
188     }
189 
190     // Search for a module map in a subdirectory with the same name as the
191     // module.
192     SmallString<128> NestedModuleMapDirName;
193     NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
194     llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
195     if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
196                           /*IsFramework*/false) == LMM_NewlyLoaded){
197       // If we just loaded a module map file, look for the module again.
198       Module = ModMap.findModule(ModuleName);
199       if (Module)
200         break;
201     }
202 
203     // If we've already performed the exhaustive search for module maps in this
204     // search directory, don't do it again.
205     if (SearchDirs[Idx].haveSearchedAllModuleMaps())
206       continue;
207 
208     // Load all module maps in the immediate subdirectories of this search
209     // directory.
210     loadSubdirectoryModuleMaps(SearchDirs[Idx]);
211 
212     // Look again for the module.
213     Module = ModMap.findModule(ModuleName);
214     if (Module)
215       break;
216   }
217 
218   return Module;
219 }
220 
221 //===----------------------------------------------------------------------===//
222 // File lookup within a DirectoryLookup scope
223 //===----------------------------------------------------------------------===//
224 
225 /// getName - Return the directory or filename corresponding to this lookup
226 /// object.
227 const char *DirectoryLookup::getName() const {
228   if (isNormalDir())
229     return getDir()->getName();
230   if (isFramework())
231     return getFrameworkDir()->getName();
232   assert(isHeaderMap() && "Unknown DirectoryLookup");
233   return getHeaderMap()->getFileName();
234 }
235 
236 static const FileEntry *
237 getFileAndSuggestModule(HeaderSearch &HS, StringRef FileName,
238                         const DirectoryEntry *Dir, bool IsSystemHeaderDir,
239                         ModuleMap::KnownHeader *SuggestedModule) {
240   // If we have a module map that might map this header, load it and
241   // check whether we'll have a suggestion for a module.
242   HS.hasModuleMap(FileName, Dir, IsSystemHeaderDir);
243   if (SuggestedModule) {
244     const FileEntry *File = HS.getFileMgr().getFile(FileName,
245                                                     /*OpenFile=*/false);
246     if (File) {
247       // If there is a module that corresponds to this header, suggest it.
248       *SuggestedModule = HS.findModuleForHeader(File);
249 
250       // FIXME: This appears to be a no-op. We loaded the module map for this
251       // directory at the start of this function.
252       if (!SuggestedModule->getModule() &&
253           HS.hasModuleMap(FileName, Dir, IsSystemHeaderDir))
254         *SuggestedModule = HS.findModuleForHeader(File);
255     }
256 
257     return File;
258   }
259 
260   return HS.getFileMgr().getFile(FileName, /*openFile=*/true);
261 }
262 
263 /// LookupFile - Lookup the specified file in this search path, returning it
264 /// if it exists or returning null if not.
265 const FileEntry *DirectoryLookup::LookupFile(
266     StringRef &Filename,
267     HeaderSearch &HS,
268     SmallVectorImpl<char> *SearchPath,
269     SmallVectorImpl<char> *RelativePath,
270     ModuleMap::KnownHeader *SuggestedModule,
271     bool &InUserSpecifiedSystemFramework,
272     bool &HasBeenMapped,
273     SmallVectorImpl<char> &MappedName) const {
274   InUserSpecifiedSystemFramework = false;
275   HasBeenMapped = false;
276 
277   SmallString<1024> TmpDir;
278   if (isNormalDir()) {
279     // Concatenate the requested file onto the directory.
280     TmpDir = getDir()->getName();
281     llvm::sys::path::append(TmpDir, Filename);
282     if (SearchPath) {
283       StringRef SearchPathRef(getDir()->getName());
284       SearchPath->clear();
285       SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
286     }
287     if (RelativePath) {
288       RelativePath->clear();
289       RelativePath->append(Filename.begin(), Filename.end());
290     }
291 
292     return getFileAndSuggestModule(HS, TmpDir.str(), getDir(),
293                                    isSystemHeaderDirectory(),
294                                    SuggestedModule);
295   }
296 
297   if (isFramework())
298     return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
299                              SuggestedModule, InUserSpecifiedSystemFramework);
300 
301   assert(isHeaderMap() && "Unknown directory lookup");
302   const HeaderMap *HM = getHeaderMap();
303   SmallString<1024> Path;
304   StringRef Dest = HM->lookupFilename(Filename, Path);
305   if (Dest.empty())
306     return nullptr;
307 
308   const FileEntry *Result;
309 
310   // Check if the headermap maps the filename to a framework include
311   // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
312   // framework include.
313   if (llvm::sys::path::is_relative(Dest)) {
314     MappedName.clear();
315     MappedName.append(Dest.begin(), Dest.end());
316     Filename = StringRef(MappedName.begin(), MappedName.size());
317     HasBeenMapped = true;
318     Result = HM->LookupFile(Filename, HS.getFileMgr());
319 
320   } else {
321     Result = HS.getFileMgr().getFile(Dest);
322   }
323 
324   if (Result) {
325     if (SearchPath) {
326       StringRef SearchPathRef(getName());
327       SearchPath->clear();
328       SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
329     }
330     if (RelativePath) {
331       RelativePath->clear();
332       RelativePath->append(Filename.begin(), Filename.end());
333     }
334   }
335   return Result;
336 }
337 
338 /// \brief Given a framework directory, find the top-most framework directory.
339 ///
340 /// \param FileMgr The file manager to use for directory lookups.
341 /// \param DirName The name of the framework directory.
342 /// \param SubmodulePath Will be populated with the submodule path from the
343 /// returned top-level module to the originally named framework.
344 static const DirectoryEntry *
345 getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
346                    SmallVectorImpl<std::string> &SubmodulePath) {
347   assert(llvm::sys::path::extension(DirName) == ".framework" &&
348          "Not a framework directory");
349 
350   // Note: as an egregious but useful hack we use the real path here, because
351   // frameworks moving between top-level frameworks to embedded frameworks tend
352   // to be symlinked, and we base the logical structure of modules on the
353   // physical layout. In particular, we need to deal with crazy includes like
354   //
355   //   #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
356   //
357   // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
358   // which one should access with, e.g.,
359   //
360   //   #include <Bar/Wibble.h>
361   //
362   // Similar issues occur when a top-level framework has moved into an
363   // embedded framework.
364   const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
365   DirName = FileMgr.getCanonicalName(TopFrameworkDir);
366   do {
367     // Get the parent directory name.
368     DirName = llvm::sys::path::parent_path(DirName);
369     if (DirName.empty())
370       break;
371 
372     // Determine whether this directory exists.
373     const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
374     if (!Dir)
375       break;
376 
377     // If this is a framework directory, then we're a subframework of this
378     // framework.
379     if (llvm::sys::path::extension(DirName) == ".framework") {
380       SubmodulePath.push_back(llvm::sys::path::stem(DirName));
381       TopFrameworkDir = Dir;
382     }
383   } while (true);
384 
385   return TopFrameworkDir;
386 }
387 
388 /// DoFrameworkLookup - Do a lookup of the specified file in the current
389 /// DirectoryLookup, which is a framework directory.
390 const FileEntry *DirectoryLookup::DoFrameworkLookup(
391     StringRef Filename,
392     HeaderSearch &HS,
393     SmallVectorImpl<char> *SearchPath,
394     SmallVectorImpl<char> *RelativePath,
395     ModuleMap::KnownHeader *SuggestedModule,
396     bool &InUserSpecifiedSystemFramework) const
397 {
398   FileManager &FileMgr = HS.getFileMgr();
399 
400   // Framework names must have a '/' in the filename.
401   size_t SlashPos = Filename.find('/');
402   if (SlashPos == StringRef::npos) return nullptr;
403 
404   // Find out if this is the home for the specified framework, by checking
405   // HeaderSearch.  Possible answers are yes/no and unknown.
406   HeaderSearch::FrameworkCacheEntry &CacheEntry =
407     HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
408 
409   // If it is known and in some other directory, fail.
410   if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
411     return nullptr;
412 
413   // Otherwise, construct the path to this framework dir.
414 
415   // FrameworkName = "/System/Library/Frameworks/"
416   SmallString<1024> FrameworkName;
417   FrameworkName += getFrameworkDir()->getName();
418   if (FrameworkName.empty() || FrameworkName.back() != '/')
419     FrameworkName.push_back('/');
420 
421   // FrameworkName = "/System/Library/Frameworks/Cocoa"
422   StringRef ModuleName(Filename.begin(), SlashPos);
423   FrameworkName += ModuleName;
424 
425   // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
426   FrameworkName += ".framework/";
427 
428   // If the cache entry was unresolved, populate it now.
429   if (!CacheEntry.Directory) {
430     HS.IncrementFrameworkLookupCount();
431 
432     // If the framework dir doesn't exist, we fail.
433     const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
434     if (!Dir) return nullptr;
435 
436     // Otherwise, if it does, remember that this is the right direntry for this
437     // framework.
438     CacheEntry.Directory = getFrameworkDir();
439 
440     // If this is a user search directory, check if the framework has been
441     // user-specified as a system framework.
442     if (getDirCharacteristic() == SrcMgr::C_User) {
443       SmallString<1024> SystemFrameworkMarker(FrameworkName);
444       SystemFrameworkMarker += ".system_framework";
445       if (llvm::sys::fs::exists(SystemFrameworkMarker.str())) {
446         CacheEntry.IsUserSpecifiedSystemFramework = true;
447       }
448     }
449   }
450 
451   // Set the 'user-specified system framework' flag.
452   InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
453 
454   if (RelativePath) {
455     RelativePath->clear();
456     RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
457   }
458 
459   // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
460   unsigned OrigSize = FrameworkName.size();
461 
462   FrameworkName += "Headers/";
463 
464   if (SearchPath) {
465     SearchPath->clear();
466     // Without trailing '/'.
467     SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
468   }
469 
470   FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
471   const FileEntry *FE = FileMgr.getFile(FrameworkName.str(),
472                                         /*openFile=*/!SuggestedModule);
473   if (!FE) {
474     // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
475     const char *Private = "Private";
476     FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
477                          Private+strlen(Private));
478     if (SearchPath)
479       SearchPath->insert(SearchPath->begin()+OrigSize, Private,
480                          Private+strlen(Private));
481 
482     FE = FileMgr.getFile(FrameworkName.str(), /*openFile=*/!SuggestedModule);
483   }
484 
485   // If we found the header and are allowed to suggest a module, do so now.
486   if (FE && SuggestedModule) {
487     // Find the framework in which this header occurs.
488     StringRef FrameworkPath = FE->getDir()->getName();
489     bool FoundFramework = false;
490     do {
491       // Determine whether this directory exists.
492       const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
493       if (!Dir)
494         break;
495 
496       // If this is a framework directory, then we're a subframework of this
497       // framework.
498       if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
499         FoundFramework = true;
500         break;
501       }
502 
503       // Get the parent directory name.
504       FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
505       if (FrameworkPath.empty())
506         break;
507     } while (true);
508 
509     if (FoundFramework) {
510       // Find the top-level framework based on this framework.
511       SmallVector<std::string, 4> SubmodulePath;
512       const DirectoryEntry *TopFrameworkDir
513         = ::getTopFrameworkDir(FileMgr, FrameworkPath, SubmodulePath);
514 
515       // Determine the name of the top-level framework.
516       StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
517 
518       // Load this framework module. If that succeeds, find the suggested module
519       // for this header, if any.
520       bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
521       if (HS.loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
522         *SuggestedModule = HS.findModuleForHeader(FE);
523       }
524     } else {
525       *SuggestedModule = HS.findModuleForHeader(FE);
526     }
527   }
528   return FE;
529 }
530 
531 void HeaderSearch::setTarget(const TargetInfo &Target) {
532   ModMap.setTarget(Target);
533 }
534 
535 
536 //===----------------------------------------------------------------------===//
537 // Header File Location.
538 //===----------------------------------------------------------------------===//
539 
540 /// \brief Return true with a diagnostic if the file that MSVC would have found
541 /// fails to match the one that Clang would have found with MSVC header search
542 /// disabled.
543 static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
544                                   const FileEntry *MSFE, const FileEntry *FE,
545                                   SourceLocation IncludeLoc) {
546   if (MSFE && FE != MSFE) {
547     Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
548     return true;
549   }
550   return false;
551 }
552 
553 static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
554   assert(!Str.empty());
555   char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
556   std::copy(Str.begin(), Str.end(), CopyStr);
557   CopyStr[Str.size()] = '\0';
558   return CopyStr;
559 }
560 
561 /// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
562 /// return null on failure.  isAngled indicates whether the file reference is
563 /// for system \#include's or not (i.e. using <> instead of ""). Includers, if
564 /// non-empty, indicates where the \#including file(s) are, in case a relative
565 /// search is needed. Microsoft mode will pass all \#including files.
566 const FileEntry *HeaderSearch::LookupFile(
567     StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
568     const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
569     ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
570     SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
571     ModuleMap::KnownHeader *SuggestedModule, bool SkipCache) {
572   if (!HSOpts->ModuleMapFiles.empty()) {
573     // Preload all explicitly specified module map files. This enables modules
574     // map files lying in a directory structure separate from the header files
575     // that they describe. These cannot be loaded lazily upon encountering a
576     // header file, as there is no other known mapping from a header file to its
577     // module map file.
578     for (llvm::SetVector<std::string>::iterator
579              I = HSOpts->ModuleMapFiles.begin(),
580              E = HSOpts->ModuleMapFiles.end();
581          I != E; ++I) {
582       const FileEntry *File = FileMgr.getFile(*I);
583       if (!File)
584         continue;
585       loadModuleMapFile(File, /*IsSystem=*/false);
586     }
587     HSOpts->ModuleMapFiles.clear();
588   }
589 
590   if (SuggestedModule)
591     *SuggestedModule = ModuleMap::KnownHeader();
592 
593   // If 'Filename' is absolute, check to see if it exists and no searching.
594   if (llvm::sys::path::is_absolute(Filename)) {
595     CurDir = nullptr;
596 
597     // If this was an #include_next "/absolute/file", fail.
598     if (FromDir) return nullptr;
599 
600     if (SearchPath)
601       SearchPath->clear();
602     if (RelativePath) {
603       RelativePath->clear();
604       RelativePath->append(Filename.begin(), Filename.end());
605     }
606     // Otherwise, just return the file.
607     return FileMgr.getFile(Filename, /*openFile=*/true);
608   }
609 
610   // This is the header that MSVC's header search would have found.
611   const FileEntry *MSFE = nullptr;
612   ModuleMap::KnownHeader MSSuggestedModule;
613 
614   // Unless disabled, check to see if the file is in the #includer's
615   // directory.  This cannot be based on CurDir, because each includer could be
616   // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
617   // include of "baz.h" should resolve to "whatever/foo/baz.h".
618   // This search is not done for <> headers.
619   if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
620     SmallString<1024> TmpDir;
621     bool First = true;
622     for (const auto &IncluderAndDir : Includers) {
623       const FileEntry *Includer = IncluderAndDir.first;
624 
625       // Concatenate the requested file onto the directory.
626       // FIXME: Portability.  Filename concatenation should be in sys::Path.
627       TmpDir = IncluderAndDir.second->getName();
628       TmpDir.push_back('/');
629       TmpDir.append(Filename.begin(), Filename.end());
630 
631       // FIXME: We don't cache the result of getFileInfo across the call to
632       // getFileAndSuggestModule, because it's a reference to an element of
633       // a container that could be reallocated across this call.
634       bool IncluderIsSystemHeader =
635           getFileInfo(Includer).DirInfo != SrcMgr::C_User;
636       if (const FileEntry *FE = getFileAndSuggestModule(
637               *this, TmpDir.str(), IncluderAndDir.second,
638               IncluderIsSystemHeader, SuggestedModule)) {
639         // Leave CurDir unset.
640         // This file is a system header or C++ unfriendly if the old file is.
641         //
642         // Note that we only use one of FromHFI/ToHFI at once, due to potential
643         // reallocation of the underlying vector potentially making the first
644         // reference binding dangling.
645         HeaderFileInfo &FromHFI = getFileInfo(Includer);
646         unsigned DirInfo = FromHFI.DirInfo;
647         bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
648         StringRef Framework = FromHFI.Framework;
649 
650         HeaderFileInfo &ToHFI = getFileInfo(FE);
651         ToHFI.DirInfo = DirInfo;
652         ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
653         ToHFI.Framework = Framework;
654 
655         if (SearchPath) {
656           StringRef SearchPathRef(IncluderAndDir.second->getName());
657           SearchPath->clear();
658           SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
659         }
660         if (RelativePath) {
661           RelativePath->clear();
662           RelativePath->append(Filename.begin(), Filename.end());
663         }
664         if (First)
665           return FE;
666 
667         // Otherwise, we found the path via MSVC header search rules.  If
668         // -Wmsvc-include is enabled, we have to keep searching to see if we
669         // would've found this header in -I or -isystem directories.
670         if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
671           return FE;
672         } else {
673           MSFE = FE;
674           if (SuggestedModule) {
675             MSSuggestedModule = *SuggestedModule;
676             *SuggestedModule = ModuleMap::KnownHeader();
677           }
678           break;
679         }
680       }
681       First = false;
682     }
683   }
684 
685   CurDir = nullptr;
686 
687   // If this is a system #include, ignore the user #include locs.
688   unsigned i = isAngled ? AngledDirIdx : 0;
689 
690   // If this is a #include_next request, start searching after the directory the
691   // file was found in.
692   if (FromDir)
693     i = FromDir-&SearchDirs[0];
694 
695   // Cache all of the lookups performed by this method.  Many headers are
696   // multiply included, and the "pragma once" optimization prevents them from
697   // being relex/pp'd, but they would still have to search through a
698   // (potentially huge) series of SearchDirs to find it.
699   LookupFileCacheInfo &CacheLookup =
700     LookupFileCache.GetOrCreateValue(Filename).getValue();
701 
702   // If the entry has been previously looked up, the first value will be
703   // non-zero.  If the value is equal to i (the start point of our search), then
704   // this is a matching hit.
705   if (!SkipCache && CacheLookup.StartIdx == i+1) {
706     // Skip querying potentially lots of directories for this lookup.
707     i = CacheLookup.HitIdx;
708     if (CacheLookup.MappedName)
709       Filename = CacheLookup.MappedName;
710   } else {
711     // Otherwise, this is the first query, or the previous query didn't match
712     // our search start.  We will fill in our found location below, so prime the
713     // start point value.
714     CacheLookup.reset(/*StartIdx=*/i+1);
715   }
716 
717   SmallString<64> MappedName;
718 
719   // Check each directory in sequence to see if it contains this file.
720   for (; i != SearchDirs.size(); ++i) {
721     bool InUserSpecifiedSystemFramework = false;
722     bool HasBeenMapped = false;
723     const FileEntry *FE =
724       SearchDirs[i].LookupFile(Filename, *this, SearchPath, RelativePath,
725                                SuggestedModule, InUserSpecifiedSystemFramework,
726                                HasBeenMapped, MappedName);
727     if (HasBeenMapped) {
728       CacheLookup.MappedName =
729           copyString(Filename, LookupFileCache.getAllocator());
730     }
731     if (!FE) continue;
732 
733     CurDir = &SearchDirs[i];
734 
735     // This file is a system header or C++ unfriendly if the dir is.
736     HeaderFileInfo &HFI = getFileInfo(FE);
737     HFI.DirInfo = CurDir->getDirCharacteristic();
738 
739     // If the directory characteristic is User but this framework was
740     // user-specified to be treated as a system framework, promote the
741     // characteristic.
742     if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
743       HFI.DirInfo = SrcMgr::C_System;
744 
745     // If the filename matches a known system header prefix, override
746     // whether the file is a system header.
747     for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
748       if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
749         HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
750                                                        : SrcMgr::C_User;
751         break;
752       }
753     }
754 
755     // If this file is found in a header map and uses the framework style of
756     // includes, then this header is part of a framework we're building.
757     if (CurDir->isIndexHeaderMap()) {
758       size_t SlashPos = Filename.find('/');
759       if (SlashPos != StringRef::npos) {
760         HFI.IndexHeaderMapHeader = 1;
761         HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
762                                                          SlashPos));
763       }
764     }
765 
766     if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
767       if (SuggestedModule)
768         *SuggestedModule = MSSuggestedModule;
769       return MSFE;
770     }
771 
772     // Remember this location for the next lookup we do.
773     CacheLookup.HitIdx = i;
774     return FE;
775   }
776 
777   // If we are including a file with a quoted include "foo.h" from inside
778   // a header in a framework that is currently being built, and we couldn't
779   // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
780   // "Foo" is the name of the framework in which the including header was found.
781   if (!Includers.empty() && !isAngled &&
782       Filename.find('/') == StringRef::npos) {
783     HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
784     if (IncludingHFI.IndexHeaderMapHeader) {
785       SmallString<128> ScratchFilename;
786       ScratchFilename += IncludingHFI.Framework;
787       ScratchFilename += '/';
788       ScratchFilename += Filename;
789 
790       const FileEntry *FE = LookupFile(
791           ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, CurDir,
792           Includers.front(), SearchPath, RelativePath, SuggestedModule);
793 
794       if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
795         if (SuggestedModule)
796           *SuggestedModule = MSSuggestedModule;
797         return MSFE;
798       }
799 
800       LookupFileCacheInfo &CacheLookup
801         = LookupFileCache.GetOrCreateValue(Filename).getValue();
802       CacheLookup.HitIdx
803         = LookupFileCache.GetOrCreateValue(ScratchFilename).getValue().HitIdx;
804       // FIXME: SuggestedModule.
805       return FE;
806     }
807   }
808 
809   if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {
810     if (SuggestedModule)
811       *SuggestedModule = MSSuggestedModule;
812     return MSFE;
813   }
814 
815   // Otherwise, didn't find it. Remember we didn't find this.
816   CacheLookup.HitIdx = SearchDirs.size();
817   return nullptr;
818 }
819 
820 /// LookupSubframeworkHeader - Look up a subframework for the specified
821 /// \#include file.  For example, if \#include'ing <HIToolbox/HIToolbox.h> from
822 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
823 /// is a subframework within Carbon.framework.  If so, return the FileEntry
824 /// for the designated file, otherwise return null.
825 const FileEntry *HeaderSearch::
826 LookupSubframeworkHeader(StringRef Filename,
827                          const FileEntry *ContextFileEnt,
828                          SmallVectorImpl<char> *SearchPath,
829                          SmallVectorImpl<char> *RelativePath,
830                          ModuleMap::KnownHeader *SuggestedModule) {
831   assert(ContextFileEnt && "No context file?");
832 
833   // Framework names must have a '/' in the filename.  Find it.
834   // FIXME: Should we permit '\' on Windows?
835   size_t SlashPos = Filename.find('/');
836   if (SlashPos == StringRef::npos) return nullptr;
837 
838   // Look up the base framework name of the ContextFileEnt.
839   const char *ContextName = ContextFileEnt->getName();
840 
841   // If the context info wasn't a framework, couldn't be a subframework.
842   const unsigned DotFrameworkLen = 10;
843   const char *FrameworkPos = strstr(ContextName, ".framework");
844   if (FrameworkPos == nullptr ||
845       (FrameworkPos[DotFrameworkLen] != '/' &&
846        FrameworkPos[DotFrameworkLen] != '\\'))
847     return nullptr;
848 
849   SmallString<1024> FrameworkName(ContextName, FrameworkPos+DotFrameworkLen+1);
850 
851   // Append Frameworks/HIToolbox.framework/
852   FrameworkName += "Frameworks/";
853   FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
854   FrameworkName += ".framework/";
855 
856   llvm::StringMapEntry<FrameworkCacheEntry> &CacheLookup =
857     FrameworkMap.GetOrCreateValue(Filename.substr(0, SlashPos));
858 
859   // Some other location?
860   if (CacheLookup.getValue().Directory &&
861       CacheLookup.getKeyLength() == FrameworkName.size() &&
862       memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
863              CacheLookup.getKeyLength()) != 0)
864     return nullptr;
865 
866   // Cache subframework.
867   if (!CacheLookup.getValue().Directory) {
868     ++NumSubFrameworkLookups;
869 
870     // If the framework dir doesn't exist, we fail.
871     const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
872     if (!Dir) return nullptr;
873 
874     // Otherwise, if it does, remember that this is the right direntry for this
875     // framework.
876     CacheLookup.getValue().Directory = Dir;
877   }
878 
879   const FileEntry *FE = nullptr;
880 
881   if (RelativePath) {
882     RelativePath->clear();
883     RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
884   }
885 
886   // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
887   SmallString<1024> HeadersFilename(FrameworkName);
888   HeadersFilename += "Headers/";
889   if (SearchPath) {
890     SearchPath->clear();
891     // Without trailing '/'.
892     SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
893   }
894 
895   HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
896   if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true))) {
897 
898     // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
899     HeadersFilename = FrameworkName;
900     HeadersFilename += "PrivateHeaders/";
901     if (SearchPath) {
902       SearchPath->clear();
903       // Without trailing '/'.
904       SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
905     }
906 
907     HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
908     if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true)))
909       return nullptr;
910   }
911 
912   // This file is a system header or C++ unfriendly if the old file is.
913   //
914   // Note that the temporary 'DirInfo' is required here, as either call to
915   // getFileInfo could resize the vector and we don't want to rely on order
916   // of evaluation.
917   unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
918   getFileInfo(FE).DirInfo = DirInfo;
919 
920   // If we're supposed to suggest a module, look for one now.
921   if (SuggestedModule) {
922     // Find the top-level framework based on this framework.
923     FrameworkName.pop_back(); // remove the trailing '/'
924     SmallVector<std::string, 4> SubmodulePath;
925     const DirectoryEntry *TopFrameworkDir
926       = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
927 
928     // Determine the name of the top-level framework.
929     StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
930 
931     // Load this framework module. If that succeeds, find the suggested module
932     // for this header, if any.
933     bool IsSystem = false;
934     if (loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
935       *SuggestedModule = findModuleForHeader(FE);
936     }
937   }
938 
939   return FE;
940 }
941 
942 //===----------------------------------------------------------------------===//
943 // File Info Management.
944 //===----------------------------------------------------------------------===//
945 
946 /// \brief Merge the header file info provided by \p OtherHFI into the current
947 /// header file info (\p HFI)
948 static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
949                                 const HeaderFileInfo &OtherHFI) {
950   HFI.isImport |= OtherHFI.isImport;
951   HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
952   HFI.isModuleHeader |= OtherHFI.isModuleHeader;
953   HFI.NumIncludes += OtherHFI.NumIncludes;
954 
955   if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
956     HFI.ControllingMacro = OtherHFI.ControllingMacro;
957     HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
958   }
959 
960   if (OtherHFI.External) {
961     HFI.DirInfo = OtherHFI.DirInfo;
962     HFI.External = OtherHFI.External;
963     HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
964   }
965 
966   if (HFI.Framework.empty())
967     HFI.Framework = OtherHFI.Framework;
968 
969   HFI.Resolved = true;
970 }
971 
972 /// getFileInfo - Return the HeaderFileInfo structure for the specified
973 /// FileEntry.
974 HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
975   if (FE->getUID() >= FileInfo.size())
976     FileInfo.resize(FE->getUID()+1);
977 
978   HeaderFileInfo &HFI = FileInfo[FE->getUID()];
979   if (ExternalSource && !HFI.Resolved)
980     mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(FE));
981   HFI.IsValid = 1;
982   return HFI;
983 }
984 
985 bool HeaderSearch::tryGetFileInfo(const FileEntry *FE, HeaderFileInfo &Result) const {
986   if (FE->getUID() >= FileInfo.size())
987     return false;
988   const HeaderFileInfo &HFI = FileInfo[FE->getUID()];
989   if (HFI.IsValid) {
990     Result = HFI;
991     return true;
992   }
993   return false;
994 }
995 
996 bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
997   // Check if we've ever seen this file as a header.
998   if (File->getUID() >= FileInfo.size())
999     return false;
1000 
1001   // Resolve header file info from the external source, if needed.
1002   HeaderFileInfo &HFI = FileInfo[File->getUID()];
1003   if (ExternalSource && !HFI.Resolved)
1004     mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(File));
1005 
1006   return HFI.isPragmaOnce || HFI.isImport ||
1007       HFI.ControllingMacro || HFI.ControllingMacroID;
1008 }
1009 
1010 void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
1011                                         ModuleMap::ModuleHeaderRole Role,
1012                                         bool isCompilingModuleHeader) {
1013   if (FE->getUID() >= FileInfo.size())
1014     FileInfo.resize(FE->getUID()+1);
1015 
1016   HeaderFileInfo &HFI = FileInfo[FE->getUID()];
1017   HFI.isModuleHeader = true;
1018   HFI.isCompilingModuleHeader = isCompilingModuleHeader;
1019   HFI.setHeaderRole(Role);
1020 }
1021 
1022 bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
1023   ++NumIncluded; // Count # of attempted #includes.
1024 
1025   // Get information about this file.
1026   HeaderFileInfo &FileInfo = getFileInfo(File);
1027 
1028   // If this is a #import directive, check that we have not already imported
1029   // this header.
1030   if (isImport) {
1031     // If this has already been imported, don't import it again.
1032     FileInfo.isImport = true;
1033 
1034     // Has this already been #import'ed or #include'd?
1035     if (FileInfo.NumIncludes) return false;
1036   } else {
1037     // Otherwise, if this is a #include of a file that was previously #import'd
1038     // or if this is the second #include of a #pragma once file, ignore it.
1039     if (FileInfo.isImport)
1040       return false;
1041   }
1042 
1043   // Next, check to see if the file is wrapped with #ifndef guards.  If so, and
1044   // if the macro that guards it is defined, we know the #include has no effect.
1045   if (const IdentifierInfo *ControllingMacro
1046       = FileInfo.getControllingMacro(ExternalLookup))
1047     if (ControllingMacro->hasMacroDefinition()) {
1048       ++NumMultiIncludeFileOptzn;
1049       return false;
1050     }
1051 
1052   // Increment the number of times this file has been included.
1053   ++FileInfo.NumIncludes;
1054 
1055   return true;
1056 }
1057 
1058 size_t HeaderSearch::getTotalMemory() const {
1059   return SearchDirs.capacity()
1060     + llvm::capacity_in_bytes(FileInfo)
1061     + llvm::capacity_in_bytes(HeaderMaps)
1062     + LookupFileCache.getAllocator().getTotalMemory()
1063     + FrameworkMap.getAllocator().getTotalMemory();
1064 }
1065 
1066 StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
1067   return FrameworkNames.GetOrCreateValue(Framework).getKey();
1068 }
1069 
1070 bool HeaderSearch::hasModuleMap(StringRef FileName,
1071                                 const DirectoryEntry *Root,
1072                                 bool IsSystem) {
1073   if (!enabledModules())
1074     return false;
1075 
1076   SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
1077 
1078   StringRef DirName = FileName;
1079   do {
1080     // Get the parent directory name.
1081     DirName = llvm::sys::path::parent_path(DirName);
1082     if (DirName.empty())
1083       return false;
1084 
1085     // Determine whether this directory exists.
1086     const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
1087     if (!Dir)
1088       return false;
1089 
1090     // Try to load the module map file in this directory.
1091     switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/false)) {
1092     case LMM_NewlyLoaded:
1093     case LMM_AlreadyLoaded:
1094       // Success. All of the directories we stepped through inherit this module
1095       // map file.
1096       for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1097         DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1098       return true;
1099 
1100     case LMM_NoDirectory:
1101     case LMM_InvalidModuleMap:
1102       break;
1103     }
1104 
1105     // If we hit the top of our search, we're done.
1106     if (Dir == Root)
1107       return false;
1108 
1109     // Keep track of all of the directories we checked, so we can mark them as
1110     // having module maps if we eventually do find a module map.
1111     FixUpDirectories.push_back(Dir);
1112   } while (true);
1113 }
1114 
1115 ModuleMap::KnownHeader
1116 HeaderSearch::findModuleForHeader(const FileEntry *File) const {
1117   if (ExternalSource) {
1118     // Make sure the external source has handled header info about this file,
1119     // which includes whether the file is part of a module.
1120     (void)getFileInfo(File);
1121   }
1122   return ModMap.findModuleForHeader(File);
1123 }
1124 
1125 static const FileEntry *getPrivateModuleMap(StringRef ModuleMapPath,
1126                                             const DirectoryEntry *Directory,
1127                                             FileManager &FileMgr) {
1128   StringRef Filename = llvm::sys::path::filename(ModuleMapPath);
1129   SmallString<128>  PrivateFilename(Directory->getName());
1130   if (Filename == "module.map")
1131     llvm::sys::path::append(PrivateFilename, "module_private.map");
1132   else if (Filename == "module.modulemap")
1133     llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1134   else
1135     return nullptr;
1136   return FileMgr.getFile(PrivateFilename);
1137 }
1138 
1139 bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem) {
1140   switch (loadModuleMapFileImpl(File, IsSystem)) {
1141   case LMM_AlreadyLoaded:
1142   case LMM_NewlyLoaded:
1143     return false;
1144   case LMM_NoDirectory:
1145   case LMM_InvalidModuleMap:
1146     return true;
1147   }
1148   llvm_unreachable("Unknown load module map result");
1149 }
1150 
1151 HeaderSearch::LoadModuleMapResult
1152 HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem) {
1153   assert(File && "expected FileEntry");
1154 
1155   const DirectoryEntry *Dir = File->getDir();
1156   auto KnownDir = DirectoryHasModuleMap.find(Dir);
1157   if (KnownDir != DirectoryHasModuleMap.end())
1158     return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1159 
1160   if (ModMap.parseModuleMapFile(File, IsSystem)) {
1161     DirectoryHasModuleMap[Dir] = false;
1162     return LMM_InvalidModuleMap;
1163   }
1164 
1165   // Try to load a corresponding private module map.
1166   if (const FileEntry *PMMFile =
1167         getPrivateModuleMap(File->getName(), Dir, FileMgr)) {
1168     if (ModMap.parseModuleMapFile(PMMFile, IsSystem)) {
1169       DirectoryHasModuleMap[Dir] = false;
1170       return LMM_InvalidModuleMap;
1171     }
1172   }
1173 
1174   // This directory has a module map.
1175   DirectoryHasModuleMap[Dir] = true;
1176   return LMM_NewlyLoaded;
1177 }
1178 
1179 const FileEntry *
1180 HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
1181   // For frameworks, the preferred spelling is Modules/module.modulemap, but
1182   // module.map at the framework root is also accepted.
1183   SmallString<128> ModuleMapFileName(Dir->getName());
1184   if (IsFramework)
1185     llvm::sys::path::append(ModuleMapFileName, "Modules");
1186   llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1187   if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName))
1188     return F;
1189 
1190   // Continue to allow module.map
1191   ModuleMapFileName = Dir->getName();
1192   llvm::sys::path::append(ModuleMapFileName, "module.map");
1193   return FileMgr.getFile(ModuleMapFileName);
1194 }
1195 
1196 Module *HeaderSearch::loadFrameworkModule(StringRef Name,
1197                                           const DirectoryEntry *Dir,
1198                                           bool IsSystem) {
1199   if (Module *Module = ModMap.findModule(Name))
1200     return Module;
1201 
1202   // Try to load a module map file.
1203   switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
1204   case LMM_InvalidModuleMap:
1205     break;
1206 
1207   case LMM_AlreadyLoaded:
1208   case LMM_NoDirectory:
1209     return nullptr;
1210 
1211   case LMM_NewlyLoaded:
1212     return ModMap.findModule(Name);
1213   }
1214 
1215 
1216   // Try to infer a module map from the framework directory.
1217   return ModMap.inferFrameworkModule(Name, Dir, IsSystem, /*Parent=*/nullptr);
1218 }
1219 
1220 
1221 HeaderSearch::LoadModuleMapResult
1222 HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1223                                 bool IsFramework) {
1224   if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
1225     return loadModuleMapFile(Dir, IsSystem, IsFramework);
1226 
1227   return LMM_NoDirectory;
1228 }
1229 
1230 HeaderSearch::LoadModuleMapResult
1231 HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1232                                 bool IsFramework) {
1233   auto KnownDir = DirectoryHasModuleMap.find(Dir);
1234   if (KnownDir != DirectoryHasModuleMap.end())
1235     return KnownDir->second? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1236 
1237   if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
1238     LoadModuleMapResult Result = loadModuleMapFileImpl(ModuleMapFile, IsSystem);
1239     // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1240     // E.g. Foo.framework/Modules/module.modulemap
1241     //      ^Dir                  ^ModuleMapFile
1242     if (Result == LMM_NewlyLoaded)
1243       DirectoryHasModuleMap[Dir] = true;
1244     return Result;
1245   }
1246   return LMM_InvalidModuleMap;
1247 }
1248 
1249 void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
1250   Modules.clear();
1251 
1252   // Load module maps for each of the header search directories.
1253   for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1254     bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
1255     if (SearchDirs[Idx].isFramework()) {
1256       std::error_code EC;
1257       SmallString<128> DirNative;
1258       llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1259                               DirNative);
1260 
1261       // Search each of the ".framework" directories to load them as modules.
1262       for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1263            Dir != DirEnd && !EC; Dir.increment(EC)) {
1264         if (llvm::sys::path::extension(Dir->path()) != ".framework")
1265           continue;
1266 
1267         const DirectoryEntry *FrameworkDir = FileMgr.getDirectory(Dir->path());
1268         if (!FrameworkDir)
1269           continue;
1270 
1271         // Load this framework module.
1272         loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir,
1273                             IsSystem);
1274       }
1275       continue;
1276     }
1277 
1278     // FIXME: Deal with header maps.
1279     if (SearchDirs[Idx].isHeaderMap())
1280       continue;
1281 
1282     // Try to load a module map file for the search directory.
1283     loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem, /*IsFramework*/false);
1284 
1285     // Try to load module map files for immediate subdirectories of this search
1286     // directory.
1287     loadSubdirectoryModuleMaps(SearchDirs[Idx]);
1288   }
1289 
1290   // Populate the list of modules.
1291   for (ModuleMap::module_iterator M = ModMap.module_begin(),
1292                                MEnd = ModMap.module_end();
1293        M != MEnd; ++M) {
1294     Modules.push_back(M->getValue());
1295   }
1296 }
1297 
1298 void HeaderSearch::loadTopLevelSystemModules() {
1299   // Load module maps for each of the header search directories.
1300   for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1301     // We only care about normal header directories.
1302     if (!SearchDirs[Idx].isNormalDir()) {
1303       continue;
1304     }
1305 
1306     // Try to load a module map file for the search directory.
1307     loadModuleMapFile(SearchDirs[Idx].getDir(),
1308                       SearchDirs[Idx].isSystemHeaderDirectory(),
1309                       SearchDirs[Idx].isFramework());
1310   }
1311 }
1312 
1313 void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
1314   if (SearchDir.haveSearchedAllModuleMaps())
1315     return;
1316 
1317   std::error_code EC;
1318   SmallString<128> DirNative;
1319   llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative);
1320   for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1321        Dir != DirEnd && !EC; Dir.increment(EC)) {
1322     loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(),
1323                       SearchDir.isFramework());
1324   }
1325 
1326   SearchDir.setSearchedAllModuleMaps(true);
1327 }
1328