Coverage Report

Created: 2023-05-31 04:38

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaCXXScopeSpec.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaCXXScopeSpec.cpp - Semantic Analysis for C++ scope specifiers-===//
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 C++ semantic analysis for scope specifiers.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "TypeLocBuilder.h"
14
#include "clang/AST/ASTContext.h"
15
#include "clang/AST/DeclTemplate.h"
16
#include "clang/AST/ExprCXX.h"
17
#include "clang/AST/NestedNameSpecifier.h"
18
#include "clang/Basic/PartialDiagnostic.h"
19
#include "clang/Sema/DeclSpec.h"
20
#include "clang/Sema/Lookup.h"
21
#include "clang/Sema/SemaInternal.h"
22
#include "clang/Sema/Template.h"
23
#include "llvm/ADT/STLExtras.h"
24
using namespace clang;
25
26
/// Find the current instantiation that associated with the given type.
27
static CXXRecordDecl *getCurrentInstantiationOf(QualType T,
28
8.92M
                                                DeclContext *CurContext) {
29
8.92M
  if (T.isNull())
30
0
    return nullptr;
31
32
8.92M
  const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
33
8.92M
  if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
34
33.5k
    CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
35
33.5k
    if (!Record->isDependentContext() ||
36
33.5k
        Record->isCurrentInstantiation(CurContext))
37
17.7k
      return Record;
38
39
15.8k
    return nullptr;
40
8.89M
  } else if (isa<InjectedClassNameType>(Ty))
41
2.77M
    return cast<InjectedClassNameType>(Ty)->getDecl();
42
6.11M
  else
43
6.11M
    return nullptr;
