Coverage Report

Created: 2020-09-15 12:33

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