]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Basic/Module.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304659, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Basic / Module.cpp
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, unsigned VisibilityID)
29     : Name(Name), DefinitionLoc(DefinitionLoc), Parent(Parent), Directory(),
30       Umbrella(), 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       NoUndeclaredIncludes(false), 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     if (Parent->NoUndeclaredIncludes)
45       NoUndeclaredIncludes = true;
46     IsMissingRequirement = Parent->IsMissingRequirement;
47     
48     Parent->SubModuleIndex[Name] = Parent->SubModules.size();
49     Parent->SubModules.push_back(this);
50   }
51 }
52
53 Module::~Module() {
54   for (submodule_iterator I = submodule_begin(), IEnd = submodule_end();
55        I != IEnd; ++I) {
56     delete *I;
57   }
58 }
59
60 /// \brief Determine whether a translation unit built using the current
61 /// language options has the given feature.
62 static bool hasFeature(StringRef Feature, const LangOptions &LangOpts,
63                        const TargetInfo &Target) {
64   bool HasFeature = llvm::StringSwitch<bool>(Feature)
65                         .Case("altivec", LangOpts.AltiVec)
66                         .Case("blocks", LangOpts.Blocks)
67                         .Case("coroutines", LangOpts.CoroutinesTS)
68                         .Case("cplusplus", LangOpts.CPlusPlus)
69                         .Case("cplusplus11", LangOpts.CPlusPlus11)
70                         .Case("freestanding", LangOpts.Freestanding)
71                         .Case("gnuinlineasm", LangOpts.GNUAsm)
72                         .Case("objc", LangOpts.ObjC1)
73                         .Case("objc_arc", LangOpts.ObjCAutoRefCount)
74                         .Case("opencl", LangOpts.OpenCL)
75                         .Case("tls", Target.isTLSSupported())
76                         .Case("zvector", LangOpts.ZVector)
77                         .Default(Target.hasFeature(Feature));
78   if (!HasFeature)
79     HasFeature = std::find(LangOpts.ModuleFeatures.begin(),
80                            LangOpts.ModuleFeatures.end(),
81                            Feature) != LangOpts.ModuleFeatures.end();
82   return HasFeature;
83 }
84
85 bool Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target,
86                          Requirement &Req,
87                          UnresolvedHeaderDirective &MissingHeader) const {
88   if (IsAvailable)
89     return true;
90
91   for (const Module *Current = this; Current; Current = Current->Parent) {
92     for (unsigned I = 0, N = Current->Requirements.size(); I != N; ++I) {
93       if (hasFeature(Current->Requirements[I].first, LangOpts, Target) !=
94               Current->Requirements[I].second) {
95         Req = Current->Requirements[I];
96         return false;
97       }
98     }
99     if (!Current->MissingHeaders.empty()) {
100       MissingHeader = Current->MissingHeaders.front();
101       return false;
102     }
103   }
104
105   llvm_unreachable("could not find a reason why module is unavailable");
106 }
107
108 bool Module::isSubModuleOf(const Module *Other) const {
109   const Module *This = this;
110   do {
111     if (This == Other)
112       return true;
113     
114     This = This->Parent;
115   } while (This);
116   
117   return false;
118 }
119
120 const Module *Module::getTopLevelModule() const {
121   const Module *Result = this;
122   while (Result->Parent)
123     Result = Result->Parent;
124   
125   return Result;
126 }
127
128 std::string Module::getFullModuleName() const {
129   SmallVector<StringRef, 2> Names;
130   
131   // Build up the set of module names (from innermost to outermost).
132   for (const Module *M = this; M; M = M->Parent)
133     Names.push_back(M->Name);
134   
135   std::string Result;
136   for (SmallVectorImpl<StringRef>::reverse_iterator I = Names.rbegin(),
137                                                  IEnd = Names.rend();
138        I != IEnd; ++I) {
139     if (!Result.empty())
140       Result += '.';
141     
142     Result += *I;
143   }
144   
145   return Result;
146 }
147
148 bool Module::fullModuleNameIs(ArrayRef<StringRef> nameParts) const {
149   for (const Module *M = this; M; M = M->Parent) {
150     if (nameParts.empty() || M->Name != nameParts.back())
151       return false;
152     nameParts = nameParts.drop_back();
153   }
154   return nameParts.empty();
155 }
156
157 Module::DirectoryName Module::getUmbrellaDir() const {
158   if (Header U = getUmbrellaHeader())
159     return {"", U.Entry->getDir()};
160   
161   return {UmbrellaAsWritten, Umbrella.dyn_cast<const DirectoryEntry *>()};
162 }
163
164 ArrayRef<const FileEntry *> Module::getTopHeaders(FileManager &FileMgr) {
165   if (!TopHeaderNames.empty()) {
166     for (std::vector<std::string>::iterator
167            I = TopHeaderNames.begin(), E = TopHeaderNames.end(); I != E; ++I) {
168       if (const FileEntry *FE = FileMgr.getFile(*I))
169         TopHeaders.insert(FE);
170     }
171     TopHeaderNames.clear();
172   }
173
174   return llvm::makeArrayRef(TopHeaders.begin(), TopHeaders.end());
175 }
176
177 bool Module::directlyUses(const Module *Requested) const {
178   auto *Top = getTopLevelModule();
179
180   // A top-level module implicitly uses itself.
181   if (Requested->isSubModuleOf(Top))
182     return true;
183
184   for (auto *Use : Top->DirectUses)
185     if (Requested->isSubModuleOf(Use))
186       return true;
187
188   // Anyone is allowed to use our builtin stddef.h and its accompanying module.
189   if (!Requested->Parent && Requested->Name == "_Builtin_stddef_max_align_t")
190     return true;
191
192   return false;
193 }
194
195 void Module::addRequirement(StringRef Feature, bool RequiredState,
196                             const LangOptions &LangOpts,
197                             const TargetInfo &Target) {
198   Requirements.push_back(Requirement(Feature, RequiredState));
199
200   // If this feature is currently available, we're done.
201   if (hasFeature(Feature, LangOpts, Target) == RequiredState)
202     return;
203
204   markUnavailable(/*MissingRequirement*/true);
205 }
206
207 void Module::markUnavailable(bool MissingRequirement) {
208   auto needUpdate = [MissingRequirement](Module *M) {
209     return M->IsAvailable || (!M->IsMissingRequirement && MissingRequirement);
210   };
211
212   if (!needUpdate(this))
213     return;
214
215   SmallVector<Module *, 2> Stack;
216   Stack.push_back(this);
217   while (!Stack.empty()) {
218     Module *Current = Stack.back();
219     Stack.pop_back();
220
221     if (!needUpdate(Current))
222       continue;
223
224     Current->IsAvailable = false;
225     Current->IsMissingRequirement |= MissingRequirement;
226     for (submodule_iterator Sub = Current->submodule_begin(),
227                          SubEnd = Current->submodule_end();
228          Sub != SubEnd; ++Sub) {
229       if (needUpdate(*Sub))
230         Stack.push_back(*Sub);
231     }
232   }
233 }
234
235 Module *Module::findSubmodule(StringRef Name) const {
236   llvm::StringMap<unsigned>::const_iterator Pos = SubModuleIndex.find(Name);
237   if (Pos == SubModuleIndex.end())
238     return nullptr;
239
240   return SubModules[Pos->getValue()];
241 }
242
243 static void printModuleId(raw_ostream &OS, const ModuleId &Id) {
244   for (unsigned I = 0, N = Id.size(); I != N; ++I) {
245     if (I)
246       OS << ".";
247     OS << Id[I].first;
248   }
249 }
250
251 void Module::getExportedModules(SmallVectorImpl<Module *> &Exported) const {
252   // All non-explicit submodules are exported.
253   for (std::vector<Module *>::const_iterator I = SubModules.begin(),
254                                              E = SubModules.end();
255        I != E; ++I) {
256     Module *Mod = *I;
257     if (!Mod->IsExplicit)
258       Exported.push_back(Mod);
259   }
260
261   // Find re-exported modules by filtering the list of imported modules.
262   bool AnyWildcard = false;
263   bool UnrestrictedWildcard = false;
264   SmallVector<Module *, 4> WildcardRestrictions;
265   for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
266     Module *Mod = Exports[I].getPointer();
267     if (!Exports[I].getInt()) {
268       // Export a named module directly; no wildcards involved.
269       Exported.push_back(Mod);
270
271       continue;
272     }
273
274     // Wildcard export: export all of the imported modules that match
275     // the given pattern.
276     AnyWildcard = true;
277     if (UnrestrictedWildcard)
278       continue;
279
280     if (Module *Restriction = Exports[I].getPointer())
281       WildcardRestrictions.push_back(Restriction);
282     else {
283       WildcardRestrictions.clear();
284       UnrestrictedWildcard = true;
285     }
286   }
287
288   // If there were any wildcards, push any imported modules that were
289   // re-exported by the wildcard restriction.
290   if (!AnyWildcard)
291     return;
292
293   for (unsigned I = 0, N = Imports.size(); I != N; ++I) {
294     Module *Mod = Imports[I];
295     bool Acceptable = UnrestrictedWildcard;
296     if (!Acceptable) {
297       // Check whether this module meets one of the restrictions.
298       for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
299         Module *Restriction = WildcardRestrictions[R];
300         if (Mod == Restriction || Mod->isSubModuleOf(Restriction)) {
301           Acceptable = true;
302           break;
303         }
304       }
305     }
306
307     if (!Acceptable)
308       continue;
309
310     Exported.push_back(Mod);
311   }
312 }
313
314 void Module::buildVisibleModulesCache() const {
315   assert(VisibleModulesCache.empty() && "cache does not need building");
316
317   // This module is visible to itself.
318   VisibleModulesCache.insert(this);
319
320   // Every imported module is visible.
321   SmallVector<Module *, 16> Stack(Imports.begin(), Imports.end());
322   while (!Stack.empty()) {
323     Module *CurrModule = Stack.pop_back_val();
324
325     // Every module transitively exported by an imported module is visible.
326     if (VisibleModulesCache.insert(CurrModule).second)
327       CurrModule->getExportedModules(Stack);
328   }
329 }
330
331 void Module::print(raw_ostream &OS, unsigned Indent) const {
332   OS.indent(Indent);
333   if (IsFramework)
334     OS << "framework ";
335   if (IsExplicit)
336     OS << "explicit ";
337   OS << "module " << Name;
338
339   if (IsSystem || IsExternC) {
340     OS.indent(Indent + 2);
341     if (IsSystem)
342       OS << " [system]";
343     if (IsExternC)
344       OS << " [extern_c]";
345   }
346
347   OS << " {\n";
348   
349   if (!Requirements.empty()) {
350     OS.indent(Indent + 2);
351     OS << "requires ";
352     for (unsigned I = 0, N = Requirements.size(); I != N; ++I) {
353       if (I)
354         OS << ", ";
355       if (!Requirements[I].second)
356         OS << "!";
357       OS << Requirements[I].first;
358     }
359     OS << "\n";
360   }
361   
362   if (Header H = getUmbrellaHeader()) {
363     OS.indent(Indent + 2);
364     OS << "umbrella header \"";
365     OS.write_escaped(H.NameAsWritten);
366     OS << "\"\n";
367   } else if (DirectoryName D = getUmbrellaDir()) {
368     OS.indent(Indent + 2);
369     OS << "umbrella \"";
370     OS.write_escaped(D.NameAsWritten);
371     OS << "\"\n";    
372   }
373
374   if (!ConfigMacros.empty() || ConfigMacrosExhaustive) {
375     OS.indent(Indent + 2);
376     OS << "config_macros ";
377     if (ConfigMacrosExhaustive)
378       OS << "[exhaustive]";
379     for (unsigned I = 0, N = ConfigMacros.size(); I != N; ++I) {
380       if (I)
381         OS << ", ";
382       OS << ConfigMacros[I];
383     }
384     OS << "\n";
385   }
386
387   struct {
388     StringRef Prefix;
389     HeaderKind Kind;
390   } Kinds[] = {{"", HK_Normal},
391                {"textual ", HK_Textual},
392                {"private ", HK_Private},
393                {"private textual ", HK_PrivateTextual},
394                {"exclude ", HK_Excluded}};
395
396   for (auto &K : Kinds) {
397     assert(&K == &Kinds[K.Kind] && "kinds in wrong order");
398     for (auto &H : Headers[K.Kind]) {
399       OS.indent(Indent + 2);
400       OS << K.Prefix << "header \"";
401       OS.write_escaped(H.NameAsWritten);
402       OS << "\" { size " << H.Entry->getSize()
403          << " mtime " << H.Entry->getModificationTime() << " }\n";
404     }
405   }
406   for (auto *Unresolved : {&UnresolvedHeaders, &MissingHeaders}) {
407     for (auto &U : *Unresolved) {
408       OS.indent(Indent + 2);
409       OS << Kinds[U.Kind].Prefix << "header \"";
410       OS.write_escaped(U.FileName);
411       OS << "\"";
412       if (U.Size || U.ModTime) {
413         OS << " {";
414         if (U.Size)
415           OS << " size " << *U.Size;
416         if (U.ModTime)
417           OS << " mtime " << *U.ModTime;
418         OS << " }";
419       }
420       OS << "\n";
421     }
422   }
423
424   for (submodule_const_iterator MI = submodule_begin(), MIEnd = submodule_end();
425        MI != MIEnd; ++MI)
426     // Print inferred subframework modules so that we don't need to re-infer
427     // them (requires expensive directory iteration + stat calls) when we build
428     // the module. Regular inferred submodules are OK, as we need to look at all
429     // those header files anyway.
430     if (!(*MI)->IsInferred || (*MI)->IsFramework)
431       (*MI)->print(OS, Indent + 2);
432   
433   for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
434     OS.indent(Indent + 2);
435     OS << "export ";
436     if (Module *Restriction = Exports[I].getPointer()) {
437       OS << Restriction->getFullModuleName();
438       if (Exports[I].getInt())
439         OS << ".*";
440     } else {
441       OS << "*";
442     }
443     OS << "\n";
444   }
445
446   for (unsigned I = 0, N = UnresolvedExports.size(); I != N; ++I) {
447     OS.indent(Indent + 2);
448     OS << "export ";
449     printModuleId(OS, UnresolvedExports[I].Id);
450     if (UnresolvedExports[I].Wildcard)
451       OS << (UnresolvedExports[I].Id.empty() ? "*" : ".*");
452     OS << "\n";
453   }
454
455   for (unsigned I = 0, N = DirectUses.size(); I != N; ++I) {
456     OS.indent(Indent + 2);
457     OS << "use ";
458     OS << DirectUses[I]->getFullModuleName();
459     OS << "\n";
460   }
461
462   for (unsigned I = 0, N = UnresolvedDirectUses.size(); I != N; ++I) {
463     OS.indent(Indent + 2);
464     OS << "use ";
465     printModuleId(OS, UnresolvedDirectUses[I]);
466     OS << "\n";
467   }
468
469   for (unsigned I = 0, N = LinkLibraries.size(); I != N; ++I) {
470     OS.indent(Indent + 2);
471     OS << "link ";
472     if (LinkLibraries[I].IsFramework)
473       OS << "framework ";
474     OS << "\"";
475     OS.write_escaped(LinkLibraries[I].Library);
476     OS << "\"";
477   }
478
479   for (unsigned I = 0, N = UnresolvedConflicts.size(); I != N; ++I) {
480     OS.indent(Indent + 2);
481     OS << "conflict ";
482     printModuleId(OS, UnresolvedConflicts[I].Id);
483     OS << ", \"";
484     OS.write_escaped(UnresolvedConflicts[I].Message);
485     OS << "\"\n";
486   }
487
488   for (unsigned I = 0, N = Conflicts.size(); I != N; ++I) {
489     OS.indent(Indent + 2);
490     OS << "conflict ";
491     OS << Conflicts[I].Other->getFullModuleName();
492     OS << ", \"";
493     OS.write_escaped(Conflicts[I].Message);
494     OS << "\"\n";
495   }
496
497   if (InferSubmodules) {
498     OS.indent(Indent + 2);
499     if (InferExplicitSubmodules)
500       OS << "explicit ";
501     OS << "module * {\n";
502     if (InferExportWildcard) {
503       OS.indent(Indent + 4);
504       OS << "export *\n";
505     }
506     OS.indent(Indent + 2);
507     OS << "}\n";
508   }
509   
510   OS.indent(Indent);
511   OS << "}\n";
512 }
513
514 LLVM_DUMP_METHOD void Module::dump() const {
515   print(llvm::errs());
516 }
517
518 void VisibleModuleSet::setVisible(Module *M, SourceLocation Loc,
519                                   VisibleCallback Vis, ConflictCallback Cb) {
520   assert(Loc.isValid() && "setVisible expects a valid import location");
521   if (isVisible(M))
522     return;
523
524   ++Generation;
525
526   struct Visiting {
527     Module *M;
528     Visiting *ExportedBy;
529   };
530
531   std::function<void(Visiting)> VisitModule = [&](Visiting V) {
532     // Modules that aren't available cannot be made visible.
533     if (!V.M->isAvailable())
534       return;
535
536     // Nothing to do for a module that's already visible.
537     unsigned ID = V.M->getVisibilityID();
538     if (ImportLocs.size() <= ID)
539       ImportLocs.resize(ID + 1);
540     else if (ImportLocs[ID].isValid())
541       return;
542
543     ImportLocs[ID] = Loc;
544     Vis(M);
545
546     // Make any exported modules visible.
547     SmallVector<Module *, 16> Exports;
548     V.M->getExportedModules(Exports);
549     for (Module *E : Exports)
550       VisitModule({E, &V});
551
552     for (auto &C : V.M->Conflicts) {
553       if (isVisible(C.Other)) {
554         llvm::SmallVector<Module*, 8> Path;
555         for (Visiting *I = &V; I; I = I->ExportedBy)
556           Path.push_back(I->M);
557         Cb(Path, C.Other, C.Message);
558       }
559     }
560   };
561   VisitModule({M, nullptr});
562 }