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), IsAvailable(true), IsFromModuleFile(false),
32 IsFramework(IsFramework), IsExplicit(IsExplicit), IsSystem(false),
33 IsExternC(false), IsInferred(false), InferSubmodules(false),
34 InferExplicitSubmodules(false), InferExportWildcard(false),
35 ConfigMacrosExhaustive(false), NameVisibility(Hidden) {
37 if (!Parent->isAvailable())
41 if (Parent->IsExternC)
43 IsMissingRequirement = Parent->IsMissingRequirement;
45 Parent->SubModuleIndex[Name] = Parent->SubModules.size();
46 Parent->SubModules.push_back(this);
51 for (submodule_iterator I = submodule_begin(), IEnd = submodule_end();
57 /// \brief Determine whether a translation unit built using the current
58 /// language options has the given feature.
59 static bool hasFeature(StringRef Feature, const LangOptions &LangOpts,
60 const TargetInfo &Target) {
61 bool HasFeature = llvm::StringSwitch<bool>(Feature)
62 .Case("altivec", LangOpts.AltiVec)
63 .Case("blocks", LangOpts.Blocks)
64 .Case("cplusplus", LangOpts.CPlusPlus)
65 .Case("cplusplus11", LangOpts.CPlusPlus11)
66 .Case("objc", LangOpts.ObjC1)
67 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
68 .Case("opencl", LangOpts.OpenCL)
69 .Case("tls", Target.isTLSSupported())
70 .Case("zvector", LangOpts.ZVector)
71 .Default(Target.hasFeature(Feature));
73 HasFeature = std::find(LangOpts.ModuleFeatures.begin(),
74 LangOpts.ModuleFeatures.end(),
75 Feature) != LangOpts.ModuleFeatures.end();
79 bool Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target,
81 UnresolvedHeaderDirective &MissingHeader) const {
85 for (const Module *Current = this; Current; Current = Current->Parent) {
86 for (unsigned I = 0, N = Current->Requirements.size(); I != N; ++I) {
87 if (hasFeature(Current->Requirements[I].first, LangOpts, Target) !=
88 Current->Requirements[I].second) {
89 Req = Current->Requirements[I];
93 if (!Current->MissingHeaders.empty()) {
94 MissingHeader = Current->MissingHeaders.front();
99 llvm_unreachable("could not find a reason why module is unavailable");
102 bool Module::isSubModuleOf(const Module *Other) const {
103 const Module *This = this;
114 const Module *Module::getTopLevelModule() const {
115 const Module *Result = this;
116 while (Result->Parent)
117 Result = Result->Parent;
122 std::string Module::getFullModuleName() const {
123 SmallVector<StringRef, 2> Names;
125 // Build up the set of module names (from innermost to outermost).
126 for (const Module *M = this; M; M = M->Parent)
127 Names.push_back(M->Name);
130 for (SmallVectorImpl<StringRef>::reverse_iterator I = Names.rbegin(),
142 Module::DirectoryName Module::getUmbrellaDir() const {
143 if (Header U = getUmbrellaHeader())
144 return {"", U.Entry->getDir()};
146 return {UmbrellaAsWritten, Umbrella.dyn_cast<const DirectoryEntry *>()};
149 ArrayRef<const FileEntry *> Module::getTopHeaders(FileManager &FileMgr) {
150 if (!TopHeaderNames.empty()) {
151 for (std::vector<std::string>::iterator
152 I = TopHeaderNames.begin(), E = TopHeaderNames.end(); I != E; ++I) {
153 if (const FileEntry *FE = FileMgr.getFile(*I))
154 TopHeaders.insert(FE);
156 TopHeaderNames.clear();
159 return llvm::makeArrayRef(TopHeaders.begin(), TopHeaders.end());
162 bool Module::directlyUses(const Module *Requested) const {
163 auto *Top = getTopLevelModule();
165 // A top-level module implicitly uses itself.
166 if (Requested->isSubModuleOf(Top))
169 for (auto *Use : Top->DirectUses)
170 if (Requested->isSubModuleOf(Use))
175 void Module::addRequirement(StringRef Feature, bool RequiredState,
176 const LangOptions &LangOpts,
177 const TargetInfo &Target) {
178 Requirements.push_back(Requirement(Feature, RequiredState));
180 // If this feature is currently available, we're done.
181 if (hasFeature(Feature, LangOpts, Target) == RequiredState)
184 markUnavailable(/*MissingRequirement*/true);
187 void Module::markUnavailable(bool MissingRequirement) {
188 auto needUpdate = [MissingRequirement](Module *M) {
189 return M->IsAvailable || (!M->IsMissingRequirement && MissingRequirement);
192 if (!needUpdate(this))
195 SmallVector<Module *, 2> Stack;
196 Stack.push_back(this);
197 while (!Stack.empty()) {
198 Module *Current = Stack.back();
201 if (!needUpdate(Current))
204 Current->IsAvailable = false;
205 Current->IsMissingRequirement |= MissingRequirement;
206 for (submodule_iterator Sub = Current->submodule_begin(),
207 SubEnd = Current->submodule_end();
208 Sub != SubEnd; ++Sub) {
209 if (needUpdate(*Sub))
210 Stack.push_back(*Sub);
215 Module *Module::findSubmodule(StringRef Name) const {
216 llvm::StringMap<unsigned>::const_iterator Pos = SubModuleIndex.find(Name);
217 if (Pos == SubModuleIndex.end())
220 return SubModules[Pos->getValue()];
223 static void printModuleId(raw_ostream &OS, const ModuleId &Id) {
224 for (unsigned I = 0, N = Id.size(); I != N; ++I) {
231 void Module::getExportedModules(SmallVectorImpl<Module *> &Exported) const {
232 // All non-explicit submodules are exported.
233 for (std::vector<Module *>::const_iterator I = SubModules.begin(),
234 E = SubModules.end();
237 if (!Mod->IsExplicit)
238 Exported.push_back(Mod);
241 // Find re-exported modules by filtering the list of imported modules.
242 bool AnyWildcard = false;
243 bool UnrestrictedWildcard = false;
244 SmallVector<Module *, 4> WildcardRestrictions;
245 for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
246 Module *Mod = Exports[I].getPointer();
247 if (!Exports[I].getInt()) {
248 // Export a named module directly; no wildcards involved.
249 Exported.push_back(Mod);
254 // Wildcard export: export all of the imported modules that match
255 // the given pattern.
257 if (UnrestrictedWildcard)
260 if (Module *Restriction = Exports[I].getPointer())
261 WildcardRestrictions.push_back(Restriction);
263 WildcardRestrictions.clear();
264 UnrestrictedWildcard = true;
268 // If there were any wildcards, push any imported modules that were
269 // re-exported by the wildcard restriction.
273 for (unsigned I = 0, N = Imports.size(); I != N; ++I) {
274 Module *Mod = Imports[I];
275 bool Acceptable = UnrestrictedWildcard;
277 // Check whether this module meets one of the restrictions.
278 for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
279 Module *Restriction = WildcardRestrictions[R];
280 if (Mod == Restriction || Mod->isSubModuleOf(Restriction)) {
290 Exported.push_back(Mod);
294 void Module::buildVisibleModulesCache() const {
295 assert(VisibleModulesCache.empty() && "cache does not need building");
297 // This module is visible to itself.
298 VisibleModulesCache.insert(this);
300 // Every imported module is visible.
301 SmallVector<Module *, 16> Stack(Imports.begin(), Imports.end());
302 while (!Stack.empty()) {
303 Module *CurrModule = Stack.pop_back_val();
305 // Every module transitively exported by an imported module is visible.
306 if (VisibleModulesCache.insert(CurrModule).second)
307 CurrModule->getExportedModules(Stack);
311 void Module::print(raw_ostream &OS, unsigned Indent) const {
317 OS << "module " << Name;
319 if (IsSystem || IsExternC) {
320 OS.indent(Indent + 2);
329 if (!Requirements.empty()) {
330 OS.indent(Indent + 2);
332 for (unsigned I = 0, N = Requirements.size(); I != N; ++I) {
335 if (!Requirements[I].second)
337 OS << Requirements[I].first;
342 if (Header H = getUmbrellaHeader()) {
343 OS.indent(Indent + 2);
344 OS << "umbrella header \"";
345 OS.write_escaped(H.NameAsWritten);
347 } else if (DirectoryName D = getUmbrellaDir()) {
348 OS.indent(Indent + 2);
350 OS.write_escaped(D.NameAsWritten);
354 if (!ConfigMacros.empty() || ConfigMacrosExhaustive) {
355 OS.indent(Indent + 2);
356 OS << "config_macros ";
357 if (ConfigMacrosExhaustive)
358 OS << "[exhaustive]";
359 for (unsigned I = 0, N = ConfigMacros.size(); I != N; ++I) {
362 OS << ConfigMacros[I];
370 } Kinds[] = {{"", HK_Normal},
371 {"textual ", HK_Textual},
372 {"private ", HK_Private},
373 {"private textual ", HK_PrivateTextual},
374 {"exclude ", HK_Excluded}};
376 for (auto &K : Kinds) {
377 for (auto &H : Headers[K.Kind]) {
378 OS.indent(Indent + 2);
379 OS << K.Prefix << "header \"";
380 OS.write_escaped(H.NameAsWritten);
385 for (submodule_const_iterator MI = submodule_begin(), MIEnd = submodule_end();
387 // Print inferred subframework modules so that we don't need to re-infer
388 // them (requires expensive directory iteration + stat calls) when we build
389 // the module. Regular inferred submodules are OK, as we need to look at all
390 // those header files anyway.
391 if (!(*MI)->IsInferred || (*MI)->IsFramework)
392 (*MI)->print(OS, Indent + 2);
394 for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
395 OS.indent(Indent + 2);
397 if (Module *Restriction = Exports[I].getPointer()) {
398 OS << Restriction->getFullModuleName();
399 if (Exports[I].getInt())
407 for (unsigned I = 0, N = UnresolvedExports.size(); I != N; ++I) {
408 OS.indent(Indent + 2);
410 printModuleId(OS, UnresolvedExports[I].Id);
411 if (UnresolvedExports[I].Wildcard) {
412 if (UnresolvedExports[I].Id.empty())
420 for (unsigned I = 0, N = DirectUses.size(); I != N; ++I) {
421 OS.indent(Indent + 2);
423 OS << DirectUses[I]->getFullModuleName();
427 for (unsigned I = 0, N = UnresolvedDirectUses.size(); I != N; ++I) {
428 OS.indent(Indent + 2);
430 printModuleId(OS, UnresolvedDirectUses[I]);
434 for (unsigned I = 0, N = LinkLibraries.size(); I != N; ++I) {
435 OS.indent(Indent + 2);
437 if (LinkLibraries[I].IsFramework)
440 OS.write_escaped(LinkLibraries[I].Library);
444 for (unsigned I = 0, N = UnresolvedConflicts.size(); I != N; ++I) {
445 OS.indent(Indent + 2);
447 printModuleId(OS, UnresolvedConflicts[I].Id);
449 OS.write_escaped(UnresolvedConflicts[I].Message);
453 for (unsigned I = 0, N = Conflicts.size(); I != N; ++I) {
454 OS.indent(Indent + 2);
456 OS << Conflicts[I].Other->getFullModuleName();
458 OS.write_escaped(Conflicts[I].Message);
462 if (InferSubmodules) {
463 OS.indent(Indent + 2);
464 if (InferExplicitSubmodules)
466 OS << "module * {\n";
467 if (InferExportWildcard) {
468 OS.indent(Indent + 4);
471 OS.indent(Indent + 2);
479 void Module::dump() const {
483 void VisibleModuleSet::setVisible(Module *M, SourceLocation Loc,
484 VisibleCallback Vis, ConflictCallback Cb) {
492 Visiting *ExportedBy;
495 std::function<void(Visiting)> VisitModule = [&](Visiting V) {
496 // Modules that aren't available cannot be made visible.
497 if (!V.M->isAvailable())
500 // Nothing to do for a module that's already visible.
501 unsigned ID = V.M->getVisibilityID();
502 if (ImportLocs.size() <= ID)
503 ImportLocs.resize(ID + 1);
504 else if (ImportLocs[ID].isValid())
507 ImportLocs[ID] = Loc;
510 // Make any exported modules visible.
511 SmallVector<Module *, 16> Exports;
512 V.M->getExportedModules(Exports);
513 for (Module *E : Exports)
514 VisitModule({E, &V});
516 for (auto &C : V.M->Conflicts) {
517 if (isVisible(C.Other)) {
518 llvm::SmallVector<Module*, 8> Path;
519 for (Visiting *I = &V; I; I = I->ExportedBy)
520 Path.push_back(I->M);
521 Cb(Path, C.Other, C.Message);
525 VisitModule({M, nullptr});