44
8.92M
}
45
46
/// Compute the DeclContext that is associated with the given type.
47
///
48
/// \param T the type for which we are attempting to find a DeclContext.
49
///
50
/// \returns the declaration context represented by the type T,
51
/// or NULL if the declaration context cannot be computed (e.g., because it is
52
/// dependent and not the current instantiation).
53
1.56M
DeclContext *Sema::computeDeclContext(QualType T) {
54
1.56M
  if (!T->isDependentType())
55
295k
    if (const TagType *Tag = T->getAs<TagType>())
56
295k
      return Tag->getDecl();
57
58
1.27M
  return ::getCurrentInstantiationOf(T, CurContext);
59
1.56M
}
60
61
/// Compute the DeclContext that is associated with the given
62
/// scope specifier.
63
///
64
/// \param SS the C++ scope specifier as it appears in the source
65
///
66
/// \param EnteringContext when true, we will be entering the context of
67
/// this scope specifier, so we can retrieve the declaration context of a
68
/// class template or class template partial specialization even if it is
69
/// not the current instantiation.
70
///
71
/// \returns the declaration context represented by the scope specifier @p SS,
72
/// or NULL if the declaration context cannot be computed (e.g., because it is
73
/// dependent and not the current instantiation).
74
DeclContext *Sema::computeDeclContext(const CXXScopeSpec &SS,
75
15.7M
                                      bool EnteringContext) {
76
15.7M
  if (!SS.isSet() || 
SS.isInvalid()15.7M
)
77
637
    return nullptr;
78
79
15.7M
  NestedNameSpecifier *NNS = SS.getScopeRep();
80
15.7M
  if (NNS->isDependent()) {
81
    // If this nested-name-specifier refers to the current
82
    // instantiation, return its DeclContext.
83
7.73M
    if (CXXRecordDecl *Record = getCurrentInstantiationOf(NNS))
84
1.53M
      return Record;
85
86
6.20M
    if (EnteringContext) {
87
338k
      const Type *NNSType = NNS->getAsType();
88
338k
      if (!NNSType) {
89
64
        return nullptr;
90
64
      }
91
92
      // Look through type alias templates, per C++0x [temp.dep.type]p1.
93
338k
      NNSType = Context.getCanonicalType(NNSType);
94
338k
      if (const TemplateSpecializationType *SpecType
95
338k
            = NNSType->getAs<TemplateSpecializationType>()) {
96
        // We are entering the context of the nested name specifier, so try to
97
        // match the nested name specifier to either a primary class template
98
        // or a class template partial specialization.
99
335k
        if (ClassTemplateDecl *ClassTemplate
100
335k
              = dyn_cast_or_null<ClassTemplateDecl>(
101
335k
                            SpecType->getTemplateName().getAsTemplateDecl())) {
102
335k
          QualType ContextType =
103
335k
              Context.getCanonicalType(QualType(SpecType, 0));
104
105
          // FIXME: The fallback on the search of partial
106
          // specialization using ContextType should be eventually removed since
107
          // it doesn't handle the case of constrained template parameters
108
          // correctly. Currently removing this fallback would change the
109
          // diagnostic output for invalid code in a number of tests.
110
335k
          ClassTemplatePartialSpecializationDecl *PartialSpec = nullptr;
111
335k
          ArrayRef<TemplateParameterList *> TemplateParamLists =
112
335k
              SS.getTemplateParamLists();
113
335k
          if (!TemplateParamLists.empty()) {
114
320k
            unsigned Depth = ClassTemplate->getTemplateParameters()->getDepth();
115
320k
            auto L = find_if(TemplateParamLists,
116
321k
                             [Depth](TemplateParameterList *TPL) {
117
321k
                               return TPL->getDepth() == Depth;
118
321k
                             });
119
320k
            if (L != TemplateParamLists.end()) {
120
320k
              void *Pos = nullptr;
121
320k
              PartialSpec = ClassTemplate->findPartialSpecialization(
122
320k
                  SpecType->template_arguments(), *L, Pos);
123
320k
            }
124
320k
          } else {
125
14.7k
            PartialSpec = ClassTemplate->findPartialSpecialization(ContextType);
126
14.7k
          }
127
128
335k
          if (PartialSpec) {
129
            // A declaration of the partial specialization must be visible.
130
            // We can always recover here, because this only happens when we're
131
            // entering the context, and that can't happen in a SFINAE context.
132
75.9k
            assert(!isSFINAEContext() && "partial specialization scope "
133
75.9k
                                         "specifier in SFINAE context?");
134
75.9k
            if (PartialSpec->hasDefinition() &&
135
75.9k
                
!hasReachableDefinition(PartialSpec)75.9k
)
136
30
              diagnoseMissingImport(SS.getLastQualifierNameLoc(), PartialSpec,
137
30
                                    MissingImportKind::PartialSpecialization,
138
30
                                    true);
139
75.9k
            return PartialSpec;
140
75.9k
          }
141
142
          // If the type of the nested name specifier is the same as the
143
          // injected class name of the named class template, we're entering
144
          // into that class template definition.
145
259k
          QualType Injected =
146
259k
              ClassTemplate->getInjectedClassNameSpecialization();
147
259k
          if (Context.hasSameType(Injected, ContextType))
148
257k
            return ClassTemplate->getTemplatedDecl();
149
259k
        }
150
335k
      } else 
if (const RecordType *3.23k
RecordT3.23k
= NNSType->getAs<RecordType>()) {
151
        // The nested name specifier refers to a member of a class template.
152
2.75k
        return RecordT->getDecl();
153
2.75k
      }
154
338k
    }
155
156
5.86M
    return nullptr;
157
6.20M
  }
158
159
7.98M
  switch (NNS->getKind()) {
160
0
  case NestedNameSpecifier::Identifier:
161
0
    llvm_unreachable("Dependent nested-name-specifier has no DeclContext");
162
163
4.26M
  case NestedNameSpecifier::Namespace:
164
4.26M
    return NNS->getAsNamespace();
165
166
882
  case NestedNameSpecifier::NamespaceAlias:
167
882
    return NNS->getAsNamespaceAlias()->getNamespace();
168
169
2.95M
  case NestedNameSpecifier::TypeSpec:
170
2.95M
  case NestedNameSpecifier::TypeSpecWithTemplate: {
171
2.95M
    const TagType *Tag = NNS->getAsType()->getAs<TagType>();
172
2.95M
    assert(Tag && "Non-tag type in nested-name-specifier");
173
2.95M
    return Tag->getDecl();
174
2.95M
  }
175
176
761k
  case NestedNameSpecifier::Global:
177
761k
    return Context.getTranslationUnitDecl();
178
179
70
  case NestedNameSpecifier::Super:
180
70
    return NNS->getAsRecordDecl();
181
7.98M
  }
182
183
0
  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
184
0
}
185
186
3.18M
bool Sema::isDependentScopeSpecifier(const CXXScopeSpec &SS) {
187
3.18M
  if (!SS.isSet() || 
SS.isInvalid()2.71M
)
188
464k
    return false;
189
190
2.71M
  return SS.getScopeRep()->isDependent();
191
3.18M
}
192
193
/// If the given nested name specifier refers to the current
194
/// instantiation, return the declaration that corresponds to that
195
/// current instantiation (C++0x [temp.dep.type]p1).
196
///
197
/// \param NNS a dependent nested name specifier.
198
7.73M
CXXRecordDecl *Sema::getCurrentInstantiationOf(NestedNameSpecifier *NNS) {
199
7.73M
  assert(getLangOpts().CPlusPlus && "Only callable in C++");
200
7.73M
  assert(NNS->isDependent() && "Only dependent nested-name-specifier allowed");
201
202
7.73M
  if (!NNS->getAsType())
203
79.2k
    return nullptr;
204
205
7.65M
  QualType T = QualType(NNS->getAsType(), 0);
206
7.65M
  return ::getCurrentInstantiationOf(T, CurContext);
207
7.73M
}
208
209
/// Require that the context specified by SS be complete.
210
///
211
/// If SS refers to a type, this routine checks whether the type is
212
/// complete enough (or can be made complete enough) for name lookup
213
/// into the DeclContext. A type that is not yet completed can be
214
/// considered "complete enough" if it is a class/struct/union/enum
215
/// that is currently being defined. Or, if we have a type that names
216
/// a class template specialization that is not a complete type, we
217
/// will attempt to instantiate that class template.
218
bool Sema::RequireCompleteDeclContext(CXXScopeSpec &SS,
219
6.91M
                                      DeclContext *DC) {
220
6.91M
  assert(DC && "given null context");
221
222
6.91M
  TagDecl *tag = dyn_cast<TagDecl>(DC);
223
224
  // If this is a dependent type, then we consider it complete.
225
  // FIXME: This is wrong; we should require a (visible) definition to
226
  // exist in this case too.
227
6.91M
  if (!tag || 
tag->isDependentContext()2.64M
)
228
4.35M
    return false;
229
230
  // Grab the tag definition, if there is one.
231
2.55M
  QualType type = Context.getTypeDeclType(tag);
232
2.55M
  tag = type->getAsTagDecl();
233
234
  // If we're currently defining this type, then lookup into the
235
  // type is okay: don't complain that it isn't complete yet.
236
2.55M
  if (tag->isBeingDefined())
237
2.77k
    return false;
238
239
2.55M
  SourceLocation loc = SS.getLastQualifierNameLoc();
240
2.55M
  if (loc.isInvalid()) 
loc = SS.getRange().getBegin()645
;
241
242
  // The type must be complete.
243
2.55M
  if (RequireCompleteType(loc, type, diag::err_incomplete_nested_name_spec,
244
2.55M
                          SS.getRange())) {
245
946
    SS.SetInvalid(SS.getRange());
246
946
    return true;
247
946
  }
248
249
2.55M
  if (auto *EnumD = dyn_cast<EnumDecl>(tag))
250
    // Fixed enum types and scoped enum instantiations are complete, but they
251
    // aren't valid as scopes until we see or instantiate their definition.
252
42.2k
    return RequireCompleteEnumDecl(EnumD, loc, &SS);
253
254
2.51M
  return false;
255
2.55M
}
256
257
/// Require that the EnumDecl is completed with its enumerators defined or
258
/// instantiated. SS, if provided, is the ScopeRef parsed.
259
///
260
bool Sema::RequireCompleteEnumDecl(EnumDecl *EnumD, SourceLocation L,
261
42.2k
                                   CXXScopeSpec *SS) {
262
42.2k
  if (EnumD->isCompleteDefinition()) {
263
    // If we know about the definition but it is not visible, complain.
264
42.2k
    NamedDecl *SuggestedDef = nullptr;
265
42.2k
    if (!hasReachableDefinition(EnumD, &SuggestedDef,
266
42.2k
                                /*OnlyNeedComplete*/ false)) {
267
      // If the user is going to see an error here, recover by making the
268
      // definition visible.
269
25
      bool TreatAsComplete = !isSFINAEContext();
270
25
      diagnoseMissingImport(L, SuggestedDef, MissingImportKind::Definition,
271
25
                            /*Recover*/ TreatAsComplete);
272
25
      return !TreatAsComplete;
273
25
    }
274
42.2k
    return false;
275
42.2k
  }
276
277
  // Try to instantiate the definition, if this is a specialization of an
278
  // enumeration temploid.
279
53
  if (EnumDecl *Pattern = EnumD->getInstantiatedFromMemberEnum()) {
280
42
    MemberSpecializationInfo *MSI = EnumD->getMemberSpecializationInfo();
281
42
    if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
282
41
      if (InstantiateEnum(L, EnumD, Pattern,
283
41
                          getTemplateInstantiationArgs(EnumD),
284
41
                          TSK_ImplicitInstantiation)) {
285
8
        if (SS)
286
7
          SS->SetInvalid(SS->getRange());
287
8
        return true;
288
8
      }
289
33
      return false;
290
41
    }
291
42
  }
