clang 23.0.0git
SemaModule.cpp
Go to the documentation of this file.
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
21#include "llvm/ADT/ScopeExit.h"
22#include "llvm/ADT/StringExtras.h"
23
24using namespace clang;
25using namespace sema;
26
28 SourceLocation ImportLoc, DeclContext *DC,
29 bool FromInclude = false) {
30 SourceLocation ExternCLoc;
31
32 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
33 switch (LSD->getLanguage()) {
35 if (ExternCLoc.isInvalid())
36 ExternCLoc = LSD->getBeginLoc();
37 break;
39 break;
40 }
41 DC = LSD->getParent();
42 }
43
44 while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
45 DC = DC->getParent();
46
47 if (!isa<TranslationUnitDecl>(DC)) {
48 S.Diag(ImportLoc, (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(cast<Decl>(DC)->getBeginLoc(),
53 diag::note_module_import_not_at_top_level)
54 << DC;
55 } else if (!M->IsExternC && ExternCLoc.isValid()) {
56 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
57 << M->getFullModuleName();
58 S.Diag(ExternCLoc, 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
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(Imported, 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
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
125 Worklist.push_back(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(Importing))
134 continue;
135 Visited.insert(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(Importing, ImportLoc);
140
141 if (isImportingModuleUnitFromSameModule(Ctx, Importing, CurrentModule,
142 FoundPrimaryModuleInterface)) {
143 for (Module *TransImported : Importing->Imports)
144 Worklist.push_back(TransImported);
145
146 for (auto [Exports, _] : Importing->Exports)
147 Worklist.push_back(Exports);
148 }
149 }
150}
151
154 // We start in the global module;
155 Module *GlobalModule =
156 PushGlobalModuleFragment(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(SourceMgr.getMainFileID());
179
180 StringRef HUName = getLangOpts().CurrentModule;
181 if (HUName.empty()) {
182 HUName =
183 SourceMgr.getFileEntryRefForID(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(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(SourceMgr.getMainFileID());
196 assert(F && "failed to find the header unit source?");
197 Module::Header H{HUName.str(), HUName.str(), *F};
198 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
199 Module *Mod = Map.createHeaderUnit(StartOfTU, HUName, H);
200 assert(Mod && "module creation should not fail");
201 ModuleScopes.push_back({}); // No GMF
202 ModuleScopes.back().BeginLoc = StartOfTU;
203 ModuleScopes.back().Module = Mod;
204 VisibleModules.setVisible(Mod, 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.
217 SourceLocation Loc) {
218 enum {
219 Valid = -1,
220 Invalid = 0,
221 Reserved = 1,
222 } Reason = Valid;
223
224 if (II->isStr("module") || II->isStr("import"))
225 Reason = Invalid;
226 else if (II->isReserved(S.getLangOpts()) !=
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, diag::err_invalid_module_name) << II;
241 case Reserved:
242 S.Diag(Loc, diag::warn_reserved_module_name) << II;
243 return false;
244 }
245 llvm_unreachable("fell off a fully covered switch");
246}
247
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;
261
262 bool IsPartition = !Partition.empty();
263 if (IsPartition)
264 switch (MDK) {
267 break;
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()) {
282 // It's OK to compile a module interface as a normal translation unit.
283 break;
284
287 break;
288
289 // We were asked to compile a module interface unit but this is a module
290 // implementation unit.
291 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
292 << FixItHint::CreateInsertion(ModuleLoc, "export ");
294 break;
295
297 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
298 return nullptr;
299
301 Diag(ModuleLoc, 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(ModuleLoc, diag::err_module_redeclaration);
313 Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
314 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(ModuleLoc, diag::err_module_decl_not_at_start);
327 SourceLocation BeginLoc = PP.getMainFileFirstPPTokenLoc();
328 Diag(BeginLoc, diag::note_global_module_introducer_missing)
329 << FixItHint::CreateInsertion(BeginLoc, "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(Path[0].getLoc()) &&
343 (FirstComponentName == "std" ||
344 (FirstComponentName.starts_with("std") &&
345 llvm::all_of(FirstComponentName.drop_front(3), &llvm::isDigit))))
346 Diag(Path[0].getLoc(), 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(*this, Part.getIdentifierInfo(), 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(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(Path.front().getLoc(), diag::err_current_module_name_mismatch)
369 << SourceRange(Path.front().getLoc(), IsPartition
370 ? Partition.back().getLoc()
371 : Path.back().getLoc())
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) {
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(ModuleName)) {
386 Diag(Path[0].getLoc(), diag::err_module_redefinition) << ModuleName;
387 if (M->DefinitionLoc.isValid())
388 Diag(M->DefinitionLoc, diag::note_prev_module_definition);
389 else if (const ModuleFileName *FileName = M->getASTFileName())
390 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
391 << *FileName;
392 Mod = M;
393 break;
394 }
395
396 // Create a Module for the module that we're defining.
397 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
400 assert(Mod && "module creation should not fail");
401 break;
402 }
403
405 // C++20 A module-declaration that contains neither an export-
406 // keyword nor a module-partition implicitly imports the primary
407 // module interface unit of the module as if by a module-import-
408 // declaration.
409 IdentifierLoc ModuleNameLoc(Path[0].getLoc(),
410 PP.getIdentifierInfo(ModuleName));
411
412 // The module loader will assume we're trying to import the module that
413 // we're building if `LangOpts.CurrentModule` equals to 'ModuleName'.
414 // Change the value for `LangOpts.CurrentModule` temporarily to make the
415 // module loader work properly.
416 const_cast<LangOptions &>(getLangOpts()).CurrentModule = "";
419 /*IsInclusionDirective=*/false);
420 const_cast<LangOptions &>(getLangOpts()).CurrentModule = ModuleName;
421
422 if (!Interface) {
423 Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
424 // Create an empty module interface unit for error recovery.
425 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
426 } else {
427 Mod = Map.createModuleForImplementationUnit(ModuleLoc, ModuleName);
428 }
429 } break;
430
432 // Create an interface, but note that it is an implementation
433 // unit.
434 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
436 break;
437 }
438
439 if (!this->TheGlobalModuleFragment) {
440 ModuleScopes.push_back({});
441 if (getLangOpts().ModulesLocalVisibility)
442 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
443 } else {
444 // We're done with the global module fragment now.
446 }
447
448 // Switch from the global module fragment (if any) to the named module.
449 ModuleScopes.back().BeginLoc = StartLoc;
450 ModuleScopes.back().Module = Mod;
451 VisibleModules.setVisible(Mod, ModuleLoc);
452
453 // From now on, we have an owning module for all declarations we see.
454 // In C++20 modules, those declaration would be reachable when imported
455 // unless explicitily exported.
456 // Otherwise, those declarations are module-private unless explicitly
457 // exported.
458 auto *TU = Context.getTranslationUnitDecl();
459 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ReachableWhenImported);
460 TU->setLocalOwningModule(Mod);
461
462 // We are in the module purview, but before any other (non import)
463 // statements, so imports are allowed.
465
467
468 // We already potentially made an implicit import (in the case of a module
469 // implementation unit importing its interface). Make this module visible
470 // and return the import decl to be added to the current TU.
471 if (Interface) {
472 HadImportedNamedModules = true;
473
475 Mod, ModuleLoc,
476 /*IsImportingPrimaryModuleInterface=*/true);
477
478 // Make the import decl for the interface in the impl module.
479 ImportDecl *Import = ImportDecl::Create(Context, CurContext, ModuleLoc,
480 Interface, Path[0].getLoc());
481 CurContext->addDecl(Import);
482
483 // Sequence initialization of the imported module before that of the current
484 // module, if any.
485 Context.addModuleInitializer(ModuleScopes.back().Module, Import);
486 Mod->Imports.insert(Interface); // As if we imported it.
487 // Also save this as a shortcut to checking for decls in the interface
488 ThePrimaryInterface = Interface;
489 // If we made an implicit import of the module interface, then return the
490 // imported module decl.
491 return ConvertDeclToDeclGroup(Import);
492 }
493
494 return nullptr;
495}
496
499 SourceLocation PrivateLoc) {
500 // C++20 [basic.link]/2:
501 // A private-module-fragment shall appear only in a primary module
502 // interface unit.
503 switch (ModuleScopes.empty() ? Module::ExplicitGlobalModuleFragment
504 : ModuleScopes.back().Module->Kind) {
511 Diag(PrivateLoc, diag::err_private_module_fragment_not_module);
512 return nullptr;
513
515 Diag(PrivateLoc, diag::err_private_module_fragment_redefined);
516 Diag(ModuleScopes.back().BeginLoc, diag::note_previous_definition);
517 return nullptr;
518
520 Diag(PrivateLoc, diag::err_private_module_fragment_not_module_interface);
521 Diag(ModuleScopes.back().BeginLoc,
522 diag::note_not_module_interface_add_export)
523 << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
524 return nullptr;
525
527 break;
528 }
529
530 // FIXME: Check that this translation unit does not import any partitions;
531 // such imports would violate [basic.link]/2's "shall be the only module unit"
532 // restriction.
533
534 // We've finished the public fragment of the translation unit.
536
537 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
538 Module *PrivateModuleFragment =
539 Map.createPrivateModuleFragmentForInterfaceUnit(
540 ModuleScopes.back().Module, PrivateLoc);
541 assert(PrivateModuleFragment && "module creation should not fail");
542
543 // Enter the scope of the private module fragment.
544 ModuleScopes.push_back({});
545 ModuleScopes.back().BeginLoc = ModuleLoc;
546 ModuleScopes.back().Module = PrivateModuleFragment;
547 VisibleModules.setVisible(PrivateModuleFragment, ModuleLoc);
548
549 // All declarations created from now on are scoped to the private module
550 // fragment (and are neither visible nor reachable in importers of the module
551 // interface).
552 auto *TU = Context.getTranslationUnitDecl();
553 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
554 TU->setLocalOwningModule(PrivateModuleFragment);
555
556 // FIXME: Consider creating an explicit representation of this declaration.
557 return nullptr;
558}
559
561 SourceLocation ExportLoc,
562 SourceLocation ImportLoc, ModuleIdPath Path,
563 bool IsPartition) {
564 assert((!IsPartition || getLangOpts().CPlusPlusModules) &&
565 "partition seen in non-C++20 code?");
566
567 // For a C++20 module name, flatten into a single identifier with the source
568 // location of the first component.
570
571 std::string ModuleName;
572 if (IsPartition) {
573 // We already checked that we are in a module purview in the parser.
574 assert(!ModuleScopes.empty() && "in a module purview, but no module?");
575 Module *NamedMod = ModuleScopes.back().Module;
576 // If we are importing into a partition, find the owning named module,
577 // otherwise, the name of the importing named module.
578 ModuleName = NamedMod->getPrimaryModuleInterfaceName().str();
579 ModuleName += ":";
580 ModuleName += ModuleLoader::getFlatNameFromPath(Path);
582 IdentifierLoc(Path[0].getLoc(), PP.getIdentifierInfo(ModuleName));
584 } else if (getLangOpts().CPlusPlusModules) {
585 ModuleName = ModuleLoader::getFlatNameFromPath(Path);
587 IdentifierLoc(Path[0].getLoc(), PP.getIdentifierInfo(ModuleName));
589 }
590
591 // Diagnose self-import before attempting a load.
592 // [module.import]/9
593 // A module implementation unit of a module M that is not a module partition
594 // shall not contain a module-import-declaration nominating M.
595 // (for an implementation, the module interface is imported implicitly,
596 // but that's handled in the module decl code).
597
598 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview() &&
599 getCurrentModule()->Name == ModuleName) {
600 Diag(ImportLoc, diag::err_module_self_import_cxx20)
601 << ModuleName << currentModuleIsImplementation();
602 return true;
603 }
604
606 ImportLoc, Path, Module::AllVisible, /*IsInclusionDirective=*/false);
607 if (!Mod)
608 return true;
609
610 if (!Mod->isInterfaceOrPartition() && !ModuleName.empty() &&
611 !getLangOpts().ObjC) {
612 Diag(ImportLoc, diag::err_module_import_non_interface_nor_parition)
613 << ModuleName;
614 return true;
615 }
616
617 return ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Mod, Path);
618}
619
620/// Determine whether \p D is lexically within an export-declaration.
621static const ExportDecl *getEnclosingExportDecl(const Decl *D) {
622 for (auto *DC = D->getLexicalDeclContext(); DC; DC = DC->getLexicalParent())
623 if (auto *ED = dyn_cast<ExportDecl>(DC))
624 return ED;
625 return nullptr;
626}
627
629 SourceLocation ExportLoc,
630 SourceLocation ImportLoc, Module *Mod,
631 ModuleIdPath Path) {
632 if (Mod->isHeaderUnit())
633 Diag(ImportLoc, diag::warn_experimental_header_unit);
634
635 if (Mod->isNamedModule())
636 makeTransitiveImportsVisible(getASTContext(), VisibleModules, Mod,
637 getCurrentModule(), ImportLoc);
638 else
639 VisibleModules.setVisible(Mod, ImportLoc);
640
642 "We can only import a partition unit in a named module.");
644 getCurrentModule()->isModuleInterfaceUnit())
645 Diag(ImportLoc,
646 diag::warn_import_implementation_partition_unit_in_interface_unit)
647 << Mod->Name;
648
649 checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
650
651 // FIXME: we should support importing a submodule within a different submodule
652 // of the same top-level module. Until we do, make it an error rather than
653 // silently ignoring the import.
654 // FIXME: Should we warn on a redundant import of the current module?
655 if (Mod->isForBuilding(getLangOpts())) {
656 Diag(ImportLoc, getLangOpts().isCompilingModule()
657 ? diag::err_module_self_import
658 : diag::err_module_import_in_implementation)
660 }
661
662 SmallVector<SourceLocation, 2> IdentifierLocs;
663
664 if (Path.empty()) {
665 // If this was a header import, pad out with dummy locations.
666 // FIXME: Pass in and use the location of the header-name token in this
667 // case.
668 for (Module *ModCheck = Mod; ModCheck; ModCheck = ModCheck->Parent)
669 IdentifierLocs.push_back(SourceLocation());
670 } else if (getLangOpts().CPlusPlusModules && !Mod->Parent) {
671 // A single identifier for the whole name.
672 IdentifierLocs.push_back(Path[0].getLoc());
673 } else {
674 Module *ModCheck = Mod;
675 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
676 // If we've run out of module parents, just drop the remaining
677 // identifiers. We need the length to be consistent.
678 if (!ModCheck)
679 break;
680 ModCheck = ModCheck->Parent;
681
682 IdentifierLocs.push_back(Path[I].getLoc());
683 }
684 }
685
686 ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
687 Mod, IdentifierLocs);
688 CurContext->addDecl(Import);
689
690 // Sequence initialization of the imported module before that of the current
691 // module, if any.
692 if (!ModuleScopes.empty())
693 Context.addModuleInitializer(ModuleScopes.back().Module, Import);
694
695 // A module (partition) implementation unit shall not be exported.
696 if (getLangOpts().CPlusPlusModules && ExportLoc.isValid() &&
698 Diag(ExportLoc, diag::err_export_partition_impl)
699 << SourceRange(ExportLoc, Path.back().getLoc());
700 } else if (ExportLoc.isValid() &&
701 (ModuleScopes.empty() || currentModuleIsImplementation())) {
702 // [module.interface]p1:
703 // An export-declaration shall inhabit a namespace scope and appear in the
704 // purview of a module interface unit.
705 Diag(ExportLoc, diag::err_export_not_in_module_interface);
706 } else if (!ModuleScopes.empty()) {
707 // Re-export the module if the imported module is exported.
708 // Note that we don't need to add re-exported module to Imports field
709 // since `Exports` implies the module is imported already.
710 if (ExportLoc.isValid() || getEnclosingExportDecl(Import))
711 getCurrentModule()->Exports.emplace_back(Mod, false);
712 else
713 getCurrentModule()->Imports.insert(Mod);
714 }
715
716 HadImportedNamedModules = true;
717
718 return Import;
719}
720
722 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
723 BuildModuleInclude(DirectiveLoc, Mod);
724}
725
727 // Determine whether we're in the #include buffer for a module. The #includes
728 // in that buffer do not qualify as module imports; they're just an
729 // implementation detail of us building the module.
730 //
731 // FIXME: Should we even get ActOnAnnotModuleInclude calls for those?
732 bool IsInModuleIncludes =
735
736 // If we are really importing a module (not just checking layering) due to an
737 // #include in the main file, synthesize an ImportDecl.
738 if (getLangOpts().Modules && !IsInModuleIncludes) {
741 DirectiveLoc, Mod,
742 DirectiveLoc);
743 if (!ModuleScopes.empty())
744 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
745 TU->addDecl(ImportD);
746 Consumer.HandleImplicitImportDecl(ImportD);
747 }
748
750 VisibleModules.setVisible(Mod, DirectiveLoc);
751
752 if (getLangOpts().isCompilingModule()) {
753 Module *ThisModule = PP.getHeaderSearchInfo().lookupModule(
754 getLangOpts().CurrentModule, DirectiveLoc, false, false);
755 (void)ThisModule;
756 // For named modules, the current module name is not known while parsing the
757 // global module fragment and lookupModule may return null.
758 assert((getLangOpts().getCompilingModule() ==
760 ThisModule) &&
761 "was expecting a module if building a Clang module");
762 }
763}
764
766 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
767
768 ModuleScopes.push_back({});
769 ModuleScopes.back().Module = Mod;
770 if (getLangOpts().ModulesLocalVisibility)
771 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
772
773 VisibleModules.setVisible(Mod, DirectiveLoc);
774
775 // The enclosing context is now part of this module.
776 // FIXME: Consider creating a child DeclContext to hold the entities
777 // lexically within the module.
778 if (getLangOpts().trackLocalOwningModule()) {
779 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
780 cast<Decl>(DC)->setModuleOwnershipKind(
781 getLangOpts().ModulesLocalVisibility
784 cast<Decl>(DC)->setLocalOwningModule(Mod);
785 }
786 }
787}
788
790 if (getLangOpts().ModulesLocalVisibility) {
791 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
792 // Leaving a module hides namespace names, so our visible namespace cache
793 // is now out of date.
794 VisibleNamespaceCache.clear();
795 }
796
797 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
798 "left the wrong module scope");
799 ModuleScopes.pop_back();
800
801 // We got to the end of processing a local module. Create an
802 // ImportDecl as we would for an imported module.
804 SourceLocation DirectiveLoc;
805 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
806 // We reached the end of a #included module header. Use the #include loc.
807 assert(File != getSourceManager().getMainFileID() &&
808 "end of submodule in main source file");
809 DirectiveLoc = getSourceManager().getIncludeLoc(File);
810 } else {
811 // We reached an EOM pragma. Use the pragma location.
812 DirectiveLoc = EomLoc;
813 }
814 BuildModuleInclude(DirectiveLoc, Mod);
815
816 // Any further declarations are in whatever module we returned to.
817 if (getLangOpts().trackLocalOwningModule()) {
818 // The parser guarantees that this is the same context that we entered
819 // the module within.
820 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
821 cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
822 if (!getCurrentModule())
823 cast<Decl>(DC)->setModuleOwnershipKind(
825 }
826 }
827}
828
830 Module *Mod) {
831 // Bail if we're not allowed to implicitly import a module here.
832 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
833 VisibleModules.isVisible(Mod))
834 return;
835
836 // Create the implicit import declaration.
839 Loc, Mod, Loc);
840 TU->addDecl(ImportD);
841 Consumer.HandleImplicitImportDecl(ImportD);
842
843 // Make the module visible.
845 VisibleModules.setVisible(Mod, Loc);
846}
847
849 SourceLocation LBraceLoc) {
851
852 // Set this temporarily so we know the export-declaration was braced.
853 D->setRBraceLoc(LBraceLoc);
854
855 CurContext->addDecl(D);
856 PushDeclContext(S, D);
857
858 // C++2a [module.interface]p1:
859 // An export-declaration shall appear only [...] in the purview of a module
860 // interface unit. An export-declaration shall not appear directly or
861 // indirectly within [...] a private-module-fragment.
862 if (!getLangOpts().HLSL) {
863 if (!isCurrentModulePurview()) {
864 Diag(ExportLoc, diag::err_export_not_in_module_interface) << 0;
865 D->setInvalidDecl();
866 return D;
867 } else if (currentModuleIsImplementation()) {
868 Diag(ExportLoc, diag::err_export_not_in_module_interface) << 1;
869 Diag(ModuleScopes.back().BeginLoc,
870 diag::note_not_module_interface_add_export)
871 << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
872 D->setInvalidDecl();
873 return D;
874 } else if (ModuleScopes.back().Module->Kind ==
876 Diag(ExportLoc, diag::err_export_in_private_module_fragment);
877 Diag(ModuleScopes.back().BeginLoc, diag::note_private_module_fragment);
878 D->setInvalidDecl();
879 return D;
880 }
881 }
882
883 for (const DeclContext *DC = CurContext; DC; DC = DC->getLexicalParent()) {
884 if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
885 // An export-declaration shall not appear directly or indirectly within
886 // an unnamed namespace [...]
887 if (ND->isAnonymousNamespace()) {
888 Diag(ExportLoc, diag::err_export_within_anonymous_namespace);
889 Diag(ND->getLocation(), diag::note_anonymous_namespace);
890 // Don't diagnose internal-linkage declarations in this region.
891 D->setInvalidDecl();
892 return D;
893 }
894
895 // A declaration is exported if it is [...] a namespace-definition
896 // that contains an exported declaration.
897 //
898 // Defer exporting the namespace until after we leave it, in order to
899 // avoid marking all subsequent declarations in the namespace as exported.
900 if (!getLangOpts().HLSL && !DeferredExportedNamespaces.insert(ND).second)
901 break;
902 }
903 }
904
905 // [...] its declaration or declaration-seq shall not contain an
906 // export-declaration.
907 if (auto *ED = getEnclosingExportDecl(D)) {
908 Diag(ExportLoc, diag::err_export_within_export);
909 if (ED->hasBraces())
910 Diag(ED->getLocation(), diag::note_export);
911 D->setInvalidDecl();
912 return D;
913 }
914
915 if (!getLangOpts().HLSL)
917
918 return D;
919}
920
921static bool checkExportedDecl(Sema &, Decl *, SourceLocation);
922
923/// Check that it's valid to export all the declarations in \p DC.
925 SourceLocation BlockStart) {
926 bool AllUnnamed = true;
927 for (auto *D : DC->decls())
928 AllUnnamed &= checkExportedDecl(S, D, BlockStart);
929 return AllUnnamed;
930}
931
932/// Check that it's valid to export \p D.
933static bool checkExportedDecl(Sema &S, Decl *D, SourceLocation BlockStart) {
934
935 // HLSL: export declaration is valid only on functions
936 if (S.getLangOpts().HLSL) {
937 // Export-within-export was already diagnosed in ActOnStartExportDecl
939 S.Diag(D->getBeginLoc(), diag::err_hlsl_export_not_on_function);
940 D->setInvalidDecl();
941 return false;
942 }
943
944 if (isa<FunctionDecl>(D)) {
946 for (const ParmVarDecl *PVD : FD->parameters()) {
947 if (PVD->hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
948 S.Diag(D->getBeginLoc(), diag::err_hlsl_attr_incompatible)
949 << "'export'" << "'groupshared' parameter";
950 D->setInvalidDecl();
951 return false;
952 }
953 }
954 }
955 }
956
957 // C++20 [module.interface]p3:
958 // [...] it shall not declare a name with internal linkage.
959 bool HasName = false;
960 if (auto *ND = dyn_cast<NamedDecl>(D)) {
961 // Don't diagnose anonymous union objects; we'll diagnose their members
962 // instead.
963 HasName = (bool)ND->getDeclName();
964 if (HasName && ND->getFormalLinkage() == Linkage::Internal) {
965 S.Diag(ND->getLocation(), diag::err_export_internal) << ND;
966 if (BlockStart.isValid())
967 S.Diag(BlockStart, diag::note_export);
968 return false;
969 }
970 }
971
972 // C++2a [module.interface]p5:
973 // all entities to which all of the using-declarators ultimately refer
974 // shall have been introduced with a name having external linkage
975 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) {
976 NamedDecl *Target = USD->getUnderlyingDecl();
977 Linkage Lk = Target->getFormalLinkage();
978 if (Lk == Linkage::Internal || Lk == Linkage::Module) {
979 S.Diag(USD->getLocation(), diag::err_export_using_internal)
980 << (Lk == Linkage::Internal ? 0 : 1) << Target;
981 S.Diag(Target->getLocation(), diag::note_using_decl_target);
982 if (BlockStart.isValid())
983 S.Diag(BlockStart, diag::note_export);
984 return false;
985 }
986 }
987
988 // Recurse into namespace-scope DeclContexts. (Only namespace-scope
989 // declarations are exported).
990 if (auto *DC = dyn_cast<DeclContext>(D)) {
991 if (!isa<NamespaceDecl>(D))
992 return true;
993
994 if (auto *ND = dyn_cast<NamedDecl>(D)) {
995 if (!ND->getDeclName()) {
996 S.Diag(ND->getLocation(), diag::err_export_anon_ns_internal);
997 if (BlockStart.isValid())
998 S.Diag(BlockStart, diag::note_export);
999 return false;
1000 } else if (!DC->decls().empty() &&
1001 DC->getRedeclContext()->isFileContext()) {
1002 return checkExportedDeclContext(S, DC, BlockStart);
1003 }
1004 }
1005 }
1006 return true;
1007}
1008
1010 auto *ED = cast<ExportDecl>(D);
1011 if (RBraceLoc.isValid())
1012 ED->setRBraceLoc(RBraceLoc);
1013
1015
1016 if (!D->isInvalidDecl()) {
1017 SourceLocation BlockStart =
1018 ED->hasBraces() ? ED->getBeginLoc() : SourceLocation();
1019 for (auto *Child : ED->decls()) {
1020 checkExportedDecl(*this, Child, BlockStart);
1021 if (auto *FD = dyn_cast<FunctionDecl>(Child)) {
1022 // [dcl.inline]/7
1023 // If an inline function or variable that is attached to a named module
1024 // is declared in a definition domain, it shall be defined in that
1025 // domain.
1026 // So, if the current declaration does not have a definition, we must
1027 // check at the end of the TU (or when the PMF starts) to see that we
1028 // have a definition at that point.
1029 if (FD->isInlineSpecified() && !FD->isDefined())
1030 PendingInlineFuncDecls.insert(FD);
1031 }
1032 }
1033 }
1034
1035 // Anything exported from a module should never be considered unused.
1036 for (auto *Exported : ED->decls())
1037 Exported->markUsed(getASTContext());
1038
1039 return D;
1040}
1041
1042Module *Sema::PushGlobalModuleFragment(SourceLocation BeginLoc) {
1043 // We shouldn't create new global module fragment if there is already
1044 // one.
1045 if (!TheGlobalModuleFragment) {
1047 TheGlobalModuleFragment = Map.createGlobalModuleFragmentForModuleUnit(
1048 BeginLoc, getCurrentModule());
1049 }
1050
1051 assert(TheGlobalModuleFragment && "module creation should not fail");
1052
1053 // Enter the scope of the global module.
1054 ModuleScopes.push_back({BeginLoc, TheGlobalModuleFragment,
1055 /*OuterVisibleModules=*/{}});
1056 VisibleModules.setVisible(TheGlobalModuleFragment, BeginLoc);
1057
1058 return TheGlobalModuleFragment;
1059}
1060
1061void Sema::PopGlobalModuleFragment() {
1062 assert(!ModuleScopes.empty() &&
1063 getCurrentModule()->isExplicitGlobalModule() &&
1064 "left the wrong module scope, which is not global module fragment");
1065 ModuleScopes.pop_back();
1066}
1067
1068Module *Sema::PushImplicitGlobalModuleFragment(SourceLocation BeginLoc) {
1069 if (!TheImplicitGlobalModuleFragment) {
1070 ModuleMap &Map = PP.getHeaderSearchInfo().getModuleMap();
1071 TheImplicitGlobalModuleFragment =
1074 }
1075 assert(TheImplicitGlobalModuleFragment && "module creation should not fail");
1076
1077 // Enter the scope of the global module.
1078 ModuleScopes.push_back({BeginLoc, TheImplicitGlobalModuleFragment,
1079 /*OuterVisibleModules=*/{}});
1080 VisibleModules.setVisible(TheImplicitGlobalModuleFragment, BeginLoc);
1081 return TheImplicitGlobalModuleFragment;
1082}
1083
1084void Sema::PopImplicitGlobalModuleFragment() {
1085 assert(!ModuleScopes.empty() &&
1086 getCurrentModule()->isImplicitGlobalModule() &&
1087 "left the wrong module scope, which is not global module fragment");
1088 ModuleScopes.pop_back();
1089}
1090
1091bool Sema::isCurrentModulePurview() const {
1092 if (!getCurrentModule())
1093 return false;
1094
1095 /// Does this Module scope describe part of the purview of a standard named
1096 /// C++ module?
1097 switch (getCurrentModule()->Kind) {
1104 return true;
1105 default:
1106 return false;
1107 }
1108}
1109
1110//===----------------------------------------------------------------------===//
1111// Checking Exposure in modules //
1112//===----------------------------------------------------------------------===//
1113
1114namespace {
1115class ExposureChecker {
1116public:
1117 ExposureChecker(Sema &S) : SemaRef(S) {}
1118
1119 bool checkExposure(const VarDecl *D, bool Diag);
1120 bool checkExposure(const CXXRecordDecl *D, bool Diag);
1121 bool checkExposure(const Stmt *S, bool Diag);
1122 bool checkExposure(const FunctionDecl *D, bool Diag);
1123 bool checkExposure(const NamedDecl *D, bool Diag);
1124 void checkExposureInContext(const DeclContext *DC);
1125 bool isExposureCandidate(const NamedDecl *D);
1126
1127 bool isTULocal(QualType Ty);
1128 bool isTULocal(const NamedDecl *ND);
1129 bool isTULocal(const Expr *E);
1130
1131 Sema &SemaRef;
1132
1133private:
1134 llvm::DenseSet<const NamedDecl *> ExposureSet;
1135 llvm::DenseSet<const NamedDecl *> KnownNonExposureSet;
1136 llvm::DenseSet<const NamedDecl *> CheckingDecls;
1137};
1138
1139bool ExposureChecker::isTULocal(QualType Ty) {
1140 // [basic.link]p15:
1141 // An entity is TU-local if it is
1142 // - a type, type alias, namespace, namespace alias, function, variable, or
1143 // template that
1144 // -- has internal linkage, or
1145 return Ty->getLinkage() == Linkage::Internal;
1146
1147 // TODO:
1148 // [basic.link]p15.2:
1149 // a type with no name that is defined outside a class-specifier, function
1150 // body, or initializer or is introduced by a defining-type-specifier that
1151 // is used to declare only TU-local entities,
1152}
1153
1154bool ExposureChecker::isTULocal(const NamedDecl *D) {
1155 if (!D)
1156 return false;
1157
1158 // [basic.link]p15:
1159 // An entity is TU-local if it is
1160 // - a type, type alias, namespace, namespace alias, function, variable, or
1161 // template that
1162 // -- has internal linkage, or
1164 return true;
1165
1166 if (D->isInAnonymousNamespace())
1167 return true;
1168
1169 // [basic.link]p15.1.2:
1170 // does not have a name with linkage and is declared, or introduced by a
1171 // lambda-expression, within the definition of a TU-local entity,
1173 if (auto *ND = dyn_cast<NamedDecl>(D->getDeclContext());
1174 ND && isTULocal(ND))
1175 return true;
1176
1177 // [basic.link]p15.3, p15.4:
1178 // - a specialization of a TU-local template,
1179 // - a specialization of a template with any TU-local template argument, or
1180 ArrayRef<TemplateArgument> TemplateArgs;
1181 NamedDecl *PrimaryTemplate = nullptr;
1182 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
1183 TemplateArgs = CTSD->getTemplateArgs().asArray();
1184 PrimaryTemplate = CTSD->getSpecializedTemplate();
1185 if (isTULocal(PrimaryTemplate))
1186 return true;
1187 } else if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
1188 TemplateArgs = VTSD->getTemplateArgs().asArray();
1189 PrimaryTemplate = VTSD->getSpecializedTemplate();
1190 if (isTULocal(PrimaryTemplate))
1191 return true;
1192 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1193 if (auto *TAList = FD->getTemplateSpecializationArgs())
1194 TemplateArgs = TAList->asArray();
1195
1196 PrimaryTemplate = FD->getPrimaryTemplate();
1197 if (isTULocal(PrimaryTemplate))
1198 return true;
1199 }
1200
1201 if (!PrimaryTemplate)
1202 // Following off, we only check for specializations.
1203 return false;
1204
1205 if (KnownNonExposureSet.count(D))
1206 return false;
1207
1208 for (auto &TA : TemplateArgs) {
1209 switch (TA.getKind()) {
1211 if (isTULocal(TA.getAsType()))
1212 return true;
1213 break;
1215 if (isTULocal(TA.getAsDecl()))
1216 return true;
1217 break;
1218 default:
1219 break;
1220 }
1221 }
1222
1223 // Avoid recursions.
1224 if (CheckingDecls.count(D))
1225 return false;
1226 CheckingDecls.insert(D);
1227 llvm::scope_exit RemoveCheckingDecls([&] { CheckingDecls.erase(D); });
1228
1229 // [basic.link]p15.5
1230 // - a specialization of a template whose (possibly instantiated) declaration
1231 // is an exposure.
1232 if (ExposureSet.count(PrimaryTemplate) ||
1233 checkExposure(PrimaryTemplate, /*Diag=*/false))
1234 return true;
1235
1236 // Avoid calling checkExposure again since it is expensive.
1237 KnownNonExposureSet.insert(D);
1238 return false;
1239}
1240
1241bool ExposureChecker::isTULocal(const Expr *E) {
1242 if (!E)
1243 return false;
1244
1245 // [basic.link]p16:
1246 // A value or object is TU-local if either
1247 // - it is of TU-local type,
1248 if (isTULocal(E->getType()))
1249 return true;
1250
1251 E = E->IgnoreParenImpCasts();
1252 // [basic.link]p16.2:
1253 // - it is, or is a pointer to, a TU-local function or the object associated
1254 // with a TU-local variable,
1255 // - it is an object of class or array type and any of its subobjects or any
1256 // of the objects or functions to which its non-static data members of
1257 // reference type refer is TU-local and is usable in constant expressions, or
1258 // FIXME: But how can we know the value of pointers or arrays at compile time?
1259 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
1260 if (auto *FD = dyn_cast_or_null<FunctionDecl>(DRE->getFoundDecl()))
1261 return isTULocal(FD);
1262 else if (auto *VD = dyn_cast_or_null<VarDecl>(DRE->getFoundDecl()))
1263 return isTULocal(VD);
1264 else if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(DRE->getFoundDecl()))
1265 return isTULocal(RD);
1266 }
1267
1268 // TODO:
1269 // [basic.link]p16.4:
1270 // it is a reflection value that represents...
1271
1272 return false;
1273}
1274
1275bool ExposureChecker::isExposureCandidate(const NamedDecl *D) {
1276 if (!D)
1277 return false;
1278
1279 // [basic.link]p17:
1280 // If a (possibly instantiated) declaration of, or a deduction guide for,
1281 // a non-TU-local entity in a module interface unit
1282 // (outside the private-module-fragment, if any) or
1283 // module partition is an exposure, the program is ill-formed.
1284 Module *M = D->getOwningModule();
1285 if (!M)
1286 return false;
1287 // If M is implicit global module, the declaration must be in the purview of
1288 // a module unit.
1289 if (M->isImplicitGlobalModule()) {
1290 M = M->Parent;
1291 assert(M && "Implicit global module must have a parent");
1292 }
1293
1294 if (!M->isInterfaceOrPartition())
1295 return false;
1296
1297 if (D->isImplicit())
1298 return false;
1299
1300 // [basic.link]p14:
1301 // A declaration is an exposure if it either names a TU-local entity
1302 // (defined below), ignoring:
1303 // ...
1304 // - friend declarations in a class definition
1305 if (D->getFriendObjectKind() &&
1307 return false;
1308
1309 return true;
1310}
1311
1312bool ExposureChecker::checkExposure(const NamedDecl *D, bool Diag) {
1313 if (!isExposureCandidate(D))
1314 return false;
1315
1316 if (auto *FD = dyn_cast<FunctionDecl>(D))
1317 return checkExposure(FD, Diag);
1318 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
1319 return checkExposure(FTD->getTemplatedDecl(), Diag);
1320
1321 if (auto *VD = dyn_cast<VarDecl>(D))
1322 return checkExposure(VD, Diag);
1323 if (auto *VTD = dyn_cast<VarTemplateDecl>(D))
1324 return checkExposure(VTD->getTemplatedDecl(), Diag);
1325
1326 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1327 return checkExposure(RD, Diag);
1328
1329 if (auto *CTD = dyn_cast<ClassTemplateDecl>(D))
1330 return checkExposure(CTD->getTemplatedDecl(), Diag);
1331
1332 return false;
1333}
1334
1335bool ExposureChecker::checkExposure(const FunctionDecl *FD, bool Diag) {
1336 bool IsExposure = false;
1337 if (isTULocal(FD->getReturnType())) {
1338 IsExposure = true;
1339 if (Diag)
1340 SemaRef.Diag(FD->getReturnTypeSourceRange().getBegin(),
1341 diag::warn_exposure)
1342 << FD->getReturnType();
1343 }
1344
1345 for (ParmVarDecl *Parms : FD->parameters())
1346 if (isTULocal(Parms->getType())) {
1347 IsExposure = true;
1348 if (Diag)
1349 SemaRef.Diag(Parms->getLocation(), diag::warn_exposure)
1350 << Parms->getType();
1351 }
1352
1353 bool IsImplicitInstantiation =
1355
1356 // [basic.link]p14:
1357 // A declaration is an exposure if it either names a TU-local entity
1358 // (defined below), ignoring:
1359 // - the function-body for a non-inline function or function template
1360 // (but not the deduced return
1361 // type for a (possibly instantiated) definition of a function with a
1362 // declared return type that uses a placeholder type
1363 // ([dcl.spec.auto])),
1364 Diag &=
1365 (FD->isInlined() || IsImplicitInstantiation) && !FD->isDependentContext();
1366
1367 IsExposure |= checkExposure(FD->getBody(), Diag);
1368 if (IsExposure)
1369 ExposureSet.insert(FD);
1370
1371 return IsExposure;
1372}
1373
1374bool ExposureChecker::checkExposure(const VarDecl *VD, bool Diag) {
1375 bool IsExposure = false;
1376 // [basic.link]p14:
1377 // A declaration is an exposure if it either names a TU-local entity (defined
1378 // below), ignoring:
1379 // ...
1380 // or defines a constexpr variable initialized to a TU-local value (defined
1381 // below).
1382 if (VD->isConstexpr() && isTULocal(VD->getInit())) {
1383 IsExposure = true;
1384 if (Diag)
1385 SemaRef.Diag(VD->getInit()->getExprLoc(), diag::warn_exposure)
1386 << VD->getInit();
1387 }
1388
1389 if (isTULocal(VD->getType())) {
1390 IsExposure = true;
1391 if (Diag)
1392 SemaRef.Diag(VD->getLocation(), diag::warn_exposure) << VD->getType();
1393 }
1394
1395 // [basic.link]p14:
1396 // ..., ignoring:
1397 // - the initializer for a variable or variable template (but not the
1398 // variable's type),
1399 //
1400 // Note: although the spec says to ignore the initializer for all variable,
1401 // for the code we generated now for inline variables, it is dangerous if the
1402 // initializer of an inline variable is TULocal.
1403 Diag &= !VD->getDeclContext()->isDependentContext() && VD->isInline();
1404 IsExposure |= checkExposure(VD->getInit(), Diag);
1405 if (IsExposure)
1406 ExposureSet.insert(VD);
1407
1408 return IsExposure;
1409}
1410
1411bool ExposureChecker::checkExposure(const CXXRecordDecl *RD, bool Diag) {
1412 if (!RD->hasDefinition())
1413 return false;
1414
1415 bool IsExposure = false;
1416 for (CXXMethodDecl *Method : RD->methods())
1417 IsExposure |= checkExposure(Method, Diag);
1418
1419 for (FieldDecl *FD : RD->fields()) {
1420 if (isTULocal(FD->getType())) {
1421 IsExposure = true;
1422 if (Diag)
1423 SemaRef.Diag(FD->getLocation(), diag::warn_exposure) << FD->getType();
1424 }
1425 }
1426
1427 for (const CXXBaseSpecifier &Base : RD->bases()) {
1428 if (isTULocal(Base.getType())) {
1429 IsExposure = true;
1430 if (Diag)
1431 SemaRef.Diag(Base.getBaseTypeLoc(), diag::warn_exposure)
1432 << Base.getType();
1433 }
1434 }
1435
1436 if (IsExposure)
1437 ExposureSet.insert(RD);
1438
1439 return IsExposure;
1440}
1441
1442class ReferenceTULocalChecker : public DynamicRecursiveASTVisitor {
1443public:
1444 using CallbackTy = std::function<void(DeclRefExpr *, ValueDecl *)>;
1445
1446 ReferenceTULocalChecker(ExposureChecker &C, CallbackTy &&Callback)
1447 : Checker(C), Callback(std::move(Callback)) {}
1448
1449 bool VisitDeclRefExpr(DeclRefExpr *DRE) override {
1450 ValueDecl *Referenced = DRE->getDecl();
1451 if (!Referenced)
1452 return true;
1453
1454 if (!Checker.isTULocal(Referenced))
1455 // We don't care if the referenced declaration is not TU-local.
1456 return true;
1457
1458 Qualifiers Qual = DRE->getType().getQualifiers();
1459 // [basic.link]p14:
1460 // A declaration is an exposure if it either names a TU-local entity
1461 // (defined below), ignoring:
1462 // ...
1463 // - any reference to a non-volatile const object ...
1464 if (Qual.hasConst() && !Qual.hasVolatile())
1465 return true;
1466
1467 // [basic.link]p14:
1468 // ..., ignoring:
1469 // ...
1470 // (p14.4) - ... or reference with internal or no linkage initialized with
1471 // a constant expression that is not an odr-use
1472 ASTContext &Context = Referenced->getASTContext();
1473 Linkage L = Referenced->getLinkageInternal();
1474 if (DRE->isNonOdrUse() && (L == Linkage::Internal || L == Linkage::None))
1475 if (auto *VD = dyn_cast<VarDecl>(Referenced);
1476 VD && VD->getInit() && !VD->getInit()->isValueDependent() &&
1477 VD->getInit()->isConstantInitializer(Context, /*IsForRef=*/false))
1478 return true;
1479
1480 Callback(DRE, Referenced);
1481 return true;
1482 }
1483
1484 ExposureChecker &Checker;
1485 CallbackTy Callback;
1486};
1487
1488bool ExposureChecker::checkExposure(const Stmt *S, bool Diag) {
1489 if (!S)
1490 return false;
1491
1492 bool HasReferencedTULocals = false;
1493 ReferenceTULocalChecker Checker(
1494 *this, [this, &HasReferencedTULocals, Diag](DeclRefExpr *DRE,
1495 ValueDecl *Referenced) {
1496 if (Diag) {
1497 SemaRef.Diag(DRE->getExprLoc(), diag::warn_exposure) << Referenced;
1498 }
1499 HasReferencedTULocals = true;
1500 });
1501 Checker.TraverseStmt(const_cast<Stmt *>(S));
1502 return HasReferencedTULocals;
1503}
1504
1505void ExposureChecker::checkExposureInContext(const DeclContext *DC) {
1506 for (auto *TopD : DC->noload_decls()) {
1507 if (auto *Export = dyn_cast<ExportDecl>(TopD)) {
1508 checkExposureInContext(Export);
1509 continue;
1510 }
1511
1512 if (auto *LinkageSpec = dyn_cast<LinkageSpecDecl>(TopD)) {
1513 checkExposureInContext(LinkageSpec);
1514 continue;
1515 }
1516
1517 auto *TopND = dyn_cast<NamedDecl>(TopD);
1518 if (!TopND)
1519 continue;
1520
1521 if (auto *Namespace = dyn_cast<NamespaceDecl>(TopND)) {
1522 checkExposureInContext(Namespace);
1523 continue;
1524 }
1525
1526 // [basic.link]p17:
1527 // If a (possibly instantiated) declaration of, or a deduction guide for,
1528 // a non-TU-local entity in a module interface unit
1529 // (outside the private-module-fragment, if any) or
1530 // module partition is an exposure, the program is ill-formed.
1531 if (!TopND->isFromASTFile() && isExposureCandidate(TopND) &&
1532 !isTULocal(TopND))
1533 checkExposure(TopND, /*Diag=*/true);
1534 }
1535}
1536
1537} // namespace
1538
1539void Sema::checkExposure(const TranslationUnitDecl *TU) {
1540 if (!TU)
1541 return;
1542
1543 ExposureChecker Checker(*this);
1544
1545 Module *M = TU->getOwningModule();
1546 if (M && M->isInterfaceOrPartition())
1547 Checker.checkExposureInContext(TU);
1548
1549 // [basic.link]p18:
1550 // If a declaration that appears in one translation unit names a TU-local
1551 // entity declared in another translation unit that is not a header unit,
1552 // the program is ill-formed.
1553 for (auto FDAndInstantiationLocPair : PendingCheckReferenceForTULocal) {
1554 FunctionDecl *FD = FDAndInstantiationLocPair.first;
1555 SourceLocation PointOfInstantiation = FDAndInstantiationLocPair.second;
1556
1557 if (!FD->hasBody())
1558 continue;
1559
1560 ReferenceTULocalChecker(Checker, [&, this](DeclRefExpr *DRE,
1561 ValueDecl *Referenced) {
1562 // A "defect" in current implementation. Now an implicit instantiation of
1563 // a template, the instantiation is considered to be in the same module
1564 // unit as the template instead of the module unit where the instantiation
1565 // happens.
1566 //
1567 // See test/Modules/Exposre-2.cppm for example.
1568 if (!Referenced->isFromASTFile())
1569 return;
1570
1571 if (!Referenced->isInAnotherModuleUnit())
1572 return;
1573
1574 // This is not standard conforming. But given there are too many static
1575 // (inline) functions in headers in existing code, it is more user
1576 // friendly to ignore them temporarily now. maybe we can have another flag
1577 // for this.
1578 if (Referenced->getOwningModule()->isExplicitGlobalModule() &&
1579 isa<FunctionDecl>(Referenced))
1580 return;
1581
1582 Diag(PointOfInstantiation,
1583 diag::warn_reference_tu_local_entity_in_other_tu)
1584 << FD << Referenced
1585 << Referenced->getOwningModule()->getTopLevelModuleName();
1586 }).TraverseStmt(FD->getBody());
1587 }
1588}
1589
1590void Sema::checkReferenceToTULocalFromOtherTU(
1591 FunctionDecl *FD, SourceLocation PointOfInstantiation) {
1592 // Checking if a declaration have any reference to TU-local entities in other
1593 // TU is expensive. Try to avoid it as much as possible.
1594 if (!FD || !HadImportedNamedModules)
1595 return;
1596
1597 PendingCheckReferenceForTULocal.push_back(
1598 std::make_pair(FD, PointOfInstantiation));
1599}
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition MachO.h:51
Defines the clang::Preprocessor interface.
static void makeTransitiveImportsVisible(ASTContext &Ctx, VisibleModuleSet &VisibleModules, Module *Imported, Module *CurrentModule, SourceLocation ImportLoc, bool IsImportingPrimaryModuleInterface=false)
[module.import]p7: Additionally, when a module-import-declaration in a module unit of some module M i...
static bool DiagReservedModuleName(Sema &S, const IdentifierInfo *II, SourceLocation Loc)
Tests whether the given identifier is reserved as a module name and diagnoses if it is.
static const ExportDecl * getEnclosingExportDecl(const Decl *D)
Determine whether D is lexically within an export-declaration.
static bool checkExportedDecl(Sema &, Decl *, SourceLocation)
Check that it's valid to export D.
static void checkModuleImportContext(Sema &S, Module *M, SourceLocation ImportLoc, DeclContext *DC, bool FromInclude=false)
static bool checkExportedDeclContext(Sema &S, DeclContext *DC, SourceLocation BlockStart)
Check that it's valid to export all the declarations in DC.
static bool isImportingModuleUnitFromSameModule(ASTContext &Ctx, Module *Imported, Module *CurrentModule, Module *&FoundPrimaryModuleInterface)
Helper function for makeTransitiveImportsVisible to decide whether the.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:226
TranslationUnitDecl * getTranslationUnitDecl() const
void setCurrentNamedModule(Module *M)
Set the (C++20) module we are building.
bool isInSameModule(const Module *M1, const Module *M2) const
If the two module M1 and M2 are in the same module.
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2136
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
base_class_range bases()
Definition DeclCXX.h:608
method_range methods() const
Definition DeclCXX.h:650
bool hasDefinition() const
Definition DeclCXX.h:561
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2125
void addDecl(Decl *D)
Add the declaration D into this context.
decl_range noload_decls() const
noload_decls_begin/end - Iterate over the declarations stored in this context that are currently load...
Definition DeclBase.h:2381
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2373
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1273
ValueDecl * getDecl()
Definition Expr.h:1341
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1471
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1226
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:546
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
bool isInAnotherModuleUnit() const
Whether this declaration comes from another module unit.
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:842
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition DeclBase.h:793
bool isInvalidDecl() const
Definition DeclBase.h:588
SourceLocation getLocation() const
Definition DeclBase.h:439
DeclContext * getDeclContext()
Definition DeclBase.h:448
bool isInAnonymousNamespace() const
Definition DeclBase.cpp:439
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
@ VisibleWhenImported
This declaration has an owning module, and is visible when that module is imported.
Definition DeclBase.h:229
@ Unowned
This declaration is not owned by a module.
Definition DeclBase.h:218
@ ReachableWhenImported
This declaration has an owning module, and is visible to lookups that occurs within that module.
Definition DeclBase.h:234
@ ModulePrivate
This declaration has an owning module, but is only visible to lookups that occur within that module.
Definition DeclBase.h:240
@ Visible
This declaration has an owning module, but is globally visible (typically because its owning module i...
Definition DeclBase.h:225
void setModuleOwnershipKind(ModuleOwnershipKind MOK)
Set whether this declaration is hidden from name lookup.
Definition DeclBase.h:881
Represents a standard C++ module export declaration.
Definition Decl.h:5149
static ExportDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExportLoc)
Definition Decl.cpp:6091
void setRBraceLoc(SourceLocation L)
Definition Decl.h:5169
This represents one expression.
Definition Expr.h:112
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3090
bool isConstantInitializer(ASTContext &Ctx, bool ForRef, const Expr **Culprit=nullptr) const
isConstantInitializer - Returns true if this expression can be emitted to IR as a constant,...
Definition Expr.cpp:3347
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:277
QualType getType() const
Definition Expr.h:144
Represents a member of a struct/union/class.
Definition Decl.h:3175
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
Represents a function declaration or definition.
Definition Decl.h:2015
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3280
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4025
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2936
QualType getReturnType() const
Definition Decl.h:2860
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2789
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4418
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3200
ModuleMap & getModuleMap()
Retrieve the module map.
One of these records is kept for each identifier that is lexed.
ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const
Determine whether this is a name reserved for the implementation (C99 7.1.3, C++ [lib....
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
A simple pair of identifier info and location.
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition Decl.h:5070
static ImportDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, Module *Imported, ArrayRef< SourceLocation > IdentifierLocs)
Create a new module import declaration.
Definition Decl.cpp:6047
static ImportDecl * CreateImplicit(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, Module *Imported, SourceLocation EndLoc)
Create a new module import declaration for an implicitly-generated import.
Definition Decl.cpp:6055
@ CMK_None
Not compiling a module interface at all.
@ CMK_HeaderUnit
Compiling a module header unit.
@ CMK_ModuleMap
Compiling a module from a module map.
@ CMK_ModuleInterface
Compiling a C++ modules interface unit.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
std::string CurrentModule
The name of the current module, of which the main source file is a part.
Identifies a module file to be loaded.
Definition Module.h:107
virtual ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path, Module::NameVisibilityKind Visibility, bool IsInclusionDirective)=0
Attempt to load the given module.
static std::string getFlatNameFromPath(ModuleIdPath Path)
virtual void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility, SourceLocation ImportLoc)=0
Make the given module visible.
Module * createGlobalModuleFragmentForModuleUnit(SourceLocation Loc, Module *Parent=nullptr)
Create a global module fragment for a C++ module unit.
Module * createImplicitGlobalModuleFragmentForModuleUnit(SourceLocation Loc, Module *Parent)
Describes a module or submodule.
Definition Module.h:251
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition Module.h:840
SmallVector< ExportDecl, 2 > Exports
The set of export declarations.
Definition Module.h:579
bool isForBuilding(const LangOptions &LangOpts) const
Determine whether this module can be built in this compilation.
Definition Module.cpp:174
bool isInterfaceOrPartition() const
Definition Module.h:779
bool isModulePartitionImplementation() const
Is this a module partition implementation unit.
Definition Module.h:767
@ AllVisible
All of the names in this module are visible.
Definition Module.h:555
Module(ModuleConstructorTag, StringRef Name, SourceLocation DefinitionLoc, Module *Parent, bool IsFramework, bool IsExplicit, unsigned VisibilityID)
Construct a new module or submodule.
Definition Module.cpp:55
Module * Parent
The parent of this module.
Definition Module.h:300
ModuleKind Kind
The kind of this module.
Definition Module.h:296
llvm::SmallSetVector< Module *, 2 > Imports
The set of modules imported by this module, and on which this module depends.
Definition Module.h:566
std::string Name
The name of this module.
Definition Module.h:254
unsigned IsExternC
Whether this is an 'extern "C"' module (which implicitly puts all headers in it within an 'extern "C"...
Definition Module.h:503
StringRef getPrimaryModuleInterfaceName() const
Get the primary module interface name from a partition.
Definition Module.h:795
bool isModulePartition() const
Is this a module partition.
Definition Module.h:761
bool isExplicitGlobalModule() const
Definition Module.h:349
bool isImplicitGlobalModule() const
Definition Module.h:352
bool isHeaderUnit() const
Is this module a header unit.
Definition Module.h:777
@ ModuleImplementationUnit
This is a C++20 module implementation unit.
Definition Module.h:274
@ ModuleMapModule
This is a module that was defined by a module map and built out of header files.
Definition Module.h:265
@ ImplicitGlobalModuleFragment
This is an implicit fragment of the global module which contains only language linkage declarations (...
Definition Module.h:292
@ ModulePartitionInterface
This is a C++20 module partition interface.
Definition Module.h:277
@ ModuleInterfaceUnit
This is a C++20 module interface unit.
Definition Module.h:271
@ ModuleHeaderUnit
This is a C++20 header unit.
Definition Module.h:268
@ ModulePartitionImplementation
This is a C++20 module partition implementation.
Definition Module.h:280
@ PrivateModuleFragment
This is the private module fragment within some C++ module.
Definition Module.h:287
@ ExplicitGlobalModuleFragment
This is the explicit Global Module Fragment of a modular TU.
Definition Module.h:284
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition Module.cpp:258
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:331
This represents a decl that may have a name.
Definition Decl.h:274
Linkage getLinkageInternal() const
Determine what kind of linkage this entity has.
Definition Decl.cpp:1182
Represents a parameter to a function.
Definition Decl.h:1805
HeaderSearch & getHeaderSearchInfo() const
A (possibly-)qualified type.
Definition TypeBase.h:937
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8471
bool hasConst() const
Definition TypeBase.h:457
bool hasVolatile() const
Definition TypeBase.h:467
field_range fields() const
Definition Decl.h:4545
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
void ActOnAnnotModuleBegin(SourceLocation DirectiveLoc, Module *Mod)
The parsed has entered a submodule.
void ActOnAnnotModuleInclude(SourceLocation DirectiveLoc, Module *Mod)
The parser has processed a module import translated from a include or similar preprocessing directive...
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition Sema.h:1258
@ PartitionImplementation
'module X:Y;'
Definition Sema.h:9939
@ Interface
'export module X;'
Definition Sema.h:9936
@ Implementation
'module X;'
Definition Sema.h:9937
@ PartitionInterface
'export module X:Y;'
Definition Sema.h:9938
llvm::DenseMap< NamedDecl *, NamedDecl * > VisibleNamespaceCache
Map from the most recent declaration of a namespace to the most recent visible declaration of that na...
Definition Sema.h:13690
ASTContext & Context
Definition Sema.h:1304
void ActOnAnnotModuleEnd(SourceLocation DirectiveLoc, Module *Mod)
The parser has left a submodule.
bool currentModuleIsImplementation() const
Is the module scope we are an implementation unit?
Definition Sema.h:9923
DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, ModuleIdPath Path, bool IsPartition=false)
The parser has processed a module import declaration.
SemaObjC & ObjC()
Definition Sema.h:1514
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition SemaDecl.cpp:79
ASTContext & getASTContext() const
Definition Sema.h:939
Decl * ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, SourceLocation LBraceLoc)
We have parsed the start of an export declaration, including the '{' (if present).
const LangOptions & getLangOpts() const
Definition Sema.h:932
Preprocessor & PP
Definition Sema.h:1303
SemaHLSL & HLSL()
Definition Sema.h:1479
void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind)
Definition Sema.cpp:1192
DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc)
The parser has processed a global-module-fragment declaration that begins the definition of the globa...
DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc, ModuleDeclKind MDK, ModuleIdPath Path, ModuleIdPath Partition, ModuleImportState &ImportState, bool SeenNoTrivialPPDirective)
The parser has processed a module-declaration that begins the definition of a module interface or imp...
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:9918
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1442
DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc, SourceLocation PrivateLoc)
The parser has processed a private-module-fragment declaration that begins the definition of the priv...
SourceManager & getSourceManager() const
Definition Sema.h:937
void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod)
bool isModuleVisible(const Module *M, bool ModulePrivate=false)
bool isSFINAEContext() const
Definition Sema.h:13769
ASTConsumer & Consumer
Definition Sema.h:1305
ModuleImportState
An enumeration to represent the transition of states in parsing module fragments and imports.
Definition Sema.h:9945
@ FirstDecl
Parsing the first decl in a TU.
Definition Sema.h:9946
@ GlobalFragment
after 'module;' but before 'module X;'
Definition Sema.h:9947
@ NotACXX20Module
Not a C++20 TU, or an invalid state was found.
Definition Sema.h:9954
@ ImportAllowed
after 'module X;' but before any non-import decl.
Definition Sema.h:9948
ModuleLoader & getModuleLoader() const
Retrieve the module loader associated with the preprocessor.
Definition Sema.cpp:110
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
void PopDeclContext()
Decl * ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, SourceLocation RBraceLoc)
Complete the definition of an export declaration.
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Sema.h:1295
void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, Module *Mod)
Create an implicit import of the given module at the given source location, for error recovery,...
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
SourceLocation getIncludeLoc(FileID FID) const
Returns the include location if FID is a #include'd file otherwise it returns an invalid location.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
bool isWrittenInMainFile(SourceLocation Loc) const
Returns true if the spelling location for the given location is in the main file buffer.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:86
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Type
The template argument is a type.
The top declaration context.
Definition Decl.h:105
Linkage getLinkage() const
Determine the linkage of this type.
Definition Type.cpp:4971
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:926
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1584
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1566
const Expr * getInit() const
Definition Decl.h:1383
A set of visible modules.
Definition Module.h:985
void setVisible(Module *M, SourceLocation Loc, bool IncludeExports=true, VisibleCallback Vis=[](Module *) {}, ConflictCallback Cb=[](ArrayRef< Module * >, Module *, StringRef) {})
Make a specific module visible.
Definition Module.cpp:681
#define bool
Definition gpuintrin.h:32
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
ArrayRef< IdentifierLoc > ModuleIdPath
A sequence of identifier/location pairs used to describe a particular module or submodule,...
ActionResult< Decl * > DeclResult
Definition Ownership.h:255
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition Linkage.h:24
@ None
No linkage, which means that the entity is unique and can only be referred to from within its scope.
Definition Linkage.h:30
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
Definition Linkage.h:54
@ Global
The global module fragment, between 'module;' and a module-declaration.
Definition Sema.h:489
@ Normal
A normal translation unit fragment.
Definition Sema.h:493
@ TU_ClangModule
The translation unit is a clang module.
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
U cast(CodeGen::Address addr)
Definition Address.h:327
int const char * function
Definition c++config.h:31
Information about a header directive as found in the module map file.
Definition Module.h:395