Module.cpp 18 KB

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