292
293
12
  if (SS) {
294
11
    Diag(L, diag::err_incomplete_nested_name_spec)
295
11
        << QualType(EnumD->getTypeForDecl(), 0) << SS->getRange();
296
11
    SS->SetInvalid(SS->getRange());
297
11
  } else {
298
1
    Diag(L, diag::err_incomplete_enum) << QualType(EnumD->getTypeForDecl(), 0);
299
1
    Diag(EnumD->getLocation(), diag::note_declared_at);
300
1
  }
301
302
12
  return true;
303
53
}
304
305
bool Sema::ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc,
306
251k
                                        CXXScopeSpec &SS) {
307
251k
  SS.MakeGlobal(Context, CCLoc);
308
251k
  return false;
309
251k
}
310
311
bool Sema::ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
312
                                    SourceLocation ColonColonLoc,
313
42
                                    CXXScopeSpec &SS) {
314
42
  if (getCurLambda()) {
315
1
    Diag(SuperLoc, diag::err_super_in_lambda_unsupported);
316
1
    return true;
317
1
  }
318
319
41
  CXXRecordDecl *RD = nullptr;
320
44
  for (Scope *S = getCurScope(); S; 
S = S->getParent()3
) {
321
44
    if (S->isFunctionScope()) {
322
26
      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(S->getEntity()))
323
26
        RD = MD->getParent();
324
26
      break;
325
26
    }
326
18
    if (S->isClassScope()) {
327
15
      RD = cast<CXXRecordDecl>(S->getEntity());
328
15
      break;
329
15
    }
330
18
  }
331
332
41
  if (!RD) {
333
0
    Diag(SuperLoc, diag::err_invalid_super_scope);
334
0
    return true;
335
41
  } else if (RD->getNumBases() == 0) {
336
1
    Diag(SuperLoc, diag::err_no_base_classes) << RD->getName();
337
1
    return true;
338
1
  }
339
340
40
  SS.MakeSuper(Context, RD, SuperLoc, ColonColonLoc);
341
40
  return false;
342
41
}
343
344
/// Determines whether the given declaration is an valid acceptable
345
/// result for name lookup of a nested-name-specifier.
346
/// \param SD Declaration checked for nested-name-specifier.
347
/// \param IsExtension If not null and the declaration is accepted as an
348
/// extension, the pointed variable is assigned true.
349
bool Sema::isAcceptableNestedNameSpecifier(const NamedDecl *SD,
350
2.16M
                                           bool *IsExtension) {
351
2.16M
  if (!SD)
352
2.69k
    return false;
353
354
2.16M
  SD = SD->getUnderlyingDecl();
355
356
  // Namespace and namespace aliases are fine.
357
2.16M
  if (isa<NamespaceDecl>(SD))
358
1.36M
    return true;
359
360
796k
  if (!isa<TypeDecl>(SD))
361
16
    return false;
362
363
  // Determine whether we have a class (or, in C++11, an enum) or
364
  // a typedef thereof. If so, build the nested-name-specifier.
365
796k
  QualType T = Context.getTypeDeclType(cast<TypeDecl>(SD));
366
796k
  if (T->isDependentType())
367
512k
    return true;
368
284k
  if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
369
17.7k
    if (TD->getUnderlyingType()->isRecordType())
370
17.6k
      return true;
371
25
    if (TD->getUnderlyingType()->isEnumeralType()) {
372
11
      if (Context.getLangOpts().CPlusPlus11)
373
11
        return true;
374
0
      if (IsExtension)
375
0
        *IsExtension = true;
376
0
    }
377
266k
  } else if (isa<RecordDecl>(SD)) {
378
255k
    return true;
379
255k
  } else 
if (10.7k
isa<EnumDecl>(SD)10.7k
) {
380
10.7k
    if (Context.getLangOpts().CPlusPlus11)
381
10.6k
      return true;
382
21
    if (IsExtension)
383
12
      *IsExtension = true;
384
21
  }
385
386
35
  return false;
387
284k
}
388
389
/// If the given nested-name-specifier begins with a bare identifier
390
/// (e.g., Base::), perform name lookup for that identifier as a
391
/// nested-name-specifier within the given scope, and return the result of that
392
/// name lookup.
393
775
NamedDecl *Sema::FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS) {
394
775
  if (!S || !NNS)
395
0
    return nullptr;
396
397
977
  
while (775
NNS->getPrefix())
398
202
    NNS = NNS->getPrefix();
399
400
775
  if (NNS->getKind() != NestedNameSpecifier::Identifier)
401
705
    return nullptr;
402
403
70
  LookupResult Found(*this, NNS->getAsIdentifier(), SourceLocation(),
404
70
                     LookupNestedNameSpecifierName);
405
70
  LookupName(Found, S);
406
70
  assert(!Found.isAmbiguous() && "Cannot handle ambiguities here yet");
407
408
70
  if (!Found.isSingleResult())
409
15
    return nullptr;
410
411
55
  NamedDecl *Result = Found.getFoundDecl();
412
55
  if (isAcceptableNestedNameSpecifier(Result))
413
53
    return Result;
414
415
2
  return nullptr;
416
55
}
417
418
bool Sema::isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
419
0
                                        NestedNameSpecInfo &IdInfo) {
420
0
  QualType ObjectType = GetTypeFromParser(IdInfo.ObjectType);
421
0
  LookupResult Found(*this, IdInfo.Identifier, IdInfo.IdentifierLoc,
422
0
                     LookupNestedNameSpecifierName);
423
424
  // Determine where to perform name lookup
425
0
  DeclContext *LookupCtx = nullptr;
426
0
  bool isDependent = false;
427
0
  if (!ObjectType.isNull()) {
428
    // This nested-name-specifier occurs in a member access expression, e.g.,
429
    // x->B::f, and we are looking into the type of the object.
430
0
    assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
431
0
    LookupCtx = computeDeclContext(ObjectType);
432
0
    isDependent = ObjectType->isDependentType();
433
0
  } else if (SS.isSet()) {
434
    // This nested-name-specifier occurs after another nested-name-specifier,
435
    // so long into the context associated with the prior nested-name-specifier.
436
0
    LookupCtx = computeDeclContext(SS, false);
437
0
    isDependent = isDependentScopeSpecifier(SS);
438
0
    Found.setContextRange(SS.getRange());
439
0
  }
440
441
0
  if (LookupCtx) {
442
    // Perform "qualified" name lookup into the declaration context we
443
    // computed, which is either the type of the base of a member access
444
    // expression or the declaration context associated with a prior
445
    // nested-name-specifier.
446
447
    // The declaration context must be complete.
448
0
    if (!LookupCtx->isDependentContext() &&
449
0
        RequireCompleteDeclContext(SS, LookupCtx))
450
0
      return false;
451
452
0
    LookupQualifiedName(Found, LookupCtx);
453
0
  } else if (isDependent) {
454
0
    return false;
455
0
  } else {
456
0
    LookupName(Found, S);
457
0
  }
458
0
  Found.suppressDiagnostics();
459
460
0
  return Found.getAsSingle<NamespaceDecl>();
461
0
}
462
463
namespace {
464
465
// Callback to only accept typo corrections that can be a valid C++ member
466
// initializer: either a non-static field member or a base class.
467
class NestedNameSpecifierValidatorCCC final
468
    : public CorrectionCandidateCallback {
469
public:
470
  explicit NestedNameSpecifierValidatorCCC(Sema &SRef)
471
173
      : SRef(SRef) {}
472
473
84
  bool ValidateCandidate(const TypoCorrection &candidate) override {
474
84
    return SRef.isAcceptableNestedNameSpecifier(candidate.getCorrectionDecl());
475
84
  }
476
477
152
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
478
152
    return std::make_unique<NestedNameSpecifierValidatorCCC>(*this);
479
152
  }
480
481
 private:
482
  Sema &SRef;
483
};
484
485
}
486
487
/// Build a new nested-name-specifier for "identifier::", as described
488
/// by ActOnCXXNestedNameSpecifier.
489
///
490
/// \param S Scope in which the nested-name-specifier occurs.
491
/// \param IdInfo Parser information about an identifier in the
492
///        nested-name-spec.
493
/// \param EnteringContext If true, enter the context specified by the
494
///        nested-name-specifier.
495
/// \param SS Optional nested name specifier preceding the identifier.
496
/// \param ScopeLookupResult Provides the result of name lookup within the
497
///        scope of the nested-name-specifier that was computed at template
498
///        definition time.
499
/// \param ErrorRecoveryLookup Specifies if the method is called to improve
500
///        error recovery and what kind of recovery is performed.
501
/// \param IsCorrectedToColon If not null, suggestion of replace '::' -> ':'
502
///        are allowed.  The bool value pointed by this parameter is set to
503
///       'true' if the identifier is treated as if it was followed by ':',
504
///        not '::'.
505
/// \param OnlyNamespace If true, only considers namespaces in lookup.
506
///
507
/// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
508
/// that it contains an extra parameter \p ScopeLookupResult, which provides
509
/// the result of name lookup within the scope of the nested-name-specifier
510
/// that was computed at template definition time.
511
///
512
/// If ErrorRecoveryLookup is true, then this call is used to improve error
513
/// recovery.  This means that it should not emit diagnostics, it should
514
/// just return true on failure.  It also means it should only return a valid
515
/// scope if it *knows* that the result is correct.  It should not return in a
516
/// dependent context, for example. Nor will it extend \p SS with the scope
517
/// specifier.
518
bool Sema::BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
519
                                       bool EnteringContext, CXXScopeSpec &SS,
