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/AST/DynamicRecursiveASTVisitor.h"
17#include "clang/Lex/HeaderSearch.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/Sema/ParsedAttr.h"
20#include "clang/Sema/SemaInternal.h"
21#include "llvm/ADT/ScopeExit.h"
22#include "llvm/ADT/StringExtras.h"
23
24using namespace clang;
25using namespace sema;
26
27static void checkModuleImportContext(Sema &S, Module *M,
28 SourceLocation ImportLoc, DeclContext *DC,
29 bool FromInclude = false) {
30 SourceLocation ExternCLoc;
31
32 if (auto *LSD = dyn_cast<LinkageSpecDecl>(Val: DC)) {
33 switch (LSD->getLanguage()) {
34 case LinkageSpecLanguageIDs::C:
35 if (ExternCLoc.isInvalid())
36 ExternCLoc = LSD->getBeginLoc();
37 break;
38 case LinkageSpecLanguageIDs::CXX:
39 break;
40 }
41 DC = LSD->getParent();
42 }
43
44 while (isa<LinkageSpecDecl>(Val: DC) || isa<ExportDecl>(Val: DC))
45 DC = DC->getParent();
46
47 if (!isa<TranslationUnitDecl>(Val: DC)) {
48 S.Diag(Loc: ImportLoc, DiagID: (FromInclude && S.isModuleVisible(M))
49 ? diag::ext_module_import_not_at_top_level_noop
50 : diag::err_module_import_not_at_top_level_fatal)
51 << M->getFullModuleName() << DC;
52 S.Diag(Loc: cast<Decl>(Val: DC)->getBeginLoc(),
53 DiagID: diag::note_module_import_not_at_top_level)
54 << DC;
55 } else if (!M->IsExternC && ExternCLoc.isValid()) {
56 S.Diag(Loc: ImportLoc, DiagID: diag::ext_module_import_in_extern_c)
57 << M->getFullModuleName();
58 S.Diag(Loc: ExternCLoc, DiagID: diag::note_extern_c_begins_here);
59 }
60}
61
62/// Helper function for makeTransitiveImportsVisible to decide whether
63/// the \param Imported module unit is in the same module with the \param
64/// CurrentModule.
65/// \param FoundPrimaryModuleInterface is a helper parameter to record the
66/// primary module interface unit corresponding to the module \param
67/// CurrentModule. Since currently it is expensive to decide whether two module
68/// units come from the same module by comparing the module name.
69static bool
70isImportingModuleUnitFromSameModule(ASTContext &Ctx, Module *Imported,
71 Module *CurrentModule,
72 Module *&FoundPrimaryModuleInterface) {
73 if (!Imported->isNamedModule())
74 return false;
75
76 // The a partition unit we're importing must be in the same module of the
77 // current module.
78 if (Imported->isModulePartition())
79 return true;
80
81 // If we found the primary module interface during the search process, we can
82 // return quickly to avoid expensive string comparison.
83 if (FoundPrimaryModuleInterface)
84 return Imported == FoundPrimaryModuleInterface;
85
86 if (!CurrentModule)
87 return false;
88
89 // Then the imported module must be a primary module interface unit. It
90 // is only allowed to import the primary module interface unit from the same
91 // module in the implementation unit and the implementation partition unit.
92
93 // Since we'll handle implementation unit above. We can only care
94 // about the implementation partition unit here.
95 if (!CurrentModule->isModulePartitionImplementation())
96 return false;
97
98 if (Ctx.isInSameModule(M1: Imported, M2: CurrentModule)) {
99 assert(!FoundPrimaryModuleInterface ||
100 FoundPrimaryModuleInterface == Imported);
101 FoundPrimaryModuleInterface = Imported;
102 return true;
103 }
104
105 return false;
106}
107
108/// [module.import]p7:
109/// Additionally, when a module-import-declaration in a module unit of some
110/// module M imports another module unit U of M, it also imports all
111/// translation units imported by non-exported module-import-declarations in
112/// the module unit purview of U. These rules can in turn lead to the
113/// importation of yet more translation units.
114static void
115makeTransitiveImportsVisible(ASTContext &Ctx, VisibleModuleSet &VisibleModules,
116 Module *Imported, Module *CurrentModule,
117 SourceLocation ImportLoc,
118 bool IsImportingPrimaryModuleInterface = false) {
119 assert(Imported->isNamedModule() &&
120 "'makeTransitiveImportsVisible()' is intended for standard C++ named "
121 "modules only.");
122
123 llvm::SmallVector<Module *, 4> Worklist;
124 llvm::SmallPtrSet<Module *, 16> Visited;
125 Worklist.push_back(Elt: Imported);
126
127 Module *FoundPrimaryModuleInterface =
128 IsImportingPrimaryModuleInterface ? Imported : nullptr;
129
130 while (!Worklist.empty()) {
131 Module *Importing = Worklist.pop_back_val();
132
133 if (Visited.count(Ptr: Importing))
134 continue;
135 Visited.insert(Ptr: Importing);
136
137 // FIXME: The ImportLoc here is not meaningful. It may be problematic if we
138 // use the sourcelocation loaded from the visible modules.
139 VisibleModules.setVisible(M: Importing, Loc: ImportLoc);
140
141 if (isImportingModuleUnitFromSameModule(Ctx, Imported: Importing, CurrentModule,
142 FoundPrimaryModuleInterface)) {
143 for (Module *TransImported : Importing->Imports)
144 Worklist.push_back(Elt: TransImported);
145
146 for (auto [Exports, _] : Importing->Exports)
147 Worklist.push_back(Elt: Exports);
148 }
149 }
150}
151
152Sema::DeclGroupPtrTy
153Sema::ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc) {
154 // We start in the global module;
155 Module *GlobalModule =
156 PushGlobalModuleFragment(BeginLoc: ModuleLoc);
157
158 // All declarations created from now on are owned by the global module.
159 auto *TU = Context.getTranslationUnitDecl();
160 // [module.global.frag]p2
161 // A global-module-fragment specifies the contents of the global module
162 // fragment for a module unit. The global module fragment can be used to
163 // provide declarations that are attached to the global module and usable
164 // within the module unit.
165 //
166 // So the declations in the global module shouldn't be visible by default.
167 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ReachableWhenImported);
168 TU->setLocalOwningModule(GlobalModule);
169
170 // FIXME: Consider creating an explicit representation of this declaration.
171 return nullptr;
172}
173
174void Sema::HandleStartOfHeaderUnit() {
175 assert(getLangOpts().CPlusPlusModules &&
176 "Header units are only valid for C++20 modules");
177 SourceLocation StartOfTU =
178 SourceMgr.getLocForStartOfFile(FID: SourceMgr.getMainFileID());
179
180 StringRef HUName = getLangOpts().CurrentModule;
181 if (HUName.empty()) {
182 HUName =
183 SourceMgr.getFileEntryRefForID(FID: SourceMgr.getMainFileID())->getName();
184 const_cast<LangOptions &>(getLangOpts()).CurrentModule = HUName.str();
185 }
186
187 // TODO: Make the C++20 header lookup independent.
188 // When the input is pre-processed source, we need a file ref to the original
189 // file for the header map.
190 auto F = SourceMgr.getFileManager().getOptionalFileRef(Filename: HUName);
191 // For the sake of error recovery (if someone has moved the original header
192 // after creating the pre-processed output) fall back to obtaining the file
193 // ref for the input file, which must be present.
194 if (!F)
195 F = SourceMgr.getFileEntryRefForID(FID: SourceMgr.getMainFileID());
196 assert(F && "failed to find the header unit source?");
197 Module::Header H{.NameAsWritten: HUName.str(), .PathRelativeToRootModuleDirectory: HUName.str(), .Entry: *F};
198 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
199 Module *Mod = Map.createHeaderUnit(Loc: StartOfTU, Name: HUName, H);
200 assert(Mod && "module creation should not fail");
201 ModuleScopes.push_back(Elt: {}); // No GMF
202 ModuleScopes.back().BeginLoc = StartOfTU;
203 ModuleScopes.back().Module = Mod;
204 VisibleModules.setVisible(M: Mod, Loc: StartOfTU);
205
206 // From now on, we have an owning module for all declarations we see.
207 // All of these are implicitly exported.
208 auto *TU = Context.getTranslationUnitDecl();
209 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::Visible);
210 TU->setLocalOwningModule(Mod);
211}
212
213/// Tests whether the given identifier is reserved as a module name and
214/// diagnoses if it is. Returns true if a diagnostic is emitted and false
215/// otherwise.
216static bool DiagReservedModuleName(Sema &S, const IdentifierInfo *II,
217 SourceLocation Loc) {
218 enum {
219 Valid = -1,
220 Invalid = 0,
221 Reserved = 1,
222 } Reason = Valid;
223
224 if (II->isStr(Str: "module") || II->isStr(Str: "import"))
225 Reason = Invalid;
226 else if (II->isReserved(LangOpts: S.getLangOpts()) !=
227 ReservedIdentifierStatus::NotReserved)
228 Reason = Reserved;
229
230 // If the identifier is reserved (not invalid) but is in a system header,
231 // we do not diagnose (because we expect system headers to use reserved
232 // identifiers).
233 if (Reason == Reserved && S.getSourceManager().isInSystemHeader(Loc))
234 Reason = Valid;
235
236 switch (Reason) {
237 case Valid:
238 return false;
239 case Invalid:
240 return S.Diag(Loc, DiagID: diag::err_invalid_module_name) << II;
241 case Reserved:
242 S.Diag(Loc, DiagID: diag::warn_reserved_module_name) << II;
243 return false;
244 }
245 llvm_unreachable("fell off a fully covered switch");
246}
247
248Sema::DeclGroupPtrTy
249Sema::ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc,
250 ModuleDeclKind MDK, ModuleIdPath Path,
251 ModuleIdPath Partition, ModuleImportState &ImportState,
252 bool SeenNoTrivialPPDirective) {
253 assert(getLangOpts().CPlusPlusModules &&
254 "should only have module decl in standard C++ modules");
255
256 bool IsFirstDecl = ImportState == ModuleImportState::FirstDecl;
257 bool SeenGMF = ImportState == ModuleImportState::GlobalFragment;
258 // If any of the steps here fail, we count that as invalidating C++20
259 // module state;
260 ImportState = ModuleImportState::NotACXX20Module;
261
262 bool IsPartition = !Partition.empty();
263 if (IsPartition)
264 switch (MDK) {
265 case ModuleDeclKind::Implementation:
266 MDK = ModuleDeclKind::PartitionImplementation;
267 break;
268 case ModuleDeclKind::Interface:
269 MDK = ModuleDeclKind::PartitionInterface;
270 break;
271 default:
272 llvm_unreachable("how did we get a partition type set?");
273 }
274
275 // A (non-partition) module implementation unit requires that we are not
276 // compiling a module of any kind. A partition implementation emits an
277 // interface (and the AST for the implementation), which will subsequently
278 // be consumed to emit a binary.
279 // A module interface unit requires that we are not compiling a module map.
280 switch (getLangOpts().getCompilingModule()) {
281 case LangOptions::CMK_None:
282 // It's OK to compile a module interface as a normal translation unit.
283 break;
284
285 case LangOptions::CMK_ModuleInterface:
286 if (MDK != ModuleDeclKind::Implementation)
287 break;
288
289 // We were asked to compile a module interface unit but this is a module
290 // implementation unit.
291 Diag(Loc: ModuleLoc, DiagID: diag::err_module_interface_implementation_mismatch)
292 << FixItHint::CreateInsertion(InsertionLoc: ModuleLoc, Code: "export ");
293 MDK = ModuleDeclKind::Interface;
294 break;
295
296 case LangOptions::CMK_ModuleMap:
297 Diag(Loc: ModuleLoc, DiagID: diag::err_module_decl_in_module_map_module);
298 return nullptr;
299
300 case LangOptions::CMK_HeaderUnit:
301 Diag(Loc: ModuleLoc, DiagID: diag::err_module_decl_in_header_unit);
302 return nullptr;
303 }
304
305 assert(ModuleScopes.size() <= 1 && "expected to be at global module scope");
306
307 // FIXME: Most of this work should be done by the preprocessor rather than
308 // here, in order to support macro import.
309
310 // Only one module-declaration is permitted per source file.
311 if (isCurrentModulePurview()) {
312 Diag(Loc: ModuleLoc, DiagID: diag::err_module_redeclaration);
313 Diag(Loc: VisibleModules.getImportLoc(M: ModuleScopes.back().Module),
314 DiagID: diag::note_prev_module_declaration);
315 return nullptr;
316 }
317
318 assert((!getLangOpts().CPlusPlusModules ||
319 SeenGMF == (bool)this->TheGlobalModuleFragment) &&
320 "mismatched global module state");
321
322 // In C++20, A module directive may only appear as the first preprocessing
323 // tokens in a file (excluding the global module fragment.).
324 if (getLangOpts().CPlusPlusModules &&
325 (!IsFirstDecl || SeenNoTrivialPPDirective) && !SeenGMF) {
326 Diag(Loc: ModuleLoc, DiagID: diag::err_module_decl_not_at_start);
327 SourceLocation BeginLoc = PP.getMainFileFirstPPTokenLoc();
328 Diag(Loc: BeginLoc, DiagID: diag::note_global_module_introducer_missing)
329 << FixItHint::CreateInsertion(InsertionLoc: BeginLoc, Code: "module;\n");
330 }
331
332 // C++23 [module.unit]p1: ... The identifiers module and import shall not
333 // appear as identifiers in a module-name or module-partition. All
334 // module-names either beginning with an identifier consisting of std
335 // followed by zero or more digits or containing a reserved identifier
336 // ([lex.name]) are reserved and shall not be specified in a
337 // module-declaration; no diagnostic is required.
338
339 // Test the first part of the path to see if it's std[0-9]+ but allow the
340 // name in a system header.
341 StringRef FirstComponentName = Path[0].getIdentifierInfo()->getName();
342 if (!getSourceManager().isInSystemHeader(Loc: Path[0].getLoc()) &&
343 (FirstComponentName == "std" ||
344 (FirstComponentName.starts_with(Prefix: "std") &&
345 llvm::all_of(Range: FirstComponentName.drop_front(N: 3), P: &llvm::isDigit))))
346 Diag(Loc: Path[0].getLoc(), DiagID: diag::warn_reserved_module_name)
347 << Path[0].getIdentifierInfo();
348
349 // Then test all of the components in the path to see if any of them are
350 // using another kind of reserved or invalid identifier.
351 for (auto Part : Path) {
352 if (DiagReservedModuleName(S&: *this, II: Part.getIdentifierInfo(), Loc: Part.getLoc()))
353 return nullptr;
354 }
355
356 // Flatten the dots in a module name. Unlike Clang's hierarchical module map
357 // modules, the dots here are just another character that can appear in a
358 // module name.
359 std::string ModuleName = ModuleLoader::getFlatNameFromPath(Path);
360 if (IsPartition) {
361 ModuleName += ":";
362 ModuleName += ModuleLoader::getFlatNameFromPath(Path: Partition);
363 }
364 // If a module name was explicitly specified on the command line, it must be
365 // correct.
366 if (!getLangOpts().CurrentModule.empty() &&
367 getLangOpts().CurrentModule != ModuleName) {
368 Diag(Loc: Path.front().getLoc(), DiagID: diag::err_current_module_name_mismatch)
369 << SourceRange(Path.front().getLoc(), IsPartition
370 ? Partition.back().getLoc()
371 : Path.back().getLoc())
372 << getLangOpts().CurrentModule;
373 return nullptr;
374 }
375 const_cast<LangOptions &>(getLangOpts()).CurrentModule = ModuleName;
376
377 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
378 Module *Mod; // The module we are creating.
379 Module *Interface = nullptr; // The interface for an implementation.
380 switch (MDK) {
381 case ModuleDeclKind::Interface:
382 case ModuleDeclKind::PartitionInterface: {
383 // We can't have parsed or imported a definition of this module or parsed a
384 // module map defining it already.
385 if (auto *M = Map.findOrLoadModule(Name: ModuleName)) {
386 Diag(Loc: Path[0].getLoc(), DiagID: diag::err_module_redefinition) << ModuleName;
387 if (M->DefinitionLoc.isValid())
388 Diag(Loc: M->DefinitionLoc, DiagID: diag::note_prev_module_definition);
389 else if (const ModuleFileName *FileName = M->getASTFileName())
390 Diag(Loc: M->DefinitionLoc, DiagID: diag::note_prev_module_definition_from_ast_file)
391 << *FileName;
392 Mod = M;
393 break;
394 }
395
396 // Create a Module for the module that we're defining.
397 Mod = Map.createModuleForInterfaceUnit(Loc: ModuleLoc, Name: ModuleName);
398 if (MDK == ModuleDeclKind::PartitionInterface)
399 Mod->Kind = Module::ModulePartitionInterface;
400 assert(Mod && "module creation should not fail");
401 break;
402 }
403
404 case ModuleDeclKind::Implementation: {
405 // C++20 A module-declaration that contains neither an export-
406 // keyword nor a module-partition implicitly imports the primary
407 // module interface unit of the module as if by a module-import-
408 // declaration.
409 IdentifierLoc ModuleNameLoc(Path[0].getLoc(),
410 PP.getIdentifierInfo(Name: ModuleName));
411
412 // The module loader will assume we're trying to import the module that
413 // we're building if `LangOpts.CurrentModule` equals to 'ModuleName'.
414 // Change the value for `LangOpts.CurrentModule` temporarily to make the
415 // module loader work properly.
416 const_cast<LangOptions &>(getLangOpts()).CurrentModule = "";
417 Interface = getModuleLoader().loadModule(ImportLoc: ModuleLoc, Path: {ModuleNameLoc},
418 Visibility: Module::AllVisible,
419 /*IsInclusionDirective=*/false);
420 const_cast<LangOptions &>(getLangOpts()).CurrentModule = ModuleName;
421
422 if (!Interface) {
423 Diag(Loc: ModuleLoc, DiagID: diag::err_module_not_defined) << ModuleName;
424 // Create an empty module interface unit for error recovery.
425 Mod = Map.createModuleForInterfaceUnit(Loc: ModuleLoc, Name: ModuleName);
426 } else {
427 Mod = Map.createModuleForImplementationUnit(Loc: ModuleLoc, Name: ModuleName);
428 }
429 } break;
430
431 case ModuleDeclKind::PartitionImplementation:
432 // Create an interface, but note that it is an implementation
433 // unit.
434 Mod = Map.createModuleForInterfaceUnit(Loc: ModuleLoc, Name: ModuleName);
435 Mod->Kind = Module::ModulePartitionImplementation;
436 break;
437 }
438
439 if (!this->TheGlobalModuleFragment) {
440 ModuleScopes.push_back(Elt: {});
441 if (getLangOpts().ModulesLocalVisibility)
442 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
443 } else {
444 // We're done with the global module fragment now.
445 ActOnEndOfTranslationUnitFragment(Kind: TUFragmentKind::Global);
446 }
447
448 // Switch from the global module fragment (if any) to the named module.
449 ModuleScopes.back().BeginLoc = StartLoc;
450 ModuleScopes.back().Module = Mod;
451 VisibleModules.setVisible(M: Mod, Loc: ModuleLoc);
452
453 // From now on, we have an owning module for all declarations we see.
454 // In C++20 modules, those declaration would be reachable when imported
455 // unless explicitily exported.
456 // Otherwise, those declarations are module-private unless explicitly
457 // exported.
458 auto *TU = Context.getTranslationUnitDecl();
459 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ReachableWhenImported);
460 TU->setLocalOwningModule(Mod);
461
462 // We are in the module purview, but before any other (non import)
463 // statements, so imports are allowed.
464 ImportState = ModuleImportState::ImportAllowed;
465
466 getASTContext().setCurrentNamedModule(Mod);
467
468 // We already potentially made an implicit import (in the case of a module
469 // implementation unit importing its interface). Make this module visible
470 // and return the import decl to be added to the current TU.
471 if (Interface) {
472 HadImportedNamedModules = true;
473
474 makeTransitiveImportsVisible(Ctx&: getASTContext(), VisibleModules, Imported: Interface,
475 CurrentModule: Mod, ImportLoc: ModuleLoc,
476 /*IsImportingPrimaryModuleInterface=*/true);
477
478 // Make the import decl for the interface in the impl module.
479 ImportDecl *Import = ImportDecl::Create(C&: Context, DC: CurContext, StartLoc: ModuleLoc,
480 Imported: Interface, IdentifierLocs: Path[0].getLoc());
481 CurContext->addDecl(D: Import);
482
483 // Sequence initialization of the imported module before that of the current
484 // module, if any.
485 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: Import);
486 Mod->Imports.insert(X: Interface); // As if we imported it.
487 // Also save this as a shortcut to checking for decls in the interface
488 ThePrimaryInterface = Interface;
489 // If we made an implicit import of the module interface, then return the
490 // imported module decl.
491 return ConvertDeclToDeclGroup(Ptr: Import);
492 }
493
494 return nullptr;
495}
496
497Sema::DeclGroupPtrTy
498Sema::ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
499 SourceLocation PrivateLoc) {
500 // C++20 [basic.link]/2:
501 // A private-module-fragment shall appear only in a primary module
502 // interface unit.
503 switch (ModuleScopes.empty() ? Module::ExplicitGlobalModuleFragment
504 : ModuleScopes.back().Module->Kind) {
505 case Module::ModuleMapModule:
506 case Module::ExplicitGlobalModuleFragment:
507 case Module::ImplicitGlobalModuleFragment:
508 case Module::ModulePartitionImplementation:
509 case Module::ModulePartitionInterface:
510 case Module::ModuleHeaderUnit:
511 Diag(Loc: PrivateLoc, DiagID: diag::err_private_module_fragment_not_module);
512 return nullptr;
513
514 case Module::PrivateModuleFragment:
515 Diag(Loc: PrivateLoc, DiagID: diag::err_private_module_fragment_redefined);
516 Diag(Loc: ModuleScopes.back().BeginLoc, DiagID: diag::note_previous_definition);
517 return nullptr;
518
519 case Module::ModuleImplementationUnit:
520 Diag(Loc: PrivateLoc, DiagID: diag::err_private_module_fragment_not_module_interface);
521 Diag(Loc: ModuleScopes.back().BeginLoc,
522 DiagID: diag::note_not_module_interface_add_export)
523 << FixItHint::CreateInsertion(InsertionLoc: ModuleScopes.back().BeginLoc, Code: "export ");
524 return nullptr;
525
526 case Module::ModuleInterfaceUnit:
527 break;
528 }
529
530 // FIXME: Check that this translation unit does not import any partitions;
531 // such imports would violate [basic.link]/2's "shall be the only module unit"
532 // restriction.
533
534 // We've finished the public fragment of the translation unit.
535 ActOnEndOfTranslationUnitFragment(Kind: TUFragmentKind::Normal);
536
537 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
538 Module *PrivateModuleFragment =
539 Map.createPrivateModuleFragmentForInterfaceUnit(
540 Parent: ModuleScopes.back().Module, Loc: PrivateLoc);
541 assert(PrivateModuleFragment && "module creation should not fail");
542
543 // Enter the scope of the private module fragment.
544 ModuleScopes.push_back(Elt: {});
545 ModuleScopes.back().BeginLoc = ModuleLoc;
546 ModuleScopes.back().Module = PrivateModuleFragment;
547 VisibleModules.setVisible(M: PrivateModuleFragment, Loc: ModuleLoc);
548
549 // All declarations created from now on are scoped to the private module
550 // fragment (and are neither visible nor reachable in importers of the module
551 // interface).
552 auto *TU = Context.getTranslationUnitDecl();
553 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
554 TU->setLocalOwningModule(PrivateModuleFragment);
555
556 // FIXME: Consider creating an explicit representation of this declaration.
557 return nullptr;
558}
559
560DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
561 SourceLocation ExportLoc,
562 SourceLocation ImportLoc, ModuleIdPath Path,
563 bool IsPartition) {
564 assert((!IsPartition || getLangOpts().CPlusPlusModules) &&
565 "partition seen in non-C++20 code?");
566
567 // For a C++20 module name, flatten into a single identifier with the source
568 // location of the first component.
569 IdentifierLoc ModuleNameLoc;
570
571 std::string ModuleName;
572 if (IsPartition) {
573 // We already checked that we are in a module purview in the parser.
574 assert(!ModuleScopes.empty() && "in a module purview, but no module?");
575 Module *NamedMod = ModuleScopes.back().Module;
576 // If we are importing into a partition, find the owning named module,
577 // otherwise, the name of the importing named module.
578 ModuleName = NamedMod->getPrimaryModuleInterfaceName().str();
579 ModuleName += ":";
580 ModuleName += ModuleLoader::getFlatNameFromPath(Path);
581 ModuleNameLoc =
582 IdentifierLoc(Path[0].getLoc(), PP.getIdentifierInfo(Name: ModuleName));
583 Path = ModuleIdPath(ModuleNameLoc);
584 } else if (getLangOpts().CPlusPlusModules) {
585 ModuleName = ModuleLoader::getFlatNameFromPath(Path);
586 ModuleNameLoc =
587 IdentifierLoc(Path[0].getLoc(), PP.getIdentifierInfo(Name: ModuleName));
588 Path = ModuleIdPath(ModuleNameLoc);
589 }
590
591 // Diagnose self-import before attempting a load.
592 // [module.import]/9
593 // A module implementation unit of a module M that is not a module partition
594 // shall not contain a module-import-declaration nominating M.
595 // (for an implementation, the module interface is imported implicitly,
596 // but that's handled in the module decl code).
597
598 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview() &&
599 getCurrentModule()->Name == ModuleName) {
600 Diag(Loc: ImportLoc, DiagID: diag::err_module_self_import_cxx20)
601 << ModuleName << currentModuleIsImplementation();
602 return true;
603 }
604
605 Module *Mod = getModuleLoader().loadModule(
606 ImportLoc, Path, Visibility: Module::AllVisible, /*IsInclusionDirective=*/false);
607 if (!Mod)
608 return true;
609
610 if (!Mod->isInterfaceOrPartition() && !ModuleName.empty() &&
611 !getLangOpts().ObjC) {
612 Diag(Loc: ImportLoc, DiagID: diag::err_module_import_non_interface_nor_parition)
613 << ModuleName;
614 return true;
615 }
616
617 return ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, M: Mod, Path);
618}
619
620/// Determine whether \p D is lexically within an export-declaration.
621static const ExportDecl *getEnclosingExportDecl(const Decl *D) {
622 for (auto *DC = D->getLexicalDeclContext(); DC; DC = DC->getLexicalParent())
623 if (auto *ED = dyn_cast<ExportDecl>(Val: DC))
624 return ED;
625 return nullptr;
626}
627
628DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
629 SourceLocation ExportLoc,
630 SourceLocation ImportLoc, Module *Mod,
631 ModuleIdPath Path) {
632 if (Mod->isHeaderUnit())
633 Diag(Loc: ImportLoc, DiagID: diag::warn_experimental_header_unit);
634
635 if (Mod->isNamedModule())
636 makeTransitiveImportsVisible(Ctx&: getASTContext(), VisibleModules, Imported: Mod,
637 CurrentModule: getCurrentModule(), ImportLoc);
638 else
639 VisibleModules.setVisible(M: Mod, Loc: ImportLoc);
640
641 assert((!Mod->isModulePartitionImplementation() || getCurrentModule()) &&
642 "We can only import a partition unit in a named module.");
643 if (Mod->isModulePartitionImplementation() &&
644 getCurrentModule()->isModuleInterfaceUnit())
645 Diag(Loc: ImportLoc,
646 DiagID: diag::warn_import_implementation_partition_unit_in_interface_unit)
647 << Mod->Name;
648
649 checkModuleImportContext(S&: *this, M: Mod, ImportLoc, DC: CurContext);
650
651 // FIXME: we should support importing a submodule within a different submodule
652 // of the same top-level module. Until we do, make it an error rather than
653 // silently ignoring the import.
654 // FIXME: Should we warn on a redundant import of the current module?
655 if (Mod->isForBuilding(LangOpts: getLangOpts())) {
656 Diag(Loc: ImportLoc, DiagID: getLangOpts().isCompilingModule()
657 ? diag::err_module_self_import
658 : diag::err_module_import_in_implementation)
659 << Mod->getFullModuleName() << getLangOpts().CurrentModule;
660 }
661
662 SmallVector<SourceLocation, 2> IdentifierLocs;
663
664 if (Path.empty()) {
665 // If this was a header import, pad out with dummy locations.
666 // FIXME: Pass in and use the location of the header-name token in this
667 // case.
668 for (Module *ModCheck = Mod; ModCheck; ModCheck = ModCheck->Parent)
669 IdentifierLocs.push_back(Elt: SourceLocation());
670 } else if (getLangOpts().CPlusPlusModules && !Mod->Parent) {
671 // A single identifier for the whole name.
672 IdentifierLocs.push_back(Elt: Path[0].getLoc());
673 } else {
674 Module *ModCheck = Mod;
675 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
676 // If we've run out of module parents, just drop the remaining
677 // identifiers. We need the length to be consistent.
678 if (!ModCheck)
679 break;
680 ModCheck = ModCheck->Parent;
681
682 IdentifierLocs.push_back(Elt: Path[I].getLoc());
683 }
684 }
685
686 ImportDecl *Import = ImportDecl::Create(C&: Context, DC: CurContext, StartLoc,
687 Imported: Mod, IdentifierLocs);
688 CurContext->addDecl(D: Import);
689
690 // Sequence initialization of the imported module before that of the current
691 // module, if any.
692 if (!ModuleScopes.empty())
693 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: Import);
694
695 // A module (partition) implementation unit shall not be exported.
696 if (getLangOpts().CPlusPlusModules && ExportLoc.isValid() &&
697 Mod->Kind == Module::ModuleKind::ModulePartitionImplementation) {
698 Diag(Loc: ExportLoc, DiagID: diag::err_export_partition_impl)
699 << SourceRange(ExportLoc, Path.back().getLoc());
700 } else if (ExportLoc.isValid() &&
701 (ModuleScopes.empty() || currentModuleIsImplementation())) {
702 // [module.interface]p1:
703 // An export-declaration shall inhabit a namespace scope and appear in the
704 // purview of a module interface unit.
705 Diag(Loc: ExportLoc, DiagID: diag::err_export_not_in_module_interface);
706 } else if (!ModuleScopes.empty()) {
707 // Re-export the module if the imported module is exported.
708 // Note that we don't need to add re-exported module to Imports field
709 // since `Exports` implies the module is imported already.
710 if (ExportLoc.isValid() || getEnclosingExportDecl(D: Import))
711 getCurrentModule()->Exports.emplace_back(Args&: Mod, Args: false);
712 else
713 getCurrentModule()->Imports.insert(X: Mod);
714 }
715
716 HadImportedNamedModules = true;
717
718 return Import;
719}
720
721void Sema::ActOnAnnotModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
722 checkModuleImportContext(S&: *this, M: Mod, ImportLoc: DirectiveLoc, DC: CurContext, FromInclude: true);
723 BuildModuleInclude(DirectiveLoc, Mod);
724}
725
726void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
727 // Determine whether we're in the #include buffer for a module. The #includes
728 // in that buffer do not qualify as module imports; they're just an
729 // implementation detail of us building the module.
730 //
731 // FIXME: Should we even get ActOnAnnotModuleInclude calls for those?
732 bool IsInModuleIncludes =
733 TUKind == TU_ClangModule &&
734 getSourceManager().isWrittenInMainFile(Loc: DirectiveLoc);
735
736 // If we are really importing a module (not just checking layering) due to an
737 // #include in the main file, synthesize an ImportDecl.
738 if (getLangOpts().Modules && !IsInModuleIncludes) {
739 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
740 ImportDecl *ImportD = ImportDecl::CreateImplicit(C&: getASTContext(), DC: TU,
741 StartLoc: DirectiveLoc, Imported: Mod,
742 EndLoc: DirectiveLoc);
743 if (!ModuleScopes.empty())
744 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: ImportD);
745 TU->addDecl(D: ImportD);
746 Consumer.HandleImplicitImportDecl(D: ImportD);
747 }
748
749 getModuleLoader().makeModuleVisible(Mod, Visibility: Module::AllVisible, ImportLoc: DirectiveLoc);
750 VisibleModules.setVisible(M: Mod, Loc: DirectiveLoc);
751
752 if (getLangOpts().isCompilingModule()) {
753 Module *ThisModule = PP.getHeaderSearchInfo().lookupModule(
754 ModuleName: getLangOpts().CurrentModule, ImportLoc: DirectiveLoc, AllowSearch: false, AllowExtraModuleMapSearch: false);
755 (void)ThisModule;
756 // For named modules, the current module name is not known while parsing the
757 // global module fragment and lookupModule may return null.
758 assert((getLangOpts().getCompilingModule() ==
759 LangOptionsBase::CMK_ModuleInterface ||
760 ThisModule) &&
761 "was expecting a module if building a Clang module");
762 }
763}
764
765void Sema::ActOnAnnotModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
766 checkModuleImportContext(S&: *this, M: Mod, ImportLoc: DirectiveLoc, DC: CurContext, FromInclude: true);
767
768 ModuleScopes.push_back(Elt: {});
769 ModuleScopes.back().Module = Mod;
770 if (getLangOpts().ModulesLocalVisibility)
771 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
772
773 VisibleModules.setVisible(M: Mod, Loc: DirectiveLoc);
774
775 // The enclosing context is now part of this module.
776 // FIXME: Consider creating a child DeclContext to hold the entities
777 // lexically within the module.
778 if (getLangOpts().trackLocalOwningModule()) {
779 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
780 cast<Decl>(Val: DC)->setModuleOwnershipKind(
781 getLangOpts().ModulesLocalVisibility
782 ? Decl::ModuleOwnershipKind::VisibleWhenImported
783 : Decl::ModuleOwnershipKind::Visible);
784 cast<Decl>(Val: DC)->setLocalOwningModule(Mod);
785 }
786 }
787}
788
789void Sema::ActOnAnnotModuleEnd(SourceLocation EomLoc, Module *Mod) {
790 if (getLangOpts().ModulesLocalVisibility) {
791 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
792 // Leaving a module hides namespace names, so our visible namespace cache
793 // is now out of date.
794 VisibleNamespaceCache.clear();
795 }
796
797 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
798 "left the wrong module scope");
799 ModuleScopes.pop_back();
800
801 // We got to the end of processing a local module. Create an
802 // ImportDecl as we would for an imported module.
803 FileID File = getSourceManager().getFileID(SpellingLoc: EomLoc);
804 SourceLocation DirectiveLoc;
805 if (EomLoc == getSourceManager().getLocForEndOfFile(FID: File)) {
806 // We reached the end of a #included module header. Use the #include loc.
807 assert(File != getSourceManager().getMainFileID() &&
808 "end of submodule in main source file");
809 DirectiveLoc = getSourceManager().getIncludeLoc(FID: File);
810 } else {
811 // We reached an EOM pragma. Use the pragma location.
812 DirectiveLoc = EomLoc;
813 }
814 BuildModuleInclude(DirectiveLoc, Mod);
815
816 // Any further declarations are in whatever module we returned to.
817 if (getLangOpts().trackLocalOwningModule()) {
818 // The parser guarantees that this is the same context that we entered
819 // the module within.
820 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
821 cast<Decl>(Val: DC)->setLocalOwningModule(getCurrentModule());
822 if (!getCurrentModule())
823 cast<Decl>(Val: DC)->setModuleOwnershipKind(
824 Decl::ModuleOwnershipKind::Unowned);
825 }
826 }
827}
828
829void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
830 Module *Mod) {
831 // Bail if we're not allowed to implicitly import a module here.
832 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
833 VisibleModules.isVisible(M: Mod))
834 return;
835
836 // Create the implicit import declaration.
837 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
838 ImportDecl *ImportD = ImportDecl::CreateImplicit(C&: getASTContext(), DC: TU,
839 StartLoc: Loc, Imported: Mod, EndLoc: Loc);
840 TU->addDecl(D: ImportD);
841 Consumer.HandleImplicitImportDecl(D: ImportD);
842
843 // Make the module visible.
844 getModuleLoader().makeModuleVisible(Mod, Visibility: Module::AllVisible, ImportLoc: Loc);
845 VisibleModules.setVisible(M: Mod, Loc);
846}
847
848Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
849 SourceLocation LBraceLoc) {
850 ExportDecl *D = ExportDecl::Create(C&: Context, DC: CurContext, ExportLoc);
851
852 // Set this temporarily so we know the export-declaration was braced.
853 D->setRBraceLoc(LBraceLoc);
854
855 CurContext->addDecl(D);
856 PushDeclContext(S, DC: D);
857
858 // C++2a [module.interface]p1:
859 // An export-declaration shall appear only [...] in the purview of a module
860 // interface unit. An export-declaration shall not appear directly or
861 // indirectly within [...] a private-module-fragment.
862 if (!getLangOpts().HLSL) {
863 if (!isCurrentModulePurview()) {
864 Diag(Loc: ExportLoc, DiagID: diag::err_export_not_in_module_interface) << 0;
865 D->setInvalidDecl();
866 return D;
867 } else if (currentModuleIsImplementation()) {
868 Diag(Loc: ExportLoc, DiagID: diag::err_export_not_in_module_interface) << 1;
869 Diag(Loc: ModuleScopes.back().BeginLoc,
870 DiagID: diag::note_not_module_interface_add_export)
871 << FixItHint::CreateInsertion(InsertionLoc: ModuleScopes.back().BeginLoc, Code: "export ");
872 D->setInvalidDecl();
873 return D;
874 } else if (ModuleScopes.back().Module->Kind ==
875 Module::PrivateModuleFragment) {
876 Diag(Loc: ExportLoc, DiagID: diag::err_export_in_private_module_fragment);
877 Diag(Loc: ModuleScopes.back().BeginLoc, DiagID: diag::note_private_module_fragment);
878 D->setInvalidDecl();
879 return D;
880 }
881 }
882
883 for (const DeclContext *DC = CurContext; DC; DC = DC->getLexicalParent()) {
884 if (const auto *ND = dyn_cast<NamespaceDecl>(Val: DC)) {
885 // An export-declaration shall not appear directly or indirectly within
886 // an unnamed namespace [...]
887 if (ND->isAnonymousNamespace()) {
888 Diag(Loc: ExportLoc, DiagID: diag::err_export_within_anonymous_namespace);
889 Diag(Loc: ND->getLocation(), DiagID: diag::note_anonymous_namespace);
890 // Don't diagnose internal-linkage declarations in this region.
891 D->setInvalidDecl();
892 return D;
893 }
894
895 // A declaration is exported if it is [...] a namespace-definition
896 // that contains an exported declaration.
897 //
898 // Defer exporting the namespace until after we leave it, in order to
899 // avoid marking all subsequent declarations in the namespace as exported.
900 if (!getLangOpts().HLSL && !DeferredExportedNamespaces.insert(Ptr: ND).second)
901 break;
902 }
903 }
904
905 // [...] its declaration or declaration-seq shall not contain an
906 // export-declaration.
907 if (auto *ED = getEnclosingExportDecl(D)) {
908 Diag(Loc: ExportLoc, DiagID: diag::err_export_within_export);
909 if (ED->hasBraces())
910 Diag(Loc: ED->getLocation(), DiagID: diag::note_export);
911 D->setInvalidDecl();
912 return D;
913 }
914
915 if (!getLangOpts().HLSL)
916 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
917
918 return D;
919}
920
921static bool checkExportedDecl(Sema &, Decl *, SourceLocation);
922
923/// Check that it's valid to export all the declarations in \p DC.
924static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
925 SourceLocation BlockStart) {
926 bool AllUnnamed = true;
927 for (auto *D : DC->decls())
928 AllUnnamed &= checkExportedDecl(S, D, BlockStart);
929 return AllUnnamed;
930}
931
932/// Check that it's valid to export \p D.
933static bool checkExportedDecl(Sema &S, Decl *D, SourceLocation BlockStart) {
934
935 // HLSL: export declaration is valid only on functions
936 if (S.getLangOpts().HLSL) {
937 // Export-within-export was already diagnosed in ActOnStartExportDecl
938 if (!isa<FunctionDecl, ExportDecl>(Val: D)) {
939 S.Diag(Loc: D->getBeginLoc(), DiagID: diag::err_hlsl_export_not_on_function);
940 D->setInvalidDecl();
941 return false;
942 }
943
944 if (isa<FunctionDecl>(Val: D)) {
945 FunctionDecl *FD = cast<FunctionDecl>(Val: D);
946 for (const ParmVarDecl *PVD : FD->parameters()) {
947 if (PVD->hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
948 S.Diag(Loc: D->getBeginLoc(), DiagID: diag::err_hlsl_attr_incompatible)
949 << "'export'" << "'groupshared' parameter";
950 D->setInvalidDecl();
951 return false;
952 }
953 }
954 }
955 }
956
957 // C++20 [module.interface]p3:
958 // [...] it shall not declare a name with internal linkage.
959 bool HasName = false;
960 if (auto *ND = dyn_cast<NamedDecl>(Val: D)) {
961 // Don't diagnose anonymous union objects; we'll diagnose their members
962 // instead.
963 HasName = (bool)ND->getDeclName();
964 if (HasName && ND->getFormalLinkage() == Linkage::Internal) {
965 S.Diag(Loc: ND->getLocation(), DiagID: diag::err_export_internal) << ND;
966 if (BlockStart.isValid())
967 S.Diag(Loc: BlockStart, DiagID: diag::note_export);
968 return false;
969 }
970 }
971
972 // C++2a [module.interface]p5:
973 // all entities to which all of the using-declarators ultimately refer
974 // shall have been introduced with a name having external linkage
975 if (auto *USD = dyn_cast<UsingShadowDecl>(Val: D)) {
976 NamedDecl *Target = USD->getUnderlyingDecl();
977 Linkage Lk = Target->getFormalLinkage();
978 if (Lk == Linkage::Internal || Lk == Linkage::Module) {
979 S.Diag(Loc: USD->getLocation(), DiagID: diag::err_export_using_internal)
980 << (Lk == Linkage::Internal ? 0 : 1) << Target;
981 S.Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
982 if (BlockStart.isValid())
983 S.Diag(Loc: BlockStart, DiagID: diag::note_export);
984 return false;
985 }
986 }
987
988 // Recurse into namespace-scope DeclContexts. (Only namespace-scope
989 // declarations are exported).
990 if (auto *DC = dyn_cast<DeclContext>(Val: D)) {
991 if (!isa<NamespaceDecl>(Val: D))
992 return true;
993
994 if (auto *ND = dyn_cast<NamedDecl>(Val: D)) {
995 if (!ND->getDeclName()) {
996 S.Diag(Loc: ND->getLocation(), DiagID: diag::err_export_anon_ns_internal);
997 if (BlockStart.isValid())
998 S.Diag(Loc: BlockStart, DiagID: diag::note_export);
999 return false;
1000 } else if (!DC->decls().empty() &&
1001 DC->getRedeclContext()->isFileContext()) {
1002 return checkExportedDeclContext(S, DC, BlockStart);
1003 }
1004 }
1005 }
1006 return true;
1007}
1008
1009Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
1010 auto *ED = cast<ExportDecl>(Val: D);
1011 if (RBraceLoc.isValid())
1012 ED->setRBraceLoc(RBraceLoc);
1013
1014 PopDeclContext();
1015
1016 if (!D->isInvalidDecl()) {
1017 SourceLocation BlockStart =
1018 ED->hasBraces() ? ED->getBeginLoc() : SourceLocation();
1019 for (auto *Child : ED->decls()) {
1020 checkExportedDecl(S&: *this, D: Child, BlockStart);
1021 if (auto *FD = dyn_cast<FunctionDecl>(Val: Child)) {
1022 // [dcl.inline]/7
1023 // If an inline function or variable that is attached to a named module
1024 // is declared in a definition domain, it shall be defined in that
1025 // domain.
1026 // So, if the current declaration does not have a definition, we must
1027 // check at the end of the TU (or when the PMF starts) to see that we
1028 // have a definition at that point.
1029 if (FD->isInlineSpecified() && !FD->isDefined())
1030 PendingInlineFuncDecls.insert(Ptr: FD);
1031 }
1032 }
1033 }
1034
1035 // Anything exported from a module should never be considered unused.
1036 for (auto *Exported : ED->decls())
1037 Exported->markUsed(C&: getASTContext());
1038
1039 return D;
1040}
1041
1042Module *Sema::PushGlobalModuleFragment(SourceLocation BeginLoc) {
1043 // We shouldn't create new global module fragment if there is already
1044 // one.
1045 if (!TheGlobalModuleFragment) {
1046 ModuleMap &Map = PP.getHeaderSearchInfo().getModuleMap();
1047 TheGlobalModuleFragment = Map.createGlobalModuleFragmentForModuleUnit(
1048 Loc: BeginLoc, Parent: getCurrentModule());
1049 }
1050
1051 assert(TheGlobalModuleFragment && "module creation should not fail");
1052
1053 // Enter the scope of the global module.
1054 ModuleScopes.push_back(Elt: {.BeginLoc: BeginLoc, .Module: TheGlobalModuleFragment,
1055 /*OuterVisibleModules=*/{}});
1056 VisibleModules.setVisible(M: TheGlobalModuleFragment, Loc: BeginLoc);
1057
1058 return TheGlobalModuleFragment;
1059}
1060
1061void Sema::PopGlobalModuleFragment() {
1062 assert(!ModuleScopes.empty() &&
1063 getCurrentModule()->isExplicitGlobalModule() &&
1064 "left the wrong module scope, which is not global module fragment");
1065 ModuleScopes.pop_back();
1066}
1067
1068Module *Sema::PushImplicitGlobalModuleFragment(SourceLocation BeginLoc) {
1069 if (!TheImplicitGlobalModuleFragment) {
1070 ModuleMap &Map = PP.getHeaderSearchInfo().getModuleMap();
1071 TheImplicitGlobalModuleFragment =
1072 Map.createImplicitGlobalModuleFragmentForModuleUnit(Loc: BeginLoc,
1073 Parent: getCurrentModule());
1074 }
1075 assert(TheImplicitGlobalModuleFragment && "module creation should not fail");
1076
1077 // Enter the scope of the global module.
1078 ModuleScopes.push_back(Elt: {.BeginLoc: BeginLoc, .Module: TheImplicitGlobalModuleFragment,
1079 /*OuterVisibleModules=*/{}});
1080 VisibleModules.setVisible(M: TheImplicitGlobalModuleFragment, Loc: BeginLoc);
1081 return TheImplicitGlobalModuleFragment;
1082}
1083
1084void Sema::PopImplicitGlobalModuleFragment() {
1085 assert(!ModuleScopes.empty() &&
1086 getCurrentModule()->isImplicitGlobalModule() &&
1087 "left the wrong module scope, which is not global module fragment");
1088 ModuleScopes.pop_back();
1089}
1090
1091bool Sema::isCurrentModulePurview() const {
1092 if (!getCurrentModule())
1093 return false;
1094
1095 /// Does this Module scope describe part of the purview of a standard named
1096 /// C++ module?
1097 switch (getCurrentModule()->Kind) {
1098 case Module::ModuleInterfaceUnit:
1099 case Module::ModuleImplementationUnit:
1100 case Module::ModulePartitionInterface:
1101 case Module::ModulePartitionImplementation:
1102 case Module::PrivateModuleFragment:
1103 case Module::ImplicitGlobalModuleFragment:
1104 return true;
1105 default:
1106 return false;
1107 }
1108}
1109
1110//===----------------------------------------------------------------------===//
1111// Checking Exposure in modules //
1112//===----------------------------------------------------------------------===//
1113
1114namespace {
1115class ExposureChecker {
1116public:
1117 ExposureChecker(Sema &S) : SemaRef(S) {}
1118
1119 bool checkExposure(const VarDecl *D, bool Diag);
1120 bool checkExposure(const CXXRecordDecl *D, bool Diag);
1121 bool checkExposure(const Stmt *S, bool Diag);
1122 bool checkExposure(const FunctionDecl *D, bool Diag);
1123 bool checkExposure(const NamedDecl *D, bool Diag);
1124 void checkExposureInContext(const DeclContext *DC);
1125 bool isExposureCandidate(const NamedDecl *D);
1126
1127 bool isTULocal(QualType Ty);
1128 bool isTULocal(const NamedDecl *ND);
1129 bool isTULocal(const Expr *E);
1130
1131 Sema &SemaRef;
1132
1133private:
1134 llvm::DenseSet<const NamedDecl *> ExposureSet;
1135 llvm::DenseSet<const NamedDecl *> KnownNonExposureSet;
1136 llvm::DenseSet<const NamedDecl *> CheckingDecls;
1137};
1138
1139bool ExposureChecker::isTULocal(QualType Ty) {
1140 // [basic.link]p15:
1141 // An entity is TU-local if it is
1142 // - a type, type alias, namespace, namespace alias, function, variable, or
1143 // template that
1144 // -- has internal linkage, or
1145 return Ty->getLinkage() == Linkage::Internal;
1146
1147 // TODO:
1148 // [basic.link]p15.2:
1149 // a type with no name that is defined outside a class-specifier, function
1150 // body, or initializer or is introduced by a defining-type-specifier that
1151 // is used to declare only TU-local entities,
1152}
1153
1154bool ExposureChecker::isTULocal(const NamedDecl *D) {
1155 if (!D)
1156 return false;
1157
1158 // [basic.link]p15:
1159 // An entity is TU-local if it is
1160 // - a type, type alias, namespace, namespace alias, function, variable, or
1161 // template that
1162 // -- has internal linkage, or
1163 if (D->getLinkageInternal() == Linkage::Internal)
1164 return true;
1165
1166 if (D->isInAnonymousNamespace())
1167 return true;
1168
1169 // [basic.link]p15.1.2:
1170 // does not have a name with linkage and is declared, or introduced by a
1171 // lambda-expression, within the definition of a TU-local entity,
1172 if (D->getLinkageInternal() == Linkage::None)
1173 if (auto *ND = dyn_cast<NamedDecl>(Val: D->getDeclContext());
1174 ND && isTULocal(D: ND))
1175 return true;
1176
1177 // [basic.link]p15.3, p15.4:
1178 // - a specialization of a TU-local template,
1179 // - a specialization of a template with any TU-local template argument, or
1180 ArrayRef<TemplateArgument> TemplateArgs;
1181 NamedDecl *PrimaryTemplate = nullptr;
1182 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: D)) {
1183 TemplateArgs = CTSD->getTemplateArgs().asArray();
1184 PrimaryTemplate = CTSD->getSpecializedTemplate();
1185 if (isTULocal(D: PrimaryTemplate))
1186 return true;
1187 } else if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Val: D)) {
1188 TemplateArgs = VTSD->getTemplateArgs().asArray();
1189 PrimaryTemplate = VTSD->getSpecializedTemplate();
1190 if (isTULocal(D: PrimaryTemplate))
1191 return true;
1192 } else if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
1193 if (auto *TAList = FD->getTemplateSpecializationArgs())
1194 TemplateArgs = TAList->asArray();
1195
1196 PrimaryTemplate = FD->getPrimaryTemplate();
1197 if (isTULocal(D: PrimaryTemplate))
1198 return true;
1199 }
1200
1201 if (!PrimaryTemplate)
1202 // Following off, we only check for specializations.
1203 return false;
1204
1205 if (KnownNonExposureSet.count(V: D))
1206 return false;
1207
1208 for (auto &TA : TemplateArgs) {
1209 switch (TA.getKind()) {
1210 case TemplateArgument::Type:
1211 if (isTULocal(Ty: TA.getAsType()))
1212 return true;
1213 break;
1214 case TemplateArgument::Declaration:
1215 if (isTULocal(D: TA.getAsDecl()))
1216 return true;
1217 break;
1218 default:
1219 break;
1220 }
1221 }
1222
1223 // Avoid recursions.
1224 if (CheckingDecls.count(V: D))
1225 return false;
1226 CheckingDecls.insert(V: D);
1227 llvm::scope_exit RemoveCheckingDecls([&] { CheckingDecls.erase(V: D); });
1228
1229 // [basic.link]p15.5
1230 // - a specialization of a template whose (possibly instantiated) declaration
1231 // is an exposure.
1232 if (ExposureSet.count(V: PrimaryTemplate) ||
1233 checkExposure(D: PrimaryTemplate, /*Diag=*/false))
1234 return true;
1235
1236 // Avoid calling checkExposure again since it is expensive.
1237 KnownNonExposureSet.insert(V: D);
1238 return false;
1239}
1240
1241bool ExposureChecker::isTULocal(const Expr *E) {
1242 if (!E)
1243 return false;
1244
1245 // [basic.link]p16:
1246 // A value or object is TU-local if either
1247 // - it is of TU-local type,
1248 if (isTULocal(Ty: E->getType()))
1249 return true;
1250
1251 E = E->IgnoreParenImpCasts();
1252 // [basic.link]p16.2:
1253 // - it is, or is a pointer to, a TU-local function or the object associated
1254 // with a TU-local variable,
1255 // - it is an object of class or array type and any of its subobjects or any
1256 // of the objects or functions to which its non-static data members of
1257 // reference type refer is TU-local and is usable in constant expressions, or
1258 // FIXME: But how can we know the value of pointers or arrays at compile time?
1259 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
1260 if (auto *FD = dyn_cast_or_null<FunctionDecl>(Val: DRE->getFoundDecl()))
1261 return isTULocal(D: FD);
1262 else if (auto *VD = dyn_cast_or_null<VarDecl>(Val: DRE->getFoundDecl()))
1263 return isTULocal(D: VD);
1264 else if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Val: DRE->getFoundDecl()))
1265 return isTULocal(D: RD);
1266 }
1267
1268 // TODO:
1269 // [basic.link]p16.4:
1270 // it is a reflection value that represents...
1271
1272 return false;
1273}
1274
1275bool ExposureChecker::isExposureCandidate(const NamedDecl *D) {
1276 if (!D)
1277 return false;
1278
1279 // [basic.link]p17:
1280 // If a (possibly instantiated) declaration of, or a deduction guide for,
1281 // a non-TU-local entity in a module interface unit
1282 // (outside the private-module-fragment, if any) or
1283 // module partition is an exposure, the program is ill-formed.
1284 Module *M = D->getOwningModule();
1285 if (!M)
1286 return false;
1287 // If M is implicit global module, the declaration must be in the purview of
1288 // a module unit.
1289 if (M->isImplicitGlobalModule()) {
1290 M = M->Parent;
1291 assert(M && "Implicit global module must have a parent");
1292 }
1293
1294 if (!M->isInterfaceOrPartition())
1295 return false;
1296
1297 if (D->isImplicit())
1298 return false;
1299
1300 // [basic.link]p14:
1301 // A declaration is an exposure if it either names a TU-local entity
1302 // (defined below), ignoring:
1303 // ...
1304 // - friend declarations in a class definition
1305 if (D->getFriendObjectKind() &&
1306 isa<CXXRecordDecl>(Val: D->getLexicalDeclContext()))
1307 return false;
1308
1309 return true;
1310}
1311
1312bool ExposureChecker::checkExposure(const NamedDecl *D, bool Diag) {
1313 if (!isExposureCandidate(D))
1314 return false;
1315
1316 if (auto *FD = dyn_cast<FunctionDecl>(Val: D))
1317 return checkExposure(D: FD, Diag);
1318 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: D))
1319 return checkExposure(D: FTD->getTemplatedDecl(), Diag);
1320
1321 if (auto *VD = dyn_cast<VarDecl>(Val: D))
1322 return checkExposure(D: VD, Diag);
1323 if (auto *VTD = dyn_cast<VarTemplateDecl>(Val: D))
1324 return checkExposure(D: VTD->getTemplatedDecl(), Diag);
1325
1326 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
1327 return checkExposure(D: RD, Diag);
1328
1329 if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: D))
1330 return checkExposure(D: CTD->getTemplatedDecl(), Diag);
1331
1332 return false;
1333}
1334
1335bool ExposureChecker::checkExposure(const FunctionDecl *FD, bool Diag) {
1336 bool IsExposure = false;
1337 if (isTULocal(Ty: FD->getReturnType())) {
1338 IsExposure = true;
1339 if (Diag)
1340 SemaRef.Diag(Loc: FD->getReturnTypeSourceRange().getBegin(),
1341 DiagID: diag::warn_exposure)
1342 << FD->getReturnType();
1343 }
1344
1345 for (ParmVarDecl *Parms : FD->parameters())
1346 if (isTULocal(Ty: Parms->getType())) {
1347 IsExposure = true;
1348 if (Diag)
1349 SemaRef.Diag(Loc: Parms->getLocation(), DiagID: diag::warn_exposure)
1350 << Parms->getType();
1351 }
1352
1353 bool IsImplicitInstantiation =
1354 FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1355
1356 // [basic.link]p14:
1357 // A declaration is an exposure if it either names a TU-local entity
1358 // (defined below), ignoring:
1359 // - the function-body for a non-inline function or function template
1360 // (but not the deduced return
1361 // type for a (possibly instantiated) definition of a function with a
1362 // declared return type that uses a placeholder type
1363 // ([dcl.spec.auto])),
1364 Diag &=
1365 (FD->isInlined() || IsImplicitInstantiation) && !FD->isDependentContext();
1366
1367 IsExposure |= checkExposure(S: FD->getBody(), Diag);
1368 if (IsExposure)
1369 ExposureSet.insert(V: FD);
1370
1371 return IsExposure;
1372}
1373
1374bool ExposureChecker::checkExposure(const VarDecl *VD, bool Diag) {
1375 bool IsExposure = false;
1376 // [basic.link]p14:
1377 // A declaration is an exposure if it either names a TU-local entity (defined
1378 // below), ignoring:
1379 // ...
1380 // or defines a constexpr variable initialized to a TU-local value (defined
1381 // below).
1382 if (VD->isConstexpr() && isTULocal(E: VD->getInit())) {
1383 IsExposure = true;
1384 if (Diag)
1385 SemaRef.Diag(Loc: VD->getInit()->getExprLoc(), DiagID: diag::warn_exposure)
1386 << VD->getInit();
1387 }
1388
1389 if (isTULocal(Ty: VD->getType())) {
1390 IsExposure = true;
1391 if (Diag)
1392 SemaRef.Diag(Loc: VD->getLocation(), DiagID: diag::warn_exposure) << VD->getType();
1393 }
1394
1395 // [basic.link]p14:
1396 // ..., ignoring:
1397 // - the initializer for a variable or variable template (but not the
1398 // variable's type),
1399 //
1400 // Note: although the spec says to ignore the initializer for all variable,
1401 // for the code we generated now for inline variables, it is dangerous if the
1402 // initializer of an inline variable is TULocal.
1403 Diag &= !VD->getDeclContext()->isDependentContext() && VD->isInline();
1404 IsExposure |= checkExposure(S: VD->getInit(), Diag);
1405 if (IsExposure)
1406 ExposureSet.insert(V: VD);
1407
1408 return IsExposure;
1409}
1410
1411bool ExposureChecker::checkExposure(const CXXRecordDecl *RD, bool Diag) {
1412 if (!RD->hasDefinition())
1413 return false;
1414
1415 bool IsExposure = false;
1416 for (CXXMethodDecl *Method : RD->methods())
1417 IsExposure |= checkExposure(FD: Method, Diag);
1418
1419 for (FieldDecl *FD : RD->fields()) {
1420 if (isTULocal(Ty: FD->getType())) {
1421 IsExposure = true;
1422 if (Diag)
1423 SemaRef.Diag(Loc: FD->getLocation(), DiagID: diag::warn_exposure) << FD->getType();
1424 }
1425 }
1426
1427 for (const CXXBaseSpecifier &Base : RD->bases()) {
1428 if (isTULocal(Ty: Base.getType())) {
1429 IsExposure = true;
1430 if (Diag)
1431 SemaRef.Diag(Loc: Base.getBaseTypeLoc(), DiagID: diag::warn_exposure)
1432 << Base.getType();
1433 }
1434 }
1435
1436 if (IsExposure)
1437 ExposureSet.insert(V: RD);
1438
1439 return IsExposure;
1440}
1441
1442class ReferenceTULocalChecker : public DynamicRecursiveASTVisitor {
1443public:
1444 using CallbackTy = std::function<void(DeclRefExpr *, ValueDecl *)>;
1445
1446 ReferenceTULocalChecker(ExposureChecker &C, CallbackTy &&Callback)
1447 : Checker(C), Callback(std::move(Callback)) {}
1448
1449 bool VisitDeclRefExpr(DeclRefExpr *DRE) override {
1450 ValueDecl *Referenced = DRE->getDecl();
1451 if (!Referenced)
1452 return true;
1453
1454 if (!Checker.isTULocal(D: Referenced))
1455 // We don't care if the referenced declaration is not TU-local.
1456 return true;
1457
1458 Qualifiers Qual = DRE->getType().getQualifiers();
1459 // [basic.link]p14:
1460 // A declaration is an exposure if it either names a TU-local entity
1461 // (defined below), ignoring:
1462 // ...
1463 // - any reference to a non-volatile const object ...
1464 if (Qual.hasConst() && !Qual.hasVolatile())
1465 return true;
1466
1467 // [basic.link]p14:
1468 // ..., ignoring:
1469 // ...
1470 // (p14.4) - ... or reference with internal or no linkage initialized with
1471 // a constant expression that is not an odr-use
1472 ASTContext &Context = Referenced->getASTContext();
1473 Linkage L = Referenced->getLinkageInternal();
1474 if (DRE->isNonOdrUse() && (L == Linkage::Internal || L == Linkage::None))
1475 if (auto *VD = dyn_cast<VarDecl>(Val: Referenced);
1476 VD && VD->getInit() && !VD->getInit()->isValueDependent() &&
1477 VD->getInit()->isConstantInitializer(Ctx&: Context))
1478 return true;
1479
1480 Callback(DRE, Referenced);
1481 return true;
1482 }
1483
1484 ExposureChecker &Checker;
1485 CallbackTy Callback;
1486};
1487
1488bool ExposureChecker::checkExposure(const Stmt *S, bool Diag) {
1489 if (!S)
1490 return false;
1491
1492 bool HasReferencedTULocals = false;
1493 ReferenceTULocalChecker Checker(
1494 *this, [this, &HasReferencedTULocals, Diag](DeclRefExpr *DRE,
1495 ValueDecl *Referenced) {
1496 if (Diag) {
1497 SemaRef.Diag(Loc: DRE->getExprLoc(), DiagID: diag::warn_exposure) << Referenced;
1498 }
1499 HasReferencedTULocals = true;
1500 });
1501 Checker.TraverseStmt(S: const_cast<Stmt *>(S));
1502 return HasReferencedTULocals;
1503}
1504
1505void ExposureChecker::checkExposureInContext(const DeclContext *DC) {
1506 for (auto *TopD : DC->noload_decls()) {
1507 if (auto *Export = dyn_cast<ExportDecl>(Val: TopD)) {
1508 checkExposureInContext(DC: Export);
1509 continue;
1510 }
1511
1512 if (auto *LinkageSpec = dyn_cast<LinkageSpecDecl>(Val: TopD)) {
1513 checkExposureInContext(DC: LinkageSpec);
1514 continue;
1515 }
1516
1517 auto *TopND = dyn_cast<NamedDecl>(Val: TopD);
1518 if (!TopND)
1519 continue;
1520
1521 if (auto *Namespace = dyn_cast<NamespaceDecl>(Val: TopND)) {
1522 checkExposureInContext(DC: Namespace);
1523 continue;
1524 }
1525
1526 // [basic.link]p17:
1527 // If a (possibly instantiated) declaration of, or a deduction guide for,
1528 // a non-TU-local entity in a module interface unit
1529 // (outside the private-module-fragment, if any) or
1530 // module partition is an exposure, the program is ill-formed.
1531 if (!TopND->isFromASTFile() && isExposureCandidate(D: TopND) &&
1532 !isTULocal(D: TopND))
1533 checkExposure(D: TopND, /*Diag=*/true);
1534 }
1535}
1536
1537} // namespace
1538
1539void Sema::checkExposure(const TranslationUnitDecl *TU) {
1540 if (!TU)
1541 return;
1542
1543 ExposureChecker Checker(*this);
1544
1545 Module *M = TU->getOwningModule();
1546 if (M && M->isInterfaceOrPartition())
1547 Checker.checkExposureInContext(DC: TU);
1548
1549 // [basic.link]p18:
1550 // If a declaration that appears in one translation unit names a TU-local
1551 // entity declared in another translation unit that is not a header unit,
1552 // the program is ill-formed.
1553 for (auto FDAndInstantiationLocPair : PendingCheckReferenceForTULocal) {
1554 FunctionDecl *FD = FDAndInstantiationLocPair.first;
1555 SourceLocation PointOfInstantiation = FDAndInstantiationLocPair.second;
1556
1557 if (!FD->hasBody())
1558 continue;
1559
1560 ReferenceTULocalChecker(Checker, [&, this](DeclRefExpr *DRE,
1561 ValueDecl *Referenced) {
1562 // A "defect" in current implementation. Now an implicit instantiation of
1563 // a template, the instantiation is considered to be in the same module
1564 // unit as the template instead of the module unit where the instantiation
1565 // happens.
1566 //
1567 // See test/Modules/Exposre-2.cppm for example.
1568 if (!Referenced->isFromASTFile())
1569 return;
1570
1571 if (!Referenced->isInAnotherModuleUnit())
1572 return;
1573
1574 // This is not standard conforming. But given there are too many static
1575 // (inline) functions in headers in existing code, it is more user
1576 // friendly to ignore them temporarily now. maybe we can have another flag
1577 // for this.
1578 if (Referenced->getOwningModule()->isExplicitGlobalModule() &&
1579 isa<FunctionDecl>(Val: Referenced))
1580 return;
1581
1582 Diag(Loc: PointOfInstantiation,
1583 DiagID: diag::warn_reference_tu_local_entity_in_other_tu)
1584 << FD << Referenced
1585 << Referenced->getOwningModule()->getTopLevelModuleName();
1586 }).TraverseStmt(S: FD->getBody());
1587 }
1588}
1589
1590void Sema::checkReferenceToTULocalFromOtherTU(
1591 FunctionDecl *FD, SourceLocation PointOfInstantiation) {
1592 // Checking if a declaration have any reference to TU-local entities in other
1593 // TU is expensive. Try to avoid it as much as possible.
1594 if (!FD || !HadImportedNamedModules)
1595 return;
1596
1597 PendingCheckReferenceForTULocal.push_back(
1598 Elt: std::make_pair(x&: FD, y&: PointOfInstantiation));
1599}
1600