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