520
                                       NamedDecl *ScopeLookupResult,
521
                                       bool ErrorRecoveryLookup,
522
                                       bool *IsCorrectedToColon,
523
2.19M
                                       bool OnlyNamespace) {
524
2.19M
  if (IdInfo.Identifier->isEditorPlaceholder())
525
4
    return true;
526
2.19M
  LookupResult Found(*this, IdInfo.Identifier, IdInfo.IdentifierLoc,
527
2.19M
                     OnlyNamespace ? 
LookupNamespaceName183
528
2.19M
                                   : 
LookupNestedNameSpecifierName2.19M
);
529
2.19M
  QualType ObjectType = GetTypeFromParser(IdInfo.ObjectType);
530
531
  // Determine where to perform name lookup
532
2.19M
  DeclContext *LookupCtx = nullptr;
533
2.19M
  bool isDependent = false;
534
2.19M
  if (IsCorrectedToColon)
535
161k
    *IsCorrectedToColon = false;
536
2.19M
  if (!ObjectType.isNull()) {
537
    // This nested-name-specifier occurs in a member access expression, e.g.,
538
    // x->B::f, and we are looking into the type of the object.
539
826
    assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
540
826
    LookupCtx = computeDeclContext(ObjectType);
541
826
    isDependent = ObjectType->isDependentType();
542
2.18M
  } else if (SS.isSet()) {
543
    // This nested-name-specifier occurs after another nested-name-specifier,
544
    // so look into the context associated with the prior nested-name-specifier.
545
49.8k
    LookupCtx = computeDeclContext(SS, EnteringContext);
546
49.8k
    isDependent = isDependentScopeSpecifier(SS);
547
49.8k
    Found.setContextRange(SS.getRange());
548
49.8k
  }
549
550
2.19M
  bool ObjectTypeSearchedInScope = false;
551
2.19M
  if (LookupCtx) {
552
    // Perform "qualified" name lookup into the declaration context we
553
    // computed, which is either the type of the base of a member access
554
    // expression or the declaration context associated with a prior
555
    // nested-name-specifier.
556
557
    // The declaration context must be complete.
558
25.3k
    if (!LookupCtx->isDependentContext() &&
559
25.3k
        
RequireCompleteDeclContext(SS, LookupCtx)24.5k
)
560
0
      return true;
561
562
25.3k
    LookupQualifiedName(Found, LookupCtx);
563
564
25.3k
    if (!ObjectType.isNull() && 
Found.empty()712
) {
565
      // C++ [basic.lookup.classref]p4:
566
      //   If the id-expression in a class member access is a qualified-id of
567
      //   the form
568
      //
569
      //        class-name-or-namespace-name::...
570
      //
571
      //   the class-name-or-namespace-name following the . or -> operator is
572
      //   looked up both in the context of the entire postfix-expression and in
573
      //   the scope of the class of the object expression. If the name is found
574
      //   only in the scope of the class of the object expression, the name
575
      //   shall refer to a class-name. If the name is found only in the
576
      //   context of the entire postfix-expression, the name shall refer to a
577
      //   class-name or namespace-name. [...]
578
      //
579
      // Qualified name lookup into a class will not find a namespace-name,
580
      // so we do not need to diagnose that case specifically. However,
581
      // this qualified name lookup may find nothing. In that case, perform
582
      // unqualified name lookup in the given scope (if available) or
583
      // reconstruct the result from when name lookup was performed at template
584
      // definition time.
585
369
      if (S)
586
342
        LookupName(Found, S);
587
27
      else if (ScopeLookupResult)
588
22
        Found.addDecl(ScopeLookupResult);
589
590
369
      ObjectTypeSearchedInScope = true;
591
369
    }
592
2.16M
  } else if (!isDependent) {
593
    // Perform unqualified name lookup in the current scope.
594
2.13M
    LookupName(Found, S);
595
2.13M
  }
596
597
2.19M
  if (Found.isAmbiguous())
598
6
    return true;
599
600
  // If we performed lookup into a dependent context and did not find anything,
601
  // that's fine: just build a dependent nested-name-specifier.
602
2.19M
  if (Found.empty() && 
isDependent28.0k
&&
603
2.19M
      
!(25.2k
LookupCtx25.2k
&&
LookupCtx->isRecord()6
&&
604
25.2k
        
(6
!cast<CXXRecordDecl>(LookupCtx)->hasDefinition()6
||
605
25.2k
         
!cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()3
))) {
606
    // Don't speculate if we're just trying to improve error recovery.
607
25.2k
    if (ErrorRecoveryLookup)
608
0
      return true;
609
610
    // We were not able to compute the declaration context for a dependent
611
    // base object type or prior nested-name-specifier, so this
612
    // nested-name-specifier refers to an unknown specialization. Just build
613
    // a dependent nested-name-specifier.
614
25.2k
    SS.Extend(Context, IdInfo.Identifier, IdInfo.IdentifierLoc, IdInfo.CCLoc);
615
25.2k
    return false;
616
25.2k
  }
617
618
2.16M
  if (Found.empty() && 
!ErrorRecoveryLookup2.78k
) {
619
    // If identifier is not found as class-name-or-namespace-name, but is found
620
    // as other entity, don't look for typos.
621
215
    LookupResult R(*this, Found.getLookupNameInfo(), LookupOrdinaryName);
622
215
    if (LookupCtx)
623
47
      LookupQualifiedName(R, LookupCtx);
624
168
    else if (S && 
!isDependent166
)
625
166
      LookupName(R, S);
626
215
    if (!R.empty()) {
627
      // Don't diagnose problems with this speculative lookup.
628
28
      R.suppressDiagnostics();
629
      // The identifier is found in ordinary lookup. If correction to colon is
630
      // allowed, suggest replacement to ':'.
631
28
      if (IsCorrectedToColon) {
632
9
        *IsCorrectedToColon = true;
633
9
        Diag(IdInfo.CCLoc, diag::err_nested_name_spec_is_not_class)
634
9
            << IdInfo.Identifier << getLangOpts().CPlusPlus
635
9
            << FixItHint::CreateReplacement(IdInfo.CCLoc, ":");
636
9
        if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
637
9
          Diag(ND->getLocation(), diag::note_declared_at);
638
9
        return true;
639
9
      }
640
      // Replacement '::' -> ':' is not allowed, just issue respective error.
641
19
      Diag(R.getNameLoc(), OnlyNamespace
642
19
                               ? 
unsigned(diag::err_expected_namespace_name)13
643
19
                               : 
unsigned(diag::err_expected_class_or_namespace)6
)
644
19
          << IdInfo.Identifier << getLangOpts().CPlusPlus;
645
19
      if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
646
19
        Diag(ND->getLocation(), diag::note_entity_declared_at)
647
19
            << IdInfo.Identifier;
648
19
      return true;
649
28
    }
650
215
  }
651
652
2.16M
  if (Found.empty() && 
!ErrorRecoveryLookup2.75k
&&
!getLangOpts().MSVCCompat187
) {
653
    // We haven't found anything, and we're not recovering from a
654
    // different kind of error, so look for typos.
655
173
    DeclarationName Name = Found.getLookupName();
656
173
    Found.clear();
657
173
    NestedNameSpecifierValidatorCCC CCC(*this);
658
173
    if (TypoCorrection Corrected = CorrectTypo(
659
173
            Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS, CCC,
660
173
            CTK_ErrorRecovery, LookupCtx, EnteringContext)) {
661
71
      if (LookupCtx) {
662
10
        bool DroppedSpecifier =
663
10
            Corrected.WillReplaceSpecifier() &&
664
10
            
Name.getAsString() == Corrected.getAsString(getLangOpts())6
;
665
10
        if (DroppedSpecifier)
666
2
          SS.clear();
667
10
        diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
668
10
                                  << Name << LookupCtx << DroppedSpecifier
669
10
                                  << SS.getRange());
670
10
      } else
671
61
        diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
672
61
                                  << Name);
673
674
71
      if (Corrected.getCorrectionSpecifier())
675
14
        SS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
676
14
                       SourceRange(Found.getNameLoc()));
