Coverage Report

Created: 2021-09-21 08:58

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaTemplate.cpp
Line
Count
Source (jump to first uncovered line)
1
//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
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
//  This file implements semantic analysis for C++ templates.
9
//===----------------------------------------------------------------------===//
10
11
#include "TreeTransform.h"
12
#include "clang/AST/ASTConsumer.h"
13
#include "clang/AST/ASTContext.h"
14
#include "clang/AST/DeclFriend.h"
15
#include "clang/AST/DeclTemplate.h"
16
#include "clang/AST/Expr.h"
17
#include "clang/AST/ExprCXX.h"
18
#include "clang/AST/RecursiveASTVisitor.h"
19
#include "clang/AST/TypeVisitor.h"
20
#include "clang/Basic/Builtins.h"
21
#include "clang/Basic/LangOptions.h"
22
#include "clang/Basic/PartialDiagnostic.h"
23
#include "clang/Basic/Stack.h"
24
#include "clang/Basic/TargetInfo.h"
25
#include "clang/Sema/DeclSpec.h"
26
#include "clang/Sema/Initialization.h"
27
#include "clang/Sema/Lookup.h"
28
#include "clang/Sema/Overload.h"
29
#include "clang/Sema/ParsedTemplate.h"
30
#include "clang/Sema/Scope.h"
31
#include "clang/Sema/SemaInternal.h"
32
#include "clang/Sema/Template.h"
33
#include "clang/Sema/TemplateDeduction.h"
34
#include "llvm/ADT/SmallBitVector.h"
35
#include "llvm/ADT/SmallString.h"
36
#include "llvm/ADT/StringExtras.h"
37
38
#include <iterator>
39
using namespace clang;
40
using namespace sema;
41
42
// Exported for use by Parser.
43
SourceRange
44
clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
45
8
                              unsigned N) {
46
8
  if (!N) 
return SourceRange()0
;
47
8
  return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
48
8
}
49
50
365k
unsigned Sema::getTemplateDepth(Scope *S) const {
51
365k
  unsigned Depth = 0;
52
53
  // Each template parameter scope represents one level of template parameter
54
  // depth.
55
883k
  for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
56
517k
       TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
57
517k
    ++Depth;
58
517k
  }
59
60
  // Note that there are template parameters with the given depth.
61
365k
  auto ParamsAtDepth = [&](unsigned D) 
{ Depth = std::max(Depth, D + 1); }0
;
62
63
  // Look for parameters of an enclosing generic lambda. We don't create a
64
  // template parameter scope for these.
65
365k
  for (FunctionScopeInfo *FSI : getFunctionScopes()) {
66
1
    if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
67
0
      if (!LSI->TemplateParams.empty()) {
68
0
        ParamsAtDepth(LSI->AutoTemplateParameterDepth);
69
0
        break;
70
0
      }
71
0
      if (LSI->GLTemplateParameterList) {
72
0
        ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
73
0
        break;
74
0
      }
75
0
    }
76
1
  }
77
78
  // Look for parameters of an enclosing terse function template. We don't
79
  // create a template parameter scope for these either.
80
365k
  for (const InventedTemplateParameterInfo &Info :
81
365k
       getInventedParameterInfos()) {
82
0
    if (!Info.TemplateParams.empty()) {
83
0
      ParamsAtDepth(Info.AutoTemplateParameterDepth);
84
0
      break;
85
0
    }
86
0
  }
87
88
365k
  return Depth;
89
365k
}
90
91
/// \brief Determine whether the declaration found is acceptable as the name
92
/// of a template and, if so, return that template declaration. Otherwise,
93
/// returns null.
94
///
95
/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
96
/// is true. In all other cases it will return a TemplateDecl (or null).
97
NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
98
                                       bool AllowFunctionTemplates,
99
7.12M
                                       bool AllowDependent) {
100
7.12M
  D = D->getUnderlyingDecl();
101
102
7.12M
  if (isa<TemplateDecl>(D)) {
103
6.14M
    if (!AllowFunctionTemplates && 
isa<FunctionTemplateDecl>(D)2.21k
)
104
1.69k
      return nullptr;
105
106
6.14M
    return D;
107
6.14M
  }
108
109
976k
  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
110
    // C++ [temp.local]p1:
111
    //   Like normal (non-template) classes, class templates have an
112
    //   injected-class-name (Clause 9). The injected-class-name
113
    //   can be used with or without a template-argument-list. When
114
    //   it is used without a template-argument-list, it is
115
    //   equivalent to the injected-class-name followed by the
116
    //   template-parameters of the class template enclosed in
117
    //   <>. When it is used with a template-argument-list, it
118
    //   refers to the specified class template specialization,
119
    //   which could be the current specialization or another
120
    //   specialization.
121
175k
    if (Record->isInjectedClassName()) {
122
169k
      Record = cast<CXXRecordDecl>(Record->getDeclContext());
123
169k
      if (Record->getDescribedClassTemplate())
124
127k
        return Record->getDescribedClassTemplate();
125
126
42.7k
      if (ClassTemplateSpecializationDecl *Spec
127
42.7k
            = dyn_cast<ClassTemplateSpecializationDecl>(Record))
128
41.6k
        return Spec->getSpecializedTemplate();
129
42.7k
    }
130
131
7.03k
    return nullptr;
132
175k
  }
133
134
  // 'using Dependent::foo;' can resolve to a template name.
135
  // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
136
  // injected-class-name).
137
801k
  if (AllowDependent && 
isa<UnresolvedUsingValueDecl>(D)800k
)
138
35
    return D;
139
140
801k
  return nullptr;
141
801k
}
142
143
void Sema::FilterAcceptableTemplateNames(LookupResult &R,
144
                                         bool AllowFunctionTemplates,
145
3.99M
                                         bool AllowDependent) {
146
3.99M
  LookupResult::Filter filter = R.makeFilter();
147
8.39M
  while (filter.hasNext()) {
148
4.40M
    NamedDecl *Orig = filter.next();
149
4.40M
    if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
150
809k
      filter.erase();
151
4.40M
  }
152
3.99M
  filter.done();
153
3.99M
}
154
155
bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
156
                                         bool AllowFunctionTemplates,
157
                                         bool AllowDependent,
158
149
                                         bool AllowNonTemplateFunctions) {
159
299
  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; 
++I150
) {
160
150
    if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
161
0
      return true;
162
150
    if (AllowNonTemplateFunctions &&
163
150
        
isa<FunctionDecl>((*I)->getUnderlyingDecl())3
)
164
0
      return true;
165
150
  }
166
167
149
  return false;
168
149
}
169
170
TemplateNameKind Sema::isTemplateName(Scope *S,
171
                                      CXXScopeSpec &SS,
172
                                      bool hasTemplateKeyword,
173
                                      const UnqualifiedId &Name,
174
                                      ParsedType ObjectTypePtr,
175
                                      bool EnteringContext,
176
                                      TemplateTy &TemplateResult,
177
                                      bool &MemberOfUnknownSpecialization,
178
3.69M
                                      bool Disambiguation) {
179
3.69M
  assert(getLangOpts().CPlusPlus && "No template names in C!");
180
181
0
  DeclarationName TName;
182
3.69M
  MemberOfUnknownSpecialization = false;
183
184
3.69M
  switch (Name.getKind()) {
185
3.69M
  case UnqualifiedIdKind::IK_Identifier:
186
3.69M
    TName = DeclarationName(Name.Identifier);
187
3.69M
    break;
188
189
2.07k
  case UnqualifiedIdKind::IK_OperatorFunctionId:
190
2.07k
    TName = Context.DeclarationNames.getCXXOperatorName(
191
2.07k
                                              Name.OperatorFunctionId.Operator);
192
2.07k
    break;
193
194
4
  case UnqualifiedIdKind::IK_LiteralOperatorId:
195
4
    TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
196
4
    break;
197
198
0
  default:
199
0
    return TNK_Non_template;
200
3.69M
  }
201
202
3.69M
  QualType ObjectType = ObjectTypePtr.get();
203
204
3.69M
  AssumedTemplateKind AssumedTemplate;
205
3.69M
  LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
206
3.69M
  if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
207
3.69M
                         MemberOfUnknownSpecialization, SourceLocation(),
208
3.69M
                         &AssumedTemplate,
209
3.69M
                         /*AllowTypoCorrection=*/!Disambiguation))
210
221
    return TNK_Non_template;
211
212
3.69M
  if (AssumedTemplate != AssumedTemplateKind::None) {
213
871
    TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
214
    // Let the parser know whether we found nothing or found functions; if we
215
    // found nothing, we want to more carefully check whether this is actually
216
    // a function template name versus some other kind of undeclared identifier.
217
871
    return AssumedTemplate == AssumedTemplateKind::FoundNothing
218
871
               ? 
TNK_Undeclared_template861
219
871
               : 
TNK_Function_template10
;
220
871
  }
221
222
3.69M
  if (R.empty())
223
874k
    return TNK_Non_template;
224
225
2.82M
  NamedDecl *D = nullptr;
226
2.82M
  if (R.isAmbiguous()) {
227
    // If we got an ambiguity involving a non-function template, treat this
228
    // as a template name, and pick an arbitrary template for error recovery.
229
9
    bool AnyFunctionTemplates = false;
230
17
    for (NamedDecl *FoundD : R) {
231
17
      if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
232
10
        if (isa<FunctionTemplateDecl>(FoundTemplate))
233
5
          AnyFunctionTemplates = true;
234
5
        else {
235
5
          D = FoundTemplate;
236
5
          break;
237
5
        }
238
10
      }
239
17
    }
240
241
    // If we didn't find any templates at all, this isn't a template name.
242
    // Leave the ambiguity for a later lookup to diagnose.
243
9
    if (!D && 
!AnyFunctionTemplates4
) {
244
2
      R.suppressDiagnostics();
245
2
      return TNK_Non_template;
246
2
    }
247
248
    // If the only templates were function templates, filter out the rest.
249
    // We'll diagnose the ambiguity later.
250
7
    if (!D)
251
2
      FilterAcceptableTemplateNames(R);
252
7
  }
253
254
  // At this point, we have either picked a single template name declaration D
255
  // or we have a non-empty set of results R containing either one template name
256
  // declaration or a set of function templates.
257
258
2.82M
  TemplateName Template;
259
2.82M
  TemplateNameKind TemplateKind;
260
261
2.82M
  unsigned ResultCount = R.end() - R.begin();
262
2.82M
  if (!D && 
ResultCount > 12.82M
) {
263
    // We assume that we'll preserve the qualifier from a function
264
    // template name in other ways.
265
106k
    Template = Context.getOverloadedTemplateName(R.begin(), R.end());
266
106k
    TemplateKind = TNK_Function_template;
267
268
    // We'll do this lookup again later.
269
106k
    R.suppressDiagnostics();
270
2.71M
  } else {
271
2.71M
    if (!D) {
272
2.71M
      D = getAsTemplateNameDecl(*R.begin());
273
2.71M
      assert(D && "unambiguous result is not a template name");
274
2.71M
    }
275
276
2.71M
    if (isa<UnresolvedUsingValueDecl>(D)) {
277
      // We don't yet know whether this is a template-name or not.
278
16
      MemberOfUnknownSpecialization = true;
279
16
      return TNK_Non_template;
280
16
    }
281
282
2.71M
    TemplateDecl *TD = cast<TemplateDecl>(D);
283
284
2.71M
    if (SS.isSet() && 
!SS.isInvalid()119k
) {
285
119k
      NestedNameSpecifier *Qualifier = SS.getScopeRep();
286
119k
      Template = Context.getQualifiedTemplateName(Qualifier,
287
119k
                                                  hasTemplateKeyword, TD);
288
2.59M
    } else {
289
2.59M
      Template = TemplateName(TD);
290
2.59M
    }
291
292
2.71M
    if (isa<FunctionTemplateDecl>(TD)) {
293
118k
      TemplateKind = TNK_Function_template;
294
295
      // We'll do this lookup again later.
296
118k
      R.suppressDiagnostics();
297
2.59M
    } else {
298
2.59M
      assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
299
2.59M
             isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
300
2.59M
             isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
301
0
      TemplateKind =
302
2.59M
          isa<VarTemplateDecl>(TD) ? 
TNK_Var_template3.41k
:
303
2.59M
          
isa<ConceptDecl>(TD)2.59M
?
TNK_Concept_template506
:
304
2.59M
          
TNK_Type_template2.59M
;
305
2.59M
    }
306
2.71M
  }
307
308
2.82M
  TemplateResult = TemplateTy::make(Template);
309
2.82M
  return TemplateKind;
310
2.82M
}
311
312
bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
313
                                SourceLocation NameLoc,
314
80.5k
                                ParsedTemplateTy *Template) {
315
80.5k
  CXXScopeSpec SS;
316
80.5k
  bool MemberOfUnknownSpecialization = false;
317
318
  // We could use redeclaration lookup here, but we don't need to: the
319
  // syntactic form of a deduction guide is enough to identify it even
320
  // if we can't look up the template name at all.
321
80.5k
  LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
322
80.5k
  if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
323
80.5k
                         /*EnteringContext*/ false,
324
80.5k
                         MemberOfUnknownSpecialization))
325
0
    return false;
326
327
80.5k
  if (R.empty()) 
return false76.5k
;
328
3.92k
  if (R.isAmbiguous()) {
329
    // FIXME: Diagnose an ambiguity if we find at least one template.
330
1
    R.suppressDiagnostics();
331
1
    return false;
332
1
  }
333
334
  // We only treat template-names that name type templates as valid deduction
335
  // guide names.
336
3.92k
  TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
337
3.92k
  if (!TD || 
!getAsTypeTemplateDecl(TD)1.08k
)
338
2.84k
    return false;
339
340
1.08k
  if (Template)
341
441
    *Template = TemplateTy::make(TemplateName(TD));
342
1.08k
  return true;
343
3.92k
}
344
345
bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
346
                                       SourceLocation IILoc,
347
                                       Scope *S,
348
                                       const CXXScopeSpec *SS,
349
                                       TemplateTy &SuggestedTemplate,
350
5
                                       TemplateNameKind &SuggestedKind) {
351
  // We can't recover unless there's a dependent scope specifier preceding the
352
  // template name.
353
  // FIXME: Typo correction?
354
5
  if (!SS || !SS->isSet() || 
!isDependentScopeSpecifier(*SS)0
||
355
5
      
computeDeclContext(*SS)0
)
356
5
    return false;
357
358
  // The code is missing a 'template' keyword prior to the dependent template
359
  // name.
360
0
  NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
361
0
  Diag(IILoc, diag::err_template_kw_missing)
362
0
    << Qualifier << II.getName()
363
0
    << FixItHint::CreateInsertion(IILoc, "template ");
364
0
  SuggestedTemplate
365
0
    = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
366
0
  SuggestedKind = TNK_Dependent_template_name;
367
0
  return true;
368
5
}
369
370
bool Sema::LookupTemplateName(LookupResult &Found,
371
                              Scope *S, CXXScopeSpec &SS,
372
                              QualType ObjectType,
373
                              bool EnteringContext,
374
                              bool &MemberOfUnknownSpecialization,
375
                              RequiredTemplateKind RequiredTemplate,
376
                              AssumedTemplateKind *ATK,
377
3.99M
                              bool AllowTypoCorrection) {
378
3.99M
  if (ATK)
379
3.89M
    *ATK = AssumedTemplateKind::None;
380
381
3.99M
  if (SS.isInvalid())
382
218
    return true;
383
384
3.99M
  Found.setTemplateNameLookup(true);
385
386
  // Determine where to perform name lookup
387
3.99M
  MemberOfUnknownSpecialization = false;
388
3.99M
  DeclContext *LookupCtx = nullptr;
389
3.99M
  bool IsDependent = false;
390
3.99M
  if (!ObjectType.isNull()) {
391
    // This nested-name-specifier occurs in a member access expression, e.g.,
392
    // x->B::f, and we are looking into the type of the object.
393
24.3k
    assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
394
0
    LookupCtx = computeDeclContext(ObjectType);
395
24.3k
    IsDependent = !LookupCtx && 
ObjectType->isDependentType()4.97k
;
396
24.3k
    assert((IsDependent || !ObjectType->isIncompleteType() ||
397
24.3k
            ObjectType->castAs<TagType>()->isBeingDefined()) &&
398
24.3k
           "Caller should have completed object type");
399
400
    // Template names cannot appear inside an Objective-C class or object type
401
    // or a vector type.
402
    //
403
    // FIXME: This is wrong. For example:
404
    //
405
    //   template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
406
    //   Vec<int> vi;
407
    //   vi.Vec<int>::~Vec<int>();
408
    //
409
    // ... should be accepted but we will not treat 'Vec' as a template name
410
    // here. The right thing to do would be to check if the name is a valid
411
    // vector component name, and look up a template name if not. And similarly
412
    // for lookups into Objective-C class and object types, where the same
413
    // problem can arise.
414
24.3k
    if (ObjectType->isObjCObjectOrInterfaceType() ||
415
24.3k
        
ObjectType->isVectorType()24.3k
) {
416
26
      Found.clear();
417
26
      return false;
418
26
    }
419
3.96M
  } else if (SS.isNotEmpty()) {
420
    // This nested-name-specifier occurs after another nested-name-specifier,
421
    // so long into the context associated with the prior nested-name-specifier.
422
481k
    LookupCtx = computeDeclContext(SS, EnteringContext);
423
481k
    IsDependent = !LookupCtx && 
isDependentScopeSpecifier(SS)162k
;
424
425
    // The declaration context must be complete.
426
481k
    if (LookupCtx && 
RequireCompleteDeclContext(SS, LookupCtx)318k
)
427
6
      return true;
428
481k
  }
429
430
3.99M
  bool ObjectTypeSearchedInScope = false;
431
3.99M
  bool AllowFunctionTemplatesInLookup = true;
432
3.99M
  if (LookupCtx) {
433
    // Perform "qualified" name lookup into the declaration context we
434
    // computed, which is either the type of the base of a member access
435
    // expression or the declaration context associated with a prior
436
    // nested-name-specifier.
437
337k
    LookupQualifiedName(Found, LookupCtx);
438
439
    // FIXME: The C++ standard does not clearly specify what happens in the
440
    // case where the object type is dependent, and implementations vary. In
441
    // Clang, we treat a name after a . or -> as a template-name if lookup
442
    // finds a non-dependent member or member of the current instantiation that
443
    // is a type template, or finds no such members and lookup in the context
444
    // of the postfix-expression finds a type template. In the latter case, the
445
    // name is nonetheless dependent, and we may resolve it to a member of an
446
    // unknown specialization when we come to instantiate the template.
447
337k
    IsDependent |= Found.wasNotFoundInCurrentInstantiation();
448
337k
  }
449
450
3.99M
  if (SS.isEmpty() && 
(3.51M
ObjectType.isNull()3.51M
||
Found.empty()24.3k
)) {
451
    // C++ [basic.lookup.classref]p1:
452
    //   In a class member access expression (5.2.5), if the . or -> token is
453
    //   immediately followed by an identifier followed by a <, the
454
    //   identifier must be looked up to determine whether the < is the
455
    //   beginning of a template argument list (14.2) or a less-than operator.
456
    //   The identifier is first looked up in the class of the object
457
    //   expression. If the identifier is not found, it is then looked up in
458
    //   the context of the entire postfix-expression and shall name a class
459
    //   template.
460
3.49M
    if (S)
461
3.49M
      LookupName(Found, S);
462
463
3.49M
    if (!ObjectType.isNull()) {
464
      //  FIXME: We should filter out all non-type templates here, particularly
465
      //  variable templates and concepts. But the exclusion of alias templates
466
      //  and template template parameters is a wording defect.
467
6.98k
      AllowFunctionTemplatesInLookup = false;
468
6.98k
      ObjectTypeSearchedInScope = true;
469
6.98k
    }
470
471
3.49M
    IsDependent |= Found.wasNotFoundInCurrentInstantiation();
472
3.49M
  }
473
474
3.99M
  if (Found.isAmbiguous())
475
12
    return false;
476
477
3.99M
  if (ATK && 
SS.isEmpty()3.89M
&&
ObjectType.isNull()3.42M
&&
478
3.99M
      
!RequiredTemplate.hasTemplateKeyword()3.40M
) {
479
    // C++2a [temp.names]p2:
480
    //   A name is also considered to refer to a template if it is an
481
    //   unqualified-id followed by a < and name lookup finds either one or more
482
    //   functions or finds nothing.
483
    //
484
    // To keep our behavior consistent, we apply the "finds nothing" part in
485
    // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
486
    // successfully form a call to an undeclared template-id.
487
3.40M
    bool AllFunctions =
488
3.40M
        getLangOpts().CPlusPlus20 &&
489
3.40M
        
std::all_of(Found.begin(), Found.end(), [](NamedDecl *ND) 7.13k
{
490
7.05k
          return isa<FunctionDecl>(ND->getUnderlyingDecl());
491
7.05k
        });
492
3.40M
    if (AllFunctions || 
(3.40M
Found.empty()3.40M
&&
!IsDependent813
)) {
493
      // If lookup found any functions, or if this is a name that can only be
494
      // used for a function, then strongly assume this is a function
495
      // template-id.
496
928
      *ATK = (Found.empty() && 
Found.getLookupName().isIdentifier()915
)
497
928
                 ? 
AssumedTemplateKind::FoundNothing915
498
928
                 : 
AssumedTemplateKind::FoundFunctions13
;
499
928
      Found.clear();
500
928
      return false;
501
928
    }
502
3.40M
  }
503
504
3.99M
  if (Found.empty() && 
!IsDependent168k
&&
AllowTypoCorrection159
) {
505
    // If we did not find any names, and this is not a disambiguation, attempt
506
    // to correct any typos.
507
127
    DeclarationName Name = Found.getLookupName();
508
127
    Found.clear();
509
    // Simple filter callback that, for keywords, only accepts the C++ *_cast
510
127
    DefaultFilterCCC FilterCCC{};
511
127
    FilterCCC.WantTypeSpecifiers = false;
512
127
    FilterCCC.WantExpressionKeywords = false;
513
127
    FilterCCC.WantRemainingKeywords = false;
514
127
    FilterCCC.WantCXXNamedCasts = true;
515
127
    if (TypoCorrection Corrected =
516
127
            CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
517
127
                        &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
518
9
      if (auto *ND = Corrected.getFoundDecl())
519
9
        Found.addDecl(ND);
520
9
      FilterAcceptableTemplateNames(Found);
521
9
      if (Found.isAmbiguous()) {
522
0
        Found.clear();
523
9
      } else if (!Found.empty()) {
524
8
        Found.setLookupName(Corrected.getCorrection());
525
8
        if (LookupCtx) {
526
8
          std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
527
8
          bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
528
8
                                  
Name.getAsString() == CorrectedStr4
;
529
8
          diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
530
8
                                    << Name << LookupCtx << DroppedSpecifier
531
8
                                    << SS.getRange());
532
8
        } else {
533
0
          diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
534
0
        }
535
8
      }
536
9
    }
537
127
  }
538
539
3.99M
  NamedDecl *ExampleLookupResult =
540
3.99M
      Found.empty() ? 
nullptr168k
:
Found.getRepresentativeDecl()3.82M
;
541
3.99M
  FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
542
3.99M
  if (Found.empty()) {
543
951k
    if (IsDependent) {
544
168k
      MemberOfUnknownSpecialization = true;
545
168k
      return false;
546
168k
    }
547
548
    // If a 'template' keyword was used, a lookup that finds only non-template
549
    // names is an error.
550
782k
    if (ExampleLookupResult && 
RequiredTemplate782k
) {
551
40
      Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
552
40
          << Found.getLookupName() << SS.getRange()
553
40
          << RequiredTemplate.hasTemplateKeyword()
554
40
          << RequiredTemplate.getTemplateKeywordLoc();
555
40
      Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
556
40
           diag::note_template_kw_refers_to_non_template)
557
40
          << Found.getLookupName();
558
40
      return true;
559
40
    }
560
561
782k
    return false;
562
782k
  }
563
564
3.04M
  if (S && 
!ObjectType.isNull()2.99M
&&
!ObjectTypeSearchedInScope8.31k
&&
565
3.04M
      
!getLangOpts().CPlusPlus117.80k
) {
566
    // C++03 [basic.lookup.classref]p1:
567
    //   [...] If the lookup in the class of the object expression finds a
568
    //   template, the name is also looked up in the context of the entire
569
    //   postfix-expression and [...]
570
    //
571
    // Note: C++11 does not perform this second lookup.
572
86
    LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
573
86
                            LookupOrdinaryName);
574
86
    FoundOuter.setTemplateNameLookup(true);
575
86
    LookupName(FoundOuter, S);
576
    // FIXME: We silently accept an ambiguous lookup here, in violation of
577
    // [basic.lookup]/1.
578
86
    FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
579
580
86
    NamedDecl *OuterTemplate;
581
86
    if (FoundOuter.empty()) {
582
      //   - if the name is not found, the name found in the class of the
583
      //     object expression is used, otherwise
584
76
    } else 
if (10
FoundOuter.isAmbiguous()10
||
!FoundOuter.isSingleResult()10
||
585
10
               !(OuterTemplate =
586
8
                     getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
587
      //   - if the name is found in the context of the entire
588
      //     postfix-expression and does not name a class template, the name
589
      //     found in the class of the object expression is used, otherwise
590
2
      FoundOuter.clear();
591
8
    } else if (!Found.isSuppressingDiagnostics()) {
592
      //   - if the name found is a class template, it must refer to the same
593
      //     entity as the one found in the class of the object expression,
594
      //     otherwise the program is ill-formed.
595
8
      if (!Found.isSingleResult() ||
596
8
          getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
597
7
              OuterTemplate->getCanonicalDecl()) {
598
2
        Diag(Found.getNameLoc(),
599
2
             diag::ext_nested_name_member_ref_lookup_ambiguous)
600
2
          << Found.getLookupName()
601
2
          << ObjectType;
602
2
        Diag(Found.getRepresentativeDecl()->getLocation(),
603
2
             diag::note_ambig_member_ref_object_type)
604
2
          << ObjectType;
605
2
        Diag(FoundOuter.getFoundDecl()->getLocation(),
606
2
             diag::note_ambig_member_ref_scope);
607
608
        // Recover by taking the template that we found in the object
609
        // expression's type.
610
2
      }
611
8
    }
612
86
  }
613
614
3.04M
  return false;
615
3.99M
}
616
617
void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
618
                                              SourceLocation Less,
619
33
                                              SourceLocation Greater) {
620
33
  if (TemplateName.isInvalid())
621
0
    return;
622
623
33
  DeclarationNameInfo NameInfo;
624
33
  CXXScopeSpec SS;
625
33
  LookupNameKind LookupKind;
626
627
33
  DeclContext *LookupCtx = nullptr;
628
33
  NamedDecl *Found = nullptr;
629
33
  bool MissingTemplateKeyword = false;
630
631
  // Figure out what name we looked up.
632
33
  if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
633
13
    NameInfo = DRE->getNameInfo();
634
13
    SS.Adopt(DRE->getQualifierLoc());
635
13
    LookupKind = LookupOrdinaryName;
636
13
    Found = DRE->getFoundDecl();
637
20
  } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
638
2
    NameInfo = ME->getMemberNameInfo();
639
2
    SS.Adopt(ME->getQualifierLoc());
640
2
    LookupKind = LookupMemberName;
641
2
    LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
642
2
    Found = ME->getMemberDecl();
643
18
  } else if (auto *DSDRE =
644
18
                 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
645
3
    NameInfo = DSDRE->getNameInfo();
646
3
    SS.Adopt(DSDRE->getQualifierLoc());
647
3
    MissingTemplateKeyword = true;
648
15
  } else if (auto *DSME =
649
15
                 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
650
15
    NameInfo = DSME->getMemberNameInfo();
651
15
    SS.Adopt(DSME->getQualifierLoc());
652
15
    MissingTemplateKeyword = true;
653
15
  } else {
654
0
    llvm_unreachable("unexpected kind of potential template name");
655
0
  }
656
657
  // If this is a dependent-scope lookup, diagnose that the 'template' keyword
658
  // was missing.
659
33
  if (MissingTemplateKeyword) {
660
18
    Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
661
18
        << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
662
18
    return;
663
18
  }
664
665
  // Try to correct the name by looking for templates and C++ named casts.
