1 //===--- Module.cpp - Describe a module -----------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the Module class, which describes a module in the source
13 //===----------------------------------------------------------------------===//
15 #include "clang/Basic/Module.h"
16 #include "clang/Basic/FileManager.h"
17 #include "clang/Basic/LangOptions.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/raw_ostream.h"
25 using namespace clang;
27 Module::Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent,
28 bool IsFramework, bool IsExplicit, unsigned VisibilityID)
29 : Name(Name), DefinitionLoc(DefinitionLoc), Parent(Parent), Directory(),
30 Umbrella(), Signature(0), ASTFile(nullptr), VisibilityID(VisibilityID),
31 IsMissingRequirement(false), HasIncompatibleModuleFile(false),
32 IsAvailable(true), IsFromModuleFile(false), IsFramework(IsFramework),
33 IsExplicit(IsExplicit), IsSystem(false), IsExternC(false),
34 IsInferred(false), InferSubmodules(false), InferExplicitSubmodules(false),
35 InferExportWildcard(false), ConfigMacrosExhaustive(false),
36 NameVisibility(Hidden) {
38 if (!Parent->isAvailable())
42 if (Parent->IsExternC)
44 IsMissingRequirement = Parent->IsMissingRequirement;
46 Parent->SubModuleIndex[Name] = Parent->SubModules.size();
47 Parent->SubModules.push_back(this);
52 for (submodule_iterator I = submodule_begin(), IEnd = submodule_end();
58 /// \brief Determine whether a translation unit built using the current
59 /// language options has the given feature.
60 static bool hasFeature(StringRef Feature, const LangOptions &LangOpts,
61 const TargetInfo &Target) {
62 bool HasFeature = llvm::StringSwitch<bool>(Feature)
63 .Case("altivec", LangOpts.AltiVec)
64 .Case("blocks", LangOpts.Blocks)
65 .Case("cplusplus", LangOpts.CPlusPlus)
66 .Case("cplusplus11", LangOpts.CPlusPlus11)
67 .Case("objc", LangOpts.ObjC1)
68 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
69 .Case("opencl", LangOpts.OpenCL)
70 .Case("tls", Target.isTLSSupported())
71 .Case("zvector", LangOpts.ZVector)
72 .Default(Target.hasFeature(Feature));
74 HasFeature = std::find(LangOpts.ModuleFeatures.begin(),
75 LangOpts.ModuleFeatures.end(),
76 Feature) != LangOpts.ModuleFeatures.end();
80 bool Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target,
82 UnresolvedHeaderDirective &MissingHeader) const {
86 for (const Module *Current = this; Current; Current = Current->Parent) {
87 for (unsigned I = 0, N = Current->Requirements.size(); I != N; ++I) {
88 if (hasFeature(Current->Requirements[I].first, LangOpts, Target) !=
89 Current->Requirements[I].second) {
90 Req = Current->Requirements[I];
94 if (!Current->MissingHeaders.empty()) {
95 MissingHeader = Current->MissingHeaders.front();
100 llvm_unreachable("could not find a reason why module is unavailable");
103 bool Module::isSubModuleOf(const Module *Other) const {
104 const Module *This = this;
115 const Module *Module::getTopLevelModule() const {
116 const Module *Result = this;
117 while (Result->Parent)
118 Result = Result->Parent;
123 std::string Module::getFullModuleName() const {
124 SmallVector<StringRef, 2> Names;
126 // Build up the set of module names (from innermost to outermost).
127 for (const Module *M = this; M; M = M->Parent)
128 Names.push_back(M->Name);
131 for (SmallVectorImpl<StringRef>::reverse_iterator I = Names.rbegin(),
143 bool Module::fullModuleNameIs(ArrayRef<StringRef> nameParts) const {
144 for (const Module *M = this; M; M = M->Parent) {
145 if (nameParts.empty() || M->Name != nameParts.back())
147 nameParts = nameParts.drop_back();
149 return nameParts.empty();
152 Module::DirectoryName Module::getUmbrellaDir() const {
153 if (Header U = getUmbrellaHeader())
154 return {"", U.Entry->getDir()};
156 return {UmbrellaAsWritten, Umbrella.dyn_cast<const DirectoryEntry *>()};
159 ArrayRef<const FileEntry *> Module::getTopHeaders(FileManager &FileMgr) {
160 if (!TopHeaderNames.empty()) {
161 for (std::vector<std::string>::iterator
162 I = TopHeaderNames.begin(), E = TopHeaderNames.end(); I != E; ++I) {
163 if (const FileEntry *FE = FileMgr.getFile(*I))
164 TopHeaders.insert(FE);
166 TopHeaderNames.clear();
169 return llvm::makeArrayRef(TopHeaders.begin(), TopHeaders.end());
172 bool Module::directlyUses(const Module *Requested) const {
173 auto *Top = getTopLevelModule();
175 // A top-level module implicitly uses itself.
176 if (Requested->isSubModuleOf(Top))
179 for (auto *Use : Top->DirectUses)
180 if (Requested->isSubModuleOf(Use))
185 void Module::addRequirement(StringRef Feature, bool RequiredState,
186 const LangOptions &LangOpts,
187 const TargetInfo &Target) {
188 Requirements.push_back(Requirement(Feature, RequiredState));
190 // If this feature is currently available, we're done.
191 if (hasFeature(Feature, LangOpts, Target) == RequiredState)
194 markUnavailable(/*MissingRequirement*/true);
197 void Module::markUnavailable(bool MissingRequirement) {
198 auto needUpdate = [MissingRequirement](Module *M) {
199 return M->IsAvailable || (!M->IsMissingRequirement && MissingRequirement);
202 if (!needUpdate(this))
205 SmallVector<Module *, 2> Stack;
206 Stack.push_back(this);
207 while (!Stack.empty()) {
208 Module *Current = Stack.back();
211 if (!needUpdate(Current))
214 Current->IsAvailable = false;
215 Current->IsMissingRequirement |= MissingRequirement;
216 for (submodule_iterator Sub = Current->submodule_begin(),
217 SubEnd = Current->submodule_end();
218 Sub != SubEnd; ++Sub) {
219 if (needUpdate(*Sub))
220 Stack.push_back(*Sub);
225 Module *Module::findSubmodule(StringRef Name) const {
226 llvm::StringMap<unsigned>::const_iterator Pos = SubModuleIndex.find(Name);
227 if (Pos == SubModuleIndex.end())
230 return SubModules[Pos->getValue()];
233 static void printModuleId(raw_ostream &OS, const ModuleId &Id) {
234 for (unsigned I = 0, N = Id.size(); I != N; ++I) {
241 void Module::getExportedModules(SmallVectorImpl<Module *> &Exported) const {
242 // All non-explicit submodules are exported.
243 for (std::vector<Module *>::const_iterator I = SubModules.begin(),
244 E = SubModules.end();
247 if (!Mod->IsExplicit)
248 Exported.push_back(Mod);
251 // Find re-exported modules by filtering the list of imported modules.
252 bool AnyWildcard = false;
253 bool UnrestrictedWildcard = false;
254 SmallVector<Module *, 4> WildcardRestrictions;
255 for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
256 Module *Mod = Exports[I].getPointer();
257 if (!Exports[I].getInt()) {
258 // Export a named module directly; no wildcards involved.
259 Exported.push_back(Mod);
264 // Wildcard export: export all of the imported modules that match
265 // the given pattern.
267 if (UnrestrictedWildcard)
270 if (Module *Restriction = Exports[I].getPointer())
271 WildcardRestrictions.push_back(Restriction);
273 WildcardRestrictions.clear();
274 UnrestrictedWildcard = true;
278 // If there were any wildcards, push any imported modules that were
279 // re-exported by the wildcard restriction.
283 for (unsigned I = 0, N = Imports.size(); I != N; ++I) {
284 Module *Mod = Imports[I];
285 bool Acceptable = UnrestrictedWildcard;
287 // Check whether this module meets one of the restrictions.
288 for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
289 Module *Restriction = WildcardRestrictions[R];
290 if (Mod == Restriction || Mod->isSubModuleOf(Restriction)) {
300 Exported.push_back(Mod);
304 void Module::buildVisibleModulesCache() const {
305 assert(VisibleModulesCache.empty() && "cache does not need building");
307 // This module is visible to itself.
308 VisibleModulesCache.insert(this);
310 // Every imported module is visible.
311 SmallVector<Module *, 16> Stack(Imports.begin(), Imports.end());
312 while (!Stack.empty()) {
313 Module *CurrModule = Stack.pop_back_val();
315 // Every module transitively exported by an imported module is visible.
316 if (VisibleModulesCache.insert(CurrModule).second)
317 CurrModule->getExportedModules(Stack);
321 void Module::print(raw_ostream &OS, unsigned Indent) const {
327 OS << "module " << Name;
329 if (IsSystem || IsExternC) {
330 OS.indent(Indent + 2);
339 if (!Requirements.empty()) {
340 OS.indent(Indent + 2);
342 for (unsigned I = 0, N = Requirements.size(); I != N; ++I) {
345 if (!Requirements[I].second)
347 OS << Requirements[I].first;
352 if (Header H = getUmbrellaHeader()) {
353 OS.indent(Indent + 2);
354 OS << "umbrella header \"";
355 OS.write_escaped(H.NameAsWritten);
357 } else if (DirectoryName D = getUmbrellaDir()) {
358 OS.indent(Indent + 2);
360 OS.write_escaped(D.NameAsWritten);
364 if (!ConfigMacros.empty() || ConfigMacrosExhaustive) {
365 OS.indent(Indent + 2);
366 OS << "config_macros ";
367 if (ConfigMacrosExhaustive)
368 OS << "[exhaustive]";
369 for (unsigned I = 0, N = ConfigMacros.size(); I != N; ++I) {
372 OS << ConfigMacros[I];
380 } Kinds[] = {{"", HK_Normal},
381 {"textual ", HK_Textual},
382 {"private ", HK_Private},
383 {"private textual ", HK_PrivateTextual},
384 {"exclude ", HK_Excluded}};
386 for (auto &K : Kinds) {
387 for (auto &H : Headers[K.Kind]) {
388 OS.indent(Indent + 2);
389 OS << K.Prefix << "header \"";
390 OS.write_escaped(H.NameAsWritten);
395 for (submodule_const_iterator MI = submodule_begin(), MIEnd = submodule_end();
397 // Print inferred subframework modules so that we don't need to re-infer
398 // them (requires expensive directory iteration + stat calls) when we build
399 // the module. Regular inferred submodules are OK, as we need to look at all
400 // those header files anyway.
401 if (!(*MI)->IsInferred || (*MI)->IsFramework)
402 (*MI)->print(OS, Indent + 2);
404 for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
405 OS.indent(Indent + 2);
407 if (Module *Restriction = Exports[I].getPointer()) {
408 OS << Restriction->getFullModuleName();
409 if (Exports[I].getInt())
417 for (unsigned I = 0, N = UnresolvedExports.size(); I != N; ++I) {
418 OS.indent(Indent + 2);
420 printModuleId(OS, UnresolvedExports[I].Id);
421 if (UnresolvedExports[I].Wildcard)
422 OS << (UnresolvedExports[I].Id.empty() ? "*" : ".*");
426 for (unsigned I = 0, N = DirectUses.size(); I != N; ++I) {
427 OS.indent(Indent + 2);
429 OS << DirectUses[I]->getFullModuleName();
433 for (unsigned I = 0, N = UnresolvedDirectUses.size(); I != N; ++I) {
434 OS.indent(Indent + 2);
436 printModuleId(OS, UnresolvedDirectUses[I]);
440 for (unsigned I = 0, N = LinkLibraries.size(); I != N; ++I) {
441 OS.indent(Indent + 2);
443 if (LinkLibraries[I].IsFramework)
446 OS.write_escaped(LinkLibraries[I].Library);
450 for (unsigned I = 0, N = UnresolvedConflicts.size(); I != N; ++I) {
451 OS.indent(Indent + 2);
453 printModuleId(OS, UnresolvedConflicts[I].Id);
455 OS.write_escaped(UnresolvedConflicts[I].Message);
459 for (unsigned I = 0, N = Conflicts.size(); I != N; ++I) {
460 OS.indent(Indent + 2);
462 OS << Conflicts[I].Other->getFullModuleName();
464 OS.write_escaped(Conflicts[I].Message);
468 if (InferSubmodules) {
469 OS.indent(Indent + 2);
470 if (InferExplicitSubmodules)
472 OS << "module * {\n";
473 if (InferExportWildcard) {
474 OS.indent(Indent + 4);
477 OS.indent(Indent + 2);
485 LLVM_DUMP_METHOD void Module::dump() const {
489 void VisibleModuleSet::setVisible(Module *M, SourceLocation Loc,
490 VisibleCallback Vis, ConflictCallback Cb) {
491 assert(Loc.isValid() && "setVisible expects a valid import location");
499 Visiting *ExportedBy;
502 std::function<void(Visiting)> VisitModule = [&](Visiting V) {
503 // Modules that aren't available cannot be made visible.
504 if (!V.M->isAvailable())
507 // Nothing to do for a module that's already visible.
508 unsigned ID = V.M->getVisibilityID();
509 if (ImportLocs.size() <= ID)
510 ImportLocs.resize(ID + 1);
511 else if (ImportLocs[ID].isValid())
514 ImportLocs[ID] = Loc;
517 // Make any exported modules visible.
518 SmallVector<Module *, 16> Exports;
519 V.M->getExportedModules(Exports);
520 for (Module *E : Exports)
521 VisitModule({E, &V});
523 for (auto &C : V.M->Conflicts) {
524 if (isVisible(C.Other)) {
525 llvm::SmallVector<Module*, 8> Path;
526 for (Visiting *I = &V; I; I = I->ExportedBy)
527 Path.push_back(I->M);
528 Cb(Path, C.Other, C.Message);
532 VisitModule({M, nullptr});