Module.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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. #include "clang/Basic/Module.h"
  15. #include "clang/Basic/FileManager.h"
  16. #include "clang/Basic/LangOptions.h"
  17. #include "clang/Basic/TargetInfo.h"
  18. #include "llvm/ADT/ArrayRef.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/StringSwitch.h"
  21. #include "llvm/Support/ErrorHandling.h"
  22. #include "llvm/Support/raw_ostream.h"
  23. using namespace clang;
  24. Module::Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent,
  25. bool IsFramework, bool IsExplicit, unsigned VisibilityID)
  26. : Name(Name), DefinitionLoc(DefinitionLoc), Parent(Parent), Directory(),
  27. Umbrella(), Signature(0), ASTFile(nullptr), VisibilityID(VisibilityID),
  28. IsMissingRequirement(false), HasIncompatibleModuleFile(false),
  29. IsAvailable(true), IsFromModuleFile(false), IsFramework(IsFramework),
  30. IsExplicit(IsExplicit), IsSystem(false), IsExternC(false),
  31. IsInferred(false), InferSubmodules(false), InferExplicitSubmodules(false),
  32. InferExportWildcard(false), ConfigMacrosExhaustive(false),
  33. NameVisibility(Hidden) {
  34. if (Parent) {
  35. if (!Parent->isAvailable())
  36. IsAvailable = false;
  37. if (Parent->IsSystem)
  38. IsSystem = true;
  39. if (Parent->IsExternC)
  40. IsExternC = true;
  41. IsMissingRequirement = Parent->IsMissingRequirement;
  42. Parent->SubModuleIndex[Name] = Parent->SubModules.size();
  43. Parent->SubModules.push_back(this);
  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. /// \brief Determine whether a translation unit built using the current
  53. /// language options has the given feature.
  54. static bool hasFeature(StringRef Feature, const LangOptions &LangOpts,
  55. const TargetInfo &Target) {
  56. bool HasFeature = llvm::StringSwitch<bool>(Feature)
  57. .Case("altivec", LangOpts.AltiVec)
  58. .Case("blocks", LangOpts.Blocks)
  59. .Case("cplusplus", LangOpts.CPlusPlus)
  60. .Case("cplusplus11", LangOpts.CPlusPlus11)
  61. .Case("objc", LangOpts.ObjC1)
  62. .Case("objc_arc", LangOpts.ObjCAutoRefCount)
  63. .Case("opencl", LangOpts.OpenCL)
  64. .Case("tls", Target.isTLSSupported())
  65. .Case("zvector", LangOpts.ZVector)
  66. .Default(Target.hasFeature(Feature));
  67. if (!HasFeature)
  68. HasFeature = std::find(LangOpts.ModuleFeatures.begin(),
  69. LangOpts.ModuleFeatures.end(),
  70. Feature) != LangOpts.ModuleFeatures.end();
  71. return HasFeature;
  72. }
  73. bool Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target,
  74. Requirement &Req,
  75. UnresolvedHeaderDirective &MissingHeader) const {
  76. if (IsAvailable)
  77. return true;
  78. for (const Module *Current = this; Current; Current = Current->Parent) {
  79. for (unsigned I = 0, N = Current->Requirements.size(); I != N; ++I) {
  80. if (hasFeature(Current->Requirements[I].first, LangOpts, Target) !=
  81. Current->Requirements[I].second) {
  82. Req = Current->Requirements[I];
  83. return false;
  84. }
  85. }
  86. if (!Current->MissingHeaders.empty()) {
  87. MissingHeader = Current->MissingHeaders.front();
  88. return false;
  89. }
  90. }
  91. llvm_unreachable("could not find a reason why module is unavailable");
  92. }
  93. bool Module::isSubModuleOf(const Module *Other) const {
  94. const Module *This = this;
  95. do {
  96. if (This == Other)
  97. return true;
  98. This = This->Parent;
  99. } while (This);
  100. return false;
  101. }
  102. const Module *Module::getTopLevelModule() const {
  103. const Module *Result = this;
  104. while (Result->Parent)
  105. Result = Result->Parent;
  106. return Result;
  107. }
  108. std::string Module::getFullModuleName() const {
  109. SmallVector<StringRef, 2> Names;
  110. // Build up the set of module names (from innermost to outermost).
  111. for (const Module *M = this; M; M = M->Parent)
  112. Names.push_back(M->Name);
  113. std::string Result;
  114. for (SmallVectorImpl<StringRef>::reverse_iterator I = Names.rbegin(),
  115. IEnd = Names.rend();
  116. I != IEnd; ++I) {
  117. if (!Result.empty())
  118. Result += '.';
  119. Result += *I;
  120. }
  121. return Result;
  122. }
  123. bool Module::fullModuleNameIs(ArrayRef<StringRef> nameParts) const {
  124. for (const Module *M = this; M; M = M->Parent) {
  125. if (nameParts.empty() || M->Name != nameParts.back())
  126. return false;
  127. nameParts = nameParts.drop_back();
  128. }
  129. return nameParts.empty();
  130. }
  131. Module::DirectoryName Module::getUmbrellaDir() const {
  132. if (Header U = getUmbrellaHeader())
  133. return {"", U.Entry->getDir()};
  134. return {UmbrellaAsWritten, Umbrella.dyn_cast<const DirectoryEntry *>()};
  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. return llvm::makeArrayRef(TopHeaders.begin(), TopHeaders.end());
  146. }
  147. bool Module::directlyUses(const Module *Requested) const {
  148. auto *Top = getTopLevelModule();
  149. // A top-level module implicitly uses itself.
  150. if (Requested->isSubModuleOf(Top))
  151. return true;
  152. for (auto *Use : Top->DirectUses)
  153. if (Requested->isSubModuleOf(Use))
  154. return true;
  155. return false;
  156. }
  157. void Module::addRequirement(StringRef Feature, bool RequiredState,
  158. const LangOptions &LangOpts,
  159. const TargetInfo &Target) {
  160. Requirements.push_back(Requirement(Feature, RequiredState));
  161. // If this feature is currently available, we're done.
  162. if (hasFeature(Feature, LangOpts, Target) == RequiredState)
  163. return;
  164. markUnavailable(/*MissingRequirement*/true);
  165. }
  166. void Module::markUnavailable(bool MissingRequirement) {
  167. auto needUpdate = [MissingRequirement](Module *M) {
  168. return M->IsAvailable || (!M->IsMissingRequirement && MissingRequirement);
  169. };
  170. if (!needUpdate(this))
  171. return;
  172. SmallVector<Module *, 2> Stack;
  173. Stack.push_back(this);
  174. while (!Stack.empty()) {
  175. Module *Current = Stack.back();
  176. Stack.pop_back();
  177. if (!needUpdate(Current))
  178. continue;
  179. Current->IsAvailable = false;
  180. Current->IsMissingRequirement |= MissingRequirement;
  181. for (submodule_iterator Sub = Current->submodule_begin(),
  182. SubEnd = Current->submodule_end();
  183. Sub != SubEnd; ++Sub) {
  184. if (needUpdate(*Sub))
  185. Stack.push_back(*Sub);
  186. }
  187. }
  188. }
  189. Module *Module::findSubmodule(StringRef Name) const {
  190. llvm::StringMap<unsigned>::const_iterator Pos = SubModuleIndex.find(Name);
  191. if (Pos == SubModuleIndex.end())
  192. return nullptr;
  193. return SubModules[Pos->getValue()];
  194. }
  195. static void printModuleId(raw_ostream &OS, const ModuleId &Id) {
  196. for (unsigned I = 0, N = Id.size(); I != N; ++I) {
  197. if (I)
  198. OS << ".";
  199. OS << Id[I].first;
  200. }
  201. }
  202. void Module::getExportedModules(SmallVectorImpl<Module *> &Exported) const {
  203. // All non-explicit submodules are exported.
  204. for (std::vector<Module *>::const_iterator I = SubModules.begin(),
  205. E = SubModules.end();
  206. I != E; ++I) {
  207. Module *Mod = *I;
  208. if (!Mod->IsExplicit)
  209. Exported.push_back(Mod);
  210. }
  211. // Find re-exported modules by filtering the list of imported modules.
  212. bool AnyWildcard = false;
  213. bool UnrestrictedWildcard = false;
  214. SmallVector<Module *, 4> WildcardRestrictions;
  215. for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
  216. Module *Mod = Exports[I].getPointer();
  217. if (!Exports[I].getInt()) {
  218. // Export a named module directly; no wildcards involved.
  219. Exported.push_back(Mod);
  220. continue;
  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. if (Module *Restriction = Exports[I].getPointer())
  228. WildcardRestrictions.push_back(Restriction);
  229. else {
  230. WildcardRestrictions.clear();
  231. UnrestrictedWildcard = true;
  232. }
  233. }
  234. // If there were any wildcards, push any imported modules that were
  235. // re-exported by the wildcard restriction.
  236. if (!AnyWildcard)
  237. return;
  238. for (unsigned I = 0, N = Imports.size(); I != N; ++I) {
  239. Module *Mod = Imports[I];
  240. bool Acceptable = UnrestrictedWildcard;
  241. if (!Acceptable) {
  242. // Check whether this module meets one of the restrictions.
  243. for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
  244. Module *Restriction = WildcardRestrictions[R];
  245. if (Mod == Restriction || Mod->isSubModuleOf(Restriction)) {
  246. Acceptable = true;
  247. break;
  248. }
  249. }
  250. }
  251. if (!Acceptable)
  252. continue;
  253. Exported.push_back(Mod);
  254. }
  255. }
  256. void Module::buildVisibleModulesCache() const {
  257. assert(VisibleModulesCache.empty() && "cache does not need building");
  258. // This module is visible to itself.
  259. VisibleModulesCache.insert(this);
  260. // Every imported module is visible.
  261. SmallVector<Module *, 16> Stack(Imports.begin(), Imports.end());
  262. while (!Stack.empty()) {
  263. Module *CurrModule = Stack.pop_back_val();
  264. // Every module transitively exported by an imported module is visible.
  265. if (VisibleModulesCache.insert(CurrModule).second)
  266. CurrModule->getExportedModules(Stack);
  267. }
  268. }
  269. void Module::print(raw_ostream &OS, unsigned Indent) const {
  270. OS.indent(Indent);
  271. if (IsFramework)
  272. OS << "framework ";
  273. if (IsExplicit)
  274. OS << "explicit ";
  275. OS << "module " << Name;
  276. if (IsSystem || IsExternC) {
  277. OS.indent(Indent + 2);
  278. if (IsSystem)
  279. OS << " [system]";
  280. if (IsExternC)
  281. OS << " [extern_c]";
  282. }
  283. OS << " {\n";
  284. if (!Requirements.empty()) {
  285. OS.indent(Indent + 2);
  286. OS << "requires ";
  287. for (unsigned I = 0, N = Requirements.size(); I != N; ++I) {
  288. if (I)
  289. OS << ", ";
  290. if (!Requirements[I].second)
  291. OS << "!";
  292. OS << Requirements[I].first;
  293. }
  294. OS << "\n";
  295. }
  296. if (Header H = getUmbrellaHeader()) {
  297. OS.indent(Indent + 2);
  298. OS << "umbrella header \"";
  299. OS.write_escaped(H.NameAsWritten);
  300. OS << "\"\n";
  301. } else if (DirectoryName D = getUmbrellaDir()) {
  302. OS.indent(Indent + 2);
  303. OS << "umbrella \"";
  304. OS.write_escaped(D.NameAsWritten);
  305. OS << "\"\n";
  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. struct {
  320. StringRef Prefix;
  321. HeaderKind Kind;
  322. } Kinds[] = {{"", HK_Normal},
  323. {"textual ", HK_Textual},
  324. {"private ", HK_Private},
  325. {"private textual ", HK_PrivateTextual},
  326. {"exclude ", HK_Excluded}};
  327. for (auto &K : Kinds) {
  328. for (auto &H : Headers[K.Kind]) {
  329. OS.indent(Indent + 2);
  330. OS << K.Prefix << "header \"";
  331. OS.write_escaped(H.NameAsWritten);
  332. OS << "\"\n";
  333. }
  334. }
  335. for (submodule_const_iterator MI = submodule_begin(), MIEnd = submodule_end();
  336. MI != MIEnd; ++MI)
  337. // Print inferred subframework modules so that we don't need to re-infer
  338. // them (requires expensive directory iteration + stat calls) when we build
  339. // the module. Regular inferred submodules are OK, as we need to look at all
  340. // those header files anyway.
  341. if (!(*MI)->IsInferred || (*MI)->IsFramework)
  342. (*MI)->print(OS, Indent + 2);
  343. for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
  344. OS.indent(Indent + 2);
  345. OS << "export ";
  346. if (Module *Restriction = Exports[I].getPointer()) {
  347. OS << Restriction->getFullModuleName();
  348. if (Exports[I].getInt())
  349. OS << ".*";
  350. } else {
  351. OS << "*";
  352. }
  353. OS << "\n";
  354. }
  355. for (unsigned I = 0, N = UnresolvedExports.size(); I != N; ++I) {
  356. OS.indent(Indent + 2);
  357. OS << "export ";
  358. printModuleId(OS, UnresolvedExports[I].Id);
  359. if (UnresolvedExports[I].Wildcard) {
  360. if (UnresolvedExports[I].Id.empty())
  361. OS << "*";
  362. else
  363. OS << ".*";
  364. }
  365. OS << "\n";
  366. }
  367. for (unsigned I = 0, N = DirectUses.size(); I != N; ++I) {
  368. OS.indent(Indent + 2);
  369. OS << "use ";
  370. OS << DirectUses[I]->getFullModuleName();
  371. OS << "\n";
  372. }
  373. for (unsigned I = 0, N = UnresolvedDirectUses.size(); I != N; ++I) {
  374. OS.indent(Indent + 2);
  375. OS << "use ";
  376. printModuleId(OS, UnresolvedDirectUses[I]);
  377. OS << "\n";
  378. }
  379. for (unsigned I = 0, N = LinkLibraries.size(); I != N; ++I) {
  380. OS.indent(Indent + 2);
  381. OS << "link ";
  382. if (LinkLibraries[I].IsFramework)
  383. OS << "framework ";
  384. OS << "\"";
  385. OS.write_escaped(LinkLibraries[I].Library);
  386. OS << "\"";
  387. }
  388. for (unsigned I = 0, N = UnresolvedConflicts.size(); I != N; ++I) {
  389. OS.indent(Indent + 2);
  390. OS << "conflict ";
  391. printModuleId(OS, UnresolvedConflicts[I].Id);
  392. OS << ", \"";
  393. OS.write_escaped(UnresolvedConflicts[I].Message);
  394. OS << "\"\n";
  395. }
  396. for (unsigned I = 0, N = Conflicts.size(); I != N; ++I) {
  397. OS.indent(Indent + 2);
  398. OS << "conflict ";
  399. OS << Conflicts[I].Other->getFullModuleName();
  400. OS << ", \"";
  401. OS.write_escaped(Conflicts[I].Message);
  402. OS << "\"\n";
  403. }
  404. if (InferSubmodules) {
  405. OS.indent(Indent + 2);
  406. if (InferExplicitSubmodules)
  407. OS << "explicit ";
  408. OS << "module * {\n";
  409. if (InferExportWildcard) {
  410. OS.indent(Indent + 4);
  411. OS << "export *\n";
  412. }
  413. OS.indent(Indent + 2);
  414. OS << "}\n";
  415. }
  416. OS.indent(Indent);
  417. OS << "}\n";
  418. }
  419. LLVM_DUMP_METHOD void Module::dump() const {
  420. print(llvm::errs());
  421. }
  422. void VisibleModuleSet::setVisible(Module *M, SourceLocation Loc,
  423. VisibleCallback Vis, ConflictCallback Cb) {
  424. assert(Loc.isValid() && "setVisible expects a valid import location");
  425. if (isVisible(M))
  426. return;
  427. ++Generation;
  428. struct Visiting {
  429. Module *M;
  430. Visiting *ExportedBy;
  431. };
  432. std::function<void(Visiting)> VisitModule = [&](Visiting V) {
  433. // Modules that aren't available cannot be made visible.
  434. if (!V.M->isAvailable())
  435. return;
  436. // Nothing to do for a module that's already visible.
  437. unsigned ID = V.M->getVisibilityID();
  438. if (ImportLocs.size() <= ID)
  439. ImportLocs.resize(ID + 1);
  440. else if (ImportLocs[ID].isValid())
  441. return;
  442. ImportLocs[ID] = Loc;
  443. Vis(M);
  444. // Make any exported modules visible.
  445. SmallVector<Module *, 16> Exports;
  446. V.M->getExportedModules(Exports);
  447. for (Module *E : Exports)
  448. VisitModule({E, &V});
  449. for (auto &C : V.M->Conflicts) {
  450. if (isVisible(C.Other)) {
  451. llvm::SmallVector<Module*, 8> Path;
  452. for (Visiting *I = &V; I; I = I->ExportedBy)
  453. Path.push_back(I->M);
  454. Cb(Path, C.Other, C.Message);
  455. }
  456. }
  457. };
  458. VisitModule({M, nullptr});
  459. }