666
15
  struct TemplateCandidateFilter : CorrectionCandidateCallback {
667
15
    Sema &S;
668
15
    TemplateCandidateFilter(Sema &S) : S(S) {
669
15
      WantTypeSpecifiers = false;
670
15
      WantExpressionKeywords = false;
671
15
      WantRemainingKeywords = false;
672
15
      WantCXXNamedCasts = true;
673
15
    };
674
43
    bool ValidateCandidate(const TypoCorrection &Candidate) override {
675
43
      if (auto *ND = Candidate.getCorrectionDecl())
676
43
        return S.getAsTemplateNameDecl(ND);
677
0
      return Candidate.isKeyword();
678
43
    }
679
680
15
    std::unique_ptr<CorrectionCandidateCallback> clone() override {
681
15
      return std::make_unique<TemplateCandidateFilter>(*this);
682
15
    }
683
15
  };
684
685
15
  DeclarationName Name = NameInfo.getName();
686
15
  TemplateCandidateFilter CCC(*this);
687
15
  if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
688
15
                                             CTK_ErrorRecovery, LookupCtx)) {
689
14
    auto *ND = Corrected.getFoundDecl();
690
14
    if (ND)
691
14
      ND = getAsTemplateNameDecl(ND);
692
14
    if (ND || 
Corrected.isKeyword()0
) {
693
14
      if (LookupCtx) {
694
1
        std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
695
1
        bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
696
1
                                
Name.getAsString() == CorrectedStr0
;
697
1
        diagnoseTypo(Corrected,
698
1
                     PDiag(diag::err_non_template_in_member_template_id_suggest)
699
1
                         << Name << LookupCtx << DroppedSpecifier
700
1
                         << SS.getRange(), false);
701
13
      } else {
702
13
        diagnoseTypo(Corrected,
703
13
                     PDiag(diag::err_non_template_in_template_id_suggest)
704
13
                         << Name, false);
705
13
      }
706
14
      if (Found)
707
14
        Diag(Found->getLocation(),
708
14
             diag::note_non_template_in_template_id_found);
709
14
      return;
710
14
    }
711
14
  }
712
713
1
  Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
714
1
    << Name << SourceRange(Less, Greater);
715
1
  if (Found)
716
1
    Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
717
1
}
718
719
/// ActOnDependentIdExpression - Handle a dependent id-expression that
720
/// was just parsed.  This is only possible with an explicit scope
721
/// specifier naming a dependent type.
722
ExprResult
723
Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
724
                                 SourceLocation TemplateKWLoc,
725
                                 const DeclarationNameInfo &NameInfo,
726
                                 bool isAddressOfOperand,
727
619k
                           const TemplateArgumentListInfo *TemplateArgs) {
728
619k
  DeclContext *DC = getFunctionLevelDeclContext();
729
730
  // C++11 [expr.prim.general]p12:
731
  //   An id-expression that denotes a non-static data member or non-static
732
  //   member function of a class can only be used:
733
  //   (...)
734
  //   - if that id-expression denotes a non-static data member and it
735
  //     appears in an unevaluated operand.
736
  //
737
  // If this might be the case, form a DependentScopeDeclRefExpr instead of a
738
  // CXXDependentScopeMemberExpr. The former can instantiate to either
739
  // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
740
  // always a MemberExpr.
741
619k
  bool MightBeCxx11UnevalField =
742
619k
      getLangOpts().CPlusPlus11 && 
isUnevaluatedContext()619k
;
743
744
  // Check if the nested name specifier is an enum type.
745
619k
  bool IsEnum = false;
746
619k
  if (NestedNameSpecifier *NNS = SS.getScopeRep())
747
619k
    IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
748
749
619k
  if (!MightBeCxx11UnevalField && 
!isAddressOfOperand616k
&&
!IsEnum616k
&&
750
619k
      
isa<CXXMethodDecl>(DC)616k
&&
cast<CXXMethodDecl>(DC)->isInstance()150k
) {
751
121k
    QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType();
752
753
    // Since the 'this' expression is synthesized, we don't need to
754
    // perform the double-lookup check.
755
121k
    NamedDecl *FirstQualifierInScope = nullptr;
756
757
121k
    return CXXDependentScopeMemberExpr::Create(
758
121k
        Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
759
121k
        /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
760
121k
        FirstQualifierInScope, NameInfo, TemplateArgs);
761
121k
  }
762
763
497k
  return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
764
619k
}
765
766
ExprResult
767
Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
768
                                SourceLocation TemplateKWLoc,
769
                                const DeclarationNameInfo &NameInfo,
770
895k
                                const TemplateArgumentListInfo *TemplateArgs) {
771
  // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc
772
895k
  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
773
895k
  if (!QualifierLoc)
774
1
    return ExprError();
775
776
895k
  return DependentScopeDeclRefExpr::Create(
777
895k
      Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs);
778
895k
}
779
780
781
/// Determine whether we would be unable to instantiate this template (because
782
/// it either has no definition, or is in the process of being instantiated).
783
bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
784
                                          NamedDecl *Instantiation,
785
                                          bool InstantiatedFromMember,
786
                                          const NamedDecl *Pattern,
787
                                          const NamedDecl *PatternDef,
788
                                          TemplateSpecializationKind TSK,
789
1.61M
                                          bool Complain /*= true*/) {
790
1.61M
  assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
791
1.61M
         isa<VarDecl>(Instantiation));
792
793
0
  bool IsEntityBeingDefined = false;
794
1.61M
  if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
795
755k
    IsEntityBeingDefined = TD->isBeingDefined();
796
797
1.61M
  if (PatternDef && 
!IsEntityBeingDefined1.57M
) {
798
1.57M
    NamedDecl *SuggestedDef = nullptr;
799
1.57M
    if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
800
1.57M
                              /*OnlyNeedComplete*/false)) {
801
      // If we're allowed to diagnose this and recover, do so.
802
23
      bool Recover = Complain && 
!isSFINAEContext()16
;
803
23
      if (Complain)
804
16
        diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
805
16
                              Sema::MissingImportKind::Definition, Recover);
806
23
      return !Recover;
807
23
    }
808
1.57M
    return false;
809
1.57M
  }
810
811
46.7k
  if (!Complain || 
(632
PatternDef632
&&
PatternDef->isInvalidDecl()3
))
812
46.1k
    return true;
813
814
632
  llvm::Optional<unsigned> Note;
815
632
  QualType InstantiationTy;
816
632
  if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
817
588
    InstantiationTy = Context.getTypeDeclType(TD);
818
632
  if (PatternDef) {
819
3
    Diag(PointOfInstantiation,
820
3
         diag::err_template_instantiate_within_definition)
821
3
      << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
822
3
      << InstantiationTy;
823
    // Not much point in noting the template declaration here, since
824
    // we're lexically inside it.
825
3
    Instantiation->setInvalidDecl();
826
629
  } else if (InstantiatedFromMember) {
827
14
    if (isa<FunctionDecl>(Instantiation)) {
828
2
      Diag(PointOfInstantiation,
829
2
           diag::err_explicit_instantiation_undefined_member)
830
2
        << /*member function*/ 1 << Instantiation->getDeclName()
831
2
        << Instantiation->getDeclContext();
832
2
      Note = diag::note_explicit_instantiation_here;
833
12
    } else {
834
12
      assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
835
0
      Diag(PointOfInstantiation,
836
12
           diag::err_implicit_instantiate_member_undefined)
837
12
        << InstantiationTy;
838
12
      Note = diag::note_member_declared_at;
839
12
    }
840
615
  } else {
841
615
    if (isa<FunctionDecl>(Instantiation)) {
842
8
      Diag(PointOfInstantiation,
843
8
           diag::err_explicit_instantiation_undefined_func_template)
844
8
        << Pattern;
845
8
      Note = diag::note_explicit_instantiation_here;
846
607
    } else if (isa<TagDecl>(Instantiation)) {
847
573
      Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
848
573
        << (TSK != TSK_ImplicitInstantiation)
849
573
        << InstantiationTy;
850
573
      Note = diag::note_template_decl_here;
851
573
    } else {
852
34
      assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
853
34
      if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
854
30
        Diag(PointOfInstantiation,
855
30
             diag::err_explicit_instantiation_undefined_var_template)
856
30
          << Instantiation;
857
30
        Instantiation->setInvalidDecl();
858
30
      } else
859
4
        Diag(PointOfInstantiation,
860
4
             diag::err_explicit_instantiation_undefined_member)
861
4
          << /*static data member*/ 2 << Instantiation->getDeclName()
862
4
          << Instantiation->getDeclContext();
863
34
      Note = diag::note_explicit_instantiation_here;
864
34
    }
865
615
  }
866
632
  if (Note) // Diagnostics were emitted.
867
629
    Diag(Pattern->getLocation(), Note.getValue());
868
869
  // In general, Instantiation isn't marked invalid to get more than one
870
  // error for multiple undefined instantiations. But the code that does
871
  // explicit declaration -> explicit definition conversion can't handle
872
  // invalid declarations, so mark as invalid in that case.
873
632
  if (TSK == TSK_ExplicitInstantiationDeclaration)
874
3
    Instantiation->setInvalidDecl();
875
632
  return true;
876
46.7k
}
877
878
/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
879
/// that the template parameter 'PrevDecl' is being shadowed by a new
880
/// declaration at location Loc. Returns true to indicate that this is
881
/// an error, and false otherwise.
882
91
void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
883
91
  assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
884
885
  // C++ [temp.local]p4:
886
  //   A template-parameter shall not be redeclared within its
887
  //   scope (including nested scopes).
888
  //
889
  // Make this a warning when MSVC compatibility is requested.
890
91
  unsigned DiagId = getLangOpts().MSVCCompat ? 
diag::ext_template_param_shadow9
891
91
                                             : 
diag::err_template_param_shadow82
;
892
91
  Diag(Loc, DiagId) << cast<NamedDecl>(PrevDecl)->getDeclName();
893
91
  Diag(PrevDecl->getLocation(), diag::note_template_param_here);
894
91
}
895
896
/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
897
/// the parameter D to reference the templated declaration and return a pointer
898
/// to the template declaration. Otherwise, do nothing to D and return null.
899
6.18M
TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
900
6.18M
  if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
901
1.32M
    D = Temp->getTemplatedDecl();
902
1.32M
    return Temp;
903
1.32M
  }
904
4.85M
  return nullptr;
905
6.18M
}
906
907
ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
908
24
                                             SourceLocation EllipsisLoc) const {
909
24
  assert(Kind == Template &&
910
24
         "Only template template arguments can be pack expansions here");
911
0
  assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
912
24
         "Template template argument pack expansion without packs");
913
0
  ParsedTemplateArgument Result(*this);
914
24
  Result.EllipsisLoc = EllipsisLoc;
915
24
  return Result;
916
24
}
917
918
static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
919
4.40M
                                            const ParsedTemplateArgument &Arg) {
920
921
4.40M
  switch (Arg.getKind()) {
922
3.69M
  case ParsedTemplateArgument::Type: {
923
3.69M
    TypeSourceInfo *DI;
924
3.69M
    QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
925
3.69M
    if (!DI)
926
0
      DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
927
3.69M
    return TemplateArgumentLoc(TemplateArgument(T), DI);
928
0
  }
929
930
693k
  case ParsedTemplateArgument::NonType: {
931
693k
    Expr *E = static_cast<Expr *>(Arg.getAsExpr());
932
693k
    return TemplateArgumentLoc(TemplateArgument(E), E);
933
0
  }
934
935
18.5k
  case ParsedTemplateArgument::Template: {
936
18.5k
    TemplateName Template = Arg.getAsTemplate().get();
937
18.5k
    TemplateArgument TArg;
938
18.5k
    if (Arg.getEllipsisLoc().isValid())
939
24
      TArg = TemplateArgument(Template, Optional<unsigned int>());
940
18.5k
    else
941
18.5k
      TArg = Template;
942
18.5k
    return TemplateArgumentLoc(
943
18.5k
        SemaRef.Context, TArg,
944
18.5k
        Arg.getScopeSpec().getWithLocInContext(SemaRef.Context),
945
18.5k
        Arg.getLocation(), Arg.getEllipsisLoc());
946
0
  }
947
4.40M
  }
948
949
0
  llvm_unreachable("Unhandled parsed template argument");
950
0
}
951
952
/// Translates template arguments as provided by the parser
953
/// into template arguments used by semantic analysis.
954
void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
955
2.78M
                                      TemplateArgumentListInfo &TemplateArgs) {
956
7.18M
 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; 
++I4.39M
)
957
4.39M
   TemplateArgs.addArgument(translateTemplateArgument(*this,
958
4.39M
                                                      TemplateArgsIn[I]));
959
2.78M
}
960
961
static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
962
                                                 SourceLocation Loc,
963
2.07M
                                                 IdentifierInfo *Name) {
964
2.07M
  NamedDecl *PrevDecl = SemaRef.LookupSingleName(
965
2.07M
      S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
966
2.07M
  if (PrevDecl && 
PrevDecl->isTemplateParameter()7.97k
)
967
23
    SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
968
2.07M
}
969
970
/// Convert a parsed type into a parsed template argument. This is mostly
971
/// trivial, except that we may have parsed a C++17 deduced class template
972
/// specialization type, in which case we should form a template template
973
/// argument instead of a type template argument.
974
3.69M
ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
975
3.69M
  TypeSourceInfo *TInfo;
976
3.69M
  QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
977
3.69M
  if (T.isNull())
978
188
    return ParsedTemplateArgument();
979
3.69M
  assert(TInfo && "template argument with no location");
980
981
  // If we might have formed a deduced template specialization type, convert
982
  // it to a template template argument.
983
3.69M
  if (getLangOpts().CPlusPlus17) {
984
104k
    TypeLoc TL = TInfo->getTypeLoc();
985
104k
    SourceLocation EllipsisLoc;
986
104k
    if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
987
0
      EllipsisLoc = PET.getEllipsisLoc();
988
0
      TL = PET.getPatternLoc();
989
0
    }
990
991
104k
    CXXScopeSpec SS;
992
104k
    if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
993
405
      SS.Adopt(ET.getQualifierLoc());
994
405
      TL = ET.getNamedTypeLoc();
995
405
    }
996
997
104k
    if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
998
414
      TemplateName Name = DTST.getTypePtr()->getTemplateName();
999
414
      if (SS.isSet())
1000
19
        Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
1001
19
                                                /*HasTemplateKeyword*/ false,
1002
19
                                                Name.getAsTemplateDecl());
1003
414
      ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
1004
414
                                    DTST.getTemplateNameLoc());
1005
414
      if (EllipsisLoc.isValid())
1006
0
        Result = Result.getTemplatePackExpansion(EllipsisLoc);
1007
414
      return Result;
1008
414
    }
1009
104k
  }
1010
1011
  // This is a normal type template argument. Note, if the type template
1012
  // argument is an injected-class-name for a template, it has a dual nature
1013
  // and can be used as either a type or a template. We handle that in
1014
  // convertTypeTemplateArgumentToTemplate.
1015
3.69M
  return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1016
3.69M
                                ParsedType.get().getAsOpaquePtr(),
1017
3.69M
                                TInfo->getTypeLoc().getBeginLoc());
1018
3.69M
}
1019
1020
/// ActOnTypeParameter - Called when a C++ template type parameter
1021
/// (e.g., "typename T") has been parsed. Typename specifies whether
1022
/// the keyword "typename" was used to declare the type parameter
1023
/// (otherwise, "class" was used), and KeyLoc is the location of the
1024
/// "class" or "typename" keyword. ParamName is the name of the
1025
/// parameter (NULL indicates an unnamed template parameter) and
1026
/// ParamNameLoc is the location of the parameter name (if any).
1027
/// If the type parameter has a default argument, it will be added
1028
/// later via ActOnTypeParameterDefault.
1029
NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
1030
                                    SourceLocation EllipsisLoc,
1031
                                    SourceLocation KeyLoc,
1032
                                    IdentifierInfo *ParamName,
1033
                                    SourceLocation ParamNameLoc,
1034
                                    unsigned Depth, unsigned Position,
1035
                                    SourceLocation EqualLoc,
1036
                                    ParsedType DefaultArg,
1037
1.99M
                                    bool HasTypeConstraint) {
1038
1.99M
  assert(S->isTemplateParamScope() &&
1039
1.99M
         "Template type parameter not in template parameter scope!");
1040
1041
0
  bool IsParameterPack = EllipsisLoc.isValid();
1042
1.99M
  TemplateTypeParmDecl *Param
1043
1.99M
    = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1044
1.99M
                                   KeyLoc, ParamNameLoc, Depth, Position,
1045
1.99M
                                   ParamName, Typename, IsParameterPack,
1046
1.99M
                                   HasTypeConstraint);
1047
1.99M
  Param->setAccess(AS_public);
1048
1049
1.99M
  if (Param->isParameterPack())
1050
145k
    if (auto *LSI = getEnclosingLambda())
1051
13
      LSI->LocalPacks.push_back(Param);
1052
1053
1.99M
  if (ParamName) {
1054
1.89M
    maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1055
1056
    // Add the template parameter into the current scope.
1057
1.89M
    S->AddDecl(Param);
1058
1.89M
    IdResolver.AddDecl(Param);
1059
1.89M
  }
1060
1061
  // C++0x [temp.param]p9:
1062
  //   A default template-argument may be specified for any kind of
1063
  //   template-parameter that is not a template parameter pack.
1064
1.99M
  if (DefaultArg && 
IsParameterPack98.8k
) {
1065
1
    Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1066
1
    DefaultArg = nullptr;
1067
1
  }
1068
1069
  // Handle the default argument, if provided.
1070
1.99M
  if (DefaultArg) {
1071
98.8k
    TypeSourceInfo *DefaultTInfo;
1072
98.8k
    GetTypeFromParser(DefaultArg, &DefaultTInfo);
1073
1074
98.8k
    assert(DefaultTInfo && "expected source information for type");
1075
1076
    // Check for unexpanded parameter packs.
1077
98.8k
    if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1078
98.8k
                                        UPPC_DefaultArgument))
1079
2
      return Param;
1080
1081
    // Check the template argument itself.
1082
98.8k
    if (CheckTemplateArgument(DefaultTInfo)) {
1083
0
      Param->setInvalidDecl();
1084
0
      return Param;
1085
0
    }
1086
1087
98.8k
    Param->setDefaultArgument(DefaultTInfo);
1088
98.8k
  }
1089
1090
1.99M
  return Param;
1091
1.99M
}
1092
1093
/// Convert the parser's template argument list representation into our form.
1094
static TemplateArgumentListInfo
1095
223k
makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
1096
223k
  TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1097
223k
                                        TemplateId.RAngleLoc);
1098
223k
  ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1099
223k
                                     TemplateId.NumArgs);
1100
223k
  S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1101
223k
  return TemplateArgs;
1102
223k
}
1103
1104
bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS,
1105
                               TemplateIdAnnotation *TypeConstr,
1106
                               TemplateTypeParmDecl *ConstrainedParameter,
1107
96
                               SourceLocation EllipsisLoc) {
1108
96
  return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1109
96
                             false);
1110
96
}
1111
1112
bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS,
1113
                               TemplateIdAnnotation *TypeConstr,
1114
                               TemplateTypeParmDecl *ConstrainedParameter,
1115
                               SourceLocation EllipsisLoc,
1116
141
                               bool AllowUnexpandedPack) {
1117
141
  TemplateName TN = TypeConstr->Template.get();
1118
141
  ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1119
1120
  // C++2a [temp.param]p4:
1121
  //     [...] The concept designated by a type-constraint shall be a type
1122
  //     concept ([temp.concept]).
1123
141
  if (!CD->isTypeConcept()) {
1124
5
    Diag(TypeConstr->TemplateNameLoc,
1125
5
         diag::err_type_constraint_non_type_concept);
1126
5
    return true;
1127
5
  }
1128
1129
136
  bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1130
1131
136
  if (!WereArgsSpecified &&
1132
136
      
CD->getTemplateParameters()->getMinRequiredArguments() > 180
) {
1133
4
    Diag(TypeConstr->TemplateNameLoc,
1134
4
         diag::err_type_constraint_missing_arguments) << CD;
1135
4
    return true;
1136
4
  }
1137
1138
132
  DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1139
132
                                  TypeConstr->TemplateNameLoc);
1140
1141
132
  TemplateArgumentListInfo TemplateArgs;
1142
132
  if (TypeConstr->LAngleLoc.isValid()) {
1143
56
    TemplateArgs =
1144
56
        makeTemplateArgumentListInfo(*this, *TypeConstr);
1145
1146
56
    if (EllipsisLoc.isInvalid() && 
!AllowUnexpandedPack49
) {
1147
27
      for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1148
27
        if (DiagnoseUnexpandedParameterPack(Arg, UPPC_TypeConstraint))
1149
2
          return true;
1150
27
      }
1151
23
    }
1152
56
  }
1153
130
  return AttachTypeConstraint(
1154
130
      SS.isSet() ? 
SS.getWithLocInContext(Context)7
:
NestedNameSpecifierLoc()123
,
1155
130
      ConceptName, CD,
1156
130
      TypeConstr->LAngleLoc.isValid() ? 
&TemplateArgs54
:
nullptr76
,
1157
130
      ConstrainedParameter, EllipsisLoc);
1158
132
}
1159
1160
template<typename ArgumentLocAppender>
1161
static ExprResult formImmediatelyDeclaredConstraint(
1162
    Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo,
1163
    ConceptDecl *NamedConcept, SourceLocation LAngleLoc,
1164
    SourceLocation RAngleLoc, QualType ConstrainedType,
1165
    SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1166
250
    SourceLocation EllipsisLoc) {
1167
1168
250
  TemplateArgumentListInfo ConstraintArgs;
1169
250
  ConstraintArgs.addArgument(
1170
250
    S.getTrivialTemplateArgumentLoc(TemplateArgument(ConstrainedType),
1171
250
                                    /*NTTPType=*/QualType(), ParamNameLoc));
1172
1173
250
  ConstraintArgs.setRAngleLoc(RAngleLoc);
1174
250
  ConstraintArgs.setLAngleLoc(LAngleLoc);
1175
250
  Appender(ConstraintArgs);
1176
1177
  // C++2a [temp.param]p4:
1178
  //     [...] This constraint-expression E is called the immediately-declared
1179
  //     constraint of T. [...]
1180
250
  CXXScopeSpec SS;
1181
250
  SS.Adopt(NS);
1182
250
  ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1183
250
      SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1184
250
      /*FoundDecl=*/NamedConcept, NamedConcept, &ConstraintArgs);
1185
250
  if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1186
221
    return ImmediatelyDeclaredConstraint;
1187
1188
  // C++2a [temp.param]p4:
1189
  //     [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1190
  //
1191
  // We have the following case:
1192
  //
1193
  // template<typename T> concept C1 = true;
1194
  // template<C1... T> struct s1;
1195
  //
1196
  // The constraint: (C1<T> && ...)
1197
  //
1198
  // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1199
  // any unqualified lookups for 'operator&&' here.
1200
29
  return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1201
29
                            /*LParenLoc=*/SourceLocation(),
1202
29
                            ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1203
29
                            EllipsisLoc, /*RHS=*/nullptr,
1204
29
                            /*RParenLoc=*/SourceLocation(),
1205
29
                            /*NumExpansions=*/None);
1206
250
}
SemaTemplate.cpp:clang::ActionResult<clang::Expr*, true> formImmediatelyDeclaredConstraint<clang::Sema::AttachTypeConstraint(clang::NestedNameSpecifierLoc, clang::DeclarationNameInfo, clang::ConceptDecl*, clang::TemplateArgumentListInfo const*, clang::TemplateTypeParmDecl*, clang::SourceLocation)::$_2>(clang::Sema&, clang::NestedNameSpecifierLoc, clang::DeclarationNameInfo, clang::ConceptDecl*, clang::SourceLocation, clang::SourceLocation, clang::QualType, clang::SourceLocation, clang::Sema::AttachTypeConstraint(clang::NestedNameSpecifierLoc, clang::DeclarationNameInfo, clang::ConceptDecl*, clang::TemplateArgumentListInfo const*, clang::TemplateTypeParmDecl*, clang::SourceLocation)::$_2, clang::SourceLocation)
Line
Count
Source
1166
248
    SourceLocation EllipsisLoc) {
1167
1168
248
  TemplateArgumentListInfo ConstraintArgs;
1169
248
  ConstraintArgs.addArgument(
1170
248
    S.getTrivialTemplateArgumentLoc(TemplateArgument(ConstrainedType),
1171
248
                                    /*NTTPType=*/QualType(), ParamNameLoc));
1172
1173
248
  ConstraintArgs.setRAngleLoc(RAngleLoc);
1174
248
  ConstraintArgs.setLAngleLoc(LAngleLoc);
1175
248
  Appender(ConstraintArgs);
1176
1177
  // C++2a [temp.param]p4:
1178
  //     [...] This constraint-expression E is called the immediately-declared
1179
  //     constraint of T. [...]
1180
248
  CXXScopeSpec SS;
1181
248
  SS.Adopt(NS);
1182
248
  ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1183
248
      SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1184
248
      /*FoundDecl=*/NamedConcept, NamedConcept, &ConstraintArgs);
1185
248
  if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1186
220
    return ImmediatelyDeclaredConstraint;
1187
1188
  // C++2a [temp.param]p4:
1189
  //     [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1190
  //
1191
  // We have the following case:
1192
  //
1193
  // template<typename T> concept C1 = true;
1194
  // template<C1... T> struct s1;
1195
  //
1196
  // The constraint: (C1<T> && ...)
1197
  //
1198
  // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1199
  // any unqualified lookups for 'operator&&' here.
1200
28
  return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1201
28
                            /*LParenLoc=*/SourceLocation(),
1202
28
                            ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1203
28
                            EllipsisLoc, /*RHS=*/nullptr,
1204
28
                            /*RParenLoc=*/SourceLocation(),
1205
28
                            /*NumExpansions=*/None);
1206
248
}
SemaTemplate.cpp:clang::ActionResult<clang::Expr*, true> formImmediatelyDeclaredConstraint<clang::Sema::AttachTypeConstraint(clang::AutoTypeLoc, clang::NonTypeTemplateParmDecl*, clang::SourceLocation)::$_3>(clang::Sema&, clang::NestedNameSpecifierLoc, clang::DeclarationNameInfo, clang::ConceptDecl*, clang::SourceLocation, clang::SourceLocation, clang::QualType, clang::SourceLocation, clang::Sema::AttachTypeConstraint(clang::AutoTypeLoc, clang::NonTypeTemplateParmDecl*, clang::SourceLocation)::$_3, clang::SourceLocation)
Line
Count
Source
1166
2
    SourceLocation EllipsisLoc) {
1167
1168
2
  TemplateArgumentListInfo ConstraintArgs;
1169
2
  ConstraintArgs.addArgument(
1170
2
    S.getTrivialTemplateArgumentLoc(TemplateArgument(ConstrainedType),
1171
2
                                    /*NTTPType=*/QualType(), ParamNameLoc));
1172
1173
2
  ConstraintArgs.setRAngleLoc(RAngleLoc);
1174
2
  ConstraintArgs.setLAngleLoc(LAngleLoc);
1175
2
  Appender(ConstraintArgs);
1176
1177
  // C++2a [temp.param]p4:
1178
  //     [...] This constraint-expression E is called the immediately-declared
1179
  //     constraint of T. [...]
1180
2
  CXXScopeSpec SS;
1181
2
  SS.Adopt(NS);
1182
2
  ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1183
2
      SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1184
2
      /*FoundDecl=*/NamedConcept, NamedConcept, &ConstraintArgs);
1185
2
  if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1186
1
    return ImmediatelyDeclaredConstraint;
1187
1188
  // C++2a [temp.param]p4:
1189
  //     [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1190
  //
1191
  // We have the following case:
1192
  //
1193
  // template<typename T> concept C1 = true;
1194
  // template<C1... T> struct s1;
1195
  //
1196
  // The constraint: (C1<T> && ...)
1197
  //
1198
  // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1199
  // any unqualified lookups for 'operator&&' here.
1200
1
  return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1201
1
                            /*LParenLoc=*/SourceLocation(),
1202
1
                            ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1203
1
                            EllipsisLoc, /*RHS=*/nullptr,
1204
1
                            /*RParenLoc=*/SourceLocation(),
1205
1
                            /*NumExpansions=*/None);
1206
2
}
1207
1208
/// Attach a type-constraint to a template parameter.
1209
/// \returns true if an error occurred. This can happen if the
1210
/// immediately-declared constraint could not be formed (e.g. incorrect number
1211
/// of arguments for the named concept).
1212
bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS,
1213
                                DeclarationNameInfo NameInfo,
