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