xref: /llvm-project/clang/lib/Basic/Module.cpp (revision 779448684662c1fb97d2daec6fbf769ca2515a6d)
1 //===--- Module.cpp - Describe a module -----------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the Module class, which describes a module in the source
11 // code.
12 //
13 //===----------------------------------------------------------------------===//
14 
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"
24 
25 using namespace clang;
26 
27 Module::Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent,
28                bool IsFramework, bool IsExplicit)
29   : Name(Name), DefinitionLoc(DefinitionLoc), Parent(Parent),
30     Umbrella(), ASTFile(0), IsAvailable(true), IsFromModuleFile(false),
31     IsFramework(IsFramework), IsExplicit(IsExplicit), IsSystem(false),
32     IsExternC(false), InferSubmodules(false), InferExplicitSubmodules(false),
33     InferExportWildcard(false), ConfigMacrosExhaustive(false),
34     NameVisibility(Hidden) {
35   if (Parent) {
36     if (!Parent->isAvailable())
37       IsAvailable = false;
38     if (Parent->IsSystem)
39       IsSystem = true;
40 
41     Parent->SubModuleIndex[Name] = Parent->SubModules.size();
42     Parent->SubModules.push_back(this);
43   }
44 }
45 
46 Module::~Module() {
47   for (submodule_iterator I = submodule_begin(), IEnd = submodule_end();
48        I != IEnd; ++I) {
49     delete *I;
50   }
51 }
52 
53 /// \brief Determine whether a translation unit built using the current
54 /// language options has the given feature.
55 static bool hasFeature(StringRef Feature, const LangOptions &LangOpts,
56                        const TargetInfo &Target) {
57   return llvm::StringSwitch<bool>(Feature)
58            .Case("altivec", LangOpts.AltiVec)
59            .Case("blocks", LangOpts.Blocks)
60            .Case("cplusplus", LangOpts.CPlusPlus)
61            .Case("cplusplus11", LangOpts.CPlusPlus11)
62            .Case("objc", LangOpts.ObjC1)
63            .Case("objc_arc", LangOpts.ObjCAutoRefCount)
64            .Case("opencl", LangOpts.OpenCL)
65            .Case("tls", Target.isTLSSupported())
66            .Default(Target.hasFeature(Feature));
67 }
68 
69 bool
70 Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target,
71                     Requirement &Req, HeaderDirective &MissingHeader) const {
72   if (IsAvailable)
73     return true;
74 
75   for (const Module *Current = this; Current; Current = Current->Parent) {
76     if (!Current->MissingHeaders.empty()) {
77       MissingHeader = Current->MissingHeaders.front();
78       return false;
79     }
80     for (unsigned I = 0, N = Current->Requirements.size(); I != N; ++I) {
81       if (hasFeature(Current->Requirements[I].first, LangOpts, Target) !=
82               Current->Requirements[I].second) {
83         Req = Current->Requirements[I];
84         return false;
85       }
86     }
87   }
88 
89   llvm_unreachable("could not find a reason why module is unavailable");
90 }
91 
92 bool Module::isSubModuleOf(Module *Other) const {
93   const Module *This = this;
94   do {
95     if (This == Other)
96       return true;
97 
98     This = This->Parent;
99   } while (This);
100 
101   return false;
102 }
103 
104 const Module *Module::getTopLevelModule() const {
105   const Module *Result = this;
106   while (Result->Parent)
107     Result = Result->Parent;
108 
109   return Result;
110 }
111 
112 std::string Module::getFullModuleName() const {
113   SmallVector<StringRef, 2> Names;
114 
115   // Build up the set of module names (from innermost to outermost).
116   for (const Module *M = this; M; M = M->Parent)
117     Names.push_back(M->Name);
118 
119   std::string Result;
120   for (SmallVectorImpl<StringRef>::reverse_iterator I = Names.rbegin(),
121                                                  IEnd = Names.rend();
122        I != IEnd; ++I) {
123     if (!Result.empty())
124       Result += '.';
125 
126     Result += *I;
127   }
128 
129   return Result;
130 }
131 
132 const DirectoryEntry *Module::getUmbrellaDir() const {
133   if (const FileEntry *Header = getUmbrellaHeader())
134     return Header->getDir();
135 
136   return Umbrella.dyn_cast<const DirectoryEntry *>();
137 }
138 
139 ArrayRef<const FileEntry *> Module::getTopHeaders(FileManager &FileMgr) {
140   if (!TopHeaderNames.empty()) {
141     for (std::vector<std::string>::iterator
142            I = TopHeaderNames.begin(), E = TopHeaderNames.end(); I != E; ++I) {
143       if (const FileEntry *FE = FileMgr.getFile(*I))
144         TopHeaders.insert(FE);
145     }
146     TopHeaderNames.clear();
147   }
148 
149   return llvm::makeArrayRef(TopHeaders.begin(), TopHeaders.end());
150 }
151 
152 void Module::addRequirement(StringRef Feature, bool RequiredState,
153                             const LangOptions &LangOpts,
154                             const TargetInfo &Target) {
155   Requirements.push_back(Requirement(Feature, RequiredState));
156 
157   // If this feature is currently available, we're done.
158   if (hasFeature(Feature, LangOpts, Target) == RequiredState)
159     return;
160 
161   if (!IsAvailable)
162     return;
163 
164   SmallVector<Module *, 2> Stack;
165   Stack.push_back(this);
166   while (!Stack.empty()) {
167     Module *Current = Stack.back();
168     Stack.pop_back();
169 
170     if (!Current->IsAvailable)
171       continue;
172 
173     Current->IsAvailable = false;
174     for (submodule_iterator Sub = Current->submodule_begin(),
175                          SubEnd = Current->submodule_end();
176          Sub != SubEnd; ++Sub) {
177       if ((*Sub)->IsAvailable)
178         Stack.push_back(*Sub);
179     }
180   }
181 }
182 
183 Module *Module::findSubmodule(StringRef Name) const {
184   llvm::StringMap<unsigned>::const_iterator Pos = SubModuleIndex.find(Name);
185   if (Pos == SubModuleIndex.end())
186     return 0;
187 
188   return SubModules[Pos->getValue()];
189 }
190 
191 static void printModuleId(raw_ostream &OS, const ModuleId &Id) {
192   for (unsigned I = 0, N = Id.size(); I != N; ++I) {
193     if (I)
194       OS << ".";
195     OS << Id[I].first;
196   }
197 }
198 
199 void Module::getExportedModules(SmallVectorImpl<Module *> &Exported) const {
200   // All non-explicit submodules are exported.
201   for (std::vector<Module *>::const_iterator I = SubModules.begin(),
202                                              E = SubModules.end();
203        I != E; ++I) {
204     Module *Mod = *I;
205     if (!Mod->IsExplicit)
206       Exported.push_back(Mod);
207   }
208 
209   // Find re-exported modules by filtering the list of imported modules.
210   bool AnyWildcard = false;
211   bool UnrestrictedWildcard = false;
212   SmallVector<Module *, 4> WildcardRestrictions;
213   for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
214     Module *Mod = Exports[I].getPointer();
215     if (!Exports[I].getInt()) {
216       // Export a named module directly; no wildcards involved.
217       Exported.push_back(Mod);
218 
219       continue;
220     }
221 
222     // Wildcard export: export all of the imported modules that match
223     // the given pattern.
224     AnyWildcard = true;
225     if (UnrestrictedWildcard)
226       continue;
227 
228     if (Module *Restriction = Exports[I].getPointer())
229       WildcardRestrictions.push_back(Restriction);
230     else {
231       WildcardRestrictions.clear();
232       UnrestrictedWildcard = true;
233     }
234   }
235 
236   // If there were any wildcards, push any imported modules that were
237   // re-exported by the wildcard restriction.
238   if (!AnyWildcard)
239     return;
240 
241   for (unsigned I = 0, N = Imports.size(); I != N; ++I) {
242     Module *Mod = Imports[I];
243     bool Acceptable = UnrestrictedWildcard;
244     if (!Acceptable) {
245       // Check whether this module meets one of the restrictions.
246       for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
247         Module *Restriction = WildcardRestrictions[R];
248         if (Mod == Restriction || Mod->isSubModuleOf(Restriction)) {
249           Acceptable = true;
250           break;
251         }
252       }
253     }
254 
255     if (!Acceptable)
256       continue;
257 
258     Exported.push_back(Mod);
259   }
260 }
261 
262 void Module::buildVisibleModulesCache() const {
263   assert(VisibleModulesCache.empty() && "cache does not need building");
264 
265   // This module is visible to itself.
266   VisibleModulesCache.insert(this);
267 
268   // Every imported module is visible.
269   SmallVector<Module *, 16> Stack(Imports.begin(), Imports.end());
270   while (!Stack.empty()) {
271     Module *CurrModule = Stack.pop_back_val();
272 
273     // Every module transitively exported by an imported module is visible.
274     if (VisibleModulesCache.insert(CurrModule).second)
275       CurrModule->getExportedModules(Stack);
276   }
277 }
278 
279 void Module::print(raw_ostream &OS, unsigned Indent) const {
280   OS.indent(Indent);
281   if (IsFramework)
282     OS << "framework ";
283   if (IsExplicit)
284     OS << "explicit ";
285   OS << "module " << Name;
286 
287   if (IsSystem) {
288     OS.indent(Indent + 2);
289     OS << " [system]";
290   }
291 
292   OS << " {\n";
293 
294   if (!Requirements.empty()) {
295     OS.indent(Indent + 2);
296     OS << "requires ";
297     for (unsigned I = 0, N = Requirements.size(); I != N; ++I) {
298       if (I)
299         OS << ", ";
300       if (!Requirements[I].second)
301         OS << "!";
302       OS << Requirements[I].first;
303     }
304     OS << "\n";
305   }
306 
307   if (const FileEntry *UmbrellaHeader = getUmbrellaHeader()) {
308     OS.indent(Indent + 2);
309     OS << "umbrella header \"";
310     OS.write_escaped(UmbrellaHeader->getName());
311     OS << "\"\n";
312   } else if (const DirectoryEntry *UmbrellaDir = getUmbrellaDir()) {
313     OS.indent(Indent + 2);
314     OS << "umbrella \"";
315     OS.write_escaped(UmbrellaDir->getName());
316     OS << "\"\n";
317   }
318 
319   if (!ConfigMacros.empty() || ConfigMacrosExhaustive) {
320     OS.indent(Indent + 2);
321     OS << "config_macros ";
322     if (ConfigMacrosExhaustive)
323       OS << "[exhaustive]";
324     for (unsigned I = 0, N = ConfigMacros.size(); I != N; ++I) {
325       if (I)
326         OS << ", ";
327       OS << ConfigMacros[I];
328     }
329     OS << "\n";
330   }
331 
332   for (unsigned I = 0, N = NormalHeaders.size(); I != N; ++I) {
333     OS.indent(Indent + 2);
334     OS << "header \"";
335     OS.write_escaped(NormalHeaders[I]->getName());
336     OS << "\"\n";
337   }
338 
339   for (unsigned I = 0, N = ExcludedHeaders.size(); I != N; ++I) {
340     OS.indent(Indent + 2);
341     OS << "exclude header \"";
342     OS.write_escaped(ExcludedHeaders[I]->getName());
343     OS << "\"\n";
344   }
345 
346   for (unsigned I = 0, N = PrivateHeaders.size(); I != N; ++I) {
347     OS.indent(Indent + 2);
348     OS << "private header \"";
349     OS.write_escaped(PrivateHeaders[I]->getName());
350     OS << "\"\n";
351   }
352 
353   for (submodule_const_iterator MI = submodule_begin(), MIEnd = submodule_end();
354        MI != MIEnd; ++MI)
355     (*MI)->print(OS, Indent + 2);
356 
357   for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
358     OS.indent(Indent + 2);
359     OS << "export ";
360     if (Module *Restriction = Exports[I].getPointer()) {
361       OS << Restriction->getFullModuleName();
362       if (Exports[I].getInt())
363         OS << ".*";
364     } else {
365       OS << "*";
366     }
367     OS << "\n";
368   }
369 
370   for (unsigned I = 0, N = UnresolvedExports.size(); I != N; ++I) {
371     OS.indent(Indent + 2);
372     OS << "export ";
373     printModuleId(OS, UnresolvedExports[I].Id);
374     if (UnresolvedExports[I].Wildcard) {
375       if (UnresolvedExports[I].Id.empty())
376         OS << "*";
377       else
378         OS << ".*";
379     }
380     OS << "\n";
381   }
382 
383   for (unsigned I = 0, N = DirectUses.size(); I != N; ++I) {
384     OS.indent(Indent + 2);
385     OS << "use ";
386     OS << DirectUses[I]->getFullModuleName();
387     OS << "\n";
388   }
389 
390   for (unsigned I = 0, N = UnresolvedDirectUses.size(); I != N; ++I) {
391     OS.indent(Indent + 2);
392     OS << "use ";
393     printModuleId(OS, UnresolvedDirectUses[I]);
394     OS << "\n";
395   }
396 
397   for (unsigned I = 0, N = LinkLibraries.size(); I != N; ++I) {
398     OS.indent(Indent + 2);
399     OS << "link ";
400     if (LinkLibraries[I].IsFramework)
401       OS << "framework ";
402     OS << "\"";
403     OS.write_escaped(LinkLibraries[I].Library);
404     OS << "\"";
405   }
406 
407   for (unsigned I = 0, N = UnresolvedConflicts.size(); I != N; ++I) {
408     OS.indent(Indent + 2);
409     OS << "conflict ";
410     printModuleId(OS, UnresolvedConflicts[I].Id);
411     OS << ", \"";
412     OS.write_escaped(UnresolvedConflicts[I].Message);
413     OS << "\"\n";
414   }
415 
416   for (unsigned I = 0, N = Conflicts.size(); I != N; ++I) {
417     OS.indent(Indent + 2);
418     OS << "conflict ";
419     OS << Conflicts[I].Other->getFullModuleName();
420     OS << ", \"";
421     OS.write_escaped(Conflicts[I].Message);
422     OS << "\"\n";
423   }
424 
425   if (InferSubmodules) {
426     OS.indent(Indent + 2);
427     if (InferExplicitSubmodules)
428       OS << "explicit ";
429     OS << "module * {\n";
430     if (InferExportWildcard) {
431       OS.indent(Indent + 4);
432       OS << "export *\n";
433     }
434     OS.indent(Indent + 2);
435     OS << "}\n";
436   }
437 
438   OS.indent(Indent);
439   OS << "}\n";
440 }
441 
442 void Module::dump() const {
443   print(llvm::errs());
444 }
445 
446 
447