1214
                                ConceptDecl *NamedConcept,
1215
                                const TemplateArgumentListInfo *TemplateArgs,
1216
                                TemplateTypeParmDecl *ConstrainedParameter,
1217
248
                                SourceLocation EllipsisLoc) {
1218
  // C++2a [temp.param]p4:
1219
  //     [...] If Q is of the form C<A1, ..., An>, then let E' be
1220
  //     C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1221
248
  const ASTTemplateArgumentListInfo *ArgsAsWritten =
1222
248
    TemplateArgs ? ASTTemplateArgumentListInfo::Create(Context,
1223
127
                                                       *TemplateArgs) : 
nullptr121
;
1224
1225
248
  QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1226
1227
248
  ExprResult ImmediatelyDeclaredConstraint =
1228
248
      formImmediatelyDeclaredConstraint(
1229
248
          *this, NS, NameInfo, NamedConcept,
1230
248
          TemplateArgs ? 
TemplateArgs->getLAngleLoc()127
:
SourceLocation()121
,
1231
248
          TemplateArgs ? 
TemplateArgs->getRAngleLoc()127
:
SourceLocation()121
,
1232
248
          ParamAsArgument, ConstrainedParameter->getLocation(),
1233
248
          [&] (TemplateArgumentListInfo &ConstraintArgs) {
1234
248
            if (TemplateArgs)
1235
127
              for (const auto &ArgLoc : TemplateArgs->arguments())
1236
129
                ConstraintArgs.addArgument(ArgLoc);
1237
248
          }, EllipsisLoc);
1238
248
  if (ImmediatelyDeclaredConstraint.isInvalid())
1239
0
    return true;
1240
1241
248
  ConstrainedParameter->setTypeConstraint(NS, NameInfo,
1242
248
                                          /*FoundDecl=*/NamedConcept,
1243
248
                                          NamedConcept, ArgsAsWritten,
1244
248
                                          ImmediatelyDeclaredConstraint.get());
1245
248
  return false;
1246
248
}
1247
1248
bool Sema::AttachTypeConstraint(AutoTypeLoc TL, NonTypeTemplateParmDecl *NTTP,
1249
3
                                SourceLocation EllipsisLoc) {
1250
3
  if (NTTP->getType() != TL.getType() ||
1251
3
      
TL.getAutoKeyword() != AutoTypeKeyword::Auto2
) {
1252
1
    Diag(NTTP->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1253
1
         diag::err_unsupported_placeholder_constraint)
1254
1
       << NTTP->getTypeSourceInfo()->getTypeLoc().getSourceRange();
1255
1
    return true;
1256
1
  }
1257
  // FIXME: Concepts: This should be the type of the placeholder, but this is
1258
  // unclear in the wording right now.
1259
2
  DeclRefExpr *Ref =
1260
2
      BuildDeclRefExpr(NTTP, NTTP->getType(), VK_PRValue, NTTP->getLocation());
1261
2
  if (!Ref)
1262
0
    return true;
1263
2
  ExprResult ImmediatelyDeclaredConstraint =
1264
2
      formImmediatelyDeclaredConstraint(
1265
2
          *this, TL.getNestedNameSpecifierLoc(), TL.getConceptNameInfo(),
1266
2
          TL.getNamedConcept(), TL.getLAngleLoc(), TL.getRAngleLoc(),
1267
2
          BuildDecltypeType(Ref, NTTP->getLocation()), NTTP->getLocation(),
1268
2
          [&] (TemplateArgumentListInfo &ConstraintArgs) {
1269
6
            for (unsigned I = 0, C = TL.getNumArgs(); I != C; 
++I4
)
1270
4
              ConstraintArgs.addArgument(TL.getArgLoc(I));
1271
2
          }, EllipsisLoc);
1272
2
  if (ImmediatelyDeclaredConstraint.isInvalid() ||
1273
2
     !ImmediatelyDeclaredConstraint.isUsable())
1274
0
    return true;
1275
1276
2
  NTTP->setPlaceholderTypeConstraint(ImmediatelyDeclaredConstraint.get());
1277
2
  return false;
1278
2
}
1279
1280
/// Check that the type of a non-type template parameter is
1281
/// well-formed.
1282
///
1283
/// \returns the (possibly-promoted) parameter type if valid;
1284
/// otherwise, produces a diagnostic and returns a NULL type.
1285
QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1286
331k
                                                 SourceLocation Loc) {
1287
331k
  if (TSI->getType()->isUndeducedType()) {
1288
    // C++17 [temp.dep.expr]p3:
1289
    //   An id-expression is type-dependent if it contains
1290
    //    - an identifier associated by name lookup with a non-type
1291
    //      template-parameter declared with a type that contains a
1292
    //      placeholder type (7.1.7.4),
1293
216
    TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
1294
216
  }
1295
1296
331k
  return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1297
331k
}
1298
1299
/// Require the given type to be a structural type, and diagnose if it is not.
1300
///
1301
/// \return \c true if an error was produced.
1302
292
bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) {
1303
292
  if (T->isDependentType())
1304
0
    return false;
1305
1306
292
  if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1307
7
    return true;
1308
1309
285
  if (T->isStructuralType())
1310
236
    return false;
1311
1312
  // Structural types are required to be object types or lvalue references.
1313
49
  if (T->isRValueReferenceType()) {
1314
3
    Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1315
3
    return true;
1316
3
  }
1317
1318
  // Don't mention structural types in our diagnostic prior to C++20. Also,
1319
  // there's not much more we can say about non-scalar non-class types --
1320
  // because we can't see functions or arrays here, those can only be language
1321
  // extensions.
1322
46
  if (!getLangOpts().CPlusPlus20 ||
1323
46
      
(15
!T->isScalarType()15
&&
!T->isRecordType()15
)) {
1324
33
    Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1325
33
    return true;
1326
33
  }
1327
1328
  // Structural types are required to be literal types.
1329
13
  if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1330
0
    return true;
1331
1332
13
  Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1333
1334
  // Drill down into the reason why the class is non-structural.
1335
18
  while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1336
    // All members are required to be public and non-mutable, and can't be of
1337
    // rvalue reference type. Check these conditions first to prefer a "local"
1338
    // reason over a more distant one.
1339
16
    for (const FieldDecl *FD : RD->fields()) {
1340
12
      if (FD->getAccess() != AS_public) {
1341
3
        Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1342
3
        return true;
1343
3
      }
1344
9
      if (FD->isMutable()) {
1345
1
        Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1346
1
        return true;
1347
1
      }
1348
8
      if (FD->getType()->isRValueReferenceType()) {
1349
4
        Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1350
4
            << T;
1351
4
        return true;
1352
4
      }
1353
8
    }
1354
1355
    // All bases are required to be public.
1356
8
    for (const auto &BaseSpec : RD->bases()) {
1357
4
      if (BaseSpec.getAccessSpecifier() != AS_public) {
1358
3
        Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1359
3
            << T << 1;
1360
3
        return true;
1361
3
      }
1362
4
    }
1363
1364
    // All subobjects are required to be of structural types.
1365
5
    SourceLocation SubLoc;
1366
5
    QualType SubType;
1367
5
    int Kind = -1;
1368
1369
5
    for (const FieldDecl *FD : RD->fields()) {
1370
4
      QualType T = Context.getBaseElementType(FD->getType());
1371
4
      if (!T->isStructuralType()) {
1372
4
        SubLoc = FD->getLocation();
1373
4
        SubType = T;
1374
4
        Kind = 0;
1375
4
        break;
1376
4
      }
1377
4
    }
1378
1379
5
    if (Kind == -1) {
1380
1
      for (const auto &BaseSpec : RD->bases()) {
1381
1
        QualType T = BaseSpec.getType();
1382
1
        if (!T->isStructuralType()) {
1383
1
          SubLoc = BaseSpec.getBaseTypeLoc();
1384
1
          SubType = T;
1385
1
          Kind = 1;
1386
1
          break;
1387
1
        }
1388
1
      }
1389
1
    }
1390
1391
5
    assert(Kind != -1 && "couldn't find reason why type is not structural");
1392
0
    Diag(SubLoc, diag::note_not_structural_subobject)
1393
5
        << T << Kind << SubType;
1394
5
    T = SubType;
1395
5
    RD = T->getAsCXXRecordDecl();
1396
5
  }
1397
1398
2
  return true;
1399
13
}
1400
1401
QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1402
778k
                                                 SourceLocation Loc) {
1403
  // We don't allow variably-modified types as the type of non-type template
1404
  // parameters.
1405
778k
  if (T->isVariablyModifiedType()) {
1406
1
    Diag(Loc, diag::err_variably_modified_nontype_template_param)
1407
1
      << T;
1408
1
    return QualType();
1409
1
  }
1410
1411
  // C++ [temp.param]p4:
1412
  //
1413
  // A non-type template-parameter shall have one of the following
1414
  // (optionally cv-qualified) types:
1415
  //
1416
  //       -- integral or enumeration type,
1417
778k
  if (T->isIntegralOrEnumerationType() ||
1418
      //   -- pointer to object or pointer to function,
1419
778k
      
T->isPointerType()145k
||
1420
      //   -- lvalue reference to object or lvalue reference to function,
1421
778k
      
T->isLValueReferenceType()125k
||
1422
      //   -- pointer to member,
1423
778k
      
T->isMemberPointerType()123k
||
1424
      //   -- std::nullptr_t, or
1425
778k
      
T->isNullPtrType()122k
||
1426
      //   -- a type that contains a placeholder type.
1427
778k
      
T->isUndeducedType()122k
) {
1428
    // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1429
    // are ignored when determining its type.
1430
657k
    return T.getUnqualifiedType();
1431
657k
  }
1432
1433
  // C++ [temp.param]p8:
1434
  //
1435
  //   A non-type template-parameter of type "array of T" or
1436
  //   "function returning T" is adjusted to be of type "pointer to
1437
  //   T" or "pointer to function returning T", respectively.
1438
121k
  if (T->isArrayType() || 
T->isFunctionType()121k
)
1439
99
    return Context.getDecayedType(T);
1440
1441
  // If T is a dependent type, we can't do the check now, so we
1442
  // assume that it is well-formed. Note that stripping off the
1443
  // qualifiers here is not really correct if T turns out to be
1444
  // an array type, but we'll recompute the type everywhere it's
1445
  // used during instantiation, so that should be OK. (Using the
1446
  // qualified type is equally wrong.)
1447
121k
  if (T->isDependentType())
1448
121k
    return T.getUnqualifiedType();
1449
1450
  // C++20 [temp.param]p6:
1451
  //   -- a structural type
1452
292
  if (RequireStructuralType(T, Loc))
1453
56
    return QualType();
1454
1455
236
  if (!getLangOpts().CPlusPlus20) {
1456
    // FIXME: Consider allowing structural types as an extension in C++17. (In
1457
    // earlier language modes, the template argument evaluation rules are too
1458
    // inflexible.)
1459
30
    Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1460
30
    return QualType();
1461
30
  }
1462
1463
206
  Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1464
206
  return T.getUnqualifiedType();
1465
236
}
1466
1467
NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1468
                                          unsigned Depth,
1469
                                          unsigned Position,
1470
                                          SourceLocation EqualLoc,
1471
214k
                                          Expr *Default) {
1472
214k
  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
1473
1474
  // Check that we have valid decl-specifiers specified.
1475
214k
  auto CheckValidDeclSpecifiers = [this, &D] {
1476
    // C++ [temp.param]
1477
    // p1
1478
    //   template-parameter:
1479
    //     ...
1480
    //     parameter-declaration
1481
    // p2
1482
    //   ... A storage class shall not be specified in a template-parameter
1483
    //   declaration.
1484
    // [dcl.typedef]p1:
1485
    //   The typedef specifier [...] shall not be used in the decl-specifier-seq
1486
    //   of a parameter-declaration
1487
214k
    const DeclSpec &DS = D.getDeclSpec();
1488
214k
    auto EmitDiag = [this](SourceLocation Loc) {
1489
35
      Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1490
35
          << FixItHint::CreateRemoval(Loc);
1491
35
    };
1492
214k
    if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1493
18
      EmitDiag(DS.getStorageClassSpecLoc());
1494
1495
214k
    if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1496
1
      EmitDiag(DS.getThreadStorageClassSpecLoc());
1497
1498
    // [dcl.inline]p1:
1499
    //   The inline specifier can be applied only to the declaration or
1500
    //   definition of a variable or function.
1501
1502
214k
    if (DS.isInlineSpecified())
1503
6
      EmitDiag(DS.getInlineSpecLoc());
1504
1505
    // [dcl.constexpr]p1:
1506
    //   The constexpr specifier shall be applied only to the definition of a
1507
    //   variable or variable template or the declaration of a function or
1508
    //   function template.
1509
1510
214k
    if (DS.hasConstexprSpecifier())
1511
1
      EmitDiag(DS.getConstexprSpecLoc());
1512
1513
    // [dcl.fct.spec]p1:
1514
    //   Function-specifiers can be used only in function declarations.
1515
1516
214k
    if (DS.isVirtualSpecified())
1517
3
      EmitDiag(DS.getVirtualSpecLoc());
1518
1519
214k
    if (DS.hasExplicitSpecifier())
1520
6
      EmitDiag(DS.getExplicitSpecLoc());
1521
1522
214k
    if (DS.isNoreturnSpecified())
1523
0
      EmitDiag(DS.getNoreturnSpecLoc());
1524
214k
  };
1525
1526
214k
  CheckValidDeclSpecifiers();
1527
1528
214k
  if (TInfo->getType()->isUndeducedType()) {
1529
196
    Diag(D.getIdentifierLoc(),
1530
196
         diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1531
196
      << QualType(TInfo->getType()->getContainedAutoType(), 0);
1532
196
  }
1533
1534
214k
  assert(S->isTemplateParamScope() &&
1535
214k
         "Non-type template parameter not in template parameter scope!");
1536
0
  bool Invalid = false;
1537
1538
214k
  QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
1539
214k
  if (T.isNull()) {
1540
71
    T = Context.IntTy; // Recover with an 'int' type.
1541
71
    Invalid = true;
1542
71
  }
1543
1544
214k
  CheckFunctionOrTemplateParamDeclarator(S, D);
1545
1546
214k
  IdentifierInfo *ParamName = D.getIdentifier();
1547
214k
  bool IsParameterPack = D.hasEllipsis();
1548
214k
  NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1549
214k
      Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1550
214k
      D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1551
214k
      TInfo);
1552
214k
  Param->setAccess(AS_public);
1553
1554
214k
  if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())
1555
184
    if (TL.isConstrained())
1556
3
      if (AttachTypeConstraint(TL, Param, D.getEllipsisLoc()))
1557
1
        Invalid = true;
1558
1559
214k
  if (Invalid)
1560
72
    Param->setInvalidDecl();
1561
1562
214k
  if (Param->isParameterPack())
1563
13.7k
    if (auto *LSI = getEnclosingLambda())
1564
12
      LSI->LocalPacks.push_back(Param);
1565
1566
214k
  if (ParamName) {
1567
160k
    maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1568
160k
                                         ParamName);
1569
1570
    // Add the template parameter into the current scope.
1571
160k
    S->AddDecl(Param);
1572
160k
    IdResolver.AddDecl(Param);
1573
160k
  }
1574
1575
  // C++0x [temp.param]p9:
1576
  //   A default template-argument may be specified for any kind of
1577
  //   template-parameter that is not a template parameter pack.
1578
214k
  if (Default && 
IsParameterPack59.5k
) {
1579
1
    Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1580
1
    Default = nullptr;
1581
1
  }
1582
1583
  // Check the well-formedness of the default template argument, if provided.
1584
214k
  if (Default) {
1585
    // Check for unexpanded parameter packs.
1586
59.5k
    if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1587
1
      return Param;
1588
1589
59.5k
    TemplateArgument Converted;
1590
59.5k
    ExprResult DefaultRes =
1591
59.5k
        CheckTemplateArgument(Param, Param->getType(), Default, Converted);
1592
59.5k
    if (DefaultRes.isInvalid()) {
1593
2
      Param->setInvalidDecl();
1594
2
      return Param;
1595
2
    }
1596
59.5k
    Default = DefaultRes.get();
1597
1598
59.5k
    Param->setDefaultArgument(Default);
1599
59.5k
  }
1600
1601
214k
  return Param;
1602
214k
}
1603
1604
/// ActOnTemplateTemplateParameter - Called when a C++ template template
1605
/// parameter (e.g. T in template <template \<typename> class T> class array)
1606
/// has been parsed. S is the current scope.
1607
NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
1608
                                           SourceLocation TmpLoc,
1609
                                           TemplateParameterList *Params,
1610
                                           SourceLocation EllipsisLoc,
1611
                                           IdentifierInfo *Name,
1612
                                           SourceLocation NameLoc,
1613
                                           unsigned Depth,
1614
                                           unsigned Position,
1615
                                           SourceLocation EqualLoc,
1616
17.5k
                                           ParsedTemplateArgument Default) {
1617
17.5k
  assert(S->isTemplateParamScope() &&
1618
17.5k
         "Template template parameter not in template parameter scope!");
1619
1620
  // Construct the parameter object.
1621
0
  bool IsParameterPack = EllipsisLoc.isValid();
1622
17.5k
  TemplateTemplateParmDecl *Param =
1623
17.5k
    TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1624
17.5k
                                     NameLoc.isInvalid()? 
TmpLoc0
: NameLoc,
1625
17.5k
                                     Depth, Position, IsParameterPack,
1626
17.5k
                                     Name, Params);
1627
17.5k
  Param->setAccess(AS_public);
1628
1629
17.5k
  if (Param->isParameterPack())
1630
106
    if (auto *LSI = getEnclosingLambda())
1631
10
      LSI->LocalPacks.push_back(Param);
1632
1633
  // If the template template parameter has a name, then link the identifier
1634
  // into the scope and lookup mechanisms.
1635
17.5k
  if (Name) {
1636
15.4k
    maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1637
1638
15.4k
    S->AddDecl(Param);
1639
15.4k
    IdResolver.AddDecl(Param);
1640
15.4k
  }
1641
1642
17.5k
  if (Params->size() == 0) {
1643
1
    Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1644
1
    << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1645
1
    Param->setInvalidDecl();
1646
1
  }
1647
1648
  // C++0x [temp.param]p9:
1649
  //   A default template-argument may be specified for any kind of
1650
  //   template-parameter that is not a template parameter pack.
1651
17.5k
  if (IsParameterPack && 
!Default.isInvalid()106
) {
1652
1
    Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1653
1
    Default = ParsedTemplateArgument();
1654
1
  }
1655
1656
17.5k
  if (!Default.isInvalid()) {
1657
    // Check only that we have a template template argument. We don't want to
1658
    // try to check well-formedness now, because our template template parameter
1659
    // might have dependent types in its template parameters, which we wouldn't
1660
    // be able to match now.
1661
    //
1662
    // If none of the template template parameter's template arguments mention
1663
    // other template parameters, we could actually perform more checking here.
1664
    // However, it isn't worth doing.
1665
8.65k
    TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1666
8.65k
    if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1667
0
      Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1668
0
        << DefaultArg.getSourceRange();
1669
0
      return Param;
1670
0
    }
1671
1672
    // Check for unexpanded parameter packs.
1673
8.65k
    if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1674
8.65k
                                        DefaultArg.getArgument().getAsTemplate(),
1675
8.65k
                                        UPPC_DefaultArgument))
1676
1
      return Param;
1677
1678
8.64k
    Param->setDefaultArgument(Context, DefaultArg);
1679
8.64k
  }
1680
1681
17.5k
  return Param;
1682
17.5k
}
1683
1684
/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1685
/// constrained by RequiresClause, that contains the template parameters in
1686
/// Params.
1687
TemplateParameterList *
1688
Sema::ActOnTemplateParameterList(unsigned Depth,
1689
                                 SourceLocation ExportLoc,
1690
                                 SourceLocation TemplateLoc,
1691
                                 SourceLocation LAngleLoc,
1692
                                 ArrayRef<NamedDecl *> Params,
1693
                                 SourceLocation RAngleLoc,
1694
1.27M
                                 Expr *RequiresClause) {
1695
1.27M
  if (ExportLoc.isValid())
1696
3
    Diag(ExportLoc, diag::warn_template_export_unsupported);
1697
1698
1.27M
  for (NamedDecl *P : Params)
1699
2.22M
    warnOnReservedIdentifier(P);
1700
1701
1.27M
  return TemplateParameterList::Create(
1702
1.27M
      Context, TemplateLoc, LAngleLoc,
1703
1.27M
      llvm::makeArrayRef(Params.data(), Params.size()),
1704
1.27M
      RAngleLoc, RequiresClause);
1705
1.27M
}
1706
1707
static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1708
472k
                                   const CXXScopeSpec &SS) {
1709
472k
  if (SS.isSet())
1710
556
    T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1711
472k
}
1712
1713
DeclResult Sema::CheckClassTemplate(
1714
    Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1715
    CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1716
    const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1717
    AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1718
    SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1719
258k
    TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1720
258k
  assert(TemplateParams && TemplateParams->size() > 0 &&
1721
258k
         "No template parameters");
1722
0
  assert(TUK != TUK_Reference && "Can only declare or define class templates");
1723
0
  bool Invalid = false;
1724
1725
  // Check that we can declare a template here.
1726
258k
  if (CheckTemplateDeclScope(S, TemplateParams))
1727
7
    return true;
1728
1729
258k
  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1730
258k
  assert(Kind != TTK_Enum && "can't build template of enumerated type");
1731
1732
  // There is no such thing as an unnamed class template.
1733
258k
  if (!Name) {
1734
0
    Diag(KWLoc, diag::err_template_unnamed_class);
1735
0
    return true;
1736
0
  }
1737
1738
  // Find any previous declaration with this name. For a friend with no
1739
  // scope explicitly specified, we only look for tag declarations (per
1740
  // C++11 [basic.lookup.elab]p2).
1741
258k
  DeclContext *SemanticContext;
1742
258k
  LookupResult Previous(*this, Name, NameLoc,
1743
258k
                        (SS.isEmpty() && 
TUK == TUK_Friend258k
)
1744
258k
                          ? 
LookupTagName6.54k
:
LookupOrdinaryName252k
,
1745
258k
                        forRedeclarationInCurContext());
1746
258k
  if (SS.isNotEmpty() && 
!SS.isInvalid()135
) {
1747
135
    SemanticContext = computeDeclContext(SS, true);
1748
135
    if (!SemanticContext) {
1749
      // FIXME: Horrible, horrible hack! We can't currently represent this
1750
      // in the AST, and historically we have just ignored such friend
1751
      // class templates, so don't complain here.
1752
2
      Diag(NameLoc, TUK == TUK_Friend
1753
2
                        ? 
diag::warn_template_qualified_friend_ignored1
1754
2
                        : 
diag::err_template_qualified_declarator_no_match1
)
1755
2
          << SS.getScopeRep() << SS.getRange();
1756
2
      return TUK != TUK_Friend;
1757
2
    }
1758
1759
133
    if (RequireCompleteDeclContext(SS, SemanticContext))
1760
0
      return true;
1761
1762
    // If we're adding a template to a dependent context, we may need to
1763
    // rebuilding some of the types used within the template parameter list,
1764
    // now that we know what the current instantiation is.
1765
133
    if (SemanticContext->isDependentContext()) {
1766
31
      ContextRAII SavedContext(*this, SemanticContext);
1767
31
      if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1768
0
        Invalid = true;
1769
102
    } else if (TUK != TUK_Friend && 
TUK != TUK_Reference87
)
1770
87
      diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
1771
1772
133
    LookupQualifiedName(Previous, SemanticContext);
1773
258k
  } else {
1774
258k
    SemanticContext = CurContext;
1775
1776
    // C++14 [class.mem]p14:
1777
    //   If T is the name of a class, then each of the following shall have a
1778
    //   name different from T:
1779
    //    -- every member template of class T
1780
258k
    if (TUK != TUK_Friend &&
1781
258k
        DiagnoseClassNameShadow(SemanticContext,
1782
252k
                                DeclarationNameInfo(Name, NameLoc)))
1783
6
      return true;
1784
1785
258k
    LookupName(Previous, S);
1786
258k
  }
1787
1788
258k
  if (Previous.isAmbiguous())
1789
0
    return true;
1790
1791
258k
  NamedDecl *PrevDecl = nullptr;
1792
258k
  if (Previous.begin() != Previous.end())
1793
25.5k
    PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1794
1795
258k
  if (PrevDecl && 
PrevDecl->isTemplateParameter()25.5k
) {
1796
    // Maybe we will complain about the shadowed template parameter.
1797
7
    DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1798
    // Just pretend that we didn't see the previous declaration.
1799
7
    PrevDecl = nullptr;
1800
7
  }
1801
1802
  // If there is a previous declaration with the same name, check
1803
  // whether this is a valid redeclaration.
1804
258k
  ClassTemplateDecl *PrevClassTemplate =
1805
258k
      dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1806
1807
  // We may have found the injected-class-name of a class template,
1808
  // class template partial specialization, or class template specialization.
1809
  // In these cases, grab the template that is being defined or specialized.
1810
258k
  if (!PrevClassTemplate && 
PrevDecl235k
&&
isa<CXXRecordDecl>(PrevDecl)1.79k
&&
1811
258k
      
cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()1.78k
) {
1812
1.76k
    PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1813
1.76k
    PrevClassTemplate
1814
1.76k
      = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1815
1.76k
    if (!PrevClassTemplate && 
isa<ClassTemplateSpecializationDecl>(PrevDecl)24
) {
1816
24
      PrevClassTemplate
1817
24
        = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1818
24
            ->getSpecializedTemplate();
1819
24
    }
1820
1.76k
  }
1821
1822
258k
  if (TUK == TUK_Friend) {
1823
    // C++ [namespace.memdef]p3:
1824
    //   [...] When looking for a prior declaration of a class or a function
1825
    //   declared as a friend, and when the name of the friend class or
1826
    //   function is neither a qualified name nor a template-id, scopes outside
1827
    //   the innermost enclosing namespace scope are not considered.
1828
6.56k
    if (!SS.isSet()) {
1829
6.54k
      DeclContext *OutermostContext = CurContext;
1830
13.1k
      while (!OutermostContext->isFileContext())
1831
6.57k
        OutermostContext = OutermostContext->getLookupParent();
1832
1833
6.54k
      if (PrevDecl &&
1834
6.54k
          
(5.52k
OutermostContext->Equals(PrevDecl->getDeclContext())5.52k
||
1835
5.52k
           
OutermostContext->Encloses(PrevDecl->getDeclContext())12
)) {
1836
5.52k
        SemanticContext = PrevDecl->getDeclContext();
1837
5.52k
      } else {
1838
        // Declarations in outer scopes don't matter. However, the outermost
1839
        // context we computed is the semantic context for our new
1840
        // declaration.
1841
1.01k
        PrevDecl = PrevClassTemplate = nullptr;
1842
1.01k
        SemanticContext = OutermostContext;
1843
1844
        // Check that the chosen semantic context doesn't already contain a
1845
        // declaration of this name as a non-tag type.
1846
1.01k
        Previous.clear(LookupOrdinaryName);
1847
1.01k
        DeclContext *LookupContext = SemanticContext;
1848
1.01k
        while (LookupContext->isTransparentContext())
1849
0
          LookupContext = LookupContext->getLookupParent();
1850
1.01k
        LookupQualifiedName(Previous, LookupContext);
1851
1852
1.01k
        if (Previous.isAmbiguous())
1853
0
          return true;
1854
1855
1.01k
        if (Previous.begin() != Previous.end())
1856
1
          PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1857
1.01k
      }
1858
6.54k
    }
1859
252k
  } else if (PrevDecl &&
1860
252k
             !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1861
19.9k
                            S, SS.isValid()))
1862
49
    PrevDecl = PrevClassTemplate = nullptr;
1863
1864
258k
  if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1865
258k
          PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1866
3
    if (SS.isEmpty() &&
1867
3
        !(PrevClassTemplate &&
1868
3
          PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1869
3
              SemanticContext->getRedeclContext()))) {
1870
2
      Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1871
2
      Diag(Shadow->getTargetDecl()->getLocation(),
1872
2
           diag::note_using_decl_target);
1873
2
      Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
1874
      // Recover by ignoring the old declaration.
1875
2
      PrevDecl = PrevClassTemplate = nullptr;
1876
2
    }
