Module.cpp 15 KB

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