Coverage Report

Created: 2022-05-17 06:19

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaModule.cpp
Line
Count
Source (jump to first uncovered line)
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/Lex/HeaderSearch.h"
16
#include "clang/Lex/Preprocessor.h"
17
#include "clang/Sema/SemaInternal.h"
18
19
using namespace clang;
20
using namespace sema;
21
22
static void checkModuleImportContext(Sema &S, Module *M,
23
                                     SourceLocation ImportLoc, DeclContext *DC,
24
123k
                                     bool FromInclude = false) {
25
123k
  SourceLocation ExternCLoc;
26
27
123k
  if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
28
35.4k
    switch (LSD->getLanguage()) {
29
35.0k
    case LinkageSpecDecl::lang_c:
30
35.0k
      if (ExternCLoc.isInvalid())
31
35.0k
        ExternCLoc = LSD->getBeginLoc();
32
35.0k
      break;
33
348
    case LinkageSpecDecl::lang_cxx:
34
348
      break;
35
35.4k
    }
36
35.4k
    DC = LSD->getParent();
37
35.4k
  }
38
39
124k
  
while (123k
isa<LinkageSpecDecl>(DC) ||
isa<ExportDecl>(DC)123k
)
40
956
    DC = DC->getParent();
41
42
123k
  if (!isa<TranslationUnitDecl>(DC)) {
43
19
    S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
44
19
                          ? 
diag::ext_module_import_not_at_top_level_noop10
45
19
                          : 
diag::err_module_import_not_at_top_level_fatal9
)
46
19
        << M->getFullModuleName() << DC;
47
19
    S.Diag(cast<Decl>(DC)->getBeginLoc(),
48
19
           diag::note_module_import_not_at_top_level)
49
19
        << DC;
50
123k
  } else if (!M->IsExternC && 
ExternCLoc.isValid()49.4k
) {
51
10
    S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
52
10
      << M->getFullModuleName();
53
10
    S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
54
10
  }
55
123k
}
56
57
// We represent the primary and partition names as 'Paths' which are sections
58
// of the hierarchical access path for a clang module.  However for C++20
59
// the periods in a name are just another character, and we will need to
60
// flatten them into a string.
61
387
static std::string stringFromPath(ModuleIdPath Path) {
62
387
  std::string Name;
63
387
  if (Path.empty())
64
0
    return Name;
65
66
403
  
for (auto &Piece : Path)387
{
67
403
    if (!Name.empty())
68
16
      Name += ".";
69
403
    Name += Piece.first->getName();
70
403
  }
71
387
  return Name;
72
387
}
73
74
Sema::DeclGroupPtrTy
75
168
Sema::ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc) {
76
168
  if (!ModuleScopes.empty() &&
77
168
      
ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment1
) {
78
    // Under -std=c++2a -fmodules-ts, we can find an explicit 'module;' after
79
    // already implicitly entering the global module fragment. That's OK.
80
1
    assert(getLangOpts().CPlusPlusModules && getLangOpts().ModulesTS &&
81
1
           "unexpectedly encountered multiple global module fragment decls");
82
0
    ModuleScopes.back().BeginLoc = ModuleLoc;
83
1
    return nullptr;
84
1
  }
85
86
  // We start in the global module; all those declarations are implicitly
87
  // module-private (though they do not have module linkage).
88
167
  Module *GlobalModule =
89
167
      PushGlobalModuleFragment(ModuleLoc, /*IsImplicit=*/false);
90
91
  // All declarations created from now on are owned by the global module.
92
167
  auto *TU = Context.getTranslationUnitDecl();
93
167
  TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::Visible);
94
167
  TU->setLocalOwningModule(GlobalModule);
95
96
  // FIXME: Consider creating an explicit representation of this declaration.
97
167
  return nullptr;
98
168
}
99
100
14
void Sema::HandleStartOfHeaderUnit() {
101
14
  assert(getLangOpts().CPlusPlusModules &&
102
14
         "Header units are only valid for C++20 modules");
103
0
  SourceLocation StartOfTU =
104
14
      SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
105
106
14
  StringRef HUName = getLangOpts().CurrentModule;
107
14
  if (HUName.empty()) {
108
3
    HUName = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())->getName();
109
3
    const_cast<LangOptions &>(getLangOpts()).CurrentModule = HUName.str();
110
3
  }
111
112
  // TODO: Make the C++20 header lookup independent.
113
  // When the input is pre-processed source, we need a file ref to the original
114
  // file for the header map.
115
14
  auto F = SourceMgr.getFileManager().getFile(HUName);
116
  // For the sake of error recovery (if someone has moved the original header
117
  // after creating the pre-processed output) fall back to obtaining the file
118
  // ref for the input file, which must be present.
119
14
  if (!F)
120
0
    F = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
121
14
  assert(F && "failed to find the header unit source?");
122
0
  Module::Header H{HUName.str(), HUName.str(), *F};
123
14
  auto &Map = PP.getHeaderSearchInfo().getModuleMap();
124
14
  Module *Mod = Map.createHeaderUnit(StartOfTU, HUName, H);
125
14
  assert(Mod && "module creation should not fail");
126
0
  ModuleScopes.push_back({}); // No GMF
127
14
  ModuleScopes.back().BeginLoc = StartOfTU;
128
14
  ModuleScopes.back().Module = Mod;
