Coverage Report

Created: 2020-02-25 14:32

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