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