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