Module.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. //===- Module.cpp - Describe a module -------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines the Module class, which describes a module in the source
  10. // code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Basic/Module.h"
  14. #include "clang/Basic/CharInfo.h"
  15. #include "clang/Basic/FileManager.h"
  16. #include "clang/Basic/LangOptions.h"
  17. #include "clang/Basic/SourceLocation.h"
  18. #include "clang/Basic/TargetInfo.h"
  19. #include "llvm/ADT/ArrayRef.h"
  20. #include "llvm/ADT/SmallVector.h"
  21. #include "llvm/ADT/StringMap.h"
  22. #include "llvm/ADT/StringRef.h"
  23. #include "llvm/ADT/StringSwitch.h"
  24. #include "llvm/Support/Compiler.h"
  25. #include "llvm/Support/ErrorHandling.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include <algorithm>
  28. #include <cassert>
  29. #include <functional>
  30. #include <string>
  31. #include <utility>
  32. #include <vector>
  33. using namespace clang;
  34. Module::Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent,
  35. bool IsFramework, bool IsExplicit, unsigned VisibilityID)
  36. : Name(Name), DefinitionLoc(DefinitionLoc), Parent(Parent),
  37. VisibilityID(VisibilityID), IsUnimportable(false),
  38. HasIncompatibleModuleFile(false), IsAvailable(true),
  39. IsFromModuleFile(false), IsFramework(IsFramework), IsExplicit(IsExplicit),
  40. IsSystem(false), IsExternC(false), IsInferred(false),
  41. InferSubmodules(false), InferExplicitSubmodules(false),
  42. InferExportWildcard(false), ConfigMacrosExhaustive(false),
  43. NoUndeclaredIncludes(false), ModuleMapIsPrivate(false),
  44. NameVisibility(Hidden) {
  45. if (Parent) {
  46. IsAvailable = Parent->isAvailable();
  47. IsUnimportable = Parent->isUnimportable();
  48. IsSystem = Parent->IsSystem;
  49. IsExternC = Parent->IsExternC;
  50. NoUndeclaredIncludes = Parent->NoUndeclaredIncludes;
  51. ModuleMapIsPrivate = Parent->ModuleMapIsPrivate;
  52. Parent->SubModuleIndex[Name] = Parent->SubModules.size();
  53. Parent->SubModules.push_back(this);
  54. }
  55. }
  56. Module::~Module() {
  57. for (submodule_iterator I = submodule_begin(), IEnd = submodule_end();
  58. I != IEnd; ++I) {
  59. delete *I;
  60. }
  61. }
  62. static bool isPlatformEnvironment(const TargetInfo &Target, StringRef Feature) {
  63. StringRef Platform = Target.getPlatformName();
  64. StringRef Env = Target.getTriple().getEnvironmentName();
  65. // Attempt to match platform and environment.
  66. if (Platform == Feature || Target.getTriple().getOSName() == Feature ||
  67. Env == Feature)
  68. return true;
  69. auto CmpPlatformEnv = [](StringRef LHS, StringRef RHS) {
  70. auto Pos = LHS.find('-');
  71. if (Pos == StringRef::npos)
  72. return false;
  73. SmallString<128> NewLHS = LHS.slice(0, Pos);
  74. NewLHS += LHS.slice(Pos+1, LHS.size());
  75. return NewLHS == RHS;
  76. };
  77. SmallString<128> PlatformEnv = Target.getTriple().getOSAndEnvironmentName();
  78. // Darwin has different but equivalent variants for simulators, example:
  79. // 1. x86_64-apple-ios-simulator
  80. // 2. x86_64-apple-iossimulator
  81. // where both are valid examples of the same platform+environment but in the
  82. // variant (2) the simulator is hardcoded as part of the platform name. Both
  83. // forms above should match for "iossimulator" requirement.
  84. if (Target.getTriple().isOSDarwin() && PlatformEnv.endswith("simulator"))
  85. return PlatformEnv == Feature || CmpPlatformEnv(PlatformEnv, Feature);
  86. return PlatformEnv == Feature;
  87. }
  88. /// Determine whether a translation unit built using the current
  89. /// language options has the given feature.
  90. static bool hasFeature(StringRef Feature, const LangOptions &LangOpts,
  91. const TargetInfo &Target) {
  92. bool HasFeature = llvm::StringSwitch<bool>(Feature)
  93. .Case("altivec", LangOpts.AltiVec)
  94. .Case("blocks", LangOpts.Blocks)
  95. .Case("coroutines", LangOpts.Coroutines)
  96. .Case("cplusplus", LangOpts.CPlusPlus)
  97. .Case("cplusplus11", LangOpts.CPlusPlus11)
  98. .Case("cplusplus14", LangOpts.CPlusPlus14)
  99. .Case("cplusplus17", LangOpts.CPlusPlus17)
  100. .Case("c99", LangOpts.C99)
  101. .Case("c11", LangOpts.C11)
  102. .Case("c17", LangOpts.C17)
  103. .Case("freestanding", LangOpts.Freestanding)
  104. .Case("gnuinlineasm", LangOpts.GNUAsm)
  105. .Case("objc", LangOpts.ObjC)
  106. .Case("objc_arc", LangOpts.ObjCAutoRefCount)
  107. .Case("opencl", LangOpts.OpenCL)
  108. .Case("tls", Target.isTLSSupported())
  109. .Case("zvector", LangOpts.ZVector)
  110. .Default(Target.hasFeature(Feature) ||
  111. isPlatformEnvironment(Target, Feature));
  112. if (!HasFeature)
  113. HasFeature = llvm::is_contained(LangOpts.ModuleFeatures, Feature);
  114. return HasFeature;
  115. }
  116. bool Module::isUnimportable(const LangOptions &LangOpts,
  117. const TargetInfo &Target, Requirement &Req,
  118. Module *&ShadowingModule) const {
  119. if (!IsUnimportable)
  120. return false;
  121. for (const Module *Current = this; Current; Current = Current->Parent) {
  122. if (Current->ShadowingModule) {
  123. ShadowingModule = Current->ShadowingModule;
  124. return true;
  125. }
  126. for (unsigned I = 0, N = Current->Requirements.size(); I != N; ++I) {
  127. if (hasFeature(Current->Requirements[I].first, LangOpts, Target) !=
  128. Current->Requirements[I].second) {
  129. Req = Current->Requirements[I];
  130. return true;
  131. }
  132. }
  133. }
  134. llvm_unreachable("could not find a reason why module is unimportable");
  135. }
  136. // The -fmodule-name option tells the compiler to textually include headers in
  137. // the specified module, meaning Clang won't build the specified module. This
  138. // is useful in a number of situations, for instance, when building a library
  139. // that vends a module map, one might want to avoid hitting intermediate build
  140. // products containing the module map or avoid finding the system installed
  141. // modulemap for that library.
  142. bool Module::isForBuilding(const LangOptions &LangOpts) const {
  143. StringRef TopLevelName = getTopLevelModuleName();
  144. StringRef CurrentModule = LangOpts.CurrentModule;
  145. // When building framework Foo, we want to make sure that Foo *and*
  146. // Foo_Private are textually included and no modules are built for both.
  147. if (getTopLevelModule()->IsFramework &&
  148. CurrentModule == LangOpts.ModuleName &&
  149. !CurrentModule.endswith("_Private") && TopLevelName.endswith("_Private"))
  150. TopLevelName = TopLevelName.drop_back(8);
  151. return TopLevelName == CurrentModule;
  152. }
  153. bool Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target,
  154. Requirement &Req,
  155. UnresolvedHeaderDirective &MissingHeader,
  156. Module *&ShadowingModule) const {
  157. if (IsAvailable)
  158. return true;
  159. if (isUnimportable(LangOpts, Target, Req, ShadowingModule))
  160. return false;
  161. // FIXME: All missing headers are listed on the top-level module. Should we
  162. // just look there?
  163. for (const Module *Current = this; Current; Current = Current->Parent) {
  164. if (!Current->MissingHeaders.empty()) {
  165. MissingHeader = Current->MissingHeaders.front();
  166. return false;
  167. }
  168. }
  169. llvm_unreachable("could not find a reason why module is unavailable");
  170. }
  171. bool Module::isSubModuleOf(const Module *Other) const {
  172. for (auto *Parent = this; Parent; Parent = Parent->Parent) {
  173. if (Parent == Other)
  174. return true;
  175. }
  176. return false;
  177. }
  178. const Module *Module::getTopLevelModule() const {
  179. const Module *Result = this;
  180. while (Result->Parent)
  181. Result = Result->Parent;
  182. return Result;
  183. }
  184. static StringRef getModuleNameFromComponent(
  185. const std::pair<std::string, SourceLocation> &IdComponent) {
  186. return IdComponent.first;
  187. }
  188. static StringRef getModuleNameFromComponent(StringRef R) { return R; }
  189. template<typename InputIter>
  190. static void printModuleId(raw_ostream &OS, InputIter Begin, InputIter End,
  191. bool AllowStringLiterals = true) {
  192. for (InputIter It = Begin; It != End; ++It) {
  193. if (It != Begin)
  194. OS << ".";
  195. StringRef Name = getModuleNameFromComponent(*It);
  196. if (!AllowStringLiterals || isValidAsciiIdentifier(Name))
  197. OS << Name;
  198. else {
  199. OS << '"';
  200. OS.write_escaped(Name);
  201. OS << '"';
  202. }
  203. }
  204. }
  205. template<typename Container>
  206. static void printModuleId(raw_ostream &OS, const Container &C) {
  207. return printModuleId(OS, C.begin(), C.end());
  208. }
  209. std::string Module::getFullModuleName(bool AllowStringLiterals) const {
  210. SmallVector<StringRef, 2> Names;
  211. // Build up the set of module names (from innermost to outermost).
  212. for (const Module *M = this; M; M = M->Parent)
  213. Names.push_back(M->Name);
  214. std::string Result;
  215. llvm::raw_string_ostream Out(Result);
  216. printModuleId(Out, Names.rbegin(), Names.rend(), AllowStringLiterals);
  217. Out.flush();
  218. return Result;
  219. }
  220. bool Module::fullModuleNameIs(ArrayRef<StringRef> nameParts) const {
  221. for (const Module *M = this; M; M = M->Parent) {
  222. if (nameParts.empty() || M->Name != nameParts.back())
  223. return false;
  224. nameParts = nameParts.drop_back();
  225. }
  226. return nameParts.empty();
  227. }
  228. Module::DirectoryName Module::getUmbrellaDir() const {
  229. if (Header U = getUmbrellaHeader())
  230. return {"", "", U.Entry->getDir()};
  231. return {UmbrellaAsWritten, UmbrellaRelativeToRootModuleDirectory,
  232. Umbrella.dyn_cast<const DirectoryEntry *>()};
  233. }
  234. void Module::addTopHeader(const FileEntry *File) {
  235. assert(File);
  236. TopHeaders.insert(File);
  237. }
  238. ArrayRef<const FileEntry *> Module::getTopHeaders(FileManager &FileMgr) {
  239. if (!TopHeaderNames.empty()) {
  240. for (std::vector<std::string>::iterator
  241. I = TopHeaderNames.begin(), E = TopHeaderNames.end(); I != E; ++I) {
  242. if (auto FE = FileMgr.getFile(*I))
  243. TopHeaders.insert(*FE);
  244. }
  245. TopHeaderNames.clear();
  246. }
  247. return llvm::ArrayRef(TopHeaders.begin(), TopHeaders.end());
  248. }
  249. bool Module::directlyUses(const Module *Requested) {
  250. auto *Top = getTopLevelModule();
  251. // A top-level module implicitly uses itself.
  252. if (Requested->isSubModuleOf(Top))
  253. return true;
  254. for (auto *Use : Top->DirectUses)
  255. if (Requested->isSubModuleOf(Use))
  256. return true;
  257. // Anyone is allowed to use our builtin stddef.h and its accompanying module.
  258. if (!Requested->Parent && Requested->Name == "_Builtin_stddef_max_align_t")
  259. return true;
  260. if (NoUndeclaredIncludes)
  261. UndeclaredUses.insert(Requested);
  262. return false;
  263. }
  264. void Module::addRequirement(StringRef Feature, bool RequiredState,
  265. const LangOptions &LangOpts,
  266. const TargetInfo &Target) {
  267. Requirements.push_back(Requirement(std::string(Feature), RequiredState));
  268. // If this feature is currently available, we're done.
  269. if (hasFeature(Feature, LangOpts, Target) == RequiredState)
  270. return;
  271. markUnavailable(/*Unimportable*/true);
  272. }
  273. void Module::markUnavailable(bool Unimportable) {
  274. auto needUpdate = [Unimportable](Module *M) {
  275. return M->IsAvailable || (!M->IsUnimportable && Unimportable);
  276. };
  277. if (!needUpdate(this))
  278. return;
  279. SmallVector<Module *, 2> Stack;
  280. Stack.push_back(this);
  281. while (!Stack.empty()) {
  282. Module *Current = Stack.back();
  283. Stack.pop_back();
  284. if (!needUpdate(Current))
  285. continue;
  286. Current->IsAvailable = false;
  287. Current->IsUnimportable |= Unimportable;
  288. for (submodule_iterator Sub = Current->submodule_begin(),
  289. SubEnd = Current->submodule_end();
  290. Sub != SubEnd; ++Sub) {
  291. if (needUpdate(*Sub))
  292. Stack.push_back(*Sub);
  293. }
  294. }
  295. }
  296. Module *Module::findSubmodule(StringRef Name) const {
  297. llvm::StringMap<unsigned>::const_iterator Pos = SubModuleIndex.find(Name);
  298. if (Pos == SubModuleIndex.end())
  299. return nullptr;
  300. return SubModules[Pos->getValue()];
  301. }
  302. Module *Module::findOrInferSubmodule(StringRef Name) {
  303. llvm::StringMap<unsigned>::const_iterator Pos = SubModuleIndex.find(Name);
  304. if (Pos != SubModuleIndex.end())
  305. return SubModules[Pos->getValue()];
  306. if (!InferSubmodules)
  307. return nullptr;
  308. Module *Result = new Module(Name, SourceLocation(), this, false, InferExplicitSubmodules, 0);
  309. Result->InferExplicitSubmodules = InferExplicitSubmodules;
  310. Result->InferSubmodules = InferSubmodules;
  311. Result->InferExportWildcard = InferExportWildcard;
  312. if (Result->InferExportWildcard)
  313. Result->Exports.push_back(Module::ExportDecl(nullptr, true));
  314. return Result;
  315. }
  316. void Module::getExportedModules(SmallVectorImpl<Module *> &Exported) const {
  317. // All non-explicit submodules are exported.
  318. for (std::vector<Module *>::const_iterator I = SubModules.begin(),
  319. E = SubModules.end();
  320. I != E; ++I) {
  321. Module *Mod = *I;
  322. if (!Mod->IsExplicit)
  323. Exported.push_back(Mod);
  324. }
  325. // Find re-exported modules by filtering the list of imported modules.
  326. bool AnyWildcard = false;
  327. bool UnrestrictedWildcard = false;
  328. SmallVector<Module *, 4> WildcardRestrictions;
  329. for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
  330. Module *Mod = Exports[I].getPointer();
  331. if (!Exports[I].getInt()) {
  332. // Export a named module directly; no wildcards involved.
  333. Exported.push_back(Mod);
  334. continue;
  335. }
  336. // Wildcard export: export all of the imported modules that match
  337. // the given pattern.
  338. AnyWildcard = true;
  339. if (UnrestrictedWildcard)
  340. continue;
  341. if (Module *Restriction = Exports[I].getPointer())
  342. WildcardRestrictions.push_back(Restriction);
  343. else {
  344. WildcardRestrictions.clear();
  345. UnrestrictedWildcard = true;
  346. }
  347. }
  348. // If there were any wildcards, push any imported modules that were
  349. // re-exported by the wildcard restriction.
  350. if (!AnyWildcard)
  351. return;
  352. for (unsigned I = 0, N = Imports.size(); I != N; ++I) {
  353. Module *Mod = Imports[I];
  354. bool Acceptable = UnrestrictedWildcard;
  355. if (!Acceptable) {
  356. // Check whether this module meets one of the restrictions.
  357. for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
  358. Module *Restriction = WildcardRestrictions[R];
  359. if (Mod == Restriction || Mod->isSubModuleOf(Restriction)) {
  360. Acceptable = true;
  361. break;
  362. }
  363. }
  364. }
  365. if (!Acceptable)
  366. continue;
  367. Exported.push_back(Mod);
  368. }
  369. }
  370. void Module::buildVisibleModulesCache() const {
  371. assert(VisibleModulesCache.empty() && "cache does not need building");
  372. // This module is visible to itself.
  373. VisibleModulesCache.insert(this);
  374. // Every imported module is visible.
  375. SmallVector<Module *, 16> Stack(Imports.begin(), Imports.end());
  376. while (!Stack.empty()) {
  377. Module *CurrModule = Stack.pop_back_val();
  378. // Every module transitively exported by an imported module is visible.
  379. if (VisibleModulesCache.insert(CurrModule).second)
  380. CurrModule->getExportedModules(Stack);
  381. }
  382. }
  383. void Module::print(raw_ostream &OS, unsigned Indent, bool Dump) const {
  384. OS.indent(Indent);
  385. if (IsFramework)
  386. OS << "framework ";
  387. if (IsExplicit)
  388. OS << "explicit ";
  389. OS << "module ";
  390. printModuleId(OS, &Name, &Name + 1);
  391. if (IsSystem || IsExternC) {
  392. OS.indent(Indent + 2);
  393. if (IsSystem)
  394. OS << " [system]";
  395. if (IsExternC)
  396. OS << " [extern_c]";
  397. }
  398. OS << " {\n";
  399. if (!Requirements.empty()) {
  400. OS.indent(Indent + 2);
  401. OS << "requires ";
  402. for (unsigned I = 0, N = Requirements.size(); I != N; ++I) {
  403. if (I)
  404. OS << ", ";
  405. if (!Requirements[I].second)
  406. OS << "!";
  407. OS << Requirements[I].first;
  408. }
  409. OS << "\n";
  410. }
  411. if (Header H = getUmbrellaHeader()) {
  412. OS.indent(Indent + 2);
  413. OS << "umbrella header \"";
  414. OS.write_escaped(H.NameAsWritten);
  415. OS << "\"\n";
  416. } else if (DirectoryName D = getUmbrellaDir()) {
  417. OS.indent(Indent + 2);
  418. OS << "umbrella \"";
  419. OS.write_escaped(D.NameAsWritten);
  420. OS << "\"\n";
  421. }
  422. if (!ConfigMacros.empty() || ConfigMacrosExhaustive) {
  423. OS.indent(Indent + 2);
  424. OS << "config_macros ";
  425. if (ConfigMacrosExhaustive)
  426. OS << "[exhaustive]";
  427. for (unsigned I = 0, N = ConfigMacros.size(); I != N; ++I) {
  428. if (I)
  429. OS << ", ";
  430. OS << ConfigMacros[I];
  431. }
  432. OS << "\n";
  433. }
  434. struct {
  435. StringRef Prefix;
  436. HeaderKind Kind;
  437. } Kinds[] = {{"", HK_Normal},
  438. {"textual ", HK_Textual},
  439. {"private ", HK_Private},
  440. {"private textual ", HK_PrivateTextual},
  441. {"exclude ", HK_Excluded}};
  442. for (auto &K : Kinds) {
  443. assert(&K == &Kinds[K.Kind] && "kinds in wrong order");
  444. for (auto &H : Headers[K.Kind]) {
  445. OS.indent(Indent + 2);
  446. OS << K.Prefix << "header \"";
  447. OS.write_escaped(H.NameAsWritten);
  448. OS << "\" { size " << H.Entry->getSize()
  449. << " mtime " << H.Entry->getModificationTime() << " }\n";
  450. }
  451. }
  452. for (auto *Unresolved : {&UnresolvedHeaders, &MissingHeaders}) {
  453. for (auto &U : *Unresolved) {
  454. OS.indent(Indent + 2);
  455. OS << Kinds[U.Kind].Prefix << "header \"";
  456. OS.write_escaped(U.FileName);
  457. OS << "\"";
  458. if (U.Size || U.ModTime) {
  459. OS << " {";
  460. if (U.Size)
  461. OS << " size " << *U.Size;
  462. if (U.ModTime)
  463. OS << " mtime " << *U.ModTime;
  464. OS << " }";
  465. }
  466. OS << "\n";
  467. }
  468. }
  469. if (!ExportAsModule.empty()) {
  470. OS.indent(Indent + 2);
  471. OS << "export_as" << ExportAsModule << "\n";
  472. }
  473. for (submodule_const_iterator MI = submodule_begin(), MIEnd = submodule_end();
  474. MI != MIEnd; ++MI)
  475. // Print inferred subframework modules so that we don't need to re-infer
  476. // them (requires expensive directory iteration + stat calls) when we build
  477. // the module. Regular inferred submodules are OK, as we need to look at all
  478. // those header files anyway.
  479. if (!(*MI)->IsInferred || (*MI)->IsFramework)
  480. (*MI)->print(OS, Indent + 2, Dump);
  481. for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
  482. OS.indent(Indent + 2);
  483. OS << "export ";
  484. if (Module *Restriction = Exports[I].getPointer()) {
  485. OS << Restriction->getFullModuleName(true);
  486. if (Exports[I].getInt())
  487. OS << ".*";
  488. } else {
  489. OS << "*";
  490. }
  491. OS << "\n";
  492. }
  493. for (unsigned I = 0, N = UnresolvedExports.size(); I != N; ++I) {
  494. OS.indent(Indent + 2);
  495. OS << "export ";
  496. printModuleId(OS, UnresolvedExports[I].Id);
  497. if (UnresolvedExports[I].Wildcard)
  498. OS << (UnresolvedExports[I].Id.empty() ? "*" : ".*");
  499. OS << "\n";
  500. }
  501. if (Dump) {
  502. for (Module *M : Imports) {
  503. OS.indent(Indent + 2);
  504. llvm::errs() << "import " << M->getFullModuleName() << "\n";
  505. }
  506. }
  507. for (unsigned I = 0, N = DirectUses.size(); I != N; ++I) {
  508. OS.indent(Indent + 2);
  509. OS << "use ";
  510. OS << DirectUses[I]->getFullModuleName(true);
  511. OS << "\n";
  512. }
  513. for (unsigned I = 0, N = UnresolvedDirectUses.size(); I != N; ++I) {
  514. OS.indent(Indent + 2);
  515. OS << "use ";
  516. printModuleId(OS, UnresolvedDirectUses[I]);
  517. OS << "\n";
  518. }
  519. for (unsigned I = 0, N = LinkLibraries.size(); I != N; ++I) {
  520. OS.indent(Indent + 2);
  521. OS << "link ";
  522. if (LinkLibraries[I].IsFramework)
  523. OS << "framework ";
  524. OS << "\"";
  525. OS.write_escaped(LinkLibraries[I].Library);
  526. OS << "\"";
  527. }
  528. for (unsigned I = 0, N = UnresolvedConflicts.size(); I != N; ++I) {
  529. OS.indent(Indent + 2);
  530. OS << "conflict ";
  531. printModuleId(OS, UnresolvedConflicts[I].Id);
  532. OS << ", \"";
  533. OS.write_escaped(UnresolvedConflicts[I].Message);
  534. OS << "\"\n";
  535. }
  536. for (unsigned I = 0, N = Conflicts.size(); I != N; ++I) {
  537. OS.indent(Indent + 2);
  538. OS << "conflict ";
  539. OS << Conflicts[I].Other->getFullModuleName(true);
  540. OS << ", \"";
  541. OS.write_escaped(Conflicts[I].Message);
  542. OS << "\"\n";
  543. }
  544. if (InferSubmodules) {
  545. OS.indent(Indent + 2);
  546. if (InferExplicitSubmodules)
  547. OS << "explicit ";
  548. OS << "module * {\n";
  549. if (InferExportWildcard) {
  550. OS.indent(Indent + 4);
  551. OS << "export *\n";
  552. }
  553. OS.indent(Indent + 2);
  554. OS << "}\n";
  555. }
  556. OS.indent(Indent);
  557. OS << "}\n";
  558. }
  559. LLVM_DUMP_METHOD void Module::dump() const {
  560. print(llvm::errs(), 0, true);
  561. }
  562. void VisibleModuleSet::setVisible(Module *M, SourceLocation Loc,
  563. VisibleCallback Vis, ConflictCallback Cb) {
  564. // We can't import a global module fragment so the location can be invalid.
  565. assert((M->isGlobalModule() || Loc.isValid()) &&
  566. "setVisible expects a valid import location");
  567. if (isVisible(M))
  568. return;
  569. ++Generation;
  570. struct Visiting {
  571. Module *M;
  572. Visiting *ExportedBy;
  573. };
  574. std::function<void(Visiting)> VisitModule = [&](Visiting V) {
  575. // Nothing to do for a module that's already visible.
  576. unsigned ID = V.M->getVisibilityID();
  577. if (ImportLocs.size() <= ID)
  578. ImportLocs.resize(ID + 1);
  579. else if (ImportLocs[ID].isValid())
  580. return;
  581. ImportLocs[ID] = Loc;
  582. Vis(V.M);
  583. // Make any exported modules visible.
  584. SmallVector<Module *, 16> Exports;
  585. V.M->getExportedModules(Exports);
  586. for (Module *E : Exports) {
  587. // Don't import non-importable modules.
  588. if (!E->isUnimportable())
  589. VisitModule({E, &V});
  590. }
  591. for (auto &C : V.M->Conflicts) {
  592. if (isVisible(C.Other)) {
  593. llvm::SmallVector<Module*, 8> Path;
  594. for (Visiting *I = &V; I; I = I->ExportedBy)
  595. Path.push_back(I->M);
  596. Cb(Path, C.Other, C.Message);
  597. }
  598. }
  599. };
  600. VisitModule({M, nullptr});
  601. }
  602. ASTSourceDescriptor::ASTSourceDescriptor(Module &M)
  603. : Signature(M.Signature), ClangModule(&M) {
  604. if (M.Directory)
  605. Path = M.Directory->getName();
  606. if (auto File = M.getASTFile())
  607. ASTFile = File->getName();
  608. }
  609. std::string ASTSourceDescriptor::getModuleName() const {
  610. if (ClangModule)
  611. return ClangModule->Name;
  612. else
  613. return std::string(PCHModuleName);
  614. }