1877
3
  }
1878
1879
258k
  if (PrevClassTemplate) {
1880
    // Ensure that the template parameter lists are compatible. Skip this check
1881
    // for a friend in a dependent context: the template parameter list itself
1882
    // could be dependent.
1883
25.4k
    if (!(TUK == TUK_Friend && 
CurContext->isDependentContext()5.54k
) &&
1884
25.4k
        !TemplateParameterListsAreEqual(TemplateParams,
1885
20.0k
                                   PrevClassTemplate->getTemplateParameters(),
1886
20.0k
                                        /*Complain=*/true,
1887
20.0k
                                        TPL_TemplateMatch))
1888
34
      return true;
1889
1890
    // C++ [temp.class]p4:
1891
    //   In a redeclaration, partial specialization, explicit
1892
    //   specialization or explicit instantiation of a class template,
1893
    //   the class-key shall agree in kind with the original class
1894
    //   template declaration (7.1.5.3).
1895
25.4k
    RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1896
25.4k
    if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1897
25.4k
                                      TUK == TUK_Definition,  KWLoc, Name)) {
1898
0
      Diag(KWLoc, diag::err_use_with_wrong_tag)
1899
0
        << Name
1900
0
        << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1901
0
      Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1902
0
      Kind = PrevRecordDecl->getTagKind();
1903
0
    }
1904
1905
    // Check for redefinition of this class template.
1906
25.4k
    if (TUK == TUK_Definition) {
1907
10.9k
      if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1908
        // If we have a prior definition that is not visible, treat this as
1909
        // simply making that previous definition visible.
1910
112
        NamedDecl *Hidden = nullptr;
1911
112
        if (SkipBody && 
!hasVisibleDefinition(Def, &Hidden)111
) {
1912
110
          SkipBody->ShouldSkip = true;
1913
110
          SkipBody->Previous = Def;
1914
110
          auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1915
110
          assert(Tmpl && "original definition of a class template is not a "
1916
110
                         "class template?");
1917
0
          makeMergedDefinitionVisible(Hidden);
1918
110
          makeMergedDefinitionVisible(Tmpl);
1919
110
        } else {
1920
2
          Diag(NameLoc, diag::err_redefinition) << Name;
1921
2
          Diag(Def->getLocation(), diag::note_previous_definition);
1922
          // FIXME: Would it make sense to try to "forget" the previous
1923
          // definition, as part of error recovery?
1924
2
          return true;
1925
2
        }
1926
112
      }
1927
10.9k
    }
1928
233k
  } else if (PrevDecl) {
1929
    // C++ [temp]p5:
1930
    //   A class template shall not have the same name as any other
1931
    //   template, class, function, object, enumeration, enumerator,
1932
    //   namespace, or type in the same scope (3.3), except as specified
1933
    //   in (14.5.4).
1934
6
    Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1935
6
    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1936
6
    return true;
1937
6
  }
1938
1939
  // Check the template parameter list of this declaration, possibly
1940
  // merging in the template parameter list from the previous class
1941
  // template declaration. Skip this check for a friend in a dependent
1942
  // context, because the template parameter list might be dependent.
1943
258k
  if (!(TUK == TUK_Friend && 
CurContext->isDependentContext()6.55k
) &&
1944
258k
      CheckTemplateParameterList(
1945
252k
          TemplateParams,
1946
252k
          PrevClassTemplate
1947
252k
              ? 
PrevClassTemplate->getMostRecentDecl()->getTemplateParameters()19.9k
1948
252k
              : 
nullptr232k
,
1949
252k
          (SS.isSet() && 
SemanticContext121
&&
SemanticContext->isRecord()121
&&
1950
252k
           
SemanticContext->isDependentContext()107
)
1951
252k
              ? 
TPC_ClassTemplateMember28
1952
252k
              : 
TUK == TUK_Friend252k
?
TPC_FriendClassTemplate154
:
TPC_ClassTemplate252k
,
1953
252k
          SkipBody))
1954
22
    Invalid = true;
1955
1956
258k
  if (SS.isSet()) {
1957
    // If the name of the template was qualified, we must be defining the
1958
    // template out-of-line.
1959
130
    if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1960
3
      Diag(NameLoc, TUK == TUK_Friend ? 
diag::err_friend_decl_does_not_match1
1961
3
                                      : 
diag::err_member_decl_does_not_match2
)
1962
3
        << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1963
3
      Invalid = true;
1964
3
    }
1965
130
  }
1966
1967
  // If this is a templated friend in a dependent context we should not put it
1968
  // on the redecl chain. In some cases, the templated friend can be the most
1969
  // recent declaration tricking the template instantiator to make substitutions
1970
  // there.
1971
  // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1972
258k
  bool ShouldAddRedecl
1973
258k
    = !(TUK == TUK_Friend && 
CurContext->isDependentContext()6.55k
);
1974
1975
258k
  CXXRecordDecl *NewClass =
1976
258k
    CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1977
258k
                          PrevClassTemplate && 
ShouldAddRedecl25.4k
?
1978
238k
                            
PrevClassTemplate->getTemplatedDecl()19.9k
: nullptr,
1979
258k
                          /*DelayTypeCreation=*/true);
1980
258k
  SetNestedNameSpecifier(*this, NewClass, SS);
1981
258k
  if (NumOuterTemplateParamLists > 0)
1982
71
    NewClass->setTemplateParameterListsInfo(
1983
71
        Context, llvm::makeArrayRef(OuterTemplateParamLists,
1984
71
                                    NumOuterTemplateParamLists));
1985
1986
  // Add alignment attributes if necessary; these attributes are checked when
1987
  // the ASTContext lays out the structure.
1988
258k
  if (TUK == TUK_Definition && 
(203k
!SkipBody203k
||
!SkipBody->ShouldSkip203k
)) {
1989
203k
    AddAlignmentAttributesForRecord(NewClass);
1990
203k
    AddMsStructLayoutForRecord(NewClass);
1991
203k
  }
1992
1993
258k
  ClassTemplateDecl *NewTemplate
1994
258k
    = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1995
258k
                                DeclarationName(Name), TemplateParams,
1996
258k
                                NewClass);
1997
1998
258k
  if (ShouldAddRedecl)
1999
252k
    NewTemplate->setPreviousDecl(PrevClassTemplate);
2000
2001
258k
  NewClass->setDescribedClassTemplate(NewTemplate);
2002
2003
258k
  if (ModulePrivateLoc.isValid())
2004
3
    NewTemplate->setModulePrivate();
2005
2006
  // Build the type for the class template declaration now.
2007
258k
  QualType T = NewTemplate->getInjectedClassNameSpecialization();
2008
258k
  T = Context.getInjectedClassNameType(NewClass, T);
2009
258k
  assert(T->isDependentType() && "Class template type is not dependent?");
2010
0
  (void)T;
2011
2012
  // If we are providing an explicit specialization of a member that is a
2013
  // class template, make a note of that.
2014
258k
  if (PrevClassTemplate &&
2015
258k
      
PrevClassTemplate->getInstantiatedFromMemberTemplate()25.4k
)
2016
39
    PrevClassTemplate->setMemberSpecialization();
2017
2018
  // Set the access specifier.
2019
258k
  if (!Invalid && 
TUK != TUK_Friend258k
&&
NewTemplate->getDeclContext()->isRecord()252k
)
2020
9.42k
    SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2021
2022
  // Set the lexical context of these templates
2023
258k
  NewClass->setLexicalDeclContext(CurContext);
2024
258k
  NewTemplate->setLexicalDeclContext(CurContext);
2025
2026
258k
  if (TUK == TUK_Definition && 
(203k
!SkipBody203k
||
!SkipBody->ShouldSkip203k
))
2027
203k
    NewClass->startDefinition();
2028
2029
258k
  ProcessDeclAttributeList(S, NewClass, Attr);
2030
2031
258k
  if (PrevClassTemplate)
2032
25.4k
    mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2033
2034
258k
  AddPushedVisibilityAttribute(NewClass);
2035
258k
  inferGslOwnerPointerAttribute(NewClass);
2036
2037
258k
  if (TUK != TUK_Friend) {
2038
    // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2039
252k
    Scope *Outer = S;
2040
504k
    while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2041
252k
      Outer = Outer->getParent();
2042
252k
    PushOnScopeChains(NewTemplate, Outer);
2043
252k
  } else {
2044
6.55k
    if (PrevClassTemplate && 
PrevClassTemplate->getAccess() != AS_none5.54k
) {
2045
19
      NewTemplate->setAccess(PrevClassTemplate->getAccess());
2046
19
      NewClass->setAccess(PrevClassTemplate->getAccess());
2047
19
    }
2048
2049
6.55k
    NewTemplate->setObjectOfFriendDecl();
2050
2051
    // Friend templates are visible in fairly strange ways.
2052
6.55k
    if (!CurContext->isDependentContext()) {
2053
154
      DeclContext *DC = SemanticContext->getRedeclContext();
2054
154
      DC->makeDeclVisibleInContext(NewTemplate);
2055
154
      if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2056
147
        PushOnScopeChains(NewTemplate, EnclosingScope,
2057
147
                          /* AddToContext = */ false);
2058
154
    }
2059
2060
6.55k
    FriendDecl *Friend = FriendDecl::Create(
2061
6.55k
        Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2062
6.55k
    Friend->setAccess(AS_public);
2063
6.55k
    CurContext->addDecl(Friend);
2064
6.55k
  }
2065
2066
258k
  if (PrevClassTemplate)
2067
25.4k
    CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate);
2068
2069
258k
  if (Invalid) {
2070
25
    NewTemplate->setInvalidDecl();
2071
25
    NewClass->setInvalidDecl();
2072
25
  }
2073
2074
258k
  ActOnDocumentableDecl(NewTemplate);
2075
2076
258k
  if (SkipBody && 
SkipBody->ShouldSkip252k
)
2077
110
    return SkipBody->Previous;
2078
2079
258k
  return NewTemplate;
2080
258k
}
2081
2082
namespace {
2083
/// Tree transform to "extract" a transformed type from a class template's
2084
/// constructor to a deduction guide.
2085
class ExtractTypeForDeductionGuide
2086
  : public TreeTransform<ExtractTypeForDeductionGuide> {
2087
  llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs;
2088
2089
public:
2090
  typedef TreeTransform<ExtractTypeForDeductionGuide> Base;
2091
  ExtractTypeForDeductionGuide(
2092
      Sema &SemaRef,
2093
      llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs)
2094
2.48k
      : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs) {}
2095
2096
2.48k
  TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
2097
2098
2.67k
  QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
2099
2.67k
    ASTContext &Context = SemaRef.getASTContext();
2100
2.67k
    TypedefNameDecl *OrigDecl = TL.getTypedefNameDecl();
2101
2.67k
    TypedefNameDecl *Decl = OrigDecl;
2102
    // Transform the underlying type of the typedef and clone the Decl only if
2103
    // the typedef has a dependent context.
2104
2.67k
    if (OrigDecl->getDeclContext()->isDependentContext()) {
2105
2.64k
      TypeLocBuilder InnerTLB;
2106
2.64k
      QualType Transformed =
2107
2.64k
          TransformType(InnerTLB, OrigDecl->getTypeSourceInfo()->getTypeLoc());
2108
2.64k
      TypeSourceInfo *TSI = InnerTLB.getTypeSourceInfo(Context, Transformed);
2109
2.64k
      if (isa<TypeAliasDecl>(OrigDecl))
2110
5
        Decl = TypeAliasDecl::Create(
2111
5
            Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
2112
5
            OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
2113
2.64k
      else {
2114
2.64k
        assert(isa<TypedefDecl>(OrigDecl) && "Not a Type alias or typedef");
2115
0
        Decl = TypedefDecl::Create(
2116
2.64k
            Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
2117
2.64k
            OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
2118
2.64k
      }
2119
0
      MaterializedTypedefs.push_back(Decl);
2120
2.64k
    }
2121
2122
0
    QualType TDTy = Context.getTypedefType(Decl);
2123
2.67k
    TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(TDTy);
2124
2.67k
    TypedefTL.setNameLoc(TL.getNameLoc());
2125
2126
2.67k
    return TDTy;
2127
2.67k
  }
2128
};
2129
2130
/// Transform to convert portions of a constructor declaration into the
2131
/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
2132
struct ConvertConstructorToDeductionGuideTransform {
2133
  ConvertConstructorToDeductionGuideTransform(Sema &S,
2134
                                              ClassTemplateDecl *Template)
2135
1.04k
      : SemaRef(S), Template(Template) {}
2136
2137
  Sema &SemaRef;
2138
  ClassTemplateDecl *Template;
2139
2140
  DeclContext *DC = Template->getDeclContext();
2141
  CXXRecordDecl *Primary = Template->getTemplatedDecl();
2142
  DeclarationName DeductionGuideName =
2143
      SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
2144
2145
  QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
2146
2147
  // Index adjustment to apply to convert depth-1 template parameters into
2148
  // depth-0 template parameters.
2149
  unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
2150
2151
  /// Transform a constructor declaration into a deduction guide.
2152
  NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
2153
1.31k
                                  CXXConstructorDecl *CD) {
2154
1.31k
    SmallVector<TemplateArgument, 16> SubstArgs;
2155
2156
1.31k
    LocalInstantiationScope Scope(SemaRef);
2157
2158
    // C++ [over.match.class.deduct]p1:
2159
    // -- For each constructor of the class template designated by the
2160
    //    template-name, a function template with the following properties:
2161
2162
    //    -- The template parameters are the template parameters of the class
2163
    //       template followed by the template parameters (including default
2164
    //       template arguments) of the constructor, if any.
2165
1.31k
    TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2166
1.31k
    if (FTD) {
2167
615
      TemplateParameterList *InnerParams = FTD->getTemplateParameters();
2168
615
      SmallVector<NamedDecl *, 16> AllParams;
2169
615
      AllParams.reserve(TemplateParams->size() + InnerParams->size());
2170
615
      AllParams.insert(AllParams.begin(),
2171
615
                       TemplateParams->begin(), TemplateParams->end());
2172
615
      SubstArgs.reserve(InnerParams->size());
2173
2174
      // Later template parameters could refer to earlier ones, so build up
2175
      // a list of substituted template arguments as we go.
2176
1.28k
      for (NamedDecl *Param : *InnerParams) {
2177
1.28k
        MultiLevelTemplateArgumentList Args;
2178
1.28k
        Args.setKind(TemplateSubstitutionKind::Rewrite);
2179
1.28k
        Args.addOuterTemplateArguments(SubstArgs);
2180
1.28k
        Args.addOuterRetainedLevel();
2181
1.28k
        NamedDecl *NewParam = transformTemplateParameter(Param, Args);
2182
1.28k
        if (!NewParam)
2183
0
          return nullptr;
2184
1.28k
        AllParams.push_back(NewParam);
2185
1.28k
        SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
2186
1.28k
            SemaRef.Context.getInjectedTemplateArg(NewParam)));
2187
1.28k
      }
2188
615
      TemplateParams = TemplateParameterList::Create(
2189
615
          SemaRef.Context, InnerParams->getTemplateLoc(),
2190
615
          InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
2191
615
          /*FIXME: RequiresClause*/ nullptr);
2192
615
    }
2193
2194
    // If we built a new template-parameter-list, track that we need to
2195
    // substitute references to the old parameters into references to the
2196
    // new ones.
2197
1.31k
    MultiLevelTemplateArgumentList Args;
2198
1.31k
    Args.setKind(TemplateSubstitutionKind::Rewrite);
2199
1.31k
    if (FTD) {
2200
615
      Args.addOuterTemplateArguments(SubstArgs);
2201
615
      Args.addOuterRetainedLevel();
2202
615
    }
2203
2204
1.31k
    FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
2205
1.31k
                                   .getAsAdjusted<FunctionProtoTypeLoc>();
2206
1.31k
    assert(FPTL && "no prototype for constructor declaration");
2207
2208
    // Transform the type of the function, adjusting the return type and
2209
    // replacing references to the old parameters with references to the
2210
    // new ones.
2211
0
    TypeLocBuilder TLB;
2212
1.31k
    SmallVector<ParmVarDecl*, 8> Params;
2213
1.31k
    SmallVector<TypedefNameDecl *, 4> MaterializedTypedefs;
2214
1.31k
    QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args,
2215
1.31k
                                                  MaterializedTypedefs);
2216
1.31k
    if (NewType.isNull())
2217
0
      return nullptr;
2218
1.31k
    TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
2219
2220
1.31k
    return buildDeductionGuide(TemplateParams, CD, CD->getExplicitSpecifier(),
2221
1.31k
                               NewTInfo, CD->getBeginLoc(), CD->getLocation(),
2222
1.31k
                               CD->getEndLoc(), MaterializedTypedefs);
2223
1.31k
  }
2224
2225
  /// Build a deduction guide with the specified parameter types.
2226
342
  NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
2227
342
    SourceLocation Loc = Template->getLocation();
2228
2229
    // Build the requested type.
2230
342
    FunctionProtoType::ExtProtoInfo EPI;
2231
342
    EPI.HasTrailingReturn = true;
2232
342
    QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
2233
342
                                                DeductionGuideName, EPI);
2234
342
    TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
2235
2236
342
    FunctionProtoTypeLoc FPTL =
2237
342
        TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
2238
2239
    // Build the parameters, needed during deduction / substitution.
2240
342
    SmallVector<ParmVarDecl*, 4> Params;
2241
342
    for (auto T : ParamTypes) {
2242
290
      ParmVarDecl *NewParam = ParmVarDecl::Create(
2243
290
          SemaRef.Context, DC, Loc, Loc, nullptr, T,
2244
290
          SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
2245
290
      NewParam->setScopeInfo(0, Params.size());
2246
290
      FPTL.setParam(Params.size(), NewParam);
2247
290
      Params.push_back(NewParam);
2248
290
    }
2249
2250
342
    return buildDeductionGuide(Template->getTemplateParameters(), nullptr,
2251
342
                               ExplicitSpecifier(), TSI, Loc, Loc, Loc);
2252
342
  }
2253
2254
private:
2255
  /// Transform a constructor template parameter into a deduction guide template
2256
  /// parameter, rebuilding any internal references to earlier parameters and
2257
  /// renumbering as we go.
2258
  NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
2259
1.28k
                                        MultiLevelTemplateArgumentList &Args) {
2260
1.28k
    if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
2261
      // TemplateTypeParmDecl's index cannot be changed after creation, so
2262
      // substitute it directly.
2263
837
      auto *NewTTP = TemplateTypeParmDecl::Create(
2264
837
          SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(),
2265
837
          /*Depth*/ 0, Depth1IndexAdjustment + TTP->getIndex(),
2266
837
          TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
2267
837
          TTP->isParameterPack(), TTP->hasTypeConstraint(),
2268
837
          TTP->isExpandedParameterPack() ?
2269
837
          
llvm::Optional<unsigned>(TTP->getNumExpansionParameters())0
: None);
2270
837
      if (const auto *TC = TTP->getTypeConstraint()) {
2271
2
        TemplateArgumentListInfo TransformedArgs;
2272
2
        const auto *ArgsAsWritten = TC->getTemplateArgsAsWritten();
2273
2
        if (!ArgsAsWritten ||
2274
2
            SemaRef.Subst(ArgsAsWritten->getTemplateArgs(),
2275
2
                          ArgsAsWritten->NumTemplateArgs, TransformedArgs,
2276
2
                          Args))
2277
0
          SemaRef.AttachTypeConstraint(
2278
0
              TC->getNestedNameSpecifierLoc(), TC->getConceptNameInfo(),
2279
0
              TC->getNamedConcept(), ArgsAsWritten ? &TransformedArgs : nullptr,
2280
0
              NewTTP,
2281
0
              NewTTP->isParameterPack()
2282
0
                 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2283
0
                     ->getEllipsisLoc()
2284
0
                 : SourceLocation());
2285
2
      }
2286
837
      if (TTP->hasDefaultArgument()) {
2287
111
        TypeSourceInfo *InstantiatedDefaultArg =
2288
111
            SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
2289
111
                              TTP->getDefaultArgumentLoc(), TTP->getDeclName());
2290
111
        if (InstantiatedDefaultArg)
2291
111
          NewTTP->setDefaultArgument(InstantiatedDefaultArg);
2292
111
      }
2293
837
      SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
2294
837
                                                           NewTTP);
2295
837
      return NewTTP;
2296
837
    }
2297
2298
450
    if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
2299
124
      return transformTemplateParameterImpl(TTP, Args);
2300
2301
326
    return transformTemplateParameterImpl(
2302
326
        cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
2303
450
  }
2304
  template<typename TemplateParmDecl>
2305
  TemplateParmDecl *
2306
  transformTemplateParameterImpl(TemplateParmDecl *OldParam,
2307
450
                                 MultiLevelTemplateArgumentList &Args) {
2308
    // Ask the template instantiator to do the heavy lifting for us, then adjust
2309
    // the index of the parameter once it's done.
2310
450
    auto *NewParam =
2311
450
        cast<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
2312
450
    assert(NewParam->getDepth() == 0 && "unexpected template param depth");
2313
0
    NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
2314
450
    return NewParam;
2315
450
  }
SemaTemplate.cpp:clang::TemplateTemplateParmDecl* (anonymous namespace)::ConvertConstructorToDeductionGuideTransform::transformTemplateParameterImpl<clang::TemplateTemplateParmDecl>(clang::TemplateTemplateParmDecl*, clang::MultiLevelTemplateArgumentList&)
Line
Count
Source
2307
124
                                 MultiLevelTemplateArgumentList &Args) {
2308
    // Ask the template instantiator to do the heavy lifting for us, then adjust
2309
    // the index of the parameter once it's done.
2310
124
    auto *NewParam =
2311
124
        cast<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
2312
124
    assert(NewParam->getDepth() == 0 && "unexpected template param depth");
2313
0
    NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
2314
124
    return NewParam;
2315
124
  }
SemaTemplate.cpp:clang::NonTypeTemplateParmDecl* (anonymous namespace)::ConvertConstructorToDeductionGuideTransform::transformTemplateParameterImpl<clang::NonTypeTemplateParmDecl>(clang::NonTypeTemplateParmDecl*, clang::MultiLevelTemplateArgumentList&)
Line
Count
Source
2307
326
                                 MultiLevelTemplateArgumentList &Args) {
2308
    // Ask the template instantiator to do the heavy lifting for us, then adjust
2309
    // the index of the parameter once it's done.
2310
326
    auto *NewParam =
2311
326
        cast<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
2312
326
    assert(NewParam->getDepth() == 0 && "unexpected template param depth");
2313
0
    NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
2314
326
    return NewParam;
2315
326
  }
2316
2317
  QualType transformFunctionProtoType(
2318
      TypeLocBuilder &TLB, FunctionProtoTypeLoc TL,
2319
      SmallVectorImpl<ParmVarDecl *> &Params,
2320
      MultiLevelTemplateArgumentList &Args,
2321
1.31k
      SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2322
1.31k
    SmallVector<QualType, 4> ParamTypes;
2323
1.31k
    const FunctionProtoType *T = TL.getTypePtr();
2324
2325
    //    -- The types of the function parameters are those of the constructor.
2326
2.48k
    for (auto *OldParam : TL.getParams()) {
2327
2.48k
      ParmVarDecl *NewParam =
2328
2.48k
          transformFunctionTypeParam(OldParam, Args, MaterializedTypedefs);
2329
2.48k
      if (!NewParam)
2330
0
        return QualType();
2331
2.48k
      ParamTypes.push_back(NewParam->getType());
2332
2.48k
      Params.push_back(NewParam);
2333
2.48k
    }
2334
2335
    //    -- The return type is the class template specialization designated by
2336
    //       the template-name and template arguments corresponding to the
2337
    //       template parameters obtained from the class template.
2338
    //
2339
    // We use the injected-class-name type of the primary template instead.
2340
    // This has the convenient property that it is different from any type that
2341
    // the user can write in a deduction-guide (because they cannot enter the
2342
    // context of the template), so implicit deduction guides can never collide
2343
    // with explicit ones.
2344
1.31k
    QualType ReturnType = DeducedType;
2345
1.31k
    TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
2346
2347
    // Resolving a wording defect, we also inherit the variadicness of the
2348
    // constructor.
2349
1.31k
    FunctionProtoType::ExtProtoInfo EPI;
2350
1.31k
    EPI.Variadic = T->isVariadic();
2351
1.31k
    EPI.HasTrailingReturn = true;
2352
2353
1.31k
    QualType Result = SemaRef.BuildFunctionType(
2354
1.31k
        ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
2355
1.31k
    if (Result.isNull())
2356
0
      return QualType();
2357
2358
1.31k
    FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
2359
1.31k
    NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
2360
1.31k
    NewTL.setLParenLoc(TL.getLParenLoc());
2361
1.31k
    NewTL.setRParenLoc(TL.getRParenLoc());
2362
1.31k
    NewTL.setExceptionSpecRange(SourceRange());
2363
1.31k
    NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
2364
3.80k
    for (unsigned I = 0, E = NewTL.getNumParams(); I != E; 
++I2.48k
)
2365
2.48k
      NewTL.setParam(I, Params[I]);
2366
2367
1.31k
    return Result;
2368
1.31k
  }
2369
2370
  ParmVarDecl *transformFunctionTypeParam(
2371
      ParmVarDecl *OldParam, MultiLevelTemplateArgumentList &Args,
2372
2.48k
      llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2373
2.48k
    TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
2374
2.48k
    TypeSourceInfo *NewDI;
2375
2.48k
    if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
2376
      // Expand out the one and only element in each inner pack.
2377
69
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
2378
69
      NewDI =
2379
69
          SemaRef.SubstType(PackTL.getPatternLoc(), Args,
2380
69
                            OldParam->getLocation(), OldParam->getDeclName());
2381
69
      if (!NewDI) 
return nullptr0
;
2382
69
      NewDI =
2383
69
          SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
2384
69
                                     PackTL.getTypePtr()->getNumExpansions());
2385
69
    } else
2386
2.42k
      NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
2387
2.42k
                                OldParam->getDeclName());
2388
2.48k
    if (!NewDI)
2389
0
      return nullptr;
2390
2391
    // Extract the type. This (for instance) replaces references to typedef
2392
    // members of the current instantiations with the definitions of those
2393
    // typedefs, avoiding triggering instantiation of the deduced type during
2394
    // deduction.
2395
2.48k
    NewDI = ExtractTypeForDeductionGuide(SemaRef, MaterializedTypedefs)
2396
2.48k
                .transform(NewDI);
2397
2398
    // Resolving a wording defect, we also inherit default arguments from the
2399
    // constructor.
2400
2.48k
    ExprResult NewDefArg;
2401
2.48k
    if (OldParam->hasDefaultArg()) {
2402
      // We don't care what the value is (we won't use it); just create a
2403
      // placeholder to indicate there is a default argument.
2404
232
      QualType ParamTy = NewDI->getType();
2405
232
      NewDefArg = new (SemaRef.Context)
2406
232
          OpaqueValueExpr(OldParam->getDefaultArg()->getBeginLoc(),
2407
232
                          ParamTy.getNonLValueExprType(SemaRef.Context),
2408
232
                          ParamTy->isLValueReferenceType()   ? 
VK_LValue84
2409
232
                          : 
ParamTy->isRValueReferenceType()148
?
VK_XValue0
2410
148
                                                             : VK_PRValue);
2411
232
    }
2412
2413
2.48k
    ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
2414
2.48k
                                                OldParam->getInnerLocStart(),
2415
2.48k
                                                OldParam->getLocation(),
2416
2.48k
                                                OldParam->getIdentifier(),
2417
2.48k
                                                NewDI->getType(),
2418
2.48k
                                                NewDI,
2419
2.48k
                                                OldParam->getStorageClass(),
2420
2.48k
                                                NewDefArg.get());
2421
2.48k
    NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
2422
2.48k
                           OldParam->getFunctionScopeIndex());
2423
2.48k
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
2424
2.48k
    return NewParam;
2425
2.48k
  }
