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