clang 22.0.0git
ModuleMap.cpp
Go to the documentation of this file.
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"
18#include "clang/Basic/LLVM.h"
20#include "clang/Basic/Module.h"
28#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/STLExtras.h"
30#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/ADT/SmallVector.h"
32#include "llvm/ADT/StringMap.h"
33#include "llvm/ADT/StringRef.h"
34#include "llvm/ADT/StringSwitch.h"
35#include "llvm/Support/Compiler.h"
36#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/Path.h"
38#include "llvm/Support/VirtualFileSystem.h"
39#include "llvm/Support/raw_ostream.h"
40#include <cassert>
41#include <cstring>
42#include <optional>
43#include <string>
44#include <system_error>
45#include <utility>
46
47using namespace clang;
48
49void ModuleMapCallbacks::anchor() {}
50
52 auto PendingLinkAs = PendingLinkAsModule.find(Mod->Name);
53 if (PendingLinkAs != PendingLinkAsModule.end()) {
54 for (auto &Name : PendingLinkAs->second) {
55 auto *M = findModule(Name.getKey());
56 if (M)
57 M->UseExportAsModuleLinkName = true;
58 }
59 }
60}
61
63 if (findModule(Mod->ExportAsModule))
64 Mod->UseExportAsModuleLinkName = true;
65 else
66 PendingLinkAsModule[Mod->ExportAsModule].insert(Mod->Name);
67}
68
70 switch ((int)Role) {
71 case NormalHeader:
72 return Module::HK_Normal;
73 case PrivateHeader:
74 return Module::HK_Private;
75 case TextualHeader:
76 return Module::HK_Textual;
79 case ExcludedHeader:
81 }
82 llvm_unreachable("unknown header role");
83}
84
87 switch ((int)Kind) {
89 return NormalHeader;
91 return PrivateHeader;
93 return TextualHeader;
97 return ExcludedHeader;
98 }
99 llvm_unreachable("unknown header kind");
100}
101
104}
105
107ModuleMap::resolveExport(Module *Mod,
109 bool Complain) const {
110 // We may have just a wildcard.
111 if (Unresolved.Id.empty()) {
112 assert(Unresolved.Wildcard && "Invalid unresolved export");
113 return Module::ExportDecl(nullptr, true);
114 }
115
116 // Resolve the module-id.
117 Module *Context = resolveModuleId(Unresolved.Id, Mod, Complain);
118 if (!Context)
119 return {};
120
121 return Module::ExportDecl(Context, Unresolved.Wildcard);
122}
123
124Module *ModuleMap::resolveModuleId(const ModuleId &Id, Module *Mod,
125 bool Complain) const {
126 // Find the starting module.
127 Module *Context = lookupModuleUnqualified(Id[0].first, Mod);
128 if (!Context) {
129 if (Complain)
130 Diags.Report(Id[0].second, diag::err_mmap_missing_module_unqualified)
131 << Id[0].first << Mod->getFullModuleName();
132
133 return nullptr;
134 }
135
136 // Dig into the module path.
137 for (unsigned I = 1, N = Id.size(); I != N; ++I) {
138 Module *Sub = lookupModuleQualified(Id[I].first, Context);
139 if (!Sub) {
140 if (Complain)
141 Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
142 << Id[I].first << Context->getFullModuleName()
143 << SourceRange(Id[0].second, Id[I-1].second);
144
145 return nullptr;
146 }
147
148 Context = Sub;
149 }
150
151 return Context;
152}
153
154/// Append to \p Paths the set of paths needed to get to the
155/// subframework in which the given module lives.
158 // Collect the framework names from the given module to the top-level module.
160 for (; Mod; Mod = Mod->Parent) {
161 if (Mod->IsFramework)
162 Paths.push_back(Mod->Name);
163 }
164
165 if (Paths.empty())
166 return;
167
168 // Add Frameworks/Name.framework for each subframework.
169 for (StringRef Framework : llvm::drop_begin(llvm::reverse(Paths)))
170 llvm::sys::path::append(Path, "Frameworks", Framework + ".framework");
171}
172
173OptionalFileEntryRef ModuleMap::findHeader(
175 SmallVectorImpl<char> &RelativePathName, bool &NeedsFramework) {
176 // Search for the header file within the module's home directory.
177 auto Directory = M->Directory;
178 SmallString<128> FullPathName(Directory->getName());
179
180 auto GetFile = [&](StringRef Filename) -> OptionalFileEntryRef {
181 auto File =
182 expectedToOptional(SourceMgr.getFileManager().getFileRef(Filename));
183 if (!File || (Header.Size && File->getSize() != *Header.Size) ||
184 (Header.ModTime && File->getModificationTime() != *Header.ModTime))
185 return std::nullopt;
186 return *File;
187 };
188
189 auto GetFrameworkFile = [&]() -> OptionalFileEntryRef {
190 unsigned FullPathLength = FullPathName.size();
191 appendSubframeworkPaths(M, RelativePathName);
192 unsigned RelativePathLength = RelativePathName.size();
193
194 // Check whether this file is in the public headers.
195 llvm::sys::path::append(RelativePathName, "Headers", Header.FileName);
196 llvm::sys::path::append(FullPathName, RelativePathName);
197 if (auto File = GetFile(FullPathName))
198 return File;
199
200 // Check whether this file is in the private headers.
201 // Ideally, private modules in the form 'FrameworkName.Private' should
202 // be defined as 'module FrameworkName.Private', and not as
203 // 'framework module FrameworkName.Private', since a 'Private.Framework'
204 // does not usually exist. However, since both are currently widely used
205 // for private modules, make sure we find the right path in both cases.
206 if (M->IsFramework && M->Name == "Private")
207 RelativePathName.clear();
208 else
209 RelativePathName.resize(RelativePathLength);
210 FullPathName.resize(FullPathLength);
211 llvm::sys::path::append(RelativePathName, "PrivateHeaders",
212 Header.FileName);
213 llvm::sys::path::append(FullPathName, RelativePathName);
214 return GetFile(FullPathName);
215 };
216
217 if (llvm::sys::path::is_absolute(Header.FileName)) {
218 RelativePathName.clear();
219 RelativePathName.append(Header.FileName.begin(), Header.FileName.end());
220 return GetFile(Header.FileName);
221 }
222
223 if (M->isPartOfFramework())
224 return GetFrameworkFile();
225
226 // Lookup for normal headers.
227 llvm::sys::path::append(RelativePathName, Header.FileName);
228 llvm::sys::path::append(FullPathName, RelativePathName);
229 auto NormalHdrFile = GetFile(FullPathName);
230
231 if (!NormalHdrFile && Directory->getName().ends_with(".framework")) {
232 // The lack of 'framework' keyword in a module declaration it's a simple
233 // mistake we can diagnose when the header exists within the proper
234 // framework style path.
235 FullPathName.assign(Directory->getName());
236 RelativePathName.clear();
237 if (GetFrameworkFile()) {
238 Diags.Report(Header.FileNameLoc,
239 diag::warn_mmap_incomplete_framework_module_declaration)
240 << Header.FileName << M->getFullModuleName();
241 NeedsFramework = true;
242 }
243 return std::nullopt;
244 }
245
246 return NormalHdrFile;
247}
248
249/// Determine whether the given file name is the name of a builtin
250/// header, supplied by Clang to replace, override, or augment existing system
251/// headers.
252static bool isBuiltinHeaderName(StringRef FileName) {
253 return llvm::StringSwitch<bool>(FileName)
254 .Case("float.h", true)
255 .Case("iso646.h", true)
256 .Case("limits.h", true)
257 .Case("stdalign.h", true)
258 .Case("stdarg.h", true)
259 .Case("stdatomic.h", true)
260 .Case("stdbool.h", true)
261 .Case("stdcountof.h", true)
262 .Case("stddef.h", true)
263 .Case("stdint.h", true)
264 .Case("tgmath.h", true)
265 .Case("unwind.h", true)
266 .Default(false);
267}
268
269/// Determine whether the given module name is the name of a builtin
270/// module that is cyclic with a system module on some platforms.
271static bool isBuiltInModuleName(StringRef ModuleName) {
272 return llvm::StringSwitch<bool>(ModuleName)
273 .Case("_Builtin_float", true)
274 .Case("_Builtin_inttypes", true)
275 .Case("_Builtin_iso646", true)
276 .Case("_Builtin_limits", true)
277 .Case("_Builtin_stdalign", true)
278 .Case("_Builtin_stdarg", true)
279 .Case("_Builtin_stdatomic", true)
280 .Case("_Builtin_stdbool", true)
281 .Case("_Builtin_stddef", true)
282 .Case("_Builtin_stdint", true)
283 .Case("_Builtin_stdnoreturn", true)
284 .Case("_Builtin_tgmath", true)
285 .Case("_Builtin_unwind", true)
286 .Default(false);
287}
288
289void ModuleMap::resolveHeader(Module *Mod,
291 bool &NeedsFramework) {
292 SmallString<128> RelativePathName;
294 findHeader(Mod, Header, RelativePathName, NeedsFramework)) {
295 if (Header.IsUmbrella) {
296 const DirectoryEntry *UmbrellaDir = &File->getDir().getDirEntry();
297 if (Module *UmbrellaMod = UmbrellaDirs[UmbrellaDir])
298 Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash)
299 << UmbrellaMod->getFullModuleName();
300 else
301 // Record this umbrella header.
303 RelativePathName.str());
304 } else {
305 Module::Header H = {Header.FileName, std::string(RelativePathName),
306 *File};
307 addHeader(Mod, H, headerKindToRole(Header.Kind));
308 }
309 } else if (Header.HasBuiltinHeader && !Header.Size && !Header.ModTime) {
310 // There's a builtin header but no corresponding on-disk header. Assume
311 // this was supposed to modularize the builtin header alone.
312 } else if (Header.Kind == Module::HK_Excluded) {
313 // Ignore missing excluded header files. They're optional anyway.
314 } else {
315 // If we find a module that has a missing header, we mark this module as
316 // unavailable and store the header directive for displaying diagnostics.
317 Mod->MissingHeaders.push_back(Header);
318 // A missing header with stat information doesn't make the module
319 // unavailable; this keeps our behavior consistent as headers are lazily
320 // resolved. (Such a module still can't be built though, except from
321 // preprocessed source.)
322 if (!Header.Size && !Header.ModTime)
323 Mod->markUnavailable(/*Unimportable=*/false);
324 }
325}
326
327bool ModuleMap::resolveAsBuiltinHeader(
328 Module *Mod, const Module::UnresolvedHeaderDirective &Header) {
329 if (Header.Kind == Module::HK_Excluded ||
330 llvm::sys::path::is_absolute(Header.FileName) ||
331 Mod->isPartOfFramework() || !Mod->IsSystem || Header.IsUmbrella ||
332 !BuiltinIncludeDir || BuiltinIncludeDir == Mod->Directory ||
333 !LangOpts.BuiltinHeadersInSystemModules || !isBuiltinHeaderName(Header.FileName))
334 return false;
335
336 // This is a system module with a top-level header. This header
337 // may have a counterpart (or replacement) in the set of headers
338 // supplied by Clang. Find that builtin header.
340 llvm::sys::path::append(Path, BuiltinIncludeDir->getName(), Header.FileName);
341 auto File = SourceMgr.getFileManager().getOptionalFileRef(Path);
342 if (!File)
343 return false;
344
345 Module::Header H = {Header.FileName, Header.FileName, *File};
346 auto Role = headerKindToRole(Header.Kind);
347 addHeader(Mod, H, Role);
348 return true;
349}
350
352 const LangOptions &LangOpts, const TargetInfo *Target,
353 HeaderSearch &HeaderInfo)
354 : SourceMgr(SourceMgr), Diags(Diags), LangOpts(LangOpts), Target(Target),
355 HeaderInfo(HeaderInfo) {
356}
357
358ModuleMap::~ModuleMap() = default;
359
361 assert((!this->Target || this->Target == &Target) &&
362 "Improper target override");
363 this->Target = &Target;
364}
365
366/// "Sanitize" a filename so that it can be used as an identifier.
367static StringRef sanitizeFilenameAsIdentifier(StringRef Name,
368 SmallVectorImpl<char> &Buffer) {
369 if (Name.empty())
370 return Name;
371
372 if (!isValidAsciiIdentifier(Name)) {
373 // If we don't already have something with the form of an identifier,
374 // create a buffer with the sanitized name.
375 Buffer.clear();
376 if (isDigit(Name[0]))
377 Buffer.push_back('_');
378 Buffer.reserve(Buffer.size() + Name.size());
379 for (unsigned I = 0, N = Name.size(); I != N; ++I) {
380 if (isAsciiIdentifierContinue(Name[I]))
381 Buffer.push_back(Name[I]);
382 else
383 Buffer.push_back('_');
384 }
385
386 Name = StringRef(Buffer.data(), Buffer.size());
387 }
388
389 while (llvm::StringSwitch<bool>(Name)
390#define KEYWORD(Keyword,Conditions) .Case(#Keyword, true)
391#define ALIAS(Keyword, AliasOf, Conditions) .Case(Keyword, true)
392#include "clang/Basic/TokenKinds.def"
393 .Default(false)) {
394 if (Name.data() != Buffer.data())
395 Buffer.append(Name.begin(), Name.end());
396 Buffer.push_back('_');
397 Name = StringRef(Buffer.data(), Buffer.size());
398 }
399
400 return Name;
401}
402
404 return File.getDir() == BuiltinIncludeDir && LangOpts.BuiltinHeadersInSystemModules &&
405 isBuiltinHeaderName(llvm::sys::path::filename(File.getName()));
406}
407
409 Module *Module) const {
410 return LangOpts.BuiltinHeadersInSystemModules && BuiltinIncludeDir &&
413}
414
415ModuleMap::HeadersMap::iterator ModuleMap::findKnownHeader(FileEntryRef File) {
417 HeadersMap::iterator Known = Headers.find(File);
418 if (HeaderInfo.getHeaderSearchOpts().ImplicitModuleMaps &&
419 Known == Headers.end() && ModuleMap::isBuiltinHeader(File)) {
420 HeaderInfo.loadTopLevelSystemModules();
421 return Headers.find(File);
422 }
423 return Known;
424}
425
426ModuleMap::KnownHeader ModuleMap::findHeaderInUmbrellaDirs(
428 if (UmbrellaDirs.empty())
429 return {};
430
431 OptionalDirectoryEntryRef Dir = File.getDir();
432
433 // Note: as an egregious but useful hack we use the real path here, because
434 // frameworks moving from top-level frameworks to embedded frameworks tend
435 // to be symlinked from the top-level location to the embedded location,
436 // and we need to resolve lookups as if we had found the embedded location.
437 StringRef DirName = SourceMgr.getFileManager().getCanonicalName(*Dir);
438
439 // Keep walking up the directory hierarchy, looking for a directory with
440 // an umbrella header.
441 do {
442 auto KnownDir = UmbrellaDirs.find(*Dir);
443 if (KnownDir != UmbrellaDirs.end())
444 return KnownHeader(KnownDir->second, NormalHeader);
445
446 IntermediateDirs.push_back(*Dir);
447
448 // Retrieve our parent path.
449 DirName = llvm::sys::path::parent_path(DirName);
450 if (DirName.empty())
451 break;
452
453 // Resolve the parent path to a directory entry.
454 Dir = SourceMgr.getFileManager().getOptionalDirectoryRef(DirName);
455 } while (Dir);
456 return {};
457}
458
459static bool violatesPrivateInclude(Module *RequestingModule,
460 const FileEntry *IncFileEnt,
461 ModuleMap::KnownHeader Header) {
462#ifndef NDEBUG
463 if (Header.getRole() & ModuleMap::PrivateHeader) {
464 // Check for consistency between the module header role
465 // as obtained from the lookup and as obtained from the module.
466 // This check is not cheap, so enable it only for debugging.
467 bool IsPrivate = false;
468 ArrayRef<Module::Header> HeaderList[] = {
471 for (auto Hs : HeaderList)
472 IsPrivate |= llvm::any_of(
473 Hs, [&](const Module::Header &H) { return H.Entry == IncFileEnt; });
474 assert(IsPrivate && "inconsistent headers and roles");
475 }
476#endif
477 return !Header.isAccessibleFrom(RequestingModule);
478}
479
481 return M ? M->getTopLevelModule() : nullptr;
482}
483
485 bool RequestingModuleIsModuleInterface,
486 SourceLocation FilenameLoc,
487 StringRef Filename, FileEntryRef File) {
488 // No errors for indirect modules. This may be a bit of a problem for modules
489 // with no source files.
490 if (getTopLevelOrNull(RequestingModule) != getTopLevelOrNull(SourceModule))
491 return;
492
493 if (RequestingModule) {
494 resolveUses(RequestingModule, /*Complain=*/false);
495 resolveHeaderDirectives(RequestingModule, /*File=*/std::nullopt);
496 }
497
498 bool Excluded = false;
499 Module *Private = nullptr;
500 Module *NotUsed = nullptr;
501
502 HeadersMap::iterator Known = findKnownHeader(File);
503 if (Known != Headers.end()) {
504 for (const KnownHeader &Header : Known->second) {
505 // Excluded headers don't really belong to a module.
506 if (Header.getRole() == ModuleMap::ExcludedHeader) {
507 Excluded = true;
508 continue;
509 }
510
511 // Remember private headers for later printing of a diagnostic.
512 if (violatesPrivateInclude(RequestingModule, File, Header)) {
513 Private = Header.getModule();
514 continue;
515 }
516
517 // If uses need to be specified explicitly, we are only allowed to return
518 // modules that are explicitly used by the requesting module.
519 if (RequestingModule && LangOpts.ModulesDeclUse &&
520 !RequestingModule->directlyUses(Header.getModule())) {
521 NotUsed = Header.getModule();
522 continue;
523 }
524
525 // We have found a module that we can happily use.
526 return;
527 }
528
529 Excluded = true;
530 }
531
532 // We have found a header, but it is private.
533 if (Private) {
534 Diags.Report(FilenameLoc, diag::warn_use_of_private_header_outside_module)
535 << Filename;
536 return;
537 }
538
539 // We have found a module, but we don't use it.
540 if (NotUsed) {
541 Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module_indirect)
542 << RequestingModule->getTopLevelModule()->Name << Filename
543 << NotUsed->Name;
544 return;
545 }
546
547 if (Excluded || isHeaderInUmbrellaDirs(File))
548 return;
549
550 // At this point, only non-modular includes remain.
551
552 if (RequestingModule && LangOpts.ModulesStrictDeclUse) {
553 Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module)
554 << RequestingModule->getTopLevelModule()->Name << Filename;
555 } else if (RequestingModule && RequestingModuleIsModuleInterface &&
556 LangOpts.isCompilingModule()) {
557 // Do not diagnose when we are not compiling a module.
558 diag::kind DiagID = RequestingModule->getTopLevelModule()->IsFramework ?
559 diag::warn_non_modular_include_in_framework_module :
560 diag::warn_non_modular_include_in_module;
561 Diags.Report(FilenameLoc, DiagID) << RequestingModule->getFullModuleName()
562 << File.getName();
563 }
564}
565
567 const ModuleMap::KnownHeader &Old) {
568 // Prefer available modules.
569 // FIXME: Considering whether the module is available rather than merely
570 // importable is non-hermetic and can result in surprising behavior for
571 // prebuilt modules. Consider only checking for importability here.
572 if (New.getModule()->isAvailable() && !Old.getModule()->isAvailable())
573 return true;
574
575 // Prefer a public header over a private header.
576 if ((New.getRole() & ModuleMap::PrivateHeader) !=
578 return !(New.getRole() & ModuleMap::PrivateHeader);
579
580 // Prefer a non-textual header over a textual header.
581 if ((New.getRole() & ModuleMap::TextualHeader) !=
583 return !(New.getRole() & ModuleMap::TextualHeader);
584
585 // Prefer a non-excluded header over an excluded header.
586 if ((New.getRole() == ModuleMap::ExcludedHeader) !=
588 return New.getRole() != ModuleMap::ExcludedHeader;
589
590 // Don't have a reason to choose between these. Just keep the first one.
591 return false;
592}
593
595 bool AllowTextual,
596 bool AllowExcluded) {
597 auto MakeResult = [&](ModuleMap::KnownHeader R) -> ModuleMap::KnownHeader {
598 if (!AllowTextual && R.getRole() & ModuleMap::TextualHeader)
599 return {};
600 return R;
601 };
602
603 HeadersMap::iterator Known = findKnownHeader(File);
604 if (Known != Headers.end()) {
606 // Iterate over all modules that 'File' is part of to find the best fit.
607 for (KnownHeader &H : Known->second) {
608 // Cannot use a module if the header is excluded in it.
609 if (!AllowExcluded && H.getRole() == ModuleMap::ExcludedHeader)
610 continue;
611 // Prefer a header from the source module over all others.
612 if (H.getModule()->getTopLevelModule() == SourceModule)
613 return MakeResult(H);
615 Result = H;
616 }
617 return MakeResult(Result);
618 }
619
620 return MakeResult(findOrCreateModuleForHeaderInUmbrellaDir(File));
621}
622
624ModuleMap::findOrCreateModuleForHeaderInUmbrellaDir(FileEntryRef File) {
625 assert(!Headers.count(File) && "already have a module for this header");
626
628 KnownHeader H = findHeaderInUmbrellaDirs(File, SkippedDirs);
629 if (H) {
630 Module *Result = H.getModule();
631
632 // Search up the module stack until we find a module with an umbrella
633 // directory.
634 Module *UmbrellaModule = Result;
635 while (!UmbrellaModule->getEffectiveUmbrellaDir() && UmbrellaModule->Parent)
636 UmbrellaModule = UmbrellaModule->Parent;
637
638 if (UmbrellaModule->InferSubmodules) {
639 FileID UmbrellaModuleMap = getModuleMapFileIDForUniquing(UmbrellaModule);
640
641 // Infer submodules for each of the directories we found between
642 // the directory of the umbrella header and the directory where
643 // the actual header is located.
644 bool Explicit = UmbrellaModule->InferExplicitSubmodules;
645
646 for (DirectoryEntryRef SkippedDir : llvm::reverse(SkippedDirs)) {
647 // Find or create the module that corresponds to this directory name.
648 SmallString<32> NameBuf;
649 StringRef Name = sanitizeFilenameAsIdentifier(
650 llvm::sys::path::stem(SkippedDir.getName()), NameBuf);
651 Result = findOrCreateModuleFirst(Name, Result, /*IsFramework=*/false,
652 Explicit);
653 setInferredModuleAllowedBy(Result, UmbrellaModuleMap);
654
655 // Associate the module and the directory.
656 UmbrellaDirs[SkippedDir] = Result;
657
658 // If inferred submodules export everything they import, add a
659 // wildcard to the set of exports.
660 if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
661 Result->Exports.push_back(Module::ExportDecl(nullptr, true));
662 }
663
664 // Infer a submodule with the same name as this header file.
665 SmallString<32> NameBuf;
666 StringRef Name = sanitizeFilenameAsIdentifier(
667 llvm::sys::path::stem(File.getName()), NameBuf);
668 Result = findOrCreateModuleFirst(Name, Result, /*IsFramework=*/false,
669 Explicit);
670 setInferredModuleAllowedBy(Result, UmbrellaModuleMap);
671 Result->addTopHeader(File);
672
673 // If inferred submodules export everything they import, add a
674 // wildcard to the set of exports.
675 if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
676 Result->Exports.push_back(Module::ExportDecl(nullptr, true));
677 } else {
678 // Record each of the directories we stepped through as being part of
679 // the module we found, since the umbrella header covers them all.
680 for (unsigned I = 0, N = SkippedDirs.size(); I != N; ++I)
681 UmbrellaDirs[SkippedDirs[I]] = Result;
682 }
683
684 KnownHeader Header(Result, NormalHeader);
685 Headers[File].push_back(Header);
686 return Header;
687 }
688
689 return {};
690}
691
694 HeadersMap::iterator Known = findKnownHeader(File);
695 if (Known != Headers.end())
696 return Known->second;
697
698 if (findOrCreateModuleForHeaderInUmbrellaDir(File))
699 return Headers.find(File)->second;
700
701 return {};
702}
703
706 // FIXME: Is this necessary?
708 auto It = Headers.find(File);
709 if (It == Headers.end())
710 return {};
711 return It->second;
712}
713
715 return isHeaderUnavailableInModule(Header, nullptr);
716}
717
719 FileEntryRef Header, const Module *RequestingModule) const {
721 HeadersMap::const_iterator Known = Headers.find(Header);
722 if (Known != Headers.end()) {
724 I = Known->second.begin(),
725 E = Known->second.end();
726 I != E; ++I) {
727
728 if (I->getRole() == ModuleMap::ExcludedHeader)
729 continue;
730
731 if (I->isAvailable() &&
732 (!RequestingModule ||
733 I->getModule()->isSubModuleOf(RequestingModule))) {
734 // When no requesting module is available, the caller is looking if a
735 // header is part a module by only looking into the module map. This is
736 // done by warn_uncovered_module_header checks; don't consider textual
737 // headers part of it in this mode, otherwise we get misleading warnings
738 // that a umbrella header is not including a textual header.
739 if (!RequestingModule && I->getRole() == ModuleMap::TextualHeader)
740 continue;
741 return false;
742 }
743 }
744 return true;
745 }
746
747 OptionalDirectoryEntryRef Dir = Header.getDir();
749 StringRef DirName = Dir->getName();
750
751 auto IsUnavailable = [&](const Module *M) {
752 return !M->isAvailable() && (!RequestingModule ||
753 M->isSubModuleOf(RequestingModule));
754 };
755
756 // Keep walking up the directory hierarchy, looking for a directory with
757 // an umbrella header.
758 do {
759 auto KnownDir = UmbrellaDirs.find(*Dir);
760 if (KnownDir != UmbrellaDirs.end()) {
761 Module *Found = KnownDir->second;
762 if (IsUnavailable(Found))
763 return true;
764
765 // Search up the module stack until we find a module with an umbrella
766 // directory.
767 Module *UmbrellaModule = Found;
768 while (!UmbrellaModule->getEffectiveUmbrellaDir() &&
769 UmbrellaModule->Parent)
770 UmbrellaModule = UmbrellaModule->Parent;
771
772 if (UmbrellaModule->InferSubmodules) {
773 for (DirectoryEntryRef SkippedDir : llvm::reverse(SkippedDirs)) {
774 // Find or create the module that corresponds to this directory name.
775 SmallString<32> NameBuf;
776 StringRef Name = sanitizeFilenameAsIdentifier(
777 llvm::sys::path::stem(SkippedDir.getName()), NameBuf);
779 if (!Found)
780 return false;
781 if (IsUnavailable(Found))
782 return true;
783 }
784
785 // Infer a submodule with the same name as this header file.
786 SmallString<32> NameBuf;
787 StringRef Name = sanitizeFilenameAsIdentifier(
788 llvm::sys::path::stem(Header.getName()),
789 NameBuf);
791 if (!Found)
792 return false;
793 }
794
795 return IsUnavailable(Found);
796 }
797
798 SkippedDirs.push_back(*Dir);
799
800 // Retrieve our parent path.
801 DirName = llvm::sys::path::parent_path(DirName);
802 if (DirName.empty())
803 break;
804
805 // Resolve the parent path to a directory entry.
806 Dir = SourceMgr.getFileManager().getOptionalDirectoryRef(DirName);
807 } while (Dir);
808
809 return false;
810}
811
812Module *ModuleMap::findModule(StringRef Name) const {
813 llvm::StringMap<Module *>::const_iterator Known = Modules.find(Name);
814 if (Known != Modules.end())
815 return Known->getValue();
816
817 return nullptr;
818}
819
821 if (Module *SubM = Parent->findSubmodule(Name))
822 return SubM;
823 if (!Parent->InferSubmodules)
824 return nullptr;
825 Module *Result = new (ModulesAlloc.Allocate())
827 Parent->InferExplicitSubmodules, 0);
828 Result->InferExplicitSubmodules = Parent->InferExplicitSubmodules;
829 Result->InferSubmodules = Parent->InferSubmodules;
830 Result->InferExportWildcard = Parent->InferExportWildcard;
831 if (Result->InferExportWildcard)
832 Result->Exports.push_back(Module::ExportDecl(nullptr, true));
833 return Result;
834}
835
837 Module *Context) const {
838 for(; Context; Context = Context->Parent) {
839 if (Module *Sub = lookupModuleQualified(Name, Context))
840 return Sub;
841 }
842
843 return findModule(Name);
844}
845
846Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) const{
847 if (!Context)
848 return findModule(Name);
849
850 return Context->findSubmodule(Name);
851}
852
853std::pair<Module *, bool> ModuleMap::findOrCreateModule(StringRef Name,
854 Module *Parent,
855 bool IsFramework,
856 bool IsExplicit) {
857 // Try to find an existing module with this name.
858 if (Module *Sub = lookupModuleQualified(Name, Parent))
859 return std::make_pair(Sub, false);
860
861 // Create a new module with this name.
862 Module *M = createModule(Name, Parent, IsFramework, IsExplicit);
863 return std::make_pair(M, true);
864}
865
867 bool IsFramework, bool IsExplicit) {
868 assert(lookupModuleQualified(Name, Parent) == nullptr &&
869 "Creating duplicate submodule");
870
871 Module *Result = new (ModulesAlloc.Allocate())
873 IsFramework, IsExplicit, NumCreatedModules++);
874 if (!Parent) {
875 if (LangOpts.CurrentModule == Name)
876 SourceModule = Result;
877 Modules[Name] = Result;
878 ModuleScopeIDs[Result] = CurrentModuleScopeID;
879 }
880 return Result;
881}
882
884 Module *Parent) {
885 auto *Result = new (ModulesAlloc.Allocate()) Module(
886 ModuleConstructorTag{}, "<global>", Loc, Parent, /*IsFramework=*/false,
887 /*IsExplicit=*/true, NumCreatedModules++);
889 // If the created module isn't owned by a parent, send it to PendingSubmodules
890 // to wait for its parent.
891 if (!Result->Parent)
892 PendingSubmodules.emplace_back(Result);
893 return Result;
894}
895
896Module *
898 Module *Parent) {
899 assert(Parent && "We should only create an implicit global module fragment "
900 "in a module purview");
901 // Note: Here the `IsExplicit` parameter refers to the semantics in clang
902 // modules. All the non-explicit submodules in clang modules will be exported
903 // too. Here we simplify the implementation by using the concept.
904 auto *Result = new (ModulesAlloc.Allocate())
905 Module(ModuleConstructorTag{}, "<implicit global>", Loc, Parent,
906 /*IsFramework=*/false, /*IsExplicit=*/false, NumCreatedModules++);
908 return Result;
909}
910
911Module *
914 auto *Result = new (ModulesAlloc.Allocate()) Module(
915 ModuleConstructorTag{}, "<private>", Loc, Parent, /*IsFramework=*/false,
916 /*IsExplicit=*/true, NumCreatedModules++);
918 return Result;
919}
920
922 Module::ModuleKind Kind) {
923 auto *Result = new (ModulesAlloc.Allocate())
924 Module(ModuleConstructorTag{}, Name, Loc, nullptr, /*IsFramework=*/false,
925 /*IsExplicit=*/false, NumCreatedModules++);
926 Result->Kind = Kind;
927
928 // Reparent any current global module fragment as a submodule of this module.
929 for (auto &Submodule : PendingSubmodules)
930 Submodule->setParent(Result);
931 PendingSubmodules.clear();
932 return Result;
933}
934
936 StringRef Name) {
937 assert(LangOpts.CurrentModule == Name && "module name mismatch");
938 assert(!Modules[Name] && "redefining existing module");
939
940 auto *Result =
942 Modules[Name] = SourceModule = Result;
943
944 // Mark the main source file as being within the newly-created module so that
945 // declarations and macros are properly visibility-restricted to it.
946 auto MainFile = SourceMgr.getFileEntryRefForID(SourceMgr.getMainFileID());
947 assert(MainFile && "no input file for module interface");
948 Headers[*MainFile].push_back(KnownHeader(Result, PrivateHeader));
949
950 return Result;
951}
952
954 StringRef Name) {
955 assert(LangOpts.CurrentModule == Name && "module name mismatch");
956 // The interface for this implementation must exist and be loaded.
957 assert(Modules[Name] && Modules[Name]->Kind == Module::ModuleInterfaceUnit &&
958 "creating implementation module without an interface");
959
960 // Create an entry in the modules map to own the implementation unit module.
961 // User module names must not start with a period (so that this cannot clash
962 // with any legal user-defined module name).
963 StringRef IName = ".ImplementationUnit";
964 assert(!Modules[IName] && "multiple implementation units?");
965
966 auto *Result =
968 Modules[IName] = SourceModule = Result;
969
970 // Check that the main file is present.
971 assert(SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) &&
972 "no input file for module implementation");
973
974 return Result;
975}
976
978 Module::Header H) {
979 assert(LangOpts.CurrentModule == Name && "module name mismatch");
980 assert(!Modules[Name] && "redefining existing module");
981
982 auto *Result = new (ModulesAlloc.Allocate())
983 Module(ModuleConstructorTag{}, Name, Loc, nullptr, /*IsFramework=*/false,
984 /*IsExplicit=*/false, NumCreatedModules++);
986 Modules[Name] = SourceModule = Result;
988 return Result;
989}
990
991/// For a framework module, infer the framework against which we
992/// should link.
993static void inferFrameworkLink(Module *Mod) {
994 assert(Mod->IsFramework && "Can only infer linking for framework modules");
995 assert(!Mod->isSubFramework() &&
996 "Can only infer linking for top-level frameworks");
997
998 StringRef FrameworkName(Mod->Name);
999 FrameworkName.consume_back("_Private");
1000 Mod->LinkLibraries.push_back(Module::LinkLibrary(FrameworkName.str(),
1001 /*IsFramework=*/true));
1002}
1003
1004Module *ModuleMap::inferFrameworkModule(DirectoryEntryRef FrameworkDir,
1005 bool IsSystem, Module *Parent) {
1006 Attributes Attrs;
1007 Attrs.IsSystem = IsSystem;
1008 return inferFrameworkModule(FrameworkDir, Attrs, Parent);
1009}
1010
1011Module *ModuleMap::inferFrameworkModule(DirectoryEntryRef FrameworkDir,
1012 Attributes Attrs, Module *Parent) {
1013 // Note: as an egregious but useful hack we use the real path here, because
1014 // we might be looking at an embedded framework that symlinks out to a
1015 // top-level framework, and we need to infer as if we were naming the
1016 // top-level framework.
1017 StringRef FrameworkDirName =
1018 SourceMgr.getFileManager().getCanonicalName(FrameworkDir);
1019
1020 // In case this is a case-insensitive filesystem, use the canonical
1021 // directory name as the ModuleName, since modules are case-sensitive.
1022 // FIXME: we should be able to give a fix-it hint for the correct spelling.
1023 SmallString<32> ModuleNameStorage;
1024 StringRef ModuleName = sanitizeFilenameAsIdentifier(
1025 llvm::sys::path::stem(FrameworkDirName), ModuleNameStorage);
1026
1027 // Check whether we've already found this module.
1028 if (Module *Mod = lookupModuleQualified(ModuleName, Parent))
1029 return Mod;
1030
1031 FileManager &FileMgr = SourceMgr.getFileManager();
1032
1033 // If the framework has a parent path from which we're allowed to infer
1034 // a framework module, do so.
1035 FileID ModuleMapFID;
1036 if (!Parent) {
1037 // Determine whether we're allowed to infer a module map.
1038 bool canInfer = false;
1039 if (llvm::sys::path::has_parent_path(FrameworkDirName)) {
1040 // Figure out the parent path.
1041 StringRef Parent = llvm::sys::path::parent_path(FrameworkDirName);
1042 if (auto ParentDir = FileMgr.getOptionalDirectoryRef(Parent)) {
1043 // Check whether we have already looked into the parent directory
1044 // for a module map.
1045 llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
1046 inferred = InferredDirectories.find(*ParentDir);
1047 if (inferred == InferredDirectories.end()) {
1048 // We haven't looked here before. Load a module map, if there is
1049 // one.
1050 bool IsFrameworkDir = Parent.ends_with(".framework");
1051 if (OptionalFileEntryRef ModMapFile =
1052 HeaderInfo.lookupModuleMapFile(*ParentDir, IsFrameworkDir)) {
1053 // TODO: Parsing a module map should populate `InferredDirectories`
1054 // so we don't need to do a full load here.
1055 parseAndLoadModuleMapFile(*ModMapFile, Attrs.IsSystem, *ParentDir);
1056 inferred = InferredDirectories.find(*ParentDir);
1057 }
1058
1059 if (inferred == InferredDirectories.end())
1060 inferred = InferredDirectories.insert(
1061 std::make_pair(*ParentDir, InferredDirectory())).first;
1062 }
1063
1064 if (inferred->second.InferModules) {
1065 // We're allowed to infer for this directory, but make sure it's okay
1066 // to infer this particular module.
1067 StringRef Name = llvm::sys::path::stem(FrameworkDirName);
1068 canInfer =
1069 !llvm::is_contained(inferred->second.ExcludedModules, Name);
1070
1071 Attrs.IsSystem |= inferred->second.Attrs.IsSystem;
1072 Attrs.IsExternC |= inferred->second.Attrs.IsExternC;
1073 Attrs.IsExhaustive |= inferred->second.Attrs.IsExhaustive;
1074 Attrs.NoUndeclaredIncludes |=
1075 inferred->second.Attrs.NoUndeclaredIncludes;
1076 ModuleMapFID = inferred->second.ModuleMapFID;
1077 }
1078 }
1079 }
1080
1081 // If we're not allowed to infer a framework module, don't.
1082 if (!canInfer)
1083 return nullptr;
1084 } else {
1085 ModuleMapFID = getModuleMapFileIDForUniquing(Parent);
1086 }
1087
1088 // Look for an umbrella header.
1089 SmallString<128> UmbrellaName = FrameworkDir.getName();
1090 llvm::sys::path::append(UmbrellaName, "Headers", ModuleName + ".h");
1091 auto UmbrellaHeader = FileMgr.getOptionalFileRef(UmbrellaName);
1092
1093 // FIXME: If there's no umbrella header, we could probably scan the
1094 // framework to load *everything*. But, it's not clear that this is a good
1095 // idea.
1096 if (!UmbrellaHeader)
1097 return nullptr;
1098
1099 Module *Result = new (ModulesAlloc.Allocate())
1101 /*IsFramework=*/true, /*IsExplicit=*/false, NumCreatedModules++);
1102 setInferredModuleAllowedBy(Result, ModuleMapFID);
1103 if (!Parent) {
1104 if (LangOpts.CurrentModule == ModuleName)
1105 SourceModule = Result;
1106 Modules[ModuleName] = Result;
1107 ModuleScopeIDs[Result] = CurrentModuleScopeID;
1108 }
1109
1110 Result->IsSystem |= Attrs.IsSystem;
1111 Result->IsExternC |= Attrs.IsExternC;
1112 Result->ConfigMacrosExhaustive |= Attrs.IsExhaustive;
1113 Result->NoUndeclaredIncludes |= Attrs.NoUndeclaredIncludes;
1114 Result->Directory = FrameworkDir;
1115
1116 // Chop off the first framework bit, as that is implied.
1117 StringRef RelativePath = UmbrellaName.str().substr(
1118 Result->getTopLevelModule()->Directory->getName().size());
1119 RelativePath = llvm::sys::path::relative_path(RelativePath);
1120
1121 // umbrella header "umbrella-header-name"
1122 setUmbrellaHeaderAsWritten(Result, *UmbrellaHeader, ModuleName + ".h",
1123 RelativePath);
1124
1125 // export *
1126 Result->Exports.push_back(Module::ExportDecl(nullptr, true));
1127
1128 // module * { export * }
1129 Result->InferSubmodules = true;
1130 Result->InferExportWildcard = true;
1131
1132 // Look for subframeworks.
1133 std::error_code EC;
1134 SmallString<128> SubframeworksDirName = FrameworkDir.getName();
1135 llvm::sys::path::append(SubframeworksDirName, "Frameworks");
1136 llvm::sys::path::native(SubframeworksDirName);
1137 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
1138 for (llvm::vfs::directory_iterator
1139 Dir = FS.dir_begin(SubframeworksDirName, EC),
1140 DirEnd;
1141 Dir != DirEnd && !EC; Dir.increment(EC)) {
1142 if (!StringRef(Dir->path()).ends_with(".framework"))
1143 continue;
1144
1145 if (auto SubframeworkDir = FileMgr.getOptionalDirectoryRef(Dir->path())) {
1146 // Note: as an egregious but useful hack, we use the real path here and
1147 // check whether it is actually a subdirectory of the parent directory.
1148 // This will not be the case if the 'subframework' is actually a symlink
1149 // out to a top-level framework.
1150 StringRef SubframeworkDirName =
1151 FileMgr.getCanonicalName(*SubframeworkDir);
1152 bool FoundParent = false;
1153 do {
1154 // Get the parent directory name.
1155 SubframeworkDirName
1156 = llvm::sys::path::parent_path(SubframeworkDirName);
1157 if (SubframeworkDirName.empty())
1158 break;
1159
1160 if (auto SubDir =
1161 FileMgr.getOptionalDirectoryRef(SubframeworkDirName)) {
1162 if (*SubDir == FrameworkDir) {
1163 FoundParent = true;
1164 break;
1165 }
1166 }
1167 } while (true);
1168
1169 if (!FoundParent)
1170 continue;
1171
1172 // FIXME: Do we want to warn about subframeworks without umbrella headers?
1173 inferFrameworkModule(*SubframeworkDir, Attrs, Result);
1174 }
1175 }
1176
1177 // If the module is a top-level framework, automatically link against the
1178 // framework.
1179 if (!Result->isSubFramework())
1181
1182 return Result;
1183}
1184
1185Module *ModuleMap::createShadowedModule(StringRef Name, bool IsFramework,
1186 Module *ShadowingModule) {
1187
1188 // Create a new module with this name.
1189 Module *Result = new (ModulesAlloc.Allocate())
1190 Module(ModuleConstructorTag{}, Name, SourceLocation(), /*Parent=*/nullptr,
1191 IsFramework, /*IsExplicit=*/false, NumCreatedModules++);
1192 Result->ShadowingModule = ShadowingModule;
1193 Result->markUnavailable(/*Unimportable*/true);
1194 ModuleScopeIDs[Result] = CurrentModuleScopeID;
1195 ShadowModules.push_back(Result);
1196
1197 return Result;
1198}
1199
1201 Module *Mod, FileEntryRef UmbrellaHeader, const Twine &NameAsWritten,
1202 const Twine &PathRelativeToRootModuleDirectory) {
1203 Headers[UmbrellaHeader].push_back(KnownHeader(Mod, NormalHeader));
1204 Mod->Umbrella = UmbrellaHeader;
1205 Mod->UmbrellaAsWritten = NameAsWritten.str();
1207 PathRelativeToRootModuleDirectory.str();
1208 UmbrellaDirs[UmbrellaHeader.getDir()] = Mod;
1209
1210 // Notify callbacks that we just added a new header.
1211 for (const auto &Cb : Callbacks)
1212 Cb->moduleMapAddUmbrellaHeader(UmbrellaHeader);
1213}
1214
1216 Module *Mod, DirectoryEntryRef UmbrellaDir, const Twine &NameAsWritten,
1217 const Twine &PathRelativeToRootModuleDirectory) {
1218 Mod->Umbrella = UmbrellaDir;
1219 Mod->UmbrellaAsWritten = NameAsWritten.str();
1221 PathRelativeToRootModuleDirectory.str();
1222 UmbrellaDirs[UmbrellaDir] = Mod;
1223}
1224
1225void ModuleMap::addUnresolvedHeader(Module *Mod,
1227 bool &NeedsFramework) {
1228 // If there is a builtin counterpart to this file, add it now so it can
1229 // wrap the system header.
1230 if (resolveAsBuiltinHeader(Mod, Header)) {
1231 // If we have both a builtin and system version of the file, the
1232 // builtin version may want to inject macros into the system header, so
1233 // force the system header to be treated as a textual header in this
1234 // case.
1237 Header.HasBuiltinHeader = true;
1238 }
1239
1240 // If possible, don't stat the header until we need to. This requires the
1241 // user to have provided us with some stat information about the file.
1242 // FIXME: Add support for lazily stat'ing umbrella headers and excluded
1243 // headers.
1244 if ((Header.Size || Header.ModTime) && !Header.IsUmbrella &&
1245 Header.Kind != Module::HK_Excluded) {
1246 // We expect more variation in mtime than size, so if we're given both,
1247 // use the mtime as the key.
1248 if (Header.ModTime)
1249 LazyHeadersByModTime[*Header.ModTime].push_back(Mod);
1250 else
1251 LazyHeadersBySize[*Header.Size].push_back(Mod);
1252 Mod->UnresolvedHeaders.push_back(Header);
1253 return;
1254 }
1255
1256 // We don't have stat information or can't defer looking this file up.
1257 // Perform the lookup now.
1258 resolveHeader(Mod, Header, NeedsFramework);
1259}
1260
1262 auto BySize = LazyHeadersBySize.find(File->getSize());
1263 if (BySize != LazyHeadersBySize.end()) {
1264 for (auto *M : BySize->second)
1266 LazyHeadersBySize.erase(BySize);
1267 }
1268
1269 auto ByModTime = LazyHeadersByModTime.find(File->getModificationTime());
1270 if (ByModTime != LazyHeadersByModTime.end()) {
1271 for (auto *M : ByModTime->second)
1273 LazyHeadersByModTime.erase(ByModTime);
1274 }
1275}
1276
1278 Module *Mod, std::optional<const FileEntry *> File) const {
1279 bool NeedsFramework = false;
1281 const auto Size = File ? (*File)->getSize() : 0;
1282 const auto ModTime = File ? (*File)->getModificationTime() : 0;
1283
1284 for (auto &Header : Mod->UnresolvedHeaders) {
1285 if (File && ((Header.ModTime && Header.ModTime != ModTime) ||
1286 (Header.Size && Header.Size != Size)))
1287 NewHeaders.push_back(Header);
1288 else
1289 // This operation is logically const; we're just changing how we represent
1290 // the header information for this file.
1291 const_cast<ModuleMap *>(this)->resolveHeader(Mod, Header, NeedsFramework);
1292 }
1293 Mod->UnresolvedHeaders.swap(NewHeaders);
1294}
1295
1297 ModuleHeaderRole Role, bool Imported) {
1298 KnownHeader KH(Mod, Role);
1299
1300 FileEntryRef HeaderEntry = Header.Entry;
1301
1302 // Only add each header to the headers list once.
1303 // FIXME: Should we diagnose if a header is listed twice in the
1304 // same module definition?
1305 auto &HeaderList = Headers[HeaderEntry];
1306 if (llvm::is_contained(HeaderList, KH))
1307 return;
1308
1309 HeaderList.push_back(KH);
1310 Mod->addHeader(headerRoleToKind(Role), std::move(Header));
1311
1312 bool isCompilingModuleHeader = Mod->isForBuilding(LangOpts);
1313 if (!Imported || isCompilingModuleHeader) {
1314 // When we import HeaderFileInfo, the external source is expected to
1315 // set the isModuleHeader flag itself.
1316 HeaderInfo.MarkFileModuleHeader(HeaderEntry, Role, isCompilingModuleHeader);
1317 }
1318
1319 // Notify callbacks that we just added a new header.
1320 for (const auto &Cb : Callbacks)
1321 Cb->moduleMapAddHeader(HeaderEntry.getName());
1322}
1323
1325 DirectoryEntryRef Dir, FileID ID,
1326 SourceLocation ExternModuleLoc) {
1327 llvm::DenseMap<const FileEntry *, const modulemap::ModuleMapFile *>::iterator
1328 Known = ParsedModuleMap.find(File);
1329 if (Known != ParsedModuleMap.end())
1330 return Known->second == nullptr;
1331
1332 // If the module map file wasn't already entered, do so now.
1333 if (ID.isInvalid()) {
1334 ID = SourceMgr.translateFile(File);
1335 if (ID.isInvalid() || SourceMgr.isLoadedFileID(ID)) {
1336 auto FileCharacter =
1338 ID = SourceMgr.createFileID(File, ExternModuleLoc, FileCharacter);
1339 }
1340 }
1341
1342 std::optional<llvm::MemoryBufferRef> Buffer = SourceMgr.getBufferOrNone(ID);
1343 if (!Buffer) {
1344 ParsedModuleMap[File] = nullptr;
1345 return true;
1346 }
1347
1348 Diags.Report(diag::remark_mmap_parse) << File.getName();
1349 std::optional<modulemap::ModuleMapFile> MaybeMMF =
1350 modulemap::parseModuleMap(ID, Dir, SourceMgr, Diags, IsSystem, nullptr);
1351
1352 if (!MaybeMMF) {
1353 ParsedModuleMap[File] = nullptr;
1354 return true;
1355 }
1356
1357 ParsedModuleMaps.push_back(
1358 std::make_unique<modulemap::ModuleMapFile>(std::move(*MaybeMMF)));
1359 const modulemap::ModuleMapFile &MMF = *ParsedModuleMaps.back();
1360 std::vector<const modulemap::ExternModuleDecl *> PendingExternalModuleMaps;
1361 for (const auto &Decl : MMF.Decls) {
1362 std::visit(llvm::makeVisitor(
1363 [&](const modulemap::ModuleDecl &MD) {
1364 // Only use the first part of the name even for submodules.
1365 // This will correctly load the submodule declarations when
1366 // the module is loaded.
1367 auto &ModuleDecls =
1368 ParsedModules[StringRef(MD.Id.front().first)];
1369 ModuleDecls.push_back(std::pair(&MMF, &MD));
1370 },
1371 [&](const modulemap::ExternModuleDecl &EMD) {
1372 PendingExternalModuleMaps.push_back(&EMD);
1373 }),
1374 Decl);
1375 }
1376
1377 for (const modulemap::ExternModuleDecl *EMD : PendingExternalModuleMaps) {
1378 StringRef FileNameRef = EMD->Path;
1379 SmallString<128> ModuleMapFileName;
1380 if (llvm::sys::path::is_relative(FileNameRef)) {
1381 ModuleMapFileName += Dir.getName();
1382 llvm::sys::path::append(ModuleMapFileName, EMD->Path);
1383 FileNameRef = ModuleMapFileName;
1384 }
1385
1386 if (auto EFile =
1387 SourceMgr.getFileManager().getOptionalFileRef(FileNameRef)) {
1388 parseModuleMapFile(*EFile, IsSystem, EFile->getDir(), FileID(),
1389 ExternModuleLoc);
1390 }
1391 }
1392
1393 ParsedModuleMap[File] = &MMF;
1394
1395 for (const auto &Cb : Callbacks)
1396 Cb->moduleMapFileRead(SourceLocation(), File, IsSystem);
1397
1398 return false;
1399}
1400
1403 return {};
1404
1405 return SourceMgr.getFileID(Module->DefinitionLoc);
1406}
1407
1411}
1412
1414 if (M->IsInferred) {
1415 assert(InferredModuleAllowedBy.count(M) && "missing inferred module map");
1416 return InferredModuleAllowedBy.find(M)->second;
1417 }
1419}
1420
1424}
1425
1427 M->IsInferred = true;
1428 InferredModuleAllowedBy[M] = ModMapFID;
1429}
1430
1431std::error_code
1433 StringRef Dir = llvm::sys::path::parent_path({Path.data(), Path.size()});
1434
1435 // Do not canonicalize within the framework; the module map loader expects
1436 // Modules/ not Versions/A/Modules.
1437 if (llvm::sys::path::filename(Dir) == "Modules") {
1438 StringRef Parent = llvm::sys::path::parent_path(Dir);
1439 if (Parent.ends_with(".framework"))
1440 Dir = Parent;
1441 }
1442
1443 FileManager &FM = SourceMgr.getFileManager();
1444 auto DirEntry = FM.getDirectoryRef(Dir.empty() ? "." : Dir);
1445 if (!DirEntry)
1446 return llvm::errorToErrorCode(DirEntry.takeError());
1447
1448 // Canonicalize the directory.
1449 StringRef CanonicalDir = FM.getCanonicalName(*DirEntry);
1450 if (CanonicalDir != Dir)
1451 llvm::sys::path::replace_path_prefix(Path, Dir, CanonicalDir);
1452
1453 // In theory, the filename component should also be canonicalized if it
1454 // on a case-insensitive filesystem. However, the extra canonicalization is
1455 // expensive and if clang looked up the filename it will always be lowercase.
1456
1457 // Remove ., remove redundant separators, and switch to native separators.
1458 // This is needed for separators between CanonicalDir and the filename.
1459 llvm::sys::path::remove_dots(Path);
1460
1461 return std::error_code();
1462}
1463
1466 AdditionalModMaps[M].insert(ModuleMap);
1467}
1468
1469LLVM_DUMP_METHOD void ModuleMap::dump() {
1470 llvm::errs() << "Modules:";
1471 for (llvm::StringMap<Module *>::iterator M = Modules.begin(),
1472 MEnd = Modules.end();
1473 M != MEnd; ++M)
1474 M->getValue()->print(llvm::errs(), 2);
1475
1476 llvm::errs() << "Headers:";
1477 for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end();
1478 H != HEnd; ++H) {
1479 llvm::errs() << " \"" << H->first.getName() << "\" -> ";
1480 for (SmallVectorImpl<KnownHeader>::const_iterator I = H->second.begin(),
1481 E = H->second.end();
1482 I != E; ++I) {
1483 if (I != H->second.begin())
1484 llvm::errs() << ",";
1485 llvm::errs() << I->getModule()->getFullModuleName();
1486 }
1487 llvm::errs() << "\n";
1488 }
1489}
1490
1491bool ModuleMap::resolveExports(Module *Mod, bool Complain) {
1492 auto Unresolved = std::move(Mod->UnresolvedExports);
1493 Mod->UnresolvedExports.clear();
1494 for (auto &UE : Unresolved) {
1495 Module::ExportDecl Export = resolveExport(Mod, UE, Complain);
1496 if (Export.getPointer() || Export.getInt())
1497 Mod->Exports.push_back(Export);
1498 else
1499 Mod->UnresolvedExports.push_back(UE);
1500 }
1501 return !Mod->UnresolvedExports.empty();
1502}
1503
1504bool ModuleMap::resolveUses(Module *Mod, bool Complain) {
1505 auto *Top = Mod->getTopLevelModule();
1506 auto Unresolved = std::move(Top->UnresolvedDirectUses);
1507 Top->UnresolvedDirectUses.clear();
1508 for (auto &UDU : Unresolved) {
1509 Module *DirectUse = resolveModuleId(UDU, Top, Complain);
1510 if (DirectUse)
1511 Top->DirectUses.push_back(DirectUse);
1512 else
1513 Top->UnresolvedDirectUses.push_back(UDU);
1514 }
1515 return !Top->UnresolvedDirectUses.empty();
1516}
1517
1518bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) {
1519 auto Unresolved = std::move(Mod->UnresolvedConflicts);
1520 Mod->UnresolvedConflicts.clear();
1521 for (auto &UC : Unresolved) {
1522 if (Module *OtherMod = resolveModuleId(UC.Id, Mod, Complain)) {
1523 Module::Conflict Conflict;
1524 Conflict.Other = OtherMod;
1525 Conflict.Message = UC.Message;
1526 Mod->Conflicts.push_back(Conflict);
1527 } else
1528 Mod->UnresolvedConflicts.push_back(UC);
1529 }
1530 return !Mod->UnresolvedConflicts.empty();
1531}
1532
1533//----------------------------------------------------------------------------//
1534// Module map file loader
1535//----------------------------------------------------------------------------//
1536
1537namespace clang {
1539 SourceManager &SourceMgr;
1540
1541 DiagnosticsEngine &Diags;
1542 ModuleMap &Map;
1543
1544 /// The current module map file.
1545 FileID ModuleMapFID;
1546
1547 /// Source location of most recent loaded module declaration
1548 SourceLocation CurrModuleDeclLoc;
1549
1550 /// The directory that file names in this module map file should
1551 /// be resolved relative to.
1552 DirectoryEntryRef Directory;
1553
1554 /// Whether this module map is in a system header directory.
1555 bool IsSystem;
1556
1557 /// Whether an error occurred.
1558 bool HadError = false;
1559
1560 /// The active module.
1561 Module *ActiveModule = nullptr;
1562
1563 /// Whether a module uses the 'requires excluded' hack to mark its
1564 /// contents as 'textual'.
1565 ///
1566 /// On older Darwin SDK versions, 'requires excluded' is used to mark the
1567 /// contents of the Darwin.C.excluded (assert.h) and Tcl.Private modules as
1568 /// non-modular headers. For backwards compatibility, we continue to
1569 /// support this idiom for just these modules, and map the headers to
1570 /// 'textual' to match the original intent.
1571 llvm::SmallPtrSet<Module *, 2> UsesRequiresExcludedHack;
1572
1573 void handleModuleDecl(const modulemap::ModuleDecl &MD);
1574 void handleExternModuleDecl(const modulemap::ExternModuleDecl &EMD);
1575 void handleRequiresDecl(const modulemap::RequiresDecl &RD);
1576 void handleHeaderDecl(const modulemap::HeaderDecl &HD);
1577 void handleUmbrellaDirDecl(const modulemap::UmbrellaDirDecl &UDD);
1578 void handleExportDecl(const modulemap::ExportDecl &ED);
1579 void handleExportAsDecl(const modulemap::ExportAsDecl &EAD);
1580 void handleUseDecl(const modulemap::UseDecl &UD);
1581 void handleLinkDecl(const modulemap::LinkDecl &LD);
1582 void handleConfigMacros(const modulemap::ConfigMacrosDecl &CMD);
1583 void handleConflict(const modulemap::ConflictDecl &CD);
1584 void handleInferredModuleDecl(const modulemap::ModuleDecl &MD);
1585
1586 /// Private modules are canonicalized as Foo_Private. Clang provides extra
1587 /// module map search logic to find the appropriate private module when PCH
1588 /// is used with implicit module maps. Warn when private modules are written
1589 /// in other ways (FooPrivate and Foo.Private), providing notes and fixits.
1590 void diagnosePrivateModules(SourceLocation StartLoc);
1591
1593
1594public:
1596 ModuleMap &Map, FileID ModuleMapFID,
1597 DirectoryEntryRef Directory, bool IsSystem)
1598 : SourceMgr(SourceMgr), Diags(Diags), Map(Map),
1599 ModuleMapFID(ModuleMapFID), Directory(Directory), IsSystem(IsSystem) {}
1600
1601 bool loadModuleDecl(const modulemap::ModuleDecl &MD);
1604};
1605
1606} // namespace clang
1607
1608/// Private modules are canonicalized as Foo_Private. Clang provides extra
1609/// module map search logic to find the appropriate private module when PCH
1610/// is used with implicit module maps. Warn when private modules are written
1611/// in other ways (FooPrivate and Foo.Private), providing notes and fixits.
1612void ModuleMapLoader::diagnosePrivateModules(SourceLocation StartLoc) {
1613 auto GenNoteAndFixIt = [&](StringRef BadName, StringRef Canonical,
1614 const Module *M, SourceRange ReplLoc) {
1615 auto D = Diags.Report(ActiveModule->DefinitionLoc,
1616 diag::note_mmap_rename_top_level_private_module);
1617 D << BadName << M->Name;
1618 D << FixItHint::CreateReplacement(ReplLoc, Canonical);
1619 };
1620
1621 for (auto E = Map.module_begin(); E != Map.module_end(); ++E) {
1622 auto const *M = E->getValue();
1623 if (M->Directory != ActiveModule->Directory)
1624 continue;
1625
1627 if (!FullName.starts_with(M->Name) && !FullName.ends_with("Private"))
1628 continue;
1629 SmallString<128> FixedPrivModDecl;
1630 SmallString<128> Canonical(M->Name);
1631 Canonical.append("_Private");
1632
1633 // Foo.Private -> Foo_Private
1634 if (ActiveModule->Parent && ActiveModule->Name == "Private" && !M->Parent &&
1635 M->Name == ActiveModule->Parent->Name) {
1636 Diags.Report(ActiveModule->DefinitionLoc,
1637 diag::warn_mmap_mismatched_private_submodule)
1638 << FullName;
1639
1640 SourceLocation FixItInitBegin = CurrModuleDeclLoc;
1641 if (StartLoc.isValid())
1642 FixItInitBegin = StartLoc;
1643
1644 if (ActiveModule->Parent->IsFramework)
1645 FixedPrivModDecl.append("framework ");
1646 FixedPrivModDecl.append("module ");
1647 FixedPrivModDecl.append(Canonical);
1648
1649 GenNoteAndFixIt(FullName, FixedPrivModDecl, M,
1650 SourceRange(FixItInitBegin, ActiveModule->DefinitionLoc));
1651 continue;
1652 }
1653
1654 // FooPrivate and whatnots -> Foo_Private
1655 if (!ActiveModule->Parent && !M->Parent && M->Name != ActiveModule->Name &&
1656 ActiveModule->Name != Canonical) {
1657 Diags.Report(ActiveModule->DefinitionLoc,
1658 diag::warn_mmap_mismatched_private_module_name)
1659 << ActiveModule->Name;
1660 GenNoteAndFixIt(ActiveModule->Name, Canonical, M,
1661 SourceRange(ActiveModule->DefinitionLoc));
1662 }
1663 }
1664}
1665
1666void ModuleMapLoader::handleModuleDecl(const modulemap::ModuleDecl &MD) {
1667 if (MD.Id.front().first == "*")
1668 return handleInferredModuleDecl(MD);
1669
1670 CurrModuleDeclLoc = MD.Location;
1671
1672 Module *PreviousActiveModule = ActiveModule;
1673 if (MD.Id.size() > 1) {
1674 // This module map defines a submodule. Go find the module of which it
1675 // is a submodule.
1676 ActiveModule = nullptr;
1677 const Module *TopLevelModule = nullptr;
1678 for (unsigned I = 0, N = MD.Id.size() - 1; I != N; ++I) {
1679 if (Module *Next =
1680 Map.lookupModuleQualified(MD.Id[I].first, ActiveModule)) {
1681 if (I == 0)
1682 TopLevelModule = Next;
1683 ActiveModule = Next;
1684 continue;
1685 }
1686
1687 Diags.Report(MD.Id[I].second, diag::err_mmap_missing_parent_module)
1688 << MD.Id[I].first << (ActiveModule != nullptr)
1689 << (ActiveModule
1690 ? ActiveModule->getTopLevelModule()->getFullModuleName()
1691 : "");
1692 HadError = true;
1693 }
1694
1695 if (TopLevelModule &&
1696 ModuleMapFID != Map.getContainingModuleMapFileID(TopLevelModule)) {
1697 assert(ModuleMapFID !=
1698 Map.getModuleMapFileIDForUniquing(TopLevelModule) &&
1699 "submodule defined in same file as 'module *' that allowed its "
1700 "top-level module");
1702 TopLevelModule, *SourceMgr.getFileEntryRefForID(ModuleMapFID));
1703 }
1704 }
1705
1706 StringRef ModuleName = MD.Id.back().first;
1707 SourceLocation ModuleNameLoc = MD.Id.back().second;
1708
1709 // Determine whether this (sub)module has already been defined.
1710 Module *ShadowingModule = nullptr;
1711 if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) {
1712 // We might see a (re)definition of a module that we already have a
1713 // definition for in four cases:
1714 // - If we loaded one definition from an AST file and we've just found a
1715 // corresponding definition in a module map file, or
1716 bool LoadedFromASTFile = Existing->IsFromModuleFile;
1717 // - If we previously inferred this module from different module map file.
1718 bool Inferred = Existing->IsInferred;
1719 // - If we're building a framework that vends a module map, we might've
1720 // previously seen the one in intermediate products and now the system
1721 // one.
1722 // FIXME: If we're parsing module map file that looks like this:
1723 // framework module FW { ... }
1724 // module FW.Sub { ... }
1725 // We can't check the framework qualifier, since it's not attached to
1726 // the definition of Sub. Checking that qualifier on \c Existing is
1727 // not correct either, since we might've previously seen:
1728 // module FW { ... }
1729 // module FW.Sub { ... }
1730 // We should enforce consistency of redefinitions so that we can rely
1731 // that \c Existing is part of a framework iff the redefinition of FW
1732 // we have just skipped had it too. Once we do that, stop checking
1733 // the local framework qualifier and only rely on \c Existing.
1734 bool PartOfFramework = MD.Framework || Existing->isPartOfFramework();
1735 // - If we're building a (preprocessed) module and we've just loaded the
1736 // module map file from which it was created.
1737 bool ParsedAsMainInput =
1738 Map.LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap &&
1739 Map.LangOpts.CurrentModule == ModuleName &&
1740 SourceMgr.getDecomposedLoc(ModuleNameLoc).first !=
1741 SourceMgr.getDecomposedLoc(Existing->DefinitionLoc).first;
1742 // TODO: Remove this check when we can avoid loading module maps multiple
1743 // times.
1744 bool SameModuleDecl = ModuleNameLoc == Existing->DefinitionLoc;
1745 if (LoadedFromASTFile || Inferred || PartOfFramework || ParsedAsMainInput ||
1746 SameModuleDecl) {
1747 ActiveModule = PreviousActiveModule;
1748 // Skip the module definition.
1749 return;
1750 }
1751
1752 if (!Existing->Parent && Map.mayShadowNewModule(Existing)) {
1753 ShadowingModule = Existing;
1754 } else {
1755 // This is not a shawdowed module decl, it is an illegal redefinition.
1756 Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition)
1757 << ModuleName;
1758 Diags.Report(Existing->DefinitionLoc, diag::note_mmap_prev_definition);
1759 HadError = true;
1760 return;
1761 }
1762 }
1763
1764 // Start defining this module.
1765 if (ShadowingModule) {
1766 ActiveModule =
1767 Map.createShadowedModule(ModuleName, MD.Framework, ShadowingModule);
1768 } else {
1769 ActiveModule = Map.findOrCreateModuleFirst(ModuleName, ActiveModule,
1770 MD.Framework, MD.Explicit);
1771 }
1772
1773 ActiveModule->DefinitionLoc = ModuleNameLoc;
1774 if (MD.Attrs.IsSystem || IsSystem)
1775 ActiveModule->IsSystem = true;
1776 if (MD.Attrs.IsExternC)
1777 ActiveModule->IsExternC = true;
1779 ActiveModule->NoUndeclaredIncludes = true;
1780 ActiveModule->Directory = Directory;
1781
1782 StringRef MapFileName(
1783 SourceMgr.getFileEntryRefForID(ModuleMapFID)->getName());
1784 if (MapFileName.ends_with("module.private.modulemap") ||
1785 MapFileName.ends_with("module_private.map")) {
1786 ActiveModule->ModuleMapIsPrivate = true;
1787 }
1788
1789 // Private modules named as FooPrivate, Foo.Private or similar are likely a
1790 // user error; provide warnings, notes and fixits to direct users to use
1791 // Foo_Private instead.
1792 SourceLocation StartLoc =
1793 SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1794 if (Map.HeaderInfo.getHeaderSearchOpts().ImplicitModuleMaps &&
1795 !Diags.isIgnored(diag::warn_mmap_mismatched_private_submodule,
1796 StartLoc) &&
1797 !Diags.isIgnored(diag::warn_mmap_mismatched_private_module_name,
1798 StartLoc) &&
1799 ActiveModule->ModuleMapIsPrivate)
1800 diagnosePrivateModules(MD.Location);
1801
1802 for (const modulemap::Decl &Decl : MD.Decls) {
1803 std::visit(
1804 llvm::makeVisitor(
1805 [&](const modulemap::RequiresDecl &RD) { handleRequiresDecl(RD); },
1806 [&](const modulemap::HeaderDecl &HD) { handleHeaderDecl(HD); },
1807 [&](const modulemap::UmbrellaDirDecl &UDD) {
1808 handleUmbrellaDirDecl(UDD);
1809 },
1810 [&](const modulemap::ModuleDecl &MD) { handleModuleDecl(MD); },
1811 [&](const modulemap::ExportDecl &ED) { handleExportDecl(ED); },
1812 [&](const modulemap::ExportAsDecl &EAD) {
1813 handleExportAsDecl(EAD);
1814 },
1815 [&](const modulemap::ExternModuleDecl &EMD) {
1816 handleExternModuleDecl(EMD);
1817 },
1818 [&](const modulemap::UseDecl &UD) { handleUseDecl(UD); },
1819 [&](const modulemap::LinkDecl &LD) { handleLinkDecl(LD); },
1820 [&](const modulemap::ConfigMacrosDecl &CMD) {
1821 handleConfigMacros(CMD);
1822 },
1823 [&](const modulemap::ConflictDecl &CD) { handleConflict(CD); },
1824 [&](const modulemap::ExcludeDecl &ED) {
1825 Diags.Report(ED.Location, diag::err_mmap_expected_member);
1826 }),
1827 Decl);
1828 }
1829
1830 // If the active module is a top-level framework, and there are no link
1831 // libraries, automatically link against the framework.
1832 if (ActiveModule->IsFramework && !ActiveModule->isSubFramework() &&
1833 ActiveModule->LinkLibraries.empty())
1834 inferFrameworkLink(ActiveModule);
1835
1836 // If the module meets all requirements but is still unavailable, mark the
1837 // whole tree as unavailable to prevent it from building.
1838 if (!ActiveModule->IsAvailable && !ActiveModule->IsUnimportable &&
1839 ActiveModule->Parent) {
1840 ActiveModule->getTopLevelModule()->markUnavailable(/*Unimportable=*/false);
1841 ActiveModule->getTopLevelModule()->MissingHeaders.append(
1842 ActiveModule->MissingHeaders.begin(), ActiveModule->MissingHeaders.end());
1843 }
1844
1845 // We're done parsing this module. Pop back to the previous module.
1846 ActiveModule = PreviousActiveModule;
1847}
1848
1849void ModuleMapLoader::handleExternModuleDecl(
1850 const modulemap::ExternModuleDecl &EMD) {
1851 StringRef FileNameRef = EMD.Path;
1852 SmallString<128> ModuleMapFileName;
1853 if (llvm::sys::path::is_relative(FileNameRef)) {
1854 ModuleMapFileName += Directory.getName();
1855 llvm::sys::path::append(ModuleMapFileName, EMD.Path);
1856 FileNameRef = ModuleMapFileName;
1857 }
1858 if (auto File = SourceMgr.getFileManager().getOptionalFileRef(FileNameRef))
1860 *File, IsSystem,
1862 ? Directory
1863 : File->getDir(),
1864 FileID(), nullptr, EMD.Location);
1865}
1866
1867/// Whether to add the requirement \p Feature to the module \p M.
1868///
1869/// This preserves backwards compatibility for two hacks in the Darwin system
1870/// module map files:
1871///
1872/// 1. The use of 'requires excluded' to make headers non-modular, which
1873/// should really be mapped to 'textual' now that we have this feature. We
1874/// drop the 'excluded' requirement, and set \p IsRequiresExcludedHack to
1875/// true. Later, this bit will be used to map all the headers inside this
1876/// module to 'textual'.
1877///
1878/// This affects Darwin.C.excluded (for assert.h) and Tcl.Private.
1879///
1880/// 2. Removes a bogus cplusplus requirement from IOKit.avc. This requirement
1881/// was never correct and causes issues now that we check it, so drop it.
1882static bool shouldAddRequirement(Module *M, StringRef Feature,
1883 bool &IsRequiresExcludedHack) {
1884 if (Feature == "excluded" &&
1885 (M->fullModuleNameIs({"Darwin", "C", "excluded"}) ||
1886 M->fullModuleNameIs({"Tcl", "Private"}))) {
1887 IsRequiresExcludedHack = true;
1888 return false;
1889 } else if (Feature == "cplusplus" && M->fullModuleNameIs({"IOKit", "avc"})) {
1890 return false;
1891 }
1892
1893 return true;
1894}
1895
1896void ModuleMapLoader::handleRequiresDecl(const modulemap::RequiresDecl &RD) {
1897
1898 for (const modulemap::RequiresFeature &RF : RD.Features) {
1899 bool IsRequiresExcludedHack = false;
1900 bool ShouldAddRequirement =
1901 shouldAddRequirement(ActiveModule, RF.Feature, IsRequiresExcludedHack);
1902
1903 if (IsRequiresExcludedHack)
1904 UsesRequiresExcludedHack.insert(ActiveModule);
1905
1906 if (ShouldAddRequirement) {
1907 // Add this feature.
1908 ActiveModule->addRequirement(RF.Feature, RF.RequiredState, Map.LangOpts,
1909 *Map.Target);
1910 }
1911 }
1912}
1913
1914void ModuleMapLoader::handleHeaderDecl(const modulemap::HeaderDecl &HD) {
1915 // We've already consumed the first token.
1917
1918 if (HD.Private) {
1920 } else if (HD.Excluded) {
1922 }
1923
1924 if (HD.Textual)
1926
1927 if (UsesRequiresExcludedHack.count(ActiveModule)) {
1928 // Mark this header 'textual' (see doc comment for
1929 // Module::UsesRequiresExcludedHack).
1931 }
1932
1934 Header.FileName = HD.Path;
1935 Header.FileNameLoc = HD.PathLoc;
1936 Header.IsUmbrella = HD.Umbrella;
1937 Header.Kind = Map.headerRoleToKind(Role);
1938
1939 // Check whether we already have an umbrella.
1940 if (Header.IsUmbrella &&
1941 !std::holds_alternative<std::monostate>(ActiveModule->Umbrella)) {
1942 Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash)
1943 << ActiveModule->getFullModuleName();
1944 HadError = true;
1945 return;
1946 }
1947
1948 if (HD.Size)
1949 Header.Size = HD.Size;
1950 if (HD.MTime)
1951 Header.ModTime = HD.MTime;
1952
1953 bool NeedsFramework = false;
1954 // Don't add headers to the builtin modules if the builtin headers belong to
1955 // the system modules, with the exception of __stddef_max_align_t.h which
1956 // always had its own module.
1957 if (!Map.LangOpts.BuiltinHeadersInSystemModules ||
1958 !isBuiltInModuleName(ActiveModule->getTopLevelModuleName()) ||
1959 ActiveModule->fullModuleNameIs({"_Builtin_stddef", "max_align_t"}))
1960 Map.addUnresolvedHeader(ActiveModule, std::move(Header), NeedsFramework);
1961
1962 if (NeedsFramework)
1963 Diags.Report(CurrModuleDeclLoc, diag::note_mmap_add_framework_keyword)
1964 << ActiveModule->getFullModuleName()
1965 << FixItHint::CreateReplacement(CurrModuleDeclLoc, "framework module");
1966}
1967
1969 const Module::Header &B) {
1970 return A.NameAsWritten < B.NameAsWritten;
1971}
1972
1973void ModuleMapLoader::handleUmbrellaDirDecl(
1974 const modulemap::UmbrellaDirDecl &UDD) {
1975 std::string DirName = std::string(UDD.Path);
1976 std::string DirNameAsWritten = DirName;
1977
1978 // Check whether we already have an umbrella.
1979 if (!std::holds_alternative<std::monostate>(ActiveModule->Umbrella)) {
1980 Diags.Report(UDD.Location, diag::err_mmap_umbrella_clash)
1981 << ActiveModule->getFullModuleName();
1982 HadError = true;
1983 return;
1984 }
1985
1986 // Look for this file.
1988 if (llvm::sys::path::is_absolute(DirName)) {
1989 Dir = SourceMgr.getFileManager().getOptionalDirectoryRef(DirName);
1990 } else {
1991 SmallString<128> PathName;
1992 PathName = Directory.getName();
1993 llvm::sys::path::append(PathName, DirName);
1994 Dir = SourceMgr.getFileManager().getOptionalDirectoryRef(PathName);
1995 }
1996
1997 if (!Dir) {
1998 Diags.Report(UDD.Location, diag::warn_mmap_umbrella_dir_not_found)
1999 << DirName;
2000 return;
2001 }
2002
2003 if (UsesRequiresExcludedHack.count(ActiveModule)) {
2004 // Mark this header 'textual' (see doc comment for
2005 // ModuleMapLoader::UsesRequiresExcludedHack). Although iterating over the
2006 // directory is relatively expensive, in practice this only applies to the
2007 // uncommonly used Tcl module on Darwin platforms.
2008 std::error_code EC;
2010 llvm::vfs::FileSystem &FS =
2012 for (llvm::vfs::recursive_directory_iterator I(FS, Dir->getName(), EC), E;
2013 I != E && !EC; I.increment(EC)) {
2014 if (auto FE = SourceMgr.getFileManager().getOptionalFileRef(I->path())) {
2015 Module::Header Header = {"", std::string(I->path()), *FE};
2016 Headers.push_back(std::move(Header));
2017 }
2018 }
2019
2020 // Sort header paths so that the pcm doesn't depend on iteration order.
2021 llvm::stable_sort(Headers, compareModuleHeaders);
2022
2023 for (auto &Header : Headers)
2024 Map.addHeader(ActiveModule, std::move(Header), ModuleMap::TextualHeader);
2025 return;
2026 }
2027
2028 if (Module *OwningModule = Map.UmbrellaDirs[*Dir]) {
2029 Diags.Report(UDD.Location, diag::err_mmap_umbrella_clash)
2030 << OwningModule->getFullModuleName();
2031 HadError = true;
2032 return;
2033 }
2034
2035 // Record this umbrella directory.
2036 Map.setUmbrellaDirAsWritten(ActiveModule, *Dir, DirNameAsWritten, DirName);
2037}
2038
2039void ModuleMapLoader::handleExportDecl(const modulemap::ExportDecl &ED) {
2041 ActiveModule->UnresolvedExports.push_back(Unresolved);
2042}
2043
2044void ModuleMapLoader::handleExportAsDecl(const modulemap::ExportAsDecl &EAD) {
2045 const auto &ModName = EAD.Id.front();
2046
2047 if (!ActiveModule->ExportAsModule.empty()) {
2048 if (ActiveModule->ExportAsModule == ModName.first) {
2049 Diags.Report(ModName.second, diag::warn_mmap_redundant_export_as)
2050 << ActiveModule->Name << ModName.first;
2051 } else {
2052 Diags.Report(ModName.second, diag::err_mmap_conflicting_export_as)
2053 << ActiveModule->Name << ActiveModule->ExportAsModule
2054 << ModName.first;
2055 }
2056 }
2057
2058 ActiveModule->ExportAsModule = ModName.first;
2059 Map.addLinkAsDependency(ActiveModule);
2060}
2061
2062void ModuleMapLoader::handleUseDecl(const modulemap::UseDecl &UD) {
2063 if (ActiveModule->Parent)
2064 Diags.Report(UD.Location, diag::err_mmap_use_decl_submodule);
2065 else
2066 ActiveModule->UnresolvedDirectUses.push_back(UD.Id);
2067}
2068
2069void ModuleMapLoader::handleLinkDecl(const modulemap::LinkDecl &LD) {
2070 ActiveModule->LinkLibraries.push_back(
2071 Module::LinkLibrary(std::string{LD.Library}, LD.Framework));
2072}
2073
2074void ModuleMapLoader::handleConfigMacros(
2075 const modulemap::ConfigMacrosDecl &CMD) {
2076 if (ActiveModule->Parent) {
2077 Diags.Report(CMD.Location, diag::err_mmap_config_macro_submodule);
2078 return;
2079 }
2080
2081 // TODO: Is this really the behavior we want for multiple config_macros
2082 // declarations? If any of them are exhaustive then all of them are.
2083 if (CMD.Exhaustive) {
2084 ActiveModule->ConfigMacrosExhaustive = true;
2085 }
2086 ActiveModule->ConfigMacros.insert(ActiveModule->ConfigMacros.end(),
2087 CMD.Macros.begin(), CMD.Macros.end());
2088}
2089
2090void ModuleMapLoader::handleConflict(const modulemap::ConflictDecl &CD) {
2092
2093 Conflict.Id = CD.Id;
2094 Conflict.Message = CD.Message;
2095
2096 // FIXME: when we move to C++20 we should consider using emplace_back
2097 ActiveModule->UnresolvedConflicts.push_back(std::move(Conflict));
2098}
2099
2100void ModuleMapLoader::handleInferredModuleDecl(
2101 const modulemap::ModuleDecl &MD) {
2102 SourceLocation StarLoc = MD.Id.front().second;
2103
2104 // Inferred modules must be submodules.
2105 if (!ActiveModule && !MD.Framework) {
2106 Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule);
2107 return;
2108 }
2109
2110 if (ActiveModule) {
2111 // Inferred modules must have umbrella directories.
2112 if (ActiveModule->IsAvailable && !ActiveModule->getEffectiveUmbrellaDir()) {
2113 Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella);
2114 return;
2115 }
2116
2117 // Check for redefinition of an inferred module.
2118 if (ActiveModule->InferSubmodules) {
2119 Diags.Report(StarLoc, diag::err_mmap_inferred_redef);
2120 if (ActiveModule->InferredSubmoduleLoc.isValid())
2121 Diags.Report(ActiveModule->InferredSubmoduleLoc,
2122 diag::note_mmap_prev_definition);
2123 return;
2124 }
2125
2126 // Check for the 'framework' keyword, which is not permitted here.
2127 if (MD.Framework) {
2128 Diags.Report(StarLoc, diag::err_mmap_inferred_framework_submodule);
2129 return;
2130 }
2131 } else if (MD.Explicit) {
2132 Diags.Report(StarLoc, diag::err_mmap_explicit_inferred_framework);
2133 return;
2134 }
2135
2136 if (ActiveModule) {
2137 // Note that we have an inferred submodule.
2138 ActiveModule->InferSubmodules = true;
2139 ActiveModule->InferredSubmoduleLoc = StarLoc;
2140 ActiveModule->InferExplicitSubmodules = MD.Explicit;
2141 } else {
2142 // We'll be inferring framework modules for this directory.
2143 auto &InfDir = Map.InferredDirectories[Directory];
2144 InfDir.InferModules = true;
2145 InfDir.Attrs = MD.Attrs;
2146 InfDir.ModuleMapFID = ModuleMapFID;
2147 // FIXME: Handle the 'framework' keyword.
2148 }
2149
2150 for (const modulemap::Decl &Decl : MD.Decls) {
2151 std::visit(
2152 llvm::makeVisitor(
2153 [&](const auto &Other) {
2154 Diags.Report(Other.Location,
2155 diag::err_mmap_expected_inferred_member)
2156 << (ActiveModule != nullptr);
2157 },
2158 [&](const modulemap::ExcludeDecl &ED) {
2159 // Only inferred frameworks can have exclude decls
2160 if (ActiveModule) {
2161 Diags.Report(ED.Location,
2162 diag::err_mmap_expected_inferred_member)
2163 << (ActiveModule != nullptr);
2164 HadError = true;
2165 return;
2166 }
2167 Map.InferredDirectories[Directory].ExcludedModules.emplace_back(
2168 ED.Module);
2169 },
2170 [&](const modulemap::ExportDecl &ED) {
2171 // Only inferred submodules can have export decls
2172 if (!ActiveModule) {
2173 Diags.Report(ED.Location,
2174 diag::err_mmap_expected_inferred_member)
2175 << (ActiveModule != nullptr);
2176 HadError = true;
2177 return;
2178 }
2179
2180 if (ED.Wildcard && ED.Id.size() == 0)
2181 ActiveModule->InferExportWildcard = true;
2182 else
2183 Diags.Report(ED.Id.front().second,
2184 diag::err_mmap_expected_export_wildcard);
2185 }),
2186 Decl);
2187 }
2188}
2189
2191 handleModuleDecl(MD);
2192 return HadError;
2193}
2194
2196 const modulemap::ExternModuleDecl &EMD) {
2197 handleExternModuleDecl(EMD);
2198 return HadError;
2199}
2200
2202 const modulemap::ModuleMapFile &MMF) {
2203 for (const auto &Decl : MMF.Decls) {
2204 std::visit(
2205 llvm::makeVisitor(
2206 [&](const modulemap::ModuleDecl &MD) { handleModuleDecl(MD); },
2207 [&](const modulemap::ExternModuleDecl &EMD) {
2208 handleExternModuleDecl(EMD);
2209 }),
2210 Decl);
2211 }
2212 return HadError;
2213}
2214
2216 llvm::StringMap<Module *>::const_iterator Known = Modules.find(Name);
2217 if (Known != Modules.end())
2218 return Known->getValue();
2219
2220 auto ParsedMod = ParsedModules.find(Name);
2221 if (ParsedMod == ParsedModules.end())
2222 return nullptr;
2223
2224 Diags.Report(diag::remark_mmap_load_module) << Name;
2225
2226 for (const auto &ModuleDecl : ParsedMod->second) {
2227 const modulemap::ModuleMapFile &MMF = *ModuleDecl.first;
2228 ModuleMapLoader Loader(SourceMgr, Diags, const_cast<ModuleMap &>(*this),
2229 MMF.ID, *MMF.Dir, MMF.IsSystem);
2230 if (Loader.loadModuleDecl(*ModuleDecl.second))
2231 return nullptr;
2232 }
2233
2234 return findModule(Name);
2235}
2236
2238 DirectoryEntryRef Dir, FileID ID,
2239 unsigned *Offset,
2240 SourceLocation ExternModuleLoc) {
2241 assert(Target && "Missing target information");
2242 llvm::DenseMap<const FileEntry *, bool>::iterator Known =
2243 LoadedModuleMap.find(File);
2244 if (Known != LoadedModuleMap.end())
2245 return Known->second;
2246
2247 // If the module map file wasn't already entered, do so now.
2248 if (ID.isInvalid()) {
2249 ID = SourceMgr.translateFile(File);
2250 // TODO: The way we compute affecting module maps requires this to be a
2251 // local FileID. This should be changed to reuse loaded FileIDs when
2252 // available, and change the way that affecting module maps are
2253 // computed to not require this.
2254 if (ID.isInvalid() || SourceMgr.isLoadedFileID(ID)) {
2255 auto FileCharacter =
2257 ID = SourceMgr.createFileID(File, ExternModuleLoc, FileCharacter);
2258 }
2259 }
2260
2261 assert(Target && "Missing target information");
2262 std::optional<llvm::MemoryBufferRef> Buffer = SourceMgr.getBufferOrNone(ID);
2263 if (!Buffer)
2264 return LoadedModuleMap[File] = true;
2265 assert((!Offset || *Offset <= Buffer->getBufferSize()) &&
2266 "invalid buffer offset");
2267
2268 std::optional<modulemap::ModuleMapFile> MMF =
2269 modulemap::parseModuleMap(ID, Dir, SourceMgr, Diags, IsSystem, Offset);
2270 bool Result = false;
2271 if (MMF) {
2272 Diags.Report(diag::remark_mmap_load) << File.getName();
2273 ModuleMapLoader Loader(SourceMgr, Diags, *this, ID, Dir, IsSystem);
2274 Result = Loader.parseAndLoadModuleMapFile(*MMF);
2275 }
2276 LoadedModuleMap[File] = Result;
2277
2278 // Notify callbacks that we observed it.
2279 // FIXME: We should only report module maps that were actually used.
2280 for (const auto &Cb : Callbacks)
2281 Cb->moduleMapFileRead(MMF ? MMF->Start : SourceLocation(), File, IsSystem);
2282
2283 return Result;
2284}
NodeId Parent
Definition: ASTDiff.cpp:191
Defines the Diagnostic-related interfaces.
const Decl * D
IndirectLocalPath & Path
Expr * E
Defines the clang::FileManager interface and associated types.
StringRef Filename
Definition: Format.cpp:3177
#define ALIAS(NAME, TOK, FLAGS)
#define KEYWORD(NAME, FLAGS)
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
llvm::MachO::Target Target
Definition: MachO.h:51
static bool isBuiltinHeaderName(StringRef FileName)
Determine whether the given file name is the name of a builtin header, supplied by Clang to replace,...
Definition: ModuleMap.cpp:252
static bool isBuiltInModuleName(StringRef ModuleName)
Determine whether the given module name is the name of a builtin module that is cyclic with a system ...
Definition: ModuleMap.cpp:271
static Module * getTopLevelOrNull(Module *M)
Definition: ModuleMap.cpp:480
static bool violatesPrivateInclude(Module *RequestingModule, const FileEntry *IncFileEnt, ModuleMap::KnownHeader Header)
Definition: ModuleMap.cpp:459
static void inferFrameworkLink(Module *Mod)
For a framework module, infer the framework against which we should link.
Definition: ModuleMap.cpp:993
static StringRef sanitizeFilenameAsIdentifier(StringRef Name, SmallVectorImpl< char > &Buffer)
"Sanitize" a filename so that it can be used as an identifier.
Definition: ModuleMap.cpp:367
static void appendSubframeworkPaths(Module *Mod, SmallVectorImpl< char > &Path)
Append to Paths the set of paths needed to get to the subframework in which the given module lives.
Definition: ModuleMap.cpp:156
static bool shouldAddRequirement(Module *M, StringRef Feature, bool &IsRequiresExcludedHack)
Whether to add the requirement Feature to the module M.
Definition: ModuleMap.cpp:1882
static bool isBetterKnownHeader(const ModuleMap::KnownHeader &New, const ModuleMap::KnownHeader &Old)
Definition: ModuleMap.cpp:566
static bool compareModuleHeaders(const Module::Header &A, const Module::Header &B)
Definition: ModuleMap.cpp:1968
Defines the clang::Module class, which describes a module in the source code.
uint32_t Id
Definition: SemaARM.cpp:1179
int32_t FullName
Definition: SemaARM.cpp:1180
SourceLocation Loc
Definition: SemaObjC.cpp:754
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:231
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1529
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:950
A reference to a DirectoryEntry that includes the name of the directory as it was accessed by the Fil...
StringRef getName() const
Cached information about one directory (either on disk or in the virtual file system).
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition: FileEntry.h:57
StringRef getName() const
The name of this FileEntry.
Definition: FileEntry.h:61
DirectoryEntryRef getDir() const
Definition: FileEntry.h:78
Cached information about one file (either on disk or in the virtual file system).
Definition: FileEntry.h:306
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Implements support for file system lookup, file system caching, and directory search management.
Definition: FileManager.h:53
llvm::vfs::FileSystem & getVirtualFileSystem() const
Definition: FileManager.h:219
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Get a FileEntryRef if it exists, without doing anything on error.
Definition: FileManager.h:208
StringRef getCanonicalName(DirectoryEntryRef Dir)
Retrieve the canonical name for a given directory.
llvm::Expected< DirectoryEntryRef > getDirectoryRef(StringRef DirName, bool CacheFailure=true)
Lookup, cache, and verify the specified directory (real or virtual).
OptionalDirectoryEntryRef getOptionalDirectoryRef(StringRef DirName, bool CacheFailure=true)
Get a DirectoryEntryRef if it exists, without doing anything on error.
Definition: FileManager.h:175
llvm::Expected< FileEntryRef > getFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true, bool IsText=true)
Lookup, cache, and verify the specified file (real or virtual).
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:139
unsigned ImplicitModuleMaps
Implicit module maps.
unsigned ModuleMapFileHomeIsCwd
Set the 'home directory' of a module map file to the current working directory (or the home directory...
Encapsulates the information needed to find the file referenced by a #include or #include_next,...
Definition: HeaderSearch.h:237
void loadTopLevelSystemModules()
Load all known, top-level system modules.
const HeaderSearchOptions & getHeaderSearchOpts() const
Retrieve the header-search options with which this header search was initialized.
Definition: HeaderSearch.h:384
void MarkFileModuleHeader(FileEntryRef FE, ModuleMap::ModuleHeaderRole Role, bool isCompilingModuleHeader)
Mark the specified file as part of a module.
OptionalFileEntryRef lookupModuleMapFile(DirectoryEntryRef Dir, bool IsFramework)
Try to find a module map file in the given directory, returning nullopt if none is found.
@ CMK_ModuleMap
Compiling a module from a module map.
Definition: LangOptions.h:121
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:434
bool isCompilingModule() const
Are we compiling a module?
Definition: LangOptions.h:596
std::string CurrentModule
The name of the current module, of which the main source file is a part.
Definition: LangOptions.h:489
Required to construct a Module.
Definition: Module.h:136
bool loadExternModuleDecl(const modulemap::ExternModuleDecl &EMD)
Definition: ModuleMap.cpp:2195
ModuleMapLoader(SourceManager &SourceMgr, DiagnosticsEngine &Diags, ModuleMap &Map, FileID ModuleMapFID, DirectoryEntryRef Directory, bool IsSystem)
Definition: ModuleMap.cpp:1595
bool parseAndLoadModuleMapFile(const modulemap::ModuleMapFile &MMF)
Definition: ModuleMap.cpp:2201
bool loadModuleDecl(const modulemap::ModuleDecl &MD)
Definition: ModuleMap.cpp:2190
A header that is known to reside within a given module, whether it was included or excluded.
Definition: ModuleMap.h:158
bool isAccessibleFrom(Module *M) const
Whether this header is accessible from the specified module.
Definition: ModuleMap.h:184
ModuleHeaderRole getRole() const
The role of this header within the module.
Definition: ModuleMap.h:176
Module * getModule() const
Retrieve the module the header is stored in.
Definition: ModuleMap.h:173
Module * createShadowedModule(StringRef Name, bool IsFramework, Module *ShadowingModule)
Create a new top-level module that is shadowed by ShadowingModule.
Definition: ModuleMap.cpp:1185
bool resolveExports(Module *Mod, bool Complain)
Resolve all of the unresolved exports in the given module.
Definition: ModuleMap.cpp:1491
void addLinkAsDependency(Module *Mod)
Make module to use export_as as the link dependency name if enough information is available or add it...
Definition: ModuleMap.cpp:62
void dump()
Dump the contents of the module map, for debugging purposes.
Definition: ModuleMap.cpp:1469
std::pair< Module *, bool > findOrCreateModule(StringRef Name, Module *Parent, bool IsFramework, bool IsExplicit)
Find a new module or submodule, or create it if it does not already exist.
Definition: ModuleMap.cpp:853
void setUmbrellaDirAsWritten(Module *Mod, DirectoryEntryRef UmbrellaDir, const Twine &NameAsWritten, const Twine &PathRelativeToRootModuleDirectory)
Sets the umbrella directory of the given module to the given directory.
Definition: ModuleMap.cpp:1215
void diagnoseHeaderInclusion(Module *RequestingModule, bool RequestingModuleIsModuleInterface, SourceLocation FilenameLoc, StringRef Filename, FileEntryRef File)
Reports errors if a module must not include a specific file.
Definition: ModuleMap.cpp:484
void addAdditionalModuleMapFile(const Module *M, FileEntryRef ModuleMap)
Definition: ModuleMap.cpp:1464
OptionalFileEntryRef getContainingModuleMapFile(const Module *Module) const
Definition: ModuleMap.cpp:1409
static Module::HeaderKind headerRoleToKind(ModuleHeaderRole Role)
Convert a header role to a kind.
Definition: ModuleMap.cpp:69
Module * findModule(StringRef Name) const
Retrieve a module with the given name.
Definition: ModuleMap.cpp:812
bool mayShadowNewModule(Module *ExistingModule)
Definition: ModuleMap.h:607
bool parseAndLoadModuleMapFile(FileEntryRef File, bool IsSystem, DirectoryEntryRef HomeDir, FileID ID=FileID(), unsigned *Offset=nullptr, SourceLocation ExternModuleLoc=SourceLocation())
Load the given module map file, and record any modules we encounter.
Definition: ModuleMap.cpp:2237
KnownHeader findModuleForHeader(FileEntryRef File, bool AllowTextual=false, bool AllowExcluded=false)
Retrieve the module that owns the given header file, if any.
Definition: ModuleMap.cpp:594
Module * createHeaderUnit(SourceLocation Loc, StringRef Name, Module::Header H)
Create a C++20 header unit.
Definition: ModuleMap.cpp:977
static bool isModular(ModuleHeaderRole Role)
Check if the header with the given role is a modular one.
Definition: ModuleMap.cpp:102
bool resolveConflicts(Module *Mod, bool Complain)
Resolve all of the unresolved conflicts in the given module.
Definition: ModuleMap.cpp:1518
bool isHeaderUnavailableInModule(FileEntryRef Header, const Module *RequestingModule) const
Determine whether the given header is unavailable as part of the specified module.
Definition: ModuleMap.cpp:718
void resolveHeaderDirectives(const FileEntry *File) const
Resolve all lazy header directives for the specified file.
Definition: ModuleMap.cpp:1261
module_iterator module_begin() const
Definition: ModuleMap.h:747
ArrayRef< KnownHeader > findResolvedModulesForHeader(FileEntryRef File) const
Like findAllModulesForHeader, but do not attempt to infer module ownership from umbrella headers if w...
Definition: ModuleMap.cpp:705
OptionalFileEntryRef getModuleMapFileForUniquing(const Module *M) const
Definition: ModuleMap.cpp:1422
bool shouldImportRelativeToBuiltinIncludeDir(StringRef FileName, Module *Module) const
Definition: ModuleMap.cpp:408
Module * createModuleForImplementationUnit(SourceLocation Loc, StringRef Name)
Create a new module for a C++ module implementation unit.
Definition: ModuleMap.cpp:953
ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags, const LangOptions &LangOpts, const TargetInfo *Target, HeaderSearch &HeaderInfo)
Construct a new module map.
Definition: ModuleMap.cpp:351
std::error_code canonicalizeModuleMapPath(SmallVectorImpl< char > &Path)
Canonicalize Path in a manner suitable for a module map file.
Definition: ModuleMap.cpp:1432
FileID getModuleMapFileIDForUniquing(const Module *M) const
Get the module map file that (along with the module name) uniquely identifies this module.
Definition: ModuleMap.cpp:1413
void setInferredModuleAllowedBy(Module *M, FileID ModMapFID)
Definition: ModuleMap.cpp:1426
void setUmbrellaHeaderAsWritten(Module *Mod, FileEntryRef UmbrellaHeader, const Twine &NameAsWritten, const Twine &PathRelativeToRootModuleDirectory)
Sets the umbrella header of the given module to the given header.
Definition: ModuleMap.cpp:1200
Module * findOrCreateModuleFirst(StringRef Name, Module *Parent, bool IsFramework, bool IsExplicit)
Call ModuleMap::findOrCreateModule and throw away the information whether the module was found or cre...
Definition: ModuleMap.h:539
Module * lookupModuleUnqualified(StringRef Name, Module *Context) const
Retrieve a module with the given name using lexical name lookup, starting at the given context.
Definition: ModuleMap.cpp:836
bool isBuiltinHeader(FileEntryRef File)
Is this a compiler builtin header?
Definition: ModuleMap.cpp:403
Module * createModule(StringRef Name, Module *Parent, bool IsFramework, bool IsExplicit)
Create new submodule, assuming it does not exist.
Definition: ModuleMap.cpp:866
module_iterator module_end() const
Definition: ModuleMap.h:748
bool isHeaderInUnavailableModule(FileEntryRef Header) const
Determine whether the given header is part of a module marked 'unavailable'.
Definition: ModuleMap.cpp:714
FileID getContainingModuleMapFileID(const Module *Module) const
Retrieve the module map file containing the definition of the given module.
Definition: ModuleMap.cpp:1401
~ModuleMap()
Destroy the module map.
bool parseModuleMapFile(FileEntryRef File, bool IsSystem, DirectoryEntryRef Dir, FileID ID=FileID(), SourceLocation ExternModuleLoc=SourceLocation())
Parse a module map without creating clang::Module instances.
Definition: ModuleMap.cpp:1324
Module * createGlobalModuleFragmentForModuleUnit(SourceLocation Loc, Module *Parent=nullptr)
Create a global module fragment for a C++ module unit.
Definition: ModuleMap.cpp:883
void setTarget(const TargetInfo &Target)
Set the target information.
Definition: ModuleMap.cpp:360
Module * lookupModuleQualified(StringRef Name, Module *Context) const
Retrieve a module with the given name within the given context, using direct (qualified) name lookup.
Definition: ModuleMap.cpp:846
void resolveLinkAsDependencies(Module *Mod)
Use PendingLinkAsModule information to mark top level link names that are going to be replaced by exp...
Definition: ModuleMap.cpp:51
ModuleHeaderRole
Flags describing the role of a module header.
Definition: ModuleMap.h:126
@ PrivateHeader
This header is included but private.
Definition: ModuleMap.h:131
@ ExcludedHeader
This header is explicitly excluded from the module.
Definition: ModuleMap.h:138
@ NormalHeader
This header is normally included in the module.
Definition: ModuleMap.h:128
@ TextualHeader
This header is part of the module (for layering purposes) but should be textually included.
Definition: ModuleMap.h:135
Module * createModuleForInterfaceUnit(SourceLocation Loc, StringRef Name)
Create a new module for a C++ module interface unit.
Definition: ModuleMap.cpp:935
void addHeader(Module *Mod, Module::Header Header, ModuleHeaderRole Role, bool Imported=false)
Adds this header to the given module.
Definition: ModuleMap.cpp:1296
Module * createPrivateModuleFragmentForInterfaceUnit(Module *Parent, SourceLocation Loc)
Create a global module fragment for a C++ module interface unit.
Definition: ModuleMap.cpp:912
Module * findOrInferSubmodule(Module *Parent, StringRef Name)
Definition: ModuleMap.cpp:820
ArrayRef< KnownHeader > findAllModulesForHeader(FileEntryRef File)
Retrieve all the modules that contain the given header file.
Definition: ModuleMap.cpp:693
Module * createImplicitGlobalModuleFragmentForModuleUnit(SourceLocation Loc, Module *Parent)
Definition: ModuleMap.cpp:897
Module * createModuleUnitWithKind(SourceLocation Loc, StringRef Name, Module::ModuleKind Kind)
Create a new C++ module with the specified kind, and reparent any pending global module fragment(s) t...
Definition: ModuleMap.cpp:921
Module * findOrLoadModule(StringRef Name)
Definition: ModuleMap.cpp:2215
static ModuleHeaderRole headerKindToRole(Module::HeaderKind Kind)
Convert a header kind to a role. Requires Kind to not be HK_Excluded.
Definition: ModuleMap.cpp:86
bool resolveUses(Module *Mod, bool Complain)
Resolve all of the unresolved uses in the given module.
Definition: ModuleMap.cpp:1504
Describes a module or submodule.
Definition: Module.h:144
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition: Module.h:732
void addRequirement(StringRef Feature, bool RequiredState, const LangOptions &LangOpts, const TargetInfo &Target)
Add the given feature requirement to the list of features required by this module.
Definition: Module.cpp:313
SmallVector< ExportDecl, 2 > Exports
The set of export declarations.
Definition: Module.h:471
bool isForBuilding(const LangOptions &LangOpts) const
Determine whether this module can be built in this compilation.
Definition: Module.cpp:155
std::variant< std::monostate, FileEntryRef, DirectoryEntryRef > Umbrella
The umbrella header or directory.
Definition: Module.h:205
unsigned InferSubmodules
Whether we should infer submodules for this module based on the headers.
Definition: Module.h:406
bool directlyUses(const Module *Requested)
Determine whether this module has declared its intention to directly use another module.
Definition: Module.cpp:287
std::vector< std::string > ConfigMacros
The set of "configuration macros", which are macros that (intentionally) change how this module is bu...
Definition: Module.h:528
SourceLocation InferredSubmoduleLoc
The location of the inferred submodule.
Definition: Module.h:454
unsigned IsUnimportable
Whether this module has declared itself unimportable, either because it's missing a requirement from ...
Definition: Module.h:361
void print(raw_ostream &OS, unsigned Indent=0, bool Dump=false) const
Print the module map for this module to the given stream.
Definition: Module.cpp:463
SourceLocation DefinitionLoc
The location of the module definition.
Definition: Module.h:150
SmallVector< UnresolvedHeaderDirective, 1 > MissingHeaders
Headers that are mentioned in the module map file but could not be found on the file system.
Definition: Module.h:341
Module * Parent
The parent of this module.
Definition: Module.h:193
void markUnavailable(bool Unimportable)
Mark this module and all of its submodules as unavailable.
Definition: Module.cpp:325
SmallVector< UnresolvedHeaderDirective, 1 > UnresolvedHeaders
Headers that are mentioned in the module map file but that we have not yet attempted to resolve to a ...
Definition: Module.h:337
@ HK_PrivateTextual
Definition: Module.h:282
bool fullModuleNameIs(ArrayRef< StringRef > nameParts) const
Whether the full name of this module is equal to joining nameParts with "."s.
Definition: Module.cpp:254
unsigned IsInferred
Whether this is an inferred submodule (module * { ... }).
Definition: Module.h:399
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers).
Definition: Module.h:389
std::string Name
The name of this module.
Definition: Module.h:147
bool isSubFramework() const
Determine whether this module is a subframework of another framework.
Definition: Module.h:635
unsigned IsExternC
Whether this is an 'extern "C"' module (which implicitly puts all headers in it within an 'extern "C"...
Definition: Module.h:395
unsigned ModuleMapIsPrivate
Whether this module came from a "private" module map, found next to a regular (public) module map.
Definition: Module.h:434
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used.
Definition: Module.h:520
SmallVector< UnresolvedExportDecl, 2 > UnresolvedExports
The set of export declarations that have yet to be resolved.
Definition: Module.h:489
void addHeader(HeaderKind HK, Header H)
Definition: Module.h:308
std::string UmbrellaRelativeToRootModuleDirectory
Definition: Module.h:214
OptionalDirectoryEntryRef Directory
The build directory of this module.
Definition: Module.h:198
SmallVector< ModuleId, 2 > UnresolvedDirectUses
The set of use declarations that have yet to be resolved.
Definition: Module.h:495
unsigned NoUndeclaredIncludes
Whether files in this module can only include non-modular headers and headers from used modules.
Definition: Module.h:429
unsigned ConfigMacrosExhaustive
Whether the set of configuration macros is exhaustive.
Definition: Module.h:424
ArrayRef< Header > getHeaders(HeaderKind HK) const
Definition: Module.h:302
unsigned InferExportWildcard
Whether, when inferring submodules, the inferr submodules should export all modules they import (e....
Definition: Module.h:416
std::vector< UnresolvedConflict > UnresolvedConflicts
The list of conflicts for which the module-id has not yet been resolved.
Definition: Module.h:541
unsigned IsFromModuleFile
Whether this module was loaded from a module file.
Definition: Module.h:376
bool isSubModuleOf(const Module *Other) const
Check if this module is a (possibly transitive) submodule of Other.
Definition: Module.cpp:193
bool isPartOfFramework() const
Determine whether this module is a part of a framework, either because it is a framework module or be...
Definition: Module.h:625
bool isAvailable() const
Determine whether this module is available for use within the current translation unit.
Definition: Module.h:586
llvm::PointerIntPair< Module *, 1, bool > ExportDecl
Describes an exported module.
Definition: Module.h:468
@ ModuleImplementationUnit
This is a C++20 module implementation unit.
Definition: Module.h:167
@ ImplicitGlobalModuleFragment
This is an implicit fragment of the global module which contains only language linkage declarations (...
Definition: Module.h:185
@ ModuleInterfaceUnit
This is a C++20 module interface unit.
Definition: Module.h:164
@ ModuleHeaderUnit
This is a C++20 header unit.
Definition: Module.h:161
@ PrivateModuleFragment
This is the private module fragment within some C++ module.
Definition: Module.h:180
@ ExplicitGlobalModuleFragment
This is the explicit Global Module Fragment of a modular TU.
Definition: Module.h:177
unsigned IsFramework
Whether this is a framework module.
Definition: Module.h:380
std::string ExportAsModule
The module through which entities defined in this module will eventually be exposed,...
Definition: Module.h:218
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition: Module.cpp:239
std::string UmbrellaAsWritten
The name of the umbrella entry, as written in the module map.
Definition: Module.h:211
unsigned IsAvailable
Whether this module is available in the current translation unit.
Definition: Module.h:372
unsigned InferExplicitSubmodules
Whether, when inferring submodules, the inferred submodules should be explicit.
Definition: Module.h:411
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition: Module.h:722
OptionalDirectoryEntryRef getEffectiveUmbrellaDir() const
Get the effective umbrella directory for this module: either the one explicitly written in the module...
Definition: Module.cpp:263
bool UseExportAsModuleLinkName
Autolinking uses the framework name for linking purposes when this is false and the export_as name ot...
Definition: Module.h:524
std::vector< Conflict > Conflicts
The list of conflicts.
Definition: Module.h:553
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
FileIDAndOffset getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
OptionalFileEntryRef getFileEntryRefForID(FileID FID) const
Returns the FileEntryRef for the provided FileID.
FileID translateFile(const FileEntry *SourceFile) const
Get the FileID for the given file.
FileID createFileID(FileEntryRef SourceFile, SourceLocation IncludePos, SrcMgr::CharacteristicKind FileCharacter, int LoadedID=0, SourceLocation::UIntTy LoadedOffset=0)
Create a new FileID that represents the specified file being #included from the specified IncludePosi...
FileManager & getFileManager() const
FileID getMainFileID() const
Returns the FileID of the main source file.
bool isLoadedFileID(FileID FID) const
Returns true if FID came from a PCH/Module.
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file.
std::optional< llvm::MemoryBufferRef > getBufferOrNone(FileID FID, SourceLocation Loc=SourceLocation()) const
Return the buffer for the specified FileID.
A trivial tuple used to represent a source range.
Exposes information about the current target.
Definition: TargetInfo.h:226
Defines the clang::TargetInfo interface.
bool Sub(InterpState &S, CodePtr OpPC)
Definition: Interp.h:425
std::optional< ModuleMapFile > parseModuleMap(FileID ID, clang::DirectoryEntryRef Dir, SourceManager &SM, DiagnosticsEngine &Diags, bool IsSystem, unsigned *Offset)
Parse a module map file into an in memory representation.
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
Definition: ModuleMapFile.h:36
The JSON file list parser is used to communicate input to InstallAPI.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
LLVM_READONLY bool isAsciiIdentifierContinue(unsigned char c)
Definition: CharInfo.h:61
@ Private
'private' clause, allowed on 'parallel', 'serial', 'loop', 'parallel loop', and 'serial loop' constru...
LLVM_READONLY bool isValidAsciiIdentifier(StringRef S, bool AllowDollar=false)
Return true if this is a valid ASCII identifier.
Definition: CharInfo.h:244
@ Result
The result type of a method or function.
LLVM_READONLY bool isDigit(unsigned char c)
Return true if this character is an ASCII digit: [0-9].
Definition: CharInfo.h:114
@ Keyword
The name has been typo-corrected to a keyword.
@ Other
Other implicit parameter.
The set of attributes that can be attached to a module.
Definition: Module.h:109
unsigned IsExternC
Whether this is an extern "C" module.
Definition: Module.h:116
unsigned IsSystem
Whether this is a system module.
Definition: Module.h:112
unsigned NoUndeclaredIncludes
Whether files in this module can only include non-modular headers and headers from used modules.
Definition: Module.h:125
A conflict between two modules.
Definition: Module.h:544
Module * Other
The module that this module conflicts with.
Definition: Module.h:546
std::string Message
The message provided to the user when there is a conflict.
Definition: Module.h:549
Information about a header directive as found in the module map file.
Definition: Module.h:287
std::string NameAsWritten
Definition: Module.h:288
FileEntryRef Entry
Definition: Module.h:290
A library or framework to link against when an entity from this module is used.
Definition: Module.h:503
An unresolved conflict with another module.
Definition: Module.h:531
std::string Message
The message provided to the user when there is a conflict.
Definition: Module.h:536
ModuleId Id
The (unresolved) module id.
Definition: Module.h:533
Describes an exported module that has not yet been resolved (perhaps because the module it refers to ...
Definition: Module.h:475
Stored information about a header directive that was found in the module map file but has not been re...
Definition: Module.h:325
std::optional< off_t > Size
Definition: Module.h:331
std::optional< time_t > ModTime
Definition: Module.h:332
std::vector< StringRef > Macros
std::optional< int64_t > Size
Definition: ModuleMapFile.h:53
std::optional< int64_t > MTime
Definition: ModuleMapFile.h:54
ModuleAttributes Attrs
Points to the first keyword in the decl.
Definition: ModuleMapFile.h:73
std::vector< Decl > Decls
Definition: ModuleMapFile.h:74
Represents the parsed form of a module map file.
std::vector< TopLevelDecl > Decls
FileID ID
The FileID used to parse this module map. This is always a local ID.
OptionalDirectoryEntryRef Dir
The directory in which the module map was discovered.
std::vector< RequiresFeature > Features
Definition: ModuleMapFile.h:46