1//===- Module.cpp - Describe a module -------------------------------------===//
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 Module class, which describes a module in the source
10// code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Basic/Module.h"
15#include "clang/Basic/CharInfo.h"
16#include "clang/Basic/FileManager.h"
17#include "clang/Basic/LangOptions.h"
18#include "clang/Basic/SourceLocation.h"
19#include "clang/Basic/TargetInfo.h"
20#include "llvm/ADT/ArrayRef.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/StringMap.h"
23#include "llvm/ADT/StringRef.h"
24#include "llvm/ADT/StringSwitch.h"
25#include "llvm/Support/Compiler.h"
26#include "llvm/Support/ErrorHandling.h"
27#include "llvm/Support/Path.h"
28#include "llvm/Support/raw_ostream.h"
29#include <cassert>
30#include <functional>
31#include <string>
32#include <utility>
33#include <vector>
34
35using namespace clang;
36
37Module::Module(ModuleConstructorTag, StringRef Name,
38 SourceLocation DefinitionLoc, Module *Parent, bool IsFramework,
39 bool IsExplicit, unsigned VisibilityID)
40 : Name(Name), DefinitionLoc(DefinitionLoc), Parent(Parent),
41 VisibilityID(VisibilityID), IsUnimportable(false),
42 HasIncompatibleModuleFile(false), IsAvailable(true),
43 IsFromModuleFile(false), IsFramework(IsFramework), IsExplicit(IsExplicit),
44 IsSystem(false), IsExternC(false), IsInferred(false),
45 InferSubmodules(false), InferExplicitSubmodules(false),
46 InferExportWildcard(false), ConfigMacrosExhaustive(false),
47 NoUndeclaredIncludes(false), ModuleMapIsPrivate(false),
48 NamedModuleHasInit(true), NameVisibility(Hidden) {
49 if (Parent) {
50 IsAvailable = Parent->isAvailable();
51 IsUnimportable = Parent->isUnimportable();
52 IsSystem = Parent->IsSystem;
53 IsExternC = Parent->IsExternC;
54 NoUndeclaredIncludes = Parent->NoUndeclaredIncludes;
55 ModuleMapIsPrivate = Parent->ModuleMapIsPrivate;
56
57 Parent->addSubmodule(Name, Submodule: this);
58 }
59}
60
61Module::~Module() = default;
62
63static bool isPlatformEnvironment(const TargetInfo &Target, StringRef Feature) {
64 StringRef Platform = Target.getPlatformName();
65 StringRef Env = Target.getTriple().getEnvironmentName();
66
67 // Attempt to match platform and environment.
68 if (Platform == Feature || Target.getTriple().getOSName() == Feature ||
69 Env == Feature)
70 return true;
71
72 auto CmpPlatformEnv = [](StringRef LHS, StringRef RHS) {
73 auto Pos = LHS.find(C: '-');
74 if (Pos == StringRef::npos)
75 return false;
76 SmallString<128> NewLHS = LHS.slice(Start: 0, End: Pos);
77 NewLHS += LHS.slice(Start: Pos+1, End: LHS.size());
78 return NewLHS == RHS;
79 };
80
81 SmallString<128> PlatformEnv = Target.getTriple().getOSAndEnvironmentName();
82 // Darwin has different but equivalent variants for simulators, example:
83 // 1. x86_64-apple-ios-simulator
84 // 2. x86_64-apple-iossimulator
85 // where both are valid examples of the same platform+environment but in the
86 // variant (2) the simulator is hardcoded as part of the platform name. Both
87 // forms above should match for "iossimulator" requirement.
88 if (Target.getTriple().isOSDarwin() && PlatformEnv.ends_with(Suffix: "simulator"))
89 return PlatformEnv == Feature || CmpPlatformEnv(PlatformEnv, Feature);
90
91 return PlatformEnv == Feature;
92}
93
94/// Determine whether a translation unit built using the current
95/// language options has the given feature.
96static bool hasFeature(StringRef Feature, const LangOptions &LangOpts,
97 const TargetInfo &Target) {
98 bool HasFeature = llvm::StringSwitch<bool>(Feature)
99 .Case(S: "altivec", Value: LangOpts.AltiVec)
100 .Case(S: "blocks", Value: LangOpts.Blocks)
101 .Case(S: "coroutines", Value: LangOpts.Coroutines)
102 .Case(S: "cplusplus", Value: LangOpts.CPlusPlus)
103 .Case(S: "cplusplus11", Value: LangOpts.CPlusPlus11)
104 .Case(S: "cplusplus14", Value: LangOpts.CPlusPlus14)
105 .Case(S: "cplusplus17", Value: LangOpts.CPlusPlus17)
106 .Case(S: "cplusplus20", Value: LangOpts.CPlusPlus20)
107 .Case(S: "cplusplus23", Value: LangOpts.CPlusPlus23)
108 .Case(S: "cplusplus26", Value: LangOpts.CPlusPlus26)
109 .Case(S: "cplusplus29", Value: LangOpts.CPlusPlus29)
110 .Case(S: "c99", Value: LangOpts.C99)
111 .Case(S: "c11", Value: LangOpts.C11)
112 .Case(S: "c17", Value: LangOpts.C17)
113 .Case(S: "c23", Value: LangOpts.C23)
114 .Case(S: "freestanding", Value: LangOpts.Freestanding)
115 .Case(S: "gnuinlineasm", Value: LangOpts.GNUAsm)
116 .Case(S: "objc", Value: LangOpts.ObjC)
117 .Case(S: "objc_arc", Value: LangOpts.ObjCAutoRefCount)
118 .Case(S: "opencl", Value: LangOpts.OpenCL)
119 .Case(S: "reflection", Value: LangOpts.Reflection)
120 .Case(S: "tls", Value: Target.isTLSSupported())
121 .Case(S: "zvector", Value: LangOpts.ZVector)
122 .Default(Value: Target.hasFeature(Feature) ||
123 isPlatformEnvironment(Target, Feature));
124 if (!HasFeature)
125 HasFeature = llvm::is_contained(Range: LangOpts.ModuleFeatures, Element: Feature);
126 return HasFeature;
127}
128
129bool Module::isUnimportable(const LangOptions &LangOpts,
130 const TargetInfo &Target, Requirement &Req,
131 Module *&ShadowingModule) const {
132 if (!IsUnimportable)
133 return false;
134
135 for (const Module *Current = this; Current; Current = Current->Parent) {
136 if (Current->ShadowingModule) {
137 ShadowingModule = Current->ShadowingModule;
138 return true;
139 }
140 for (unsigned I = 0, N = Current->Requirements.size(); I != N; ++I) {
141 if (hasFeature(Feature: Current->Requirements[I].FeatureName, LangOpts, Target) !=
142 Current->Requirements[I].RequiredState) {
143 Req = Current->Requirements[I];
144 return true;
145 }
146 }
147 }
148
149 llvm_unreachable("could not find a reason why module is unimportable");
150}
151
152// The -fmodule-name option tells the compiler to textually include headers in
153// the specified module, meaning Clang won't build the specified module. This
154// is useful in a number of situations, for instance, when building a library
155// that vends a module map, one might want to avoid hitting intermediate build
156// products containing the module map or avoid finding the system installed
157// modulemap for that library.
158bool Module::isForBuilding(const LangOptions &LangOpts) const {
159 StringRef TopLevelName = getTopLevelModuleName();
160 StringRef CurrentModule = LangOpts.CurrentModule;
161
162 // When building the implementation of framework Foo, we want to make sure
163 // that Foo *and* Foo_Private are textually included and no modules are built
164 // for either.
165 if (!LangOpts.isCompilingModule() && getTopLevelModule()->IsFramework &&
166 CurrentModule == LangOpts.ModuleName &&
167 !CurrentModule.ends_with(Suffix: "_Private") &&
168 TopLevelName.ends_with(Suffix: "_Private"))
169 TopLevelName = TopLevelName.drop_back(N: 8);
170
171 return TopLevelName == CurrentModule;
172}
173
174bool Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target,
175 Requirement &Req,
176 UnresolvedHeaderDirective &MissingHeader,
177 Module *&ShadowingModule) const {
178 if (IsAvailable)
179 return true;
180
181 if (isUnimportable(LangOpts, Target, Req, ShadowingModule))
182 return false;
183
184 // FIXME: All missing headers are listed on the top-level module. Should we
185 // just look there?
186 for (const Module *Current = this; Current; Current = Current->Parent) {
187 if (!Current->MissingHeaders.empty()) {
188 MissingHeader = Current->MissingHeaders.front();
189 return false;
190 }
191 }
192
193 llvm_unreachable("could not find a reason why module is unavailable");
194}
195
196bool Module::isSubModuleOf(const Module *Other) const {
197 for (auto *Parent = this; Parent; Parent = Parent->Parent) {
198 if (Parent == Other)
199 return true;
200 }
201 return false;
202}
203
204const Module *Module::getTopLevelModule() const {
205 const Module *Result = this;
206 while (Result->Parent)
207 Result = Result->Parent;
208
209 return Result;
210}
211
212static StringRef getModuleNameFromComponent(
213 const std::pair<std::string, SourceLocation> &IdComponent) {
214 return IdComponent.first;
215}
216
217static StringRef getModuleNameFromComponent(StringRef R) { return R; }
218
219template<typename InputIter>
220static void printModuleId(raw_ostream &OS, InputIter Begin, InputIter End,
221 bool AllowStringLiterals = true) {
222 for (InputIter It = Begin; It != End; ++It) {
223 if (It != Begin)
224 OS << ".";
225
226 StringRef Name = getModuleNameFromComponent(*It);
227 if (!AllowStringLiterals || isValidAsciiIdentifier(S: Name))
228 OS << Name;
229 else {
230 OS << '"';
231 OS.write_escaped(Str: Name);
232 OS << '"';
233 }
234 }
235}
236
237template<typename Container>
238static void printModuleId(raw_ostream &OS, const Container &C) {
239 return printModuleId(OS, C.begin(), C.end());
240}
241
242std::string Module::getFullModuleName(bool AllowStringLiterals) const {
243 SmallVector<StringRef, 2> Names;
244
245 // Build up the set of module names (from innermost to outermost).
246 for (const Module *M = this; M; M = M->Parent)
247 Names.push_back(Elt: M->Name);
248
249 std::string Result;
250
251 llvm::raw_string_ostream Out(Result);
252 printModuleId(OS&: Out, Begin: Names.rbegin(), End: Names.rend(), AllowStringLiterals);
253
254 return Result;
255}
256
257bool Module::fullModuleNameIs(ArrayRef<StringRef> nameParts) const {
258 for (const Module *M = this; M; M = M->Parent) {
259 if (nameParts.empty() || M->Name != nameParts.back())
260 return false;
261 nameParts = nameParts.drop_back();
262 }
263 return nameParts.empty();
264}
265
266OptionalDirectoryEntryRef Module::getEffectiveUmbrellaDir() const {
267 if (const auto *Hdr = std::get_if<FileEntryRef>(ptr: &Umbrella))
268 return Hdr->getDir();
269 if (const auto *Dir = std::get_if<DirectoryEntryRef>(ptr: &Umbrella))
270 return *Dir;
271 return std::nullopt;
272}
273
274/// Whether watching \p Ancestor recursively also covers \p Path.
275static bool coversPath(StringRef Ancestor, StringRef Path) {
276 return Path.starts_with(Prefix: Ancestor) &&
277 (Path.size() == Ancestor.size() ||
278 llvm::sys::path::is_separator(value: Path[Ancestor.size()]));
279}
280
281void Module::addDirectoryDependency(StringRef Path) {
282 Module *TopLevel = getTopLevelModule();
283 std::vector<std::string> &Deps = TopLevel->DirectoryDependencies;
284 // These are recursive dependencies, so an entry under one already recorded
285 // adds nothing. Submodules contribute to the same list, and their umbrellas
286 // often nest.
287 for (StringRef Dep : Deps)
288 if (coversPath(Ancestor: Dep, Path))
289 return;
290 llvm::erase_if(C&: Deps,
291 P: [&](const std::string &Dep) { return coversPath(Ancestor: Path, Path: Dep); });
292 Deps.emplace_back(args&: Path);
293}
294
295void Module::addTopHeader(FileEntryRef File) {
296 assert(File);
297 TopHeaders.insert(X: File);
298}
299
300ArrayRef<FileEntryRef> Module::getTopHeaders(FileManager &FileMgr) {
301 if (!TopHeaderNames.empty()) {
302 for (StringRef TopHeaderName : TopHeaderNames)
303 if (auto FE = FileMgr.getOptionalFileRef(Filename: TopHeaderName))
304 TopHeaders.insert(X: *FE);
305 TopHeaderNames.clear();
306 }
307
308 return llvm::ArrayRef(TopHeaders.begin(), TopHeaders.end());
309}
310
311bool Module::directlyUses(const Module *Requested) {
312 auto *Top = getTopLevelModule();
313
314 // A top-level module implicitly uses itself.
315 if (Requested->isSubModuleOf(Other: Top))
316 return true;
317
318 for (auto *Use : Top->DirectUses)
319 if (Requested->isSubModuleOf(Other: Use))
320 return true;
321
322 // Anyone is allowed to use our builtin stddef.h and its accompanying modules.
323 if (Requested->fullModuleNameIs(nameParts: {"_Builtin_stddef", "max_align_t"}) ||
324 Requested->fullModuleNameIs(nameParts: {"_Builtin_stddef_wint_t"}))
325 return true;
326 // Darwin is allowed is to use our builtin 'ptrauth.h' and its accompanying
327 // module.
328 if (!Requested->Parent && Requested->Name == "ptrauth")
329 return true;
330
331 if (NoUndeclaredIncludes)
332 UndeclaredUses.insert(X: Requested);
333
334 return false;
335}
336
337void Module::addRequirement(StringRef Feature, bool RequiredState,
338 const LangOptions &LangOpts,
339 const TargetInfo &Target) {
340 Requirements.push_back(Elt: Requirement{.FeatureName: std::string(Feature), .RequiredState: RequiredState});
341
342 // If this feature is currently available, we're done.
343 if (hasFeature(Feature, LangOpts, Target) == RequiredState)
344 return;
345
346 markUnavailable(/*Unimportable*/true);
347}
348
349void Module::markUnavailable(bool Unimportable) {
350 auto needUpdate = [Unimportable](Module *M) {
351 return M->IsAvailable || (!M->IsUnimportable && Unimportable);
352 };
353
354 if (!needUpdate(this))
355 return;
356
357 SmallVector<Module *, 2> Stack;
358 Stack.push_back(Elt: this);
359 while (!Stack.empty()) {
360 Module *Current = Stack.pop_back_val();
361
362 if (!needUpdate(Current))
363 continue;
364
365 Current->IsAvailable = false;
366 Current->IsUnimportable |= Unimportable;
367 for (Module *Submodule : Current->submodules()) {
368 if (needUpdate(Submodule))
369 Stack.push_back(Elt: Submodule);
370 }
371 }
372}
373
374ModuleRef Module::findSubmodule(StringRef Name) const {
375 if (auto It = SubModuleIndex.find(Key: Name); It != SubModuleIndex.end())
376 return SubModules[It->second];
377
378 return nullptr;
379}
380
381Module *Module::getGlobalModuleFragment() const {
382 assert(isNamedModuleUnit() && "We should only query the global module "
383 "fragment from the C++20 Named modules");
384
385 for (Module *SubModule : submodules())
386 if (SubModule->isExplicitGlobalModule())
387 return SubModule;
388
389 return nullptr;
390}
391
392Module *Module::getPrivateModuleFragment() const {
393 assert(isNamedModuleUnit() && "We should only query the private module "
394 "fragment from the C++20 Named modules");
395
396 for (Module *SubModule : submodules())
397 if (SubModule->isPrivateModule())
398 return SubModule;
399
400 return nullptr;
401}
402
403void Module::getExportedModules(SmallVectorImpl<Module *> &Exported) const {
404 // All non-explicit submodules are exported.
405 for (Module *Mod : submodules())
406 if (!Mod->IsExplicit)
407 Exported.push_back(Elt: Mod);
408
409 // Find re-exported modules by filtering the list of imported modules.
410 bool AnyWildcard = false;
411 bool UnrestrictedWildcard = false;
412 SmallVector<Module *, 4> WildcardRestrictions;
413 for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
414 Module *Mod = Exports[I].first;
415 if (!Exports[I].second) {
416 // Export a named module directly; no wildcards involved.
417 Exported.push_back(Elt: Mod);
418
419 continue;
420 }
421
422 // Wildcard export: export all of the imported modules that match
423 // the given pattern.
424 AnyWildcard = true;
425 if (UnrestrictedWildcard)
426 continue;
427
428 if (Module *Restriction = Exports[I].first)
429 WildcardRestrictions.push_back(Elt: Restriction);
430 else {
431 WildcardRestrictions.clear();
432 UnrestrictedWildcard = true;
433 }
434 }
435
436 // If there were any wildcards, push any imported modules that were
437 // re-exported by the wildcard restriction.
438 if (!AnyWildcard)
439 return;
440
441 for (unsigned I = 0, N = Imports.size(); I != N; ++I) {
442 Module *Mod = Imports[I];
443 bool Acceptable = UnrestrictedWildcard;
444 if (!Acceptable) {
445 // Check whether this module meets one of the restrictions.
446 for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
447 Module *Restriction = WildcardRestrictions[R];
448 if (Mod == Restriction || Mod->isSubModuleOf(Other: Restriction)) {
449 Acceptable = true;
450 break;
451 }
452 }
453 }
454
455 if (!Acceptable)
456 continue;
457
458 Exported.push_back(Elt: Mod);
459 }
460}
461
462void Module::buildVisibleModulesCache() const {
463 assert(VisibleModulesCache.empty() && "cache does not need building");
464
465 // This module is visible to itself.
466 VisibleModulesCache.insert(V: this);
467
468 // Every imported module is visible.
469 SmallVector<Module *, 16> Stack(Imports.begin(), Imports.end());
470 while (!Stack.empty()) {
471 Module *CurrModule = Stack.pop_back_val();
472
473 // Every module transitively exported by an imported module is visible.
474 if (VisibleModulesCache.insert(V: CurrModule).second)
475 CurrModule->getExportedModules(Exported&: Stack);
476 }
477}
478
479void Module::print(raw_ostream &OS, unsigned Indent, bool Dump) const {
480 OS.indent(NumSpaces: Indent);
481 if (IsFramework)
482 OS << "framework ";
483 if (IsExplicit)
484 OS << "explicit ";
485 OS << "module ";
486 printModuleId(OS, Begin: &Name, End: &Name + 1);
487
488 if (IsSystem || IsExternC) {
489 OS.indent(NumSpaces: Indent + 2);
490 if (IsSystem)
491 OS << " [system]";
492 if (IsExternC)
493 OS << " [extern_c]";
494 }
495
496 OS << " {\n";
497
498 if (!Requirements.empty()) {
499 OS.indent(NumSpaces: Indent + 2);
500 OS << "requires ";
501 for (unsigned I = 0, N = Requirements.size(); I != N; ++I) {
502 if (I)
503 OS << ", ";
504 if (!Requirements[I].RequiredState)
505 OS << "!";
506 OS << Requirements[I].FeatureName;
507 }
508 OS << "\n";
509 }
510
511 if (std::optional<Header> H = getUmbrellaHeaderAsWritten()) {
512 OS.indent(NumSpaces: Indent + 2);
513 OS << "umbrella header \"";
514 OS.write_escaped(Str: H->NameAsWritten);
515 OS << "\"\n";
516 } else if (std::optional<DirectoryName> D = getUmbrellaDirAsWritten()) {
517 OS.indent(NumSpaces: Indent + 2);
518 OS << "umbrella \"";
519 OS.write_escaped(Str: D->NameAsWritten);
520 OS << "\"\n";
521 }
522
523 if (!ConfigMacros.empty() || ConfigMacrosExhaustive) {
524 OS.indent(NumSpaces: Indent + 2);
525 OS << "config_macros ";
526 if (ConfigMacrosExhaustive)
527 OS << "[exhaustive]";
528 for (unsigned I = 0, N = ConfigMacros.size(); I != N; ++I) {
529 if (I)
530 OS << ", ";
531 OS << ConfigMacros[I];
532 }
533 OS << "\n";
534 }
535
536 struct {
537 StringRef Prefix;
538 HeaderKind Kind;
539 } Kinds[] = {{.Prefix: "", .Kind: HK_Normal},
540 {.Prefix: "textual ", .Kind: HK_Textual},
541 {.Prefix: "private ", .Kind: HK_Private},
542 {.Prefix: "private textual ", .Kind: HK_PrivateTextual},
543 {.Prefix: "exclude ", .Kind: HK_Excluded}};
544
545 for (auto &K : Kinds) {
546 assert(&K == &Kinds[K.Kind] && "kinds in wrong order");
547 for (auto &H : getHeaders(HK: K.Kind)) {
548 OS.indent(NumSpaces: Indent + 2);
549 OS << K.Prefix << "header \"";
550 OS.write_escaped(Str: H.NameAsWritten);
551 OS << "\" { size " << H.Entry.getSize()
552 << " mtime " << H.Entry.getModificationTime() << " }\n";
553 }
554 }
555 for (auto *Unresolved : {&UnresolvedHeaders, &MissingHeaders}) {
556 for (auto &U : *Unresolved) {
557 OS.indent(NumSpaces: Indent + 2);
558 OS << Kinds[U.Kind].Prefix << "header \"";
559 OS.write_escaped(Str: U.FileName);
560 OS << "\"";
561 if (U.Size || U.ModTime) {
562 OS << " {";
563 if (U.Size)
564 OS << " size " << *U.Size;
565 if (U.ModTime)
566 OS << " mtime " << *U.ModTime;
567 OS << " }";
568 }
569 OS << "\n";
570 }
571 }
572
573 if (!ExportAsModule.empty()) {
574 OS.indent(NumSpaces: Indent + 2);
575 OS << "export_as" << ExportAsModule << "\n";
576 }
577
578 for (Module *Submodule : submodules())
579 // Print inferred subframework modules so that we don't need to re-infer
580 // them (requires expensive directory iteration + stat calls) when we build
581 // the module. Regular inferred submodules are OK, as we need to look at all
582 // those header files anyway.
583 if (!Submodule->IsInferred || Submodule->IsFramework)
584 Submodule->print(OS, Indent: Indent + 2, Dump);
585
586 for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
587 OS.indent(NumSpaces: Indent + 2);
588 OS << "export ";
589 if (Module *Restriction = Exports[I].first) {
590 OS << Restriction->getFullModuleName(AllowStringLiterals: true);
591 if (Exports[I].second)
592 OS << ".*";
593 } else {
594 OS << "*";
595 }
596 OS << "\n";
597 }
598
599 for (unsigned I = 0, N = UnresolvedExports.size(); I != N; ++I) {
600 OS.indent(NumSpaces: Indent + 2);
601 OS << "export ";
602 printModuleId(OS, C: UnresolvedExports[I].Id);
603 if (UnresolvedExports[I].Wildcard)
604 OS << (UnresolvedExports[I].Id.empty() ? "*" : ".*");
605 OS << "\n";
606 }
607
608 if (Dump) {
609 for (Module *M : Imports) {
610 OS.indent(NumSpaces: Indent + 2);
611 llvm::errs() << "import " << M->getFullModuleName() << "\n";
612 }
613 }
614
615 for (unsigned I = 0, N = DirectUses.size(); I != N; ++I) {
616 OS.indent(NumSpaces: Indent + 2);
617 OS << "use ";
618 OS << DirectUses[I]->getFullModuleName(AllowStringLiterals: true);
619 OS << "\n";
620 }
621
622 for (unsigned I = 0, N = UnresolvedDirectUses.size(); I != N; ++I) {
623 OS.indent(NumSpaces: Indent + 2);
624 OS << "use ";
625 printModuleId(OS, C: UnresolvedDirectUses[I]);
626 OS << "\n";
627 }
628
629 for (unsigned I = 0, N = LinkLibraries.size(); I != N; ++I) {
630 OS.indent(NumSpaces: Indent + 2);
631 OS << "link ";
632 if (LinkLibraries[I].IsFramework)
633 OS << "framework ";
634 OS << "\"";
635 OS.write_escaped(Str: LinkLibraries[I].Library);
636 OS << "\"";
637 }
638
639 for (unsigned I = 0, N = UnresolvedConflicts.size(); I != N; ++I) {
640 OS.indent(NumSpaces: Indent + 2);
641 OS << "conflict ";
642 printModuleId(OS, C: UnresolvedConflicts[I].Id);
643 OS << ", \"";
644 OS.write_escaped(Str: UnresolvedConflicts[I].Message);
645 OS << "\"\n";
646 }
647
648 for (unsigned I = 0, N = Conflicts.size(); I != N; ++I) {
649 OS.indent(NumSpaces: Indent + 2);
650 OS << "conflict ";
651 OS << Conflicts[I].Other->getFullModuleName(AllowStringLiterals: true);
652 OS << ", \"";
653 OS.write_escaped(Str: Conflicts[I].Message);
654 OS << "\"\n";
655 }
656
657 if (InferSubmodules) {
658 OS.indent(NumSpaces: Indent + 2);
659 if (InferExplicitSubmodules)
660 OS << "explicit ";
661 OS << "module * {\n";
662 if (InferExportWildcard) {
663 OS.indent(NumSpaces: Indent + 4);
664 OS << "export *\n";
665 }
666 OS.indent(NumSpaces: Indent + 2);
667 OS << "}\n";
668 }
669
670 OS.indent(NumSpaces: Indent);
671 OS << "}\n";
672}
673
674LLVM_DUMP_METHOD void Module::dump() const {
675 print(OS&: llvm::errs(), Indent: 0, Dump: true);
676}
677
678void VisibleModuleSet::setVisible(Module *M, SourceLocation Loc,
679 bool IncludeExports, VisibleCallback Vis,
680 ConflictCallback Cb) {
681 // We can't import a global module fragment so the location can be invalid.
682 assert((M->isGlobalModule() || Loc.isValid()) &&
683 "setVisible expects a valid import location");
684 if (isVisible(M))
685 return;
686
687 ++Generation;
688
689 struct Visiting {
690 Module *M;
691 Visiting *ExportedBy;
692 };
693
694 std::function<void(Visiting)> VisitModule = [&](Visiting V) {
695 // Nothing to do for a module that's already visible.
696 unsigned ID = V.M->getVisibilityID();
697 if (ImportLocs.size() <= ID)
698 ImportLocs.resize(new_size: ID + 1);
699 else if (ImportLocs[ID].isValid())
700 return;
701
702 ImportLocs[ID] = Loc;
703 Vis(V.M);
704
705 // Make any exported modules visible.
706 if (IncludeExports) {
707 SmallVector<Module *, 16> Exports;
708 V.M->getExportedModules(Exported&: Exports);
709 for (Module *E : Exports) {
710 // Don't import non-importable modules.
711 if (!E->isUnimportable())
712 VisitModule({.M: E, .ExportedBy: &V});
713 }
714 }
715
716 for (auto &C : V.M->Conflicts) {
717 if (isVisible(M: C.Other)) {
718 llvm::SmallVector<Module*, 8> Path;
719 for (Visiting *I = &V; I; I = I->ExportedBy)
720 Path.push_back(Elt: I->M);
721 Cb(Path, C.Other, C.Message);
722 }
723 }
724 };
725 VisitModule({.M: M, .ExportedBy: nullptr});
726}
727