2426
2427
  FunctionTemplateDecl *buildDeductionGuide(
2428
      TemplateParameterList *TemplateParams, CXXConstructorDecl *Ctor,
2429
      ExplicitSpecifier ES, TypeSourceInfo *TInfo, SourceLocation LocStart,
2430
      SourceLocation Loc, SourceLocation LocEnd,
2431
1.65k
      llvm::ArrayRef<TypedefNameDecl *> MaterializedTypedefs = {}) {
2432
1.65k
    DeclarationNameInfo Name(DeductionGuideName, Loc);
2433
1.65k
    ArrayRef<ParmVarDecl *> Params =
2434
1.65k
        TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
2435
2436
    // Build the implicit deduction guide template.
2437
1.65k
    auto *Guide =
2438
1.65k
        CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name,
2439
1.65k
                                      TInfo->getType(), TInfo, LocEnd, Ctor);
2440
1.65k
    Guide->setImplicit();
2441
1.65k
    Guide->setParams(Params);
2442
2443
1.65k
    for (auto *Param : Params)
2444
2.77k
      Param->setDeclContext(Guide);
2445
1.65k
    for (auto *TD : MaterializedTypedefs)
2446
2.64k
      TD->setDeclContext(Guide);
2447
2448
1.65k
    auto *GuideTemplate = FunctionTemplateDecl::Create(
2449
1.65k
        SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
2450
1.65k
    GuideTemplate->setImplicit();
2451
1.65k
    Guide->setDescribedFunctionTemplate(GuideTemplate);
2452
2453
1.65k
    if (isa<CXXRecordDecl>(DC)) {
2454
28
      Guide->setAccess(AS_public);
2455
28
      GuideTemplate->setAccess(AS_public);
2456
28
    }
2457
2458
1.65k
    DC->addDecl(GuideTemplate);
2459
1.65k
    return GuideTemplate;
2460
1.65k
  }
2461
};
2462
}
2463
2464
void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
2465
1.05k
                                          SourceLocation Loc) {
2466
1.05k
  if (CXXRecordDecl *DefRecord =
2467
1.05k
          cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
2468
1.01k
    TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate();
2469
1.01k
    Template = DescribedTemplate ? DescribedTemplate : 
Template0
;
2470
1.01k
  }
2471
2472
1.05k
  DeclContext *DC = Template->getDeclContext();
2473
1.05k
  if (DC->isDependentContext())
2474
4
    return;
2475
2476
1.04k
  ConvertConstructorToDeductionGuideTransform Transform(
2477
1.04k
      *this, cast<ClassTemplateDecl>(Template));
2478
1.04k
  if (!isCompleteType(Loc, Transform.DeducedType))
2479
0
    return;
2480
2481
  // Check whether we've already declared deduction guides for this template.
2482
  // FIXME: Consider storing a flag on the template to indicate this.
2483
1.04k
  auto Existing = DC->lookup(Transform.DeductionGuideName);
2484
1.04k
  for (auto *D : Existing)
2485
755
    if (D->isImplicit())
2486
755
      return;
2487
2488
  // In case we were expanding a pack when we attempted to declare deduction
2489
  // guides, turn off pack expansion for everything we're about to do.
2490
291
  ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2491
  // Create a template instantiation record to track the "instantiation" of
2492
  // constructors into deduction guides.
2493
  // FIXME: Add a kind for this to give more meaningful diagnostics. But can
2494
  // this substitution process actually fail?
2495
291
  InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
2496
291
  if (BuildingDeductionGuides.isInvalid())
2497
1
    return;
2498
2499
  // Convert declared constructors into deduction guide templates.
2500
  // FIXME: Skip constructors for which deduction must necessarily fail (those
2501
  // for which some class template parameter without a default argument never
2502
  // appears in a deduced context).
2503
290
  bool AddedAny = false;
2504
1.31k
  for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
2505
1.31k
    D = D->getUnderlyingDecl();
2506
1.31k
    if (D->isInvalidDecl() || D->isImplicit())
2507
0
      continue;
2508
1.31k
    D = cast<NamedDecl>(D->getCanonicalDecl());
2509
2510
1.31k
    auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
2511
1.31k
    auto *CD =
2512
1.31k
        dyn_cast_or_null<CXXConstructorDecl>(FTD ? 
FTD->getTemplatedDecl()615
:
D701
);
2513
    // Class-scope explicit specializations (MS extension) do not result in
2514
    // deduction guides.
2515
1.31k
    if (!CD || (!FTD && 
CD->isFunctionTemplateSpecialization()701
))
2516
0
      continue;
2517
2518
    // Cannot make a deduction guide when unparsed arguments are present.
2519
2.49k
    
if (1.31k
std::any_of(CD->param_begin(), CD->param_end(), [](ParmVarDecl *P) 1.31k
{
2520
2.49k
          return !P || P->hasUnparsedDefaultArg();
2521
2.49k
        }))
2522
1
      continue;
2523
2524
1.31k
    Transform.transformConstructor(FTD, CD);
2525
1.31k
    AddedAny = true;
2526
1.31k
  }
2527
2528
  // C++17 [over.match.class.deduct]
2529
  //    --  If C is not defined or does not declare any constructors, an
2530
  //    additional function template derived as above from a hypothetical
2531
  //    constructor C().
2532
290
  if (!AddedAny)
2533
52
    Transform.buildSimpleDeductionGuide(None);
2534
2535
  //    -- An additional function template derived as above from a hypothetical
2536
  //    constructor C(C), called the copy deduction candidate.
2537
290
  cast<CXXDeductionGuideDecl>(
2538
290
      cast<FunctionTemplateDecl>(
2539
290
          Transform.buildSimpleDeductionGuide(Transform.DeducedType))
2540
290
          ->getTemplatedDecl())
2541
290
      ->setIsCopyDeductionCandidate();
2542
290
}
2543
2544
/// Diagnose the presence of a default template argument on a
2545
/// template parameter, which is ill-formed in certain contexts.
2546
///
2547
/// \returns true if the default template argument should be dropped.
2548
static bool DiagnoseDefaultTemplateArgument(Sema &S,
2549
                                            Sema::TemplateParamListContext TPC,
2550
                                            SourceLocation ParamLoc,
2551
166k
                                            SourceRange DefArgRange) {
2552
166k
  switch (TPC) {
2553
70.6k
  case Sema::TPC_ClassTemplate:
2554
70.6k
  case Sema::TPC_VarTemplate:
2555
82.2k
  case Sema::TPC_TypeAliasTemplate:
2556
82.2k
    return false;
2557
2558
84.6k
  case Sema::TPC_FunctionTemplate:
2559
84.6k
  case Sema::TPC_FriendFunctionTemplateDefinition:
2560
    // C++ [temp.param]p9:
2561
    //   A default template-argument shall not be specified in a
2562
    //   function template declaration or a function template
2563
    //   definition [...]
2564
    //   If a friend function template declaration specifies a default
2565
    //   template-argument, that declaration shall be a definition and shall be
2566
    //   the only declaration of the function template in the translation unit.
2567
    // (C++98/03 doesn't have this wording; see DR226).
2568
84.6k
    S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2569
84.6k
         diag::warn_cxx98_compat_template_parameter_default_in_function_template
2570
84.6k
           : 
diag::ext_template_parameter_default_in_function_template39
)
2571
84.6k
      << DefArgRange;
2572
84.6k
    return false;
2573
2574
14
  case Sema::TPC_ClassTemplateMember:
2575
    // C++0x [temp.param]p9:
2576
    //   A default template-argument shall not be specified in the
2577
    //   template-parameter-lists of the definition of a member of a
2578
    //   class template that appears outside of the member's class.
2579
14
    S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2580
14
      << DefArgRange;
2581
14
    return true;
2582
2583
8
  case Sema::TPC_FriendClassTemplate:
2584
10
  case Sema::TPC_FriendFunctionTemplate:
2585
    // C++ [temp.param]p9:
2586
    //   A default template-argument shall not be specified in a
2587
    //   friend template declaration.
2588
10
    S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2589
10
      << DefArgRange;
2590
10
    return true;
2591
2592
    // FIXME: C++0x [temp.param]p9 allows default template-arguments
2593
    // for friend function templates if there is only a single
2594
    // declaration (and it is a definition). Strange!
2595
166k
  }
2596
2597
0
  llvm_unreachable("Invalid TemplateParamListContext!");
2598
0
}
2599
2600
/// Check for unexpanded parameter packs within the template parameters
2601
/// of a template template parameter, recursively.
2602
static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2603
14.6k
                                             TemplateTemplateParmDecl *TTP) {
2604
  // A template template parameter which is a parameter pack is also a pack
2605
  // expansion.
2606
14.6k
  if (TTP->isParameterPack())
2607
89
    return false;
2608
2609
14.5k
  TemplateParameterList *Params = TTP->getTemplateParameters();
2610
30.0k
  for (unsigned I = 0, N = Params->size(); I != N; 
++I15.5k
) {
2611
15.5k
    NamedDecl *P = Params->getParam(I);
2612
15.5k
    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2613
14.8k
      if (!TTP->isParameterPack())
2614
1.70k
        if (const TypeConstraint *TC = TTP->getTypeConstraint())
2615
1
          if (TC->hasExplicitTemplateArgs())
2616
0
            for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2617
0
              if (S.DiagnoseUnexpandedParameterPack(ArgLoc,
2618
0
                                                    Sema::UPPC_TypeConstraint))
2619
0
                return true;
2620
14.8k
      continue;
2621
14.8k
    }
2622
2623
704
    if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2624
677
      if (!NTTP->isParameterPack() &&
2625
677
          S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2626
239
                                            NTTP->getTypeSourceInfo(),
2627
239
                                      Sema::UPPC_NonTypeTemplateParameterType))
2628
0
        return true;
2629
2630
677
      continue;
2631
677
    }
2632
2633
27
    if (TemplateTemplateParmDecl *InnerTTP
2634
27
                                        = dyn_cast<TemplateTemplateParmDecl>(P))
2635
27
      if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2636
0
        return true;
2637
27
  }
2638
2639
14.5k
  return false;
2640
14.5k
}
2641
2642
/// Checks the validity of a template parameter list, possibly
2643
/// considering the template parameter list from a previous
2644
/// declaration.
2645
///
2646
/// If an "old" template parameter list is provided, it must be
2647
/// equivalent (per TemplateParameterListsAreEqual) to the "new"
2648
/// template parameter list.
2649
///
2650
/// \param NewParams Template parameter list for a new template
2651
/// declaration. This template parameter list will be updated with any
2652
/// default arguments that are carried through from the previous
2653
/// template parameter list.
2654
///
2655
/// \param OldParams If provided, template parameter list from a
2656
/// previous declaration of the same template. Default template
2657
/// arguments will be merged from the old template parameter list to
2658
/// the new template parameter list.
2659
///
2660
/// \param TPC Describes the context in which we are checking the given
2661
/// template parameter list.
2662
///
2663
/// \param SkipBody If we might have already made a prior merged definition
2664
/// of this template visible, the corresponding body-skipping information.
2665
/// Default argument redefinition is not an error when skipping such a body,
2666
/// because (under the ODR) we can assume the default arguments are the same
2667
/// as the prior merged definition.
2668
///
2669
/// \returns true if an error occurred, false otherwise.
2670
bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2671
                                      TemplateParameterList *OldParams,
2672
                                      TemplateParamListContext TPC,
2673
1.19M
                                      SkipBodyInfo *SkipBody) {
2674
1.19M
  bool Invalid = false;
2675
2676
  // C++ [temp.param]p10:
2677
  //   The set of default template-arguments available for use with a
2678
  //   template declaration or definition is obtained by merging the
2679
  //   default arguments from the definition (if in scope) and all
2680
  //   declarations in scope in the same way default function
2681
  //   arguments are (8.3.6).
2682
1.19M
  bool SawDefaultArgument = false;
2683
1.19M
  SourceLocation PreviousDefaultArgLoc;
2684
2685
  // Dummy initialization to avoid warnings.
2686
1.19M
  TemplateParameterList::iterator OldParam = NewParams->end();
2687
1.19M
  if (OldParams)
2688
80.4k
    OldParam = OldParams->begin();
2689
2690
1.19M
  bool RemoveDefaultArguments = false;
2691
1.19M
  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2692
1.19M
                                    NewParamEnd = NewParams->end();
2693
3.42M
       NewParam != NewParamEnd; 
++NewParam2.23M
) {
2694
    // Variables used to diagnose redundant default arguments
2695
2.23M
    bool RedundantDefaultArg = false;
2696
2.23M
    SourceLocation OldDefaultLoc;
2697
2.23M
    SourceLocation NewDefaultLoc;
2698
2699
    // Variable used to diagnose missing default arguments
2700
2.23M
    bool MissingDefaultArg = false;
2701
2702
    // Variable used to diagnose non-final parameter packs
2703
2.23M
    bool SawParameterPack = false;
2704
2705
2.23M
    if (TemplateTypeParmDecl *NewTypeParm
2706
2.23M
          = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2707
      // Check the presence of a default argument here.
2708
2.03M
      if (NewTypeParm->hasDefaultArgument() &&
2709
2.03M
          DiagnoseDefaultTemplateArgument(*this, TPC,
2710
98.7k
                                          NewTypeParm->getLocation(),
2711
98.7k
               NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
2712
98.7k
                                                       .getSourceRange()))
2713
22
        NewTypeParm->removeDefaultArgument();
2714
2715
      // Merge default arguments for template type parameters.
2716
2.03M
      TemplateTypeParmDecl *OldTypeParm
2717
2.03M
          = OldParams? 
cast<TemplateTypeParmDecl>(*OldParam)127k
:
nullptr1.90M
;
2718
2.03M
      if (NewTypeParm->isParameterPack()) {
2719
103k
        assert(!NewTypeParm->hasDefaultArgument() &&
2720
103k
               "Parameter packs can't have a default argument!");
2721
0
        SawParameterPack = true;
2722
1.92M
      } else if (OldTypeParm && 
hasVisibleDefaultArgument(OldTypeParm)121k
&&
2723
1.92M
                 
NewTypeParm->hasDefaultArgument()18.0k
&&
2724
1.92M
                 
(3
!SkipBody3
||
!SkipBody->ShouldSkip3
)) {
2725
1
        OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2726
1
        NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2727
1
        SawDefaultArgument = true;
2728
1
        RedundantDefaultArg = true;
2729
1
        PreviousDefaultArgLoc = NewDefaultLoc;
2730
1.92M
      } else if (OldTypeParm && 
OldTypeParm->hasDefaultArgument()121k
) {
2731
        // Merge the default argument from the old declaration to the
2732
        // new declaration.
2733
18.2k
        NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2734
18.2k
        PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2735
1.91M
      } else if (NewTypeParm->hasDefaultArgument()) {
2736
98.7k
        SawDefaultArgument = true;
2737
98.7k
        PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2738
1.81M
      } else if (SawDefaultArgument)
2739
86
        MissingDefaultArg = true;
2740
2.03M
    } else 
if (NonTypeTemplateParmDecl *204k
NewNonTypeParm204k
2741
204k
               = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2742
      // Check for unexpanded parameter packs.
2743
189k
      if (!NewNonTypeParm->isParameterPack() &&
2744
189k
          DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2745
180k
                                          NewNonTypeParm->getTypeSourceInfo(),
2746
180k
                                          UPPC_NonTypeTemplateParameterType)) {
2747
1
        Invalid = true;
2748
1
        continue;
2749
1
      }
2750
2751
      // Check the presence of a default argument here.
2752
189k
      if (NewNonTypeParm->hasDefaultArgument() &&
2753
189k
          DiagnoseDefaultTemplateArgument(*this, TPC,
2754
59.5k
                                          NewNonTypeParm->getLocation(),
2755
59.5k
                    NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
2756
1
        NewNonTypeParm->removeDefaultArgument();
2757
1
      }
2758
2759
      // Merge default arguments for non-type template parameters
2760
189k
      NonTypeTemplateParmDecl *OldNonTypeParm
2761
189k
        = OldParams? 
cast<NonTypeTemplateParmDecl>(*OldParam)16.3k
:
nullptr173k
;
2762
189k
      if (NewNonTypeParm->isParameterPack()) {
2763
9.82k
        assert(!NewNonTypeParm->hasDefaultArgument() &&
2764
9.82k
               "Parameter packs can't have a default argument!");
2765
9.82k
        if (!NewNonTypeParm->isPackExpansion())
2766
9.79k
          SawParameterPack = true;
2767
180k
      } else if (OldNonTypeParm && 
hasVisibleDefaultArgument(OldNonTypeParm)15.4k
&&
2768
180k
                 
NewNonTypeParm->hasDefaultArgument()791
&&
2769
180k
                 
(1
!SkipBody1
||
!SkipBody->ShouldSkip1
)) {
2770
1
        OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2771
1
        NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2772
1
        SawDefaultArgument = true;
2773
1
        RedundantDefaultArg = true;
2774
1
        PreviousDefaultArgLoc = NewDefaultLoc;
2775
180k
      } else if (OldNonTypeParm && 
OldNonTypeParm->hasDefaultArgument()15.4k
) {
2776
        // Merge the default argument from the old declaration to the
2777
        // new declaration.
2778
817
        NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2779
817
        PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2780
179k
      } else if (NewNonTypeParm->hasDefaultArgument()) {
2781
59.5k
        SawDefaultArgument = true;
2782
59.5k
        PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2783
119k
      } else if (SawDefaultArgument)
2784
7
        MissingDefaultArg = true;
2785
189k
    } else {
2786
14.5k
      TemplateTemplateParmDecl *NewTemplateParm
2787
14.5k
        = cast<TemplateTemplateParmDecl>(*NewParam);
2788
2789
      // Check for unexpanded parameter packs, recursively.
2790
14.5k
      if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2791
0
        Invalid = true;
2792
0
        continue;
2793
0
      }
2794
2795
      // Check the presence of a default argument here.
2796
14.5k
      if (NewTemplateParm->hasDefaultArgument() &&
2797
14.5k
          DiagnoseDefaultTemplateArgument(*this, TPC,
2798
8.63k
                                          NewTemplateParm->getLocation(),
2799
8.63k
                     NewTemplateParm->getDefaultArgument().getSourceRange()))
2800
1
        NewTemplateParm->removeDefaultArgument();
2801
2802
      // Merge default arguments for template template parameters
2803
14.5k
      TemplateTemplateParmDecl *OldTemplateParm
2804
14.5k
        = OldParams? 
cast<TemplateTemplateParmDecl>(*OldParam)76
:
nullptr14.5k
;
2805
14.5k
      if (NewTemplateParm->isParameterPack()) {
2806
89
        assert(!NewTemplateParm->hasDefaultArgument() &&
2807
89
               "Parameter packs can't have a default argument!");
2808
89
        if (!NewTemplateParm->isPackExpansion())
2809
80
          SawParameterPack = true;
2810
14.5k
      } else if (OldTemplateParm &&
2811
14.5k
                 
hasVisibleDefaultArgument(OldTemplateParm)76
&&
2812
14.5k
                 
NewTemplateParm->hasDefaultArgument()30
&&
2813
14.5k
                 
(1
!SkipBody1
||
!SkipBody->ShouldSkip1
)) {
2814
1
        OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2815
1
        NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2816
1
        SawDefaultArgument = true;
2817
1
        RedundantDefaultArg = true;
2818
1
        PreviousDefaultArgLoc = NewDefaultLoc;
2819
14.5k
      } else if (OldTemplateParm && 
OldTemplateParm->hasDefaultArgument()75
) {
2820
        // Merge the default argument from the old declaration to the
2821
        // new declaration.
2822
56
        NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2823
56
        PreviousDefaultArgLoc
2824
56
          = OldTemplateParm->getDefaultArgument().getLocation();
2825
14.4k
      } else if (NewTemplateParm->hasDefaultArgument()) {
2826
8.61k
        SawDefaultArgument = true;
2827
8.61k
        PreviousDefaultArgLoc
2828
8.61k
          = NewTemplateParm->getDefaultArgument().getLocation();
2829
8.61k
      } else 
if (5.83k
SawDefaultArgument5.83k
)
2830
5
        MissingDefaultArg = true;
2831
14.5k
    }
2832
2833
    // C++11 [temp.param]p11:
2834
    //   If a template parameter of a primary class template or alias template
2835
    //   is a template parameter pack, it shall be the last template parameter.
2836
2.23M
    if (SawParameterPack && 
(NewParam + 1) != NewParamEnd113k
&&
2837
2.23M
        
(24.3k
TPC == TPC_ClassTemplate24.3k
||
TPC == TPC_VarTemplate24.3k
||
2838
24.3k
         
TPC == TPC_TypeAliasTemplate24.3k
)) {
2839
7
      Diag((*NewParam)->getLocation(),
2840
7
           diag::err_template_param_pack_must_be_last_template_parameter);
2841
7
      Invalid = true;
2842
7
    }
2843
2844
2.23M
    if (RedundantDefaultArg) {
2845
      // C++ [temp.param]p12:
2846
      //   A template-parameter shall not be given default arguments
2847
      //   by two different declarations in the same scope.
2848
3
      Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2849
3
      Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2850
3
      Invalid = true;
2851
2.23M
    } else if (MissingDefaultArg && 
TPC != TPC_FunctionTemplate98
) {
2852
      // C++ [temp.param]p11:
2853
      //   If a template-parameter of a class template has a default
2854
      //   template-argument, each subsequent template-parameter shall either
2855
      //   have a default template-argument supplied or be a template parameter
2856
      //   pack.
2857
17
      Diag((*NewParam)->getLocation(),
2858
17
           diag::err_template_param_default_arg_missing);
2859
17
      Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2860
17
      Invalid = true;
2861
17
      RemoveDefaultArguments = true;
2862
17
    }
2863
2864
    // If we have an old template parameter list that we're merging
2865
    // in, move on to the next parameter.
2866
2.23M
    if (OldParams)
2867
144k
      ++OldParam;
2868
2.23M
  }
2869
2870
  // We were missing some default arguments at the end of the list, so remove
2871
  // all of the default arguments.
2872
1.19M
  if (RemoveDefaultArguments) {
2873
17
    for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2874
17
                                      NewParamEnd = NewParams->end();
2875
55
         NewParam != NewParamEnd; 
++NewParam38
) {
2876
38
      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2877
24
        TTP->removeDefaultArgument();
2878
14
      else if (NonTypeTemplateParmDecl *NTTP
2879
14
                                = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2880
8
        NTTP->removeDefaultArgument();
2881
6
      else
2882
6
        cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2883
38
    }
2884
17
  }
2885
2886
1.19M
  return Invalid;
2887
1.19M
}
2888
2889
namespace {
2890
2891
/// A class which looks for a use of a certain level of template
2892
/// parameter.
2893
struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2894
  typedef RecursiveASTVisitor<DependencyChecker> super;
2895
2896
  unsigned Depth;
2897
2898
  // Whether we're looking for a use of a template parameter that makes the
2899
  // overall construct type-dependent / a dependent type. This is strictly
2900
  // best-effort for now; we may fail to match at all for a dependent type
2901
  // in some cases if this is set.
2902
  bool IgnoreNonTypeDependent;
2903
2904
  bool Match;
2905
  SourceLocation MatchLoc;
2906
2907
  DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2908
      : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2909
18
        Match(false) {}
2910
2911
  DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2912
43
      : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2913
43
    NamedDecl *ND = Params->getParam(0);
2914
43
    if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2915
41
      Depth = PD->getDepth();
2916
41
    } else 
if (NonTypeTemplateParmDecl *2
PD2
=
2917
2
                 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2918
0
      Depth = PD->getDepth();
2919
2
    } else {
2920
2
      Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2921
2
    }
2922
43
  }
2923
2924
55
  bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2925
55
    if (ParmDepth >= Depth) {
2926
52
      Match = true;
2927
52
      MatchLoc = Loc;
2928
52
      return true;
2929
52
    }
2930
3
    return false;
2931
55
  }
2932
2933
35
  bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2934
    // Prune out non-type-dependent expressions if requested. This can
2935
    // sometimes result in us failing to find a template parameter reference
2936
    // (if a value-dependent expression creates a dependent type), but this
2937
    // mode is best-effort only.
2938
35
    if (auto *E = dyn_cast_or_null<Expr>(S))
2939
35
      if (IgnoreNonTypeDependent && 
!E->isTypeDependent()34
)
2940
16
        return true;
2941
19
    return super::TraverseStmt(S, Q);
2942
35
  }
2943
2944
36
  bool TraverseTypeLoc(TypeLoc TL) {
2945
36
    if (IgnoreNonTypeDependent && !TL.isNull() &&
2946
36
        !TL.getType()->isDependentType())
2947
6
      return true;
2948
30
    return super::TraverseTypeLoc(TL);
2949
36
  }
2950
2951
11
  bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2952
11
    return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2953
11
  }
2954
2955
41
  bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
2956
    // For a best-effort search, keep looking until we find a location.
2957
41
    return IgnoreNonTypeDependent || !Matches(T->getDepth());
2958
41
  }
2959
2960
45
  bool TraverseTemplateName(TemplateName N) {
2961
45
    if (TemplateTemplateParmDecl *PD =
2962
45
          dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2963
1
      if (Matches(PD->getDepth()))
2964
1
        return false;
2965
44
    return super::TraverseTemplateName(N);
2966
45
  }
2967
2968
2
  bool VisitDeclRefExpr(DeclRefExpr *E) {
2969
2
    if (NonTypeTemplateParmDecl *PD =
2970
2
          dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2971
2
      if (Matches(PD->getDepth(), E->getExprLoc()))
2972
1
        return false;
2973
1
    return super::VisitDeclRefExpr(E);
2974
2
  }
2975
2976
0
  bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2977
0
    return TraverseType(T->getReplacementType());
2978
0
  }
2979
2980
  bool
2981
0
  VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2982
0
    return TraverseTemplateArgument(T->getArgumentPack());
2983
0
  }
2984
2985
38
  bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2986
38
    return TraverseType(T->getInjectedSpecializationType());
2987
38
  }
2988
};
2989
} // end anonymous namespace
2990
2991
/// Determines whether a given type depends on the given parameter
2992
/// list.
2993
static bool
2994
43
DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2995
43
  if (!Params->size())
2996
0
    return false;
2997
2998
43
  DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2999
43
  Checker.TraverseType(T);
3000
43
  return Checker.Match;
3001
43
}
3002
3003
// Find the source range corresponding to the named type in the given
3004
// nested-name-specifier, if any.
3005
static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
3006
                                                       QualType T,
3007
56
                                                       const CXXScopeSpec &SS) {
3008
56
  NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
3009
66
  while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
3010
65
    if (const Type *CurType = NNS->getAsType()) {
3011
65
      if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
3012
55
        return NNSLoc.getTypeLoc().getSourceRange();
3013
65
    } else
3014
0
      break;
3015
3016
10
    NNSLoc = NNSLoc.getPrefix();
3017
10
  }
3018
3019
1
  return SourceRange();
3020
56
}
3021
3022
/// Match the given template parameter lists to the given scope
3023
/// specifier, returning the template parameter list that applies to the
3024
/// name.
3025
///
3026
/// \param DeclStartLoc the start of the declaration that has a scope
3027
/// specifier or a template parameter list.
3028
///
3029
/// \param DeclLoc The location of the declaration itself.
3030
///
3031
/// \param SS the scope specifier that will be matched to the given template
3032
/// parameter lists. This scope specifier precedes a qualified name that is
3033
/// being declared.
3034
///
3035
/// \param TemplateId The template-id following the scope specifier, if there
3036
/// is one. Used to check for a missing 'template<>'.
3037
///
3038
/// \param ParamLists the template parameter lists, from the outermost to the
3039
/// innermost template parameter lists.
3040
///
3041
/// \param IsFriend Whether to apply the slightly different rules for
3042
/// matching template parameters to scope specifiers in friend
3043
/// declarations.
3044
///
3045
/// \param IsMemberSpecialization will be set true if the scope specifier
3046
/// denotes a fully-specialized type, and therefore this is a declaration of
3047
/// a member specialization.
3048
///
3049
/// \returns the template parameter list, if any, that corresponds to the
3050
/// name that is preceded by the scope specifier @p SS. This template
3051
/// parameter list may have template parameters (if we're declaring a
3052
/// template) or may have no template parameters (if we're declaring a
3053
/// template specialization), or may be NULL (if what we're declaring isn't
3054
/// itself a template).
3055
TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
3056
    SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
3057
    TemplateIdAnnotation *TemplateId,
3058
    ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
3059
12.5M
    bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
3060
12.5M
  IsMemberSpecialization = false;
3061
12.5M
  Invalid = false;
3062
3063
  // The sequence of nested types to which we will match up the template
3064
  // parameter lists. We first build this list by starting with the type named
3065
  // by the nested-name-specifier and walking out until we run out of types.
