1 //===--- SemaModule.cpp - Semantic Analysis for Modules -------------------===//
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 implements semantic analysis for modules (C++ modules syntax,
10 //  Objective-C modules syntax, and Clang header modules).
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/Lex/HeaderSearch.h"
16 #include "clang/Lex/Preprocessor.h"
17 #include "clang/Sema/SemaInternal.h"
18 
19 using namespace clang;
20 using namespace sema;
21 
22 static void checkModuleImportContext(Sema &S, Module *M,
23                                      SourceLocation ImportLoc, DeclContext *DC,
24                                      bool FromInclude = false) {
25   SourceLocation ExternCLoc;
26 
27   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
28     switch (LSD->getLanguage()) {
29     case LinkageSpecDecl::lang_c:
30       if (ExternCLoc.isInvalid())
31         ExternCLoc = LSD->getBeginLoc();
32       break;
33     case LinkageSpecDecl::lang_cxx:
34       break;
35     }
36     DC = LSD->getParent();
37   }
38 
39   while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
40     DC = DC->getParent();
41 
42   if (!isa<TranslationUnitDecl>(DC)) {
43     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
44                           ? diag::ext_module_import_not_at_top_level_noop
45                           : diag::err_module_import_not_at_top_level_fatal)
46         << M->getFullModuleName() << DC;
47     S.Diag(cast<Decl>(DC)->getBeginLoc(),
48            diag::note_module_import_not_at_top_level)
49         << DC;
50   } else if (!M->IsExternC && ExternCLoc.isValid()) {
51     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
52       << M->getFullModuleName();
53     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
54   }
55 }
56 
57 // We represent the primary and partition names as 'Paths' which are sections
58 // of the hierarchical access path for a clang module.  However for C++20
59 // the periods in a name are just another character, and we will need to
60 // flatten them into a string.
61 static std::string stringFromPath(ModuleIdPath Path) {
62   std::string Name;
63   if (Path.empty())
64     return Name;
65 
66   for (auto &Piece : Path) {
67     if (!Name.empty())
68       Name += ".";
69     Name += Piece.first->getName();
70   }
71   return Name;
72 }
73 
74 Sema::DeclGroupPtrTy
75 Sema::ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc) {
76   if (!ModuleScopes.empty() &&
77       ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment) {
78     // Under -std=c++2a -fmodules-ts, we can find an explicit 'module;' after
79     // already implicitly entering the global module fragment. That's OK.
80     assert(getLangOpts().CPlusPlusModules && getLangOpts().ModulesTS &&
81            "unexpectedly encountered multiple global module fragment decls");
82     ModuleScopes.back().BeginLoc = ModuleLoc;
83     return nullptr;
84   }
85 
86   // We start in the global module; all those declarations are implicitly
87   // module-private (though they do not have module linkage).
88   Module *GlobalModule =
89       PushGlobalModuleFragment(ModuleLoc, /*IsImplicit=*/false);
90 
91   // All declarations created from now on are owned by the global module.
92   auto *TU = Context.getTranslationUnitDecl();
93   // [module.global.frag]p2
94   // A global-module-fragment specifies the contents of the global module
95   // fragment for a module unit. The global module fragment can be used to
96   // provide declarations that are attached to the global module and usable
97   // within the module unit.
98   //
99   // So the declations in the global module shouldn't be visible by default.
100   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ReachableWhenImported);
101   TU->setLocalOwningModule(GlobalModule);
102 
103   // FIXME: Consider creating an explicit representation of this declaration.
104   return nullptr;
105 }
106 
107 void Sema::HandleStartOfHeaderUnit() {
108   assert(getLangOpts().CPlusPlusModules &&
109          "Header units are only valid for C++20 modules");
110   SourceLocation StartOfTU =
111       SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
112 
113   StringRef HUName = getLangOpts().CurrentModule;
114   if (HUName.empty()) {
115     HUName = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())->getName();
116     const_cast<LangOptions &>(getLangOpts()).CurrentModule = HUName.str();
117   }
118 
119   // TODO: Make the C++20 header lookup independent.
120   // When the input is pre-processed source, we need a file ref to the original
121   // file for the header map.
122   auto F = SourceMgr.getFileManager().getFile(HUName);
123   // For the sake of error recovery (if someone has moved the original header
124   // after creating the pre-processed output) fall back to obtaining the file
125   // ref for the input file, which must be present.
126   if (!F)
127     F = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
128   assert(F && "failed to find the header unit source?");
129   Module::Header H{HUName.str(), HUName.str(), *F};
130   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
131   Module *Mod = Map.createHeaderUnit(StartOfTU, HUName, H);
132   assert(Mod && "module creation should not fail");
133   ModuleScopes.push_back({}); // No GMF
134   ModuleScopes.back().BeginLoc = StartOfTU;
135   ModuleScopes.back().Module = Mod;
136   ModuleScopes.back().ModuleInterface = true;
137   ModuleScopes.back().IsPartition = false;
138   VisibleModules.setVisible(Mod, StartOfTU);
139 
140   // From now on, we have an owning module for all declarations we see.
141   // All of these are implicitly exported.
142   auto *TU = Context.getTranslationUnitDecl();
143   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::Visible);
144   TU->setLocalOwningModule(Mod);
145 }
146 
147 Sema::DeclGroupPtrTy
148 Sema::ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc,
149                       ModuleDeclKind MDK, ModuleIdPath Path,
150                       ModuleIdPath Partition, ModuleImportState &ImportState) {
151   assert((getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules) &&
152          "should only have module decl in Modules TS or C++20");
153 
154   bool IsFirstDecl = ImportState == ModuleImportState::FirstDecl;
155   bool SeenGMF = ImportState == ModuleImportState::GlobalFragment;
156   // If any of the steps here fail, we count that as invalidating C++20
157   // module state;
158   ImportState = ModuleImportState::NotACXX20Module;
159 
160   bool IsPartition = !Partition.empty();
161   if (IsPartition)
162     switch (MDK) {
163     case ModuleDeclKind::Implementation:
164       MDK = ModuleDeclKind::PartitionImplementation;
165       break;
166     case ModuleDeclKind::Interface:
167       MDK = ModuleDeclKind::PartitionInterface;
168       break;
169     default:
170       llvm_unreachable("how did we get a partition type set?");
171     }
172 
173   // A (non-partition) module implementation unit requires that we are not
174   // compiling a module of any kind.  A partition implementation emits an
175   // interface (and the AST for the implementation), which will subsequently
176   // be consumed to emit a binary.
177   // A module interface unit requires that we are not compiling a module map.
178   switch (getLangOpts().getCompilingModule()) {
179   case LangOptions::CMK_None:
180     // It's OK to compile a module interface as a normal translation unit.
181     break;
182 
183   case LangOptions::CMK_ModuleInterface:
184     if (MDK != ModuleDeclKind::Implementation)
185       break;
186 
187     // We were asked to compile a module interface unit but this is a module
188     // implementation unit.
189     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
190       << FixItHint::CreateInsertion(ModuleLoc, "export ");
191     MDK = ModuleDeclKind::Interface;
192     break;
193 
194   case LangOptions::CMK_ModuleMap:
195     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
196     return nullptr;
197 
198   case LangOptions::CMK_HeaderModule:
199   case LangOptions::CMK_HeaderUnit:
200     Diag(ModuleLoc, diag::err_module_decl_in_header_module);
201     return nullptr;
202   }
203 
204   assert(ModuleScopes.size() <= 1 && "expected to be at global module scope");
205 
206   // FIXME: Most of this work should be done by the preprocessor rather than
207   // here, in order to support macro import.
208 
209   // Only one module-declaration is permitted per source file.
210   if (!ModuleScopes.empty() &&
211       ModuleScopes.back().Module->isModulePurview()) {
212     Diag(ModuleLoc, diag::err_module_redeclaration);
213     Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
214          diag::note_prev_module_declaration);
215     return nullptr;
216   }
217 
218   // Find the global module fragment we're adopting into this module, if any.
219   Module *GlobalModuleFragment = nullptr;
220   if (!ModuleScopes.empty() &&
221       ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment)
222     GlobalModuleFragment = ModuleScopes.back().Module;
223 
224   assert((!getLangOpts().CPlusPlusModules || getLangOpts().ModulesTS ||
225           SeenGMF == (bool)GlobalModuleFragment) &&
226          "mismatched global module state");
227 
228   // In C++20, the module-declaration must be the first declaration if there
229   // is no global module fragment.
230   if (getLangOpts().CPlusPlusModules && !IsFirstDecl && !SeenGMF) {
231     Diag(ModuleLoc, diag::err_module_decl_not_at_start);
232     SourceLocation BeginLoc =
233         ModuleScopes.empty()
234             ? SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID())
235             : ModuleScopes.back().BeginLoc;
236     if (BeginLoc.isValid()) {
237       Diag(BeginLoc, diag::note_global_module_introducer_missing)
238           << FixItHint::CreateInsertion(BeginLoc, "module;\n");
239     }
240   }
241 
242   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
243   // modules, the dots here are just another character that can appear in a
244   // module name.
245   std::string ModuleName = stringFromPath(Path);
246   if (IsPartition) {
247     ModuleName += ":";
248     ModuleName += stringFromPath(Partition);
249   }
250   // If a module name was explicitly specified on the command line, it must be
251   // correct.
252   if (!getLangOpts().CurrentModule.empty() &&
253       getLangOpts().CurrentModule != ModuleName) {
254     Diag(Path.front().second, diag::err_current_module_name_mismatch)
255         << SourceRange(Path.front().second, IsPartition
256                                                 ? Partition.back().second
257                                                 : Path.back().second)
258         << getLangOpts().CurrentModule;
259     return nullptr;
260   }
261   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
262 
263   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
264   Module *Mod;
265 
266   switch (MDK) {
267   case ModuleDeclKind::Interface:
268   case ModuleDeclKind::PartitionInterface: {
269     // We can't have parsed or imported a definition of this module or parsed a
270     // module map defining it already.
271     if (auto *M = Map.findModule(ModuleName)) {
272       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
273       if (M->DefinitionLoc.isValid())
274         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
275       else if (Optional<FileEntryRef> FE = M->getASTFile())
276         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
277             << FE->getName();
278       Mod = M;
279       break;
280     }
281 
282     // Create a Module for the module that we're defining.
283     Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
284                                            GlobalModuleFragment);
285     if (MDK == ModuleDeclKind::PartitionInterface)
286       Mod->Kind = Module::ModulePartitionInterface;
287     assert(Mod && "module creation should not fail");
288     break;
289   }
290 
291   case ModuleDeclKind::Implementation: {
292     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
293         PP.getIdentifierInfo(ModuleName), Path[0].second);
294     // C++20 A module-declaration that contains neither an export-
295     // keyword nor a module-partition implicitly imports the primary
296     // module interface unit of the module as if by a module-import-
297     // declaration.
298     Mod = getModuleLoader().loadModule(ModuleLoc, {ModuleNameLoc},
299                                        Module::AllVisible,
300                                        /*IsInclusionDirective=*/false);
301     if (!Mod) {
302       Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
303       // Create an empty module interface unit for error recovery.
304       Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
305                                              GlobalModuleFragment);
306     }
307   } break;
308 
309   case ModuleDeclKind::PartitionImplementation:
310     // Create an interface, but note that it is an implementation
311     // unit.
312     Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
313                                            GlobalModuleFragment);
314     Mod->Kind = Module::ModulePartitionImplementation;
315     break;
316   }
317 
318   if (!GlobalModuleFragment) {
319     ModuleScopes.push_back({});
320     if (getLangOpts().ModulesLocalVisibility)
321       ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
322   } else {
323     // We're done with the global module fragment now.
324     ActOnEndOfTranslationUnitFragment(TUFragmentKind::Global);
325   }
326 
327   // Switch from the global module fragment (if any) to the named module.
328   ModuleScopes.back().BeginLoc = StartLoc;
329   ModuleScopes.back().Module = Mod;
330   ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
331   ModuleScopes.back().IsPartition = IsPartition;
332   VisibleModules.setVisible(Mod, ModuleLoc);
333 
334   // From now on, we have an owning module for all declarations we see.
335   // In C++20 modules, those declaration would be reachable when imported
336   // unless explicitily exported.
337   // Otherwise, those declarations are module-private unless explicitly
338   // exported.
339   auto *TU = Context.getTranslationUnitDecl();
340   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ReachableWhenImported);
341   TU->setLocalOwningModule(Mod);
342 
343   // We are in the module purview, but before any other (non import)
344   // statements, so imports are allowed.
345   ImportState = ModuleImportState::ImportAllowed;
346 
347   // For an implementation, We already made an implicit import (its interface).
348   // Make and return the import decl to be added to the current TU.
349   if (MDK == ModuleDeclKind::Implementation) {
350     // Make the import decl for the interface.
351     ImportDecl *Import =
352         ImportDecl::Create(Context, CurContext, ModuleLoc, Mod, Path[0].second);
353     // and return it to be added.
354     return ConvertDeclToDeclGroup(Import);
355   }
356 
357   // FIXME: Create a ModuleDecl.
358   return nullptr;
359 }
360 
361 Sema::DeclGroupPtrTy
362 Sema::ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
363                                      SourceLocation PrivateLoc) {
364   // C++20 [basic.link]/2:
365   //   A private-module-fragment shall appear only in a primary module
366   //   interface unit.
367   switch (ModuleScopes.empty() ? Module::GlobalModuleFragment
368                                : ModuleScopes.back().Module->Kind) {
369   case Module::ModuleMapModule:
370   case Module::GlobalModuleFragment:
371   case Module::ModulePartitionImplementation:
372   case Module::ModulePartitionInterface:
373   case Module::ModuleHeaderUnit:
374     Diag(PrivateLoc, diag::err_private_module_fragment_not_module);
375     return nullptr;
376 
377   case Module::PrivateModuleFragment:
378     Diag(PrivateLoc, diag::err_private_module_fragment_redefined);
379     Diag(ModuleScopes.back().BeginLoc, diag::note_previous_definition);
380     return nullptr;
381 
382   case Module::ModuleInterfaceUnit:
383     break;
384   }
385 
386   if (!ModuleScopes.back().ModuleInterface) {
387     Diag(PrivateLoc, diag::err_private_module_fragment_not_module_interface);
388     Diag(ModuleScopes.back().BeginLoc,
389          diag::note_not_module_interface_add_export)
390         << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
391     return nullptr;
392   }
393 
394   // FIXME: Check this isn't a module interface partition.
395   // FIXME: Check that this translation unit does not import any partitions;
396   // such imports would violate [basic.link]/2's "shall be the only module unit"
397   // restriction.
398 
399   // We've finished the public fragment of the translation unit.
400   ActOnEndOfTranslationUnitFragment(TUFragmentKind::Normal);
401 
402   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
403   Module *PrivateModuleFragment =
404       Map.createPrivateModuleFragmentForInterfaceUnit(
405           ModuleScopes.back().Module, PrivateLoc);
406   assert(PrivateModuleFragment && "module creation should not fail");
407 
408   // Enter the scope of the private module fragment.
409   ModuleScopes.push_back({});
410   ModuleScopes.back().BeginLoc = ModuleLoc;
411   ModuleScopes.back().Module = PrivateModuleFragment;
412   ModuleScopes.back().ModuleInterface = true;
413   VisibleModules.setVisible(PrivateModuleFragment, ModuleLoc);
414 
415   // All declarations created from now on are scoped to the private module
416   // fragment (and are neither visible nor reachable in importers of the module
417   // interface).
418   auto *TU = Context.getTranslationUnitDecl();
419   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
420   TU->setLocalOwningModule(PrivateModuleFragment);
421 
422   // FIXME: Consider creating an explicit representation of this declaration.
423   return nullptr;
424 }
425 
426 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
427                                    SourceLocation ExportLoc,
428                                    SourceLocation ImportLoc, ModuleIdPath Path,
429                                    bool IsPartition) {
430 
431   bool Cxx20Mode = getLangOpts().CPlusPlusModules || getLangOpts().ModulesTS;
432   assert((!IsPartition || Cxx20Mode) && "partition seen in non-C++20 code?");
433 
434   // For a C++20 module name, flatten into a single identifier with the source
435   // location of the first component.
436   std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
437 
438   std::string ModuleName;
439   if (IsPartition) {
440     // We already checked that we are in a module purview in the parser.
441     assert(!ModuleScopes.empty() && "in a module purview, but no module?");
442     Module *NamedMod = ModuleScopes.back().Module;
443     // If we are importing into a partition, find the owning named module,
444     // otherwise, the name of the importing named module.
445     ModuleName = NamedMod->getPrimaryModuleInterfaceName().str();
446     ModuleName += ":";
447     ModuleName += stringFromPath(Path);
448     ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
449     Path = ModuleIdPath(ModuleNameLoc);
450   } else if (Cxx20Mode) {
451     ModuleName = stringFromPath(Path);
452     ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
453     Path = ModuleIdPath(ModuleNameLoc);
454   }
455 
456   // Diagnose self-import before attempting a load.
457   // [module.import]/9
458   // A module implementation unit of a module M that is not a module partition
459   // shall not contain a module-import-declaration nominating M.
460   // (for an implementation, the module interface is imported implicitly,
461   //  but that's handled in the module decl code).
462 
463   if (getLangOpts().CPlusPlusModules && isCurrentModulePurview() &&
464       getCurrentModule()->Name == ModuleName) {
465     Diag(ImportLoc, diag::err_module_self_import_cxx20)
466         << ModuleName << !ModuleScopes.back().ModuleInterface;
467     return true;
468   }
469 
470   Module *Mod = getModuleLoader().loadModule(
471       ImportLoc, Path, Module::AllVisible, /*IsInclusionDirective=*/false);
472   if (!Mod)
473     return true;
474 
475   return ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Mod, Path);
476 }
477 
478 /// Determine whether \p D is lexically within an export-declaration.
479 static const ExportDecl *getEnclosingExportDecl(const Decl *D) {
480   for (auto *DC = D->getLexicalDeclContext(); DC; DC = DC->getLexicalParent())
481     if (auto *ED = dyn_cast<ExportDecl>(DC))
482       return ED;
483   return nullptr;
484 }
485 
486 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
487                                    SourceLocation ExportLoc,
488                                    SourceLocation ImportLoc, Module *Mod,
489                                    ModuleIdPath Path) {
490   VisibleModules.setVisible(Mod, ImportLoc);
491 
492   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
493 
494   // FIXME: we should support importing a submodule within a different submodule
495   // of the same top-level module. Until we do, make it an error rather than
496   // silently ignoring the import.
497   // FIXME: Should we warn on a redundant import of the current module?
498   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
499       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) {
500     Diag(ImportLoc, getLangOpts().isCompilingModule()
501                         ? diag::err_module_self_import
502                         : diag::err_module_import_in_implementation)
503         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
504   }
505 
506   SmallVector<SourceLocation, 2> IdentifierLocs;
507 
508   if (Path.empty()) {
509     // If this was a header import, pad out with dummy locations.
510     // FIXME: Pass in and use the location of the header-name token in this
511     // case.
512     for (Module *ModCheck = Mod; ModCheck; ModCheck = ModCheck->Parent)
513       IdentifierLocs.push_back(SourceLocation());
514   } else if (getLangOpts().CPlusPlusModules && !Mod->Parent) {
515     // A single identifier for the whole name.
516     IdentifierLocs.push_back(Path[0].second);
517   } else {
518     Module *ModCheck = Mod;
519     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
520       // If we've run out of module parents, just drop the remaining
521       // identifiers.  We need the length to be consistent.
522       if (!ModCheck)
523         break;
524       ModCheck = ModCheck->Parent;
525 
526       IdentifierLocs.push_back(Path[I].second);
527     }
528   }
529 
530   ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
531                                           Mod, IdentifierLocs);
532   CurContext->addDecl(Import);
533 
534   // Sequence initialization of the imported module before that of the current
535   // module, if any.
536   if (!ModuleScopes.empty())
537     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
538 
539   // A module (partition) implementation unit shall not be exported.
540   if (getLangOpts().CPlusPlusModules && ExportLoc.isValid() &&
541       Mod->Kind == Module::ModuleKind::ModulePartitionImplementation) {
542     Diag(ExportLoc, diag::err_export_partition_impl)
543         << SourceRange(ExportLoc, Path.back().second);
544   } else if (!ModuleScopes.empty() &&
545              (ModuleScopes.back().ModuleInterface ||
546               (getLangOpts().CPlusPlusModules &&
547                ModuleScopes.back().Module->isGlobalModule()))) {
548     assert((!ModuleScopes.back().Module->isGlobalModule() ||
549             Mod->Kind == Module::ModuleKind::ModuleHeaderUnit) &&
550            "should only be importing a header unit into the GMF");
551     // Re-export the module if the imported module is exported.
552     // Note that we don't need to add re-exported module to Imports field
553     // since `Exports` implies the module is imported already.
554     if (ExportLoc.isValid() || getEnclosingExportDecl(Import))
555       getCurrentModule()->Exports.emplace_back(Mod, false);
556     else
557       getCurrentModule()->Imports.insert(Mod);
558   } else if (ExportLoc.isValid()) {
559     // [module.interface]p1:
560     // An export-declaration shall inhabit a namespace scope and appear in the
561     // purview of a module interface unit.
562     Diag(ExportLoc, diag::err_export_not_in_module_interface)
563         << (!ModuleScopes.empty() &&
564             !ModuleScopes.back().ImplicitGlobalModuleFragment);
565   } else if (getLangOpts().isCompilingModule()) {
566     Module *ThisModule = PP.getHeaderSearchInfo().lookupModule(
567         getLangOpts().CurrentModule, ExportLoc, false, false);
568     (void)ThisModule;
569     assert(ThisModule && "was expecting a module if building one");
570   }
571 
572   // In some cases we need to know if an entity was present in a directly-
573   // imported module (as opposed to a transitive import).  This avoids
574   // searching both Imports and Exports.
575   DirectModuleImports.insert(Mod);
576 
577   return Import;
578 }
579 
580 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
581   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
582   BuildModuleInclude(DirectiveLoc, Mod);
583 }
584 
585 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
586   // Determine whether we're in the #include buffer for a module. The #includes
587   // in that buffer do not qualify as module imports; they're just an
588   // implementation detail of us building the module.
589   //
590   // FIXME: Should we even get ActOnModuleInclude calls for those?
591   bool IsInModuleIncludes =
592       TUKind == TU_Module &&
593       getSourceManager().isWrittenInMainFile(DirectiveLoc);
594 
595   bool ShouldAddImport = !IsInModuleIncludes;
596 
597   // If this module import was due to an inclusion directive, create an
598   // implicit import declaration to capture it in the AST.
599   if (ShouldAddImport) {
600     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
601     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
602                                                      DirectiveLoc, Mod,
603                                                      DirectiveLoc);
604     if (!ModuleScopes.empty())
605       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
606     TU->addDecl(ImportD);
607     Consumer.HandleImplicitImportDecl(ImportD);
608   }
609 
610   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
611   VisibleModules.setVisible(Mod, DirectiveLoc);
612 
613   if (getLangOpts().isCompilingModule()) {
614     Module *ThisModule = PP.getHeaderSearchInfo().lookupModule(
615         getLangOpts().CurrentModule, DirectiveLoc, false, false);
616     (void)ThisModule;
617     assert(ThisModule && "was expecting a module if building one");
618   }
619 }
620 
621 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
622   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
623 
624   ModuleScopes.push_back({});
625   ModuleScopes.back().Module = Mod;
626   if (getLangOpts().ModulesLocalVisibility)
627     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
628 
629   VisibleModules.setVisible(Mod, DirectiveLoc);
630 
631   // The enclosing context is now part of this module.
632   // FIXME: Consider creating a child DeclContext to hold the entities
633   // lexically within the module.
634   if (getLangOpts().trackLocalOwningModule()) {
635     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
636       cast<Decl>(DC)->setModuleOwnershipKind(
637           getLangOpts().ModulesLocalVisibility
638               ? Decl::ModuleOwnershipKind::VisibleWhenImported
639               : Decl::ModuleOwnershipKind::Visible);
640       cast<Decl>(DC)->setLocalOwningModule(Mod);
641     }
642   }
643 }
644 
645 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
646   if (getLangOpts().ModulesLocalVisibility) {
647     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
648     // Leaving a module hides namespace names, so our visible namespace cache
649     // is now out of date.
650     VisibleNamespaceCache.clear();
651   }
652 
653   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
654          "left the wrong module scope");
655   ModuleScopes.pop_back();
656 
657   // We got to the end of processing a local module. Create an
658   // ImportDecl as we would for an imported module.
659   FileID File = getSourceManager().getFileID(EomLoc);
660   SourceLocation DirectiveLoc;
661   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
662     // We reached the end of a #included module header. Use the #include loc.
663     assert(File != getSourceManager().getMainFileID() &&
664            "end of submodule in main source file");
665     DirectiveLoc = getSourceManager().getIncludeLoc(File);
666   } else {
667     // We reached an EOM pragma. Use the pragma location.
668     DirectiveLoc = EomLoc;
669   }
670   BuildModuleInclude(DirectiveLoc, Mod);
671 
672   // Any further declarations are in whatever module we returned to.
673   if (getLangOpts().trackLocalOwningModule()) {
674     // The parser guarantees that this is the same context that we entered
675     // the module within.
676     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
677       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
678       if (!getCurrentModule())
679         cast<Decl>(DC)->setModuleOwnershipKind(
680             Decl::ModuleOwnershipKind::Unowned);
681     }
682   }
683 }
684 
685 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
686                                                       Module *Mod) {
687   // Bail if we're not allowed to implicitly import a module here.
688   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
689       VisibleModules.isVisible(Mod))
690     return;
691 
692   // Create the implicit import declaration.
693   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
694   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
695                                                    Loc, Mod, Loc);
696   TU->addDecl(ImportD);
697   Consumer.HandleImplicitImportDecl(ImportD);
698 
699   // Make the module visible.
700   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
701   VisibleModules.setVisible(Mod, Loc);
702 }
703 
704 /// We have parsed the start of an export declaration, including the '{'
705 /// (if present).
706 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
707                                  SourceLocation LBraceLoc) {
708   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
709 
710   // Set this temporarily so we know the export-declaration was braced.
711   D->setRBraceLoc(LBraceLoc);
712 
713   CurContext->addDecl(D);
714   PushDeclContext(S, D);
715 
716   // C++2a [module.interface]p1:
717   //   An export-declaration shall appear only [...] in the purview of a module
718   //   interface unit. An export-declaration shall not appear directly or
719   //   indirectly within [...] a private-module-fragment.
720   if (ModuleScopes.empty() || !ModuleScopes.back().Module->isModulePurview()) {
721     Diag(ExportLoc, diag::err_export_not_in_module_interface) << 0;
722     D->setInvalidDecl();
723     return D;
724   } else if (!ModuleScopes.back().ModuleInterface) {
725     Diag(ExportLoc, diag::err_export_not_in_module_interface) << 1;
726     Diag(ModuleScopes.back().BeginLoc,
727          diag::note_not_module_interface_add_export)
728         << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
729     D->setInvalidDecl();
730     return D;
731   } else if (ModuleScopes.back().Module->Kind ==
732              Module::PrivateModuleFragment) {
733     Diag(ExportLoc, diag::err_export_in_private_module_fragment);
734     Diag(ModuleScopes.back().BeginLoc, diag::note_private_module_fragment);
735     D->setInvalidDecl();
736     return D;
737   }
738 
739   for (const DeclContext *DC = CurContext; DC; DC = DC->getLexicalParent()) {
740     if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
741       //   An export-declaration shall not appear directly or indirectly within
742       //   an unnamed namespace [...]
743       if (ND->isAnonymousNamespace()) {
744         Diag(ExportLoc, diag::err_export_within_anonymous_namespace);
745         Diag(ND->getLocation(), diag::note_anonymous_namespace);
746         // Don't diagnose internal-linkage declarations in this region.
747         D->setInvalidDecl();
748         return D;
749       }
750 
751       //   A declaration is exported if it is [...] a namespace-definition
752       //   that contains an exported declaration.
753       //
754       // Defer exporting the namespace until after we leave it, in order to
755       // avoid marking all subsequent declarations in the namespace as exported.
756       if (!DeferredExportedNamespaces.insert(ND).second)
757         break;
758     }
759   }
760 
761   //   [...] its declaration or declaration-seq shall not contain an
762   //   export-declaration.
763   if (auto *ED = getEnclosingExportDecl(D)) {
764     Diag(ExportLoc, diag::err_export_within_export);
765     if (ED->hasBraces())
766       Diag(ED->getLocation(), diag::note_export);
767     D->setInvalidDecl();
768     return D;
769   }
770 
771   D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
772   return D;
773 }
774 
775 static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
776                                      SourceLocation BlockStart);
777 
778 namespace {
779 enum class UnnamedDeclKind {
780   Empty,
781   StaticAssert,
782   Asm,
783   UsingDirective,
784   Namespace,
785   Context
786 };
787 }
788 
789 static llvm::Optional<UnnamedDeclKind> getUnnamedDeclKind(Decl *D) {
790   if (isa<EmptyDecl>(D))
791     return UnnamedDeclKind::Empty;
792   if (isa<StaticAssertDecl>(D))
793     return UnnamedDeclKind::StaticAssert;
794   if (isa<FileScopeAsmDecl>(D))
795     return UnnamedDeclKind::Asm;
796   if (isa<UsingDirectiveDecl>(D))
797     return UnnamedDeclKind::UsingDirective;
798   // Everything else either introduces one or more names or is ill-formed.
799   return llvm::None;
800 }
801 
802 unsigned getUnnamedDeclDiag(UnnamedDeclKind UDK, bool InBlock) {
803   switch (UDK) {
804   case UnnamedDeclKind::Empty:
805   case UnnamedDeclKind::StaticAssert:
806     // Allow empty-declarations and static_asserts in an export block as an
807     // extension.
808     return InBlock ? diag::ext_export_no_name_block : diag::err_export_no_name;
809 
810   case UnnamedDeclKind::UsingDirective:
811     // Allow exporting using-directives as an extension.
812     return diag::ext_export_using_directive;
813 
814   case UnnamedDeclKind::Namespace:
815     // Anonymous namespace with no content.
816     return diag::introduces_no_names;
817 
818   case UnnamedDeclKind::Context:
819     // Allow exporting DeclContexts that transitively contain no declarations
820     // as an extension.
821     return diag::ext_export_no_names;
822 
823   case UnnamedDeclKind::Asm:
824     return diag::err_export_no_name;
825   }
826   llvm_unreachable("unknown kind");
827 }
828 
829 static void diagExportedUnnamedDecl(Sema &S, UnnamedDeclKind UDK, Decl *D,
830                                     SourceLocation BlockStart) {
831   S.Diag(D->getLocation(), getUnnamedDeclDiag(UDK, BlockStart.isValid()))
832       << (unsigned)UDK;
833   if (BlockStart.isValid())
834     S.Diag(BlockStart, diag::note_export);
835 }
836 
837 /// Check that it's valid to export \p D.
838 static bool checkExportedDecl(Sema &S, Decl *D, SourceLocation BlockStart) {
839   // C++2a [module.interface]p3:
840   //   An exported declaration shall declare at least one name
841   if (auto UDK = getUnnamedDeclKind(D))
842     diagExportedUnnamedDecl(S, *UDK, D, BlockStart);
843 
844   //   [...] shall not declare a name with internal linkage.
845   bool HasName = false;
846   if (auto *ND = dyn_cast<NamedDecl>(D)) {
847     // Don't diagnose anonymous union objects; we'll diagnose their members
848     // instead.
849     HasName = (bool)ND->getDeclName();
850     if (HasName && ND->getFormalLinkage() == InternalLinkage) {
851       S.Diag(ND->getLocation(), diag::err_export_internal) << ND;
852       if (BlockStart.isValid())
853         S.Diag(BlockStart, diag::note_export);
854     }
855   }
856 
857   // C++2a [module.interface]p5:
858   //   all entities to which all of the using-declarators ultimately refer
859   //   shall have been introduced with a name having external linkage
860   if (auto *USD = dyn_cast<UsingShadowDecl>(D)) {
861     NamedDecl *Target = USD->getUnderlyingDecl();
862     Linkage Lk = Target->getFormalLinkage();
863     if (Lk == InternalLinkage || Lk == ModuleLinkage) {
864       S.Diag(USD->getLocation(), diag::err_export_using_internal)
865           << (Lk == InternalLinkage ? 0 : 1) << Target;
866       S.Diag(Target->getLocation(), diag::note_using_decl_target);
867       if (BlockStart.isValid())
868         S.Diag(BlockStart, diag::note_export);
869     }
870   }
871 
872   // Recurse into namespace-scope DeclContexts. (Only namespace-scope
873   // declarations are exported.).
874   if (auto *DC = dyn_cast<DeclContext>(D)) {
875     if (isa<NamespaceDecl>(D) && DC->decls().empty()) {
876       if (!HasName)
877         // We don't allow an empty anonymous namespace (we don't allow decls
878         // in them either, but that's handled in the recursion).
879         diagExportedUnnamedDecl(S, UnnamedDeclKind::Namespace, D, BlockStart);
880       // We allow an empty named namespace decl.
881     } else if (DC->getRedeclContext()->isFileContext() && !isa<EnumDecl>(D))
882       return checkExportedDeclContext(S, DC, BlockStart);
883   }
884   return false;
885 }
886 
887 /// Check that it's valid to export all the declarations in \p DC.
888 static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
889                                      SourceLocation BlockStart) {
890   bool AllUnnamed = true;
891   for (auto *D : DC->decls())
892     AllUnnamed &= checkExportedDecl(S, D, BlockStart);
893   return AllUnnamed;
894 }
895 
896 /// Complete the definition of an export declaration.
897 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
898   auto *ED = cast<ExportDecl>(D);
899   if (RBraceLoc.isValid())
900     ED->setRBraceLoc(RBraceLoc);
901 
902   PopDeclContext();
903 
904   if (!D->isInvalidDecl()) {
905     SourceLocation BlockStart =
906         ED->hasBraces() ? ED->getBeginLoc() : SourceLocation();
907     for (auto *Child : ED->decls()) {
908       if (checkExportedDecl(*this, Child, BlockStart)) {
909         // If a top-level child is a linkage-spec declaration, it might contain
910         // no declarations (transitively), in which case it's ill-formed.
911         diagExportedUnnamedDecl(*this, UnnamedDeclKind::Context, Child,
912                                 BlockStart);
913       }
914     }
915   }
916 
917   return D;
918 }
919 
920 Module *Sema::PushGlobalModuleFragment(SourceLocation BeginLoc,
921                                        bool IsImplicit) {
922   // We shouldn't create new global module fragment if there is already
923   // one.
924   if (!GlobalModuleFragment) {
925     ModuleMap &Map = PP.getHeaderSearchInfo().getModuleMap();
926     GlobalModuleFragment = Map.createGlobalModuleFragmentForModuleUnit(
927         BeginLoc, getCurrentModule());
928   }
929 
930   assert(GlobalModuleFragment && "module creation should not fail");
931 
932   // Enter the scope of the global module.
933   ModuleScopes.push_back({BeginLoc, GlobalModuleFragment,
934                           /*ModuleInterface=*/false,
935                           /*IsPartition=*/false,
936                           /*ImplicitGlobalModuleFragment=*/IsImplicit,
937                           /*OuterVisibleModules=*/{}});
938   VisibleModules.setVisible(GlobalModuleFragment, BeginLoc);
939 
940   return GlobalModuleFragment;
941 }
942 
943 void Sema::PopGlobalModuleFragment() {
944   assert(!ModuleScopes.empty() && getCurrentModule()->isGlobalModule() &&
945          "left the wrong module scope, which is not global module fragment");
946   ModuleScopes.pop_back();
947 }
948 
949 bool Sema::isModuleUnitOfCurrentTU(const Module *M) const {
950   assert(M);
951 
952   Module *CurrentModuleUnit = getCurrentModule();
953 
954   // If we are not in a module currently, M must not be the module unit of
955   // current TU.
956   if (!CurrentModuleUnit)
957     return false;
958 
959   return M->isSubModuleOf(CurrentModuleUnit->getTopLevelModule());
960 }
961