129
14
  ModuleScopes.back().ModuleInterface = true;
130
14
  ModuleScopes.back().IsPartition = false;
131
14
  VisibleModules.setVisible(Mod, StartOfTU);
132
133
  // From now on, we have an owning module for all declarations we see.
134
  // All of these are implicitly exported.
135
14
  auto *TU = Context.getTranslationUnitDecl();
136
14
  TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::Visible);
137
14
  TU->setLocalOwningModule(Mod);
138
14
}
139
140
Sema::DeclGroupPtrTy
141
Sema::ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc,
142
                      ModuleDeclKind MDK, ModuleIdPath Path,
143
233
                      ModuleIdPath Partition, ModuleImportState &ImportState) {
144
233
  assert((getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules) &&
145
233
         "should only have module decl in Modules TS or C++20");
146
147
0
  bool IsFirstDecl = ImportState == ModuleImportState::FirstDecl;
148
233
  bool SeenGMF = ImportState == ModuleImportState::GlobalFragment;
149
  // If any of the steps here fail, we count that as invalidating C++20
150
  // module state;
151
233
  ImportState = ModuleImportState::NotACXX20Module;
152
153
233
  bool IsPartition = !Partition.empty();
154
233
  if (IsPartition)
155
27
    switch (MDK) {
156
10
    case ModuleDeclKind::Implementation:
157
10
      MDK = ModuleDeclKind::PartitionImplementation;
158
10
      break;
159
17
    case ModuleDeclKind::Interface:
160
17
      MDK = ModuleDeclKind::PartitionInterface;
161
17
      break;
162
0
    default:
163
0
      llvm_unreachable("how did we get a partition type set?");
164
27
    }
165
166
  // A (non-partition) module implementation unit requires that we are not
167
  // compiling a module of any kind.  A partition implementation emits an
168
  // interface (and the AST for the implementation), which will subsequently
169
  // be consumed to emit a binary.
170
  // A module interface unit requires that we are not compiling a module map.
171
233
  switch (getLangOpts().getCompilingModule()) {
172
111
  case LangOptions::CMK_None:
173
    // It's OK to compile a module interface as a normal translation unit.
174
111
    break;
175
176
122
  case LangOptions::CMK_ModuleInterface:
177
122
    if (MDK != ModuleDeclKind::Implementation)
178
121
      break;
179
180
    // We were asked to compile a module interface unit but this is a module
181
    // implementation unit.
182
1
    Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
183
1
      << FixItHint::CreateInsertion(ModuleLoc, "export ");
184
1
    MDK = ModuleDeclKind::Interface;
185
1
    break;
186
187
0
  case LangOptions::CMK_ModuleMap:
188
0
    Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
189
0
    return nullptr;
190
191
0
  case LangOptions::CMK_HeaderModule:
192
0
  case LangOptions::CMK_HeaderUnit:
193
0
    Diag(ModuleLoc, diag::err_module_decl_in_header_module);
194
0
    return nullptr;
195
233
  }
196
197
233
  assert(ModuleScopes.size() <= 1 && "expected to be at global module scope");
198
199
  // FIXME: Most of this work should be done by the preprocessor rather than
200
  // here, in order to support macro import.
201
202
  // Only one module-declaration is permitted per source file.
203
233
  if (!ModuleScopes.empty() &&
204
233
      
ModuleScopes.back().Module->isModulePurview()120
) {
205
4
    Diag(ModuleLoc, diag::err_module_redeclaration);
206
4
    Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
207
4
         diag::note_prev_module_declaration);
208
4
    return nullptr;
209
4
  }
210
211
  // Find the global module fragment we're adopting into this module, if any.
212
229
  Module *GlobalModuleFragment = nullptr;
213
229
  if (!ModuleScopes.empty() &&
214
229
      
ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment116
)
215
116
    GlobalModuleFragment = ModuleScopes.back().Module;
216
217
229
  assert((!getLangOpts().CPlusPlusModules || getLangOpts().ModulesTS ||
218
229
          SeenGMF == (bool)GlobalModuleFragment) &&
219
229
         "mismatched global module state");
220
221
  // In C++20, the module-declaration must be the first declaration if there
222
  // is no global module fragment.
223
229
  if (getLangOpts().CPlusPlusModules && 
!IsFirstDecl154
&&
!SeenGMF42
) {
224
2
    Diag(ModuleLoc, diag::err_module_decl_not_at_start);
225
2
    SourceLocation BeginLoc =
226
2
        ModuleScopes.empty()
227
2
            ? SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID())
228
2
            : 
ModuleScopes.back().BeginLoc0
;
229
2
    if (BeginLoc.isValid()) {
230
2
      Diag(BeginLoc, diag::note_global_module_introducer_missing)
231
2
          << FixItHint::CreateInsertion(BeginLoc, "module;\n");
232
2
    }
233
2
  }
234
235
  // Flatten the dots in a module name. Unlike Clang's hierarchical module map
236
  // modules, the dots here are just another character that can appear in a
237
  // module name.
238
229
  std::string ModuleName = stringFromPath(Path);
239
229
  if (IsPartition) {
240
27
    ModuleName += ":";
241
27
    ModuleName += stringFromPath(Partition);
242
27
  }
243
  // If a module name was explicitly specified on the command line, it must be
244
  // correct.
