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
Module(StringRef Name,SourceLocation DefinitionLoc,Module * Parent,bool IsFramework,bool IsExplicit,unsigned VisibilityID)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) {
37 if (Parent) {
38 if (!Parent->isAvailable())
39 IsAvailable = false;
40 if (Parent->IsSystem)
41 IsSystem = true;
42 if (Parent->IsExternC)
43 IsExternC = true;
44 IsMissingRequirement = Parent->IsMissingRequirement;
45
46 Parent->SubModuleIndex[Name] = Parent->SubModules.size();
47 Parent->SubModules.push_back(this);
48 }
49 }
50
~Module()51 Module::~Module() {
52 for (submodule_iterator I = submodule_begin(), IEnd = submodule_end();
53 I != IEnd; ++I) {
54 delete *I;
55 }
56 }
57
58 /// \brief Determine whether a translation unit built using the current
59 /// language options has the given feature.
hasFeature(StringRef Feature,const LangOptions & LangOpts,const TargetInfo & Target)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));
73 if (!HasFeature)
74 HasFeature = std::find(LangOpts.ModuleFeatures.begin(),
75 LangOpts.ModuleFeatures.end(),
76 Feature) != LangOpts.ModuleFeatures.end();
77 return HasFeature;
78 }
79
isAvailable(const LangOptions & LangOpts,const TargetInfo & Target,Requirement & Req,UnresolvedHeaderDirective & MissingHeader) const80 bool Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target,
81 Requirement &Req,
82 UnresolvedHeaderDirective &MissingHeader) const {
83 if (IsAvailable)
84 return true;
85
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];
91 return false;
92 }
93 }
94 if (!Current->MissingHeaders.empty()) {
95 MissingHeader = Current->MissingHeaders.front();
96 return false;
97 }
98 }
99
100 llvm_unreachable("could not find a reason why module is unavailable");
101 }
102
isSubModuleOf(const Module * Other) const103 bool Module::isSubModuleOf(const Module *Other) const {
104 const Module *This = this;
105 do {
106 if (This == Other)
107 return true;
108
109 This = This->Parent;
110 } while (This);
111
112 return false;
113 }
114
getTopLevelModule() const115 const Module *Module::getTopLevelModule() const {
116 const Module *Result = this;
117 while (Result->Parent)
118 Result = Result->Parent;
119
120 return Result;
121 }
122
getFullModuleName() const123 std::string Module::getFullModuleName() const {
124 SmallVector<StringRef, 2> Names;
125
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);
129
130 std::string Result;
131 for (SmallVectorImpl<StringRef>::reverse_iterator I = Names.rbegin(),
132 IEnd = Names.rend();
133 I != IEnd; ++I) {
134 if (!Result.empty())
135 Result += '.';
136
137 Result += *I;
138 }
139
140 return Result;
141 }
142
fullModuleNameIs(ArrayRef<StringRef> nameParts) const143 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())
146 return false;
147 nameParts = nameParts.drop_back();
148 }
149 return nameParts.empty();
150 }
151
getUmbrellaDir() const152 Module::DirectoryName Module::getUmbrellaDir() const {
153 if (Header U = getUmbrellaHeader())
154 return {"", U.Entry->getDir()};
155
156 return {UmbrellaAsWritten, Umbrella.dyn_cast<const DirectoryEntry *>()};
157 }
158
getTopHeaders(FileManager & FileMgr)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);
165 }
166 TopHeaderNames.clear();
167 }
168
169 return llvm::makeArrayRef(TopHeaders.begin(), TopHeaders.end());
170 }
171
directlyUses(const Module * Requested) const172 bool Module::directlyUses(const Module *Requested) const {
173 auto *Top = getTopLevelModule();
174
175 // A top-level module implicitly uses itself.
176 if (Requested->isSubModuleOf(Top))
177 return true;
178
179 for (auto *Use : Top->DirectUses)
180 if (Requested->isSubModuleOf(Use))
181 return true;
182 return false;
183 }
184
addRequirement(StringRef Feature,bool RequiredState,const LangOptions & LangOpts,const TargetInfo & Target)185 void Module::addRequirement(StringRef Feature, bool RequiredState,
186 const LangOptions &LangOpts,
187 const TargetInfo &Target) {
188 Requirements.push_back(Requirement(Feature, RequiredState));
189
190 // If this feature is currently available, we're done.
191 if (hasFeature(Feature, LangOpts, Target) == RequiredState)
192 return;
193
194 markUnavailable(/*MissingRequirement*/true);
195 }
196
markUnavailable(bool MissingRequirement)197 void Module::markUnavailable(bool MissingRequirement) {
198 auto needUpdate = [MissingRequirement](Module *M) {
199 return M->IsAvailable || (!M->IsMissingRequirement && MissingRequirement);
200 };
201
202 if (!needUpdate(this))
203 return;
204
205 SmallVector<Module *, 2> Stack;
206 Stack.push_back(this);
207 while (!Stack.empty()) {
208 Module *Current = Stack.back();
209 Stack.pop_back();
210
211 if (!needUpdate(Current))
212 continue;
213
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);
221 }
222 }
223 }
224
findSubmodule(StringRef Name) const225 Module *Module::findSubmodule(StringRef Name) const {
226 llvm::StringMap<unsigned>::const_iterator Pos = SubModuleIndex.find(Name);
227 if (Pos == SubModuleIndex.end())
228 return nullptr;
229
230 return SubModules[Pos->getValue()];
231 }
232
printModuleId(raw_ostream & OS,const ModuleId & Id)233 static void printModuleId(raw_ostream &OS, const ModuleId &Id) {
234 for (unsigned I = 0, N = Id.size(); I != N; ++I) {
235 if (I)
236 OS << ".";
237 OS << Id[I].first;
238 }
239 }
240
getExportedModules(SmallVectorImpl<Module * > & Exported) const241 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();
245 I != E; ++I) {
246 Module *Mod = *I;
247 if (!Mod->IsExplicit)
248 Exported.push_back(Mod);
249 }
250
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);
260
261 continue;
262 }
263
264 // Wildcard export: export all of the imported modules that match
265 // the given pattern.
266 AnyWildcard = true;
267 if (UnrestrictedWildcard)
268 continue;
269
270 if (Module *Restriction = Exports[I].getPointer())
271 WildcardRestrictions.push_back(Restriction);
272 else {
273 WildcardRestrictions.clear();
274 UnrestrictedWildcard = true;
275 }
276 }
277
278 // If there were any wildcards, push any imported modules that were
279 // re-exported by the wildcard restriction.
280 if (!AnyWildcard)
281 return;
282
283 for (unsigned I = 0, N = Imports.size(); I != N; ++I) {
284 Module *Mod = Imports[I];
285 bool Acceptable = UnrestrictedWildcard;
286 if (!Acceptable) {
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)) {
291 Acceptable = true;
292 break;
293 }
294 }
295 }
296
297 if (!Acceptable)
298 continue;
299
300 Exported.push_back(Mod);
301 }
302 }
303
buildVisibleModulesCache() const304 void Module::buildVisibleModulesCache() const {
305 assert(VisibleModulesCache.empty() && "cache does not need building");
306
307 // This module is visible to itself.
308 VisibleModulesCache.insert(this);
309
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();
314
315 // Every module transitively exported by an imported module is visible.
316 if (VisibleModulesCache.insert(CurrModule).second)
317 CurrModule->getExportedModules(Stack);
318 }
319 }
320
print(raw_ostream & OS,unsigned Indent) const321 void Module::print(raw_ostream &OS, unsigned Indent) const {
322 OS.indent(Indent);
323 if (IsFramework)
324 OS << "framework ";
325 if (IsExplicit)
326 OS << "explicit ";
327 OS << "module " << Name;
328
329 if (IsSystem || IsExternC) {
330 OS.indent(Indent + 2);
331 if (IsSystem)
332 OS << " [system]";
333 if (IsExternC)
334 OS << " [extern_c]";
335 }
336
337 OS << " {\n";
338
339 if (!Requirements.empty()) {
340 OS.indent(Indent + 2);
341 OS << "requires ";
342 for (unsigned I = 0, N = Requirements.size(); I != N; ++I) {
343 if (I)
344 OS << ", ";
345 if (!Requirements[I].second)
346 OS << "!";
347 OS << Requirements[I].first;
348 }
349 OS << "\n";
350 }
351
352 if (Header H = getUmbrellaHeader()) {
353 OS.indent(Indent + 2);
354 OS << "umbrella header \"";
355 OS.write_escaped(H.NameAsWritten);
356 OS << "\"\n";
357 } else if (DirectoryName D = getUmbrellaDir()) {
358 OS.indent(Indent + 2);
359 OS << "umbrella \"";
360 OS.write_escaped(D.NameAsWritten);
361 OS << "\"\n";
362 }
363
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) {
370 if (I)
371 OS << ", ";
372 OS << ConfigMacros[I];
373 }
374 OS << "\n";
375 }
376
377 struct {
378 StringRef Prefix;
379 HeaderKind Kind;
380 } Kinds[] = {{"", HK_Normal},
381 {"textual ", HK_Textual},
382 {"private ", HK_Private},
383 {"private textual ", HK_PrivateTextual},
384 {"exclude ", HK_Excluded}};
385
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);
391 OS << "\"\n";
392 }
393 }
394
395 for (submodule_const_iterator MI = submodule_begin(), MIEnd = submodule_end();
396 MI != MIEnd; ++MI)
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);
403
404 for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
405 OS.indent(Indent + 2);
406 OS << "export ";
407 if (Module *Restriction = Exports[I].getPointer()) {
408 OS << Restriction->getFullModuleName();
409 if (Exports[I].getInt())
410 OS << ".*";
411 } else {
412 OS << "*";
413 }
414 OS << "\n";
415 }
416
417 for (unsigned I = 0, N = UnresolvedExports.size(); I != N; ++I) {
418 OS.indent(Indent + 2);
419 OS << "export ";
420 printModuleId(OS, UnresolvedExports[I].Id);
421 if (UnresolvedExports[I].Wildcard) {
422 if (UnresolvedExports[I].Id.empty())
423 OS << "*";
424 else
425 OS << ".*";
426 }
427 OS << "\n";
428 }
429
430 for (unsigned I = 0, N = DirectUses.size(); I != N; ++I) {
431 OS.indent(Indent + 2);
432 OS << "use ";
433 OS << DirectUses[I]->getFullModuleName();
434 OS << "\n";
435 }
436
437 for (unsigned I = 0, N = UnresolvedDirectUses.size(); I != N; ++I) {
438 OS.indent(Indent + 2);
439 OS << "use ";
440 printModuleId(OS, UnresolvedDirectUses[I]);
441 OS << "\n";
442 }
443
444 for (unsigned I = 0, N = LinkLibraries.size(); I != N; ++I) {
445 OS.indent(Indent + 2);
446 OS << "link ";
447 if (LinkLibraries[I].IsFramework)
448 OS << "framework ";
449 OS << "\"";
450 OS.write_escaped(LinkLibraries[I].Library);
451 OS << "\"";
452 }
453
454 for (unsigned I = 0, N = UnresolvedConflicts.size(); I != N; ++I) {
455 OS.indent(Indent + 2);
456 OS << "conflict ";
457 printModuleId(OS, UnresolvedConflicts[I].Id);
458 OS << ", \"";
459 OS.write_escaped(UnresolvedConflicts[I].Message);
460 OS << "\"\n";
461 }
462
463 for (unsigned I = 0, N = Conflicts.size(); I != N; ++I) {
464 OS.indent(Indent + 2);
465 OS << "conflict ";
466 OS << Conflicts[I].Other->getFullModuleName();
467 OS << ", \"";
468 OS.write_escaped(Conflicts[I].Message);
469 OS << "\"\n";
470 }
471
472 if (InferSubmodules) {
473 OS.indent(Indent + 2);
474 if (InferExplicitSubmodules)
475 OS << "explicit ";
476 OS << "module * {\n";
477 if (InferExportWildcard) {
478 OS.indent(Indent + 4);
479 OS << "export *\n";
480 }
481 OS.indent(Indent + 2);
482 OS << "}\n";
483 }
484
485 OS.indent(Indent);
486 OS << "}\n";
487 }
488
dump() const489 void Module::dump() const {
490 print(llvm::errs());
491 }
492
setVisible(Module * M,SourceLocation Loc,VisibleCallback Vis,ConflictCallback Cb)493 void VisibleModuleSet::setVisible(Module *M, SourceLocation Loc,
494 VisibleCallback Vis, ConflictCallback Cb) {
495 if (isVisible(M))
496 return;
497
498 ++Generation;
499
500 struct Visiting {
501 Module *M;
502 Visiting *ExportedBy;
503 };
504
505 std::function<void(Visiting)> VisitModule = [&](Visiting V) {
506 // Modules that aren't available cannot be made visible.
507 if (!V.M->isAvailable())
508 return;
509
510 // Nothing to do for a module that's already visible.
511 unsigned ID = V.M->getVisibilityID();
512 if (ImportLocs.size() <= ID)
513 ImportLocs.resize(ID + 1);
514 else if (ImportLocs[ID].isValid())
515 return;
516
517 ImportLocs[ID] = Loc;
518 Vis(M);
519
520 // Make any exported modules visible.
521 SmallVector<Module *, 16> Exports;
522 V.M->getExportedModules(Exports);
523 for (Module *E : Exports)
524 VisitModule({E, &V});
525
526 for (auto &C : V.M->Conflicts) {
527 if (isVisible(C.Other)) {
528 llvm::SmallVector<Module*, 8> Path;
529 for (Visiting *I = &V; I; I = I->ExportedBy)
530 Path.push_back(I->M);
531 Cb(Path, C.Other, C.Message);
532 }
533 }
534 };
535 VisitModule({M, nullptr});
536 }
537