677
678
71
      if (NamedDecl *ND = Corrected.getFoundDecl())
679
71
        Found.addDecl(ND);
680
71
      Found.setLookupName(Corrected.getCorrection());
681
102
    } else {
682
102
      Found.setLookupName(IdInfo.Identifier);
683
102
    }
684
173
  }
685
686
2.16M
  NamedDecl *SD =
687
2.16M
      Found.isSingleResult() ? 
Found.getRepresentativeDecl()2.16M
:
nullptr2.68k
;
688
2.16M
  bool IsExtension = false;
689
2.16M
  bool AcceptSpec = isAcceptableNestedNameSpecifier(SD, &IsExtension);
690
2.16M
  if (!AcceptSpec && 
IsExtension2.71k
) {
691
12
    AcceptSpec = true;
692
12
    Diag(IdInfo.IdentifierLoc, diag::ext_nested_name_spec_is_enum);
693
12
  }
694
2.16M
  if (AcceptSpec) {
695
2.16M
    if (!ObjectType.isNull() && 
!ObjectTypeSearchedInScope716
&&
696
2.16M
        
!getLangOpts().CPlusPlus11382
) {
697
      // C++03 [basic.lookup.classref]p4:
698
      //   [...] If the name is found in both contexts, the
699
      //   class-name-or-namespace-name shall refer to the same entity.
700
      //
701
      // We already found the name in the scope of the object. Now, look
702
      // into the current scope (the scope of the postfix-expression) to
703
      // see if we can find the same name there. As above, if there is no
704
      // scope, reconstruct the result from the template instantiation itself.
705
      //
706
      // Note that C++11 does *not* perform this redundant lookup.
707
52
      NamedDecl *OuterDecl;
708
52
      if (S) {
709
43
        LookupResult FoundOuter(*this, IdInfo.Identifier, IdInfo.IdentifierLoc,
710
43
                                LookupNestedNameSpecifierName);
711
43
        LookupName(FoundOuter, S);
712
43
        OuterDecl = FoundOuter.getAsSingle<NamedDecl>();
713
43
      } else
714
9
        OuterDecl = ScopeLookupResult;
715
716
52
      if (isAcceptableNestedNameSpecifier(OuterDecl) &&
717
52
          
OuterDecl->getCanonicalDecl() != SD->getCanonicalDecl()41
&&
718
52
          
(32
!isa<TypeDecl>(OuterDecl)32
||
!isa<TypeDecl>(SD)32
||
719
32
           !Context.hasSameType(
720
32
                            Context.getTypeDeclType(cast<TypeDecl>(OuterDecl)),
721
32
                               Context.getTypeDeclType(cast<TypeDecl>(SD))))) {
722
2
        if (ErrorRecoveryLookup)
723
0
          return true;
724
725
2
         Diag(IdInfo.IdentifierLoc,
726
2
              diag::err_nested_name_member_ref_lookup_ambiguous)
727
2
           << IdInfo.Identifier;
728
2
         Diag(SD->getLocation(), diag::note_ambig_member_ref_object_type)
729
2
           << ObjectType;
730
2
         Diag(OuterDecl->getLocation(), diag::note_ambig_member_ref_scope);
731
732
         // Fall through so that we'll pick the name we found in the object
733
         // type, since that's probably what the user wanted anyway.
734
2
       }
735
52
    }
736
737
2.16M
    if (auto *TD = dyn_cast_or_null<TypedefNameDecl>(SD))
738
350k
      MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
739
740
    // If we're just performing this lookup for error-recovery purposes,
741
    // don't extend the nested-name-specifier. Just return now.
742
2.16M
    if (ErrorRecoveryLookup)
743
176
      return false;
744
745
    // The use of a nested name specifier may trigger deprecation warnings.
746
2.16M
    DiagnoseUseOfDecl(SD, IdInfo.CCLoc);
747
748
2.16M
    if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(SD)) {
749
1.36M
      SS.Extend(Context, Namespace, IdInfo.IdentifierLoc, IdInfo.CCLoc);
750
1.36M
      return false;
751
1.36M
    }