245
229
  if (!getLangOpts().CurrentModule.empty() &&
246
229
      
getLangOpts().CurrentModule != ModuleName0
) {
247
0
    Diag(Path.front().second, diag::err_current_module_name_mismatch)
248
0
        << SourceRange(Path.front().second, IsPartition
249
0
                                                ? Partition.back().second
250
0
                                                : Path.back().second)
251
0
        << getLangOpts().CurrentModule;
252
0
    return nullptr;
253
0
  }
254
229
  const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
255
256
229
  auto &Map = PP.getHeaderSearchInfo().getModuleMap();
257
229
  Module *Mod;
258
259
229
  switch (MDK) {
260
170
  case ModuleDeclKind::Interface:
261
187
  case ModuleDeclKind::PartitionInterface: {
262
    // We can't have parsed or imported a definition of this module or parsed a
263
    // module map defining it already.
264
187
    if (auto *M = Map.findModule(ModuleName)) {
265
3
      Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
266
3
      if (M->DefinitionLoc.isValid())
267
0
        Diag(M->DefinitionLoc, diag::note_prev_module_definition);
268
3
      else if (Optional<FileEntryRef> FE = M->getASTFile())
269
3
        Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
270
3
            << FE->getName();
271
3
      Mod = M;
272
3
      break;
273
3
    }
274
275
    // Create a Module for the module that we're defining.
276
184
    Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
277
184
                                           GlobalModuleFragment);
278
184
    if (MDK == ModuleDeclKind::PartitionInterface)
279
17
      Mod->Kind = Module::ModulePartitionInterface;
280
184
    assert(Mod && "module creation should not fail");
281
0
    break;
282
187
  }
283
284
32
  case ModuleDeclKind::Implementation: {
285
32
    std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
286
32
        PP.getIdentifierInfo(ModuleName), Path[0].second);
287
    // C++20 A module-declaration that contains neither an export-
288
    // keyword nor a module-partition implicitly imports the primary
289
    // module interface unit of the module as if by a module-import-
290
    // declaration.
291
32
    Mod = getModuleLoader().loadModule(ModuleLoc, {ModuleNameLoc},
292
32
                                       Module::AllVisible,
293
32
                                       /*IsInclusionDirective=*/false);
294
32
    if (!Mod) {
295
2
      Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
296
      // Create an empty module interface unit for error recovery.
297
2
      Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
298
2
                                             GlobalModuleFragment);
299
2
    }
300
32
  } break;
301
302
10
  case ModuleDeclKind::PartitionImplementation:
303
    // Create an interface, but note that it is an implementation
304
    // unit.
305
10
    Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
306
10
                                           GlobalModuleFragment);
307
10
    Mod->Kind = Module::ModulePartitionImplementation;
308
10
    break;
309
229
  }
310
311
229
  if (!GlobalModuleFragment) {
312
113
    ModuleScopes.push_back({});
313
113
    if (getLangOpts().ModulesLocalVisibility)
314
113
      ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
315
116
  } else {
316
    // We're done with the global module fragment now.
317
116
    ActOnEndOfTranslationUnitFragment(TUFragmentKind::Global);
318
116
  }
319
320
  // Switch from the global module fragment (if any) to the named module.
321
229
  ModuleScopes.back().BeginLoc = StartLoc;
322
229
  ModuleScopes.back().Module = Mod;
323
229
  ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
324
229
  ModuleScopes.back().IsPartition = IsPartition;
325
229
  VisibleModules.setVisible(Mod, ModuleLoc);
326
327
  // From now on, we have an owning module for all declarations we see.
328
  // However, those declarations are module-private unless explicitly
329
  // exported.
330
229
  auto *TU = Context.getTranslationUnitDecl();
331
229
  TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
332
229
  TU->setLocalOwningModule(Mod);
333
334
  // We are in the module purview, but before any other (non import)
335
  // statements, so imports are allowed.
336
229
  ImportState = ModuleImportState::ImportAllowed;
337
338
  // FIXME: Create a ModuleDecl.
339
229
  return nullptr;
