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