Coverage Report

Created: 2022-01-25 06:29

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