340
229
}
341
342
Sema::DeclGroupPtrTy
343
Sema::ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
344
18
                                     SourceLocation PrivateLoc) {
345
  // C++20 [basic.link]/2:
346
  //   A private-module-fragment shall appear only in a primary module
347
  //   interface unit.
348
18
  switch (ModuleScopes.empty() ? 
Module::GlobalModuleFragment1
349
18
                               : 
ModuleScopes.back().Module->Kind17
) {
350
0
  case Module::ModuleMapModule:
351
2
  case Module::GlobalModuleFragment:
352
3
  case Module::ModulePartitionImplementation:
353
4
  case Module::ModulePartitionInterface:
354
4
  case Module::ModuleHeaderUnit:
355
4
    Diag(PrivateLoc, diag::err_private_module_fragment_not_module);
356
4
    return nullptr;
357
358
3
  case Module::PrivateModuleFragment:
359
3
    Diag(PrivateLoc, diag::err_private_module_fragment_redefined);
360
3
    Diag(ModuleScopes.back().BeginLoc, diag::note_previous_definition);
361
3
    return nullptr;
362
363
11
  case Module::ModuleInterfaceUnit:
364
11
    break;
365
18
  }
366
367
11
  if (!ModuleScopes.back().ModuleInterface) {
368
1
    Diag(PrivateLoc, diag::err_private_module_fragment_not_module_interface);
369
1
    Diag(ModuleScopes.back().BeginLoc,
370
1
         diag::note_not_module_interface_add_export)
371
1
        << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
372
1
    return nullptr;
373
1
  }
374
375
  // FIXME: Check this isn't a module interface partition.
376
  // FIXME: Check that this translation unit does not import any partitions;
377
  // such imports would violate [basic.link]/2's "shall be the only module unit"
378
  // restriction.
379
380
  // We've finished the public fragment of the translation unit.
381
10
  ActOnEndOfTranslationUnitFragment(TUFragmentKind::Normal);
382
383
10
  auto &Map = PP.getHeaderSearchInfo().getModuleMap();
384
10
  Module *PrivateModuleFragment =
385
10
      Map.createPrivateModuleFragmentForInterfaceUnit(
386
10
          ModuleScopes.back().Module, PrivateLoc);
387
10
  assert(PrivateModuleFragment && "module creation should not fail");
388
389
  // Enter the scope of the private module fragment.
390
0
  ModuleScopes.push_back({});
391
10
  ModuleScopes.back().BeginLoc = ModuleLoc;
392
10
  ModuleScopes.back().Module = PrivateModuleFragment;
393
10
  ModuleScopes.back().ModuleInterface = true;
394
10
  VisibleModules.setVisible(PrivateModuleFragment, ModuleLoc);
395
396
  // All declarations created from now on are scoped to the private module
397
  // fragment (and are neither visible nor reachable in importers of the module
398
  // interface).
399
10
  auto *TU = Context.getTranslationUnitDecl();
400
10
  TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
401
10
  TU->setLocalOwningModule(PrivateModuleFragment);
402
403
  // FIXME: Consider creating an explicit representation of this declaration.
404
10
  return nullptr;
405
11
}
406
407
DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
408
                                   SourceLocation ExportLoc,
409
                                   SourceLocation ImportLoc, ModuleIdPath Path,
410
1.80k
                                   bool IsPartition) {
411
412
1.80k
  bool Cxx20Mode = getLangOpts().CPlusPlusModules || 
getLangOpts().ModulesTS1.73k
;
413
1.80k
  assert((!IsPartition || Cxx20Mode) && "partition seen in non-C++20 code?");
414
415
  // For a C++20 module name, flatten into a single identifier with the source
416
  // location of the first component.
417
0
  std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
418
419
1.80k
  std::string ModuleName;
420
1.80k
  if (IsPartition) {
421
    // We already checked that we are in a module purview in the parser.
422
22
    assert(!ModuleScopes.empty() && "in a module purview, but no module?");
423
0
    Module *NamedMod = ModuleScopes.back().Module;
424
    // If we are importing into a partition, find the owning named module,
425
    // otherwise, the name of the importing named module.
426
22
    ModuleName = NamedMod->getPrimaryModuleInterfaceName().str();
427
22
    ModuleName += ":";
428
22
    ModuleName += stringFromPath(Path);
429
22
    ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
430
22
    Path = ModuleIdPath(ModuleNameLoc);
431
1.78k
  } else if (Cxx20Mode) {
432
109
    ModuleName = stringFromPath(Path);
433
109
    ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
434
109
    Path = ModuleIdPath(ModuleNameLoc);
435
109
  }
436
437
  // Diagnose self-import before attempting a load.
438
  // [module.import]/9
439
  // A module implementation unit of a module M that is not a module partition
440
  // shall not contain a module-import-declaration nominating M.
441
  // (for an implementation, the module interface is imported implicitly,
442
  //  but that's handled in the module decl code).
443
444
1.80k
  if (getLangOpts().CPlusPlusModules && 
isCurrentModulePurview()63
&&
445
1.80k
      
getCurrentModule()->Name == ModuleName49
) {
446
4
    Diag(ImportLoc, diag::err_module_self_import_cxx20)
447
4
        << ModuleName << !ModuleScopes.back().ModuleInterface;
448
4
    return true;
449
4
  }
450
451
1.79k
  Module *Mod = getModuleLoader().loadModule(
452
1.79k
      ImportLoc, Path, Module::AllVisible, /*IsInclusionDirective=*/false);
453
1.79k
  if (!Mod)
454
77
    return true;
455
456
1.72k
  return ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Mod, Path);
457
1.79k
}
458
459
/// Determine whether \p D is lexically within an export-declaration.
460
245
static const ExportDecl *getEnclosingExportDecl(const Decl *D) {
461
511
  for (auto *DC = D->getLexicalDeclContext(); DC; 
DC = DC->getLexicalParent()266
)
462
273
    if (auto *ED = dyn_cast<ExportDecl>(DC))
463
7
      return ED;
464
238
  return nullptr;
465
245
}
466
467
DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
468
                                   SourceLocation ExportLoc,
469
                                   SourceLocation ImportLoc, Module *Mod,
470
1.74k
                                   ModuleIdPath Path) {
471
1.74k
  VisibleModules.setVisible(Mod, ImportLoc);
472
473
1.74k
  checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
474
475
  // FIXME: we should support importing a submodule within a different submodule
476
  // of the same top-level module. Until we do, make it an error rather than
477
  // silently ignoring the import.
478
  // FIXME: Should we warn on a redundant import of the current module?
479
1.74k
  if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
480
1.74k
      
(10
getLangOpts().isCompilingModule()10
||
!getLangOpts().ModulesTS9
)) {
481
4
    Diag(ImportLoc, getLangOpts().isCompilingModule()
482
4
                        ? 
diag::err_module_self_import1
483
4
                        : 
diag::err_module_import_in_implementation3
)
484
4
        << Mod->getFullModuleName() << getLangOpts().CurrentModule;
485
4
  }