3066
12.5M
  SmallVector<QualType, 4> NestedTypes;
3067
12.5M
  QualType T;
3068
12.5M
  if (SS.getScopeRep()) {
3069
364k
    if (CXXRecordDecl *Record
3070
364k
              = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
3071
363k
      T = Context.getTypeDeclType(Record);
3072
1.45k
    else
3073
1.45k
      T = QualType(SS.getScopeRep()->getAsType(), 0);
3074
364k
  }
3075
3076
  // If we found an explicit specialization that prevents us from needing
3077
  // 'template<>' headers, this will be set to the location of that
3078
  // explicit specialization.
3079
12.5M
  SourceLocation ExplicitSpecLoc;
3080
3081
12.8M
  while (!T.isNull()) {
3082
365k
    NestedTypes.push_back(T);
3083
3084
    // Retrieve the parent of a record type.
3085
365k
    if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3086
      // If this type is an explicit specialization, we're done.
3087
364k
      if (ClassTemplateSpecializationDecl *Spec
3088
364k
          = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3089
84.6k
        if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
3090
84.6k
            
Spec->getSpecializationKind() == TSK_ExplicitSpecialization12.0k
) {
3091
5.66k
          ExplicitSpecLoc = Spec->getLocation();
3092
5.66k
          break;
3093
5.66k
        }
3094
280k
      } else if (Record->getTemplateSpecializationKind()
3095
280k
                                                == TSK_ExplicitSpecialization) {
3096
8
        ExplicitSpecLoc = Record->getLocation();
3097
8
        break;
3098
8
      }
3099
3100
359k
      if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
3101
1.93k
        T = Context.getTypeDeclType(Parent);
3102
357k
      else
3103
357k
        T = QualType();
3104
359k
      continue;
3105
364k
    }
3106
3107
53
    if (const TemplateSpecializationType *TST
3108
53
                                     = T->getAs<TemplateSpecializationType>()) {
3109
29
      if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
3110
29
        if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
3111
16
          T = Context.getTypeDeclType(Parent);
3112
13
        else
3113
13
          T = QualType();
3114
29
        continue;
3115
29
      }
3116
29
    }
3117
3118
    // Look one step prior in a dependent template specialization type.
3119
24
    if (const DependentTemplateSpecializationType *DependentTST
3120
24
                          = T->getAs<DependentTemplateSpecializationType>()) {
3121
0
      if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
3122
0
        T = QualType(NNS->getAsType(), 0);
3123
0
      else
3124
0
        T = QualType();
3125
0
      continue;
3126
0
    }
3127
3128
    // Look one step prior in a dependent name type.
3129
24
    if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
3130
0
      if (NestedNameSpecifier *NNS = DependentName->getQualifier())
3131
0
        T = QualType(NNS->getAsType(), 0);
3132
0
      else
3133
0
        T = QualType();
3134
0
      continue;
3135
0
    }
3136
3137
    // Retrieve the parent of an enumeration type.
3138
24
    if (const EnumType *EnumT = T->getAs<EnumType>()) {
3139
      // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
3140
      // check here.
3141
4
      EnumDecl *Enum = EnumT->getDecl();
3142
3143
      // Get to the parent type.
3144
4
      if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
3145
0
        T = Context.getTypeDeclType(Parent);
3146
4
      else
3147
4
        T = QualType();
3148
4
      continue;
3149
4
    }
3150
3151
20
    T = QualType();
3152
20
  }
3153
  // Reverse the nested types list, since we want to traverse from the outermost
3154
  // to the innermost while checking template-parameter-lists.
3155
12.5M
  std::reverse(NestedTypes.begin(), NestedTypes.end());
3156
3157
  // C++0x [temp.expl.spec]p17:
3158
  //   A member or a member template may be nested within many
3159
  //   enclosing class templates. In an explicit specialization for
3160
  //   such a member, the member declaration shall be preceded by a
3161
  //   template<> for each enclosing class template that is
3162
  //   explicitly specialized.
3163
12.5M
  bool SawNonEmptyTemplateParameterList = false;
3164
3165
12.5M
  auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
3166
68.9k
    if (SawNonEmptyTemplateParameterList) {
3167
19
      if (!SuppressDiagnostic)
3168
4
        Diag(DeclLoc, diag::err_specialize_member_of_template)
3169
4
          << !Recovery << Range;
3170
19
      Invalid = true;
3171
19
      IsMemberSpecialization = false;
3172
19
      return true;
3173
19
    }
3174
3175
68.8k
    return false;
3176
68.9k
  };
3177
3178
12.5M
  auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
3179
    // Check that we can have an explicit specialization here.
3180
60
    if (CheckExplicitSpecialization(Range, true))
3181
3
      return true;
3182
3183
    // We don't have a template header, but we should.
3184
57
    SourceLocation ExpectedTemplateLoc;
3185
57
    if (!ParamLists.empty())
3186
10
      ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
3187
47
    else
3188
47
      ExpectedTemplateLoc = DeclStartLoc;
3189
3190
57
    if (!SuppressDiagnostic)
3191
52
      Diag(DeclLoc, diag::err_template_spec_needs_header)
3192
52
        << Range
3193
52
        << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
3194
57
    return false;
3195
60
  };
3196
3197
12.5M
  unsigned ParamIdx = 0;
3198
12.8M
  for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
3199
12.5M
       
++TypeIdx364k
) {
3200
364k
    T = NestedTypes[TypeIdx];
3201
3202
    // Whether we expect a 'template<>' header.
3203
364k
    bool NeedEmptyTemplateHeader = false;
3204
3205
    // Whether we expect a template header with parameters.
3206
364k
    bool NeedNonemptyTemplateHeader = false;
3207
3208
    // For a dependent type, the set of template parameters that we
3209
    // expect to see.
3210
364k
    TemplateParameterList *ExpectedTemplateParams = nullptr;
3211
3212
    // C++0x [temp.expl.spec]p15:
3213
    //   A member or a member template may be nested within many enclosing
3214
    //   class templates. In an explicit specialization for such a member, the
3215
    //   member declaration shall be preceded by a template<> for each
3216
    //   enclosing class template that is explicitly specialized.
3217
364k
    if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3218
364k
      if (ClassTemplatePartialSpecializationDecl *Partial
3219
364k
            = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
3220
72.5k
        ExpectedTemplateParams = Partial->getTemplateParameters();
3221
72.5k
        NeedNonemptyTemplateHeader = true;
3222
292k
      } else if (Record->isDependentType()) {
3223
262k
        if (Record->getDescribedClassTemplate()) {
3224
261k
          ExpectedTemplateParams = Record->getDescribedClassTemplate()
3225
261k
                                                      ->getTemplateParameters();
3226
261k
          NeedNonemptyTemplateHeader = true;
3227
261k
        }
3228
262k
      } else 
if (ClassTemplateSpecializationDecl *29.5k
Spec29.5k
3229
29.5k
                     = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3230
        // C++0x [temp.expl.spec]p4:
3231
        //   Members of an explicitly specialized class template are defined
3232
        //   in the same manner as members of normal classes, and not using
3233
        //   the template<> syntax.
3234
12.0k
        if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3235
6.38k
          NeedEmptyTemplateHeader = true;
3236
5.66k
        else
3237
5.66k
          continue;
3238
17.5k
      } else if (Record->getTemplateSpecializationKind()) {
3239
9
        if (Record->getTemplateSpecializationKind()
3240
9
                                                != TSK_ExplicitSpecialization &&
3241
9
            
TypeIdx == NumTypes - 11
)
3242
1
          IsMemberSpecialization = true;
3243
3244
9
        continue;
3245
9
      }
3246
364k
    } else 
if (const TemplateSpecializationType *53
TST53
3247
53
                                     = T->getAs<TemplateSpecializationType>()) {
3248
29
      if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
3249
29
        ExpectedTemplateParams = Template->getTemplateParameters();
3250
29
        NeedNonemptyTemplateHeader = true;
3251
29
      }
3252
29
    } else 
if (24
T->getAs<DependentTemplateSpecializationType>()24
) {
3253
      // FIXME:  We actually could/should check the template arguments here
3254
      // against the corresponding template parameter list.
3255
0
      NeedNonemptyTemplateHeader = false;
3256
0
    }
3257
3258
    // C++ [temp.expl.spec]p16:
3259
    //   In an explicit specialization declaration for a member of a class
3260
    //   template or a member template that ap- pears in namespace scope, the
3261
    //   member template and some of its enclosing class templates may remain
3262
    //   unspecialized, except that the declaration shall not explicitly
3263
    //   specialize a class member template if its en- closing class templates
3264
    //   are not explicitly specialized as well.
3265
359k
    if (ParamIdx < ParamLists.size()) {
3266
347k
      if (ParamLists[ParamIdx]->size() == 0) {
3267
7.32k
        if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3268
7.32k
                                        false))
3269
14
          return nullptr;
3270
7.32k
      } else
3271
340k
        SawNonEmptyTemplateParameterList = true;
3272
347k
    }
3273
3274
359k
    if (NeedEmptyTemplateHeader) {
3275
      // If we're on the last of the types, and we need a 'template<>' header
3276
      // here, then it's a member specialization.
3277
6.38k
      if (TypeIdx == NumTypes - 1)
3278
6.25k
        IsMemberSpecialization = true;
3279
3280
6.38k
      if (ParamIdx < ParamLists.size()) {
3281
6.30k
        if (ParamLists[ParamIdx]->size() > 0) {
3282
          // The header has template parameters when it shouldn't. Complain.
3283
39
          if (!SuppressDiagnostic)
3284
22
            Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3285
22
                 diag::err_template_param_list_matches_nontemplate)
3286
22
              << T
3287
22
              << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3288
22
                             ParamLists[ParamIdx]->getRAngleLoc())
3289
22
              << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3290
39
          Invalid = true;
3291
39
          return nullptr;
3292
39
        }
3293
3294
        // Consume this template header.
3295
6.26k
        ++ParamIdx;
3296
6.26k
        continue;
3297
6.30k
      }
3298
3299
75
      if (!IsFriend)
3300
33
        if (DiagnoseMissingExplicitSpecialization(
3301
33
                getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
3302
0
          return nullptr;
3303
3304
75
      continue;
3305
75
    }
3306
3307
352k
    if (NeedNonemptyTemplateHeader) {
3308
      // In friend declarations we can have template-ids which don't
3309
      // depend on the corresponding template parameter lists.  But
3310
      // assume that empty parameter lists are supposed to match this
3311
      // template-id.
3312
333k
      if (IsFriend && 
T->isDependentType()55
) {
3313
55
        if (ParamIdx < ParamLists.size() &&
3314
55
            
DependsOnTemplateParameters(T, ParamLists[ParamIdx])43
)
3315
40
          ExpectedTemplateParams = nullptr;
3316
15
        else
3317
15
          continue;
3318
55
      }
3319
3320
333k
      if (ParamIdx < ParamLists.size()) {
3321
        // Check the template parameter list, if we can.
3322
333k
        if (ExpectedTemplateParams &&
3323
333k
            !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
3324
333k
                                            ExpectedTemplateParams,
3325
333k
                                            !SuppressDiagnostic, TPL_TemplateMatch))
3326
4
          Invalid = true;
3327
3328
333k
        if (!Invalid &&
3329
333k
            CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3330
333k
                                       TPC_ClassTemplateMember))
3331
0
          Invalid = true;
3332
3333
333k
        ++ParamIdx;
3334
333k
        continue;
3335
333k
      }
3336
3337
3
      if (!SuppressDiagnostic)
3338
1
        Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3339
1
          << T
3340
1
          << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3341
3
      Invalid = true;
3342
3
      continue;
3343
333k
    }
3344
352k
  }
3345
3346
  // If there were at least as many template-ids as there were template
3347
  // parameter lists, then there are no template parameter lists remaining for
3348
  // the declaration itself.
3349
12.5M
  if (ParamIdx >= ParamLists.size()) {
3350
10.9M
    if (TemplateId && 
!IsFriend1.61k
) {
3351
      // We don't have a template header for the declaration itself, but we
3352
      // should.
3353
27
      DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3354
27
                                                        TemplateId->RAngleLoc));
3355
3356
      // Fabricate an empty template parameter list for the invented header.
3357
27
      return TemplateParameterList::Create(Context, SourceLocation(),
3358
27
                                           SourceLocation(), None,
3359
27
                                           SourceLocation(), nullptr);
3360
27
    }
3361
3362
10.9M
    return nullptr;
3363
10.9M
  }
3364
3365
  // If there were too many template parameter lists, complain about that now.
3366
1.57M
  if (ParamIdx < ParamLists.size() - 1) {
3367
20
    bool HasAnyExplicitSpecHeader = false;
3368
20
    bool AllExplicitSpecHeaders = true;
3369
40
    for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; 
++I20
) {
3370
20
      if (ParamLists[I]->size() == 0)
3371
15
        HasAnyExplicitSpecHeader = true;
3372
5
      else
3373
5
        AllExplicitSpecHeaders = false;
3374
20
    }
3375
3376
20
    if (!SuppressDiagnostic)
3377
14
      Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3378
14
           AllExplicitSpecHeaders ? 
diag::warn_template_spec_extra_headers11
3379
14
                                  : 
diag::err_template_spec_extra_headers3
)
3380
14
          << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3381
14
                         ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3382
3383
    // If there was a specialization somewhere, such that 'template<>' is
3384
    // not required, and there were any 'template<>' headers, note where the
3385
    // specialization occurred.
3386
20
    if (ExplicitSpecLoc.isValid() && 
HasAnyExplicitSpecHeader15
&&
3387
20
        
!SuppressDiagnostic15
)
3388
11
      Diag(ExplicitSpecLoc,
3389
11
           diag::note_explicit_template_spec_does_not_need_header)
3390
11
        << NestedTypes.back();
3391
3392
    // We have a template parameter list with no corresponding scope, which
3393
    // means that the resulting template declaration can't be instantiated
3394
    // properly (we'll end up with dependent nodes when we shouldn't).
3395
20
    if (!AllExplicitSpecHeaders)
3396
5
      Invalid = true;
3397
20
  }
3398
3399
  // C++ [temp.expl.spec]p16:
3400
  //   In an explicit specialization declaration for a member of a class
3401
  //   template or a member template that ap- pears in namespace scope, the
3402
  //   member template and some of its enclosing class templates may remain
3403
  //   unspecialized, except that the declaration shall not explicitly
3404
  //   specialize a class member template if its en- closing class templates
3405
  //   are not explicitly specialized as well.
3406
1.57M
  if (ParamLists.back()->size() == 0 &&
3407
1.57M
      CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3408
61.5k
                                  false))
3409
2
    return nullptr;
3410
3411
  // Return the last template parameter list, which corresponds to the
3412
  // entity being declared.
3413
1.57M
  return ParamLists.back();
3414
1.57M
}
3415
3416
43
void Sema::NoteAllFoundTemplates(TemplateName Name) {
3417
43
  if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3418
28
    Diag(Template->getLocation(), diag::note_template_declared_here)
3419
28
        << (isa<FunctionTemplateDecl>(Template)
3420
28
                ? 
06
3421
28
                : 
isa<ClassTemplateDecl>(Template)22
3422
22
                      ? 
10
3423
22
                      : isa<VarTemplateDecl>(Template)
3424
22
                            ? 
220
3425
22
                            : 
isa<TypeAliasTemplateDecl>(Template)2
?
32
:
40
)
3426
28
        << Template->getDeclName();
3427
28
    return;
3428
28
  }
3429
3430
15
  if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3431
3
    for (OverloadedTemplateStorage::iterator I = OST->begin(),
3432
3
                                          IEnd = OST->end();
3433
9
         I != IEnd; 
++I6
)
3434
6
      Diag((*I)->getLocation(), diag::note_template_declared_here)
3435
6
        << 0 << (*I)->getDeclName();
3436
3437
3
    return;
3438
3
  }
3439
15
}
3440
3441
static QualType
3442
checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
3443
                           const SmallVectorImpl<TemplateArgument> &Converted,
3444
                           SourceLocation TemplateLoc,
3445
1.81k
                           TemplateArgumentListInfo &TemplateArgs) {
3446
1.81k
  ASTContext &Context = SemaRef.getASTContext();
3447
1.81k
  switch (BTD->getBuiltinTemplateKind()) {
3448
1.06k
  case BTK__make_integer_seq: {
3449
    // Specializations of __make_integer_seq<S, T, N> are treated like
3450
    // S<T, 0, ..., N-1>.
3451
3452
    // C++14 [inteseq.intseq]p1:
3453
    //   T shall be an integer type.
3454
1.06k
    if (!Converted[1].getAsType()->isIntegralType(Context)) {
3455
1
      SemaRef.Diag(TemplateArgs[1].getLocation(),
3456
1
                   diag::err_integer_sequence_integral_element_type);
3457
1
      return QualType();
3458
1
    }
3459
3460
    // C++14 [inteseq.make]p1:
3461
    //   If N is negative the program is ill-formed.
3462
1.06k
    TemplateArgument NumArgsArg = Converted[2];
3463
1.06k
    llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
3464
1.06k
    if (NumArgs < 0) {
3465
1
      SemaRef.Diag(TemplateArgs[2].getLocation(),
3466
1
                   diag::err_integer_sequence_negative_length);
3467
1
      return QualType();
3468
1
    }
3469
3470
1.06k
    QualType ArgTy = NumArgsArg.getIntegralType();
3471
1.06k
    TemplateArgumentListInfo SyntheticTemplateArgs;
3472
    // The type argument gets reused as the first template argument in the
3473
    // synthetic template argument list.
3474
1.06k
    SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
3475
    // Expand N into 0 ... N-1.
3476
1.06k
    for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3477
18.3k
         I < NumArgs; 
++I17.2k
) {
3478
17.2k
      TemplateArgument TA(Context, I, ArgTy);
3479
17.2k
      SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3480
17.2k
          TA, ArgTy, TemplateArgs[2].getLocation()));
3481
17.2k
    }
3482
    // The first template argument will be reused as the template decl that
3483
    // our synthetic template arguments will be applied to.
3484
1.06k
    return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3485
1.06k
                                       TemplateLoc, SyntheticTemplateArgs);
3486
1.06k
  }
3487
3488
751
  case BTK__type_pack_element:
3489
    // Specializations of
3490
    //    __type_pack_element<Index, T_1, ..., T_N>
3491
    // are treated like T_Index.
3492
751
    assert(Converted.size() == 2 &&
3493
751
      "__type_pack_element should be given an index and a parameter pack");
3494
3495
    // If the Index is out of bounds, the program is ill-formed.
3496
0
    TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3497
751
    llvm::APSInt Index = IndexArg.getAsIntegral();
3498
751
    assert(Index >= 0 && "the index used with __type_pack_element should be of "
3499
751
                         "type std::size_t, and hence be non-negative");
3500
751
    if (Index >= Ts.pack_size()) {
3501
1
      SemaRef.Diag(TemplateArgs[0].getLocation(),
3502
1
                   diag::err_type_pack_element_out_of_bounds);
3503
1
      return QualType();
3504
1
    }
3505
3506
    // We simply return the type at index `Index`.
3507
750
    auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
3508
750
    return Nth->getAsType();
3509
1.81k
  }
3510
0
  llvm_unreachable("unexpected BuiltinTemplateDecl!");
3511
0
}
3512
3513
/// Determine whether this alias template is "enable_if_t".
3514
/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3515
33.8k
static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3516
33.8k
  return AliasTemplate->getName().equals("enable_if_t") ||
3517
33.8k
         
AliasTemplate->getName().equals("__enable_if_t")33.7k
;
3518
33.8k
}
3519
3520
/// Collect all of the separable terms in the given condition, which
3521
/// might be a conjunction.
3522
///
3523
/// FIXME: The right answer is to convert the logical expression into
3524
/// disjunctive normal form, so we can find the first failed term
3525
/// within each possible clause.
3526
static void collectConjunctionTerms(Expr *Clause,
3527
137k
                                    SmallVectorImpl<Expr *> &Terms) {
3528
137k
  if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3529
37.3k
    if (BinOp->getOpcode() == BO_LAnd) {
3530
29.3k
      collectConjunctionTerms(BinOp->getLHS(), Terms);
3531
29.3k
      collectConjunctionTerms(BinOp->getRHS(), Terms);
3532
29.3k
    }
3533
3534
37.3k
    return;
3535
37.3k
  }
3536
3537
100k
  Terms.push_back(Clause);
3538
100k
}
3539
3540
// The ranges-v3 library uses an odd pattern of a top-level "||" with
3541
// a left-hand side that is value-dependent but never true. Identify
3542
// the idiom and ignore that term.
3543
79.0k
static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3544
  // Top-level '||'.
3545
79.0k
  auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3546
79.0k
  if (!BinOp) 
return Cond54.6k
;
3547
3548
24.4k
  if (BinOp->getOpcode() != BO_LOr) 
return Cond24.4k
;
3549
3550
  // With an inner '==' that has a literal on the right-hand side.
3551
8
  Expr *LHS = BinOp->getLHS();
3552
8
  auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3553
8
  if (!InnerBinOp) 
return Cond2
;
3554
3555
6
  if (InnerBinOp->getOpcode() != BO_EQ ||
3556
6
      !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3557
0
    return Cond;
3558
3559
  // If the inner binary operation came from a macro expansion named
3560
  // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3561
  // of the '||', which is the real, user-provided condition.
3562
6
  SourceLocation Loc = InnerBinOp->getExprLoc();
3563
6
  if (!Loc.isMacroID()) 
return Cond3
;
3564
3565
3
  StringRef MacroName = PP.getImmediateMacroName(Loc);
3566
3
  if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3567
3
    return BinOp->getRHS();
3568
3569
0
  return Cond;
3570
3
}
3571
3572
namespace {
3573
3574
// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3575
// within failing boolean expression, such as substituting template parameters
3576
// for actual types.
3577
class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3578
public:
3579
  explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3580
79.0k
      : Policy(P) {}
3581
3582
151k
  bool handledStmt(Stmt *E, raw_ostream &OS) override {
3583
151k
    const auto *DR = dyn_cast<DeclRefExpr>(E);
3584
151k
    if (DR && 
DR->getQualifier()79.2k
) {
3585
      // If this is a qualified name, expand the template arguments in nested
3586
      // qualifiers.
3587
79.1k
      DR->getQualifier()->print(OS, Policy, true);
3588
      // Then print the decl itself.
3589
79.1k
      const ValueDecl *VD = DR->getDecl();
3590
79.1k
      OS << VD->getName();
3591
79.1k
      if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3592
        // This is a template variable, print the expanded template arguments.
3593
4
        printTemplateArgumentList(
3594
4
            OS, IV->getTemplateArgs().asArray(), Policy,
3595
4
            IV->getSpecializedTemplate()->getTemplateParameters());
3596
4
      }
3597
79.1k
      return true;
3598
79.1k
    }
3599
71.8k
    return false;
3600
151k
  }
3601
3602
private:
3603
  const PrintingPolicy Policy;
3604
};
3605
3606
} // end anonymous namespace
3607
3608
std::pair<Expr *, std::string>
3609
79.0k
Sema::findFailedBooleanCondition(Expr *Cond) {
3610
79.0k
  Cond = lookThroughRangesV3Condition(PP, Cond);
3611
3612
  // Separate out all of the terms in a conjunction.
3613
79.0k
  SmallVector<Expr *, 4> Terms;
3614
79.0k
  collectConjunctionTerms(Cond, Terms);
3615
3616
  // Determine which term failed.
3617
79.0k
  Expr *FailedCond = nullptr;
3618
86.7k
  for (Expr *Term : Terms) {
3619
86.7k
    Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3620
3621
    // Literals are uninteresting.
3622
86.7k
    if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3623
86.7k
        
isa<IntegerLiteral>(TermAsWritten)86.7k
)
3624
56
      continue;
3625
3626
    // The initialization of the parameter from the argument is
3627
    // a constant-evaluated context.
3628
86.7k
    EnterExpressionEvaluationContext ConstantEvaluated(
3629
86.7k
      *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3630
3631
86.7k
    bool Succeeded;
3632
86.7k
    if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3633
86.7k
        !Succeeded) {
3634
78.8k
      FailedCond = TermAsWritten;
3635
78.8k
      break;
3636
78.8k
    }
3637
86.7k
  }
3638
79.0k
  if (!FailedCond)
3639
172
    FailedCond = Cond->IgnoreParenImpCasts();
3640
3641
79.0k
  std::string Description;
3642
79.0k
  {
3643
79.0k
    llvm::raw_string_ostream Out(Description);
3644
79.0k
    PrintingPolicy Policy = getPrintingPolicy();
3645
79.0k
    Policy.PrintCanonicalTypes = true;
3646
79.0k
    FailedBooleanConditionPrinterHelper Helper(Policy);
3647
79.0k
    FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3648
79.0k
  }
3649
79.0k
  return { FailedCond, Description };
3650
79.0k
}
3651
3652
QualType Sema::CheckTemplateIdType(TemplateName Name,
3653
                                   SourceLocation TemplateLoc,
3654
6.19M
                                   TemplateArgumentListInfo &TemplateArgs) {
3655
6.19M
  DependentTemplateName *DTN
3656
6.19M
    = Name.getUnderlying().getAsDependentTemplateName();
3657
6.19M
  if (DTN && 
DTN->isIdentifier()10
)
3658
    // When building a template-id where the template-name is dependent,
3659
    // assume the template is a type template. Either our assumption is
3660
    // correct, or the code is ill-formed and will be diagnosed when the
3661
    // dependent name is substituted.
3662
10
    return Context.getDependentTemplateSpecializationType(ETK_None,
3663
10
                                                          DTN->getQualifier(),
3664
10
                                                          DTN->getIdentifier(),
3665
10
                                                          TemplateArgs);
3666
3667
6.19M
  if (Name.getAsAssumedTemplateName() &&
3668
6.19M
      
resolveAssumedTemplateNameAsType(/*Scope*/nullptr, Name, TemplateLoc)0
)
3669
0
    return QualType();
3670
3671
6.19M
  TemplateDecl *Template = Name.getAsTemplateDecl();
3672
6.19M
  if (!Template || 
isa<FunctionTemplateDecl>(Template)6.19M
||
3673
6.19M
      
isa<VarTemplateDecl>(Template)6.19M
||
isa<ConceptDecl>(Template)6.19M
) {
3674
    // We might have a substituted template template parameter pack. If so,
3675
    // build a template specialization type for it.
3676
22
    if (Name.getAsSubstTemplateTemplateParmPack())
3677
2
      return Context.getTemplateSpecializationType(Name, TemplateArgs);
3678
3679
20
    Diag(TemplateLoc, diag::err_template_id_not_a_type)
3680
20
      << Name;
3681
20
    NoteAllFoundTemplates(Name);
3682
20
    return QualType();
3683
22
  }
3684
3685
  // Check that the template argument list is well-formed for this
3686
  // template.
3687
6.19M
  SmallVector<TemplateArgument, 4> Converted;
3688
6.19M
  if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3689
6.19M
                                false, Converted,
3690
6.19M
                                /*UpdateArgsWithConversion=*/true))
3691
2.20k
    return QualType();
3692
3693
6.19M
  QualType CanonType;
3694
3695
6.19M
  if (TypeAliasTemplateDecl *AliasTemplate =
3696
6.19M
          dyn_cast<TypeAliasTemplateDecl>(Template)) {
3697
3698
    // Find the canonical type for this type alias template specialization.
3699
761k
    TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3700
761k
    if (Pattern->isInvalidDecl())
3701
1
      return QualType();
3702
3703
761k
    TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
3704
761k
                                           Converted);
3705
3706
    // Only substitute for the innermost template argument list.
3707
761k
    MultiLevelTemplateArgumentList TemplateArgLists;
3708
761k
    TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
3709
761k
    TemplateArgLists.addOuterRetainedLevels(
3710
761k
        AliasTemplate->getTemplateParameters()->getDepth());
3711
3712
761k
    LocalInstantiationScope Scope(*this);
3713
761k
    InstantiatingTemplate Inst(*this, TemplateLoc, Template);
3714
761k
    if (Inst.isInvalid())
3715
70
      return QualType();
3716
3717
761k
    CanonType = SubstType(Pattern->getUnderlyingType(),
3718
761k
                          TemplateArgLists, AliasTemplate->getLocation(),
3719
761k
                          AliasTemplate->getDeclName());
