xref: /llvm-project/clang/lib/Lex/ModuleMap.cpp (revision 7cc8fa2dd2d8167d427cadb4fc6f4254b53a8359)
1 //===- ModuleMap.cpp - Describe the layout of modules ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the ModuleMap implementation, which describes the layout
10 // of a module as it relates to headers.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Lex/ModuleMap.h"
15 #include "clang/Basic/CharInfo.h"
16 #include "clang/Basic/Diagnostic.h"
17 #include "clang/Basic/FileManager.h"
18 #include "clang/Basic/LLVM.h"
19 #include "clang/Basic/LangOptions.h"
20 #include "clang/Basic/Module.h"
21 #include "clang/Basic/SourceLocation.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/Lex/HeaderSearch.h"
25 #include "clang/Lex/HeaderSearchOptions.h"
26 #include "clang/Lex/LexDiagnostic.h"
27 #include "clang/Lex/Lexer.h"
28 #include "clang/Lex/LiteralSupport.h"
29 #include "clang/Lex/Token.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/None.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include "llvm/ADT/StringMap.h"
37 #include "llvm/ADT/StringRef.h"
38 #include "llvm/ADT/StringSwitch.h"
39 #include "llvm/Support/Allocator.h"
40 #include "llvm/Support/Compiler.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/Path.h"
44 #include "llvm/Support/VirtualFileSystem.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include <algorithm>
47 #include <cassert>
48 #include <cstdint>
49 #include <cstring>
50 #include <string>
51 #include <system_error>
52 #include <utility>
53 
54 using namespace clang;
55 
56 void ModuleMapCallbacks::anchor() {}
57 
58 void ModuleMap::resolveLinkAsDependencies(Module *Mod) {
59   auto PendingLinkAs = PendingLinkAsModule.find(Mod->Name);
60   if (PendingLinkAs != PendingLinkAsModule.end()) {
61     for (auto &Name : PendingLinkAs->second) {
62       auto *M = findModule(Name.getKey());
63       if (M)
64         M->UseExportAsModuleLinkName = true;
65     }
66   }
67 }
68 
69 void ModuleMap::addLinkAsDependency(Module *Mod) {
70   if (findModule(Mod->ExportAsModule))
71     Mod->UseExportAsModuleLinkName = true;
72   else
73     PendingLinkAsModule[Mod->ExportAsModule].insert(Mod->Name);
74 }
75 
76 Module::HeaderKind ModuleMap::headerRoleToKind(ModuleHeaderRole Role) {
77   switch ((int)Role) {
78   default: llvm_unreachable("unknown header role");
79   case NormalHeader:
80     return Module::HK_Normal;
81   case PrivateHeader:
82     return Module::HK_Private;
83   case TextualHeader:
84     return Module::HK_Textual;
85   case PrivateHeader | TextualHeader:
86     return Module::HK_PrivateTextual;
87   }
88 }
89 
90 ModuleMap::ModuleHeaderRole
91 ModuleMap::headerKindToRole(Module::HeaderKind Kind) {
92   switch ((int)Kind) {
93   case Module::HK_Normal:
94     return NormalHeader;
95   case Module::HK_Private:
96     return PrivateHeader;
97   case Module::HK_Textual:
98     return TextualHeader;
99   case Module::HK_PrivateTextual:
100     return ModuleHeaderRole(PrivateHeader | TextualHeader);
101   case Module::HK_Excluded:
102     llvm_unreachable("unexpected header kind");
103   }
104   llvm_unreachable("unknown header kind");
105 }
106 
107 Module::ExportDecl
108 ModuleMap::resolveExport(Module *Mod,
109                          const Module::UnresolvedExportDecl &Unresolved,
110                          bool Complain) const {
111   // We may have just a wildcard.
112   if (Unresolved.Id.empty()) {
113     assert(Unresolved.Wildcard && "Invalid unresolved export");
114     return Module::ExportDecl(nullptr, true);
115   }
116 
117   // Resolve the module-id.
118   Module *Context = resolveModuleId(Unresolved.Id, Mod, Complain);
119   if (!Context)
120     return {};
121 
122   return Module::ExportDecl(Context, Unresolved.Wildcard);
123 }
124 
125 Module *ModuleMap::resolveModuleId(const ModuleId &Id, Module *Mod,
126                                    bool Complain) const {
127   // Find the starting module.
128   Module *Context = lookupModuleUnqualified(Id[0].first, Mod);
129   if (!Context) {
130     if (Complain)
131       Diags.Report(Id[0].second, diag::err_mmap_missing_module_unqualified)
132       << Id[0].first << Mod->getFullModuleName();
133 
134     return nullptr;
135   }
136 
137   // Dig into the module path.
138   for (unsigned I = 1, N = Id.size(); I != N; ++I) {
139     Module *Sub = lookupModuleQualified(Id[I].first, Context);
140     if (!Sub) {
141       if (Complain)
142         Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
143         << Id[I].first << Context->getFullModuleName()
144         << SourceRange(Id[0].second, Id[I-1].second);
145 
146       return nullptr;
147     }
148 
149     Context = Sub;
150   }
151 
152   return Context;
153 }
154 
155 /// Append to \p Paths the set of paths needed to get to the
156 /// subframework in which the given module lives.
157 static void appendSubframeworkPaths(Module *Mod,
158                                     SmallVectorImpl<char> &Path) {
159   // Collect the framework names from the given module to the top-level module.
160   SmallVector<StringRef, 2> Paths;
161   for (; Mod; Mod = Mod->Parent) {
162     if (Mod->IsFramework)
163       Paths.push_back(Mod->Name);
164   }
165 
166   if (Paths.empty())
167     return;
168 
169   // Add Frameworks/Name.framework for each subframework.
170   for (unsigned I = Paths.size() - 1; I != 0; --I)
171     llvm::sys::path::append(Path, "Frameworks", Paths[I-1] + ".framework");
172 }
173 
174 Optional<FileEntryRef> ModuleMap::findHeader(
175     Module *M, const Module::UnresolvedHeaderDirective &Header,
176     SmallVectorImpl<char> &RelativePathName, bool &NeedsFramework) {
177   // Search for the header file within the module's home directory.
178   auto *Directory = M->Directory;
179   SmallString<128> FullPathName(Directory->getName());
180 
181   auto GetFile = [&](StringRef Filename) -> Optional<FileEntryRef> {
182     auto File =
183         expectedToOptional(SourceMgr.getFileManager().getFileRef(Filename));
184     if (!File || (Header.Size && File->getSize() != *Header.Size) ||
185         (Header.ModTime && File->getModificationTime() != *Header.ModTime))
186       return None;
187     return *File;
188   };
189 
190   auto GetFrameworkFile = [&]() -> Optional<FileEntryRef> {
191     unsigned FullPathLength = FullPathName.size();
192     appendSubframeworkPaths(M, RelativePathName);
193     unsigned RelativePathLength = RelativePathName.size();
194 
195     // Check whether this file is in the public headers.
196     llvm::sys::path::append(RelativePathName, "Headers", Header.FileName);
197     llvm::sys::path::append(FullPathName, RelativePathName);
198     if (auto File = GetFile(FullPathName))
199       return File;
200 
201     // Check whether this file is in the private headers.
202     // Ideally, private modules in the form 'FrameworkName.Private' should
203     // be defined as 'module FrameworkName.Private', and not as
204     // 'framework module FrameworkName.Private', since a 'Private.Framework'
205     // does not usually exist. However, since both are currently widely used
206     // for private modules, make sure we find the right path in both cases.
207     if (M->IsFramework && M->Name == "Private")
208       RelativePathName.clear();
209     else
210       RelativePathName.resize(RelativePathLength);
211     FullPathName.resize(FullPathLength);
212     llvm::sys::path::append(RelativePathName, "PrivateHeaders",
213                             Header.FileName);
214     llvm::sys::path::append(FullPathName, RelativePathName);
215     return GetFile(FullPathName);
216   };
217 
218   if (llvm::sys::path::is_absolute(Header.FileName)) {
219     RelativePathName.clear();
220     RelativePathName.append(Header.FileName.begin(), Header.FileName.end());
221     return GetFile(Header.FileName);
222   }
223 
224   if (M->isPartOfFramework())
225     return GetFrameworkFile();
226 
227   // Lookup for normal headers.
228   llvm::sys::path::append(RelativePathName, Header.FileName);
229   llvm::sys::path::append(FullPathName, RelativePathName);
230   auto NormalHdrFile = GetFile(FullPathName);
231 
232   if (!NormalHdrFile && Directory->getName().endswith(".framework")) {
233     // The lack of 'framework' keyword in a module declaration it's a simple
234     // mistake we can diagnose when the header exists within the proper
235     // framework style path.
236     FullPathName.assign(Directory->getName());
237     RelativePathName.clear();
238     if (GetFrameworkFile()) {
239       Diags.Report(Header.FileNameLoc,
240                    diag::warn_mmap_incomplete_framework_module_declaration)
241           << Header.FileName << M->getFullModuleName();
242       NeedsFramework = true;
243     }
244     return None;
245   }
246 
247   return NormalHdrFile;
248 }
249 
250 void ModuleMap::resolveHeader(Module *Mod,
251                               const Module::UnresolvedHeaderDirective &Header,
252                               bool &NeedsFramework) {
253   SmallString<128> RelativePathName;
254   if (Optional<FileEntryRef> File =
255           findHeader(Mod, Header, RelativePathName, NeedsFramework)) {
256     if (Header.IsUmbrella) {
257       const DirectoryEntry *UmbrellaDir = &File->getDir().getDirEntry();
258       if (Module *UmbrellaMod = UmbrellaDirs[UmbrellaDir])
259         Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash)
260           << UmbrellaMod->getFullModuleName();
261       else
262         // Record this umbrella header.
263         setUmbrellaHeader(Mod, *File, Header.FileName, RelativePathName.str());
264     } else {
265       Module::Header H = {Header.FileName, std::string(RelativePathName.str()),
266                           *File};
267       if (Header.Kind == Module::HK_Excluded)
268         excludeHeader(Mod, H);
269       else
270         addHeader(Mod, H, headerKindToRole(Header.Kind));
271     }
272   } else if (Header.HasBuiltinHeader && !Header.Size && !Header.ModTime) {
273     // There's a builtin header but no corresponding on-disk header. Assume
274     // this was supposed to modularize the builtin header alone.
275   } else if (Header.Kind == Module::HK_Excluded) {
276     // Ignore missing excluded header files. They're optional anyway.
277   } else {
278     // If we find a module that has a missing header, we mark this module as
279     // unavailable and store the header directive for displaying diagnostics.
280     Mod->MissingHeaders.push_back(Header);
281     // A missing header with stat information doesn't make the module
282     // unavailable; this keeps our behavior consistent as headers are lazily
283     // resolved. (Such a module still can't be built though, except from
284     // preprocessed source.)
285     if (!Header.Size && !Header.ModTime)
286       Mod->markUnavailable(/*Unimportable=*/false);
287   }
288 }
289 
290 bool ModuleMap::resolveAsBuiltinHeader(
291     Module *Mod, const Module::UnresolvedHeaderDirective &Header) {
292   if (Header.Kind == Module::HK_Excluded ||
293       llvm::sys::path::is_absolute(Header.FileName) ||
294       Mod->isPartOfFramework() || !Mod->IsSystem || Header.IsUmbrella ||
295       !BuiltinIncludeDir || BuiltinIncludeDir == Mod->Directory ||
296       !isBuiltinHeader(Header.FileName))
297     return false;
298 
299   // This is a system module with a top-level header. This header
300   // may have a counterpart (or replacement) in the set of headers
301   // supplied by Clang. Find that builtin header.
302   SmallString<128> Path;
303   llvm::sys::path::append(Path, BuiltinIncludeDir->getName(), Header.FileName);
304   auto File = SourceMgr.getFileManager().getFile(Path);
305   if (!File)
306     return false;
307 
308   auto Role = headerKindToRole(Header.Kind);
309   Module::Header H = {Header.FileName, std::string(Path.str()), *File};
310   addHeader(Mod, H, Role);
311   return true;
312 }
313 
314 ModuleMap::ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags,
315                      const LangOptions &LangOpts, const TargetInfo *Target,
316                      HeaderSearch &HeaderInfo)
317     : SourceMgr(SourceMgr), Diags(Diags), LangOpts(LangOpts), Target(Target),
318       HeaderInfo(HeaderInfo) {
319   MMapLangOpts.LineComment = true;
320 }
321 
322 ModuleMap::~ModuleMap() {
323   for (auto &M : Modules)
324     delete M.getValue();
325   for (auto *M : ShadowModules)
326     delete M;
327 }
328 
329 void ModuleMap::setTarget(const TargetInfo &Target) {
330   assert((!this->Target || this->Target == &Target) &&
331          "Improper target override");
332   this->Target = &Target;
333 }
334 
335 /// "Sanitize" a filename so that it can be used as an identifier.
336 static StringRef sanitizeFilenameAsIdentifier(StringRef Name,
337                                               SmallVectorImpl<char> &Buffer) {
338   if (Name.empty())
339     return Name;
340 
341   if (!isValidAsciiIdentifier(Name)) {
342     // If we don't already have something with the form of an identifier,
343     // create a buffer with the sanitized name.
344     Buffer.clear();
345     if (isDigit(Name[0]))
346       Buffer.push_back('_');
347     Buffer.reserve(Buffer.size() + Name.size());
348     for (unsigned I = 0, N = Name.size(); I != N; ++I) {
349       if (isAsciiIdentifierContinue(Name[I]))
350         Buffer.push_back(Name[I]);
351       else
352         Buffer.push_back('_');
353     }
354 
355     Name = StringRef(Buffer.data(), Buffer.size());
356   }
357 
358   while (llvm::StringSwitch<bool>(Name)
359 #define KEYWORD(Keyword,Conditions) .Case(#Keyword, true)
360 #define ALIAS(Keyword, AliasOf, Conditions) .Case(Keyword, true)
361 #include "clang/Basic/TokenKinds.def"
362            .Default(false)) {
363     if (Name.data() != Buffer.data())
364       Buffer.append(Name.begin(), Name.end());
365     Buffer.push_back('_');
366     Name = StringRef(Buffer.data(), Buffer.size());
367   }
368 
369   return Name;
370 }
371 
372 /// Determine whether the given file name is the name of a builtin
373 /// header, supplied by Clang to replace, override, or augment existing system
374 /// headers.
375 bool ModuleMap::isBuiltinHeader(StringRef FileName) {
376   return llvm::StringSwitch<bool>(FileName)
377            .Case("float.h", true)
378            .Case("iso646.h", true)
379            .Case("limits.h", true)
380            .Case("stdalign.h", true)
381            .Case("stdarg.h", true)
382            .Case("stdatomic.h", true)
383            .Case("stdbool.h", true)
384            .Case("stddef.h", true)
385            .Case("stdint.h", true)
386            .Case("tgmath.h", true)
387            .Case("unwind.h", true)
388            .Default(false);
389 }
390 
391 bool ModuleMap::isBuiltinHeader(const FileEntry *File) {
392   return File->getDir() == BuiltinIncludeDir &&
393          ModuleMap::isBuiltinHeader(llvm::sys::path::filename(File->getName()));
394 }
395 
396 ModuleMap::HeadersMap::iterator
397 ModuleMap::findKnownHeader(const FileEntry *File) {
398   resolveHeaderDirectives(File);
399   HeadersMap::iterator Known = Headers.find(File);
400   if (HeaderInfo.getHeaderSearchOpts().ImplicitModuleMaps &&
401       Known == Headers.end() && ModuleMap::isBuiltinHeader(File)) {
402     HeaderInfo.loadTopLevelSystemModules();
403     return Headers.find(File);
404   }
405   return Known;
406 }
407 
408 ModuleMap::KnownHeader
409 ModuleMap::findHeaderInUmbrellaDirs(const FileEntry *File,
410                     SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs) {
411   if (UmbrellaDirs.empty())
412     return {};
413 
414   const DirectoryEntry *Dir = File->getDir();
415   assert(Dir && "file in no directory");
416 
417   // Note: as an egregious but useful hack we use the real path here, because
418   // frameworks moving from top-level frameworks to embedded frameworks tend
419   // to be symlinked from the top-level location to the embedded location,
420   // and we need to resolve lookups as if we had found the embedded location.
421   StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir);
422 
423   // Keep walking up the directory hierarchy, looking for a directory with
424   // an umbrella header.
425   do {
426     auto KnownDir = UmbrellaDirs.find(Dir);
427     if (KnownDir != UmbrellaDirs.end())
428       return KnownHeader(KnownDir->second, NormalHeader);
429 
430     IntermediateDirs.push_back(Dir);
431 
432     // Retrieve our parent path.
433     DirName = llvm::sys::path::parent_path(DirName);
434     if (DirName.empty())
435       break;
436 
437     // Resolve the parent path to a directory entry.
438     if (auto DirEntry = SourceMgr.getFileManager().getDirectory(DirName))
439       Dir = *DirEntry;
440     else
441       Dir = nullptr;
442   } while (Dir);
443   return {};
444 }
445 
446 static bool violatesPrivateInclude(Module *RequestingModule,
447                                    const FileEntry *IncFileEnt,
448                                    ModuleMap::KnownHeader Header) {
449 #ifndef NDEBUG
450   if (Header.getRole() & ModuleMap::PrivateHeader) {
451     // Check for consistency between the module header role
452     // as obtained from the lookup and as obtained from the module.
453     // This check is not cheap, so enable it only for debugging.
454     bool IsPrivate = false;
455     SmallVectorImpl<Module::Header> *HeaderList[] = {
456         &Header.getModule()->Headers[Module::HK_Private],
457         &Header.getModule()->Headers[Module::HK_PrivateTextual]};
458     for (auto *Hs : HeaderList)
459       IsPrivate |=
460           std::find_if(Hs->begin(), Hs->end(), [&](const Module::Header &H) {
461             return H.Entry == IncFileEnt;
462           }) != Hs->end();
463     assert(IsPrivate && "inconsistent headers and roles");
464   }
465 #endif
466   return !Header.isAccessibleFrom(RequestingModule);
467 }
468 
469 static Module *getTopLevelOrNull(Module *M) {
470   return M ? M->getTopLevelModule() : nullptr;
471 }
472 
473 void ModuleMap::diagnoseHeaderInclusion(Module *RequestingModule,
474                                         bool RequestingModuleIsModuleInterface,
475                                         SourceLocation FilenameLoc,
476                                         StringRef Filename,
477                                         const FileEntry *File) {
478   // No errors for indirect modules. This may be a bit of a problem for modules
479   // with no source files.
480   if (getTopLevelOrNull(RequestingModule) != getTopLevelOrNull(SourceModule))
481     return;
482 
483   if (RequestingModule) {
484     resolveUses(RequestingModule, /*Complain=*/false);
485     resolveHeaderDirectives(RequestingModule);
486   }
487 
488   bool Excluded = false;
489   Module *Private = nullptr;
490   Module *NotUsed = nullptr;
491 
492   HeadersMap::iterator Known = findKnownHeader(File);
493   if (Known != Headers.end()) {
494     for (const KnownHeader &Header : Known->second) {
495       // Remember private headers for later printing of a diagnostic.
496       if (violatesPrivateInclude(RequestingModule, File, Header)) {
497         Private = Header.getModule();
498         continue;
499       }
500 
501       // If uses need to be specified explicitly, we are only allowed to return
502       // modules that are explicitly used by the requesting module.
503       if (RequestingModule && LangOpts.ModulesDeclUse &&
504           !RequestingModule->directlyUses(Header.getModule())) {
505         NotUsed = Header.getModule();
506         continue;
507       }
508 
509       // We have found a module that we can happily use.
510       return;
511     }
512 
513     Excluded = true;
514   }
515 
516   // We have found a header, but it is private.
517   if (Private) {
518     Diags.Report(FilenameLoc, diag::warn_use_of_private_header_outside_module)
519         << Filename;
520     return;
521   }
522 
523   // We have found a module, but we don't use it.
524   if (NotUsed) {
525     Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module)
526         << RequestingModule->getTopLevelModule()->Name << Filename;
527     return;
528   }
529 
530   if (Excluded || isHeaderInUmbrellaDirs(File))
531     return;
532 
533   // At this point, only non-modular includes remain.
534 
535   if (RequestingModule && LangOpts.ModulesStrictDeclUse) {
536     Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module)
537         << RequestingModule->getTopLevelModule()->Name << Filename;
538   } else if (RequestingModule && RequestingModuleIsModuleInterface &&
539              LangOpts.isCompilingModule()) {
540     // Do not diagnose when we are not compiling a module.
541     diag::kind DiagID = RequestingModule->getTopLevelModule()->IsFramework ?
542         diag::warn_non_modular_include_in_framework_module :
543         diag::warn_non_modular_include_in_module;
544     Diags.Report(FilenameLoc, DiagID) << RequestingModule->getFullModuleName()
545         << File->getName();
546   }
547 }
548 
549 static bool isBetterKnownHeader(const ModuleMap::KnownHeader &New,
550                                 const ModuleMap::KnownHeader &Old) {
551   // Prefer available modules.
552   // FIXME: Considering whether the module is available rather than merely
553   // importable is non-hermetic and can result in surprising behavior for
554   // prebuilt modules. Consider only checking for importability here.
555   if (New.getModule()->isAvailable() && !Old.getModule()->isAvailable())
556     return true;
557 
558   // Prefer a public header over a private header.
559   if ((New.getRole() & ModuleMap::PrivateHeader) !=
560       (Old.getRole() & ModuleMap::PrivateHeader))
561     return !(New.getRole() & ModuleMap::PrivateHeader);
562 
563   // Prefer a non-textual header over a textual header.
564   if ((New.getRole() & ModuleMap::TextualHeader) !=
565       (Old.getRole() & ModuleMap::TextualHeader))
566     return !(New.getRole() & ModuleMap::TextualHeader);
567 
568   // Don't have a reason to choose between these. Just keep the first one.
569   return false;
570 }
571 
572 ModuleMap::KnownHeader ModuleMap::findModuleForHeader(const FileEntry *File,
573                                                       bool AllowTextual) {
574   auto MakeResult = [&](ModuleMap::KnownHeader R) -> ModuleMap::KnownHeader {
575     if (!AllowTextual && R.getRole() & ModuleMap::TextualHeader)
576       return {};
577     return R;
578   };
579 
580   HeadersMap::iterator Known = findKnownHeader(File);
581   if (Known != Headers.end()) {
582     ModuleMap::KnownHeader Result;
583     // Iterate over all modules that 'File' is part of to find the best fit.
584     for (KnownHeader &H : Known->second) {
585       // Prefer a header from the source module over all others.
586       if (H.getModule()->getTopLevelModule() == SourceModule)
587         return MakeResult(H);
588       if (!Result || isBetterKnownHeader(H, Result))
589         Result = H;
590     }
591     return MakeResult(Result);
592   }
593 
594   return MakeResult(findOrCreateModuleForHeaderInUmbrellaDir(File));
595 }
596 
597 ModuleMap::KnownHeader
598 ModuleMap::findOrCreateModuleForHeaderInUmbrellaDir(const FileEntry *File) {
599   assert(!Headers.count(File) && "already have a module for this header");
600 
601   SmallVector<const DirectoryEntry *, 2> SkippedDirs;
602   KnownHeader H = findHeaderInUmbrellaDirs(File, SkippedDirs);
603   if (H) {
604     Module *Result = H.getModule();
605 
606     // Search up the module stack until we find a module with an umbrella
607     // directory.
608     Module *UmbrellaModule = Result;
609     while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
610       UmbrellaModule = UmbrellaModule->Parent;
611 
612     if (UmbrellaModule->InferSubmodules) {
613       const FileEntry *UmbrellaModuleMap =
614           getModuleMapFileForUniquing(UmbrellaModule);
615 
616       // Infer submodules for each of the directories we found between
617       // the directory of the umbrella header and the directory where
618       // the actual header is located.
619       bool Explicit = UmbrellaModule->InferExplicitSubmodules;
620 
621       for (unsigned I = SkippedDirs.size(); I != 0; --I) {
622         // Find or create the module that corresponds to this directory name.
623         SmallString<32> NameBuf;
624         StringRef Name = sanitizeFilenameAsIdentifier(
625             llvm::sys::path::stem(SkippedDirs[I-1]->getName()), NameBuf);
626         Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
627                                     Explicit).first;
628         InferredModuleAllowedBy[Result] = UmbrellaModuleMap;
629         Result->IsInferred = true;
630 
631         // Associate the module and the directory.
632         UmbrellaDirs[SkippedDirs[I-1]] = Result;
633 
634         // If inferred submodules export everything they import, add a
635         // wildcard to the set of exports.
636         if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
637           Result->Exports.push_back(Module::ExportDecl(nullptr, true));
638       }
639 
640       // Infer a submodule with the same name as this header file.
641       SmallString<32> NameBuf;
642       StringRef Name = sanitizeFilenameAsIdentifier(
643                          llvm::sys::path::stem(File->getName()), NameBuf);
644       Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
645                                   Explicit).first;
646       InferredModuleAllowedBy[Result] = UmbrellaModuleMap;
647       Result->IsInferred = true;
648       Result->addTopHeader(File);
649 
650       // If inferred submodules export everything they import, add a
651       // wildcard to the set of exports.
652       if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
653         Result->Exports.push_back(Module::ExportDecl(nullptr, true));
654     } else {
655       // Record each of the directories we stepped through as being part of
656       // the module we found, since the umbrella header covers them all.
657       for (unsigned I = 0, N = SkippedDirs.size(); I != N; ++I)
658         UmbrellaDirs[SkippedDirs[I]] = Result;
659     }
660 
661     KnownHeader Header(Result, NormalHeader);
662     Headers[File].push_back(Header);
663     return Header;
664   }
665 
666   return {};
667 }
668 
669 ArrayRef<ModuleMap::KnownHeader>
670 ModuleMap::findAllModulesForHeader(const FileEntry *File) {
671   HeadersMap::iterator Known = findKnownHeader(File);
672   if (Known != Headers.end())
673     return Known->second;
674 
675   if (findOrCreateModuleForHeaderInUmbrellaDir(File))
676     return Headers.find(File)->second;
677 
678   return None;
679 }
680 
681 ArrayRef<ModuleMap::KnownHeader>
682 ModuleMap::findResolvedModulesForHeader(const FileEntry *File) const {
683   // FIXME: Is this necessary?
684   resolveHeaderDirectives(File);
685   auto It = Headers.find(File);
686   if (It == Headers.end())
687     return None;
688   return It->second;
689 }
690 
691 bool ModuleMap::isHeaderInUnavailableModule(const FileEntry *Header) const {
692   return isHeaderUnavailableInModule(Header, nullptr);
693 }
694 
695 bool
696 ModuleMap::isHeaderUnavailableInModule(const FileEntry *Header,
697                                        const Module *RequestingModule) const {
698   resolveHeaderDirectives(Header);
699   HeadersMap::const_iterator Known = Headers.find(Header);
700   if (Known != Headers.end()) {
701     for (SmallVectorImpl<KnownHeader>::const_iterator
702              I = Known->second.begin(),
703              E = Known->second.end();
704          I != E; ++I) {
705 
706       if (I->isAvailable() &&
707           (!RequestingModule ||
708            I->getModule()->isSubModuleOf(RequestingModule))) {
709         // When no requesting module is available, the caller is looking if a
710         // header is part a module by only looking into the module map. This is
711         // done by warn_uncovered_module_header checks; don't consider textual
712         // headers part of it in this mode, otherwise we get misleading warnings
713         // that a umbrella header is not including a textual header.
714         if (!RequestingModule && I->getRole() == ModuleMap::TextualHeader)
715           continue;
716         return false;
717       }
718     }
719     return true;
720   }
721 
722   const DirectoryEntry *Dir = Header->getDir();
723   SmallVector<const DirectoryEntry *, 2> SkippedDirs;
724   StringRef DirName = Dir->getName();
725 
726   auto IsUnavailable = [&](const Module *M) {
727     return !M->isAvailable() && (!RequestingModule ||
728                                  M->isSubModuleOf(RequestingModule));
729   };
730 
731   // Keep walking up the directory hierarchy, looking for a directory with
732   // an umbrella header.
733   do {
734     llvm::DenseMap<const DirectoryEntry *, Module *>::const_iterator KnownDir
735       = UmbrellaDirs.find(Dir);
736     if (KnownDir != UmbrellaDirs.end()) {
737       Module *Found = KnownDir->second;
738       if (IsUnavailable(Found))
739         return true;
740 
741       // Search up the module stack until we find a module with an umbrella
742       // directory.
743       Module *UmbrellaModule = Found;
744       while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
745         UmbrellaModule = UmbrellaModule->Parent;
746 
747       if (UmbrellaModule->InferSubmodules) {
748         for (unsigned I = SkippedDirs.size(); I != 0; --I) {
749           // Find or create the module that corresponds to this directory name.
750           SmallString<32> NameBuf;
751           StringRef Name = sanitizeFilenameAsIdentifier(
752                              llvm::sys::path::stem(SkippedDirs[I-1]->getName()),
753                              NameBuf);
754           Found = lookupModuleQualified(Name, Found);
755           if (!Found)
756             return false;
757           if (IsUnavailable(Found))
758             return true;
759         }
760 
761         // Infer a submodule with the same name as this header file.
762         SmallString<32> NameBuf;
763         StringRef Name = sanitizeFilenameAsIdentifier(
764                            llvm::sys::path::stem(Header->getName()),
765                            NameBuf);
766         Found = lookupModuleQualified(Name, Found);
767         if (!Found)
768           return false;
769       }
770 
771       return IsUnavailable(Found);
772     }
773 
774     SkippedDirs.push_back(Dir);
775 
776     // Retrieve our parent path.
777     DirName = llvm::sys::path::parent_path(DirName);
778     if (DirName.empty())
779       break;
780 
781     // Resolve the parent path to a directory entry.
782     if (auto DirEntry = SourceMgr.getFileManager().getDirectory(DirName))
783       Dir = *DirEntry;
784     else
785       Dir = nullptr;
786   } while (Dir);
787 
788   return false;
789 }
790 
791 Module *ModuleMap::findModule(StringRef Name) const {
792   llvm::StringMap<Module *>::const_iterator Known = Modules.find(Name);
793   if (Known != Modules.end())
794     return Known->getValue();
795 
796   return nullptr;
797 }
798 
799 Module *ModuleMap::lookupModuleUnqualified(StringRef Name,
800                                            Module *Context) const {
801   for(; Context; Context = Context->Parent) {
802     if (Module *Sub = lookupModuleQualified(Name, Context))
803       return Sub;
804   }
805 
806   return findModule(Name);
807 }
808 
809 Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) const{
810   if (!Context)
811     return findModule(Name);
812 
813   return Context->findSubmodule(Name);
814 }
815 
816 std::pair<Module *, bool> ModuleMap::findOrCreateModule(StringRef Name,
817                                                         Module *Parent,
818                                                         bool IsFramework,
819                                                         bool IsExplicit) {
820   // Try to find an existing module with this name.
821   if (Module *Sub = lookupModuleQualified(Name, Parent))
822     return std::make_pair(Sub, false);
823 
824   // Create a new module with this name.
825   Module *Result = new Module(Name, SourceLocation(), Parent, IsFramework,
826                               IsExplicit, NumCreatedModules++);
827   if (!Parent) {
828     if (LangOpts.CurrentModule == Name)
829       SourceModule = Result;
830     Modules[Name] = Result;
831     ModuleScopeIDs[Result] = CurrentModuleScopeID;
832   }
833   return std::make_pair(Result, true);
834 }
835 
836 Module *ModuleMap::createGlobalModuleFragmentForModuleUnit(SourceLocation Loc) {
837   PendingSubmodules.emplace_back(
838       new Module("<global>", Loc, nullptr, /*IsFramework*/ false,
839                  /*IsExplicit*/ true, NumCreatedModules++));
840   PendingSubmodules.back()->Kind = Module::GlobalModuleFragment;
841   return PendingSubmodules.back().get();
842 }
843 
844 Module *
845 ModuleMap::createPrivateModuleFragmentForInterfaceUnit(Module *Parent,
846                                                        SourceLocation Loc) {
847   auto *Result =
848       new Module("<private>", Loc, Parent, /*IsFramework*/ false,
849                  /*IsExplicit*/ true, NumCreatedModules++);
850   Result->Kind = Module::PrivateModuleFragment;
851   return Result;
852 }
853 
854 Module *ModuleMap::createModuleForInterfaceUnit(SourceLocation Loc,
855                                                 StringRef Name,
856                                                 Module *GlobalModule) {
857   assert(LangOpts.CurrentModule == Name && "module name mismatch");
858   assert(!Modules[Name] && "redefining existing module");
859 
860   auto *Result =
861       new Module(Name, Loc, nullptr, /*IsFramework*/ false,
862                  /*IsExplicit*/ false, NumCreatedModules++);
863   Result->Kind = Module::ModuleInterfaceUnit;
864   Modules[Name] = SourceModule = Result;
865 
866   // Reparent the current global module fragment as a submodule of this module.
867   for (auto &Submodule : PendingSubmodules) {
868     Submodule->setParent(Result);
869     Submodule.release(); // now owned by parent
870   }
871   PendingSubmodules.clear();
872 
873   // Mark the main source file as being within the newly-created module so that
874   // declarations and macros are properly visibility-restricted to it.
875   auto *MainFile = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
876   assert(MainFile && "no input file for module interface");
877   Headers[MainFile].push_back(KnownHeader(Result, PrivateHeader));
878 
879   return Result;
880 }
881 
882 Module *ModuleMap::createHeaderModule(StringRef Name,
883                                       ArrayRef<Module::Header> Headers) {
884   assert(LangOpts.CurrentModule == Name && "module name mismatch");
885   assert(!Modules[Name] && "redefining existing module");
886 
887   auto *Result =
888       new Module(Name, SourceLocation(), nullptr, /*IsFramework*/ false,
889                  /*IsExplicit*/ false, NumCreatedModules++);
890   Result->Kind = Module::ModuleInterfaceUnit;
891   Modules[Name] = SourceModule = Result;
892 
893   for (const Module::Header &H : Headers) {
894     auto *M = new Module(H.NameAsWritten, SourceLocation(), Result,
895                          /*IsFramework*/ false,
896                          /*IsExplicit*/ true, NumCreatedModules++);
897     // Header modules are implicitly 'export *'.
898     M->Exports.push_back(Module::ExportDecl(nullptr, true));
899     addHeader(M, H, NormalHeader);
900   }
901 
902   return Result;
903 }
904 
905 /// For a framework module, infer the framework against which we
906 /// should link.
907 static void inferFrameworkLink(Module *Mod, const DirectoryEntry *FrameworkDir,
908                                FileManager &FileMgr) {
909   assert(Mod->IsFramework && "Can only infer linking for framework modules");
910   assert(!Mod->isSubFramework() &&
911          "Can only infer linking for top-level frameworks");
912 
913   SmallString<128> LibName;
914   LibName += FrameworkDir->getName();
915   llvm::sys::path::append(LibName, Mod->Name);
916 
917   // The library name of a framework has more than one possible extension since
918   // the introduction of the text-based dynamic library format. We need to check
919   // for both before we give up.
920   for (const char *extension : {"", ".tbd"}) {
921     llvm::sys::path::replace_extension(LibName, extension);
922     if (FileMgr.getFile(LibName)) {
923       Mod->LinkLibraries.push_back(Module::LinkLibrary(Mod->Name,
924                                                        /*IsFramework=*/true));
925       return;
926     }
927   }
928 }
929 
930 Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
931                                         bool IsSystem, Module *Parent) {
932   Attributes Attrs;
933   Attrs.IsSystem = IsSystem;
934   return inferFrameworkModule(FrameworkDir, Attrs, Parent);
935 }
936 
937 Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
938                                         Attributes Attrs, Module *Parent) {
939   // Note: as an egregious but useful hack we use the real path here, because
940   // we might be looking at an embedded framework that symlinks out to a
941   // top-level framework, and we need to infer as if we were naming the
942   // top-level framework.
943   StringRef FrameworkDirName =
944       SourceMgr.getFileManager().getCanonicalName(FrameworkDir);
945 
946   // In case this is a case-insensitive filesystem, use the canonical
947   // directory name as the ModuleName, since modules are case-sensitive.
948   // FIXME: we should be able to give a fix-it hint for the correct spelling.
949   SmallString<32> ModuleNameStorage;
950   StringRef ModuleName = sanitizeFilenameAsIdentifier(
951       llvm::sys::path::stem(FrameworkDirName), ModuleNameStorage);
952 
953   // Check whether we've already found this module.
954   if (Module *Mod = lookupModuleQualified(ModuleName, Parent))
955     return Mod;
956 
957   FileManager &FileMgr = SourceMgr.getFileManager();
958 
959   // If the framework has a parent path from which we're allowed to infer
960   // a framework module, do so.
961   const FileEntry *ModuleMapFile = nullptr;
962   if (!Parent) {
963     // Determine whether we're allowed to infer a module map.
964     bool canInfer = false;
965     if (llvm::sys::path::has_parent_path(FrameworkDirName)) {
966       // Figure out the parent path.
967       StringRef Parent = llvm::sys::path::parent_path(FrameworkDirName);
968       if (auto ParentDir = FileMgr.getDirectory(Parent)) {
969         // Check whether we have already looked into the parent directory
970         // for a module map.
971         llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
972           inferred = InferredDirectories.find(*ParentDir);
973         if (inferred == InferredDirectories.end()) {
974           // We haven't looked here before. Load a module map, if there is
975           // one.
976           bool IsFrameworkDir = Parent.endswith(".framework");
977           if (const FileEntry *ModMapFile =
978                 HeaderInfo.lookupModuleMapFile(*ParentDir, IsFrameworkDir)) {
979             parseModuleMapFile(ModMapFile, Attrs.IsSystem, *ParentDir);
980             inferred = InferredDirectories.find(*ParentDir);
981           }
982 
983           if (inferred == InferredDirectories.end())
984             inferred = InferredDirectories.insert(
985                          std::make_pair(*ParentDir, InferredDirectory())).first;
986         }
987 
988         if (inferred->second.InferModules) {
989           // We're allowed to infer for this directory, but make sure it's okay
990           // to infer this particular module.
991           StringRef Name = llvm::sys::path::stem(FrameworkDirName);
992           canInfer =
993               !llvm::is_contained(inferred->second.ExcludedModules, Name);
994 
995           Attrs.IsSystem |= inferred->second.Attrs.IsSystem;
996           Attrs.IsExternC |= inferred->second.Attrs.IsExternC;
997           Attrs.IsExhaustive |= inferred->second.Attrs.IsExhaustive;
998           Attrs.NoUndeclaredIncludes |=
999               inferred->second.Attrs.NoUndeclaredIncludes;
1000           ModuleMapFile = inferred->second.ModuleMapFile;
1001         }
1002       }
1003     }
1004 
1005     // If we're not allowed to infer a framework module, don't.
1006     if (!canInfer)
1007       return nullptr;
1008   } else
1009     ModuleMapFile = getModuleMapFileForUniquing(Parent);
1010 
1011 
1012   // Look for an umbrella header.
1013   SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName());
1014   llvm::sys::path::append(UmbrellaName, "Headers", ModuleName + ".h");
1015   auto UmbrellaHeader = FileMgr.getFile(UmbrellaName);
1016 
1017   // FIXME: If there's no umbrella header, we could probably scan the
1018   // framework to load *everything*. But, it's not clear that this is a good
1019   // idea.
1020   if (!UmbrellaHeader)
1021     return nullptr;
1022 
1023   Module *Result = new Module(ModuleName, SourceLocation(), Parent,
1024                               /*IsFramework=*/true, /*IsExplicit=*/false,
1025                               NumCreatedModules++);
1026   InferredModuleAllowedBy[Result] = ModuleMapFile;
1027   Result->IsInferred = true;
1028   if (!Parent) {
1029     if (LangOpts.CurrentModule == ModuleName)
1030       SourceModule = Result;
1031     Modules[ModuleName] = Result;
1032     ModuleScopeIDs[Result] = CurrentModuleScopeID;
1033   }
1034 
1035   Result->IsSystem |= Attrs.IsSystem;
1036   Result->IsExternC |= Attrs.IsExternC;
1037   Result->ConfigMacrosExhaustive |= Attrs.IsExhaustive;
1038   Result->NoUndeclaredIncludes |= Attrs.NoUndeclaredIncludes;
1039   Result->Directory = FrameworkDir;
1040 
1041   // Chop off the first framework bit, as that is implied.
1042   StringRef RelativePath = UmbrellaName.str().substr(
1043       Result->getTopLevelModule()->Directory->getName().size());
1044   RelativePath = llvm::sys::path::relative_path(RelativePath);
1045 
1046   // umbrella header "umbrella-header-name"
1047   setUmbrellaHeader(Result, *UmbrellaHeader, ModuleName + ".h", RelativePath);
1048 
1049   // export *
1050   Result->Exports.push_back(Module::ExportDecl(nullptr, true));
1051 
1052   // module * { export * }
1053   Result->InferSubmodules = true;
1054   Result->InferExportWildcard = true;
1055 
1056   // Look for subframeworks.
1057   std::error_code EC;
1058   SmallString<128> SubframeworksDirName
1059     = StringRef(FrameworkDir->getName());
1060   llvm::sys::path::append(SubframeworksDirName, "Frameworks");
1061   llvm::sys::path::native(SubframeworksDirName);
1062   llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
1063   for (llvm::vfs::directory_iterator
1064            Dir = FS.dir_begin(SubframeworksDirName, EC),
1065            DirEnd;
1066        Dir != DirEnd && !EC; Dir.increment(EC)) {
1067     if (!StringRef(Dir->path()).endswith(".framework"))
1068       continue;
1069 
1070     if (auto SubframeworkDir =
1071             FileMgr.getDirectory(Dir->path())) {
1072       // Note: as an egregious but useful hack, we use the real path here and
1073       // check whether it is actually a subdirectory of the parent directory.
1074       // This will not be the case if the 'subframework' is actually a symlink
1075       // out to a top-level framework.
1076       StringRef SubframeworkDirName =
1077           FileMgr.getCanonicalName(*SubframeworkDir);
1078       bool FoundParent = false;
1079       do {
1080         // Get the parent directory name.
1081         SubframeworkDirName
1082           = llvm::sys::path::parent_path(SubframeworkDirName);
1083         if (SubframeworkDirName.empty())
1084           break;
1085 
1086         if (auto SubDir = FileMgr.getDirectory(SubframeworkDirName)) {
1087           if (*SubDir == FrameworkDir) {
1088             FoundParent = true;
1089             break;
1090           }
1091         }
1092       } while (true);
1093 
1094       if (!FoundParent)
1095         continue;
1096 
1097       // FIXME: Do we want to warn about subframeworks without umbrella headers?
1098       inferFrameworkModule(*SubframeworkDir, Attrs, Result);
1099     }
1100   }
1101 
1102   // If the module is a top-level framework, automatically link against the
1103   // framework.
1104   if (!Result->isSubFramework()) {
1105     inferFrameworkLink(Result, FrameworkDir, FileMgr);
1106   }
1107 
1108   return Result;
1109 }
1110 
1111 Module *ModuleMap::createShadowedModule(StringRef Name, bool IsFramework,
1112                                         Module *ShadowingModule) {
1113 
1114   // Create a new module with this name.
1115   Module *Result =
1116       new Module(Name, SourceLocation(), /*Parent=*/nullptr, IsFramework,
1117                  /*IsExplicit=*/false, NumCreatedModules++);
1118   Result->ShadowingModule = ShadowingModule;
1119   Result->markUnavailable(/*Unimportable*/true);
1120   ModuleScopeIDs[Result] = CurrentModuleScopeID;
1121   ShadowModules.push_back(Result);
1122 
1123   return Result;
1124 }
1125 
1126 void ModuleMap::setUmbrellaHeader(
1127     Module *Mod, const FileEntry *UmbrellaHeader, const Twine &NameAsWritten,
1128     const Twine &PathRelativeToRootModuleDirectory) {
1129   Headers[UmbrellaHeader].push_back(KnownHeader(Mod, NormalHeader));
1130   Mod->Umbrella = UmbrellaHeader;
1131   Mod->UmbrellaAsWritten = NameAsWritten.str();
1132   Mod->UmbrellaRelativeToRootModuleDirectory =
1133       PathRelativeToRootModuleDirectory.str();
1134   UmbrellaDirs[UmbrellaHeader->getDir()] = Mod;
1135 
1136   // Notify callbacks that we just added a new header.
1137   for (const auto &Cb : Callbacks)
1138     Cb->moduleMapAddUmbrellaHeader(&SourceMgr.getFileManager(), UmbrellaHeader);
1139 }
1140 
1141 void ModuleMap::setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir,
1142                                const Twine &NameAsWritten,
1143                                const Twine &PathRelativeToRootModuleDirectory) {
1144   Mod->Umbrella = UmbrellaDir;
1145   Mod->UmbrellaAsWritten = NameAsWritten.str();
1146   Mod->UmbrellaRelativeToRootModuleDirectory =
1147       PathRelativeToRootModuleDirectory.str();
1148   UmbrellaDirs[UmbrellaDir] = Mod;
1149 }
1150 
1151 void ModuleMap::addUnresolvedHeader(Module *Mod,
1152                                     Module::UnresolvedHeaderDirective Header,
1153                                     bool &NeedsFramework) {
1154   // If there is a builtin counterpart to this file, add it now so it can
1155   // wrap the system header.
1156   if (resolveAsBuiltinHeader(Mod, Header)) {
1157     // If we have both a builtin and system version of the file, the
1158     // builtin version may want to inject macros into the system header, so
1159     // force the system header to be treated as a textual header in this
1160     // case.
1161     Header.Kind = headerRoleToKind(ModuleMap::ModuleHeaderRole(
1162         headerKindToRole(Header.Kind) | ModuleMap::TextualHeader));
1163     Header.HasBuiltinHeader = true;
1164   }
1165 
1166   // If possible, don't stat the header until we need to. This requires the
1167   // user to have provided us with some stat information about the file.
1168   // FIXME: Add support for lazily stat'ing umbrella headers and excluded
1169   // headers.
1170   if ((Header.Size || Header.ModTime) && !Header.IsUmbrella &&
1171       Header.Kind != Module::HK_Excluded) {
1172     // We expect more variation in mtime than size, so if we're given both,
1173     // use the mtime as the key.
1174     if (Header.ModTime)
1175       LazyHeadersByModTime[*Header.ModTime].push_back(Mod);
1176     else
1177       LazyHeadersBySize[*Header.Size].push_back(Mod);
1178     Mod->UnresolvedHeaders.push_back(Header);
1179     return;
1180   }
1181 
1182   // We don't have stat information or can't defer looking this file up.
1183   // Perform the lookup now.
1184   resolveHeader(Mod, Header, NeedsFramework);
1185 }
1186 
1187 void ModuleMap::resolveHeaderDirectives(const FileEntry *File) const {
1188   auto BySize = LazyHeadersBySize.find(File->getSize());
1189   if (BySize != LazyHeadersBySize.end()) {
1190     for (auto *M : BySize->second)
1191       resolveHeaderDirectives(M);
1192     LazyHeadersBySize.erase(BySize);
1193   }
1194 
1195   auto ByModTime = LazyHeadersByModTime.find(File->getModificationTime());
1196   if (ByModTime != LazyHeadersByModTime.end()) {
1197     for (auto *M : ByModTime->second)
1198       resolveHeaderDirectives(M);
1199     LazyHeadersByModTime.erase(ByModTime);
1200   }
1201 }
1202 
1203 void ModuleMap::resolveHeaderDirectives(Module *Mod) const {
1204   bool NeedsFramework = false;
1205   for (auto &Header : Mod->UnresolvedHeaders)
1206     // This operation is logically const; we're just changing how we represent
1207     // the header information for this file.
1208     const_cast<ModuleMap*>(this)->resolveHeader(Mod, Header, NeedsFramework);
1209   Mod->UnresolvedHeaders.clear();
1210 }
1211 
1212 void ModuleMap::addHeader(Module *Mod, Module::Header Header,
1213                           ModuleHeaderRole Role, bool Imported) {
1214   KnownHeader KH(Mod, Role);
1215 
1216   // Only add each header to the headers list once.
1217   // FIXME: Should we diagnose if a header is listed twice in the
1218   // same module definition?
1219   auto &HeaderList = Headers[Header.Entry];
1220   if (llvm::is_contained(HeaderList, KH))
1221     return;
1222 
1223   HeaderList.push_back(KH);
1224   Mod->Headers[headerRoleToKind(Role)].push_back(Header);
1225 
1226   bool isCompilingModuleHeader =
1227       LangOpts.isCompilingModule() && Mod->getTopLevelModule() == SourceModule;
1228   if (!Imported || isCompilingModuleHeader) {
1229     // When we import HeaderFileInfo, the external source is expected to
1230     // set the isModuleHeader flag itself.
1231     HeaderInfo.MarkFileModuleHeader(Header.Entry, Role,
1232                                     isCompilingModuleHeader);
1233   }
1234 
1235   // Notify callbacks that we just added a new header.
1236   for (const auto &Cb : Callbacks)
1237     Cb->moduleMapAddHeader(Header.Entry->getName());
1238 }
1239 
1240 void ModuleMap::excludeHeader(Module *Mod, Module::Header Header) {
1241   // Add this as a known header so we won't implicitly add it to any
1242   // umbrella directory module.
1243   // FIXME: Should we only exclude it from umbrella modules within the
1244   // specified module?
1245   (void) Headers[Header.Entry];
1246 
1247   Mod->Headers[Module::HK_Excluded].push_back(std::move(Header));
1248 }
1249 
1250 const FileEntry *
1251 ModuleMap::getContainingModuleMapFile(const Module *Module) const {
1252   if (Module->DefinitionLoc.isInvalid())
1253     return nullptr;
1254 
1255   return SourceMgr.getFileEntryForID(
1256            SourceMgr.getFileID(Module->DefinitionLoc));
1257 }
1258 
1259 const FileEntry *ModuleMap::getModuleMapFileForUniquing(const Module *M) const {
1260   if (M->IsInferred) {
1261     assert(InferredModuleAllowedBy.count(M) && "missing inferred module map");
1262     return InferredModuleAllowedBy.find(M)->second;
1263   }
1264   return getContainingModuleMapFile(M);
1265 }
1266 
1267 void ModuleMap::setInferredModuleAllowedBy(Module *M, const FileEntry *ModMap) {
1268   assert(M->IsInferred && "module not inferred");
1269   InferredModuleAllowedBy[M] = ModMap;
1270 }
1271 
1272 void ModuleMap::addAdditionalModuleMapFile(const Module *M,
1273                                            const FileEntry *ModuleMap) {
1274   AdditionalModMaps[M].insert(ModuleMap);
1275 }
1276 
1277 LLVM_DUMP_METHOD void ModuleMap::dump() {
1278   llvm::errs() << "Modules:";
1279   for (llvm::StringMap<Module *>::iterator M = Modules.begin(),
1280                                         MEnd = Modules.end();
1281        M != MEnd; ++M)
1282     M->getValue()->print(llvm::errs(), 2);
1283 
1284   llvm::errs() << "Headers:";
1285   for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end();
1286        H != HEnd; ++H) {
1287     llvm::errs() << "  \"" << H->first->getName() << "\" -> ";
1288     for (SmallVectorImpl<KnownHeader>::const_iterator I = H->second.begin(),
1289                                                       E = H->second.end();
1290          I != E; ++I) {
1291       if (I != H->second.begin())
1292         llvm::errs() << ",";
1293       llvm::errs() << I->getModule()->getFullModuleName();
1294     }
1295     llvm::errs() << "\n";
1296   }
1297 }
1298 
1299 bool ModuleMap::resolveExports(Module *Mod, bool Complain) {
1300   auto Unresolved = std::move(Mod->UnresolvedExports);
1301   Mod->UnresolvedExports.clear();
1302   for (auto &UE : Unresolved) {
1303     Module::ExportDecl Export = resolveExport(Mod, UE, Complain);
1304     if (Export.getPointer() || Export.getInt())
1305       Mod->Exports.push_back(Export);
1306     else
1307       Mod->UnresolvedExports.push_back(UE);
1308   }
1309   return !Mod->UnresolvedExports.empty();
1310 }
1311 
1312 bool ModuleMap::resolveUses(Module *Mod, bool Complain) {
1313   auto Unresolved = std::move(Mod->UnresolvedDirectUses);
1314   Mod->UnresolvedDirectUses.clear();
1315   for (auto &UDU : Unresolved) {
1316     Module *DirectUse = resolveModuleId(UDU, Mod, Complain);
1317     if (DirectUse)
1318       Mod->DirectUses.push_back(DirectUse);
1319     else
1320       Mod->UnresolvedDirectUses.push_back(UDU);
1321   }
1322   return !Mod->UnresolvedDirectUses.empty();
1323 }
1324 
1325 bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) {
1326   auto Unresolved = std::move(Mod->UnresolvedConflicts);
1327   Mod->UnresolvedConflicts.clear();
1328   for (auto &UC : Unresolved) {
1329     if (Module *OtherMod = resolveModuleId(UC.Id, Mod, Complain)) {
1330       Module::Conflict Conflict;
1331       Conflict.Other = OtherMod;
1332       Conflict.Message = UC.Message;
1333       Mod->Conflicts.push_back(Conflict);
1334     } else
1335       Mod->UnresolvedConflicts.push_back(UC);
1336   }
1337   return !Mod->UnresolvedConflicts.empty();
1338 }
1339 
1340 //----------------------------------------------------------------------------//
1341 // Module map file parser
1342 //----------------------------------------------------------------------------//
1343 
1344 namespace clang {
1345 
1346   /// A token in a module map file.
1347   struct MMToken {
1348     enum TokenKind {
1349       Comma,
1350       ConfigMacros,
1351       Conflict,
1352       EndOfFile,
1353       HeaderKeyword,
1354       Identifier,
1355       Exclaim,
1356       ExcludeKeyword,
1357       ExplicitKeyword,
1358       ExportKeyword,
1359       ExportAsKeyword,
1360       ExternKeyword,
1361       FrameworkKeyword,
1362       LinkKeyword,
1363       ModuleKeyword,
1364       Period,
1365       PrivateKeyword,
1366       UmbrellaKeyword,
1367       UseKeyword,
1368       RequiresKeyword,
1369       Star,
1370       StringLiteral,
1371       IntegerLiteral,
1372       TextualKeyword,
1373       LBrace,
1374       RBrace,
1375       LSquare,
1376       RSquare
1377     } Kind;
1378 
1379     SourceLocation::UIntTy Location;
1380     unsigned StringLength;
1381     union {
1382       // If Kind != IntegerLiteral.
1383       const char *StringData;
1384 
1385       // If Kind == IntegerLiteral.
1386       uint64_t IntegerValue;
1387     };
1388 
1389     void clear() {
1390       Kind = EndOfFile;
1391       Location = 0;
1392       StringLength = 0;
1393       StringData = nullptr;
1394     }
1395 
1396     bool is(TokenKind K) const { return Kind == K; }
1397 
1398     SourceLocation getLocation() const {
1399       return SourceLocation::getFromRawEncoding(Location);
1400     }
1401 
1402     uint64_t getInteger() const {
1403       return Kind == IntegerLiteral ? IntegerValue : 0;
1404     }
1405 
1406     StringRef getString() const {
1407       return Kind == IntegerLiteral ? StringRef()
1408                                     : StringRef(StringData, StringLength);
1409     }
1410   };
1411 
1412   class ModuleMapParser {
1413     Lexer &L;
1414     SourceManager &SourceMgr;
1415 
1416     /// Default target information, used only for string literal
1417     /// parsing.
1418     const TargetInfo *Target;
1419 
1420     DiagnosticsEngine &Diags;
1421     ModuleMap &Map;
1422 
1423     /// The current module map file.
1424     const FileEntry *ModuleMapFile;
1425 
1426     /// Source location of most recent parsed module declaration
1427     SourceLocation CurrModuleDeclLoc;
1428 
1429     /// The directory that file names in this module map file should
1430     /// be resolved relative to.
1431     const DirectoryEntry *Directory;
1432 
1433     /// Whether this module map is in a system header directory.
1434     bool IsSystem;
1435 
1436     /// Whether an error occurred.
1437     bool HadError = false;
1438 
1439     /// Stores string data for the various string literals referenced
1440     /// during parsing.
1441     llvm::BumpPtrAllocator StringData;
1442 
1443     /// The current token.
1444     MMToken Tok;
1445 
1446     /// The active module.
1447     Module *ActiveModule = nullptr;
1448 
1449     /// Whether a module uses the 'requires excluded' hack to mark its
1450     /// contents as 'textual'.
1451     ///
1452     /// On older Darwin SDK versions, 'requires excluded' is used to mark the
1453     /// contents of the Darwin.C.excluded (assert.h) and Tcl.Private modules as
1454     /// non-modular headers.  For backwards compatibility, we continue to
1455     /// support this idiom for just these modules, and map the headers to
1456     /// 'textual' to match the original intent.
1457     llvm::SmallPtrSet<Module *, 2> UsesRequiresExcludedHack;
1458 
1459     /// Consume the current token and return its location.
1460     SourceLocation consumeToken();
1461 
1462     /// Skip tokens until we reach the a token with the given kind
1463     /// (or the end of the file).
1464     void skipUntil(MMToken::TokenKind K);
1465 
1466     using ModuleId = SmallVector<std::pair<std::string, SourceLocation>, 2>;
1467 
1468     bool parseModuleId(ModuleId &Id);
1469     void parseModuleDecl();
1470     void parseExternModuleDecl();
1471     void parseRequiresDecl();
1472     void parseHeaderDecl(MMToken::TokenKind, SourceLocation LeadingLoc);
1473     void parseUmbrellaDirDecl(SourceLocation UmbrellaLoc);
1474     void parseExportDecl();
1475     void parseExportAsDecl();
1476     void parseUseDecl();
1477     void parseLinkDecl();
1478     void parseConfigMacros();
1479     void parseConflict();
1480     void parseInferredModuleDecl(bool Framework, bool Explicit);
1481 
1482     /// Private modules are canonicalized as Foo_Private. Clang provides extra
1483     /// module map search logic to find the appropriate private module when PCH
1484     /// is used with implicit module maps. Warn when private modules are written
1485     /// in other ways (FooPrivate and Foo.Private), providing notes and fixits.
1486     void diagnosePrivateModules(SourceLocation ExplicitLoc,
1487                                 SourceLocation FrameworkLoc);
1488 
1489     using Attributes = ModuleMap::Attributes;
1490 
1491     bool parseOptionalAttributes(Attributes &Attrs);
1492 
1493   public:
1494     explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr,
1495                              const TargetInfo *Target, DiagnosticsEngine &Diags,
1496                              ModuleMap &Map, const FileEntry *ModuleMapFile,
1497                              const DirectoryEntry *Directory, bool IsSystem)
1498         : L(L), SourceMgr(SourceMgr), Target(Target), Diags(Diags), Map(Map),
1499           ModuleMapFile(ModuleMapFile), Directory(Directory),
1500           IsSystem(IsSystem) {
1501       Tok.clear();
1502       consumeToken();
1503     }
1504 
1505     bool parseModuleMapFile();
1506 
1507     bool terminatedByDirective() { return false; }
1508     SourceLocation getLocation() { return Tok.getLocation(); }
1509   };
1510 
1511 } // namespace clang
1512 
1513 SourceLocation ModuleMapParser::consumeToken() {
1514   SourceLocation Result = Tok.getLocation();
1515 
1516 retry:
1517   Tok.clear();
1518   Token LToken;
1519   L.LexFromRawLexer(LToken);
1520   Tok.Location = LToken.getLocation().getRawEncoding();
1521   switch (LToken.getKind()) {
1522   case tok::raw_identifier: {
1523     StringRef RI = LToken.getRawIdentifier();
1524     Tok.StringData = RI.data();
1525     Tok.StringLength = RI.size();
1526     Tok.Kind = llvm::StringSwitch<MMToken::TokenKind>(RI)
1527                  .Case("config_macros", MMToken::ConfigMacros)
1528                  .Case("conflict", MMToken::Conflict)
1529                  .Case("exclude", MMToken::ExcludeKeyword)
1530                  .Case("explicit", MMToken::ExplicitKeyword)
1531                  .Case("export", MMToken::ExportKeyword)
1532                  .Case("export_as", MMToken::ExportAsKeyword)
1533                  .Case("extern", MMToken::ExternKeyword)
1534                  .Case("framework", MMToken::FrameworkKeyword)
1535                  .Case("header", MMToken::HeaderKeyword)
1536                  .Case("link", MMToken::LinkKeyword)
1537                  .Case("module", MMToken::ModuleKeyword)
1538                  .Case("private", MMToken::PrivateKeyword)
1539                  .Case("requires", MMToken::RequiresKeyword)
1540                  .Case("textual", MMToken::TextualKeyword)
1541                  .Case("umbrella", MMToken::UmbrellaKeyword)
1542                  .Case("use", MMToken::UseKeyword)
1543                  .Default(MMToken::Identifier);
1544     break;
1545   }
1546 
1547   case tok::comma:
1548     Tok.Kind = MMToken::Comma;
1549     break;
1550 
1551   case tok::eof:
1552     Tok.Kind = MMToken::EndOfFile;
1553     break;
1554 
1555   case tok::l_brace:
1556     Tok.Kind = MMToken::LBrace;
1557     break;
1558 
1559   case tok::l_square:
1560     Tok.Kind = MMToken::LSquare;
1561     break;
1562 
1563   case tok::period:
1564     Tok.Kind = MMToken::Period;
1565     break;
1566 
1567   case tok::r_brace:
1568     Tok.Kind = MMToken::RBrace;
1569     break;
1570 
1571   case tok::r_square:
1572     Tok.Kind = MMToken::RSquare;
1573     break;
1574 
1575   case tok::star:
1576     Tok.Kind = MMToken::Star;
1577     break;
1578 
1579   case tok::exclaim:
1580     Tok.Kind = MMToken::Exclaim;
1581     break;
1582 
1583   case tok::string_literal: {
1584     if (LToken.hasUDSuffix()) {
1585       Diags.Report(LToken.getLocation(), diag::err_invalid_string_udl);
1586       HadError = true;
1587       goto retry;
1588     }
1589 
1590     // Parse the string literal.
1591     LangOptions LangOpts;
1592     StringLiteralParser StringLiteral(LToken, SourceMgr, LangOpts, *Target);
1593     if (StringLiteral.hadError)
1594       goto retry;
1595 
1596     // Copy the string literal into our string data allocator.
1597     unsigned Length = StringLiteral.GetStringLength();
1598     char *Saved = StringData.Allocate<char>(Length + 1);
1599     memcpy(Saved, StringLiteral.GetString().data(), Length);
1600     Saved[Length] = 0;
1601 
1602     // Form the token.
1603     Tok.Kind = MMToken::StringLiteral;
1604     Tok.StringData = Saved;
1605     Tok.StringLength = Length;
1606     break;
1607   }
1608 
1609   case tok::numeric_constant: {
1610     // We don't support any suffixes or other complications.
1611     SmallString<32> SpellingBuffer;
1612     SpellingBuffer.resize(LToken.getLength() + 1);
1613     const char *Start = SpellingBuffer.data();
1614     unsigned Length =
1615         Lexer::getSpelling(LToken, Start, SourceMgr, L.getLangOpts());
1616     uint64_t Value;
1617     if (StringRef(Start, Length).getAsInteger(0, Value)) {
1618       Diags.Report(Tok.getLocation(), diag::err_mmap_unknown_token);
1619       HadError = true;
1620       goto retry;
1621     }
1622 
1623     Tok.Kind = MMToken::IntegerLiteral;
1624     Tok.IntegerValue = Value;
1625     break;
1626   }
1627 
1628   case tok::comment:
1629     goto retry;
1630 
1631   case tok::hash:
1632     // A module map can be terminated prematurely by
1633     //   #pragma clang module contents
1634     // When building the module, we'll treat the rest of the file as the
1635     // contents of the module.
1636     {
1637       auto NextIsIdent = [&](StringRef Str) -> bool {
1638         L.LexFromRawLexer(LToken);
1639         return !LToken.isAtStartOfLine() && LToken.is(tok::raw_identifier) &&
1640                LToken.getRawIdentifier() == Str;
1641       };
1642       if (NextIsIdent("pragma") && NextIsIdent("clang") &&
1643           NextIsIdent("module") && NextIsIdent("contents")) {
1644         Tok.Kind = MMToken::EndOfFile;
1645         break;
1646       }
1647     }
1648     LLVM_FALLTHROUGH;
1649 
1650   default:
1651     Diags.Report(Tok.getLocation(), diag::err_mmap_unknown_token);
1652     HadError = true;
1653     goto retry;
1654   }
1655 
1656   return Result;
1657 }
1658 
1659 void ModuleMapParser::skipUntil(MMToken::TokenKind K) {
1660   unsigned braceDepth = 0;
1661   unsigned squareDepth = 0;
1662   do {
1663     switch (Tok.Kind) {
1664     case MMToken::EndOfFile:
1665       return;
1666 
1667     case MMToken::LBrace:
1668       if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1669         return;
1670 
1671       ++braceDepth;
1672       break;
1673 
1674     case MMToken::LSquare:
1675       if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1676         return;
1677 
1678       ++squareDepth;
1679       break;
1680 
1681     case MMToken::RBrace:
1682       if (braceDepth > 0)
1683         --braceDepth;
1684       else if (Tok.is(K))
1685         return;
1686       break;
1687 
1688     case MMToken::RSquare:
1689       if (squareDepth > 0)
1690         --squareDepth;
1691       else if (Tok.is(K))
1692         return;
1693       break;
1694 
1695     default:
1696       if (braceDepth == 0 && squareDepth == 0 && Tok.is(K))
1697         return;
1698       break;
1699     }
1700 
1701    consumeToken();
1702   } while (true);
1703 }
1704 
1705 /// Parse a module-id.
1706 ///
1707 ///   module-id:
1708 ///     identifier
1709 ///     identifier '.' module-id
1710 ///
1711 /// \returns true if an error occurred, false otherwise.
1712 bool ModuleMapParser::parseModuleId(ModuleId &Id) {
1713   Id.clear();
1714   do {
1715     if (Tok.is(MMToken::Identifier) || Tok.is(MMToken::StringLiteral)) {
1716       Id.push_back(
1717           std::make_pair(std::string(Tok.getString()), Tok.getLocation()));
1718       consumeToken();
1719     } else {
1720       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name);
1721       return true;
1722     }
1723 
1724     if (!Tok.is(MMToken::Period))
1725       break;
1726 
1727     consumeToken();
1728   } while (true);
1729 
1730   return false;
1731 }
1732 
1733 namespace {
1734 
1735   /// Enumerates the known attributes.
1736   enum AttributeKind {
1737     /// An unknown attribute.
1738     AT_unknown,
1739 
1740     /// The 'system' attribute.
1741     AT_system,
1742 
1743     /// The 'extern_c' attribute.
1744     AT_extern_c,
1745 
1746     /// The 'exhaustive' attribute.
1747     AT_exhaustive,
1748 
1749     /// The 'no_undeclared_includes' attribute.
1750     AT_no_undeclared_includes
1751   };
1752 
1753 } // namespace
1754 
1755 /// Private modules are canonicalized as Foo_Private. Clang provides extra
1756 /// module map search logic to find the appropriate private module when PCH
1757 /// is used with implicit module maps. Warn when private modules are written
1758 /// in other ways (FooPrivate and Foo.Private), providing notes and fixits.
1759 void ModuleMapParser::diagnosePrivateModules(SourceLocation ExplicitLoc,
1760                                              SourceLocation FrameworkLoc) {
1761   auto GenNoteAndFixIt = [&](StringRef BadName, StringRef Canonical,
1762                              const Module *M, SourceRange ReplLoc) {
1763     auto D = Diags.Report(ActiveModule->DefinitionLoc,
1764                           diag::note_mmap_rename_top_level_private_module);
1765     D << BadName << M->Name;
1766     D << FixItHint::CreateReplacement(ReplLoc, Canonical);
1767   };
1768 
1769   for (auto E = Map.module_begin(); E != Map.module_end(); ++E) {
1770     auto const *M = E->getValue();
1771     if (M->Directory != ActiveModule->Directory)
1772       continue;
1773 
1774     SmallString<128> FullName(ActiveModule->getFullModuleName());
1775     if (!FullName.startswith(M->Name) && !FullName.endswith("Private"))
1776       continue;
1777     SmallString<128> FixedPrivModDecl;
1778     SmallString<128> Canonical(M->Name);
1779     Canonical.append("_Private");
1780 
1781     // Foo.Private -> Foo_Private
1782     if (ActiveModule->Parent && ActiveModule->Name == "Private" && !M->Parent &&
1783         M->Name == ActiveModule->Parent->Name) {
1784       Diags.Report(ActiveModule->DefinitionLoc,
1785                    diag::warn_mmap_mismatched_private_submodule)
1786           << FullName;
1787 
1788       SourceLocation FixItInitBegin = CurrModuleDeclLoc;
1789       if (FrameworkLoc.isValid())
1790         FixItInitBegin = FrameworkLoc;
1791       if (ExplicitLoc.isValid())
1792         FixItInitBegin = ExplicitLoc;
1793 
1794       if (FrameworkLoc.isValid() || ActiveModule->Parent->IsFramework)
1795         FixedPrivModDecl.append("framework ");
1796       FixedPrivModDecl.append("module ");
1797       FixedPrivModDecl.append(Canonical);
1798 
1799       GenNoteAndFixIt(FullName, FixedPrivModDecl, M,
1800                       SourceRange(FixItInitBegin, ActiveModule->DefinitionLoc));
1801       continue;
1802     }
1803 
1804     // FooPrivate and whatnots -> Foo_Private
1805     if (!ActiveModule->Parent && !M->Parent && M->Name != ActiveModule->Name &&
1806         ActiveModule->Name != Canonical) {
1807       Diags.Report(ActiveModule->DefinitionLoc,
1808                    diag::warn_mmap_mismatched_private_module_name)
1809           << ActiveModule->Name;
1810       GenNoteAndFixIt(ActiveModule->Name, Canonical, M,
1811                       SourceRange(ActiveModule->DefinitionLoc));
1812     }
1813   }
1814 }
1815 
1816 /// Parse a module declaration.
1817 ///
1818 ///   module-declaration:
1819 ///     'extern' 'module' module-id string-literal
1820 ///     'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt]
1821 ///       { module-member* }
1822 ///
1823 ///   module-member:
1824 ///     requires-declaration
1825 ///     header-declaration
1826 ///     submodule-declaration
1827 ///     export-declaration
1828 ///     export-as-declaration
1829 ///     link-declaration
1830 ///
1831 ///   submodule-declaration:
1832 ///     module-declaration
1833 ///     inferred-submodule-declaration
1834 void ModuleMapParser::parseModuleDecl() {
1835   assert(Tok.is(MMToken::ExplicitKeyword) || Tok.is(MMToken::ModuleKeyword) ||
1836          Tok.is(MMToken::FrameworkKeyword) || Tok.is(MMToken::ExternKeyword));
1837   if (Tok.is(MMToken::ExternKeyword)) {
1838     parseExternModuleDecl();
1839     return;
1840   }
1841 
1842   // Parse 'explicit' or 'framework' keyword, if present.
1843   SourceLocation ExplicitLoc;
1844   SourceLocation FrameworkLoc;
1845   bool Explicit = false;
1846   bool Framework = false;
1847 
1848   // Parse 'explicit' keyword, if present.
1849   if (Tok.is(MMToken::ExplicitKeyword)) {
1850     ExplicitLoc = consumeToken();
1851     Explicit = true;
1852   }
1853 
1854   // Parse 'framework' keyword, if present.
1855   if (Tok.is(MMToken::FrameworkKeyword)) {
1856     FrameworkLoc = consumeToken();
1857     Framework = true;
1858   }
1859 
1860   // Parse 'module' keyword.
1861   if (!Tok.is(MMToken::ModuleKeyword)) {
1862     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
1863     consumeToken();
1864     HadError = true;
1865     return;
1866   }
1867   CurrModuleDeclLoc = consumeToken(); // 'module' keyword
1868 
1869   // If we have a wildcard for the module name, this is an inferred submodule.
1870   // Parse it.
1871   if (Tok.is(MMToken::Star))
1872     return parseInferredModuleDecl(Framework, Explicit);
1873 
1874   // Parse the module name.
1875   ModuleId Id;
1876   if (parseModuleId(Id)) {
1877     HadError = true;
1878     return;
1879   }
1880 
1881   if (ActiveModule) {
1882     if (Id.size() > 1) {
1883       Diags.Report(Id.front().second, diag::err_mmap_nested_submodule_id)
1884         << SourceRange(Id.front().second, Id.back().second);
1885 
1886       HadError = true;
1887       return;
1888     }
1889   } else if (Id.size() == 1 && Explicit) {
1890     // Top-level modules can't be explicit.
1891     Diags.Report(ExplicitLoc, diag::err_mmap_explicit_top_level);
1892     Explicit = false;
1893     ExplicitLoc = SourceLocation();
1894     HadError = true;
1895   }
1896 
1897   Module *PreviousActiveModule = ActiveModule;
1898   if (Id.size() > 1) {
1899     // This module map defines a submodule. Go find the module of which it
1900     // is a submodule.
1901     ActiveModule = nullptr;
1902     const Module *TopLevelModule = nullptr;
1903     for (unsigned I = 0, N = Id.size() - 1; I != N; ++I) {
1904       if (Module *Next = Map.lookupModuleQualified(Id[I].first, ActiveModule)) {
1905         if (I == 0)
1906           TopLevelModule = Next;
1907         ActiveModule = Next;
1908         continue;
1909       }
1910 
1911       Diags.Report(Id[I].second, diag::err_mmap_missing_parent_module)
1912           << Id[I].first << (ActiveModule != nullptr)
1913           << (ActiveModule
1914                   ? ActiveModule->getTopLevelModule()->getFullModuleName()
1915                   : "");
1916       HadError = true;
1917     }
1918 
1919     if (TopLevelModule &&
1920         ModuleMapFile != Map.getContainingModuleMapFile(TopLevelModule)) {
1921       assert(ModuleMapFile != Map.getModuleMapFileForUniquing(TopLevelModule) &&
1922              "submodule defined in same file as 'module *' that allowed its "
1923              "top-level module");
1924       Map.addAdditionalModuleMapFile(TopLevelModule, ModuleMapFile);
1925     }
1926   }
1927 
1928   StringRef ModuleName = Id.back().first;
1929   SourceLocation ModuleNameLoc = Id.back().second;
1930 
1931   // Parse the optional attribute list.
1932   Attributes Attrs;
1933   if (parseOptionalAttributes(Attrs))
1934     return;
1935 
1936   // Parse the opening brace.
1937   if (!Tok.is(MMToken::LBrace)) {
1938     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace)
1939       << ModuleName;
1940     HadError = true;
1941     return;
1942   }
1943   SourceLocation LBraceLoc = consumeToken();
1944 
1945   // Determine whether this (sub)module has already been defined.
1946   Module *ShadowingModule = nullptr;
1947   if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) {
1948     // We might see a (re)definition of a module that we already have a
1949     // definition for in two cases:
1950     //  - If we loaded one definition from an AST file and we've just found a
1951     //    corresponding definition in a module map file, or
1952     bool LoadedFromASTFile = Existing->DefinitionLoc.isInvalid();
1953     //  - If we're building a (preprocessed) module and we've just loaded the
1954     //    module map file from which it was created.
1955     bool ParsedAsMainInput =
1956         Map.LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap &&
1957         Map.LangOpts.CurrentModule == ModuleName &&
1958         SourceMgr.getDecomposedLoc(ModuleNameLoc).first !=
1959             SourceMgr.getDecomposedLoc(Existing->DefinitionLoc).first;
1960     if (!ActiveModule && (LoadedFromASTFile || ParsedAsMainInput)) {
1961       // Skip the module definition.
1962       skipUntil(MMToken::RBrace);
1963       if (Tok.is(MMToken::RBrace))
1964         consumeToken();
1965       else {
1966         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1967         Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1968         HadError = true;
1969       }
1970       return;
1971     }
1972 
1973     if (!Existing->Parent && Map.mayShadowNewModule(Existing)) {
1974       ShadowingModule = Existing;
1975     } else {
1976       // This is not a shawdowed module decl, it is an illegal redefinition.
1977       Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition)
1978           << ModuleName;
1979       Diags.Report(Existing->DefinitionLoc, diag::note_mmap_prev_definition);
1980 
1981       // Skip the module definition.
1982       skipUntil(MMToken::RBrace);
1983       if (Tok.is(MMToken::RBrace))
1984         consumeToken();
1985 
1986       HadError = true;
1987       return;
1988     }
1989   }
1990 
1991   // Start defining this module.
1992   if (ShadowingModule) {
1993     ActiveModule =
1994         Map.createShadowedModule(ModuleName, Framework, ShadowingModule);
1995   } else {
1996     ActiveModule =
1997         Map.findOrCreateModule(ModuleName, ActiveModule, Framework, Explicit)
1998             .first;
1999   }
2000 
2001   ActiveModule->DefinitionLoc = ModuleNameLoc;
2002   if (Attrs.IsSystem || IsSystem)
2003     ActiveModule->IsSystem = true;
2004   if (Attrs.IsExternC)
2005     ActiveModule->IsExternC = true;
2006   if (Attrs.NoUndeclaredIncludes ||
2007       (!ActiveModule->Parent && ModuleName == "Darwin"))
2008     ActiveModule->NoUndeclaredIncludes = true;
2009   ActiveModule->Directory = Directory;
2010 
2011   StringRef MapFileName(ModuleMapFile->getName());
2012   if (MapFileName.endswith("module.private.modulemap") ||
2013       MapFileName.endswith("module_private.map")) {
2014     ActiveModule->ModuleMapIsPrivate = true;
2015   }
2016 
2017   // Private modules named as FooPrivate, Foo.Private or similar are likely a
2018   // user error; provide warnings, notes and fixits to direct users to use
2019   // Foo_Private instead.
2020   SourceLocation StartLoc =
2021       SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
2022   if (Map.HeaderInfo.getHeaderSearchOpts().ImplicitModuleMaps &&
2023       !Diags.isIgnored(diag::warn_mmap_mismatched_private_submodule,
2024                        StartLoc) &&
2025       !Diags.isIgnored(diag::warn_mmap_mismatched_private_module_name,
2026                        StartLoc) &&
2027       ActiveModule->ModuleMapIsPrivate)
2028     diagnosePrivateModules(ExplicitLoc, FrameworkLoc);
2029 
2030   bool Done = false;
2031   do {
2032     switch (Tok.Kind) {
2033     case MMToken::EndOfFile:
2034     case MMToken::RBrace:
2035       Done = true;
2036       break;
2037 
2038     case MMToken::ConfigMacros:
2039       parseConfigMacros();
2040       break;
2041 
2042     case MMToken::Conflict:
2043       parseConflict();
2044       break;
2045 
2046     case MMToken::ExplicitKeyword:
2047     case MMToken::ExternKeyword:
2048     case MMToken::FrameworkKeyword:
2049     case MMToken::ModuleKeyword:
2050       parseModuleDecl();
2051       break;
2052 
2053     case MMToken::ExportKeyword:
2054       parseExportDecl();
2055       break;
2056 
2057     case MMToken::ExportAsKeyword:
2058       parseExportAsDecl();
2059       break;
2060 
2061     case MMToken::UseKeyword:
2062       parseUseDecl();
2063       break;
2064 
2065     case MMToken::RequiresKeyword:
2066       parseRequiresDecl();
2067       break;
2068 
2069     case MMToken::TextualKeyword:
2070       parseHeaderDecl(MMToken::TextualKeyword, consumeToken());
2071       break;
2072 
2073     case MMToken::UmbrellaKeyword: {
2074       SourceLocation UmbrellaLoc = consumeToken();
2075       if (Tok.is(MMToken::HeaderKeyword))
2076         parseHeaderDecl(MMToken::UmbrellaKeyword, UmbrellaLoc);
2077       else
2078         parseUmbrellaDirDecl(UmbrellaLoc);
2079       break;
2080     }
2081 
2082     case MMToken::ExcludeKeyword:
2083       parseHeaderDecl(MMToken::ExcludeKeyword, consumeToken());
2084       break;
2085 
2086     case MMToken::PrivateKeyword:
2087       parseHeaderDecl(MMToken::PrivateKeyword, consumeToken());
2088       break;
2089 
2090     case MMToken::HeaderKeyword:
2091       parseHeaderDecl(MMToken::HeaderKeyword, consumeToken());
2092       break;
2093 
2094     case MMToken::LinkKeyword:
2095       parseLinkDecl();
2096       break;
2097 
2098     default:
2099       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member);
2100       consumeToken();
2101       break;
2102     }
2103   } while (!Done);
2104 
2105   if (Tok.is(MMToken::RBrace))
2106     consumeToken();
2107   else {
2108     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
2109     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
2110     HadError = true;
2111   }
2112 
2113   // If the active module is a top-level framework, and there are no link
2114   // libraries, automatically link against the framework.
2115   if (ActiveModule->IsFramework && !ActiveModule->isSubFramework() &&
2116       ActiveModule->LinkLibraries.empty()) {
2117     inferFrameworkLink(ActiveModule, Directory, SourceMgr.getFileManager());
2118   }
2119 
2120   // If the module meets all requirements but is still unavailable, mark the
2121   // whole tree as unavailable to prevent it from building.
2122   if (!ActiveModule->IsAvailable && !ActiveModule->IsUnimportable &&
2123       ActiveModule->Parent) {
2124     ActiveModule->getTopLevelModule()->markUnavailable(/*Unimportable=*/false);
2125     ActiveModule->getTopLevelModule()->MissingHeaders.append(
2126       ActiveModule->MissingHeaders.begin(), ActiveModule->MissingHeaders.end());
2127   }
2128 
2129   // We're done parsing this module. Pop back to the previous module.
2130   ActiveModule = PreviousActiveModule;
2131 }
2132 
2133 /// Parse an extern module declaration.
2134 ///
2135 ///   extern module-declaration:
2136 ///     'extern' 'module' module-id string-literal
2137 void ModuleMapParser::parseExternModuleDecl() {
2138   assert(Tok.is(MMToken::ExternKeyword));
2139   SourceLocation ExternLoc = consumeToken(); // 'extern' keyword
2140 
2141   // Parse 'module' keyword.
2142   if (!Tok.is(MMToken::ModuleKeyword)) {
2143     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
2144     consumeToken();
2145     HadError = true;
2146     return;
2147   }
2148   consumeToken(); // 'module' keyword
2149 
2150   // Parse the module name.
2151   ModuleId Id;
2152   if (parseModuleId(Id)) {
2153     HadError = true;
2154     return;
2155   }
2156 
2157   // Parse the referenced module map file name.
2158   if (!Tok.is(MMToken::StringLiteral)) {
2159     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_mmap_file);
2160     HadError = true;
2161     return;
2162   }
2163   std::string FileName = std::string(Tok.getString());
2164   consumeToken(); // filename
2165 
2166   StringRef FileNameRef = FileName;
2167   SmallString<128> ModuleMapFileName;
2168   if (llvm::sys::path::is_relative(FileNameRef)) {
2169     ModuleMapFileName += Directory->getName();
2170     llvm::sys::path::append(ModuleMapFileName, FileName);
2171     FileNameRef = ModuleMapFileName;
2172   }
2173   if (auto File = SourceMgr.getFileManager().getFile(FileNameRef))
2174     Map.parseModuleMapFile(
2175         *File, IsSystem,
2176         Map.HeaderInfo.getHeaderSearchOpts().ModuleMapFileHomeIsCwd
2177             ? Directory
2178             : (*File)->getDir(),
2179         FileID(), nullptr, ExternLoc);
2180 }
2181 
2182 /// Whether to add the requirement \p Feature to the module \p M.
2183 ///
2184 /// This preserves backwards compatibility for two hacks in the Darwin system
2185 /// module map files:
2186 ///
2187 /// 1. The use of 'requires excluded' to make headers non-modular, which
2188 ///    should really be mapped to 'textual' now that we have this feature.  We
2189 ///    drop the 'excluded' requirement, and set \p IsRequiresExcludedHack to
2190 ///    true.  Later, this bit will be used to map all the headers inside this
2191 ///    module to 'textual'.
2192 ///
2193 ///    This affects Darwin.C.excluded (for assert.h) and Tcl.Private.
2194 ///
2195 /// 2. Removes a bogus cplusplus requirement from IOKit.avc.  This requirement
2196 ///    was never correct and causes issues now that we check it, so drop it.
2197 static bool shouldAddRequirement(Module *M, StringRef Feature,
2198                                  bool &IsRequiresExcludedHack) {
2199   if (Feature == "excluded" &&
2200       (M->fullModuleNameIs({"Darwin", "C", "excluded"}) ||
2201        M->fullModuleNameIs({"Tcl", "Private"}))) {
2202     IsRequiresExcludedHack = true;
2203     return false;
2204   } else if (Feature == "cplusplus" && M->fullModuleNameIs({"IOKit", "avc"})) {
2205     return false;
2206   }
2207 
2208   return true;
2209 }
2210 
2211 /// Parse a requires declaration.
2212 ///
2213 ///   requires-declaration:
2214 ///     'requires' feature-list
2215 ///
2216 ///   feature-list:
2217 ///     feature ',' feature-list
2218 ///     feature
2219 ///
2220 ///   feature:
2221 ///     '!'[opt] identifier
2222 void ModuleMapParser::parseRequiresDecl() {
2223   assert(Tok.is(MMToken::RequiresKeyword));
2224 
2225   // Parse 'requires' keyword.
2226   consumeToken();
2227 
2228   // Parse the feature-list.
2229   do {
2230     bool RequiredState = true;
2231     if (Tok.is(MMToken::Exclaim)) {
2232       RequiredState = false;
2233       consumeToken();
2234     }
2235 
2236     if (!Tok.is(MMToken::Identifier)) {
2237       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_feature);
2238       HadError = true;
2239       return;
2240     }
2241 
2242     // Consume the feature name.
2243     std::string Feature = std::string(Tok.getString());
2244     consumeToken();
2245 
2246     bool IsRequiresExcludedHack = false;
2247     bool ShouldAddRequirement =
2248         shouldAddRequirement(ActiveModule, Feature, IsRequiresExcludedHack);
2249 
2250     if (IsRequiresExcludedHack)
2251       UsesRequiresExcludedHack.insert(ActiveModule);
2252 
2253     if (ShouldAddRequirement) {
2254       // Add this feature.
2255       ActiveModule->addRequirement(Feature, RequiredState, Map.LangOpts,
2256                                    *Map.Target);
2257     }
2258 
2259     if (!Tok.is(MMToken::Comma))
2260       break;
2261 
2262     // Consume the comma.
2263     consumeToken();
2264   } while (true);
2265 }
2266 
2267 /// Parse a header declaration.
2268 ///
2269 ///   header-declaration:
2270 ///     'textual'[opt] 'header' string-literal
2271 ///     'private' 'textual'[opt] 'header' string-literal
2272 ///     'exclude' 'header' string-literal
2273 ///     'umbrella' 'header' string-literal
2274 ///
2275 /// FIXME: Support 'private textual header'.
2276 void ModuleMapParser::parseHeaderDecl(MMToken::TokenKind LeadingToken,
2277                                       SourceLocation LeadingLoc) {
2278   // We've already consumed the first token.
2279   ModuleMap::ModuleHeaderRole Role = ModuleMap::NormalHeader;
2280   if (LeadingToken == MMToken::PrivateKeyword) {
2281     Role = ModuleMap::PrivateHeader;
2282     // 'private' may optionally be followed by 'textual'.
2283     if (Tok.is(MMToken::TextualKeyword)) {
2284       LeadingToken = Tok.Kind;
2285       consumeToken();
2286     }
2287   }
2288 
2289   if (LeadingToken == MMToken::TextualKeyword)
2290     Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
2291 
2292   if (UsesRequiresExcludedHack.count(ActiveModule)) {
2293     // Mark this header 'textual' (see doc comment for
2294     // Module::UsesRequiresExcludedHack).
2295     Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
2296   }
2297 
2298   if (LeadingToken != MMToken::HeaderKeyword) {
2299     if (!Tok.is(MMToken::HeaderKeyword)) {
2300       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
2301           << (LeadingToken == MMToken::PrivateKeyword ? "private" :
2302               LeadingToken == MMToken::ExcludeKeyword ? "exclude" :
2303               LeadingToken == MMToken::TextualKeyword ? "textual" : "umbrella");
2304       return;
2305     }
2306     consumeToken();
2307   }
2308 
2309   // Parse the header name.
2310   if (!Tok.is(MMToken::StringLiteral)) {
2311     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
2312       << "header";
2313     HadError = true;
2314     return;
2315   }
2316   Module::UnresolvedHeaderDirective Header;
2317   Header.FileName = std::string(Tok.getString());
2318   Header.FileNameLoc = consumeToken();
2319   Header.IsUmbrella = LeadingToken == MMToken::UmbrellaKeyword;
2320   Header.Kind =
2321       (LeadingToken == MMToken::ExcludeKeyword ? Module::HK_Excluded
2322                                                : Map.headerRoleToKind(Role));
2323 
2324   // Check whether we already have an umbrella.
2325   if (Header.IsUmbrella && ActiveModule->Umbrella) {
2326     Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash)
2327       << ActiveModule->getFullModuleName();
2328     HadError = true;
2329     return;
2330   }
2331 
2332   // If we were given stat information, parse it so we can skip looking for
2333   // the file.
2334   if (Tok.is(MMToken::LBrace)) {
2335     SourceLocation LBraceLoc = consumeToken();
2336 
2337     while (!Tok.is(MMToken::RBrace) && !Tok.is(MMToken::EndOfFile)) {
2338       enum Attribute { Size, ModTime, Unknown };
2339       StringRef Str = Tok.getString();
2340       SourceLocation Loc = consumeToken();
2341       switch (llvm::StringSwitch<Attribute>(Str)
2342                   .Case("size", Size)
2343                   .Case("mtime", ModTime)
2344                   .Default(Unknown)) {
2345       case Size:
2346         if (Header.Size)
2347           Diags.Report(Loc, diag::err_mmap_duplicate_header_attribute) << Str;
2348         if (!Tok.is(MMToken::IntegerLiteral)) {
2349           Diags.Report(Tok.getLocation(),
2350                        diag::err_mmap_invalid_header_attribute_value) << Str;
2351           skipUntil(MMToken::RBrace);
2352           break;
2353         }
2354         Header.Size = Tok.getInteger();
2355         consumeToken();
2356         break;
2357 
2358       case ModTime:
2359         if (Header.ModTime)
2360           Diags.Report(Loc, diag::err_mmap_duplicate_header_attribute) << Str;
2361         if (!Tok.is(MMToken::IntegerLiteral)) {
2362           Diags.Report(Tok.getLocation(),
2363                        diag::err_mmap_invalid_header_attribute_value) << Str;
2364           skipUntil(MMToken::RBrace);
2365           break;
2366         }
2367         Header.ModTime = Tok.getInteger();
2368         consumeToken();
2369         break;
2370 
2371       case Unknown:
2372         Diags.Report(Loc, diag::err_mmap_expected_header_attribute);
2373         skipUntil(MMToken::RBrace);
2374         break;
2375       }
2376     }
2377 
2378     if (Tok.is(MMToken::RBrace))
2379       consumeToken();
2380     else {
2381       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
2382       Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
2383       HadError = true;
2384     }
2385   }
2386 
2387   bool NeedsFramework = false;
2388   Map.addUnresolvedHeader(ActiveModule, std::move(Header), NeedsFramework);
2389 
2390   if (NeedsFramework && ActiveModule)
2391     Diags.Report(CurrModuleDeclLoc, diag::note_mmap_add_framework_keyword)
2392       << ActiveModule->getFullModuleName()
2393       << FixItHint::CreateReplacement(CurrModuleDeclLoc, "framework module");
2394 }
2395 
2396 static int compareModuleHeaders(const Module::Header *A,
2397                                 const Module::Header *B) {
2398   return A->NameAsWritten.compare(B->NameAsWritten);
2399 }
2400 
2401 /// Parse an umbrella directory declaration.
2402 ///
2403 ///   umbrella-dir-declaration:
2404 ///     umbrella string-literal
2405 void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) {
2406   // Parse the directory name.
2407   if (!Tok.is(MMToken::StringLiteral)) {
2408     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
2409       << "umbrella";
2410     HadError = true;
2411     return;
2412   }
2413 
2414   std::string DirName = std::string(Tok.getString());
2415   std::string DirNameAsWritten = DirName;
2416   SourceLocation DirNameLoc = consumeToken();
2417 
2418   // Check whether we already have an umbrella.
2419   if (ActiveModule->Umbrella) {
2420     Diags.Report(DirNameLoc, diag::err_mmap_umbrella_clash)
2421       << ActiveModule->getFullModuleName();
2422     HadError = true;
2423     return;
2424   }
2425 
2426   // Look for this file.
2427   const DirectoryEntry *Dir = nullptr;
2428   if (llvm::sys::path::is_absolute(DirName)) {
2429     if (auto D = SourceMgr.getFileManager().getDirectory(DirName))
2430       Dir = *D;
2431   } else {
2432     SmallString<128> PathName;
2433     PathName = Directory->getName();
2434     llvm::sys::path::append(PathName, DirName);
2435     if (auto D = SourceMgr.getFileManager().getDirectory(PathName))
2436       Dir = *D;
2437   }
2438 
2439   if (!Dir) {
2440     Diags.Report(DirNameLoc, diag::warn_mmap_umbrella_dir_not_found)
2441       << DirName;
2442     return;
2443   }
2444 
2445   if (UsesRequiresExcludedHack.count(ActiveModule)) {
2446     // Mark this header 'textual' (see doc comment for
2447     // ModuleMapParser::UsesRequiresExcludedHack). Although iterating over the
2448     // directory is relatively expensive, in practice this only applies to the
2449     // uncommonly used Tcl module on Darwin platforms.
2450     std::error_code EC;
2451     SmallVector<Module::Header, 6> Headers;
2452     llvm::vfs::FileSystem &FS =
2453         SourceMgr.getFileManager().getVirtualFileSystem();
2454     for (llvm::vfs::recursive_directory_iterator I(FS, Dir->getName(), EC), E;
2455          I != E && !EC; I.increment(EC)) {
2456       if (auto FE = SourceMgr.getFileManager().getFile(I->path())) {
2457         Module::Header Header = {"", std::string(I->path()), *FE};
2458         Headers.push_back(std::move(Header));
2459       }
2460     }
2461 
2462     // Sort header paths so that the pcm doesn't depend on iteration order.
2463     llvm::array_pod_sort(Headers.begin(), Headers.end(), compareModuleHeaders);
2464 
2465     for (auto &Header : Headers)
2466       Map.addHeader(ActiveModule, std::move(Header), ModuleMap::TextualHeader);
2467     return;
2468   }
2469 
2470   if (Module *OwningModule = Map.UmbrellaDirs[Dir]) {
2471     Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash)
2472       << OwningModule->getFullModuleName();
2473     HadError = true;
2474     return;
2475   }
2476 
2477   // Record this umbrella directory.
2478   Map.setUmbrellaDir(ActiveModule, Dir, DirNameAsWritten, DirName);
2479 }
2480 
2481 /// Parse a module export declaration.
2482 ///
2483 ///   export-declaration:
2484 ///     'export' wildcard-module-id
2485 ///
2486 ///   wildcard-module-id:
2487 ///     identifier
2488 ///     '*'
2489 ///     identifier '.' wildcard-module-id
2490 void ModuleMapParser::parseExportDecl() {
2491   assert(Tok.is(MMToken::ExportKeyword));
2492   SourceLocation ExportLoc = consumeToken();
2493 
2494   // Parse the module-id with an optional wildcard at the end.
2495   ModuleId ParsedModuleId;
2496   bool Wildcard = false;
2497   do {
2498     // FIXME: Support string-literal module names here.
2499     if (Tok.is(MMToken::Identifier)) {
2500       ParsedModuleId.push_back(
2501           std::make_pair(std::string(Tok.getString()), Tok.getLocation()));
2502       consumeToken();
2503 
2504       if (Tok.is(MMToken::Period)) {
2505         consumeToken();
2506         continue;
2507       }
2508 
2509       break;
2510     }
2511 
2512     if(Tok.is(MMToken::Star)) {
2513       Wildcard = true;
2514       consumeToken();
2515       break;
2516     }
2517 
2518     Diags.Report(Tok.getLocation(), diag::err_mmap_module_id);
2519     HadError = true;
2520     return;
2521   } while (true);
2522 
2523   Module::UnresolvedExportDecl Unresolved = {
2524     ExportLoc, ParsedModuleId, Wildcard
2525   };
2526   ActiveModule->UnresolvedExports.push_back(Unresolved);
2527 }
2528 
2529 /// Parse a module export_as declaration.
2530 ///
2531 ///   export-as-declaration:
2532 ///     'export_as' identifier
2533 void ModuleMapParser::parseExportAsDecl() {
2534   assert(Tok.is(MMToken::ExportAsKeyword));
2535   consumeToken();
2536 
2537   if (!Tok.is(MMToken::Identifier)) {
2538     Diags.Report(Tok.getLocation(), diag::err_mmap_module_id);
2539     HadError = true;
2540     return;
2541   }
2542 
2543   if (ActiveModule->Parent) {
2544     Diags.Report(Tok.getLocation(), diag::err_mmap_submodule_export_as);
2545     consumeToken();
2546     return;
2547   }
2548 
2549   if (!ActiveModule->ExportAsModule.empty()) {
2550     if (ActiveModule->ExportAsModule == Tok.getString()) {
2551       Diags.Report(Tok.getLocation(), diag::warn_mmap_redundant_export_as)
2552         << ActiveModule->Name << Tok.getString();
2553     } else {
2554       Diags.Report(Tok.getLocation(), diag::err_mmap_conflicting_export_as)
2555         << ActiveModule->Name << ActiveModule->ExportAsModule
2556         << Tok.getString();
2557     }
2558   }
2559 
2560   ActiveModule->ExportAsModule = std::string(Tok.getString());
2561   Map.addLinkAsDependency(ActiveModule);
2562 
2563   consumeToken();
2564 }
2565 
2566 /// Parse a module use declaration.
2567 ///
2568 ///   use-declaration:
2569 ///     'use' wildcard-module-id
2570 void ModuleMapParser::parseUseDecl() {
2571   assert(Tok.is(MMToken::UseKeyword));
2572   auto KWLoc = consumeToken();
2573   // Parse the module-id.
2574   ModuleId ParsedModuleId;
2575   parseModuleId(ParsedModuleId);
2576 
2577   if (ActiveModule->Parent)
2578     Diags.Report(KWLoc, diag::err_mmap_use_decl_submodule);
2579   else
2580     ActiveModule->UnresolvedDirectUses.push_back(ParsedModuleId);
2581 }
2582 
2583 /// Parse a link declaration.
2584 ///
2585 ///   module-declaration:
2586 ///     'link' 'framework'[opt] string-literal
2587 void ModuleMapParser::parseLinkDecl() {
2588   assert(Tok.is(MMToken::LinkKeyword));
2589   SourceLocation LinkLoc = consumeToken();
2590 
2591   // Parse the optional 'framework' keyword.
2592   bool IsFramework = false;
2593   if (Tok.is(MMToken::FrameworkKeyword)) {
2594     consumeToken();
2595     IsFramework = true;
2596   }
2597 
2598   // Parse the library name
2599   if (!Tok.is(MMToken::StringLiteral)) {
2600     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_library_name)
2601       << IsFramework << SourceRange(LinkLoc);
2602     HadError = true;
2603     return;
2604   }
2605 
2606   std::string LibraryName = std::string(Tok.getString());
2607   consumeToken();
2608   ActiveModule->LinkLibraries.push_back(Module::LinkLibrary(LibraryName,
2609                                                             IsFramework));
2610 }
2611 
2612 /// Parse a configuration macro declaration.
2613 ///
2614 ///   module-declaration:
2615 ///     'config_macros' attributes[opt] config-macro-list?
2616 ///
2617 ///   config-macro-list:
2618 ///     identifier (',' identifier)?
2619 void ModuleMapParser::parseConfigMacros() {
2620   assert(Tok.is(MMToken::ConfigMacros));
2621   SourceLocation ConfigMacrosLoc = consumeToken();
2622 
2623   // Only top-level modules can have configuration macros.
2624   if (ActiveModule->Parent) {
2625     Diags.Report(ConfigMacrosLoc, diag::err_mmap_config_macro_submodule);
2626   }
2627 
2628   // Parse the optional attributes.
2629   Attributes Attrs;
2630   if (parseOptionalAttributes(Attrs))
2631     return;
2632 
2633   if (Attrs.IsExhaustive && !ActiveModule->Parent) {
2634     ActiveModule->ConfigMacrosExhaustive = true;
2635   }
2636 
2637   // If we don't have an identifier, we're done.
2638   // FIXME: Support macros with the same name as a keyword here.
2639   if (!Tok.is(MMToken::Identifier))
2640     return;
2641 
2642   // Consume the first identifier.
2643   if (!ActiveModule->Parent) {
2644     ActiveModule->ConfigMacros.push_back(Tok.getString().str());
2645   }
2646   consumeToken();
2647 
2648   do {
2649     // If there's a comma, consume it.
2650     if (!Tok.is(MMToken::Comma))
2651       break;
2652     consumeToken();
2653 
2654     // We expect to see a macro name here.
2655     // FIXME: Support macros with the same name as a keyword here.
2656     if (!Tok.is(MMToken::Identifier)) {
2657       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_config_macro);
2658       break;
2659     }
2660 
2661     // Consume the macro name.
2662     if (!ActiveModule->Parent) {
2663       ActiveModule->ConfigMacros.push_back(Tok.getString().str());
2664     }
2665     consumeToken();
2666   } while (true);
2667 }
2668 
2669 /// Format a module-id into a string.
2670 static std::string formatModuleId(const ModuleId &Id) {
2671   std::string result;
2672   {
2673     llvm::raw_string_ostream OS(result);
2674 
2675     for (unsigned I = 0, N = Id.size(); I != N; ++I) {
2676       if (I)
2677         OS << ".";
2678       OS << Id[I].first;
2679     }
2680   }
2681 
2682   return result;
2683 }
2684 
2685 /// Parse a conflict declaration.
2686 ///
2687 ///   module-declaration:
2688 ///     'conflict' module-id ',' string-literal
2689 void ModuleMapParser::parseConflict() {
2690   assert(Tok.is(MMToken::Conflict));
2691   SourceLocation ConflictLoc = consumeToken();
2692   Module::UnresolvedConflict Conflict;
2693 
2694   // Parse the module-id.
2695   if (parseModuleId(Conflict.Id))
2696     return;
2697 
2698   // Parse the ','.
2699   if (!Tok.is(MMToken::Comma)) {
2700     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_comma)
2701       << SourceRange(ConflictLoc);
2702     return;
2703   }
2704   consumeToken();
2705 
2706   // Parse the message.
2707   if (!Tok.is(MMToken::StringLiteral)) {
2708     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_message)
2709       << formatModuleId(Conflict.Id);
2710     return;
2711   }
2712   Conflict.Message = Tok.getString().str();
2713   consumeToken();
2714 
2715   // Add this unresolved conflict.
2716   ActiveModule->UnresolvedConflicts.push_back(Conflict);
2717 }
2718 
2719 /// Parse an inferred module declaration (wildcard modules).
2720 ///
2721 ///   module-declaration:
2722 ///     'explicit'[opt] 'framework'[opt] 'module' * attributes[opt]
2723 ///       { inferred-module-member* }
2724 ///
2725 ///   inferred-module-member:
2726 ///     'export' '*'
2727 ///     'exclude' identifier
2728 void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) {
2729   assert(Tok.is(MMToken::Star));
2730   SourceLocation StarLoc = consumeToken();
2731   bool Failed = false;
2732 
2733   // Inferred modules must be submodules.
2734   if (!ActiveModule && !Framework) {
2735     Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule);
2736     Failed = true;
2737   }
2738 
2739   if (ActiveModule) {
2740     // Inferred modules must have umbrella directories.
2741     if (!Failed && ActiveModule->IsAvailable &&
2742         !ActiveModule->getUmbrellaDir()) {
2743       Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella);
2744       Failed = true;
2745     }
2746 
2747     // Check for redefinition of an inferred module.
2748     if (!Failed && ActiveModule->InferSubmodules) {
2749       Diags.Report(StarLoc, diag::err_mmap_inferred_redef);
2750       if (ActiveModule->InferredSubmoduleLoc.isValid())
2751         Diags.Report(ActiveModule->InferredSubmoduleLoc,
2752                      diag::note_mmap_prev_definition);
2753       Failed = true;
2754     }
2755 
2756     // Check for the 'framework' keyword, which is not permitted here.
2757     if (Framework) {
2758       Diags.Report(StarLoc, diag::err_mmap_inferred_framework_submodule);
2759       Framework = false;
2760     }
2761   } else if (Explicit) {
2762     Diags.Report(StarLoc, diag::err_mmap_explicit_inferred_framework);
2763     Explicit = false;
2764   }
2765 
2766   // If there were any problems with this inferred submodule, skip its body.
2767   if (Failed) {
2768     if (Tok.is(MMToken::LBrace)) {
2769       consumeToken();
2770       skipUntil(MMToken::RBrace);
2771       if (Tok.is(MMToken::RBrace))
2772         consumeToken();
2773     }
2774     HadError = true;
2775     return;
2776   }
2777 
2778   // Parse optional attributes.
2779   Attributes Attrs;
2780   if (parseOptionalAttributes(Attrs))
2781     return;
2782 
2783   if (ActiveModule) {
2784     // Note that we have an inferred submodule.
2785     ActiveModule->InferSubmodules = true;
2786     ActiveModule->InferredSubmoduleLoc = StarLoc;
2787     ActiveModule->InferExplicitSubmodules = Explicit;
2788   } else {
2789     // We'll be inferring framework modules for this directory.
2790     Map.InferredDirectories[Directory].InferModules = true;
2791     Map.InferredDirectories[Directory].Attrs = Attrs;
2792     Map.InferredDirectories[Directory].ModuleMapFile = ModuleMapFile;
2793     // FIXME: Handle the 'framework' keyword.
2794   }
2795 
2796   // Parse the opening brace.
2797   if (!Tok.is(MMToken::LBrace)) {
2798     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard);
2799     HadError = true;
2800     return;
2801   }
2802   SourceLocation LBraceLoc = consumeToken();
2803 
2804   // Parse the body of the inferred submodule.
2805   bool Done = false;
2806   do {
2807     switch (Tok.Kind) {
2808     case MMToken::EndOfFile:
2809     case MMToken::RBrace:
2810       Done = true;
2811       break;
2812 
2813     case MMToken::ExcludeKeyword:
2814       if (ActiveModule) {
2815         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2816           << (ActiveModule != nullptr);
2817         consumeToken();
2818         break;
2819       }
2820 
2821       consumeToken();
2822       // FIXME: Support string-literal module names here.
2823       if (!Tok.is(MMToken::Identifier)) {
2824         Diags.Report(Tok.getLocation(), diag::err_mmap_missing_exclude_name);
2825         break;
2826       }
2827 
2828       Map.InferredDirectories[Directory].ExcludedModules.push_back(
2829           std::string(Tok.getString()));
2830       consumeToken();
2831       break;
2832 
2833     case MMToken::ExportKeyword:
2834       if (!ActiveModule) {
2835         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2836           << (ActiveModule != nullptr);
2837         consumeToken();
2838         break;
2839       }
2840 
2841       consumeToken();
2842       if (Tok.is(MMToken::Star))
2843         ActiveModule->InferExportWildcard = true;
2844       else
2845         Diags.Report(Tok.getLocation(),
2846                      diag::err_mmap_expected_export_wildcard);
2847       consumeToken();
2848       break;
2849 
2850     case MMToken::ExplicitKeyword:
2851     case MMToken::ModuleKeyword:
2852     case MMToken::HeaderKeyword:
2853     case MMToken::PrivateKeyword:
2854     case MMToken::UmbrellaKeyword:
2855     default:
2856       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2857           << (ActiveModule != nullptr);
2858       consumeToken();
2859       break;
2860     }
2861   } while (!Done);
2862 
2863   if (Tok.is(MMToken::RBrace))
2864     consumeToken();
2865   else {
2866     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
2867     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
2868     HadError = true;
2869   }
2870 }
2871 
2872 /// Parse optional attributes.
2873 ///
2874 ///   attributes:
2875 ///     attribute attributes
2876 ///     attribute
2877 ///
2878 ///   attribute:
2879 ///     [ identifier ]
2880 ///
2881 /// \param Attrs Will be filled in with the parsed attributes.
2882 ///
2883 /// \returns true if an error occurred, false otherwise.
2884 bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) {
2885   bool HadError = false;
2886 
2887   while (Tok.is(MMToken::LSquare)) {
2888     // Consume the '['.
2889     SourceLocation LSquareLoc = consumeToken();
2890 
2891     // Check whether we have an attribute name here.
2892     if (!Tok.is(MMToken::Identifier)) {
2893       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_attribute);
2894       skipUntil(MMToken::RSquare);
2895       if (Tok.is(MMToken::RSquare))
2896         consumeToken();
2897       HadError = true;
2898     }
2899 
2900     // Decode the attribute name.
2901     AttributeKind Attribute
2902       = llvm::StringSwitch<AttributeKind>(Tok.getString())
2903           .Case("exhaustive", AT_exhaustive)
2904           .Case("extern_c", AT_extern_c)
2905           .Case("no_undeclared_includes", AT_no_undeclared_includes)
2906           .Case("system", AT_system)
2907           .Default(AT_unknown);
2908     switch (Attribute) {
2909     case AT_unknown:
2910       Diags.Report(Tok.getLocation(), diag::warn_mmap_unknown_attribute)
2911         << Tok.getString();
2912       break;
2913 
2914     case AT_system:
2915       Attrs.IsSystem = true;
2916       break;
2917 
2918     case AT_extern_c:
2919       Attrs.IsExternC = true;
2920       break;
2921 
2922     case AT_exhaustive:
2923       Attrs.IsExhaustive = true;
2924       break;
2925 
2926     case AT_no_undeclared_includes:
2927       Attrs.NoUndeclaredIncludes = true;
2928       break;
2929     }
2930     consumeToken();
2931 
2932     // Consume the ']'.
2933     if (!Tok.is(MMToken::RSquare)) {
2934       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rsquare);
2935       Diags.Report(LSquareLoc, diag::note_mmap_lsquare_match);
2936       skipUntil(MMToken::RSquare);
2937       HadError = true;
2938     }
2939 
2940     if (Tok.is(MMToken::RSquare))
2941       consumeToken();
2942   }
2943 
2944   return HadError;
2945 }
2946 
2947 /// Parse a module map file.
2948 ///
2949 ///   module-map-file:
2950 ///     module-declaration*
2951 bool ModuleMapParser::parseModuleMapFile() {
2952   do {
2953     switch (Tok.Kind) {
2954     case MMToken::EndOfFile:
2955       return HadError;
2956 
2957     case MMToken::ExplicitKeyword:
2958     case MMToken::ExternKeyword:
2959     case MMToken::ModuleKeyword:
2960     case MMToken::FrameworkKeyword:
2961       parseModuleDecl();
2962       break;
2963 
2964     case MMToken::Comma:
2965     case MMToken::ConfigMacros:
2966     case MMToken::Conflict:
2967     case MMToken::Exclaim:
2968     case MMToken::ExcludeKeyword:
2969     case MMToken::ExportKeyword:
2970     case MMToken::ExportAsKeyword:
2971     case MMToken::HeaderKeyword:
2972     case MMToken::Identifier:
2973     case MMToken::LBrace:
2974     case MMToken::LinkKeyword:
2975     case MMToken::LSquare:
2976     case MMToken::Period:
2977     case MMToken::PrivateKeyword:
2978     case MMToken::RBrace:
2979     case MMToken::RSquare:
2980     case MMToken::RequiresKeyword:
2981     case MMToken::Star:
2982     case MMToken::StringLiteral:
2983     case MMToken::IntegerLiteral:
2984     case MMToken::TextualKeyword:
2985     case MMToken::UmbrellaKeyword:
2986     case MMToken::UseKeyword:
2987       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
2988       HadError = true;
2989       consumeToken();
2990       break;
2991     }
2992   } while (true);
2993 }
2994 
2995 bool ModuleMap::parseModuleMapFile(const FileEntry *File, bool IsSystem,
2996                                    const DirectoryEntry *Dir, FileID ID,
2997                                    unsigned *Offset,
2998                                    SourceLocation ExternModuleLoc) {
2999   assert(Target && "Missing target information");
3000   llvm::DenseMap<const FileEntry *, bool>::iterator Known
3001     = ParsedModuleMap.find(File);
3002   if (Known != ParsedModuleMap.end())
3003     return Known->second;
3004 
3005   // If the module map file wasn't already entered, do so now.
3006   if (ID.isInvalid()) {
3007     auto FileCharacter =
3008         IsSystem ? SrcMgr::C_System_ModuleMap : SrcMgr::C_User_ModuleMap;
3009     ID = SourceMgr.createFileID(File, ExternModuleLoc, FileCharacter);
3010   }
3011 
3012   assert(Target && "Missing target information");
3013   llvm::Optional<llvm::MemoryBufferRef> Buffer = SourceMgr.getBufferOrNone(ID);
3014   if (!Buffer)
3015     return ParsedModuleMap[File] = true;
3016   assert((!Offset || *Offset <= Buffer->getBufferSize()) &&
3017          "invalid buffer offset");
3018 
3019   // Parse this module map file.
3020   Lexer L(SourceMgr.getLocForStartOfFile(ID), MMapLangOpts,
3021           Buffer->getBufferStart(),
3022           Buffer->getBufferStart() + (Offset ? *Offset : 0),
3023           Buffer->getBufferEnd());
3024   SourceLocation Start = L.getSourceLocation();
3025   ModuleMapParser Parser(L, SourceMgr, Target, Diags, *this, File, Dir,
3026                          IsSystem);
3027   bool Result = Parser.parseModuleMapFile();
3028   ParsedModuleMap[File] = Result;
3029 
3030   if (Offset) {
3031     auto Loc = SourceMgr.getDecomposedLoc(Parser.getLocation());
3032     assert(Loc.first == ID && "stopped in a different file?");
3033     *Offset = Loc.second;
3034   }
3035 
3036   // Notify callbacks that we parsed it.
3037   for (const auto &Cb : Callbacks)
3038     Cb->moduleMapFileRead(Start, *File, IsSystem);
3039 
3040   return Result;
3041 }
3042