486
487
1.74k
  SmallVector<SourceLocation, 2> IdentifierLocs;
488
489
1.74k
  if (Path.empty()) {
490
    // If this was a header import, pad out with dummy locations.
491
    // FIXME: Pass in and use the location of the header-name token in this
492
    // case.
493
42
    for (Module *ModCheck = Mod; ModCheck; 
ModCheck = ModCheck->Parent22
)
494
22
      IdentifierLocs.push_back(SourceLocation());
495
1.72k
  } else if (getLangOpts().CPlusPlusModules && 
!Mod->Parent56
) {
496
    // A single identifier for the whole name.
497
56
    IdentifierLocs.push_back(Path[0].second);
498
1.66k
  } else {
499
1.66k
    Module *ModCheck = Mod;
500
3.46k
    for (unsigned I = 0, N = Path.size(); I != N; 
++I1.79k
) {
501
      // If we've run out of module parents, just drop the remaining
502
      // identifiers.  We need the length to be consistent.
503
1.80k
      if (!ModCheck)
504
6
        break;
505
1.79k
      ModCheck = ModCheck->Parent;
506
507
1.79k
      IdentifierLocs.push_back(Path[I].second);
508
1.79k
    }
509
1.66k
  }
510
511
1.74k
  ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
512
1.74k
                                          Mod, IdentifierLocs);
513
1.74k
  CurContext->addDecl(Import);
514
515
  // Sequence initialization of the imported module before that of the current
516
  // module, if any.
517
1.74k
  if (!ModuleScopes.empty())
518
285
    Context.addModuleInitializer(ModuleScopes.back().Module, Import);
519
520
  // A module (partition) implementation unit shall not be exported.
521
1.74k
  if (getLangOpts().CPlusPlusModules && 
ExportLoc.isValid()76
&&
522
1.74k
      
Mod->Kind == Module::ModuleKind::ModulePartitionImplementation17
) {
523
1
    Diag(ExportLoc, diag::err_export_partition_impl)
524
1
        << SourceRange(ExportLoc, Path.back().second);
525
1.74k
  } else if (!ModuleScopes.empty() &&
526
1.74k
             
(284
ModuleScopes.back().ModuleInterface284
||
527
284
              
(218
getLangOpts().CPlusPlusModules218
&&
528
218
               
ModuleScopes.back().Module->isGlobalModule()7
))) {
529
70
    assert((!ModuleScopes.back().Module->isGlobalModule() ||
530
70
            Mod->Kind == Module::ModuleKind::ModuleHeaderUnit) &&
531
70
           "should only be importing a header unit into the GMF");
532
    // Re-export the module if the imported module is exported.
533
    // Note that we don't need to add re-exported module to Imports field
534
    // since `Exports` implies the module is imported already.
535
70
    if (ExportLoc.isValid() || 
getEnclosingExportDecl(Import)56
)
536
18
      getCurrentModule()->Exports.emplace_back(Mod, false);
537
52
    else
538
52
      getCurrentModule()->Imports.insert(Mod);
539
1.67k
  } else if (ExportLoc.isValid()) {
540
    // [module.interface]p1:
541
    // An export-declaration shall inhabit a namespace scope and appear in the
542
    // purview of a module interface unit.
543
2
    Diag(ExportLoc, diag::err_export_not_in_module_interface)
544
2
        << (!ModuleScopes.empty() &&
545
2
            
!ModuleScopes.back().ImplicitGlobalModuleFragment1
);
546
1.66k
  } else if (getLangOpts().isCompilingModule()) {
547
161
    Module *ThisModule = PP.getHeaderSearchInfo().lookupModule(
548
161
        getLangOpts().CurrentModule, ExportLoc, false, false);
549
161
    (void)ThisModule;
550
161
    assert(ThisModule && "was expecting a module if building one");
551
161
  }
552
553
  // In some cases we need to know if an entity was present in a directly-
554
  // imported module (as opposed to a transitive import).  This avoids
555
  // searching both Imports and Exports.
556
0
  DirectModuleImports.insert(Mod);
557
558
1.74k
  return Import;
559
1.74k
}
560
561
25.4k
void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
562
25.4k
  checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
563
25.4k
  BuildModuleInclude(DirectiveLoc, Mod);
564
25.4k
}
565
566
121k
void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
567
  // Determine whether we're in the #include buffer for a module. The #includes
568
  // in that buffer do not qualify as module imports; they're just an
569
  // implementation detail of us building the module.
570
  //
571
  // FIXME: Should we even get ActOnModuleInclude calls for those?
572
121k
  bool IsInModuleIncludes =
573
121k
      TUKind == TU_Module &&
574
121k
      
getSourceManager().isWrittenInMainFile(DirectiveLoc)119k
;
575
576
121k
  bool ShouldAddImport = !IsInModuleIncludes;
577
578
  // If this module import was due to an inclusion directive, create an
579
  // implicit import declaration to capture it in the AST.