752
753
796k
    if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(SD)) {
754
245
      SS.Extend(Context, Alias, IdInfo.IdentifierLoc, IdInfo.CCLoc);
755
245
      return false;
756
245
    }
757
758
796k
    QualType T =
759
796k
        Context.getTypeDeclType(cast<TypeDecl>(SD->getUnderlyingDecl()));
760
761
796k
    if (T->isEnumeralType())
762
10.7k
      Diag(IdInfo.IdentifierLoc, diag::warn_cxx98_compat_enum_nested_name_spec);
763
764
796k
    TypeLocBuilder TLB;
765
796k
    if (const auto *USD = dyn_cast<UsingShadowDecl>(SD)) {
766
415
      T = Context.getUsingType(USD, T);
767
415
      TLB.pushTypeSpec(T).setNameLoc(IdInfo.IdentifierLoc);
768
795k
    } else if (isa<InjectedClassNameType>(T)) {
769
945
      InjectedClassNameTypeLoc InjectedTL
770
945
        = TLB.push<InjectedClassNameTypeLoc>(T);
771
945
      InjectedTL.setNameLoc(IdInfo.IdentifierLoc);
772
794k
    } else if (isa<RecordType>(T)) {
773
258k
      RecordTypeLoc RecordTL = TLB.push<RecordTypeLoc>(T);
774
258k
      RecordTL.setNameLoc(IdInfo.IdentifierLoc);
775
535k
    } else if (isa<TypedefType>(T)) {
776
350k
      TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(T);
777
350k
      TypedefTL.setNameLoc(IdInfo.IdentifierLoc);
778
350k
    } else 
if (185k
isa<EnumType>(T)185k
) {
779
10.5k
      EnumTypeLoc EnumTL = TLB.push<EnumTypeLoc>(T);
780
10.5k
      EnumTL.setNameLoc(IdInfo.IdentifierLoc);
781
174k
    } else if (isa<TemplateTypeParmType>(T)) {
782
174k
      TemplateTypeParmTypeLoc TemplateTypeTL
783
174k
        = TLB.push<TemplateTypeParmTypeLoc>(T);
784
174k
      TemplateTypeTL.setNameLoc(IdInfo.IdentifierLoc);
785
174k
    } else 
if (1
isa<UnresolvedUsingType>(T)1
) {
786
1
      UnresolvedUsingTypeLoc UnresolvedTL
787
1
        = TLB.push<UnresolvedUsingTypeLoc>(T);
788
1
      UnresolvedTL.setNameLoc(IdInfo.IdentifierLoc);
789
1
    } else 
if (0
isa<SubstTemplateTypeParmType>(T)0
) {
790
0
      SubstTemplateTypeParmTypeLoc TL
791
0
        = TLB.push<SubstTemplateTypeParmTypeLoc>(T);
792
0
      TL.setNameLoc(IdInfo.IdentifierLoc);
793
0
    } else if (isa<SubstTemplateTypeParmPackType>(T)) {
794
0
      SubstTemplateTypeParmPackTypeLoc TL
795
0
        = TLB.push<SubstTemplateTypeParmPackTypeLoc>(T);
796
0
      TL.setNameLoc(IdInfo.IdentifierLoc);
797
0
    } else {
798
0
      llvm_unreachable("Unhandled TypeDecl node in nested-name-specifier");
799
0
    }
800
801
796k
    SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T),
802
796k
              IdInfo.CCLoc);
803
796k
    return false;
804
796k
  }
805
806
  // Otherwise, we have an error case.  If we don't want diagnostics, just
807
  // return an error now.
808
2.69k
  if (ErrorRecoveryLookup)
809
2.56k
    return true;
810
811
  // If we didn't find anything during our lookup, try again with
812
  // ordinary name lookup, which can help us produce better error
813
  // messages.
814
132
  if (Found.empty()) {
815
116
    Found.clear(LookupOrdinaryName);
816
116
    LookupName(Found, S);
817
116
  }
818
819
  // In Microsoft mode, if we are within a templated function and we can't
820
  // resolve Identifier, then extend the SS with Identifier. This will have
821
  // the effect of resolving Identifier during template instantiation.
822
  // The goal is to be able to resolve a function call whose
823
  // nested-name-specifier is located inside a dependent base class.
824
  // Example:
825
  //
826
  // class C {
827
  // public:
828
  //    static void foo2() {  }
829
  // };
830
  // template <class T> class A { public: typedef C D; };
831
  //
832
  // template <class T> class B : public A<T> {
833
  // public:
834
  //   void foo() { D::foo2(); }
835
  // };
836
132
  if (getLangOpts().MSVCCompat) {
837
20
    DeclContext *DC = LookupCtx ? 
LookupCtx4
:
CurContext16
;
838
20
    if (DC->isDependentContext() && 
DC->isFunctionOrMethod()13
) {
839
13
      CXXRecordDecl *ContainingClass = dyn_cast<CXXRecordDecl>(DC->getParent());
840
13
      if (ContainingClass && 
ContainingClass->hasAnyDependentBases()11
) {
841
10
        Diag(IdInfo.IdentifierLoc,
842
10
             diag::ext_undeclared_unqual_id_with_dependent_base)
843
10
            << IdInfo.Identifier << ContainingClass;
844
10
        SS.Extend(Context, IdInfo.Identifier, IdInfo.IdentifierLoc,
845
10
                  IdInfo.CCLoc);
846
10
        return false;
847
10
      }
848
13
    }
849
20
  }