3720
761k
    if (CanonType.isNull()) {
3721
      // If this was enable_if and we failed to find the nested type
3722
      // within enable_if in a SFINAE context, dig out the specific
3723
      // enable_if condition that failed and present that instead.
3724
33.8k
      if (isEnableIfAliasTemplate(AliasTemplate)) {
3725
28.6k
        if (auto DeductionInfo = isSFINAEContext()) {
3726
28.6k
          if (*DeductionInfo &&
3727
28.6k
              (*DeductionInfo)->hasSFINAEDiagnostic() &&
3728
28.6k
              (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3729
28.6k
                diag::err_typename_nested_not_found_enable_if &&
3730
28.6k
              TemplateArgs[0].getArgument().getKind()
3731
28.6k
                == TemplateArgument::Expression) {
3732
28.6k
            Expr *FailedCond;
3733
28.6k
            std::string FailedDescription;
3734
28.6k
            std::tie(FailedCond, FailedDescription) =
3735
28.6k
              findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3736
3737
            // Remove the old SFINAE diagnostic.
3738
28.6k
            PartialDiagnosticAt OldDiag =
3739
28.6k
              {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3740
28.6k
            (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3741
3742
            // Add a new SFINAE diagnostic specifying which condition
3743
            // failed.
3744
28.6k
            (*DeductionInfo)->addSFINAEDiagnostic(
3745
28.6k
              OldDiag.first,
3746
28.6k
              PDiag(diag::err_typename_nested_not_found_requirement)
3747
28.6k
                << FailedDescription
3748
28.6k
                << FailedCond->getSourceRange());
3749
28.6k
          }
3750
28.6k
        }
3751
28.6k
      }
3752
3753
33.8k
      return QualType();
3754
33.8k
    }
3755
5.43M
  } else if (Name.isDependent() ||
3756
5.43M
             TemplateSpecializationType::anyDependentTemplateArguments(
3757
5.37M
                 TemplateArgs, Converted)) {
3758
    // This class template specialization is a dependent
3759
    // type. Therefore, its canonical type is another class template
3760
    // specialization type that contains all of the converted
3761
    // arguments in canonical form. This ensures that, e.g., A<T> and
3762
    // A<T, T> have identical types when A is declared as:
3763
    //
3764
    //   template<typename T, typename U = T> struct A;
3765
3.22M
    CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
3766
3767
    // This might work out to be a current instantiation, in which
3768
    // case the canonical type needs to be the InjectedClassNameType.
3769
    //
3770
    // TODO: in theory this could be a simple hashtable lookup; most
3771
    // changes to CurContext don't change the set of current
3772
    // instantiations.
3773
3.22M
    if (isa<ClassTemplateDecl>(Template)) {
3774
5.22M
      for (DeclContext *Ctx = CurContext; Ctx; 
Ctx = Ctx->getLookupParent()2.04M
) {
3775
        // If we get out to a namespace, we're done.
3776
5.22M
        if (Ctx->isFileContext()) 
break2.90M
;
3777
3778
        // If this isn't a record, keep looking.
3779
2.32M
        CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3780
2.32M
        if (!Record) 
continue369k
;
3781
3782
        // Look for one of the two cases with InjectedClassNameTypes
3783
        // and check whether it's the same template.
3784
1.95M
        if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3785
1.95M
            
!Record->getDescribedClassTemplate()1.63M
)
3786
551k
          continue;
3787
3788
        // Fetch the injected class name type and check whether its
3789
        // injected type is equal to the type we just built.
3790
1.40M
        QualType ICNT = Context.getTypeDeclType(Record);
3791
1.40M
        QualType Injected = cast<InjectedClassNameType>(ICNT)
3792
1.40M
          ->getInjectedSpecializationType();
3793
3794
1.40M
        if (CanonType != Injected->getCanonicalTypeInternal())
3795
1.12M
          continue;
3796
3797
        // If so, the canonical type of this TST is the injected
3798
        // class name type of the record we just found.
3799
282k
        assert(ICNT.isCanonical());
3800
0
        CanonType = ICNT;
3801
282k
        break;
3802
1.40M
      }
3803
3.18M
    }
3804
3.22M
  } else 
if (ClassTemplateDecl *2.21M
ClassTemplate2.21M
3805
2.21M
               = dyn_cast<ClassTemplateDecl>(Template)) {
3806
    // Find the class template specialization declaration that
3807
    // corresponds to these arguments.
3808
2.20M
    void *InsertPos = nullptr;
3809
2.20M
    ClassTemplateSpecializationDecl *Decl
3810
2.20M
      = ClassTemplate->findSpecialization(Converted, InsertPos);
3811
2.20M
    if (!Decl) {
3812
      // This is the first time we have referenced this class template
3813
      // specialization. Create the canonical declaration and add it to
3814
      // the set of specializations.
3815
819k
      Decl = ClassTemplateSpecializationDecl::Create(
3816
819k
          Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3817
819k
          ClassTemplate->getDeclContext(),
3818
819k
          ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3819
819k
          ClassTemplate->getLocation(), ClassTemplate, Converted, nullptr);
3820
819k
      ClassTemplate->AddSpecialization(Decl, InsertPos);
3821
819k
      if (ClassTemplate->isOutOfLine())
3822
47
        Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3823
819k
    }
3824
3825
2.20M
    if (Decl->getSpecializationKind() == TSK_Undeclared &&
3826
2.20M
        
ClassTemplate->getTemplatedDecl()->hasAttrs()915k
) {
3827
513k
      InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3828
513k
      if (!Inst.isInvalid()) {
3829
513k
        MultiLevelTemplateArgumentList TemplateArgLists;
3830
513k
        TemplateArgLists.addOuterTemplateArguments(Converted);
3831
513k
        InstantiateAttrsForDecl(TemplateArgLists,
3832
513k
                                ClassTemplate->getTemplatedDecl(), Decl);
3833
513k
      }
3834
513k
    }
3835
3836
    // Diagnose uses of this specialization.
3837
2.20M
    (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3838
3839
2.20M
    CanonType = Context.getTypeDeclType(Decl);
3840
2.20M
    assert(isa<RecordType>(CanonType) &&
3841
2.20M
           "type of non-dependent specialization is not a RecordType");
3842
2.20M
  } else 
if (auto *1.81k
BTD1.81k
= dyn_cast<BuiltinTemplateDecl>(Template)) {
3843
1.81k
    CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3844
1.81k
                                           TemplateArgs);
3845
1.81k
  }
3846
3847
  // Build the fully-sugared type for this class template
3848
  // specialization, which refers back to the class template
3849
  // specialization we created or found.
3850
6.16M
  return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
3851
6.19M
}
3852
3853
void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
3854
                                           TemplateNameKind &TNK,
3855
                                           SourceLocation NameLoc,
3856
18
                                           IdentifierInfo *&II) {
3857
18
  assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3858
3859
0
  TemplateName Name = ParsedName.get();
3860
18
  auto *ATN = Name.getAsAssumedTemplateName();
3861
18
  assert(ATN && "not an assumed template name");
3862
0
  II = ATN->getDeclName().getAsIdentifierInfo();
3863
3864
18
  if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3865
    // Resolved to a type template name.
3866
3
    ParsedName = TemplateTy::make(Name);
3867
3
    TNK = TNK_Type_template;
3868
3
  }
3869
18
}
3870
3871
bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
3872
                                            SourceLocation NameLoc,
3873
233
                                            bool Diagnose) {
3874
  // We assumed this undeclared identifier to be an (ADL-only) function
3875
  // template name, but it was used in a context where a type was required.
3876
  // Try to typo-correct it now.
3877
233
  AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
3878
233
  assert(ATN && "not an assumed template name");
3879
3880
0
  LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3881
233
  struct CandidateCallback : CorrectionCandidateCallback {
3882
233
    bool ValidateCandidate(const TypoCorrection &TC) override {
3883
46
      return TC.getCorrectionDecl() &&
3884
46
             
getAsTypeTemplateDecl(TC.getCorrectionDecl())45
;
3885
46
    }
3886
233
    std::unique_ptr<CorrectionCandidateCallback> clone() override {
3887
138
      return std::make_unique<CandidateCallback>(*this);
3888
138
    }
3889
233
  } FilterCCC;
3890
3891
233
  TypoCorrection Corrected =
3892
233
      CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
3893
233
                  FilterCCC, CTK_ErrorRecovery);
3894
233
  if (Corrected && 
Corrected.getFoundDecl()34
) {
3895
34
    diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3896
34
                                << ATN->getDeclName());
3897
34
    Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
3898
34
    return false;
3899
34
  }
3900
3901
199
  if (Diagnose)
3902
184
    Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3903
199
  return true;
3904
233
}
3905
3906
TypeResult Sema::ActOnTemplateIdType(
3907
    Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3908
    TemplateTy TemplateD, IdentifierInfo *TemplateII,
3909
    SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
3910
    ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
3911
1.22M
    bool IsCtorOrDtorName, bool IsClassName) {
3912
1.22M
  if (SS.isInvalid())
3913
0
    return true;
3914
3915
1.22M
  if (!IsCtorOrDtorName && 
!IsClassName1.22M
&&
SS.isSet()1.09M
) {
3916
28.2k
    DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3917
3918
    // C++ [temp.res]p3:
3919
    //   A qualified-id that refers to a type and in which the
3920
    //   nested-name-specifier depends on a template-parameter (14.6.2)
3921
    //   shall be prefixed by the keyword typename to indicate that the
3922
    //   qualified-id denotes a type, forming an
3923
    //   elaborated-type-specifier (7.1.5.3).
3924
28.2k
    if (!LookupCtx && 
isDependentScopeSpecifier(SS)7
) {
3925
7
      Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3926
7
        << SS.getScopeRep() << TemplateII->getName();
3927
      // Recover as if 'typename' were specified.
3928
      // FIXME: This is not quite correct recovery as we don't transform SS
3929
      // into the corresponding dependent form (and we don't diagnose missing
3930
      // 'template' keywords within SS as a result).
3931
7
      return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3932
7
                               TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3933
7
                               TemplateArgsIn, RAngleLoc);
3934
7
    }
3935
3936
    // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3937
    // it's not actually allowed to be used as a type in most cases. Because
3938
    // we annotate it before we know whether it's valid, we have to check for
3939
    // this case here.
3940
28.2k
    auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3941
28.2k
    if (LookupRD && 
LookupRD->getIdentifier() == TemplateII493
) {
3942
16
      Diag(TemplateIILoc,
3943
16
           TemplateKWLoc.isInvalid()
3944
16
               ? 
diag::err_out_of_line_qualified_id_type_names_constructor12
3945
16
               : 
diag::ext_out_of_line_qualified_id_type_names_constructor4
)
3946
16
        << TemplateII << 0 /*injected-class-name used as template name*/
3947
16
        << 1 /*if any keyword was present, it was 'template'*/;
3948
16
    }
3949
28.2k
  }
3950
3951
1.22M
  TemplateName Template = TemplateD.get();
3952
1.22M
  if (Template.getAsAssumedTemplateName() &&
3953
1.22M
      
resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc)182
)
3954
154
    return true;
3955
3956
  // Translate the parser's template argument list in our AST format.
3957
1.22M
  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3958
1.22M
  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3959
3960
1.22M
  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3961
60
    QualType T
3962
60
      = Context.getDependentTemplateSpecializationType(ETK_None,
3963
60
                                                       DTN->getQualifier(),
3964
60
                                                       DTN->getIdentifier(),
3965
60
                                                       TemplateArgs);
3966
    // Build type-source information.
3967
60
    TypeLocBuilder TLB;
3968
60
    DependentTemplateSpecializationTypeLoc SpecTL
3969
60
      = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3970
60
    SpecTL.setElaboratedKeywordLoc(SourceLocation());
3971
60
    SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3972
60
    SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3973
60
    SpecTL.setTemplateNameLoc(TemplateIILoc);
3974
60
    SpecTL.setLAngleLoc(LAngleLoc);
3975
60
    SpecTL.setRAngleLoc(RAngleLoc);
3976
120
    for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; 
++I60
)
3977
60
      SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3978
60
    return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3979
60
  }
3980
3981
1.22M
  QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3982
1.22M
  if (Result.isNull())
3983
1.11k
    return true;
3984
3985
  // Build type-source information.
3986
1.22M
  TypeLocBuilder TLB;
3987
1.22M
  TemplateSpecializationTypeLoc SpecTL
3988
1.22M
    = TLB.push<TemplateSpecializationTypeLoc>(Result);
3989
1.22M
  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3990
1.22M
  SpecTL.setTemplateNameLoc(TemplateIILoc);
3991
1.22M
  SpecTL.setLAngleLoc(LAngleLoc);
3992
1.22M
  SpecTL.setRAngleLoc(RAngleLoc);
3993
3.18M
  for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; 
++i1.96M
)
3994
1.96M
    SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3995
3996
  // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3997
  // constructor or destructor name (in such a case, the scope specifier
3998
  // will be attached to the enclosing Decl or Expr node).
3999
1.22M
  if (SS.isNotEmpty() && 
!IsCtorOrDtorName30.3k
) {
4000
    // Create an elaborated-type-specifier containing the nested-name-specifier.
4001
30.3k
    Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
4002
30.3k
    ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
4003
30.3k
    ElabTL.setElaboratedKeywordLoc(SourceLocation());
4004
30.3k
    ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
4005
30.3k
  }
4006
4007
1.22M
  return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
4008
1.22M
}
4009
4010
TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
4011
                                        TypeSpecifierType TagSpec,
4012
                                        SourceLocation TagLoc,
4013
                                        CXXScopeSpec &SS,
4014
                                        SourceLocation TemplateKWLoc,
4015
                                        TemplateTy TemplateD,
4016
                                        SourceLocation TemplateLoc,
4017
                                        SourceLocation LAngleLoc,
4018
                                        ASTTemplateArgsPtr TemplateArgsIn,
4019
4.72k
                                        SourceLocation RAngleLoc) {
4020
4.72k
  if (SS.isInvalid())
4021
0
    return TypeResult(true);
4022
4023
4.72k
  TemplateName Template = TemplateD.get();
4024
4025
  // Translate the parser's template argument list in our AST format.
4026
4.72k
  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4027
4.72k
  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4028
4029
  // Determine the tag kind
4030
4.72k
  TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4031
4.72k
  ElaboratedTypeKeyword Keyword
4032
4.72k
    = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
4033
4034
4.72k
  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4035
5
    QualType T = Context.getDependentTemplateSpecializationType(Keyword,
4036
5
                                                          DTN->getQualifier(),
4037
5
                                                          DTN->getIdentifier(),
4038
5
                                                                TemplateArgs);
4039
4040
    // Build type-source information.
4041
5
    TypeLocBuilder TLB;
4042
5
    DependentTemplateSpecializationTypeLoc SpecTL
4043
5
      = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
4044
5
    SpecTL.setElaboratedKeywordLoc(TagLoc);
4045
5
    SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
4046
5
    SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4047
5
    SpecTL.setTemplateNameLoc(TemplateLoc);
4048
5
    SpecTL.setLAngleLoc(LAngleLoc);
4049
5
    SpecTL.setRAngleLoc(RAngleLoc);
4050
10
    for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; 
++I5
)
4051
5
      SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
4052
5
    return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
4053
5
  }
4054
4055
4.71k
  if (TypeAliasTemplateDecl *TAT =
4056
4.71k
        dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
4057
    // C++0x [dcl.type.elab]p2:
4058
    //   If the identifier resolves to a typedef-name or the simple-template-id
4059
    //   resolves to an alias template specialization, the
4060
    //   elaborated-type-specifier is ill-formed.
4061
2
    Diag(TemplateLoc, diag::err_tag_reference_non_tag)
4062
2
        << TAT << NTK_TypeAliasTemplate << TagKind;
4063
2
    Diag(TAT->getLocation(), diag::note_declared_at);
4064
2
  }
4065
4066
4.71k
  QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
4067
4.71k
  if (Result.isNull())
4068
15
    return TypeResult(true);
4069
4070
  // Check the tag kind
4071
4.70k
  if (const RecordType *RT = Result->getAs<RecordType>()) {
4072
967
    RecordDecl *D = RT->getDecl();
4073
4074
967
    IdentifierInfo *Id = D->getIdentifier();
4075
967
    assert(Id && "templated class must have an identifier");
4076
4077
967
    if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
4078
967
                                      TagLoc, Id)) {
4079
4
      Diag(TagLoc, diag::err_use_with_wrong_tag)
4080
4
        << Result
4081
4
        << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
4082
4
      Diag(D->getLocation(), diag::note_previous_use);
4083
4
    }
4084
967
  }
4085
4086
  // Provide source-location information for the template specialization.
4087
0
  TypeLocBuilder TLB;
4088
4.70k
  TemplateSpecializationTypeLoc SpecTL
4089
4.70k
    = TLB.push<TemplateSpecializationTypeLoc>(Result);
4090
4.70k
  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4091
4.70k
  SpecTL.setTemplateNameLoc(TemplateLoc);
4092
4.70k
  SpecTL.setLAngleLoc(LAngleLoc);
4093
4.70k
  SpecTL.setRAngleLoc(RAngleLoc);
4094
11.1k
  for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; 
++i6.41k
)
4095
6.41k
    SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
4096
4097
  // Construct an elaborated type containing the nested-name-specifier (if any)
4098
  // and tag keyword.
4099
4.70k
  Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
4100
4.70k
  ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
4101
4.70k
  ElabTL.setElaboratedKeywordLoc(TagLoc);
4102
4.70k
  ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
4103
4.70k
  return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
4104
4.71k
}
4105
4106
static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4107
                                             NamedDecl *PrevDecl,
4108
                                             SourceLocation Loc,
4109
                                             bool IsPartialSpecialization);
4110
4111
static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
4112
4113
static bool isTemplateArgumentTemplateParameter(
4114
462
    const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
4115
462
  switch (Arg.getKind()) {
4116
0
  case TemplateArgument::Null:
4117
0
  case TemplateArgument::NullPtr:
4118
10
  case TemplateArgument::Integral:
4119
10
  case TemplateArgument::Declaration:
4120
10
  case TemplateArgument::Pack:
4121
10
  case TemplateArgument::TemplateExpansion:
4122
10
    return false;
4123
4124
442
  case TemplateArgument::Type: {
4125
442
    QualType Type = Arg.getAsType();
4126
442
    const TemplateTypeParmType *TPT =
4127
442
        Arg.getAsType()->getAs<TemplateTypeParmType>();
4128
442
    return TPT && 
!Type.hasQualifiers()143
&&
4129
442
           
TPT->getDepth() == Depth143
&&
TPT->getIndex() == Index141
;
4130
10
  }
4131
4132
8
  case TemplateArgument::Expression: {
4133
8
    DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4134
8
    if (!DRE || !DRE->getDecl())
4135
0
      return false;
4136
8
    const NonTypeTemplateParmDecl *NTTP =
4137
8
        dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4138
8
    return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4139
8
  }
4140
4141
2
  case TemplateArgument::Template:
4142
2
    const TemplateTemplateParmDecl *TTP =
4143
2
        dyn_cast_or_null<TemplateTemplateParmDecl>(
4144
2
            Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
4145
2
    return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4146
462
  }
4147
0
  llvm_unreachable("unexpected kind of template argument");
4148
0
}
4149
4150
static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
4151
368
                                    ArrayRef<TemplateArgument> Args) {
4152
368
  if (Params->size() != Args.size())
4153
6
    return false;
4154
4155
362
  unsigned Depth = Params->getDepth();
4156
4157
482
  for (unsigned I = 0, N = Args.size(); I != N; 
++I120
) {
4158
464
    TemplateArgument Arg = Args[I];
4159
4160
    // If the parameter is a pack expansion, the argument must be a pack
4161
    // whose only element is a pack expansion.
4162
464
    if (Params->getParam(I)->isParameterPack()) {
4163
5
      if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4164
5
          !Arg.pack_begin()->isPackExpansion())
4165
2
        return false;
4166
3
      Arg = Arg.pack_begin()->getPackExpansionPattern();
4167
3
    }
4168
4169
462
    if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4170
342
      return false;
4171
462
  }
4172
4173
18
  return true;
4174
362
}
4175
4176
template<typename PartialSpecDecl>
4177
158k
static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4178
158k
  if (Partial->getDeclContext()->isDependentContext())
4179
3.47k
    return;
4180
4181
  // FIXME: Get the TDK from deduction in order to provide better diagnostics
4182
  // for non-substitution-failure issues?
4183
155k
  TemplateDeductionInfo Info(Partial->getLocation());
4184
155k
  if (S.isMoreSpecializedThanPrimary(Partial, Info))
4185
154k
    return;
4186
4187
364
  auto *Template = Partial->getSpecializedTemplate();
4188
364
  S.Diag(Partial->getLocation(),
4189
364
         diag::ext_partial_spec_not_more_specialized_than_primary)
4190
364
      << isa<VarTemplateDecl>(Template);
4191
4192
364
  if (Info.hasSFINAEDiagnostic()) {
4193
3
    PartialDiagnosticAt Diag = {SourceLocation(),
4194
3
                                PartialDiagnostic::NullDiagnostic()};
4195
3
    Info.takeSFINAEDiagnostic(Diag);
4196
3
    SmallString<128> SFINAEArgString;
4197
3
    Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4198
3
    S.Diag(Diag.first,
4199
3
           diag::note_partial_spec_not_more_specialized_than_primary)
4200
3
      << SFINAEArgString;
4201
3
  }
4202
4203
364
  S.Diag(Template->getLocation(), diag::note_template_decl_here);
4204
364
  SmallVector<const Expr *, 3> PartialAC, TemplateAC;
4205
364
  Template->getAssociatedConstraints(TemplateAC);
4206
364
  Partial->getAssociatedConstraints(PartialAC);
4207
364
  S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
4208
364
                                                  TemplateAC);
4209
364
}
SemaTemplate.cpp:void checkMoreSpecializedThanPrimary<clang::ClassTemplatePartialSpecializationDecl>(clang::Sema&, clang::ClassTemplatePartialSpecializationDecl*)
Line
Count
Source
4177
158k
static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4178
158k
  if (Partial->getDeclContext()->isDependentContext())
4179
3.40k
    return;
4180
4181
  // FIXME: Get the TDK from deduction in order to provide better diagnostics
4182
  // for non-substitution-failure issues?
4183
154k
  TemplateDeductionInfo Info(Partial->getLocation());
4184
154k
  if (S.isMoreSpecializedThanPrimary(Partial, Info))
4185
154k
    return;
4186
4187
354
  auto *Template = Partial->getSpecializedTemplate();
4188
354
  S.Diag(Partial->getLocation(),
4189
354
         diag::ext_partial_spec_not_more_specialized_than_primary)
4190
354
      << isa<VarTemplateDecl>(Template);
4191
4192
354
  if (Info.hasSFINAEDiagnostic()) {
4193
3
    PartialDiagnosticAt Diag = {SourceLocation(),
4194
3
                                PartialDiagnostic::NullDiagnostic()};
4195
3
    Info.takeSFINAEDiagnostic(Diag);
4196
3
    SmallString<128> SFINAEArgString;
4197
3
    Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4198
3
    S.Diag(Diag.first,
4199
3
           diag::note_partial_spec_not_more_specialized_than_primary)
4200
3
      << SFINAEArgString;
4201
3
  }
4202
4203
354
  S.Diag(Template->getLocation(), diag::note_template_decl_here);
4204
354
  SmallVector<const Expr *, 3> PartialAC, TemplateAC;
4205
354
  Template->getAssociatedConstraints(TemplateAC);
4206
354
  Partial->getAssociatedConstraints(PartialAC);
4207
354
  S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
4208
354
                                                  TemplateAC);
4209
354
}
SemaTemplate.cpp:void checkMoreSpecializedThanPrimary<clang::VarTemplatePartialSpecializationDecl>(clang::Sema&, clang::VarTemplatePartialSpecializationDecl*)
Line
Count
Source
4177
398
static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4178
398
  if (Partial->getDeclContext()->isDependentContext())
4179
69
    return;
4180
4181
  // FIXME: Get the TDK from deduction in order to provide better diagnostics
4182
  // for non-substitution-failure issues?
4183
329
  TemplateDeductionInfo Info(Partial->getLocation());
4184
329
  if (S.isMoreSpecializedThanPrimary(Partial, Info))
4185
319
    return;
4186
4187
10
  auto *Template = Partial->getSpecializedTemplate();
4188
10
  S.Diag(Partial->getLocation(),
4189
10
         diag::ext_partial_spec_not_more_specialized_than_primary)
4190
10
      << isa<VarTemplateDecl>(Template);
4191
4192
10
  if (Info.hasSFINAEDiagnostic()) {
4193
0
    PartialDiagnosticAt Diag = {SourceLocation(),
4194
0
                                PartialDiagnostic::NullDiagnostic()};
4195
0
    Info.takeSFINAEDiagnostic(Diag);
4196
0
    SmallString<128> SFINAEArgString;
4197
0
    Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4198
0
    S.Diag(Diag.first,
4199
0
           diag::note_partial_spec_not_more_specialized_than_primary)
4200
0
      << SFINAEArgString;
4201
0
  }
4202
4203
10
  S.Diag(Template->getLocation(), diag::note_template_decl_here);
4204
10
  SmallVector<const Expr *, 3> PartialAC, TemplateAC;
4205
10
  Template->getAssociatedConstraints(TemplateAC);
4206
10
  Partial->getAssociatedConstraints(PartialAC);
4207
10
  S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
4208
10
                                                  TemplateAC);
4209
10
}
4210
4211
static void
4212
noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
4213
25
                           const llvm::SmallBitVector &DeducibleParams) {
4214
58
  for (unsigned I = 0, N = DeducibleParams.size(); I != N; 
++I33
) {
4215
33
    if (!DeducibleParams[I]) {
4216
27
      NamedDecl *Param = TemplateParams->getParam(I);
4217
27
      if (Param->getDeclName())
4218
26
        S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4219
26
            << Param->getDeclName();
4220
1
      else
4221
1
        S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4222
1
            << "(anonymous)";
4223
27
    }
4224
33
  }
4225
25
}
4226
4227
4228
template<typename PartialSpecDecl>
4229
static void checkTemplatePartialSpecialization(Sema &S,
4230
158k
                                               PartialSpecDecl *Partial) {
4231
  // C++1z [temp.class.spec]p8: (DR1495)
4232
  //   - The specialization shall be more specialized than the primary
4233
  //     template (14.5.5.2).
4234
158k
  checkMoreSpecializedThanPrimary(S, Partial);
4235
4236
  // C++ [temp.class.spec]p8: (DR1315)
4237
  //   - Each template-parameter shall appear at least once in the
4238
  //     template-id outside a non-deduced context.
4239
  // C++1z [temp.class.spec.match]p3 (P0127R2)
4240
  //   If the template arguments of a partial specialization cannot be
4241
  //   deduced because of the structure of its template-parameter-list
4242
  //   and the template-id, the program is ill-formed.
4243
158k
  auto *TemplateParams = Partial->getTemplateParameters();
4244
158k
  llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4245
158k
  S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4246
158k
                               TemplateParams->getDepth(), DeducibleParams);
4247
4248
158k
  if (!DeducibleParams.all()) {
4249
21
    unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4250
21
    S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4251
21
      << isa<VarTemplatePartialSpecializationDecl>(Partial)
4252
21
      << (NumNonDeducible > 1)
4253
21
      << SourceRange(Partial->getLocation(),
4254
21
                     Partial->getTemplateArgsAsWritten()->RAngleLoc);
4255
21
    noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4256
21
  }
4257
158k
}
SemaTemplate.cpp:void checkTemplatePartialSpecialization<clang::ClassTemplatePartialSpecializationDecl>(clang::Sema&, clang::ClassTemplatePartialSpecializationDecl*)
Line
Count
Source
4230
158k
                                               PartialSpecDecl *Partial) {
4231
  // C++1z [temp.class.spec]p8: (DR1495)
4232
  //   - The specialization shall be more specialized than the primary
4233
  //     template (14.5.5.2).
4234
158k
  checkMoreSpecializedThanPrimary(S, Partial);
4235
4236
  // C++ [temp.class.spec]p8: (DR1315)
4237
  //   - Each template-parameter shall appear at least once in the
4238
  //     template-id outside a non-deduced context.
4239
  // C++1z [temp.class.spec.match]p3 (P0127R2)
4240
  //   If the template arguments of a partial specialization cannot be
4241
  //   deduced because of the structure of its template-parameter-list
4242
  //   and the template-id, the program is ill-formed.
4243
158k
  auto *TemplateParams = Partial->getTemplateParameters();
4244
158k
  llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4245
158k
  S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4246
158k
                               TemplateParams->getDepth(), DeducibleParams);