580
121k
  if (ShouldAddImport) {
581
118k
    TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
582
118k
    ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
583
118k
                                                     DirectiveLoc, Mod,
584
118k
                                                     DirectiveLoc);
585
118k
    if (!ModuleScopes.empty())
586
98.6k
      Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
587
118k
    TU->addDecl(ImportD);
588
118k
    Consumer.HandleImplicitImportDecl(ImportD);
589
118k
  }
590
591
121k
  getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
592
121k
  VisibleModules.setVisible(Mod, DirectiveLoc);
593
594
121k
  if (getLangOpts().isCompilingModule()) {
595
119k
    Module *ThisModule = PP.getHeaderSearchInfo().lookupModule(
596
119k
        getLangOpts().CurrentModule, DirectiveLoc, false, false);
597
119k
    (void)ThisModule;
598
119k
    assert(ThisModule && "was expecting a module if building one");
599
119k
  }
600
121k
}
601
602
96.1k
void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
603
96.1k
  checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
604
605
96.1k
  ModuleScopes.push_back({});
606
96.1k
  ModuleScopes.back().Module = Mod;
607
96.1k
  if (getLangOpts().ModulesLocalVisibility)
608
297
    ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
609
610
96.1k
  VisibleModules.setVisible(Mod, DirectiveLoc);
611
612
  // The enclosing context is now part of this module.
613
  // FIXME: Consider creating a child DeclContext to hold the entities
614
  // lexically within the module.
615
96.1k
  if (getLangOpts().trackLocalOwningModule()) {
616
221k
    for (auto *DC = CurContext; DC; 
DC = DC->getLexicalParent()125k
) {
617
125k
      cast<Decl>(DC)->setModuleOwnershipKind(
618
125k
          getLangOpts().ModulesLocalVisibility
619
125k
              ? 
Decl::ModuleOwnershipKind::VisibleWhenImported303
620
125k
              : 
Decl::ModuleOwnershipKind::Visible124k
);
621
125k
      cast<Decl>(DC)->setLocalOwningModule(Mod);
622
125k
    }
623
96.0k
  }
624
96.1k
}
625
626
96.1k
void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
627
96.1k
  if (getLangOpts().ModulesLocalVisibility) {
628
297
    VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
629
    // Leaving a module hides namespace names, so our visible namespace cache
630
    // is now out of date.
631
297
    VisibleNamespaceCache.clear();
632
297
  }
633
634
96.1k
  assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
635
96.1k
         "left the wrong module scope");
636
0
  ModuleScopes.pop_back();
637
638
  // We got to the end of processing a local module. Create an
639
  // ImportDecl as we would for an imported module.
640
96.1k
  FileID File = getSourceManager().getFileID(EomLoc);
641
96.1k
  SourceLocation DirectiveLoc;
642
96.1k
  if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
643
    // We reached the end of a #included module header. Use the #include loc.
644
497
    assert(File != getSourceManager().getMainFileID() &&
645
497
           "end of submodule in main source file");
646
0
    DirectiveLoc = getSourceManager().getIncludeLoc(File);
647
95.6k
  } else {
648
    // We reached an EOM pragma. Use the pragma location.
649
95.6k
    DirectiveLoc = EomLoc;
650
95.6k
  }
651
0
  BuildModuleInclude(DirectiveLoc, Mod);
652
653
  // Any further declarations are in whatever module we returned to.
654
96.1k
  if (getLangOpts().trackLocalOwningModule()) {
655
    // The parser guarantees that this is the same context that we entered
656
    // the module within.
657
221k
    for (auto *DC = CurContext; DC; 
DC = DC->getLexicalParent()125k
) {
658
125k
      cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
659
125k
      if (!getCurrentModule())
660
24.3k
        cast<Decl>(DC)->setModuleOwnershipKind(
661
24.3k
            Decl::ModuleOwnershipKind::Unowned);
662
125k
    }
663
96.0k
  }
664
96.1k
}
665
666
void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
667
675
                                                      Module *Mod) {
668
  // Bail if we're not allowed to implicitly import a module here.
669
675
  if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
670
675
      
VisibleModules.isVisible(Mod)60
)
671
617
    return;
672
673
  // Create the implicit import declaration.
674
58
  TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
675
58
  ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
676
58
                                                   Loc, Mod, Loc);
677
58
  TU->addDecl(ImportD);
678
58
  Consumer.HandleImplicitImportDecl(ImportD);
679
680
  // Make the module visible.
681
58
  getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
682
58
  VisibleModules.setVisible(Mod, Loc);
