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