xref: /llvm-project/clang/lib/Lex/ModuleMap.cpp (revision 8f4ea36bfe4caf7d08f9778ee2a347b78f02bc0f)
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 (StringRef Framework : llvm::drop_begin(llvm::reverse(Paths)))
171     llvm::sys::path::append(Path, "Frameworks", Framework + ".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, /*File=*/llvm::None);
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 (const DirectoryEntry *SkippedDir : llvm::reverse(SkippedDirs)) {
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(SkippedDir->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[SkippedDir] = 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 (const DirectoryEntry *SkippedDir : llvm::reverse(SkippedDirs)) {
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(SkippedDir->getName()), NameBuf);
753           Found = lookupModuleQualified(Name, Found);
754           if (!Found)
755             return false;
756           if (IsUnavailable(Found))
757             return true;
758         }
759 
760         // Infer a submodule with the same name as this header file.
761         SmallString<32> NameBuf;
762         StringRef Name = sanitizeFilenameAsIdentifier(
763                            llvm::sys::path::stem(Header->getName()),
764                            NameBuf);
765         Found = lookupModuleQualified(Name, Found);
766         if (!Found)
767           return false;
768       }
769 
770       return IsUnavailable(Found);
771     }
772 
773     SkippedDirs.push_back(Dir);
774 
775     // Retrieve our parent path.
776     DirName = llvm::sys::path::parent_path(DirName);
777     if (DirName.empty())
778       break;
779 
780     // Resolve the parent path to a directory entry.
781     if (auto DirEntry = SourceMgr.getFileManager().getDirectory(DirName))
782       Dir = *DirEntry;
783     else
784       Dir = nullptr;
785   } while (Dir);
786 
787   return false;
788 }
789 
790 Module *ModuleMap::findModule(StringRef Name) const {
791   llvm::StringMap<Module *>::const_iterator Known = Modules.find(Name);
792   if (Known != Modules.end())
793     return Known->getValue();
794 
795   return nullptr;
796 }
797 
798 Module *ModuleMap::lookupModuleUnqualified(StringRef Name,
799                                            Module *Context) const {
800   for(; Context; Context = Context->Parent) {
801     if (Module *Sub = lookupModuleQualified(Name, Context))
802       return Sub;
803   }
804 
805   return findModule(Name);
806 }
807 
808 Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) const{
809   if (!Context)
810     return findModule(Name);
811 
812   return Context->findSubmodule(Name);
813 }
814 
815 std::pair<Module *, bool> ModuleMap::findOrCreateModule(StringRef Name,
816                                                         Module *Parent,
817                                                         bool IsFramework,
818                                                         bool IsExplicit) {
819   // Try to find an existing module with this name.
820   if (Module *Sub = lookupModuleQualified(Name, Parent))
821     return std::make_pair(Sub, false);
822 
823   // Create a new module with this name.
824   Module *Result = new Module(Name, SourceLocation(), Parent, IsFramework,
825                               IsExplicit, NumCreatedModules++);
826   if (!Parent) {
827     if (LangOpts.CurrentModule == Name)
828       SourceModule = Result;
829     Modules[Name] = Result;
830     ModuleScopeIDs[Result] = CurrentModuleScopeID;
831   }
832   return std::make_pair(Result, true);
833 }
834 
835 Module *ModuleMap::createGlobalModuleFragmentForModuleUnit(SourceLocation Loc,
836                                                            Module *Parent) {
837   auto *Result = new Module("<global>", Loc, Parent, /*IsFramework*/ false,
838                             /*IsExplicit*/ true, NumCreatedModules++);
839   Result->Kind = Module::GlobalModuleFragment;
840   // If the created module isn't owned by a parent, send it to PendingSubmodules
841   // to wait for its parent.
842   if (!Result->Parent)
843     PendingSubmodules.emplace_back(Result);
844   return Result;
845 }
846 
847 Module *
848 ModuleMap::createPrivateModuleFragmentForInterfaceUnit(Module *Parent,
849                                                        SourceLocation Loc) {
850   auto *Result =
851       new Module("<private>", Loc, Parent, /*IsFramework*/ false,
852                  /*IsExplicit*/ true, NumCreatedModules++);
853   Result->Kind = Module::PrivateModuleFragment;
854   return Result;
855 }
856 
857 Module *ModuleMap::createModuleForInterfaceUnit(SourceLocation Loc,
858                                                 StringRef Name,
859                                                 Module *GlobalModule) {
860   assert(LangOpts.CurrentModule == Name && "module name mismatch");
861   assert(!Modules[Name] && "redefining existing module");
862 
863   auto *Result =
864       new Module(Name, Loc, nullptr, /*IsFramework*/ false,
865                  /*IsExplicit*/ false, NumCreatedModules++);
866   Result->Kind = Module::ModuleInterfaceUnit;
867   Modules[Name] = SourceModule = Result;
868 
869   // Reparent the current global module fragment as a submodule of this module.
870   for (auto &Submodule : PendingSubmodules) {
871     Submodule->setParent(Result);
872     Submodule.release(); // now owned by parent
873   }
874   PendingSubmodules.clear();
875 
876   // Mark the main source file as being within the newly-created module so that
877   // declarations and macros are properly visibility-restricted to it.
878   auto *MainFile = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
879   assert(MainFile && "no input file for module interface");
880   Headers[MainFile].push_back(KnownHeader(Result, PrivateHeader));
881 
882   return Result;
883 }
884 
885 Module *ModuleMap::createHeaderModule(StringRef Name,
886                                       ArrayRef<Module::Header> Headers) {
887   assert(LangOpts.CurrentModule == Name && "module name mismatch");
888   assert(!Modules[Name] && "redefining existing module");
889 
890   auto *Result =
891       new Module(Name, SourceLocation(), nullptr, /*IsFramework*/ false,
892                  /*IsExplicit*/ false, NumCreatedModules++);
893   Result->Kind = Module::ModuleInterfaceUnit;
894   Modules[Name] = SourceModule = Result;
895 
896   for (const Module::Header &H : Headers) {
897     auto *M = new Module(H.NameAsWritten, SourceLocation(), Result,
898                          /*IsFramework*/ false,
899                          /*IsExplicit*/ true, NumCreatedModules++);
900     // Header modules are implicitly 'export *'.
901     M->Exports.push_back(Module::ExportDecl(nullptr, true));
902     addHeader(M, H, NormalHeader);
903   }
904 
905   return Result;
906 }
907 
908 /// For a framework module, infer the framework against which we
909 /// should link.
910 static void inferFrameworkLink(Module *Mod, const DirectoryEntry *FrameworkDir,
911                                FileManager &FileMgr) {
912   assert(Mod->IsFramework && "Can only infer linking for framework modules");
913   assert(!Mod->isSubFramework() &&
914          "Can only infer linking for top-level frameworks");
915 
916   SmallString<128> LibName;
917   LibName += FrameworkDir->getName();
918   llvm::sys::path::append(LibName, Mod->Name);
919 
920   // The library name of a framework has more than one possible extension since
921   // the introduction of the text-based dynamic library format. We need to check
922   // for both before we give up.
923   for (const char *extension : {"", ".tbd"}) {
924     llvm::sys::path::replace_extension(LibName, extension);
925     if (FileMgr.getFile(LibName)) {
926       Mod->LinkLibraries.push_back(Module::LinkLibrary(Mod->Name,
927                                                        /*IsFramework=*/true));
928       return;
929     }
930   }
931 }
932 
933 Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
934                                         bool IsSystem, Module *Parent) {
935   Attributes Attrs;
936   Attrs.IsSystem = IsSystem;
937   return inferFrameworkModule(FrameworkDir, Attrs, Parent);
938 }
939 
940 Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
941                                         Attributes Attrs, Module *Parent) {
942   // Note: as an egregious but useful hack we use the real path here, because
943   // we might be looking at an embedded framework that symlinks out to a
944   // top-level framework, and we need to infer as if we were naming the
945   // top-level framework.
946   StringRef FrameworkDirName =
947       SourceMgr.getFileManager().getCanonicalName(FrameworkDir);
948 
949   // In case this is a case-insensitive filesystem, use the canonical
950   // directory name as the ModuleName, since modules are case-sensitive.
951   // FIXME: we should be able to give a fix-it hint for the correct spelling.
952   SmallString<32> ModuleNameStorage;
953   StringRef ModuleName = sanitizeFilenameAsIdentifier(
954       llvm::sys::path::stem(FrameworkDirName), ModuleNameStorage);
955 
956   // Check whether we've already found this module.
957   if (Module *Mod = lookupModuleQualified(ModuleName, Parent))
958     return Mod;
959 
960   FileManager &FileMgr = SourceMgr.getFileManager();
961 
962   // If the framework has a parent path from which we're allowed to infer
963   // a framework module, do so.
964   const FileEntry *ModuleMapFile = nullptr;
965   if (!Parent) {
966     // Determine whether we're allowed to infer a module map.
967     bool canInfer = false;
968     if (llvm::sys::path::has_parent_path(FrameworkDirName)) {
969       // Figure out the parent path.
970       StringRef Parent = llvm::sys::path::parent_path(FrameworkDirName);
971       if (auto ParentDir = FileMgr.getDirectory(Parent)) {
972         // Check whether we have already looked into the parent directory
973         // for a module map.
974         llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
975           inferred = InferredDirectories.find(*ParentDir);
976         if (inferred == InferredDirectories.end()) {
977           // We haven't looked here before. Load a module map, if there is
978           // one.
979           bool IsFrameworkDir = Parent.endswith(".framework");
980           if (const FileEntry *ModMapFile =
981                 HeaderInfo.lookupModuleMapFile(*ParentDir, IsFrameworkDir)) {
982             parseModuleMapFile(ModMapFile, Attrs.IsSystem, *ParentDir);
983             inferred = InferredDirectories.find(*ParentDir);
984           }
985 
986           if (inferred == InferredDirectories.end())
987             inferred = InferredDirectories.insert(
988                          std::make_pair(*ParentDir, InferredDirectory())).first;
989         }
990 
991         if (inferred->second.InferModules) {
992           // We're allowed to infer for this directory, but make sure it's okay
993           // to infer this particular module.
994           StringRef Name = llvm::sys::path::stem(FrameworkDirName);
995           canInfer =
996               !llvm::is_contained(inferred->second.ExcludedModules, Name);
997 
998           Attrs.IsSystem |= inferred->second.Attrs.IsSystem;
999           Attrs.IsExternC |= inferred->second.Attrs.IsExternC;
1000           Attrs.IsExhaustive |= inferred->second.Attrs.IsExhaustive;
1001           Attrs.NoUndeclaredIncludes |=
1002               inferred->second.Attrs.NoUndeclaredIncludes;
1003           ModuleMapFile = inferred->second.ModuleMapFile;
1004         }
1005       }
1006     }
1007 
1008     // If we're not allowed to infer a framework module, don't.
1009     if (!canInfer)
1010       return nullptr;
1011   } else
1012     ModuleMapFile = getModuleMapFileForUniquing(Parent);
1013 
1014 
1015   // Look for an umbrella header.
1016   SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName());
1017   llvm::sys::path::append(UmbrellaName, "Headers", ModuleName + ".h");
1018   auto UmbrellaHeader = FileMgr.getFile(UmbrellaName);
1019 
1020   // FIXME: If there's no umbrella header, we could probably scan the
1021   // framework to load *everything*. But, it's not clear that this is a good
1022   // idea.
1023   if (!UmbrellaHeader)
1024     return nullptr;
1025 
1026   Module *Result = new Module(ModuleName, SourceLocation(), Parent,
1027                               /*IsFramework=*/true, /*IsExplicit=*/false,
1028                               NumCreatedModules++);
1029   InferredModuleAllowedBy[Result] = ModuleMapFile;
1030   Result->IsInferred = true;
1031   if (!Parent) {
1032     if (LangOpts.CurrentModule == ModuleName)
1033       SourceModule = Result;
1034     Modules[ModuleName] = Result;
1035     ModuleScopeIDs[Result] = CurrentModuleScopeID;
1036   }
1037 
1038   Result->IsSystem |= Attrs.IsSystem;
1039   Result->IsExternC |= Attrs.IsExternC;
1040   Result->ConfigMacrosExhaustive |= Attrs.IsExhaustive;
1041   Result->NoUndeclaredIncludes |= Attrs.NoUndeclaredIncludes;
1042   Result->Directory = FrameworkDir;
1043 
1044   // Chop off the first framework bit, as that is implied.
1045   StringRef RelativePath = UmbrellaName.str().substr(
1046       Result->getTopLevelModule()->Directory->getName().size());
1047   RelativePath = llvm::sys::path::relative_path(RelativePath);
1048 
1049   // umbrella header "umbrella-header-name"
1050   setUmbrellaHeader(Result, *UmbrellaHeader, ModuleName + ".h", RelativePath);
1051 
1052   // export *
1053   Result->Exports.push_back(Module::ExportDecl(nullptr, true));
1054 
1055   // module * { export * }
1056   Result->InferSubmodules = true;
1057   Result->InferExportWildcard = true;
1058 
1059   // Look for subframeworks.
1060   std::error_code EC;
1061   SmallString<128> SubframeworksDirName
1062     = StringRef(FrameworkDir->getName());
1063   llvm::sys::path::append(SubframeworksDirName, "Frameworks");
1064   llvm::sys::path::native(SubframeworksDirName);
1065   llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
1066   for (llvm::vfs::directory_iterator
1067            Dir = FS.dir_begin(SubframeworksDirName, EC),
1068            DirEnd;
1069        Dir != DirEnd && !EC; Dir.increment(EC)) {
1070     if (!StringRef(Dir->path()).endswith(".framework"))
1071       continue;
1072 
1073     if (auto SubframeworkDir =
1074             FileMgr.getDirectory(Dir->path())) {
1075       // Note: as an egregious but useful hack, we use the real path here and
1076       // check whether it is actually a subdirectory of the parent directory.
1077       // This will not be the case if the 'subframework' is actually a symlink
1078       // out to a top-level framework.
1079       StringRef SubframeworkDirName =
1080           FileMgr.getCanonicalName(*SubframeworkDir);
1081       bool FoundParent = false;
1082       do {
1083         // Get the parent directory name.
1084         SubframeworkDirName
1085           = llvm::sys::path::parent_path(SubframeworkDirName);
1086         if (SubframeworkDirName.empty())
1087           break;
1088 
1089         if (auto SubDir = FileMgr.getDirectory(SubframeworkDirName)) {
1090           if (*SubDir == FrameworkDir) {
1091             FoundParent = true;
1092             break;
1093           }
1094         }
1095       } while (true);
1096 
1097       if (!FoundParent)
1098         continue;
1099 
1100       // FIXME: Do we want to warn about subframeworks without umbrella headers?
1101       inferFrameworkModule(*SubframeworkDir, Attrs, Result);
1102     }
1103   }
1104 
1105   // If the module is a top-level framework, automatically link against the
1106   // framework.
1107   if (!Result->isSubFramework()) {
1108     inferFrameworkLink(Result, FrameworkDir, FileMgr);
1109   }
1110 
1111   return Result;
1112 }
1113 
1114 Module *ModuleMap::createShadowedModule(StringRef Name, bool IsFramework,
1115                                         Module *ShadowingModule) {
1116 
1117   // Create a new module with this name.
1118   Module *Result =
1119       new Module(Name, SourceLocation(), /*Parent=*/nullptr, IsFramework,
1120                  /*IsExplicit=*/false, NumCreatedModules++);
1121   Result->ShadowingModule = ShadowingModule;
1122   Result->markUnavailable(/*Unimportable*/true);
1123   ModuleScopeIDs[Result] = CurrentModuleScopeID;
1124   ShadowModules.push_back(Result);
1125 
1126   return Result;
1127 }
1128 
1129 void ModuleMap::setUmbrellaHeader(
1130     Module *Mod, const FileEntry *UmbrellaHeader, const Twine &NameAsWritten,
1131     const Twine &PathRelativeToRootModuleDirectory) {
1132   Headers[UmbrellaHeader].push_back(KnownHeader(Mod, NormalHeader));
1133   Mod->Umbrella = UmbrellaHeader;
1134   Mod->UmbrellaAsWritten = NameAsWritten.str();
1135   Mod->UmbrellaRelativeToRootModuleDirectory =
1136       PathRelativeToRootModuleDirectory.str();
1137   UmbrellaDirs[UmbrellaHeader->getDir()] = Mod;
1138 
1139   // Notify callbacks that we just added a new header.
1140   for (const auto &Cb : Callbacks)
1141     Cb->moduleMapAddUmbrellaHeader(&SourceMgr.getFileManager(), UmbrellaHeader);
1142 }
1143 
1144 void ModuleMap::setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir,
1145                                const Twine &NameAsWritten,
1146                                const Twine &PathRelativeToRootModuleDirectory) {
1147   Mod->Umbrella = UmbrellaDir;
1148   Mod->UmbrellaAsWritten = NameAsWritten.str();
1149   Mod->UmbrellaRelativeToRootModuleDirectory =
1150       PathRelativeToRootModuleDirectory.str();
1151   UmbrellaDirs[UmbrellaDir] = Mod;
1152 }
1153 
1154 void ModuleMap::addUnresolvedHeader(Module *Mod,
1155                                     Module::UnresolvedHeaderDirective Header,
1156                                     bool &NeedsFramework) {
1157   // If there is a builtin counterpart to this file, add it now so it can
1158   // wrap the system header.
1159   if (resolveAsBuiltinHeader(Mod, Header)) {
1160     // If we have both a builtin and system version of the file, the
1161     // builtin version may want to inject macros into the system header, so
1162     // force the system header to be treated as a textual header in this
1163     // case.
1164     Header.Kind = headerRoleToKind(ModuleMap::ModuleHeaderRole(
1165         headerKindToRole(Header.Kind) | ModuleMap::TextualHeader));
1166     Header.HasBuiltinHeader = true;
1167   }
1168 
1169   // If possible, don't stat the header until we need to. This requires the
1170   // user to have provided us with some stat information about the file.
1171   // FIXME: Add support for lazily stat'ing umbrella headers and excluded
1172   // headers.
1173   if ((Header.Size || Header.ModTime) && !Header.IsUmbrella &&
1174       Header.Kind != Module::HK_Excluded) {
1175     // We expect more variation in mtime than size, so if we're given both,
1176     // use the mtime as the key.
1177     if (Header.ModTime)
1178       LazyHeadersByModTime[*Header.ModTime].push_back(Mod);
1179     else
1180       LazyHeadersBySize[*Header.Size].push_back(Mod);
1181     Mod->UnresolvedHeaders.push_back(Header);
1182     return;
1183   }
1184 
1185   // We don't have stat information or can't defer looking this file up.
1186   // Perform the lookup now.
1187   resolveHeader(Mod, Header, NeedsFramework);
1188 }
1189 
1190 void ModuleMap::resolveHeaderDirectives(const FileEntry *File) const {
1191   auto BySize = LazyHeadersBySize.find(File->getSize());
1192   if (BySize != LazyHeadersBySize.end()) {
1193     for (auto *M : BySize->second)
1194       resolveHeaderDirectives(M, File);
1195     LazyHeadersBySize.erase(BySize);
1196   }
1197 
1198   auto ByModTime = LazyHeadersByModTime.find(File->getModificationTime());
1199   if (ByModTime != LazyHeadersByModTime.end()) {
1200     for (auto *M : ByModTime->second)
1201       resolveHeaderDirectives(M, File);
1202     LazyHeadersByModTime.erase(ByModTime);
1203   }
1204 }
1205 
1206 void ModuleMap::resolveHeaderDirectives(
1207     Module *Mod, llvm::Optional<const FileEntry *> File) const {
1208   bool NeedsFramework = false;
1209   SmallVector<Module::UnresolvedHeaderDirective, 1> NewHeaders;
1210   const auto Size = File ? File.getValue()->getSize() : 0;
1211   const auto ModTime = File ? File.getValue()->getModificationTime() : 0;
1212 
1213   for (auto &Header : Mod->UnresolvedHeaders) {
1214     if (File && ((Header.ModTime && Header.ModTime != ModTime) ||
1215                  (Header.Size && Header.Size != Size)))
1216       NewHeaders.push_back(Header);
1217     else
1218       // This operation is logically const; we're just changing how we represent
1219       // the header information for this file.
1220       const_cast<ModuleMap *>(this)->resolveHeader(Mod, Header, NeedsFramework);
1221   }
1222   Mod->UnresolvedHeaders.swap(NewHeaders);
1223 }
1224 
1225 void ModuleMap::addHeader(Module *Mod, Module::Header Header,
1226                           ModuleHeaderRole Role, bool Imported) {
1227   KnownHeader KH(Mod, Role);
1228 
1229   // Only add each header to the headers list once.
1230   // FIXME: Should we diagnose if a header is listed twice in the
1231   // same module definition?
1232   auto &HeaderList = Headers[Header.Entry];
1233   if (llvm::is_contained(HeaderList, KH))
1234     return;
1235 
1236   HeaderList.push_back(KH);
1237   Mod->Headers[headerRoleToKind(Role)].push_back(Header);
1238 
1239   bool isCompilingModuleHeader =
1240       LangOpts.isCompilingModule() && Mod->getTopLevelModule() == SourceModule;
1241   if (!Imported || isCompilingModuleHeader) {
1242     // When we import HeaderFileInfo, the external source is expected to
1243     // set the isModuleHeader flag itself.
1244     HeaderInfo.MarkFileModuleHeader(Header.Entry, Role,
1245                                     isCompilingModuleHeader);
1246   }
1247 
1248   // Notify callbacks that we just added a new header.
1249   for (const auto &Cb : Callbacks)
1250     Cb->moduleMapAddHeader(Header.Entry->getName());
1251 }
1252 
1253 void ModuleMap::excludeHeader(Module *Mod, Module::Header Header) {
1254   // Add this as a known header so we won't implicitly add it to any
1255   // umbrella directory module.
1256   // FIXME: Should we only exclude it from umbrella modules within the
1257   // specified module?
1258   (void) Headers[Header.Entry];
1259 
1260   Mod->Headers[Module::HK_Excluded].push_back(std::move(Header));
1261 }
1262 
1263 const FileEntry *
1264 ModuleMap::getContainingModuleMapFile(const Module *Module) const {
1265   if (Module->DefinitionLoc.isInvalid())
1266     return nullptr;
1267 
1268   return SourceMgr.getFileEntryForID(
1269            SourceMgr.getFileID(Module->DefinitionLoc));
1270 }
1271 
1272 const FileEntry *ModuleMap::getModuleMapFileForUniquing(const Module *M) const {
1273   if (M->IsInferred) {
1274     assert(InferredModuleAllowedBy.count(M) && "missing inferred module map");
1275     return InferredModuleAllowedBy.find(M)->second;
1276   }
1277   return getContainingModuleMapFile(M);
1278 }
1279 
1280 void ModuleMap::setInferredModuleAllowedBy(Module *M, const FileEntry *ModMap) {
1281   assert(M->IsInferred && "module not inferred");
1282   InferredModuleAllowedBy[M] = ModMap;
1283 }
1284 
1285 void ModuleMap::addAdditionalModuleMapFile(const Module *M,
1286                                            const FileEntry *ModuleMap) {
1287   AdditionalModMaps[M].insert(ModuleMap);
1288 }
1289 
1290 LLVM_DUMP_METHOD void ModuleMap::dump() {
1291   llvm::errs() << "Modules:";
1292   for (llvm::StringMap<Module *>::iterator M = Modules.begin(),
1293                                         MEnd = Modules.end();
1294        M != MEnd; ++M)
1295     M->getValue()->print(llvm::errs(), 2);
1296 
1297   llvm::errs() << "Headers:";
1298   for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end();
1299        H != HEnd; ++H) {
1300     llvm::errs() << "  \"" << H->first->getName() << "\" -> ";
1301     for (SmallVectorImpl<KnownHeader>::const_iterator I = H->second.begin(),
1302                                                       E = H->second.end();
1303          I != E; ++I) {
1304       if (I != H->second.begin())
1305         llvm::errs() << ",";
1306       llvm::errs() << I->getModule()->getFullModuleName();
1307     }
1308     llvm::errs() << "\n";
1309   }
1310 }
1311 
1312 bool ModuleMap::resolveExports(Module *Mod, bool Complain) {
1313   auto Unresolved = std::move(Mod->UnresolvedExports);
1314   Mod->UnresolvedExports.clear();
1315   for (auto &UE : Unresolved) {
1316     Module::ExportDecl Export = resolveExport(Mod, UE, Complain);
1317     if (Export.getPointer() || Export.getInt())
1318       Mod->Exports.push_back(Export);
1319     else
1320       Mod->UnresolvedExports.push_back(UE);
1321   }
1322   return !Mod->UnresolvedExports.empty();
1323 }
1324 
1325 bool ModuleMap::resolveUses(Module *Mod, bool Complain) {
1326   auto Unresolved = std::move(Mod->UnresolvedDirectUses);
1327   Mod->UnresolvedDirectUses.clear();
1328   for (auto &UDU : Unresolved) {
1329     Module *DirectUse = resolveModuleId(UDU, Mod, Complain);
1330     if (DirectUse)
1331       Mod->DirectUses.push_back(DirectUse);
1332     else
1333       Mod->UnresolvedDirectUses.push_back(UDU);
1334   }
1335   return !Mod->UnresolvedDirectUses.empty();
1336 }
1337 
1338 bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) {
1339   auto Unresolved = std::move(Mod->UnresolvedConflicts);
1340   Mod->UnresolvedConflicts.clear();
1341   for (auto &UC : Unresolved) {
1342     if (Module *OtherMod = resolveModuleId(UC.Id, Mod, Complain)) {
1343       Module::Conflict Conflict;
1344       Conflict.Other = OtherMod;
1345       Conflict.Message = UC.Message;
1346       Mod->Conflicts.push_back(Conflict);
1347     } else
1348       Mod->UnresolvedConflicts.push_back(UC);
1349   }
1350   return !Mod->UnresolvedConflicts.empty();
1351 }
1352 
1353 //----------------------------------------------------------------------------//
1354 // Module map file parser
1355 //----------------------------------------------------------------------------//
1356 
1357 namespace clang {
1358 
1359   /// A token in a module map file.
1360   struct MMToken {
1361     enum TokenKind {
1362       Comma,
1363       ConfigMacros,
1364       Conflict,
1365       EndOfFile,
1366       HeaderKeyword,
1367       Identifier,
1368       Exclaim,
1369       ExcludeKeyword,
1370       ExplicitKeyword,
1371       ExportKeyword,
1372       ExportAsKeyword,
1373       ExternKeyword,
1374       FrameworkKeyword,
1375       LinkKeyword,
1376       ModuleKeyword,
1377       Period,
1378       PrivateKeyword,
1379       UmbrellaKeyword,
1380       UseKeyword,
1381       RequiresKeyword,
1382       Star,
1383       StringLiteral,
1384       IntegerLiteral,
1385       TextualKeyword,
1386       LBrace,
1387       RBrace,
1388       LSquare,
1389       RSquare
1390     } Kind;
1391 
1392     SourceLocation::UIntTy Location;
1393     unsigned StringLength;
1394     union {
1395       // If Kind != IntegerLiteral.
1396       const char *StringData;
1397 
1398       // If Kind == IntegerLiteral.
1399       uint64_t IntegerValue;
1400     };
1401 
1402     void clear() {
1403       Kind = EndOfFile;
1404       Location = 0;
1405       StringLength = 0;
1406       StringData = nullptr;
1407     }
1408 
1409     bool is(TokenKind K) const { return Kind == K; }
1410 
1411     SourceLocation getLocation() const {
1412       return SourceLocation::getFromRawEncoding(Location);
1413     }
1414 
1415     uint64_t getInteger() const {
1416       return Kind == IntegerLiteral ? IntegerValue : 0;
1417     }
1418 
1419     StringRef getString() const {
1420       return Kind == IntegerLiteral ? StringRef()
1421                                     : StringRef(StringData, StringLength);
1422     }
1423   };
1424 
1425   class ModuleMapParser {
1426     Lexer &L;
1427     SourceManager &SourceMgr;
1428 
1429     /// Default target information, used only for string literal
1430     /// parsing.
1431     const TargetInfo *Target;
1432 
1433     DiagnosticsEngine &Diags;
1434     ModuleMap &Map;
1435 
1436     /// The current module map file.
1437     const FileEntry *ModuleMapFile;
1438 
1439     /// Source location of most recent parsed module declaration
1440     SourceLocation CurrModuleDeclLoc;
1441 
1442     /// The directory that file names in this module map file should
1443     /// be resolved relative to.
1444     const DirectoryEntry *Directory;
1445 
1446     /// Whether this module map is in a system header directory.
1447     bool IsSystem;
1448 
1449     /// Whether an error occurred.
1450     bool HadError = false;
1451 
1452     /// Stores string data for the various string literals referenced
1453     /// during parsing.
1454     llvm::BumpPtrAllocator StringData;
1455 
1456     /// The current token.
1457     MMToken Tok;
1458 
1459     /// The active module.
1460     Module *ActiveModule = nullptr;
1461 
1462     /// Whether a module uses the 'requires excluded' hack to mark its
1463     /// contents as 'textual'.
1464     ///
1465     /// On older Darwin SDK versions, 'requires excluded' is used to mark the
1466     /// contents of the Darwin.C.excluded (assert.h) and Tcl.Private modules as
1467     /// non-modular headers.  For backwards compatibility, we continue to
1468     /// support this idiom for just these modules, and map the headers to
1469     /// 'textual' to match the original intent.
1470     llvm::SmallPtrSet<Module *, 2> UsesRequiresExcludedHack;
1471 
1472     /// Consume the current token and return its location.
1473     SourceLocation consumeToken();
1474 
1475     /// Skip tokens until we reach the a token with the given kind
1476     /// (or the end of the file).
1477     void skipUntil(MMToken::TokenKind K);
1478 
1479     using ModuleId = SmallVector<std::pair<std::string, SourceLocation>, 2>;
1480 
1481     bool parseModuleId(ModuleId &Id);
1482     void parseModuleDecl();
1483     void parseExternModuleDecl();
1484     void parseRequiresDecl();
1485     void parseHeaderDecl(MMToken::TokenKind, SourceLocation LeadingLoc);
1486     void parseUmbrellaDirDecl(SourceLocation UmbrellaLoc);
1487     void parseExportDecl();
1488     void parseExportAsDecl();
1489     void parseUseDecl();
1490     void parseLinkDecl();
1491     void parseConfigMacros();
1492     void parseConflict();
1493     void parseInferredModuleDecl(bool Framework, bool Explicit);
1494 
1495     /// Private modules are canonicalized as Foo_Private. Clang provides extra
1496     /// module map search logic to find the appropriate private module when PCH
1497     /// is used with implicit module maps. Warn when private modules are written
1498     /// in other ways (FooPrivate and Foo.Private), providing notes and fixits.
1499     void diagnosePrivateModules(SourceLocation ExplicitLoc,
1500                                 SourceLocation FrameworkLoc);
1501 
1502     using Attributes = ModuleMap::Attributes;
1503 
1504     bool parseOptionalAttributes(Attributes &Attrs);
1505 
1506   public:
1507     explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr,
1508                              const TargetInfo *Target, DiagnosticsEngine &Diags,
1509                              ModuleMap &Map, const FileEntry *ModuleMapFile,
1510                              const DirectoryEntry *Directory, bool IsSystem)
1511         : L(L), SourceMgr(SourceMgr), Target(Target), Diags(Diags), Map(Map),
1512           ModuleMapFile(ModuleMapFile), Directory(Directory),
1513           IsSystem(IsSystem) {
1514       Tok.clear();
1515       consumeToken();
1516     }
1517 
1518     bool parseModuleMapFile();
1519 
1520     bool terminatedByDirective() { return false; }
1521     SourceLocation getLocation() { return Tok.getLocation(); }
1522   };
1523 
1524 } // namespace clang
1525 
1526 SourceLocation ModuleMapParser::consumeToken() {
1527   SourceLocation Result = Tok.getLocation();
1528 
1529 retry:
1530   Tok.clear();
1531   Token LToken;
1532   L.LexFromRawLexer(LToken);
1533   Tok.Location = LToken.getLocation().getRawEncoding();
1534   switch (LToken.getKind()) {
1535   case tok::raw_identifier: {
1536     StringRef RI = LToken.getRawIdentifier();
1537     Tok.StringData = RI.data();
1538     Tok.StringLength = RI.size();
1539     Tok.Kind = llvm::StringSwitch<MMToken::TokenKind>(RI)
1540                  .Case("config_macros", MMToken::ConfigMacros)
1541                  .Case("conflict", MMToken::Conflict)
1542                  .Case("exclude", MMToken::ExcludeKeyword)
1543                  .Case("explicit", MMToken::ExplicitKeyword)
1544                  .Case("export", MMToken::ExportKeyword)
1545                  .Case("export_as", MMToken::ExportAsKeyword)
1546                  .Case("extern", MMToken::ExternKeyword)
1547                  .Case("framework", MMToken::FrameworkKeyword)
1548                  .Case("header", MMToken::HeaderKeyword)
1549                  .Case("link", MMToken::LinkKeyword)
1550                  .Case("module", MMToken::ModuleKeyword)
1551                  .Case("private", MMToken::PrivateKeyword)
1552                  .Case("requires", MMToken::RequiresKeyword)
1553                  .Case("textual", MMToken::TextualKeyword)
1554                  .Case("umbrella", MMToken::UmbrellaKeyword)
1555                  .Case("use", MMToken::UseKeyword)
1556                  .Default(MMToken::Identifier);
1557     break;
1558   }
1559 
1560   case tok::comma:
1561     Tok.Kind = MMToken::Comma;
1562     break;
1563 
1564   case tok::eof:
1565     Tok.Kind = MMToken::EndOfFile;
1566     break;
1567 
1568   case tok::l_brace:
1569     Tok.Kind = MMToken::LBrace;
1570     break;
1571 
1572   case tok::l_square:
1573     Tok.Kind = MMToken::LSquare;
1574     break;
1575 
1576   case tok::period:
1577     Tok.Kind = MMToken::Period;
1578     break;
1579 
1580   case tok::r_brace:
1581     Tok.Kind = MMToken::RBrace;
1582     break;
1583 
1584   case tok::r_square:
1585     Tok.Kind = MMToken::RSquare;
1586     break;
1587 
1588   case tok::star:
1589     Tok.Kind = MMToken::Star;
1590     break;
1591 
1592   case tok::exclaim:
1593     Tok.Kind = MMToken::Exclaim;
1594     break;
1595 
1596   case tok::string_literal: {
1597     if (LToken.hasUDSuffix()) {
1598       Diags.Report(LToken.getLocation(), diag::err_invalid_string_udl);
1599       HadError = true;
1600       goto retry;
1601     }
1602 
1603     // Parse the string literal.
1604     LangOptions LangOpts;
1605     StringLiteralParser StringLiteral(LToken, SourceMgr, LangOpts, *Target);
1606     if (StringLiteral.hadError)
1607       goto retry;
1608 
1609     // Copy the string literal into our string data allocator.
1610     unsigned Length = StringLiteral.GetStringLength();
1611     char *Saved = StringData.Allocate<char>(Length + 1);
1612     memcpy(Saved, StringLiteral.GetString().data(), Length);
1613     Saved[Length] = 0;
1614 
1615     // Form the token.
1616     Tok.Kind = MMToken::StringLiteral;
1617     Tok.StringData = Saved;
1618     Tok.StringLength = Length;
1619     break;
1620   }
1621 
1622   case tok::numeric_constant: {
1623     // We don't support any suffixes or other complications.
1624     SmallString<32> SpellingBuffer;
1625     SpellingBuffer.resize(LToken.getLength() + 1);
1626     const char *Start = SpellingBuffer.data();
1627     unsigned Length =
1628         Lexer::getSpelling(LToken, Start, SourceMgr, L.getLangOpts());
1629     uint64_t Value;
1630     if (StringRef(Start, Length).getAsInteger(0, Value)) {
1631       Diags.Report(Tok.getLocation(), diag::err_mmap_unknown_token);
1632       HadError = true;
1633       goto retry;
1634     }
1635 
1636     Tok.Kind = MMToken::IntegerLiteral;
1637     Tok.IntegerValue = Value;
1638     break;
1639   }
1640 
1641   case tok::comment:
1642     goto retry;
1643 
1644   case tok::hash:
1645     // A module map can be terminated prematurely by
1646     //   #pragma clang module contents
1647     // When building the module, we'll treat the rest of the file as the
1648     // contents of the module.
1649     {
1650       auto NextIsIdent = [&](StringRef Str) -> bool {
1651         L.LexFromRawLexer(LToken);
1652         return !LToken.isAtStartOfLine() && LToken.is(tok::raw_identifier) &&
1653                LToken.getRawIdentifier() == Str;
1654       };
1655       if (NextIsIdent("pragma") && NextIsIdent("clang") &&
1656           NextIsIdent("module") && NextIsIdent("contents")) {
1657         Tok.Kind = MMToken::EndOfFile;
1658         break;
1659       }
1660     }
1661     LLVM_FALLTHROUGH;
1662 
1663   default:
1664     Diags.Report(Tok.getLocation(), diag::err_mmap_unknown_token);
1665     HadError = true;
1666     goto retry;
1667   }
1668 
1669   return Result;
1670 }
1671 
1672 void ModuleMapParser::skipUntil(MMToken::TokenKind K) {
1673   unsigned braceDepth = 0;
1674   unsigned squareDepth = 0;
1675   do {
1676     switch (Tok.Kind) {
1677     case MMToken::EndOfFile:
1678       return;
1679 
1680     case MMToken::LBrace:
1681       if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1682         return;
1683 
1684       ++braceDepth;
1685       break;
1686 
1687     case MMToken::LSquare:
1688       if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1689         return;
1690 
1691       ++squareDepth;
1692       break;
1693 
1694     case MMToken::RBrace:
1695       if (braceDepth > 0)
1696         --braceDepth;
1697       else if (Tok.is(K))
1698         return;
1699       break;
1700 
1701     case MMToken::RSquare:
1702       if (squareDepth > 0)
1703         --squareDepth;
1704       else if (Tok.is(K))
1705         return;
1706       break;
1707 
1708     default:
1709       if (braceDepth == 0 && squareDepth == 0 && Tok.is(K))
1710         return;
1711       break;
1712     }
1713 
1714    consumeToken();
1715   } while (true);
1716 }
1717 
1718 /// Parse a module-id.
1719 ///
1720 ///   module-id:
1721 ///     identifier
1722 ///     identifier '.' module-id
1723 ///
1724 /// \returns true if an error occurred, false otherwise.
1725 bool ModuleMapParser::parseModuleId(ModuleId &Id) {
1726   Id.clear();
1727   do {
1728     if (Tok.is(MMToken::Identifier) || Tok.is(MMToken::StringLiteral)) {
1729       Id.push_back(
1730           std::make_pair(std::string(Tok.getString()), Tok.getLocation()));
1731       consumeToken();
1732     } else {
1733       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name);
1734       return true;
1735     }
1736 
1737     if (!Tok.is(MMToken::Period))
1738       break;
1739 
1740     consumeToken();
1741   } while (true);
1742 
1743   return false;
1744 }
1745 
1746 namespace {
1747 
1748   /// Enumerates the known attributes.
1749   enum AttributeKind {
1750     /// An unknown attribute.
1751     AT_unknown,
1752 
1753     /// The 'system' attribute.
1754     AT_system,
1755 
1756     /// The 'extern_c' attribute.
1757     AT_extern_c,
1758 
1759     /// The 'exhaustive' attribute.
1760     AT_exhaustive,
1761 
1762     /// The 'no_undeclared_includes' attribute.
1763     AT_no_undeclared_includes
1764   };
1765 
1766 } // namespace
1767 
1768 /// Private modules are canonicalized as Foo_Private. Clang provides extra
1769 /// module map search logic to find the appropriate private module when PCH
1770 /// is used with implicit module maps. Warn when private modules are written
1771 /// in other ways (FooPrivate and Foo.Private), providing notes and fixits.
1772 void ModuleMapParser::diagnosePrivateModules(SourceLocation ExplicitLoc,
1773                                              SourceLocation FrameworkLoc) {
1774   auto GenNoteAndFixIt = [&](StringRef BadName, StringRef Canonical,
1775                              const Module *M, SourceRange ReplLoc) {
1776     auto D = Diags.Report(ActiveModule->DefinitionLoc,
1777                           diag::note_mmap_rename_top_level_private_module);
1778     D << BadName << M->Name;
1779     D << FixItHint::CreateReplacement(ReplLoc, Canonical);
1780   };
1781 
1782   for (auto E = Map.module_begin(); E != Map.module_end(); ++E) {
1783     auto const *M = E->getValue();
1784     if (M->Directory != ActiveModule->Directory)
1785       continue;
1786 
1787     SmallString<128> FullName(ActiveModule->getFullModuleName());
1788     if (!FullName.startswith(M->Name) && !FullName.endswith("Private"))
1789       continue;
1790     SmallString<128> FixedPrivModDecl;
1791     SmallString<128> Canonical(M->Name);
1792     Canonical.append("_Private");
1793 
1794     // Foo.Private -> Foo_Private
1795     if (ActiveModule->Parent && ActiveModule->Name == "Private" && !M->Parent &&
1796         M->Name == ActiveModule->Parent->Name) {
1797       Diags.Report(ActiveModule->DefinitionLoc,
1798                    diag::warn_mmap_mismatched_private_submodule)
1799           << FullName;
1800 
1801       SourceLocation FixItInitBegin = CurrModuleDeclLoc;
1802       if (FrameworkLoc.isValid())
1803         FixItInitBegin = FrameworkLoc;
1804       if (ExplicitLoc.isValid())
1805         FixItInitBegin = ExplicitLoc;
1806 
1807       if (FrameworkLoc.isValid() || ActiveModule->Parent->IsFramework)
1808         FixedPrivModDecl.append("framework ");
1809       FixedPrivModDecl.append("module ");
1810       FixedPrivModDecl.append(Canonical);
1811 
1812       GenNoteAndFixIt(FullName, FixedPrivModDecl, M,
1813                       SourceRange(FixItInitBegin, ActiveModule->DefinitionLoc));
1814       continue;
1815     }
1816 
1817     // FooPrivate and whatnots -> Foo_Private
1818     if (!ActiveModule->Parent && !M->Parent && M->Name != ActiveModule->Name &&
1819         ActiveModule->Name != Canonical) {
1820       Diags.Report(ActiveModule->DefinitionLoc,
1821                    diag::warn_mmap_mismatched_private_module_name)
1822           << ActiveModule->Name;
1823       GenNoteAndFixIt(ActiveModule->Name, Canonical, M,
1824                       SourceRange(ActiveModule->DefinitionLoc));
1825     }
1826   }
1827 }
1828 
1829 /// Parse a module declaration.
1830 ///
1831 ///   module-declaration:
1832 ///     'extern' 'module' module-id string-literal
1833 ///     'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt]
1834 ///       { module-member* }
1835 ///
1836 ///   module-member:
1837 ///     requires-declaration
1838 ///     header-declaration
1839 ///     submodule-declaration
1840 ///     export-declaration
1841 ///     export-as-declaration
1842 ///     link-declaration
1843 ///
1844 ///   submodule-declaration:
1845 ///     module-declaration
1846 ///     inferred-submodule-declaration
1847 void ModuleMapParser::parseModuleDecl() {
1848   assert(Tok.is(MMToken::ExplicitKeyword) || Tok.is(MMToken::ModuleKeyword) ||
1849          Tok.is(MMToken::FrameworkKeyword) || Tok.is(MMToken::ExternKeyword));
1850   if (Tok.is(MMToken::ExternKeyword)) {
1851     parseExternModuleDecl();
1852     return;
1853   }
1854 
1855   // Parse 'explicit' or 'framework' keyword, if present.
1856   SourceLocation ExplicitLoc;
1857   SourceLocation FrameworkLoc;
1858   bool Explicit = false;
1859   bool Framework = false;
1860 
1861   // Parse 'explicit' keyword, if present.
1862   if (Tok.is(MMToken::ExplicitKeyword)) {
1863     ExplicitLoc = consumeToken();
1864     Explicit = true;
1865   }
1866 
1867   // Parse 'framework' keyword, if present.
1868   if (Tok.is(MMToken::FrameworkKeyword)) {
1869     FrameworkLoc = consumeToken();
1870     Framework = true;
1871   }
1872 
1873   // Parse 'module' keyword.
1874   if (!Tok.is(MMToken::ModuleKeyword)) {
1875     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
1876     consumeToken();
1877     HadError = true;
1878     return;
1879   }
1880   CurrModuleDeclLoc = consumeToken(); // 'module' keyword
1881 
1882   // If we have a wildcard for the module name, this is an inferred submodule.
1883   // Parse it.
1884   if (Tok.is(MMToken::Star))
1885     return parseInferredModuleDecl(Framework, Explicit);
1886 
1887   // Parse the module name.
1888   ModuleId Id;
1889   if (parseModuleId(Id)) {
1890     HadError = true;
1891     return;
1892   }
1893 
1894   if (ActiveModule) {
1895     if (Id.size() > 1) {
1896       Diags.Report(Id.front().second, diag::err_mmap_nested_submodule_id)
1897         << SourceRange(Id.front().second, Id.back().second);
1898 
1899       HadError = true;
1900       return;
1901     }
1902   } else if (Id.size() == 1 && Explicit) {
1903     // Top-level modules can't be explicit.
1904     Diags.Report(ExplicitLoc, diag::err_mmap_explicit_top_level);
1905     Explicit = false;
1906     ExplicitLoc = SourceLocation();
1907     HadError = true;
1908   }
1909 
1910   Module *PreviousActiveModule = ActiveModule;
1911   if (Id.size() > 1) {
1912     // This module map defines a submodule. Go find the module of which it
1913     // is a submodule.
1914     ActiveModule = nullptr;
1915     const Module *TopLevelModule = nullptr;
1916     for (unsigned I = 0, N = Id.size() - 1; I != N; ++I) {
1917       if (Module *Next = Map.lookupModuleQualified(Id[I].first, ActiveModule)) {
1918         if (I == 0)
1919           TopLevelModule = Next;
1920         ActiveModule = Next;
1921         continue;
1922       }
1923 
1924       Diags.Report(Id[I].second, diag::err_mmap_missing_parent_module)
1925           << Id[I].first << (ActiveModule != nullptr)
1926           << (ActiveModule
1927                   ? ActiveModule->getTopLevelModule()->getFullModuleName()
1928                   : "");
1929       HadError = true;
1930     }
1931 
1932     if (TopLevelModule &&
1933         ModuleMapFile != Map.getContainingModuleMapFile(TopLevelModule)) {
1934       assert(ModuleMapFile != Map.getModuleMapFileForUniquing(TopLevelModule) &&
1935              "submodule defined in same file as 'module *' that allowed its "
1936              "top-level module");
1937       Map.addAdditionalModuleMapFile(TopLevelModule, ModuleMapFile);
1938     }
1939   }
1940 
1941   StringRef ModuleName = Id.back().first;
1942   SourceLocation ModuleNameLoc = Id.back().second;
1943 
1944   // Parse the optional attribute list.
1945   Attributes Attrs;
1946   if (parseOptionalAttributes(Attrs))
1947     return;
1948 
1949   // Parse the opening brace.
1950   if (!Tok.is(MMToken::LBrace)) {
1951     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace)
1952       << ModuleName;
1953     HadError = true;
1954     return;
1955   }
1956   SourceLocation LBraceLoc = consumeToken();
1957 
1958   // Determine whether this (sub)module has already been defined.
1959   Module *ShadowingModule = nullptr;
1960   if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) {
1961     // We might see a (re)definition of a module that we already have a
1962     // definition for in two cases:
1963     //  - If we loaded one definition from an AST file and we've just found a
1964     //    corresponding definition in a module map file, or
1965     bool LoadedFromASTFile = Existing->DefinitionLoc.isInvalid();
1966     //  - If we're building a (preprocessed) module and we've just loaded the
1967     //    module map file from which it was created.
1968     bool ParsedAsMainInput =
1969         Map.LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap &&
1970         Map.LangOpts.CurrentModule == ModuleName &&
1971         SourceMgr.getDecomposedLoc(ModuleNameLoc).first !=
1972             SourceMgr.getDecomposedLoc(Existing->DefinitionLoc).first;
1973     if (!ActiveModule && (LoadedFromASTFile || ParsedAsMainInput)) {
1974       // Skip the module definition.
1975       skipUntil(MMToken::RBrace);
1976       if (Tok.is(MMToken::RBrace))
1977         consumeToken();
1978       else {
1979         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1980         Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1981         HadError = true;
1982       }
1983       return;
1984     }
1985 
1986     if (!Existing->Parent && Map.mayShadowNewModule(Existing)) {
1987       ShadowingModule = Existing;
1988     } else {
1989       // This is not a shawdowed module decl, it is an illegal redefinition.
1990       Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition)
1991           << ModuleName;
1992       Diags.Report(Existing->DefinitionLoc, diag::note_mmap_prev_definition);
1993 
1994       // Skip the module definition.
1995       skipUntil(MMToken::RBrace);
1996       if (Tok.is(MMToken::RBrace))
1997         consumeToken();
1998 
1999       HadError = true;
2000       return;
2001     }
2002   }
2003 
2004   // Start defining this module.
2005   if (ShadowingModule) {
2006     ActiveModule =
2007         Map.createShadowedModule(ModuleName, Framework, ShadowingModule);
2008   } else {
2009     ActiveModule =
2010         Map.findOrCreateModule(ModuleName, ActiveModule, Framework, Explicit)
2011             .first;
2012   }
2013 
2014   ActiveModule->DefinitionLoc = ModuleNameLoc;
2015   if (Attrs.IsSystem || IsSystem)
2016     ActiveModule->IsSystem = true;
2017   if (Attrs.IsExternC)
2018     ActiveModule->IsExternC = true;
2019   if (Attrs.NoUndeclaredIncludes ||
2020       (!ActiveModule->Parent && ModuleName == "Darwin"))
2021     ActiveModule->NoUndeclaredIncludes = true;
2022   ActiveModule->Directory = Directory;
2023 
2024   StringRef MapFileName(ModuleMapFile->getName());
2025   if (MapFileName.endswith("module.private.modulemap") ||
2026       MapFileName.endswith("module_private.map")) {
2027     ActiveModule->ModuleMapIsPrivate = true;
2028   }
2029 
2030   // Private modules named as FooPrivate, Foo.Private or similar are likely a
2031   // user error; provide warnings, notes and fixits to direct users to use
2032   // Foo_Private instead.
2033   SourceLocation StartLoc =
2034       SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
2035   if (Map.HeaderInfo.getHeaderSearchOpts().ImplicitModuleMaps &&
2036       !Diags.isIgnored(diag::warn_mmap_mismatched_private_submodule,
2037                        StartLoc) &&
2038       !Diags.isIgnored(diag::warn_mmap_mismatched_private_module_name,
2039                        StartLoc) &&
2040       ActiveModule->ModuleMapIsPrivate)
2041     diagnosePrivateModules(ExplicitLoc, FrameworkLoc);
2042 
2043   bool Done = false;
2044   do {
2045     switch (Tok.Kind) {
2046     case MMToken::EndOfFile:
2047     case MMToken::RBrace:
2048       Done = true;
2049       break;
2050 
2051     case MMToken::ConfigMacros:
2052       parseConfigMacros();
2053       break;
2054 
2055     case MMToken::Conflict:
2056       parseConflict();
2057       break;
2058 
2059     case MMToken::ExplicitKeyword:
2060     case MMToken::ExternKeyword:
2061     case MMToken::FrameworkKeyword:
2062     case MMToken::ModuleKeyword:
2063       parseModuleDecl();
2064       break;
2065 
2066     case MMToken::ExportKeyword:
2067       parseExportDecl();
2068       break;
2069 
2070     case MMToken::ExportAsKeyword:
2071       parseExportAsDecl();
2072       break;
2073 
2074     case MMToken::UseKeyword:
2075       parseUseDecl();
2076       break;
2077 
2078     case MMToken::RequiresKeyword:
2079       parseRequiresDecl();
2080       break;
2081 
2082     case MMToken::TextualKeyword:
2083       parseHeaderDecl(MMToken::TextualKeyword, consumeToken());
2084       break;
2085 
2086     case MMToken::UmbrellaKeyword: {
2087       SourceLocation UmbrellaLoc = consumeToken();
2088       if (Tok.is(MMToken::HeaderKeyword))
2089         parseHeaderDecl(MMToken::UmbrellaKeyword, UmbrellaLoc);
2090       else
2091         parseUmbrellaDirDecl(UmbrellaLoc);
2092       break;
2093     }
2094 
2095     case MMToken::ExcludeKeyword:
2096       parseHeaderDecl(MMToken::ExcludeKeyword, consumeToken());
2097       break;
2098 
2099     case MMToken::PrivateKeyword:
2100       parseHeaderDecl(MMToken::PrivateKeyword, consumeToken());
2101       break;
2102 
2103     case MMToken::HeaderKeyword:
2104       parseHeaderDecl(MMToken::HeaderKeyword, consumeToken());
2105       break;
2106 
2107     case MMToken::LinkKeyword:
2108       parseLinkDecl();
2109       break;
2110 
2111     default:
2112       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member);
2113       consumeToken();
2114       break;
2115     }
2116   } while (!Done);
2117 
2118   if (Tok.is(MMToken::RBrace))
2119     consumeToken();
2120   else {
2121     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
2122     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
2123     HadError = true;
2124   }
2125 
2126   // If the active module is a top-level framework, and there are no link
2127   // libraries, automatically link against the framework.
2128   if (ActiveModule->IsFramework && !ActiveModule->isSubFramework() &&
2129       ActiveModule->LinkLibraries.empty()) {
2130     inferFrameworkLink(ActiveModule, Directory, SourceMgr.getFileManager());
2131   }
2132 
2133   // If the module meets all requirements but is still unavailable, mark the
2134   // whole tree as unavailable to prevent it from building.
2135   if (!ActiveModule->IsAvailable && !ActiveModule->IsUnimportable &&
2136       ActiveModule->Parent) {
2137     ActiveModule->getTopLevelModule()->markUnavailable(/*Unimportable=*/false);
2138     ActiveModule->getTopLevelModule()->MissingHeaders.append(
2139       ActiveModule->MissingHeaders.begin(), ActiveModule->MissingHeaders.end());
2140   }
2141 
2142   // We're done parsing this module. Pop back to the previous module.
2143   ActiveModule = PreviousActiveModule;
2144 }
2145 
2146 /// Parse an extern module declaration.
2147 ///
2148 ///   extern module-declaration:
2149 ///     'extern' 'module' module-id string-literal
2150 void ModuleMapParser::parseExternModuleDecl() {
2151   assert(Tok.is(MMToken::ExternKeyword));
2152   SourceLocation ExternLoc = consumeToken(); // 'extern' keyword
2153 
2154   // Parse 'module' keyword.
2155   if (!Tok.is(MMToken::ModuleKeyword)) {
2156     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
2157     consumeToken();
2158     HadError = true;
2159     return;
2160   }
2161   consumeToken(); // 'module' keyword
2162 
2163   // Parse the module name.
2164   ModuleId Id;
2165   if (parseModuleId(Id)) {
2166     HadError = true;
2167     return;
2168   }
2169 
2170   // Parse the referenced module map file name.
2171   if (!Tok.is(MMToken::StringLiteral)) {
2172     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_mmap_file);
2173     HadError = true;
2174     return;
2175   }
2176   std::string FileName = std::string(Tok.getString());
2177   consumeToken(); // filename
2178 
2179   StringRef FileNameRef = FileName;
2180   SmallString<128> ModuleMapFileName;
2181   if (llvm::sys::path::is_relative(FileNameRef)) {
2182     ModuleMapFileName += Directory->getName();
2183     llvm::sys::path::append(ModuleMapFileName, FileName);
2184     FileNameRef = ModuleMapFileName;
2185   }
2186   if (auto File = SourceMgr.getFileManager().getFile(FileNameRef))
2187     Map.parseModuleMapFile(
2188         *File, IsSystem,
2189         Map.HeaderInfo.getHeaderSearchOpts().ModuleMapFileHomeIsCwd
2190             ? Directory
2191             : (*File)->getDir(),
2192         FileID(), nullptr, ExternLoc);
2193 }
2194 
2195 /// Whether to add the requirement \p Feature to the module \p M.
2196 ///
2197 /// This preserves backwards compatibility for two hacks in the Darwin system
2198 /// module map files:
2199 ///
2200 /// 1. The use of 'requires excluded' to make headers non-modular, which
2201 ///    should really be mapped to 'textual' now that we have this feature.  We
2202 ///    drop the 'excluded' requirement, and set \p IsRequiresExcludedHack to
2203 ///    true.  Later, this bit will be used to map all the headers inside this
2204 ///    module to 'textual'.
2205 ///
2206 ///    This affects Darwin.C.excluded (for assert.h) and Tcl.Private.
2207 ///
2208 /// 2. Removes a bogus cplusplus requirement from IOKit.avc.  This requirement
2209 ///    was never correct and causes issues now that we check it, so drop it.
2210 static bool shouldAddRequirement(Module *M, StringRef Feature,
2211                                  bool &IsRequiresExcludedHack) {
2212   if (Feature == "excluded" &&
2213       (M->fullModuleNameIs({"Darwin", "C", "excluded"}) ||
2214        M->fullModuleNameIs({"Tcl", "Private"}))) {
2215     IsRequiresExcludedHack = true;
2216     return false;
2217   } else if (Feature == "cplusplus" && M->fullModuleNameIs({"IOKit", "avc"})) {
2218     return false;
2219   }
2220 
2221   return true;
2222 }
2223 
2224 /// Parse a requires declaration.
2225 ///
2226 ///   requires-declaration:
2227 ///     'requires' feature-list
2228 ///
2229 ///   feature-list:
2230 ///     feature ',' feature-list
2231 ///     feature
2232 ///
2233 ///   feature:
2234 ///     '!'[opt] identifier
2235 void ModuleMapParser::parseRequiresDecl() {
2236   assert(Tok.is(MMToken::RequiresKeyword));
2237 
2238   // Parse 'requires' keyword.
2239   consumeToken();
2240 
2241   // Parse the feature-list.
2242   do {
2243     bool RequiredState = true;
2244     if (Tok.is(MMToken::Exclaim)) {
2245       RequiredState = false;
2246       consumeToken();
2247     }
2248 
2249     if (!Tok.is(MMToken::Identifier)) {
2250       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_feature);
2251       HadError = true;
2252       return;
2253     }
2254 
2255     // Consume the feature name.
2256     std::string Feature = std::string(Tok.getString());
2257     consumeToken();
2258 
2259     bool IsRequiresExcludedHack = false;
2260     bool ShouldAddRequirement =
2261         shouldAddRequirement(ActiveModule, Feature, IsRequiresExcludedHack);
2262 
2263     if (IsRequiresExcludedHack)
2264       UsesRequiresExcludedHack.insert(ActiveModule);
2265 
2266     if (ShouldAddRequirement) {
2267       // Add this feature.
2268       ActiveModule->addRequirement(Feature, RequiredState, Map.LangOpts,
2269                                    *Map.Target);
2270     }
2271 
2272     if (!Tok.is(MMToken::Comma))
2273       break;
2274 
2275     // Consume the comma.
2276     consumeToken();
2277   } while (true);
2278 }
2279 
2280 /// Parse a header declaration.
2281 ///
2282 ///   header-declaration:
2283 ///     'textual'[opt] 'header' string-literal
2284 ///     'private' 'textual'[opt] 'header' string-literal
2285 ///     'exclude' 'header' string-literal
2286 ///     'umbrella' 'header' string-literal
2287 ///
2288 /// FIXME: Support 'private textual header'.
2289 void ModuleMapParser::parseHeaderDecl(MMToken::TokenKind LeadingToken,
2290                                       SourceLocation LeadingLoc) {
2291   // We've already consumed the first token.
2292   ModuleMap::ModuleHeaderRole Role = ModuleMap::NormalHeader;
2293   if (LeadingToken == MMToken::PrivateKeyword) {
2294     Role = ModuleMap::PrivateHeader;
2295     // 'private' may optionally be followed by 'textual'.
2296     if (Tok.is(MMToken::TextualKeyword)) {
2297       LeadingToken = Tok.Kind;
2298       consumeToken();
2299     }
2300   }
2301 
2302   if (LeadingToken == MMToken::TextualKeyword)
2303     Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
2304 
2305   if (UsesRequiresExcludedHack.count(ActiveModule)) {
2306     // Mark this header 'textual' (see doc comment for
2307     // Module::UsesRequiresExcludedHack).
2308     Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
2309   }
2310 
2311   if (LeadingToken != MMToken::HeaderKeyword) {
2312     if (!Tok.is(MMToken::HeaderKeyword)) {
2313       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
2314           << (LeadingToken == MMToken::PrivateKeyword ? "private" :
2315               LeadingToken == MMToken::ExcludeKeyword ? "exclude" :
2316               LeadingToken == MMToken::TextualKeyword ? "textual" : "umbrella");
2317       return;
2318     }
2319     consumeToken();
2320   }
2321 
2322   // Parse the header name.
2323   if (!Tok.is(MMToken::StringLiteral)) {
2324     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
2325       << "header";
2326     HadError = true;
2327     return;
2328   }
2329   Module::UnresolvedHeaderDirective Header;
2330   Header.FileName = std::string(Tok.getString());
2331   Header.FileNameLoc = consumeToken();
2332   Header.IsUmbrella = LeadingToken == MMToken::UmbrellaKeyword;
2333   Header.Kind =
2334       (LeadingToken == MMToken::ExcludeKeyword ? Module::HK_Excluded
2335                                                : Map.headerRoleToKind(Role));
2336 
2337   // Check whether we already have an umbrella.
2338   if (Header.IsUmbrella && ActiveModule->Umbrella) {
2339     Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash)
2340       << ActiveModule->getFullModuleName();
2341     HadError = true;
2342     return;
2343   }
2344 
2345   // If we were given stat information, parse it so we can skip looking for
2346   // the file.
2347   if (Tok.is(MMToken::LBrace)) {
2348     SourceLocation LBraceLoc = consumeToken();
2349 
2350     while (!Tok.is(MMToken::RBrace) && !Tok.is(MMToken::EndOfFile)) {
2351       enum Attribute { Size, ModTime, Unknown };
2352       StringRef Str = Tok.getString();
2353       SourceLocation Loc = consumeToken();
2354       switch (llvm::StringSwitch<Attribute>(Str)
2355                   .Case("size", Size)
2356                   .Case("mtime", ModTime)
2357                   .Default(Unknown)) {
2358       case Size:
2359         if (Header.Size)
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.Size = Tok.getInteger();
2368         consumeToken();
2369         break;
2370 
2371       case ModTime:
2372         if (Header.ModTime)
2373           Diags.Report(Loc, diag::err_mmap_duplicate_header_attribute) << Str;
2374         if (!Tok.is(MMToken::IntegerLiteral)) {
2375           Diags.Report(Tok.getLocation(),
2376                        diag::err_mmap_invalid_header_attribute_value) << Str;
2377           skipUntil(MMToken::RBrace);
2378           break;
2379         }
2380         Header.ModTime = Tok.getInteger();
2381         consumeToken();
2382         break;
2383 
2384       case Unknown:
2385         Diags.Report(Loc, diag::err_mmap_expected_header_attribute);
2386         skipUntil(MMToken::RBrace);
2387         break;
2388       }
2389     }
2390 
2391     if (Tok.is(MMToken::RBrace))
2392       consumeToken();
2393     else {
2394       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
2395       Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
2396       HadError = true;
2397     }
2398   }
2399 
2400   bool NeedsFramework = false;
2401   Map.addUnresolvedHeader(ActiveModule, std::move(Header), NeedsFramework);
2402 
2403   if (NeedsFramework && ActiveModule)
2404     Diags.Report(CurrModuleDeclLoc, diag::note_mmap_add_framework_keyword)
2405       << ActiveModule->getFullModuleName()
2406       << FixItHint::CreateReplacement(CurrModuleDeclLoc, "framework module");
2407 }
2408 
2409 static int compareModuleHeaders(const Module::Header *A,
2410                                 const Module::Header *B) {
2411   return A->NameAsWritten.compare(B->NameAsWritten);
2412 }
2413 
2414 /// Parse an umbrella directory declaration.
2415 ///
2416 ///   umbrella-dir-declaration:
2417 ///     umbrella string-literal
2418 void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) {
2419   // Parse the directory name.
2420   if (!Tok.is(MMToken::StringLiteral)) {
2421     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
2422       << "umbrella";
2423     HadError = true;
2424     return;
2425   }
2426 
2427   std::string DirName = std::string(Tok.getString());
2428   std::string DirNameAsWritten = DirName;
2429   SourceLocation DirNameLoc = consumeToken();
2430 
2431   // Check whether we already have an umbrella.
2432   if (ActiveModule->Umbrella) {
2433     Diags.Report(DirNameLoc, diag::err_mmap_umbrella_clash)
2434       << ActiveModule->getFullModuleName();
2435     HadError = true;
2436     return;
2437   }
2438 
2439   // Look for this file.
2440   const DirectoryEntry *Dir = nullptr;
2441   if (llvm::sys::path::is_absolute(DirName)) {
2442     if (auto D = SourceMgr.getFileManager().getDirectory(DirName))
2443       Dir = *D;
2444   } else {
2445     SmallString<128> PathName;
2446     PathName = Directory->getName();
2447     llvm::sys::path::append(PathName, DirName);
2448     if (auto D = SourceMgr.getFileManager().getDirectory(PathName))
2449       Dir = *D;
2450   }
2451 
2452   if (!Dir) {
2453     Diags.Report(DirNameLoc, diag::warn_mmap_umbrella_dir_not_found)
2454       << DirName;
2455     return;
2456   }
2457 
2458   if (UsesRequiresExcludedHack.count(ActiveModule)) {
2459     // Mark this header 'textual' (see doc comment for
2460     // ModuleMapParser::UsesRequiresExcludedHack). Although iterating over the
2461     // directory is relatively expensive, in practice this only applies to the
2462     // uncommonly used Tcl module on Darwin platforms.
2463     std::error_code EC;
2464     SmallVector<Module::Header, 6> Headers;
2465     llvm::vfs::FileSystem &FS =
2466         SourceMgr.getFileManager().getVirtualFileSystem();
2467     for (llvm::vfs::recursive_directory_iterator I(FS, Dir->getName(), EC), E;
2468          I != E && !EC; I.increment(EC)) {
2469       if (auto FE = SourceMgr.getFileManager().getFile(I->path())) {
2470         Module::Header Header = {"", std::string(I->path()), *FE};
2471         Headers.push_back(std::move(Header));
2472       }
2473     }
2474 
2475     // Sort header paths so that the pcm doesn't depend on iteration order.
2476     llvm::array_pod_sort(Headers.begin(), Headers.end(), compareModuleHeaders);
2477 
2478     for (auto &Header : Headers)
2479       Map.addHeader(ActiveModule, std::move(Header), ModuleMap::TextualHeader);
2480     return;
2481   }
2482 
2483   if (Module *OwningModule = Map.UmbrellaDirs[Dir]) {
2484     Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash)
2485       << OwningModule->getFullModuleName();
2486     HadError = true;
2487     return;
2488   }
2489 
2490   // Record this umbrella directory.
2491   Map.setUmbrellaDir(ActiveModule, Dir, DirNameAsWritten, DirName);
2492 }
2493 
2494 /// Parse a module export declaration.
2495 ///
2496 ///   export-declaration:
2497 ///     'export' wildcard-module-id
2498 ///
2499 ///   wildcard-module-id:
2500 ///     identifier
2501 ///     '*'
2502 ///     identifier '.' wildcard-module-id
2503 void ModuleMapParser::parseExportDecl() {
2504   assert(Tok.is(MMToken::ExportKeyword));
2505   SourceLocation ExportLoc = consumeToken();
2506 
2507   // Parse the module-id with an optional wildcard at the end.
2508   ModuleId ParsedModuleId;
2509   bool Wildcard = false;
2510   do {
2511     // FIXME: Support string-literal module names here.
2512     if (Tok.is(MMToken::Identifier)) {
2513       ParsedModuleId.push_back(
2514           std::make_pair(std::string(Tok.getString()), Tok.getLocation()));
2515       consumeToken();
2516 
2517       if (Tok.is(MMToken::Period)) {
2518         consumeToken();
2519         continue;
2520       }
2521 
2522       break;
2523     }
2524 
2525     if(Tok.is(MMToken::Star)) {
2526       Wildcard = true;
2527       consumeToken();
2528       break;
2529     }
2530 
2531     Diags.Report(Tok.getLocation(), diag::err_mmap_module_id);
2532     HadError = true;
2533     return;
2534   } while (true);
2535 
2536   Module::UnresolvedExportDecl Unresolved = {
2537     ExportLoc, ParsedModuleId, Wildcard
2538   };
2539   ActiveModule->UnresolvedExports.push_back(Unresolved);
2540 }
2541 
2542 /// Parse a module export_as declaration.
2543 ///
2544 ///   export-as-declaration:
2545 ///     'export_as' identifier
2546 void ModuleMapParser::parseExportAsDecl() {
2547   assert(Tok.is(MMToken::ExportAsKeyword));
2548   consumeToken();
2549 
2550   if (!Tok.is(MMToken::Identifier)) {
2551     Diags.Report(Tok.getLocation(), diag::err_mmap_module_id);
2552     HadError = true;
2553     return;
2554   }
2555 
2556   if (ActiveModule->Parent) {
2557     Diags.Report(Tok.getLocation(), diag::err_mmap_submodule_export_as);
2558     consumeToken();
2559     return;
2560   }
2561 
2562   if (!ActiveModule->ExportAsModule.empty()) {
2563     if (ActiveModule->ExportAsModule == Tok.getString()) {
2564       Diags.Report(Tok.getLocation(), diag::warn_mmap_redundant_export_as)
2565         << ActiveModule->Name << Tok.getString();
2566     } else {
2567       Diags.Report(Tok.getLocation(), diag::err_mmap_conflicting_export_as)
2568         << ActiveModule->Name << ActiveModule->ExportAsModule
2569         << Tok.getString();
2570     }
2571   }
2572 
2573   ActiveModule->ExportAsModule = std::string(Tok.getString());
2574   Map.addLinkAsDependency(ActiveModule);
2575 
2576   consumeToken();
2577 }
2578 
2579 /// Parse a module use declaration.
2580 ///
2581 ///   use-declaration:
2582 ///     'use' wildcard-module-id
2583 void ModuleMapParser::parseUseDecl() {
2584   assert(Tok.is(MMToken::UseKeyword));
2585   auto KWLoc = consumeToken();
2586   // Parse the module-id.
2587   ModuleId ParsedModuleId;
2588   parseModuleId(ParsedModuleId);
2589 
2590   if (ActiveModule->Parent)
2591     Diags.Report(KWLoc, diag::err_mmap_use_decl_submodule);
2592   else
2593     ActiveModule->UnresolvedDirectUses.push_back(ParsedModuleId);
2594 }
2595 
2596 /// Parse a link declaration.
2597 ///
2598 ///   module-declaration:
2599 ///     'link' 'framework'[opt] string-literal
2600 void ModuleMapParser::parseLinkDecl() {
2601   assert(Tok.is(MMToken::LinkKeyword));
2602   SourceLocation LinkLoc = consumeToken();
2603 
2604   // Parse the optional 'framework' keyword.
2605   bool IsFramework = false;
2606   if (Tok.is(MMToken::FrameworkKeyword)) {
2607     consumeToken();
2608     IsFramework = true;
2609   }
2610 
2611   // Parse the library name
2612   if (!Tok.is(MMToken::StringLiteral)) {
2613     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_library_name)
2614       << IsFramework << SourceRange(LinkLoc);
2615     HadError = true;
2616     return;
2617   }
2618 
2619   std::string LibraryName = std::string(Tok.getString());
2620   consumeToken();
2621   ActiveModule->LinkLibraries.push_back(Module::LinkLibrary(LibraryName,
2622                                                             IsFramework));
2623 }
2624 
2625 /// Parse a configuration macro declaration.
2626 ///
2627 ///   module-declaration:
2628 ///     'config_macros' attributes[opt] config-macro-list?
2629 ///
2630 ///   config-macro-list:
2631 ///     identifier (',' identifier)?
2632 void ModuleMapParser::parseConfigMacros() {
2633   assert(Tok.is(MMToken::ConfigMacros));
2634   SourceLocation ConfigMacrosLoc = consumeToken();
2635 
2636   // Only top-level modules can have configuration macros.
2637   if (ActiveModule->Parent) {
2638     Diags.Report(ConfigMacrosLoc, diag::err_mmap_config_macro_submodule);
2639   }
2640 
2641   // Parse the optional attributes.
2642   Attributes Attrs;
2643   if (parseOptionalAttributes(Attrs))
2644     return;
2645 
2646   if (Attrs.IsExhaustive && !ActiveModule->Parent) {
2647     ActiveModule->ConfigMacrosExhaustive = true;
2648   }
2649 
2650   // If we don't have an identifier, we're done.
2651   // FIXME: Support macros with the same name as a keyword here.
2652   if (!Tok.is(MMToken::Identifier))
2653     return;
2654 
2655   // Consume the first identifier.
2656   if (!ActiveModule->Parent) {
2657     ActiveModule->ConfigMacros.push_back(Tok.getString().str());
2658   }
2659   consumeToken();
2660 
2661   do {
2662     // If there's a comma, consume it.
2663     if (!Tok.is(MMToken::Comma))
2664       break;
2665     consumeToken();
2666 
2667     // We expect to see a macro name here.
2668     // FIXME: Support macros with the same name as a keyword here.
2669     if (!Tok.is(MMToken::Identifier)) {
2670       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_config_macro);
2671       break;
2672     }
2673 
2674     // Consume the macro name.
2675     if (!ActiveModule->Parent) {
2676       ActiveModule->ConfigMacros.push_back(Tok.getString().str());
2677     }
2678     consumeToken();
2679   } while (true);
2680 }
2681 
2682 /// Format a module-id into a string.
2683 static std::string formatModuleId(const ModuleId &Id) {
2684   std::string result;
2685   {
2686     llvm::raw_string_ostream OS(result);
2687 
2688     for (unsigned I = 0, N = Id.size(); I != N; ++I) {
2689       if (I)
2690         OS << ".";
2691       OS << Id[I].first;
2692     }
2693   }
2694 
2695   return result;
2696 }
2697 
2698 /// Parse a conflict declaration.
2699 ///
2700 ///   module-declaration:
2701 ///     'conflict' module-id ',' string-literal
2702 void ModuleMapParser::parseConflict() {
2703   assert(Tok.is(MMToken::Conflict));
2704   SourceLocation ConflictLoc = consumeToken();
2705   Module::UnresolvedConflict Conflict;
2706 
2707   // Parse the module-id.
2708   if (parseModuleId(Conflict.Id))
2709     return;
2710 
2711   // Parse the ','.
2712   if (!Tok.is(MMToken::Comma)) {
2713     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_comma)
2714       << SourceRange(ConflictLoc);
2715     return;
2716   }
2717   consumeToken();
2718 
2719   // Parse the message.
2720   if (!Tok.is(MMToken::StringLiteral)) {
2721     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_message)
2722       << formatModuleId(Conflict.Id);
2723     return;
2724   }
2725   Conflict.Message = Tok.getString().str();
2726   consumeToken();
2727 
2728   // Add this unresolved conflict.
2729   ActiveModule->UnresolvedConflicts.push_back(Conflict);
2730 }
2731 
2732 /// Parse an inferred module declaration (wildcard modules).
2733 ///
2734 ///   module-declaration:
2735 ///     'explicit'[opt] 'framework'[opt] 'module' * attributes[opt]
2736 ///       { inferred-module-member* }
2737 ///
2738 ///   inferred-module-member:
2739 ///     'export' '*'
2740 ///     'exclude' identifier
2741 void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) {
2742   assert(Tok.is(MMToken::Star));
2743   SourceLocation StarLoc = consumeToken();
2744   bool Failed = false;
2745 
2746   // Inferred modules must be submodules.
2747   if (!ActiveModule && !Framework) {
2748     Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule);
2749     Failed = true;
2750   }
2751 
2752   if (ActiveModule) {
2753     // Inferred modules must have umbrella directories.
2754     if (!Failed && ActiveModule->IsAvailable &&
2755         !ActiveModule->getUmbrellaDir()) {
2756       Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella);
2757       Failed = true;
2758     }
2759 
2760     // Check for redefinition of an inferred module.
2761     if (!Failed && ActiveModule->InferSubmodules) {
2762       Diags.Report(StarLoc, diag::err_mmap_inferred_redef);
2763       if (ActiveModule->InferredSubmoduleLoc.isValid())
2764         Diags.Report(ActiveModule->InferredSubmoduleLoc,
2765                      diag::note_mmap_prev_definition);
2766       Failed = true;
2767     }
2768 
2769     // Check for the 'framework' keyword, which is not permitted here.
2770     if (Framework) {
2771       Diags.Report(StarLoc, diag::err_mmap_inferred_framework_submodule);
2772       Framework = false;
2773     }
2774   } else if (Explicit) {
2775     Diags.Report(StarLoc, diag::err_mmap_explicit_inferred_framework);
2776     Explicit = false;
2777   }
2778 
2779   // If there were any problems with this inferred submodule, skip its body.
2780   if (Failed) {
2781     if (Tok.is(MMToken::LBrace)) {
2782       consumeToken();
2783       skipUntil(MMToken::RBrace);
2784       if (Tok.is(MMToken::RBrace))
2785         consumeToken();
2786     }
2787     HadError = true;
2788     return;
2789   }
2790 
2791   // Parse optional attributes.
2792   Attributes Attrs;
2793   if (parseOptionalAttributes(Attrs))
2794     return;
2795 
2796   if (ActiveModule) {
2797     // Note that we have an inferred submodule.
2798     ActiveModule->InferSubmodules = true;
2799     ActiveModule->InferredSubmoduleLoc = StarLoc;
2800     ActiveModule->InferExplicitSubmodules = Explicit;
2801   } else {
2802     // We'll be inferring framework modules for this directory.
2803     Map.InferredDirectories[Directory].InferModules = true;
2804     Map.InferredDirectories[Directory].Attrs = Attrs;
2805     Map.InferredDirectories[Directory].ModuleMapFile = ModuleMapFile;
2806     // FIXME: Handle the 'framework' keyword.
2807   }
2808 
2809   // Parse the opening brace.
2810   if (!Tok.is(MMToken::LBrace)) {
2811     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard);
2812     HadError = true;
2813     return;
2814   }
2815   SourceLocation LBraceLoc = consumeToken();
2816 
2817   // Parse the body of the inferred submodule.
2818   bool Done = false;
2819   do {
2820     switch (Tok.Kind) {
2821     case MMToken::EndOfFile:
2822     case MMToken::RBrace:
2823       Done = true;
2824       break;
2825 
2826     case MMToken::ExcludeKeyword:
2827       if (ActiveModule) {
2828         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2829           << (ActiveModule != nullptr);
2830         consumeToken();
2831         break;
2832       }
2833 
2834       consumeToken();
2835       // FIXME: Support string-literal module names here.
2836       if (!Tok.is(MMToken::Identifier)) {
2837         Diags.Report(Tok.getLocation(), diag::err_mmap_missing_exclude_name);
2838         break;
2839       }
2840 
2841       Map.InferredDirectories[Directory].ExcludedModules.push_back(
2842           std::string(Tok.getString()));
2843       consumeToken();
2844       break;
2845 
2846     case MMToken::ExportKeyword:
2847       if (!ActiveModule) {
2848         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2849           << (ActiveModule != nullptr);
2850         consumeToken();
2851         break;
2852       }
2853 
2854       consumeToken();
2855       if (Tok.is(MMToken::Star))
2856         ActiveModule->InferExportWildcard = true;
2857       else
2858         Diags.Report(Tok.getLocation(),
2859                      diag::err_mmap_expected_export_wildcard);
2860       consumeToken();
2861       break;
2862 
2863     case MMToken::ExplicitKeyword:
2864     case MMToken::ModuleKeyword:
2865     case MMToken::HeaderKeyword:
2866     case MMToken::PrivateKeyword:
2867     case MMToken::UmbrellaKeyword:
2868     default:
2869       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2870           << (ActiveModule != nullptr);
2871       consumeToken();
2872       break;
2873     }
2874   } while (!Done);
2875 
2876   if (Tok.is(MMToken::RBrace))
2877     consumeToken();
2878   else {
2879     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
2880     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
2881     HadError = true;
2882   }
2883 }
2884 
2885 /// Parse optional attributes.
2886 ///
2887 ///   attributes:
2888 ///     attribute attributes
2889 ///     attribute
2890 ///
2891 ///   attribute:
2892 ///     [ identifier ]
2893 ///
2894 /// \param Attrs Will be filled in with the parsed attributes.
2895 ///
2896 /// \returns true if an error occurred, false otherwise.
2897 bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) {
2898   bool HadError = false;
2899 
2900   while (Tok.is(MMToken::LSquare)) {
2901     // Consume the '['.
2902     SourceLocation LSquareLoc = consumeToken();
2903 
2904     // Check whether we have an attribute name here.
2905     if (!Tok.is(MMToken::Identifier)) {
2906       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_attribute);
2907       skipUntil(MMToken::RSquare);
2908       if (Tok.is(MMToken::RSquare))
2909         consumeToken();
2910       HadError = true;
2911     }
2912 
2913     // Decode the attribute name.
2914     AttributeKind Attribute
2915       = llvm::StringSwitch<AttributeKind>(Tok.getString())
2916           .Case("exhaustive", AT_exhaustive)
2917           .Case("extern_c", AT_extern_c)
2918           .Case("no_undeclared_includes", AT_no_undeclared_includes)
2919           .Case("system", AT_system)
2920           .Default(AT_unknown);
2921     switch (Attribute) {
2922     case AT_unknown:
2923       Diags.Report(Tok.getLocation(), diag::warn_mmap_unknown_attribute)
2924         << Tok.getString();
2925       break;
2926 
2927     case AT_system:
2928       Attrs.IsSystem = true;
2929       break;
2930 
2931     case AT_extern_c:
2932       Attrs.IsExternC = true;
2933       break;
2934 
2935     case AT_exhaustive:
2936       Attrs.IsExhaustive = true;
2937       break;
2938 
2939     case AT_no_undeclared_includes:
2940       Attrs.NoUndeclaredIncludes = true;
2941       break;
2942     }
2943     consumeToken();
2944 
2945     // Consume the ']'.
2946     if (!Tok.is(MMToken::RSquare)) {
2947       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rsquare);
2948       Diags.Report(LSquareLoc, diag::note_mmap_lsquare_match);
2949       skipUntil(MMToken::RSquare);
2950       HadError = true;
2951     }
2952 
2953     if (Tok.is(MMToken::RSquare))
2954       consumeToken();
2955   }
2956 
2957   return HadError;
2958 }
2959 
2960 /// Parse a module map file.
2961 ///
2962 ///   module-map-file:
2963 ///     module-declaration*
2964 bool ModuleMapParser::parseModuleMapFile() {
2965   do {
2966     switch (Tok.Kind) {
2967     case MMToken::EndOfFile:
2968       return HadError;
2969 
2970     case MMToken::ExplicitKeyword:
2971     case MMToken::ExternKeyword:
2972     case MMToken::ModuleKeyword:
2973     case MMToken::FrameworkKeyword:
2974       parseModuleDecl();
2975       break;
2976 
2977     case MMToken::Comma:
2978     case MMToken::ConfigMacros:
2979     case MMToken::Conflict:
2980     case MMToken::Exclaim:
2981     case MMToken::ExcludeKeyword:
2982     case MMToken::ExportKeyword:
2983     case MMToken::ExportAsKeyword:
2984     case MMToken::HeaderKeyword:
2985     case MMToken::Identifier:
2986     case MMToken::LBrace:
2987     case MMToken::LinkKeyword:
2988     case MMToken::LSquare:
2989     case MMToken::Period:
2990     case MMToken::PrivateKeyword:
2991     case MMToken::RBrace:
2992     case MMToken::RSquare:
2993     case MMToken::RequiresKeyword:
2994     case MMToken::Star:
2995     case MMToken::StringLiteral:
2996     case MMToken::IntegerLiteral:
2997     case MMToken::TextualKeyword:
2998     case MMToken::UmbrellaKeyword:
2999     case MMToken::UseKeyword:
3000       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
3001       HadError = true;
3002       consumeToken();
3003       break;
3004     }
3005   } while (true);
3006 }
3007 
3008 bool ModuleMap::parseModuleMapFile(const FileEntry *File, bool IsSystem,
3009                                    const DirectoryEntry *Dir, FileID ID,
3010                                    unsigned *Offset,
3011                                    SourceLocation ExternModuleLoc) {
3012   assert(Target && "Missing target information");
3013   llvm::DenseMap<const FileEntry *, bool>::iterator Known
3014     = ParsedModuleMap.find(File);
3015   if (Known != ParsedModuleMap.end())
3016     return Known->second;
3017 
3018   // If the module map file wasn't already entered, do so now.
3019   if (ID.isInvalid()) {
3020     auto FileCharacter =
3021         IsSystem ? SrcMgr::C_System_ModuleMap : SrcMgr::C_User_ModuleMap;
3022     ID = SourceMgr.createFileID(File, ExternModuleLoc, FileCharacter);
3023   }
3024 
3025   assert(Target && "Missing target information");
3026   llvm::Optional<llvm::MemoryBufferRef> Buffer = SourceMgr.getBufferOrNone(ID);
3027   if (!Buffer)
3028     return ParsedModuleMap[File] = true;
3029   assert((!Offset || *Offset <= Buffer->getBufferSize()) &&
3030          "invalid buffer offset");
3031 
3032   // Parse this module map file.
3033   Lexer L(SourceMgr.getLocForStartOfFile(ID), MMapLangOpts,
3034           Buffer->getBufferStart(),
3035           Buffer->getBufferStart() + (Offset ? *Offset : 0),
3036           Buffer->getBufferEnd());
3037   SourceLocation Start = L.getSourceLocation();
3038   ModuleMapParser Parser(L, SourceMgr, Target, Diags, *this, File, Dir,
3039                          IsSystem);
3040   bool Result = Parser.parseModuleMapFile();
3041   ParsedModuleMap[File] = Result;
3042 
3043   if (Offset) {
3044     auto Loc = SourceMgr.getDecomposedLoc(Parser.getLocation());
3045     assert(Loc.first == ID && "stopped in a different file?");
3046     *Offset = Loc.second;
3047   }
3048 
3049   // Notify callbacks that we parsed it.
3050   for (const auto &Cb : Callbacks)
3051     Cb->moduleMapFileRead(Start, *File, IsSystem);
3052 
3053   return Result;
3054 }
3055