683
58
}
684
685
/// We have parsed the start of an export declaration, including the '{'
686
/// (if present).
687
Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
688
204
                                 SourceLocation LBraceLoc) {
689
204
  ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
690
691
  // Set this temporarily so we know the export-declaration was braced.
692
204
  D->setRBraceLoc(LBraceLoc);
693
694
204
  CurContext->addDecl(D);
695
204
  PushDeclContext(S, D);
696
697
  // C++2a [module.interface]p1:
698
  //   An export-declaration shall appear only [...] in the purview of a module
699
  //   interface unit. An export-declaration shall not appear directly or
700
  //   indirectly within [...] a private-module-fragment.
701
204
  if (ModuleScopes.empty() || 
!ModuleScopes.back().Module->isModulePurview()203
) {
702
7
    Diag(ExportLoc, diag::err_export_not_in_module_interface) << 0;
703
7
    D->setInvalidDecl();
704
7
    return D;
705
197
  } else if (!ModuleScopes.back().ModuleInterface) {
706
3
    Diag(ExportLoc, diag::err_export_not_in_module_interface) << 1;
707
3
    Diag(ModuleScopes.back().BeginLoc,
708
3
         diag::note_not_module_interface_add_export)
709
3
        << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
710
3
    D->setInvalidDecl();
711
3
    return D;
712
194
  } else if (ModuleScopes.back().Module->Kind ==
713
194
             Module::PrivateModuleFragment) {
714
1
    Diag(ExportLoc, diag::err_export_in_private_module_fragment);
715
1
    Diag(ModuleScopes.back().BeginLoc, diag::note_private_module_fragment);
716
1
    D->setInvalidDecl();
717
1
    return D;
718
1
  }
719
720
593
  
for (const DeclContext *DC = CurContext; 193
DC;
DC = DC->getLexicalParent()400
) {
721
411
    if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
722
      //   An export-declaration shall not appear directly or indirectly within
723
      //   an unnamed namespace [...]
724
32
      if (ND->isAnonymousNamespace()) {
725
4
        Diag(ExportLoc, diag::err_export_within_anonymous_namespace);
726
4
        Diag(ND->getLocation(), diag::note_anonymous_namespace);
727
        // Don't diagnose internal-linkage declarations in this region.
728
4
        D->setInvalidDecl();
729
4
        return D;
730
4
      }
731
732
      //   A declaration is exported if it is [...] a namespace-definition
733
      //   that contains an exported declaration.
734
      //
735
      // Defer exporting the namespace until after we leave it, in order to
736
      // avoid marking all subsequent declarations in the namespace as exported.
737
28
      if (!DeferredExportedNamespaces.insert(ND).second)
738
7
        break;
739
28
    }
740
411
  }
741
742
  //   [...] its declaration or declaration-seq shall not contain an
743
  //   export-declaration.
744
189
  if (auto *ED = getEnclosingExportDecl(D)) {
745
3
    Diag(ExportLoc, diag::err_export_within_export);
746
3
    if (ED->hasBraces())
747
2
      Diag(ED->getLocation(), diag::note_export);
748
3
    D->setInvalidDecl();
749
3
    return D;
750
3
  }
751
752
186
  D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
753
186
  return D;
754
189
}
755
756
static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
757
                                     SourceLocation BlockStart);