850
851
122
  if (!Found.empty()) {
852
11
    if (TypeDecl *TD = Found.getAsSingle<TypeDecl>()) {
853
8
      Diag(IdInfo.IdentifierLoc, diag::err_expected_class_or_namespace)
854
8
          << Context.getTypeDeclType(TD) << getLangOpts().CPlusPlus;
855
8
    } else 
if (3
Found.getAsSingle<TemplateDecl>()3
) {
856
1
      ParsedType SuggestedType;
857
1
      DiagnoseUnknownTypeName(IdInfo.Identifier, IdInfo.IdentifierLoc, S, &SS,
858
1
                              SuggestedType);
859
2
    } else {
860
2
      Diag(IdInfo.IdentifierLoc, diag::err_expected_class_or_namespace)
861
2
          << IdInfo.Identifier << getLangOpts().CPlusPlus;
862
2
      if (NamedDecl *ND = Found.getAsSingle<NamedDecl>())
863
2
        Diag(ND->getLocation(), diag::note_entity_declared_at)
864
2
            << IdInfo.Identifier;
865
2
    }
866
111
  } else if (SS.isSet())
867
16
    Diag(IdInfo.IdentifierLoc, diag::err_no_member) << IdInfo.Identifier
868
16
        << LookupCtx << SS.getRange();
869
95
  else
870
95
    Diag(IdInfo.IdentifierLoc, diag::err_undeclared_var_use)
871
95
        << IdInfo.Identifier;
872
873
122
  return true;
874
132
}
875
876
bool Sema::ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
877
                                       bool EnteringContext, CXXScopeSpec &SS,
878
                                       bool *IsCorrectedToColon,
879
2.18M
                                       bool OnlyNamespace) {
880
2.18M
  if (SS.isInvalid())
881
25
    return true;
882
883
2.18M
  return BuildCXXNestedNameSpecifier(S, IdInfo, EnteringContext, SS,
884
2.18M
                                     /*ScopeLookupResult=*/nullptr, false,
885
2.18M
                                     IsCorrectedToColon, OnlyNamespace);
886
2.18M
}
887
888
bool Sema::ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
889
                                               const DeclSpec &DS,
890
3.64k
                                               SourceLocation ColonColonLoc) {
891
3.64k
  if (SS.isInvalid() || DS.getTypeSpecType() == DeclSpec::TST_error)
892
3
    return true;
893
894
3.64k
  assert(DS.getTypeSpecType() == DeclSpec::TST_decltype);
895
896
3.64k
  QualType T = BuildDecltypeType(DS.getRepAsExpr());
897
3.64k
  if (T.isNull())
898
0
    return true;
899
900
3.64k
  if (!T->isDependentType() && 
!T->getAs<TagType>()103
) {
901
11
    Diag(DS.getTypeSpecTypeLoc(), diag::err_expected_class_or_namespace)
902
11
      << T << getLangOpts().CPlusPlus;
903
11
    return true;
904
11
  }
905
906
3.63k
  TypeLocBuilder TLB;
907
3.63k
  DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
908
3.63k
  DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
909
3.63k
  DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd());
910
3.63k
  SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T),
911
3.63k
            ColonColonLoc);
912
3.63k
  return false;
913
3.64k
}
914
915
/// IsInvalidUnlessNestedName - This method is used for error recovery
916
/// purposes to determine whether the specified identifier is only valid as
917
/// a nested name specifier, for example a namespace name.  It is
918
/// conservatively correct to always return false from this method.
919
///
920
/// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
921
bool Sema::IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
922
                                     NestedNameSpecInfo &IdInfo,
923
2.74k
                                     bool EnteringContext) {
924
2.74k
  if (SS.isInvalid())
925
0
    return false;
926
927
2.74k
  return !BuildCXXNestedNameSpecifier(S, IdInfo, EnteringContext, SS,
928
2.74k
                                      /*ScopeLookupResult=*/nullptr, true);
929
2.74k
}
930
931
bool Sema::ActOnCXXNestedNameSpecifier(Scope *S,
932
                                       CXXScopeSpec &SS,
933
                                       SourceLocation TemplateKWLoc,
934
                                       TemplateTy OpaqueTemplate,
935
                                       SourceLocation TemplateNameLoc,
936
                                       SourceLocation LAngleLoc,
937
                                       ASTTemplateArgsPtr TemplateArgsIn,
938
                                       SourceLocation RAngleLoc,
939
                                       SourceLocation CCLoc,
940
1.46M
                                       bool EnteringContext) {
941
1.46M
  if (SS.isInvalid())
942
0
    return true;
943
944
1.46M
  TemplateName Template = OpaqueTemplate.get();
945
946
  // Translate the parser's template argument list in our AST format.
947
1.46M
  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
948
1.46M
  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
949
950
1.46M
  DependentTemplateName *DTN = Template.getAsDependentTemplateName();
951
1.46M
  if (DTN && 
DTN->isIdentifier()1.55k
) {
952
    // Handle a dependent template specialization for which we cannot resolve
953
    // the template name.
954
1.54k
    assert(DTN->getQualifier() == SS.getScopeRep());
955
1.54k
    QualType T = Context.getDependentTemplateSpecializationType(
956
1.54k
        ETK_None, DTN->getQualifier(), DTN->getIdentifier(),
957
1.54k
        TemplateArgs.arguments());
958
959
    // Create source-location information for this type.
960
1.54k
    TypeLocBuilder Builder;
961
1.54k
    DependentTemplateSpecializationTypeLoc SpecTL
962
1.54k
      = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
963
1.54k
    SpecTL.setElaboratedKeywordLoc(SourceLocation());
964
1.54k
    SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
965
1.54k
    SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
966
1.54k
    SpecTL.setTemplateNameLoc(TemplateNameLoc);
967
1.54k
    SpecTL.setLAngleLoc(LAngleLoc);
968
1.54k
    SpecTL.setRAngleLoc(RAngleLoc);
969
3.09k
    for (unsigned I = 0, N = TemplateArgs.size(); I != N; 
++I1.55k
)
970
1.55k
      SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
971
972
1.54k
    SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T),
973
1.54k
              CCLoc);
974
1.54k
    return false;
975
1.54k
  }
976
977
  // If we assumed an undeclared identifier was a template name, try to
978
  // typo-correct it now.
979
1.46M
  if (Template.getAsAssumedTemplateName() &&
980
1.46M
      
resolveAssumedTemplateNameAsType(S, Template, TemplateNameLoc)12
)
981
9
    return true;
982
983
1.46M
  TemplateDecl *TD = Template.getAsTemplateDecl();
984
1.46M
  if (Template.getAsOverloadedTemplate() || 
DTN1.46M
||
985
1.46M
      
isa<FunctionTemplateDecl>(TD)1.46M
||
isa<VarTemplateDecl>(TD)1.46M
) {
986
21
    SourceRange R(TemplateNameLoc, RAngleLoc);
987
21
    if (SS.getRange().isValid())
988
12
      R.setBegin(SS.getRange().getBegin());
989
990
21
    Diag(CCLoc, diag::err_non_type_template_in_nested_name_specifier)
991
21
      << (TD && 
isa<VarTemplateDecl>(TD)6
) << Template << R;
992
21
    NoteAllFoundTemplates(Template);
993
21
    return true;
994
21
  }
995
996
  // We were able to resolve the template name to an actual template.
997
  // Build an appropriate nested-name-specifier.
998
1.46M
  QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
