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