758
759
namespace {
760
enum class UnnamedDeclKind {
761
  Empty,
762
  StaticAssert,
763
  Asm,
764
  UsingDirective,
765
  Namespace,
766
  Context
767
};
768
}
769
770
359
static llvm::Optional<UnnamedDeclKind> getUnnamedDeclKind(Decl *D) {
771
359
  if (isa<EmptyDecl>(D))
772
5
    return UnnamedDeclKind::Empty;
773
354
  if (isa<StaticAssertDecl>(D))
774
4
    return UnnamedDeclKind::StaticAssert;
775
350
  if (isa<FileScopeAsmDecl>(D))
776
1
    return UnnamedDeclKind::Asm;
777
349
  if (isa<UsingDirectiveDecl>(D))
778
3
    return UnnamedDeclKind::UsingDirective;
779
  // Everything else either introduces one or more names or is ill-formed.
780
346
  return llvm::None;
781
349
}
782
783
17
unsigned getUnnamedDeclDiag(UnnamedDeclKind UDK, bool InBlock) {
784
17
  switch (UDK) {
785
5
  case UnnamedDeclKind::Empty:
786
9
  case UnnamedDeclKind::StaticAssert:
787
    // Allow empty-declarations and static_asserts in an export block as an
788
    // extension.
789
9
    return InBlock ? 
diag::ext_export_no_name_block4
:
diag::err_export_no_name5
;
790
791
3
  case UnnamedDeclKind::UsingDirective:
792
    // Allow exporting using-directives as an extension.
793
3
    return diag::ext_export_using_directive;
794
795
1
  case UnnamedDeclKind::Namespace:
796
    // Anonymous namespace with no content.
797
1
    return diag::introduces_no_names;
798
799
3
  case UnnamedDeclKind::Context:
800
    // Allow exporting DeclContexts that transitively contain no declarations
801
    // as an extension.
802
3
    return diag::ext_export_no_names;
803
804
1
  case UnnamedDeclKind::Asm:
805
1
    return diag::err_export_no_name;
806
17
  }
807
0
  llvm_unreachable("unknown kind");
808
0
}
809
810
static void diagExportedUnnamedDecl(Sema &S, UnnamedDeclKind UDK, Decl *D,
811
17
                                    SourceLocation BlockStart) {
812
17
  S.Diag(D->getLocation(), getUnnamedDeclDiag(UDK, BlockStart.isValid()))
813
17
      << (unsigned)UDK;
814
17
  if (BlockStart.isValid())
815
6
    S.Diag(BlockStart, diag::note_export);
816
17
}
817
818
/// Check that it's valid to export \p D.
819
359
static bool checkExportedDecl(Sema &S, Decl *D, SourceLocation BlockStart) {
820
  // C++2a [module.interface]p3:
821
  //   An exported declaration shall declare at least one name
822
359
  if (auto UDK = getUnnamedDeclKind(D))
823
13
    diagExportedUnnamedDecl(S, *UDK, D, BlockStart);
824
825
  //   [...] shall not declare a name with internal linkage.
826
359
  bool HasName = false;
827
359
  if (auto *ND = dyn_cast<NamedDecl>(D)) {
828
    // Don't diagnose anonymous union objects; we'll diagnose their members
829
    // instead.
830
334
    HasName = (bool)ND->getDeclName();
831
334
    if (HasName && 
ND->getFormalLinkage() == InternalLinkage313
) {
832
11
      S.Diag(ND->getLocation(), diag::err_export_internal) << ND;
833
11
      if (BlockStart.isValid())
834
2
        S.Diag(BlockStart, diag::note_export);
835
11
    }
836
334
  }
837
838
  // C++2a [module.interface]p5:
839
  //   all entities to which all of the using-declarators ultimately refer
840
  //   shall have been introduced with a name having external linkage
841
359
  if (auto *USD = dyn_cast<UsingShadowDecl>(D)) {
842
44
    NamedDecl *Target = USD->getUnderlyingDecl();
843
44
    Linkage Lk = Target->getFormalLinkage();
844
44
    if (Lk == InternalLinkage || 
Lk == ModuleLinkage24
) {
845
32
      S.Diag(USD->getLocation(), diag::err_export_using_internal)
846
32
          << (Lk == InternalLinkage ? 
020
:
112
) << Target;
847
32
      S.Diag(Target->getLocation(), diag::note_using_decl_target);
848
32
      if (BlockStart.isValid())
849
28
        S.Diag(BlockStart, diag::note_export);
850
32
    }
851
44
  }
852
853
  // Recurse into namespace-scope DeclContexts. (Only namespace-scope
854
  // declarations are exported.).
855
359
  if (auto *DC = dyn_cast<DeclContext>(D)) {
856
131
    if (isa<NamespaceDecl>(D) && 
DC->decls().empty()22
) {
857
4
      if (!HasName)
858
        // We don't allow an empty anonymous namespace (we don't allow decls
859
        // in them either, but that's handled in the recursion).
860
1
        diagExportedUnnamedDecl(S, UnnamedDeclKind::Namespace, D, BlockStart);
861
      // We allow an empty named namespace decl.
862
127
    } else if (DC->getRedeclContext()->isFileContext() && 
!isa<EnumDecl>(D)32
)
863
29
      return checkExportedDeclContext(S, DC, BlockStart);
864
131
  }
865
330
  return false;
866
359
}
867
868
/// Check that it's valid to export all the declarations in \p DC.
869
static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
870
29
                                     SourceLocation BlockStart) {
871
29
  bool AllUnnamed = true;
872
29
  for (auto *D : DC->decls())
873
62
    AllUnnamed &= checkExportedDecl(S, D, BlockStart);
874
29
  return AllUnnamed;
875
29
}
876
877
/// Complete the definition of an export declaration.
878
204
Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
879
204
  auto *ED = cast<ExportDecl>(D);
880
204
  if (RBraceLoc.isValid())
881
23
    ED->setRBraceLoc(RBraceLoc);
882
883
204
  PopDeclContext();
884
885
204
  if (!D->isInvalidDecl()) {
886
186
    SourceLocation BlockStart =
887
186
        ED->hasBraces() ? 
ED->getBeginLoc()22
:
SourceLocation()164
;
888
297
    for (auto *Child : ED->decls()) {
889
297
      if (checkExportedDecl(*this, Child, BlockStart)) {
890
        // If a top-level child is a linkage-spec declaration, it might contain
891
        // no declarations (transitively), in which case it's ill-formed.
892
3
        diagExportedUnnamedDecl(*this, UnnamedDeclKind::Context, Child,
893
3
                                BlockStart);
894
3
      }
895
297
    }
896
186
  }
897
898
204
  return D;
899
204
}
900
901
Module *Sema::PushGlobalModuleFragment(SourceLocation BeginLoc,
902
188
                                       bool IsImplicit) {
903
  // We shouldn't create new global module fragment if there is already
904
  // one.
905
188
  if (!GlobalModuleFragment) {
906
170
    ModuleMap &Map = PP.getHeaderSearchInfo().getModuleMap();
907
170
    GlobalModuleFragment = Map.createGlobalModuleFragmentForModuleUnit(
908
170
        BeginLoc, getCurrentModule());
909
170
  }
910
911
188
  assert(GlobalModuleFragment && "module creation should not fail");
912
913
  // Enter the scope of the global module.
914
0
  ModuleScopes.push_back({BeginLoc, GlobalModuleFragment,
915
188
                          /*ModuleInterface=*/false,
916
188
                          /*IsPartition=*/false,
917
188
                          /*ImplicitGlobalModuleFragment=*/IsImplicit,
918
188
                          /*OuterVisibleModules=*/{}});
919
188
  VisibleModules.setVisible(GlobalModuleFragment, BeginLoc);
920
921
188
  return GlobalModuleFragment;
922
188
}
923
924
21
void Sema::PopGlobalModuleFragment() {
925
21
  assert(!ModuleScopes.empty() && getCurrentModule()->isGlobalModule() &&
926
21
         "left the wrong module scope, which is not global module fragment");
927
0
  ModuleScopes.pop_back();
928
21
}