999
1.46M
  if (T.isNull())
1000
15
    return true;
1001
1002
  // Alias template specializations can produce types which are not valid
1003
  // nested name specifiers.
1004
1.46M
  if (!T->isDependentType() && 
!T->getAs<TagType>()93.1k
) {
1005
2
    Diag(TemplateNameLoc, diag::err_nested_name_spec_non_tag) << T;
1006
2
    NoteAllFoundTemplates(Template);
1007
2
    return true;
1008
2
  }
1009
1010
  // Provide source-location information for the template specialization type.
1011
1.46M
  TypeLocBuilder Builder;
1012
1.46M
  TemplateSpecializationTypeLoc SpecTL
1013
1.46M
    = Builder.push<TemplateSpecializationTypeLoc>(T);
1014
1.46M
  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
1015
1.46M
  SpecTL.setTemplateNameLoc(TemplateNameLoc);
1016
1.46M
  SpecTL.setLAngleLoc(LAngleLoc);
1017
1.46M
  SpecTL.setRAngleLoc(RAngleLoc);
1018
3.82M
  for (unsigned I = 0, N = TemplateArgs.size(); I != N; 
++I2.35M
)
1019
2.35M
    SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
1020
1021
1022
1.46M
  SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T),
1023
1.46M
            CCLoc);
1024
1.46M
  return false;
1025
1.46M
}
1026
1027
namespace {
1028
  /// A structure that stores a nested-name-specifier annotation,
1029
  /// including both the nested-name-specifier
1030
  struct NestedNameSpecifierAnnotation {
1031
    NestedNameSpecifier *NNS;
1032
  };
1033
}
1034
1035
5.19M
void *Sema::SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS) {
1036
5.19M
  if (SS.isEmpty() || SS.isInvalid())
1037
362
    return nullptr;
1038
1039
5.19M
  void *Mem = Context.Allocate(
1040
5.19M
      (sizeof(NestedNameSpecifierAnnotation) + SS.location_size()),
1041
5.19M
      alignof(NestedNameSpecifierAnnotation));
1042
5.19M
  NestedNameSpecifierAnnotation *Annotation
1043
5.19M
    = new (Mem) NestedNameSpecifierAnnotation;
1044
5.19M
  Annotation->NNS = SS.getScopeRep();
1045
5.19M
  memcpy(Annotation + 1, SS.location_data(), SS.location_size());
1046
5.19M
  return Annotation;
1047
5.19M
}
1048
1049
void Sema::RestoreNestedNameSpecifierAnnotation(void *AnnotationPtr,
1050
                                                SourceRange AnnotationRange,
1051
6.11M
                                                CXXScopeSpec &SS) {
1052
6.11M
  if (!AnnotationPtr) {
1053
414
    SS.SetInvalid(AnnotationRange);
1054
414
    return;
1055
414
  }
1056
1057
6.11M
  NestedNameSpecifierAnnotation *Annotation
1058
6.11M
    = static_cast<NestedNameSpecifierAnnotation *>(AnnotationPtr);
1059
6.11M
  SS.Adopt(NestedNameSpecifierLoc(Annotation->NNS, Annotation + 1));
1060
6.11M
}
1061
1062
380k
bool Sema::ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
1063
380k
  assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
1064
1065
  // Don't enter a declarator context when the current context is an Objective-C
1066
  // declaration.
1067
380k
  if (isa<ObjCContainerDecl>(CurContext) || 
isa<ObjCMethodDecl>(CurContext)380k
)
1068
12
    return false;
1069
1070
380k
  NestedNameSpecifier *Qualifier = SS.getScopeRep();
1071
1072
  // There are only two places a well-formed program may qualify a
1073
  // declarator: first, when defining a namespace or class member
1074
  // out-of-line, and second, when naming an explicitly-qualified
1075
  // friend function.  The latter case is governed by
1076
  // C++03 [basic.lookup.unqual]p10:
1077
  //   In a friend declaration naming a member function, a name used
1078
  //   in the function declarator and not part of a template-argument
1079
  //   in a template-id is first looked up in the scope of the member
1080
  //   function's class. If it is not found, or if the name is part of
1081
  //   a template-argument in a template-id, the look up is as
1082
  //   described for unqualified names in the definition of the class
1083
  //   granting friendship.
1084
  // i.e. we don't push a scope unless it's a class member.
1085
1086
380k
  switch (Qualifier->getKind()) {
1087
68
  case NestedNameSpecifier::Global:
1088
1.13k
  case NestedNameSpecifier::Namespace:
1089
1.15k
  case NestedNameSpecifier::NamespaceAlias:
1090
    // These are always namespace scopes.  We never want to enter a
1091
    // namespace scope from anything but a file context.
1092
1.15k
    return CurContext->getRedeclContext()->isFileContext();
1093
1094
7
  case NestedNameSpecifier::Identifier:
1095
379k
  case NestedNameSpecifier::TypeSpec:
1096
379k
  case NestedNameSpecifier::TypeSpecWithTemplate:
1097
379k
  case NestedNameSpecifier::Super:
1098
    // These are never namespace scopes.
1099
379k
    return true;
1100
380k
  }
1101
1102
0
  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
1103
0
}
1104
1105
/// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
1106
/// scope or nested-name-specifier) is parsed, part of a declarator-id.
1107
/// After this method is called, according to [C++ 3.4.3p3], names should be
1108
/// looked up in the declarator-id's scope, until the declarator is parsed and
1109
/// ActOnCXXExitDeclaratorScope is called.
1110
/// The 'SS' should be a non-empty valid CXXScopeSpec.
1111
379k
bool Sema::ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS) {
1112
379k
  assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
1113
1114
379k
  if (SS.isInvalid()) 
return true0
;
1115
1116
379k
  DeclContext *DC = computeDeclContext(SS, true);
1117
379k
  if (!DC) 
return true47
;
1118
1119
  // Before we enter a declarator's context, we need to make sure that
1120
  // it is a complete declaration context.
1121
379k
  if (!DC->isDependentContext() && 
RequireCompleteDeclContext(SS, DC)90.6k
)
1122
10
    return true;
1123
1124
379k
  EnterDeclaratorContext(S, DC);
1125
1126
  // Rebuild the nested name specifier for the new scope.
1127
379k
  if (DC->isDependentContext())
1128
288k
    RebuildNestedNameSpecifierInCurrentInstantiation(SS);
1129
1130
379k
  return false;
1131
379k
}
1132
1133
/// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
1134
/// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
1135
/// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
1136
/// Used to indicate that names should revert to being looked up in the
1137
/// defining scope.
1138
379k
void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
1139
379k
  assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
1140
379k
  if (SS.isInvalid())
1141
0
    return;
1142
379k
  assert(!SS.isInvalid() && computeDeclContext(SS, true) &&
1143
379k
         "exiting declarator scope we never really entered");
1144
379k
  ExitDeclaratorContext(S);
1145
379k
}