4247
4248
158k
  if (!DeducibleParams.all()) {
4249
16
    unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4250
16
    S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4251
16
      << isa<VarTemplatePartialSpecializationDecl>(Partial)
4252
16
      << (NumNonDeducible > 1)
4253
16
      << SourceRange(Partial->getLocation(),
4254
16
                     Partial->getTemplateArgsAsWritten()->RAngleLoc);
4255
16
    noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4256
16
  }
4257
158k
}
SemaTemplate.cpp:void checkTemplatePartialSpecialization<clang::VarTemplatePartialSpecializationDecl>(clang::Sema&, clang::VarTemplatePartialSpecializationDecl*)
Line
Count
Source
4230
398
                                               PartialSpecDecl *Partial) {
4231
  // C++1z [temp.class.spec]p8: (DR1495)
4232
  //   - The specialization shall be more specialized than the primary
4233
  //     template (14.5.5.2).
4234
398
  checkMoreSpecializedThanPrimary(S, Partial);
4235
4236
  // C++ [temp.class.spec]p8: (DR1315)
4237
  //   - Each template-parameter shall appear at least once in the
4238
  //     template-id outside a non-deduced context.
4239
  // C++1z [temp.class.spec.match]p3 (P0127R2)
4240
  //   If the template arguments of a partial specialization cannot be
4241
  //   deduced because of the structure of its template-parameter-list
4242
  //   and the template-id, the program is ill-formed.
4243
398
  auto *TemplateParams = Partial->getTemplateParameters();
4244
398
  llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4245
398
  S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4246
398
                               TemplateParams->getDepth(), DeducibleParams);
4247
4248
398
  if (!DeducibleParams.all()) {
4249
5
    unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4250
5
    S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4251
5
      << isa<VarTemplatePartialSpecializationDecl>(Partial)
4252
5
      << (NumNonDeducible > 1)
4253
5
      << SourceRange(Partial->getLocation(),
4254
5
                     Partial->getTemplateArgsAsWritten()->RAngleLoc);
4255
5
    noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4256
5
  }
4257
398
}
4258
4259
void Sema::CheckTemplatePartialSpecialization(
4260
158k
    ClassTemplatePartialSpecializationDecl *Partial) {
4261
158k
  checkTemplatePartialSpecialization(*this, Partial);
4262
158k
}
4263
4264
void Sema::CheckTemplatePartialSpecialization(
4265
398
    VarTemplatePartialSpecializationDecl *Partial) {
4266
398
  checkTemplatePartialSpecialization(*this, Partial);
4267
398
}
4268
4269
303
void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
4270
  // C++1z [temp.param]p11:
4271
  //   A template parameter of a deduction guide template that does not have a
4272
  //   default-argument shall be deducible from the parameter-type-list of the
4273
  //   deduction guide template.
4274
303
  auto *TemplateParams = TD->getTemplateParameters();
4275
303
  llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4276
303
  MarkDeducedTemplateParameters(TD, DeducibleParams);
4277
1.22k
  for (unsigned I = 0; I != TemplateParams->size(); 
++I924
) {
4278
    // A parameter pack is deducible (to an empty pack).
4279
924
    auto *Param = TemplateParams->getParam(I);
4280
924
    if (Param->isParameterPack() || 
hasVisibleDefaultArgument(Param)895
)
4281
450
      DeducibleParams[I] = true;
4282
924
  }
4283
4284
303
  if (!DeducibleParams.all()) {
4285
4
    unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4286
4
    Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4287
4
      << (NumNonDeducible > 1);
4288
4
    noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4289
4
  }
4290
303
}
4291
4292
DeclResult Sema::ActOnVarTemplateSpecialization(
4293
    Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
4294
    TemplateParameterList *TemplateParams, StorageClass SC,
4295
911
    bool IsPartialSpecialization) {
4296
  // D must be variable template id.
4297
911
  assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
4298
911
         "Variable template specialization is declared with a template it.");
4299
4300
0
  TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4301
911
  TemplateArgumentListInfo TemplateArgs =
4302
911
      makeTemplateArgumentListInfo(*this, *TemplateId);
4303
911
  SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4304
911
  SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4305
911
  SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4306
4307
911
  TemplateName Name = TemplateId->Template.get();
4308
4309
  // The template-id must name a variable template.
4310
911
  VarTemplateDecl *VarTemplate =
4311
911
      dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4312
911
  if (!VarTemplate) {
4313
8
    NamedDecl *FnTemplate;
4314
8
    if (auto *OTS = Name.getAsOverloadedTemplate())
4315
3
      FnTemplate = *OTS->begin();
4316
5
    else
4317
5
      FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4318
8
    if (FnTemplate)
4319
6
      return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4320
6
               << FnTemplate->getDeclName();
4321
2
    return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4322
2
             << IsPartialSpecialization;
4323
8
  }
4324
4325
  // Check for unexpanded parameter packs in any of the template arguments.
4326
1.96k
  
for (unsigned I = 0, N = TemplateArgs.size(); 903
I != N;
++I1.06k
)
4327
1.06k
    if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4328
1.06k
                                        UPPC_PartialSpecialization))
4329
0
      return true;
4330
4331
  // Check that the template argument list is well-formed for this
4332
  // template.
4333
903
  SmallVector<TemplateArgument, 4> Converted;
4334
903
  if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4335
903
                                false, Converted,
4336
903
                                /*UpdateArgsWithConversion=*/true))
4337
0
    return true;
4338
4339
  // Find the variable template (partial) specialization declaration that
4340
  // corresponds to these arguments.
4341
903
  if (IsPartialSpecialization) {
4342
368
    if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
4343
368
                                               TemplateArgs.size(), Converted))
4344
0
      return true;
4345
4346
    // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
4347
    // also do them during instantiation.
4348
368
    if (!Name.isDependent() &&
4349
368
        !TemplateSpecializationType::anyDependentTemplateArguments(TemplateArgs,
4350
297
                                                                   Converted)) {
4351
0
      Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4352
0
          << VarTemplate->getDeclName();
4353
0
      IsPartialSpecialization = false;
4354
0
    }
4355
4356
368
    if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4357
368
                                Converted) &&
4358
368
        
(18
!Context.getLangOpts().CPlusPlus2018
||
4359
18
         
!TemplateParams->hasAssociatedConstraints()11
)) {
4360
      // C++ [temp.class.spec]p9b3:
4361
      //
4362
      //   -- The argument list of the specialization shall not be identical
4363
      //      to the implicit argument list of the primary template.
4364
9
      Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4365
9
        << /*variable template*/ 1
4366
9
        << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
4367
9
        << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4368
      // FIXME: Recover from this by treating the declaration as a redeclaration
4369
      // of the primary template.
4370
9
      return true;
4371
9
    }
4372
368
  }
4373
4374
894
  void *InsertPos = nullptr;
4375
894
  VarTemplateSpecializationDecl *PrevDecl = nullptr;
4376
4377
894
  if (IsPartialSpecialization)
4378
359
    PrevDecl = VarTemplate->findPartialSpecialization(Converted, TemplateParams,
4379
359
                                                      InsertPos);
4380
535
  else
4381
535
    PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
4382
4383
894
  VarTemplateSpecializationDecl *Specialization = nullptr;
4384
4385
  // Check whether we can declare a variable template specialization in
4386
  // the current scope.
4387
894
  if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4388
894
                                       TemplateNameLoc,
4389
894
                                       IsPartialSpecialization))
4390
20
    return true;
4391
4392
874
  if (PrevDecl && 
PrevDecl->getSpecializationKind() == TSK_Undeclared118
) {
4393
    // Since the only prior variable template specialization with these
4394
    // arguments was referenced but not declared,  reuse that
4395
    // declaration node as our own, updating its source location and
4396
    // the list of outer template parameters to reflect our new declaration.
4397
0
    Specialization = PrevDecl;
4398
0
    Specialization->setLocation(TemplateNameLoc);
4399
0
    PrevDecl = nullptr;
4400
874
  } else if (IsPartialSpecialization) {
4401
    // Create a new class template partial specialization declaration node.
4402
349
    VarTemplatePartialSpecializationDecl *PrevPartial =
4403
349
        cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4404
349
    VarTemplatePartialSpecializationDecl *Partial =
4405
349
        VarTemplatePartialSpecializationDecl::Create(
4406
349
            Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4407
349
            TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4408
349
            Converted, TemplateArgs);
4409
4410
349
    if (!PrevPartial)
4411
284
      VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4412
349
    Specialization = Partial;
4413
4414
    // If we are providing an explicit specialization of a member variable
4415
    // template specialization, make a note of that.
4416
349
    if (PrevPartial && 
PrevPartial->getInstantiatedFromMember()65
)
4417
21
      PrevPartial->setMemberSpecialization();
4418
4419
349
    CheckTemplatePartialSpecialization(Partial);
4420
525
  } else {
4421
    // Create a new class template specialization declaration node for
4422
    // this explicit specialization or friend declaration.
4423
525
    Specialization = VarTemplateSpecializationDecl::Create(
4424
525
        Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4425
525
        VarTemplate, DI->getType(), DI, SC, Converted);
4426
525
    Specialization->setTemplateArgsInfo(TemplateArgs);
4427
4428
525
    if (!PrevDecl)
4429
472
      VarTemplate->AddSpecialization(Specialization, InsertPos);
4430
525
  }
4431
4432
  // C++ [temp.expl.spec]p6:
4433
  //   If a template, a member template or the member of a class template is
4434
  //   explicitly specialized then that specialization shall be declared
4435
  //   before the first use of that specialization that would cause an implicit
4436
  //   instantiation to take place, in every translation unit in which such a
4437
  //   use occurs; no diagnostic is required.
4438
874
  if (PrevDecl && 
PrevDecl->getPointOfInstantiation().isValid()118
) {
4439
6
    bool Okay = false;
4440
12
    for (Decl *Prev = PrevDecl; Prev; 
Prev = Prev->getPreviousDecl()6
) {
4441
      // Is there any previous explicit specialization declaration?
4442
6
      if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4443
0
        Okay = true;
4444
0
        break;
4445
0
      }
4446
6
    }
4447
4448
6
    if (!Okay) {
4449
6
      SourceRange Range(TemplateNameLoc, RAngleLoc);
4450
6
      Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4451
6
          << Name << Range;
4452
4453
6
      Diag(PrevDecl->getPointOfInstantiation(),
4454
6
           diag::note_instantiation_required_here)
4455
6
          << (PrevDecl->getTemplateSpecializationKind() !=
4456
6
              TSK_ImplicitInstantiation);
4457
6
      return true;
4458
6
    }
4459
6
  }
4460
4461
868
  Specialization->setTemplateKeywordLoc(TemplateKWLoc);
4462
868
  Specialization->setLexicalDeclContext(CurContext);
4463
4464
  // Add the specialization into its lexical context, so that it can
4465
  // be seen when iterating through the list of declarations in that
4466
  // context. However, specializations are not found by name lookup.
4467
868
  CurContext->addDecl(Specialization);
4468
4469
  // Note that this is an explicit specialization.
4470
868
  Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4471
4472
868
  if (PrevDecl) {
4473
    // Check that this isn't a redefinition of this specialization,
4474
    // merging with previous declarations.
4475
112
    LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
4476
112
                          forRedeclarationInCurContext());
4477
112
    PrevSpec.addDecl(PrevDecl);
4478
112
    D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
4479
756
  } else if (Specialization->isStaticDataMember() &&
4480
756
             
Specialization->isOutOfLine()323
) {
4481
158
    Specialization->setAccess(VarTemplate->getAccess());
4482
158
  }
4483
4484
868
  return Specialization;
4485
874
}
4486
4487
namespace {
4488
/// A partial specialization whose template arguments have matched
4489
/// a given template-id.
4490
struct PartialSpecMatchResult {
4491
  VarTemplatePartialSpecializationDecl *Partial;
4492
  TemplateArgumentList *Args;
4493
};
4494
} // end anonymous namespace
4495
4496
DeclResult
4497
Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4498
                         SourceLocation TemplateNameLoc,
4499
3.98k
                         const TemplateArgumentListInfo &TemplateArgs) {
4500
3.98k
  assert(Template && "A variable template id without template?");
4501
4502
  // Check that the template argument list is well-formed for this template.
4503
0
  SmallVector<TemplateArgument, 4> Converted;
4504
3.98k
  if (CheckTemplateArgumentList(
4505
3.98k
          Template, TemplateNameLoc,
4506
3.98k
          const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
4507
3.98k
          Converted, /*UpdateArgsWithConversion=*/true))
4508
14
    return true;
4509
4510
  // Produce a placeholder value if the specialization is dependent.
4511
3.97k
  if (Template->getDeclContext()->isDependentContext() ||
4512
3.97k
      TemplateSpecializationType::anyDependentTemplateArguments(TemplateArgs,
4513
3.97k
                                                                Converted))
4514
1.00k
    return DeclResult();
4515
4516
  // Find the variable template specialization declaration that
4517
  // corresponds to these arguments.
4518
2.97k
  void *InsertPos = nullptr;
4519
2.97k
  if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
4520
2.97k
          Converted, InsertPos)) {
4521
817
    checkSpecializationVisibility(TemplateNameLoc, Spec);
4522
    // If we already have a variable template specialization, return it.
4523
817
    return Spec;
4524
817
  }
4525
4526
  // This is the first time we have referenced this variable template
4527
  // specialization. Create the canonical declaration and add it to
4528
  // the set of specializations, based on the closest partial specialization
4529
  // that it represents. That is,
4530
2.15k
  VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4531
2.15k
  TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
4532
2.15k
                                       Converted);
4533
2.15k
  TemplateArgumentList *InstantiationArgs = &TemplateArgList;
4534
2.15k
  bool AmbiguousPartialSpec = false;
4535
2.15k
  typedef PartialSpecMatchResult MatchResult;
4536
2.15k
  SmallVector<MatchResult, 4> Matched;
4537
2.15k
  SourceLocation PointOfInstantiation = TemplateNameLoc;
4538
2.15k
  TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4539
2.15k
                                            /*ForTakingAddress=*/false);
4540
4541
  // 1. Attempt to find the closest partial specialization that this
4542
  // specializes, if any.
4543
  // TODO: Unify with InstantiateClassTemplateSpecialization()?
4544
  //       Perhaps better after unification of DeduceTemplateArguments() and
4545
  //       getMoreSpecializedPartialSpecialization().
4546
2.15k
  SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4547
2.15k
  Template->getPartialSpecializations(PartialSpecs);
4548
4549
3.12k
  for (unsigned I = 0, N = PartialSpecs.size(); I != N; 
++I966
) {
4550
966
    VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
4551
966
    TemplateDeductionInfo Info(FailedCandidates.getLocation());
4552
4553
966
    if (TemplateDeductionResult Result =
4554
966
            DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
4555
      // Store the failed-deduction information for use in diagnostics, later.
4556
      // TODO: Actually use the failed-deduction info?
4557
184
      FailedCandidates.addCandidate().set(
4558
184
          DeclAccessPair::make(Template, AS_public), Partial,
4559
184
          MakeDeductionFailureInfo(Context, Result, Info));
4560
184
      (void)Result;
4561
782
    } else {
4562
782
      Matched.push_back(PartialSpecMatchResult());
4563
782
      Matched.back().Partial = Partial;
4564
782
      Matched.back().Args = Info.take();
4565
782
    }
4566
966
  }
4567
4568
2.15k
  if (Matched.size() >= 1) {
4569
770
    SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4570
770
    if (Matched.size() == 1) {
4571
      //   -- If exactly one matching specialization is found, the
4572
      //      instantiation is generated from that specialization.
4573
      // We don't need to do anything for this.
4574
758
    } else {
4575
      //   -- If more than one matching specialization is found, the
4576
      //      partial order rules (14.5.4.2) are used to determine
4577
      //      whether one of the specializations is more specialized
4578
      //      than the others. If none of the specializations is more
4579
      //      specialized than all of the other matching
4580
      //      specializations, then the use of the variable template is
4581
      //      ambiguous and the program is ill-formed.
4582
12
      for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4583
12
                                                 PEnd = Matched.end();
4584
24
           P != PEnd; 
++P12
) {
4585
12
        if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4586
12
                                                    PointOfInstantiation) ==
4587
12
            P->Partial)
4588
8
          Best = P;
4589
12
      }
4590
4591
      // Determine if the best partial specialization is more specialized than
4592
      // the others.
4593
12
      for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4594
12
                                                 PEnd = Matched.end();
4595
33
           P != PEnd; 
++P21
) {
4596
24
        if (P != Best && getMoreSpecializedPartialSpecialization(
4597
12
                             P->Partial, Best->Partial,
4598
12
                             PointOfInstantiation) != Best->Partial) {
4599
3
          AmbiguousPartialSpec = true;
4600
3
          break;
4601
3
        }
4602
24
      }
4603
12
    }
4604
4605
    // Instantiate using the best variable template partial specialization.
4606
770
    InstantiationPattern = Best->Partial;
4607
770
    InstantiationArgs = Best->Args;
4608
1.38k
  } else {
4609
    //   -- If no match is found, the instantiation is generated
4610
    //      from the primary template.
4611
    // InstantiationPattern = Template->getTemplatedDecl();
4612
1.38k
  }
4613
4614
  // 2. Create the canonical declaration.
4615
  // Note that we do not instantiate a definition until we see an odr-use
4616
  // in DoMarkVarDeclReferenced().
4617
  // FIXME: LateAttrs et al.?
4618
2.15k
  VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4619
2.15k
      Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
4620
2.15k
      Converted, TemplateNameLoc /*, LateAttrs, StartingScope*/);
4621
2.15k
  if (!Decl)
4622
0
    return true;
4623
4624
2.15k
  if (AmbiguousPartialSpec) {
4625
    // Partial ordering did not produce a clear winner. Complain.
4626
3
    Decl->setInvalidDecl();
4627
3
    Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4628
3
        << Decl;
4629
4630
    // Print the matching partial specializations.
4631
3
    for (MatchResult P : Matched)
4632
6
      Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4633
6
          << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4634
6
                                             *P.Args);
4635
3
    return true;
4636
3
  }
4637
4638
2.15k
  if (VarTemplatePartialSpecializationDecl *D =
4639
2.15k
          dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4640
767
    Decl->setInstantiationOf(D, InstantiationArgs);
4641
4642
2.15k
  checkSpecializationVisibility(TemplateNameLoc, Decl);
4643
4644
2.15k
  assert(Decl && "No variable template specialization?");
4645
0
  return Decl;
4646
2.15k
}
4647
4648
ExprResult
4649
Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
4650
                         const DeclarationNameInfo &NameInfo,
4651
                         VarTemplateDecl *Template, SourceLocation TemplateLoc,
4652
3.35k
                         const TemplateArgumentListInfo *TemplateArgs) {
4653
4654
3.35k
  DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4655
3.35k
                                       *TemplateArgs);
4656
3.35k
  if (Decl.isInvalid())
4657
16
    return ExprError();
4658
4659
3.33k
  if (!Decl.get())
4660
1.00k
    return ExprResult();
4661
4662
2.33k
  VarDecl *Var = cast<VarDecl>(Decl.get());
4663
2.33k
  if (!Var->getTemplateSpecializationKind())
4664
1.62k
    Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
4665
1.62k
                                       NameInfo.getLoc());
4666
4667
  // Build an ordinary singleton decl ref.
4668
2.33k
  return BuildDeclarationNameExpr(SS, NameInfo, Var,
4669
2.33k
                                  /*FoundD=*/nullptr, TemplateArgs);
4670
3.33k
}
4671
4672
void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4673
87
                                            SourceLocation Loc) {
4674
87
  Diag(Loc, diag::err_template_missing_args)
4675
87
    << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4676
87
  if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4677
87
    Diag(TD->getLocation(), diag::note_template_decl_here)
4678
87
      << TD->getTemplateParameters()->getSourceRange();
4679
87
  }
4680
87
}
4681
4682
ExprResult
4683
Sema::CheckConceptTemplateId(const CXXScopeSpec &SS,
4684
                             SourceLocation TemplateKWLoc,
4685
                             const DeclarationNameInfo &ConceptNameInfo,
4686
                             NamedDecl *FoundDecl,
4687
                             ConceptDecl *NamedConcept,
4688
929
                             const TemplateArgumentListInfo *TemplateArgs) {
4689
929
  assert(NamedConcept && "A concept template id without a template?");
4690
4691
0
  llvm::SmallVector<TemplateArgument, 4> Converted;
4692
929
  if (CheckTemplateArgumentList(NamedConcept, ConceptNameInfo.getLoc(),
4693
929
                           const_cast<TemplateArgumentListInfo&>(*TemplateArgs),
4694
929
                                /*PartialTemplateArgs=*/false, Converted,
4695
929
                                /*UpdateArgsWithConversion=*/false))
4696
3
    return ExprError();
4697
4698
926
  ConstraintSatisfaction Satisfaction;
4699
926
  bool AreArgsDependent =
4700
926
      TemplateSpecializationType::anyDependentTemplateArguments(*TemplateArgs,
4701
926
                                                                Converted);
4702
926
  if (!AreArgsDependent &&
4703
926
      CheckConstraintSatisfaction(
4704
544
          NamedConcept, {NamedConcept->getConstraintExpr()}, Converted,
4705
544
          SourceRange(SS.isSet() ? 
SS.getBeginLoc()23
:
ConceptNameInfo.getLoc()521
,
4706
544
                      TemplateArgs->getRAngleLoc()),
4707
544
          Satisfaction))
4708
5
    return ExprError();
4709
4710
921
  return ConceptSpecializationExpr::Create(Context,
4711
921
      SS.isSet() ? 
SS.getWithLocInContext(Context)46
:
NestedNameSpecifierLoc{}875
,
4712
921
      TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4713
921
      ASTTemplateArgumentListInfo::Create(Context, *TemplateArgs), Converted,
4714
921
      AreArgsDependent ? 
nullptr382
:
&Satisfaction539
);
4715
926
}
4716
4717
ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
4718
                                     SourceLocation TemplateKWLoc,
4719
                                     LookupResult &R,
4720
                                     bool RequiresADL,
4721
385k
                                 const TemplateArgumentListInfo *TemplateArgs) {
4722
  // FIXME: Can we do any checking at this point? I guess we could check the
4723
  // template arguments that we have against the template name, if the template
4724
  // name refers to a single template. That's not a terribly common case,
4725
  // though.
4726
  // foo<int> could identify a single function unambiguously
4727
  // This approach does NOT work, since f<int>(1);
4728
  // gets resolved prior to resorting to overload resolution
4729
  // i.e., template<class T> void f(double);
4730
  //       vs template<class T, class U> void f(U);
4731
4732
  // These should be filtered out by our callers.
4733
385k
  assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4734
4735
  // Non-function templates require a template argument list.
4736
385k
  if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4737
3.62k
    if (!TemplateArgs && 
!isa<FunctionTemplateDecl>(TD)9
) {
4738
9
      diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
4739
9
      return ExprError();
4740
9
    }
4741
3.62k
  }
4742
4743
  // In C++1y, check variable template ids.
4744
385k
  if (R.getAsSingle<VarTemplateDecl>()) {
4745
3.35k
    ExprResult Res = CheckVarTemplateId(SS, R.getLookupNameInfo(),
4746
3.35k
                                        R.getAsSingle<VarTemplateDecl>(),
4747
3.35k
                                        TemplateKWLoc, TemplateArgs);
4748
3.35k
    if (Res.isInvalid() || 
Res.isUsable()3.33k
)
4749
2.35k
      return Res;
4750
    // Result is dependent. Carry on to build an UnresolvedLookupEpxr.
4751
3.35k
  }
4752
4753
383k
  if (R.getAsSingle<ConceptDecl>()) {
4754
261
    return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4755
261
                                  R.getFoundDecl(),
4756
261
                                  R.getAsSingle<ConceptDecl>(), TemplateArgs);
4757
261
  }
4758
4759
  // We don't want lookup warnings at this point.
4760
383k
  R.suppressDiagnostics();
4761
4762
383k
  UnresolvedLookupExpr *ULE
4763
383k
    = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
4764
383k
                                   SS.getWithLocInContext(Context),
4765
383k
                                   TemplateKWLoc,
4766
383k
                                   R.getLookupNameInfo(),
4767
383k
                                   RequiresADL, TemplateArgs,
4768
383k
                                   R.begin(), R.end());
4769
4770
383k
  return ULE;
4771
383k
}
4772
4773
// We actually only call this from template instantiation.
4774
ExprResult
4775
Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
4776
                                   SourceLocation TemplateKWLoc,
4777
                                   const DeclarationNameInfo &NameInfo,
4778
15.2k
                             const TemplateArgumentListInfo *TemplateArgs) {
4779
4780
15.2k
  assert(TemplateArgs || TemplateKWLoc.isValid());
4781
0
  DeclContext *DC;
4782
15.2k
  if (!(DC = computeDeclContext(SS, false)) ||
4783
15.2k
      
DC->isDependentContext()7.55k
||
4784
15.2k
      
RequireCompleteDeclContext(SS, DC)7.55k
)
4785
7.70k
    return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4786
4787
7.55k
  bool MemberOfUnknownSpecialization;
4788
7.55k
  LookupResult R(*this, NameInfo, LookupOrdinaryName);
4789
7.55k
  if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
4790
7.55k
                         /*Entering*/false, MemberOfUnknownSpecialization,
4791
7.55k
                         TemplateKWLoc))
4792
3
    return ExprError();
4793
4794
7.55k
  if (R.isAmbiguous())
4795
0
    return ExprError();
4796
4797
7.55k
  if (R.empty()) {
4798
0
    Diag(NameInfo.getLoc(), diag::err_no_member)
4799
0
      << NameInfo.getName() << DC << SS.getRange();
4800
0
    return ExprError();
4801
0
  }
4802
4803
7.55k
  if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
4804
1
    Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
4805
1
      << SS.getScopeRep()
4806
1
      << NameInfo.getName().getAsString() << SS.getRange();
4807
1
    Diag(Temp->getLocation(), diag::note_referenced_class_template);
4808
1
    return ExprError();
4809
1
  }
4810
4811
7.55k
  return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
4812
7.55k
}
4813
4814
/// Form a template name from a name that is syntactically required to name a
4815
/// template, either due to use of the 'template' keyword or because a name in
4816
/// this syntactic context is assumed to name a template (C++ [temp.names]p2-4).
4817
///
4818
/// This action forms a template name given the name of the template and its
4819
/// optional scope specifier. This is used when the 'template' keyword is used
4820
/// or when the parsing context unambiguously treats a following '<' as
4821
/// introducing a template argument list. Note that this may produce a
4822
/// non-dependent template name if we can perform the lookup now and identify
4823
/// the named template.
4824
///
4825
/// For example, given "x.MetaFun::template apply", the scope specifier
4826
/// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
4827
/// of the "template" keyword, and "apply" is the \p Name.
4828
TemplateNameKind Sema::ActOnTemplateName(Scope *S,
4829
                                         CXXScopeSpec &SS,
4830
                                         SourceLocation TemplateKWLoc,
4831
                                         const UnqualifiedId &Name,
4832
                                         ParsedType ObjectType,
4833
                                         bool EnteringContext,
4834
                                         TemplateTy &Result,
4835
75.4k
                                         bool AllowInjectedClassName) {
4836
75.4k
  if (TemplateKWLoc.isValid() && 
S74.9k
&&
!S->getTemplateParamParent()23.4k
)
4837
237
    Diag(TemplateKWLoc,
4838
237
         getLangOpts().CPlusPlus11 ?
4839
198
           diag::warn_cxx98_compat_template_outside_of_template :
4840
237
           
diag::ext_template_outside_of_template39
)
4841
237
      << FixItHint::CreateRemoval(TemplateKWLoc);
4842
4843
75.4k
  if (SS.isInvalid())
4844
15
    return TNK_Non_template;
4845
4846
  // Figure out where isTemplateName is going to look.
4847
75.4k
  DeclContext *LookupCtx = nullptr;
4848
75.4k
  if (SS.isNotEmpty())
4849
67.3k
    LookupCtx = computeDeclContext(SS, EnteringContext);
4850
8.11k
  else if (ObjectType)
4851
8.11k
    LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
4852
4853
  // C++0x [temp.names]p5: