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 // A Clang module or a header unit cannot be used as the current named
393 // module while recovering from it. See clang/test/Modules/GH204632.cppm
394 // for an example.
395 if (!M->isNamedModule())
396 return nullptr;
397 Mod = M;
398 break;
399 }
400
401 // Create a Module for the module that we're defining.
402 Mod = Map.createModuleForInterfaceUnit(Loc: ModuleLoc, Name: ModuleName);
403 if (MDK == ModuleDeclKind::PartitionInterface)
404 Mod->Kind = Module::ModulePartitionInterface;
405 assert(Mod && "module creation should not fail");
406 break;
407 }
408
409 case ModuleDeclKind::Implementation: {
410 // C++20 A module-declaration that contains neither an export-
411 // keyword nor a module-partition implicitly imports the primary
412 // module interface unit of the module as if by a module-import-
413 // declaration.
414 IdentifierLoc ModuleNameLoc(Path[0].getLoc(),
415 PP.getIdentifierInfo(Name: ModuleName));
416
417 // The module loader will assume we're trying to import the module that
418 // we're building if `LangOpts.CurrentModule` equals to 'ModuleName'.
419 // Change the value for `LangOpts.CurrentModule` temporarily to make the
420 // module loader work properly.
421 const_cast<LangOptions &>(getLangOpts()).CurrentModule = "";
422 Interface = getModuleLoader().loadModule(ImportLoc: ModuleLoc, Path: {ModuleNameLoc},
423 Visibility: Module::AllVisible,
424 /*IsInclusionDirective=*/false);
425 const_cast<LangOptions &>(getLangOpts()).CurrentModule = ModuleName;
426
427 // A Clang module or a header unit cannot serve as the primary module
428 // interface while recovering from an implementation unit declaration.
429 if (Interface && !Interface->isNamedModule()) {
430 Diag(Loc: ModuleLoc, DiagID: diag::err_module_not_defined) << ModuleName;
431 return nullptr;
432 }
433
434 if (!Interface) {
435 Diag(Loc: ModuleLoc, DiagID: diag::err_module_not_defined) << ModuleName;
436 // Create an empty module interface unit for error recovery.
437 Mod = Map.createModuleForInterfaceUnit(Loc: ModuleLoc, Name: ModuleName);
438 } else {
439 Mod = Map.createModuleForImplementationUnit(Loc: ModuleLoc, Name: ModuleName);
440 }
441 } break;
442
443 case ModuleDeclKind::PartitionImplementation:
444 // Create an interface, but note that it is an implementation
445 // unit.
446 Mod = Map.createModuleForInterfaceUnit(Loc: ModuleLoc, Name: ModuleName);
447 Mod->Kind = Module::ModulePartitionImplementation;
448 break;
449 }
450
451 if (!this->TheGlobalModuleFragment) {
452 ModuleScopes.push_back(Elt: {});
453 if (getLangOpts().ModulesLocalVisibility)
454 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
455 } else {
456 // We're done with the global module fragment now.
457 ActOnEndOfTranslationUnitFragment(Kind: TUFragmentKind::Global);
458 }
459
460 // Switch from the global module fragment (if any) to the named module.
461 ModuleScopes.back().BeginLoc = StartLoc;
462 ModuleScopes.back().Module = Mod;
463 VisibleModules.setVisible(M: Mod, Loc: ModuleLoc);
464
465 // From now on, we have an owning module for all declarations we see.
466 // In C++20 modules, those declaration would be reachable when imported
467 // unless explicitily exported.
468 // Otherwise, those declarations are module-private unless explicitly
469 // exported.
470 auto *TU = Context.getTranslationUnitDecl();
471 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ReachableWhenImported);
472 TU->setLocalOwningModule(Mod);
473
474 // We are in the module purview, but before any other (non import)
475 // statements, so imports are allowed.
476 ImportState = ModuleImportState::ImportAllowed;
477
478 getASTContext().setCurrentNamedModule(Mod);
479
480 // We already potentially made an implicit import (in the case of a module
481 // implementation unit importing its interface). Make this module visible
482 // and return the import decl to be added to the current TU.
483 if (Interface) {
484 HadImportedNamedModules = true;
485
486 makeTransitiveImportsVisible(Ctx&: getASTContext(), VisibleModules, Imported: Interface,
487 CurrentModule: Mod, ImportLoc: ModuleLoc,
488 /*IsImportingPrimaryModuleInterface=*/true);
489
490 // Make the import decl for the interface in the impl module.
491 ImportDecl *Import = ImportDecl::Create(C&: Context, DC: CurContext, StartLoc: ModuleLoc,
492 Imported: Interface, IdentifierLocs: Path[0].getLoc());
493 CurContext->addDecl(D: Import);
494
495 // Sequence initialization of the imported module before that of the current
496 // module, if any.
497 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: Import);
498 Mod->Imports.push_back(Elt: 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(Ptr: Import);
504 }
505
506 return nullptr;
507}
508
509Sema::DeclGroupPtrTy
510Sema::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(Loc: PrivateLoc, DiagID: diag::err_private_module_fragment_not_module);
524 return nullptr;
525
526 case Module::PrivateModuleFragment:
527 Diag(Loc: PrivateLoc, DiagID: diag::err_private_module_fragment_redefined);
528 Diag(Loc: ModuleScopes.back().BeginLoc, DiagID: diag::note_previous_definition);
529 return nullptr;
530
531 case Module::ModuleImplementationUnit:
532 Diag(Loc: PrivateLoc, DiagID: diag::err_private_module_fragment_not_module_interface);
533 Diag(Loc: ModuleScopes.back().BeginLoc,
534 DiagID: diag::note_not_module_interface_add_export)
535 << FixItHint::CreateInsertion(InsertionLoc: ModuleScopes.back().BeginLoc, Code: "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(Kind: TUFragmentKind::Normal);
548
549 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
550 Module *PrivateModuleFragment =
551 Map.createPrivateModuleFragmentForInterfaceUnit(
552 Parent: ModuleScopes.back().Module, Loc: PrivateLoc);
553 assert(PrivateModuleFragment && "module creation should not fail");
554
555 // Enter the scope of the private module fragment.
556 ModuleScopes.push_back(Elt: {});
557 ModuleScopes.back().BeginLoc = ModuleLoc;
558 ModuleScopes.back().Module = PrivateModuleFragment;
559 VisibleModules.setVisible(M: PrivateModuleFragment, Loc: 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
572DeclResult 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 IdentifierLoc 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 += ModuleLoader::getFlatNameFromPath(Path);
593 ModuleNameLoc =
594 IdentifierLoc(Path[0].getLoc(), PP.getIdentifierInfo(Name: ModuleName));
595 Path = ModuleIdPath(ModuleNameLoc);
596 } else if (getLangOpts().CPlusPlusModules) {
597 ModuleName = ModuleLoader::getFlatNameFromPath(Path);
598 ModuleNameLoc =
599 IdentifierLoc(Path[0].getLoc(), PP.getIdentifierInfo(Name: ModuleName));
600 Path = ModuleIdPath(ModuleNameLoc);
601 }
602
603 // Diagnose self-import before attempting a load.
604 // [module.import]/9
605 // A module implementation unit of a module M that is not a module partition
606 // shall not contain a module-import-declaration nominating M.
607 // (for an implementation, the module interface is imported implicitly,
608 // but that's handled in the module decl code).
609
610 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview() &&
611 getCurrentModule()->Name == ModuleName) {
612 Diag(Loc: ImportLoc, DiagID: diag::err_module_self_import_cxx20)
613 << ModuleName << currentModuleIsImplementation();
614 return true;
615 }
616
617 Module *Mod = getModuleLoader().loadModule(
618 ImportLoc, Path, Visibility: Module::AllVisible, /*IsInclusionDirective=*/false);
619 if (!Mod)
620 return true;
621
622 if (!Mod->isInterfaceOrPartition() && !ModuleName.empty() &&
623 !getLangOpts().ObjC) {
624 Diag(Loc: ImportLoc, DiagID: diag::err_module_import_non_interface_nor_parition)
625 << ModuleName;
626 return true;
627 }
628
629 return ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, M: Mod, Path);
630}
631
632/// Determine whether \p D is lexically within an export-declaration.
633static const ExportDecl *getEnclosingExportDecl(const Decl *D) {
634 for (auto *DC = D->getLexicalDeclContext(); DC; DC = DC->getLexicalParent())
635 if (auto *ED = dyn_cast<ExportDecl>(Val: DC))
636 return ED;
637 return nullptr;
638}
639
640DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
641 SourceLocation ExportLoc,
642 SourceLocation ImportLoc, Module *Mod,
643 ModuleIdPath Path) {
644 if (Mod->isHeaderUnit())
645 Diag(Loc: ImportLoc, DiagID: diag::warn_experimental_header_unit);
646
647 if (Mod->isNamedModule())
648 makeTransitiveImportsVisible(Ctx&: getASTContext(), VisibleModules, Imported: Mod,
649 CurrentModule: getCurrentModule(), ImportLoc);
650 else
651 VisibleModules.setVisible(M: Mod, Loc: ImportLoc);
652
653 assert((!Mod->isModulePartitionImplementation() || getCurrentModule()) &&
654 "We can only import a partition unit in a named module.");
655 if (Mod->isModulePartitionImplementation() &&
656 getCurrentModule()->isModuleInterfaceUnit())
657 Diag(Loc: ImportLoc,
658 DiagID: diag::warn_import_implementation_partition_unit_in_interface_unit)
659 << Mod->Name;
660
661 checkModuleImportContext(S&: *this, M: Mod, ImportLoc, DC: CurContext);
662
663 // FIXME: we should support importing a submodule within a different submodule
664 // of the same top-level module. Until we do, make it an error rather than
665 // silently ignoring the import.
666 // FIXME: Should we warn on a redundant import of the current module?
667 if (Mod->isForBuilding(LangOpts: getLangOpts())) {
668 Diag(Loc: ImportLoc, DiagID: getLangOpts().isCompilingModule()
669 ? diag::err_module_self_import
670 : diag::err_module_import_in_implementation)
671 << Mod->getFullModuleName() << getLangOpts().CurrentModule;
672 }
673
674 SmallVector<SourceLocation, 2> IdentifierLocs;
675
676 if (Path.empty()) {
677 // If this was a header import, pad out with dummy locations.
678 // FIXME: Pass in and use the location of the header-name token in this
679 // case.
680 for (Module *ModCheck = Mod; ModCheck; ModCheck = ModCheck->Parent)
681 IdentifierLocs.push_back(Elt: SourceLocation());
682 } else if (getLangOpts().CPlusPlusModules && !Mod->Parent) {
683 // A single identifier for the whole name.
684 IdentifierLocs.push_back(Elt: Path[0].getLoc());
685 } else {
686 Module *ModCheck = Mod;
687 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
688 // If we've run out of module parents, just drop the remaining
689 // identifiers. We need the length to be consistent.
690 if (!ModCheck)
691 break;
692 ModCheck = ModCheck->Parent;
693
694 IdentifierLocs.push_back(Elt: Path[I].getLoc());
695 }
696 }
697
698 ImportDecl *Import = ImportDecl::Create(C&: Context, DC: CurContext, StartLoc,
699 Imported: Mod, IdentifierLocs);
700 CurContext->addDecl(D: Import);
701
702 // Sequence initialization of the imported module before that of the current
703 // module, if any.
704 if (!ModuleScopes.empty())
705 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: Import);
706
707 // A module (partition) implementation unit shall not be exported.
708 if (getLangOpts().CPlusPlusModules && ExportLoc.isValid() &&
709 Mod->Kind == Module::ModuleKind::ModulePartitionImplementation) {
710 Diag(Loc: ExportLoc, DiagID: diag::err_export_partition_impl)
711 << SourceRange(ExportLoc, Path.back().getLoc());
712 } else if (ExportLoc.isValid() &&
713 (ModuleScopes.empty() || currentModuleIsImplementation())) {
714 // [module.interface]p1:
715 // An export-declaration shall inhabit a namespace scope and appear in the
716 // purview of a module interface unit.
717 Diag(Loc: ExportLoc, DiagID: diag::err_export_not_in_module_interface);
718 } else if (!ModuleScopes.empty()) {
719 // Re-export the module if the imported module is exported.
720 // Note that we don't need to add re-exported module to Imports field
721 // since `Exports` implies the module is imported already.
722 if (ExportLoc.isValid() || getEnclosingExportDecl(D: Import))
723 getCurrentModule()->Exports.emplace_back(Args&: Mod, Args: false);
724 else
725 getCurrentModule()->Imports.push_back(Elt: Mod);
726 }
727
728 HadImportedNamedModules = true;
729
730 return Import;
731}
732
733void Sema::ActOnAnnotModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
734 checkModuleImportContext(S&: *this, M: Mod, ImportLoc: DirectiveLoc, DC: CurContext, FromInclude: true);
735 BuildModuleInclude(DirectiveLoc, Mod);
736}
737
738void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
739 // Determine whether we're in the #include buffer for a module. The #includes
740 // in that buffer do not qualify as module imports; they're just an
741 // implementation detail of us building the module.
742 //
743 // FIXME: Should we even get ActOnAnnotModuleInclude calls for those?
744 bool IsInModuleIncludes =
745 TUKind == TU_ClangModule &&
746 getSourceManager().isWrittenInMainFile(Loc: DirectiveLoc);
747
748 // If we are really importing a module (not just checking layering) due to an
749 // #include in the main file, synthesize an ImportDecl.
750 if (getLangOpts().Modules && !IsInModuleIncludes) {
751 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
752 ImportDecl *ImportD = ImportDecl::CreateImplicit(C&: getASTContext(), DC: TU,
753 StartLoc: DirectiveLoc, Imported: Mod,
754 EndLoc: DirectiveLoc);
755 if (!ModuleScopes.empty())
756 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: ImportD);
757 TU->addDecl(D: ImportD);
758 Consumer.HandleImplicitImportDecl(D: ImportD);
759 }
760
761 getModuleLoader().makeModuleVisible(Mod, Visibility: Module::AllVisible, ImportLoc: DirectiveLoc);
762 VisibleModules.setVisible(M: Mod, Loc: DirectiveLoc);
763
764 if (getLangOpts().isCompilingModule()) {
765 Module *ThisModule = PP.getHeaderSearchInfo().lookupModule(
766 ModuleName: getLangOpts().CurrentModule, ImportLoc: DirectiveLoc, AllowSearch: false, AllowExtraModuleMapSearch: false);
767 (void)ThisModule;
768 // For named modules, the current module name is not known while parsing the
769 // global module fragment and lookupModule may return null.
770 assert((getLangOpts().getCompilingModule() ==
771 LangOptionsBase::CMK_ModuleInterface ||
772 ThisModule) &&
773 "was expecting a module if building a Clang module");
774 }
775}
776
777void Sema::ActOnAnnotModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
778 checkModuleImportContext(S&: *this, M: Mod, ImportLoc: DirectiveLoc, DC: CurContext, FromInclude: true);
779
780 ModuleScopes.push_back(Elt: {});
781 ModuleScopes.back().Module = Mod;
782 if (getLangOpts().ModulesLocalVisibility)
783 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
784
785 VisibleModules.setVisible(M: Mod, Loc: DirectiveLoc);
786
787 // The enclosing context is now part of this module.
788 // FIXME: Consider creating a child DeclContext to hold the entities
789 // lexically within the module.
790 if (getLangOpts().trackLocalOwningModule()) {
791 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
792 cast<Decl>(Val: DC)->setModuleOwnershipKind(
793 getLangOpts().ModulesLocalVisibility
794 ? Decl::ModuleOwnershipKind::VisibleWhenImported
795 : Decl::ModuleOwnershipKind::Visible);
796 cast<Decl>(Val: DC)->setLocalOwningModule(Mod);
797 }
798 }
799}
800
801void Sema::ActOnAnnotModuleEnd(SourceLocation EomLoc, Module *Mod) {
802 if (getLangOpts().ModulesLocalVisibility) {
803 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
804 // Leaving a module hides namespace names, so our visible namespace cache
805 // is now out of date.
806 VisibleNamespaceCache.clear();
807 }
808
809 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
810 "left the wrong module scope");
811 ModuleScopes.pop_back();
812
813 // We got to the end of processing a local module. Create an
814 // ImportDecl as we would for an imported module.
815 FileID File = getSourceManager().getFileID(SpellingLoc: EomLoc);
816 SourceLocation DirectiveLoc;
817 if (EomLoc == getSourceManager().getLocForEndOfFile(FID: File)) {
818 // We reached the end of a #included module header. Use the #include loc.
819 assert(File != getSourceManager().getMainFileID() &&
820 "end of submodule in main source file");
821 DirectiveLoc = getSourceManager().getIncludeLoc(FID: File);
822 } else {
823 // We reached an EOM pragma. Use the pragma location.
824 DirectiveLoc = EomLoc;
825 }
826 BuildModuleInclude(DirectiveLoc, Mod);
827
828 // Any further declarations are in whatever module we returned to.
829 if (getLangOpts().trackLocalOwningModule()) {
830 // The parser guarantees that this is the same context that we entered
831 // the module within.
832 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
833 cast<Decl>(Val: DC)->setLocalOwningModule(getCurrentModule());
834 if (!getCurrentModule())
835 cast<Decl>(Val: DC)->setModuleOwnershipKind(
836 Decl::ModuleOwnershipKind::Unowned);
837 }
838 }
839}
840
841void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
842 Module *Mod) {
843 // Bail if we're not allowed to implicitly import a module here.
844 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
845 VisibleModules.isVisible(M: Mod))
846 return;
847
848 // Create the implicit import declaration.
849 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
850 ImportDecl *ImportD = ImportDecl::CreateImplicit(C&: getASTContext(), DC: TU,
851 StartLoc: Loc, Imported: Mod, EndLoc: Loc);
852 TU->addDecl(D: ImportD);
853 Consumer.HandleImplicitImportDecl(D: ImportD);
854
855 // Make the module visible.
856 getModuleLoader().makeModuleVisible(Mod, Visibility: Module::AllVisible, ImportLoc: Loc);
857 VisibleModules.setVisible(M: Mod, Loc);
858}
859
860Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
861 SourceLocation LBraceLoc) {
862 ExportDecl *D = ExportDecl::Create(C&: Context, DC: CurContext, ExportLoc);
863
864 // Set this temporarily so we know the export-declaration was braced.
865 D->setRBraceLoc(LBraceLoc);
866
867 CurContext->addDecl(D);
868 PushDeclContext(S, DC: D);
869
870 // C++2a [module.interface]p1:
871 // An export-declaration shall appear only [...] in the purview of a module
872 // interface unit. An export-declaration shall not appear directly or
873 // indirectly within [...] a private-module-fragment.
874 if (!getLangOpts().HLSL) {
875 if (!isCurrentModulePurview()) {
876 Diag(Loc: ExportLoc, DiagID: diag::err_export_not_in_module_interface) << 0;
877 D->setInvalidDecl();
878 return D;
879 } else if (currentModuleIsImplementation()) {
880 Diag(Loc: ExportLoc, DiagID: diag::err_export_not_in_module_interface) << 1;
881 Diag(Loc: ModuleScopes.back().BeginLoc,
882 DiagID: diag::note_not_module_interface_add_export)
883 << FixItHint::CreateInsertion(InsertionLoc: ModuleScopes.back().BeginLoc, Code: "export ");
884 D->setInvalidDecl();
885 return D;
886 } else if (ModuleScopes.back().Module->Kind ==
887 Module::PrivateModuleFragment) {
888 Diag(Loc: ExportLoc, DiagID: diag::err_export_in_private_module_fragment);
889 Diag(Loc: ModuleScopes.back().BeginLoc, DiagID: diag::note_private_module_fragment);
890 D->setInvalidDecl();
891 return D;
892 }
893 }
894
895 for (const DeclContext *DC = CurContext; DC; DC = DC->getLexicalParent()) {
896 if (const auto *ND = dyn_cast<NamespaceDecl>(Val: DC)) {
897 // An export-declaration shall not appear directly or indirectly within
898 // an unnamed namespace [...]
899 if (ND->isAnonymousNamespace()) {
900 Diag(Loc: ExportLoc, DiagID: diag::err_export_within_anonymous_namespace);
901 Diag(Loc: ND->getLocation(), DiagID: diag::note_anonymous_namespace);
902 // Don't diagnose internal-linkage declarations in this region.
903 D->setInvalidDecl();
904 return D;
905 }
906
907 // A declaration is exported if it is [...] a namespace-definition
908 // that contains an exported declaration.
909 //
910 // Defer exporting the namespace until after we leave it, in order to
911 // avoid marking all subsequent declarations in the namespace as exported.
912 if (!getLangOpts().HLSL && !DeferredExportedNamespaces.insert(Ptr: ND).second)
913 break;
914 }
915 }
916
917 // [...] its declaration or declaration-seq shall not contain an
918 // export-declaration.
919 if (auto *ED = getEnclosingExportDecl(D)) {
920 Diag(Loc: ExportLoc, DiagID: diag::err_export_within_export);
921 if (ED->hasBraces())
922 Diag(Loc: ED->getLocation(), DiagID: diag::note_export);
923 D->setInvalidDecl();
924 return D;
925 }
926
927 if (!getLangOpts().HLSL)
928 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
929
930 return D;
931}
932
933static bool checkExportedDecl(Sema &, Decl *, SourceLocation);
934
935/// Check that it's valid to export all the declarations in \p DC.
936static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
937 SourceLocation BlockStart) {
938 bool AllUnnamed = true;
939 for (auto *D : DC->decls())
940 AllUnnamed &= checkExportedDecl(S, D, BlockStart);
941 return AllUnnamed;
942}
943
944/// Check that it's valid to export \p D.
945static bool checkExportedDecl(Sema &S, Decl *D, SourceLocation BlockStart) {
946
947 // HLSL: export declaration is valid only on functions
948 if (S.getLangOpts().HLSL) {
949 // Export-within-export was already diagnosed in ActOnStartExportDecl
950 if (!isa<FunctionDecl, ExportDecl, ExplicitInstantiationDecl>(Val: D)) {
951 S.Diag(Loc: D->getBeginLoc(), DiagID: diag::err_hlsl_export_not_on_function);
952 D->setInvalidDecl();
953 return false;
954 }
955
956 if (isa<FunctionDecl>(Val: D)) {
957 FunctionDecl *FD = cast<FunctionDecl>(Val: D);
958 for (const ParmVarDecl *PVD : FD->parameters()) {
959 if (PVD->hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
960 S.Diag(Loc: D->getBeginLoc(), DiagID: diag::err_hlsl_attr_incompatible)
961 << "'export'" << "'groupshared' parameter";
962 D->setInvalidDecl();
963 return false;
964 }
965 }
966 }
967 }
968
969 // C++20 [module.interface]p3:
970 // [...] it shall not declare a name with internal linkage.
971 bool HasName = false;
972 if (auto *ND = dyn_cast<NamedDecl>(Val: D)) {
973 // Don't diagnose anonymous union objects; we'll diagnose their members
974 // instead.
975 HasName = (bool)ND->getDeclName();
976 if (HasName && ND->getFormalLinkage() == Linkage::Internal) {
977 S.Diag(Loc: ND->getLocation(), DiagID: diag::err_export_internal) << ND;
978 if (BlockStart.isValid())
979 S.Diag(Loc: BlockStart, DiagID: diag::note_export);
980 return false;
981 }
982 }
983
984 // C++2a [module.interface]p5:
985 // all entities to which all of the using-declarators ultimately refer
986 // shall have been introduced with a name having external linkage
987 if (auto *USD = dyn_cast<UsingShadowDecl>(Val: D)) {
988 NamedDecl *Target = USD->getUnderlyingDecl();
989 Linkage Lk = Target->getFormalLinkage();
990 if (Lk == Linkage::Internal || Lk == Linkage::Module) {
991 S.Diag(Loc: USD->getLocation(), DiagID: diag::err_export_using_internal)
992 << (Lk == Linkage::Internal ? 0 : 1) << Target;
993 S.Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
994 if (BlockStart.isValid())
995 S.Diag(Loc: BlockStart, DiagID: diag::note_export);
996 return false;
997 }
998 }
999
1000 // Recurse into namespace-scope DeclContexts. (Only namespace-scope
1001 // declarations are exported).
1002 if (auto *DC = dyn_cast<DeclContext>(Val: D)) {
1003 if (!isa<NamespaceDecl>(Val: D))
1004 return true;
1005
1006 if (auto *ND = dyn_cast<NamedDecl>(Val: D)) {
1007 if (!ND->getDeclName()) {
1008 S.Diag(Loc: ND->getLocation(), DiagID: diag::err_export_anon_ns_internal);
1009 if (BlockStart.isValid())
1010 S.Diag(Loc: BlockStart, DiagID: diag::note_export);
1011 return false;
1012 } else if (!DC->decls().empty() &&
1013 DC->getRedeclContext()->isFileContext()) {
1014 return checkExportedDeclContext(S, DC, BlockStart);
1015 }
1016 }
1017 }
1018 return true;
1019}
1020
1021Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
1022 auto *ED = cast<ExportDecl>(Val: D);
1023 if (RBraceLoc.isValid())
1024 ED->setRBraceLoc(RBraceLoc);
1025
1026 PopDeclContext();
1027
1028 if (!D->isInvalidDecl()) {
1029 SourceLocation BlockStart =
1030 ED->hasBraces() ? ED->getBeginLoc() : SourceLocation();
1031 for (auto *Child : ED->decls()) {
1032 checkExportedDecl(S&: *this, D: Child, BlockStart);
1033 if (auto *FD = dyn_cast<FunctionDecl>(Val: Child)) {
1034 // [dcl.inline]/7
1035 // If an inline function or variable that is attached to a named module
1036 // is declared in a definition domain, it shall be defined in that
1037 // domain.
1038 // So, if the current declaration does not have a definition, we must
1039 // check at the end of the TU (or when the PMF starts) to see that we
1040 // have a definition at that point.
1041 if (FD->isInlineSpecified() && !FD->isDefined())
1042 PendingInlineFuncDecls.insert(Ptr: FD);
1043 }
1044 }
1045 }
1046
1047 // Anything exported from a module should never be considered unused.
1048 for (auto *Exported : ED->decls())
1049 Exported->markUsed(C&: getASTContext());
1050
1051 return D;
1052}
1053
1054Module *Sema::PushGlobalModuleFragment(SourceLocation BeginLoc) {
1055 // We shouldn't create new global module fragment if there is already
1056 // one.
1057 if (!TheGlobalModuleFragment) {
1058 ModuleMap &Map = PP.getHeaderSearchInfo().getModuleMap();
1059 TheGlobalModuleFragment = Map.createGlobalModuleFragmentForModuleUnit(
1060 Loc: BeginLoc, Parent: getCurrentModule());
1061 }
1062
1063 assert(TheGlobalModuleFragment && "module creation should not fail");
1064
1065 // Enter the scope of the global module.
1066 ModuleScopes.push_back(Elt: {.BeginLoc: BeginLoc, .Module: TheGlobalModuleFragment,
1067 /*OuterVisibleModules=*/{}});
1068 VisibleModules.setVisible(M: TheGlobalModuleFragment, Loc: BeginLoc);
1069
1070 return TheGlobalModuleFragment;
1071}
1072
1073void Sema::PopGlobalModuleFragment() {
1074 assert(!ModuleScopes.empty() &&
1075 getCurrentModule()->isExplicitGlobalModule() &&
1076 "left the wrong module scope, which is not global module fragment");
1077 ModuleScopes.pop_back();
1078}
1079
1080Module *Sema::PushImplicitGlobalModuleFragment(SourceLocation BeginLoc) {
1081 if (!TheImplicitGlobalModuleFragment) {
1082 ModuleMap &Map = PP.getHeaderSearchInfo().getModuleMap();
1083 TheImplicitGlobalModuleFragment =
1084 Map.createImplicitGlobalModuleFragmentForModuleUnit(Loc: BeginLoc,
1085 Parent: getCurrentModule());
1086 }
1087 assert(TheImplicitGlobalModuleFragment && "module creation should not fail");
1088
1089 // Enter the scope of the global module.
1090 ModuleScopes.push_back(Elt: {.BeginLoc: BeginLoc, .Module: TheImplicitGlobalModuleFragment,
1091 /*OuterVisibleModules=*/{}});
1092 VisibleModules.setVisible(M: TheImplicitGlobalModuleFragment, Loc: BeginLoc);
1093 return TheImplicitGlobalModuleFragment;
1094}
1095
1096void Sema::PopImplicitGlobalModuleFragment() {
1097 assert(!ModuleScopes.empty() &&
1098 getCurrentModule()->isImplicitGlobalModule() &&
1099 "left the wrong module scope, which is not global module fragment");
1100 ModuleScopes.pop_back();
1101}
1102
1103bool Sema::isCurrentModulePurview() const {
1104 if (!getCurrentModule())
1105 return false;
1106
1107 /// Does this Module scope describe part of the purview of a standard named
1108 /// C++ module?
1109 switch (getCurrentModule()->Kind) {
1110 case Module::ModuleInterfaceUnit:
1111 case Module::ModuleImplementationUnit:
1112 case Module::ModulePartitionInterface:
1113 case Module::ModulePartitionImplementation:
1114 case Module::PrivateModuleFragment:
1115 case Module::ImplicitGlobalModuleFragment:
1116 return true;
1117 default:
1118 return false;
1119 }
1120}
1121
1122//===----------------------------------------------------------------------===//
1123// Checking Exposure in modules //
1124//===----------------------------------------------------------------------===//
1125
1126namespace {
1127class ExposureChecker {
1128public:
1129 ExposureChecker(Sema &S) : SemaRef(S) {}
1130
1131 bool checkExposure(const VarDecl *D, bool Diag);
1132 bool checkExposure(const CXXRecordDecl *D, bool Diag);
1133 bool checkExposure(const Stmt *S, bool Diag);
1134 bool checkExposure(const FunctionDecl *D, bool Diag);
1135 bool checkExposure(const NamedDecl *D, bool Diag);
1136 void checkExposureInContext(const DeclContext *DC);
1137 bool isExposureCandidate(const NamedDecl *D);
1138
1139 bool isTULocal(QualType Ty);
1140 bool isTULocal(const NamedDecl *ND);
1141 bool isTULocal(const Expr *E);
1142
1143 Sema &SemaRef;
1144
1145private:
1146 llvm::DenseSet<const NamedDecl *> ExposureSet;
1147 llvm::DenseSet<const NamedDecl *> KnownNonExposureSet;
1148 llvm::DenseSet<const NamedDecl *> CheckingDecls;
1149};
1150
1151bool ExposureChecker::isTULocal(QualType Ty) {
1152 // [basic.link]p15:
1153 // An entity is TU-local if it is
1154 // - a type, type alias, namespace, namespace alias, function, variable, or
1155 // template that
1156 // -- has internal linkage, or
1157 return Ty->getLinkage() == Linkage::Internal;
1158
1159 // TODO:
1160 // [basic.link]p15.2:
1161 // a type with no name that is defined outside a class-specifier, function
1162 // body, or initializer or is introduced by a defining-type-specifier that
1163 // is used to declare only TU-local entities,
1164}
1165
1166bool ExposureChecker::isTULocal(const NamedDecl *D) {
1167 if (!D)
1168 return false;
1169
1170 // [basic.link]p15:
1171 // An entity is TU-local if it is
1172 // - a type, type alias, namespace, namespace alias, function, variable, or
1173 // template that
1174 // -- has internal linkage, or
1175 if (D->getLinkageInternal() == Linkage::Internal)
1176 return true;
1177
1178 if (D->isInAnonymousNamespace())
1179 return true;
1180
1181 // [basic.link]p15.1.2:
1182 // does not have a name with linkage and is declared, or introduced by a
1183 // lambda-expression, within the definition of a TU-local entity,
1184 if (D->getLinkageInternal() == Linkage::None)
1185 if (auto *ND = dyn_cast<NamedDecl>(Val: D->getDeclContext());
1186 ND && isTULocal(D: ND))
1187 return true;
1188
1189 // [basic.link]p15.3, p15.4:
1190 // - a specialization of a TU-local template,
1191 // - a specialization of a template with any TU-local template argument, or
1192 ArrayRef<TemplateArgument> TemplateArgs;
1193 NamedDecl *PrimaryTemplate = nullptr;
1194 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: D)) {
1195 TemplateArgs = CTSD->getTemplateArgs().asArray();
1196 PrimaryTemplate = CTSD->getSpecializedTemplate();
1197 if (isTULocal(D: PrimaryTemplate))
1198 return true;
1199 } else if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Val: D)) {
1200 TemplateArgs = VTSD->getTemplateArgs().asArray();
1201 PrimaryTemplate = VTSD->getSpecializedTemplate();
1202 if (isTULocal(D: PrimaryTemplate))
1203 return true;
1204 } else if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
1205 if (auto *TAList = FD->getTemplateSpecializationArgs())
1206 TemplateArgs = TAList->asArray();
1207
1208 PrimaryTemplate = FD->getPrimaryTemplate();
1209 if (isTULocal(D: PrimaryTemplate))
1210 return true;
1211 }
1212
1213 if (!PrimaryTemplate)
1214 // Following off, we only check for specializations.
1215 return false;
1216
1217 if (KnownNonExposureSet.count(V: D))
1218 return false;
1219
1220 for (auto &TA : TemplateArgs) {
1221 switch (TA.getKind()) {
1222 case TemplateArgument::Type:
1223 if (isTULocal(Ty: TA.getAsType()))
1224 return true;
1225 break;
1226 case TemplateArgument::Declaration:
1227 if (isTULocal(D: TA.getAsDecl()))
1228 return true;
1229 break;
1230 default:
1231 break;
1232 }
1233 }
1234
1235 // Avoid recursions.
1236 if (CheckingDecls.count(V: D))
1237 return false;
1238 CheckingDecls.insert(V: D);
1239 llvm::scope_exit RemoveCheckingDecls([&] { CheckingDecls.erase(V: D); });
1240
1241 // [basic.link]p15.5
1242 // - a specialization of a template whose (possibly instantiated) declaration
1243 // is an exposure.
1244 if (ExposureSet.count(V: PrimaryTemplate) ||
1245 checkExposure(D: PrimaryTemplate, /*Diag=*/false))
1246 return true;
1247
1248 // Avoid calling checkExposure again since it is expensive.
1249 KnownNonExposureSet.insert(V: D);
1250 return false;
1251}
1252
1253bool ExposureChecker::isTULocal(const Expr *E) {
1254 if (!E)
1255 return false;
1256
1257 // [basic.link]p16:
1258 // A value or object is TU-local if either
1259 // - it is of TU-local type,
1260 if (isTULocal(Ty: E->getType()))
1261 return true;
1262
1263 E = E->IgnoreParenImpCasts();
1264 // [basic.link]p16.2:
1265 // - it is, or is a pointer to, a TU-local function or the object associated
1266 // with a TU-local variable,
1267 // - it is an object of class or array type and any of its subobjects or any
1268 // of the objects or functions to which its non-static data members of
1269 // reference type refer is TU-local and is usable in constant expressions, or
1270 // FIXME: But how can we know the value of pointers or arrays at compile time?
1271 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
1272 if (auto *FD = dyn_cast_or_null<FunctionDecl>(Val: DRE->getFoundDecl()))
1273 return isTULocal(D: FD);
1274 else if (auto *VD = dyn_cast_or_null<VarDecl>(Val: DRE->getFoundDecl()))
1275 return isTULocal(D: VD);
1276 else if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Val: DRE->getFoundDecl()))
1277 return isTULocal(D: RD);
1278 }
1279
1280 // TODO:
1281 // [basic.link]p16.4:
1282 // it is a reflection value that represents...
1283
1284 return false;
1285}
1286
1287bool ExposureChecker::isExposureCandidate(const NamedDecl *D) {
1288 if (!D)
1289 return false;
1290
1291 // [basic.link]p17:
1292 // If a (possibly instantiated) declaration of, or a deduction guide for,
1293 // a non-TU-local entity in a module interface unit
1294 // (outside the private-module-fragment, if any) or
1295 // module partition is an exposure, the program is ill-formed.
1296 Module *M = D->getOwningModule();
1297 if (!M)
1298 return false;
1299 // If M is implicit global module, the declaration must be in the purview of
1300 // a module unit.
1301 if (M->isImplicitGlobalModule()) {
1302 M = M->Parent;
1303 assert(M && "Implicit global module must have a parent");
1304 }
1305
1306 if (!M->isInterfaceOrPartition())
1307 return false;
1308
1309 if (D->isImplicit())
1310 return false;
1311
1312 // [basic.link]p14:
1313 // A declaration is an exposure if it either names a TU-local entity
1314 // (defined below), ignoring:
1315 // ...
1316 // - friend declarations in a class definition
1317 if (D->getFriendObjectKind() &&
1318 isa<CXXRecordDecl>(Val: D->getLexicalDeclContext()))
1319 return false;
1320
1321 return true;
1322}
1323
1324bool ExposureChecker::checkExposure(const NamedDecl *D, bool Diag) {
1325 if (!isExposureCandidate(D))
1326 return false;
1327
1328 if (auto *FD = dyn_cast<FunctionDecl>(Val: D))
1329 return checkExposure(D: FD, Diag);
1330 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: D))
1331 return checkExposure(D: FTD->getTemplatedDecl(), Diag);
1332
1333 if (auto *VD = dyn_cast<VarDecl>(Val: D))
1334 return checkExposure(D: VD, Diag);
1335 if (auto *VTD = dyn_cast<VarTemplateDecl>(Val: D))
1336 return checkExposure(D: VTD->getTemplatedDecl(), Diag);
1337
1338 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
1339 return checkExposure(D: RD, Diag);
1340
1341 if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: D))
1342 return checkExposure(D: CTD->getTemplatedDecl(), Diag);
1343
1344 return false;
1345}
1346
1347bool ExposureChecker::checkExposure(const FunctionDecl *FD, bool Diag) {
1348 bool IsExposure = false;
1349 if (isTULocal(Ty: FD->getReturnType())) {
1350 IsExposure = true;
1351 if (Diag)
1352 SemaRef.Diag(Loc: FD->getReturnTypeSourceRange().getBegin(),
1353 DiagID: diag::warn_exposure)
1354 << FD->getReturnType();
1355 }
1356
1357 for (ParmVarDecl *Parms : FD->parameters())
1358 if (isTULocal(Ty: Parms->getType())) {
1359 IsExposure = true;
1360 if (Diag)
1361 SemaRef.Diag(Loc: Parms->getLocation(), DiagID: diag::warn_exposure)
1362 << Parms->getType();
1363 }
1364
1365 bool IsImplicitInstantiation =
1366 FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1367
1368 // [basic.link]p14:
1369 // A declaration is an exposure if it either names a TU-local entity
1370 // (defined below), ignoring:
1371 // - the function-body for a non-inline function or function template
1372 // (but not the deduced return
1373 // type for a (possibly instantiated) definition of a function with a
1374 // declared return type that uses a placeholder type
1375 // ([dcl.spec.auto])),
1376 Diag &=
1377 (FD->isInlined() || IsImplicitInstantiation) && !FD->isDependentContext();
1378
1379 IsExposure |= checkExposure(S: FD->getBody(), Diag);
1380 if (IsExposure)
1381 ExposureSet.insert(V: FD);
1382
1383 return IsExposure;
1384}
1385
1386bool ExposureChecker::checkExposure(const VarDecl *VD, bool Diag) {
1387 bool IsExposure = false;
1388 // [basic.link]p14:
1389 // A declaration is an exposure if it either names a TU-local entity (defined
1390 // below), ignoring:
1391 // ...
1392 // or defines a constexpr variable initialized to a TU-local value (defined
1393 // below).
1394 if (VD->isConstexpr() && isTULocal(E: VD->getInit())) {
1395 IsExposure = true;
1396 if (Diag)
1397 SemaRef.Diag(Loc: VD->getInit()->getExprLoc(), DiagID: diag::warn_exposure)
1398 << VD->getInit();
1399 }
1400
1401 if (isTULocal(Ty: VD->getType())) {
1402 IsExposure = true;
1403 if (Diag)
1404 SemaRef.Diag(Loc: VD->getLocation(), DiagID: diag::warn_exposure) << VD->getType();
1405 }
1406
1407 // [basic.link]p14:
1408 // ..., ignoring:
1409 // - the initializer for a variable or variable template (but not the
1410 // variable's type),
1411 //
1412 // Note: although the spec says to ignore the initializer for all variable,
1413 // for the code we generated now for inline variables, it is dangerous if the
1414 // initializer of an inline variable is TULocal.
1415 Diag &= !VD->getDeclContext()->isDependentContext() && VD->isInline();
1416 IsExposure |= checkExposure(S: VD->getInit(), Diag);
1417 if (IsExposure)
1418 ExposureSet.insert(V: VD);
1419
1420 return IsExposure;
1421}
1422
1423bool ExposureChecker::checkExposure(const CXXRecordDecl *RD, bool Diag) {
1424 if (!RD->hasDefinition())
1425 return false;
1426
1427 bool IsExposure = false;
1428 for (CXXMethodDecl *Method : RD->methods())
1429 IsExposure |= checkExposure(FD: Method, Diag);
1430
1431 for (FieldDecl *FD : RD->fields()) {
1432 if (isTULocal(Ty: FD->getType())) {
1433 IsExposure = true;
1434 if (Diag)
1435 SemaRef.Diag(Loc: FD->getLocation(), DiagID: diag::warn_exposure) << FD->getType();
1436 }
1437 }
1438
1439 for (const CXXBaseSpecifier &Base : RD->bases()) {
1440 if (isTULocal(Ty: Base.getType())) {
1441 IsExposure = true;
1442 if (Diag)
1443 SemaRef.Diag(Loc: Base.getBaseTypeLoc(), DiagID: diag::warn_exposure)
1444 << Base.getType();
1445 }
1446 }
1447
1448 if (IsExposure)
1449 ExposureSet.insert(V: RD);
1450
1451 return IsExposure;
1452}
1453
1454class ReferenceTULocalChecker : public DynamicRecursiveASTVisitor {
1455public:
1456 using CallbackTy = std::function<void(SourceLocation, NamedDecl *)>;
1457
1458 ReferenceTULocalChecker(ExposureChecker &C, CallbackTy &&Callback)
1459 : Checker(C), Callback(std::move(Callback)) {}
1460
1461 bool VisitDeclRefExpr(DeclRefExpr *DRE) override {
1462 ValueDecl *Referenced = DRE->getDecl();
1463 if (!Referenced)
1464 return true;
1465
1466 if (!Checker.isTULocal(D: Referenced))
1467 // We don't care if the referenced declaration is not TU-local.
1468 return true;
1469
1470 Qualifiers Qual = DRE->getType().getQualifiers();
1471 // [basic.link]p14:
1472 // A declaration is an exposure if it either names a TU-local entity
1473 // (defined below), ignoring:
1474 // ...
1475 // - any reference to a non-volatile const object ...
1476 if (Qual.hasConst() && !Qual.hasVolatile())
1477 return true;
1478
1479 // [basic.link]p14:
1480 // ..., ignoring:
1481 // ...
1482 // (p14.4) - ... or reference with internal or no linkage initialized with
1483 // a constant expression that is not an odr-use
1484 ASTContext &Context = Referenced->getASTContext();
1485 Linkage L = Referenced->getLinkageInternal();
1486 if (DRE->isNonOdrUse() && (L == Linkage::Internal || L == Linkage::None))
1487 if (auto *VD = dyn_cast<VarDecl>(Val: Referenced);
1488 VD && VD->getInit() && !VD->getInit()->isValueDependent() &&
1489 VD->getInit()->isConstantInitializer(Ctx&: Context))
1490 return true;
1491
1492 Callback(DRE->getExprLoc(), Referenced);
1493 return true;
1494 }
1495
1496 bool VisitTagTypeLoc(TagTypeLoc TL) override {
1497 TagDecl *Referenced = TL.getDecl();
1498 if (Checker.isTULocal(D: Referenced))
1499 Callback(TL.getNameLoc(), Referenced);
1500 return true;
1501 }
1502
1503 ExposureChecker &Checker;
1504 CallbackTy Callback;
1505};
1506
1507bool ExposureChecker::checkExposure(const Stmt *S, bool Diag) {
1508 if (!S)
1509 return false;
1510
1511 bool HasReferencedTULocals = false;
1512 ReferenceTULocalChecker Checker(
1513 *this, [this, &HasReferencedTULocals, Diag](SourceLocation Loc,
1514 NamedDecl *Referenced) {
1515 if (Diag) {
1516 SemaRef.Diag(Loc, DiagID: diag::warn_exposure) << Referenced;
1517 }
1518 HasReferencedTULocals = true;
1519 });
1520 Checker.TraverseStmt(S: const_cast<Stmt *>(S));
1521 return HasReferencedTULocals;
1522}
1523
1524void ExposureChecker::checkExposureInContext(const DeclContext *DC) {
1525 for (auto *TopD : DC->noload_decls()) {
1526 if (auto *Export = dyn_cast<ExportDecl>(Val: TopD)) {
1527 checkExposureInContext(DC: Export);
1528 continue;
1529 }
1530
1531 if (auto *LinkageSpec = dyn_cast<LinkageSpecDecl>(Val: TopD)) {
1532 checkExposureInContext(DC: LinkageSpec);
1533 continue;
1534 }
1535
1536 auto *TopND = dyn_cast<NamedDecl>(Val: TopD);
1537 if (!TopND)
1538 continue;
1539
1540 if (auto *Namespace = dyn_cast<NamespaceDecl>(Val: TopND)) {
1541 checkExposureInContext(DC: Namespace);
1542 continue;
1543 }
1544
1545 // [basic.link]p17:
1546 // If a (possibly instantiated) declaration of, or a deduction guide for,
1547 // a non-TU-local entity in a module interface unit
1548 // (outside the private-module-fragment, if any) or
1549 // module partition is an exposure, the program is ill-formed.
1550 if (!TopND->isFromASTFile() && isExposureCandidate(D: TopND) &&
1551 !isTULocal(D: TopND))
1552 checkExposure(D: TopND, /*Diag=*/true);
1553 }
1554}
1555
1556} // namespace
1557
1558void Sema::checkExposure(const TranslationUnitDecl *TU) {
1559 if (!TU)
1560 return;
1561
1562 ExposureChecker Checker(*this);
1563
1564 Module *M = TU->getOwningModule();
1565 if (M && M->isInterfaceOrPartition())
1566 Checker.checkExposureInContext(DC: TU);
1567
1568 // [basic.link]p18:
1569 // If a declaration that appears in one translation unit names a TU-local
1570 // entity declared in another translation unit that is not a header unit,
1571 // the program is ill-formed.
1572 for (auto FDAndInstantiationLocPair : PendingCheckReferenceForTULocal) {
1573 FunctionDecl *FD = FDAndInstantiationLocPair.first;
1574 SourceLocation PointOfInstantiation = FDAndInstantiationLocPair.second;
1575
1576 // Substitution may fail before an instantiated body is formed. The pattern
1577 // still contains non-dependent references to TU-local entities, use the
1578 // instantiation pattern as the body.
1579 const FunctionDecl *BodyOwner = FD;
1580 if (!BodyOwner->hasBody())
1581 BodyOwner = FD->getTemplateInstantiationPattern();
1582 if (!BodyOwner || !BodyOwner->hasBody())
1583 continue;
1584
1585 ReferenceTULocalChecker(Checker, [&, this](SourceLocation,
1586 NamedDecl *Referenced) {
1587 // A "defect" in current implementation. Now an implicit instantiation of
1588 // a template, the instantiation is considered to be in the same module
1589 // unit as the template instead of the module unit where the instantiation
1590 // happens.
1591 //
1592 // See test/Modules/Exposre-2.cppm for example.
1593 if (!Referenced->isFromASTFile())
1594 return;
1595
1596 if (!Referenced->isInAnotherModuleUnit())
1597 return;
1598
1599 // This is not standard conforming. But given there are too many static
1600 // (inline) functions in headers in existing code, it is more user
1601 // friendly to ignore them temporarily now. maybe we can have another flag
1602 // for this.
1603 if (Referenced->getOwningModule()->isExplicitGlobalModule() &&
1604 isa<FunctionDecl>(Val: Referenced))
1605 return;
1606
1607 Diag(Loc: PointOfInstantiation,
1608 DiagID: diag::warn_reference_tu_local_entity_in_other_tu)
1609 << FD << Referenced
1610 << Referenced->getOwningModule()->getTopLevelModuleName();
1611 }).TraverseStmt(S: BodyOwner->getBody());
1612 }
1613}
1614
1615void Sema::checkReferenceToTULocalFromOtherTU(
1616 FunctionDecl *FD, SourceLocation PointOfInstantiation) {
1617 // Checking if a declaration have any reference to TU-local entities in other
1618 // TU is expensive. Try to avoid it as much as possible.
1619 if (!FD || !HadImportedNamedModules)
1620 return;
1621
1622 PendingCheckReferenceForTULocal.push_back(
1623 Elt: std::make_pair(x&: FD, y&: PointOfInstantiation));
1624}
1625