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