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