]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/clang/lib/Sema/SemaTemplate.cpp
Merge ^/head r357966 through r357999.
[FreeBSD/FreeBSD.git] / contrib / llvm-project / clang / lib / Sema / SemaTemplate.cpp
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                               unsigned N) {
45   if (!N) return SourceRange();
46   return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
47 }
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                                        bool AllowDependent) {
58   D = D->getUnderlyingDecl();
59
60   if (isa<TemplateDecl>(D)) {
61     if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
62       return nullptr;
63
64     return D;
65   }
66
67   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
68     // C++ [temp.local]p1:
69     //   Like normal (non-template) classes, class templates have an
70     //   injected-class-name (Clause 9). The injected-class-name
71     //   can be used with or without a template-argument-list. When
72     //   it is used without a template-argument-list, it is
73     //   equivalent to the injected-class-name followed by the
74     //   template-parameters of the class template enclosed in
75     //   <>. When it is used with a template-argument-list, it
76     //   refers to the specified class template specialization,
77     //   which could be the current specialization or another
78     //   specialization.
79     if (Record->isInjectedClassName()) {
80       Record = cast<CXXRecordDecl>(Record->getDeclContext());
81       if (Record->getDescribedClassTemplate())
82         return Record->getDescribedClassTemplate();
83
84       if (ClassTemplateSpecializationDecl *Spec
85             = dyn_cast<ClassTemplateSpecializationDecl>(Record))
86         return Spec->getSpecializedTemplate();
87     }
88
89     return nullptr;
90   }
91
92   // 'using Dependent::foo;' can resolve to a template name.
93   // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
94   // injected-class-name).
95   if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
96     return D;
97
98   return nullptr;
99 }
100
101 void Sema::FilterAcceptableTemplateNames(LookupResult &R,
102                                          bool AllowFunctionTemplates,
103                                          bool AllowDependent) {
104   LookupResult::Filter filter = R.makeFilter();
105   while (filter.hasNext()) {
106     NamedDecl *Orig = filter.next();
107     if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
108       filter.erase();
109   }
110   filter.done();
111 }
112
113 bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
114                                          bool AllowFunctionTemplates,
115                                          bool AllowDependent,
116                                          bool AllowNonTemplateFunctions) {
117   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
118     if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
119       return true;
120     if (AllowNonTemplateFunctions &&
121         isa<FunctionDecl>((*I)->getUnderlyingDecl()))
122       return true;
123   }
124
125   return false;
126 }
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                                       bool &MemberOfUnknownSpecialization) {
136   assert(getLangOpts().CPlusPlus && "No template names in C!");
137
138   DeclarationName TName;
139   MemberOfUnknownSpecialization = false;
140
141   switch (Name.getKind()) {
142   case UnqualifiedIdKind::IK_Identifier:
143     TName = DeclarationName(Name.Identifier);
144     break;
145
146   case UnqualifiedIdKind::IK_OperatorFunctionId:
147     TName = Context.DeclarationNames.getCXXOperatorName(
148                                               Name.OperatorFunctionId.Operator);
149     break;
150
151   case UnqualifiedIdKind::IK_LiteralOperatorId:
152     TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
153     break;
154
155   default:
156     return TNK_Non_template;
157   }
158
159   QualType ObjectType = ObjectTypePtr.get();
160
161   AssumedTemplateKind AssumedTemplate;
162   LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
163   if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
164                          MemberOfUnknownSpecialization, SourceLocation(),
165                          &AssumedTemplate))
166     return TNK_Non_template;
167
168   if (AssumedTemplate != AssumedTemplateKind::None) {
169     TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
170     // Let the parser know whether we found nothing or found functions; if we
171     // found nothing, we want to more carefully check whether this is actually
172     // a function template name versus some other kind of undeclared identifier.
173     return AssumedTemplate == AssumedTemplateKind::FoundNothing
174                ? TNK_Undeclared_template
175                : TNK_Function_template;
176   }
177
178   if (R.empty())
179     return TNK_Non_template;
180
181   NamedDecl *D = nullptr;
182   if (R.isAmbiguous()) {
183     // If we got an ambiguity involving a non-function template, treat this
184     // as a template name, and pick an arbitrary template for error recovery.
185     bool AnyFunctionTemplates = false;
186     for (NamedDecl *FoundD : R) {
187       if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
188         if (isa<FunctionTemplateDecl>(FoundTemplate))
189           AnyFunctionTemplates = true;
190         else {
191           D = FoundTemplate;
192           break;
193         }
194       }
195     }
196
197     // If we didn't find any templates at all, this isn't a template name.
198     // Leave the ambiguity for a later lookup to diagnose.
199     if (!D && !AnyFunctionTemplates) {
200       R.suppressDiagnostics();
201       return TNK_Non_template;
202     }
203
204     // If the only templates were function templates, filter out the rest.
205     // We'll diagnose the ambiguity later.
206     if (!D)
207       FilterAcceptableTemplateNames(R);
208   }
209
210   // At this point, we have either picked a single template name declaration D
211   // or we have a non-empty set of results R containing either one template name
212   // declaration or a set of function templates.
213
214   TemplateName Template;
215   TemplateNameKind TemplateKind;
216
217   unsigned ResultCount = R.end() - R.begin();
218   if (!D && ResultCount > 1) {
219     // We assume that we'll preserve the qualifier from a function
220     // template name in other ways.
221     Template = Context.getOverloadedTemplateName(R.begin(), R.end());
222     TemplateKind = TNK_Function_template;
223
224     // We'll do this lookup again later.
225     R.suppressDiagnostics();
226   } else {
227     if (!D) {
228       D = getAsTemplateNameDecl(*R.begin());
229       assert(D && "unambiguous result is not a template name");
230     }
231
232     if (isa<UnresolvedUsingValueDecl>(D)) {
233       // We don't yet know whether this is a template-name or not.
234       MemberOfUnknownSpecialization = true;
235       return TNK_Non_template;
236     }
237
238     TemplateDecl *TD = cast<TemplateDecl>(D);
239
240     if (SS.isSet() && !SS.isInvalid()) {
241       NestedNameSpecifier *Qualifier = SS.getScopeRep();
242       Template = Context.getQualifiedTemplateName(Qualifier,
243                                                   hasTemplateKeyword, TD);
244     } else {
245       Template = TemplateName(TD);
246     }
247
248     if (isa<FunctionTemplateDecl>(TD)) {
249       TemplateKind = TNK_Function_template;
250
251       // We'll do this lookup again later.
252       R.suppressDiagnostics();
253     } else {
254       assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
255              isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
256              isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
257       TemplateKind =
258           isa<VarTemplateDecl>(TD) ? TNK_Var_template :
259           isa<ConceptDecl>(TD) ? TNK_Concept_template :
260           TNK_Type_template;
261     }
262   }
263
264   TemplateResult = TemplateTy::make(Template);
265   return TemplateKind;
266 }
267
268 bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
269                                 SourceLocation NameLoc,
270                                 ParsedTemplateTy *Template) {
271   CXXScopeSpec SS;
272   bool MemberOfUnknownSpecialization = false;
273
274   // We could use redeclaration lookup here, but we don't need to: the
275   // syntactic form of a deduction guide is enough to identify it even
276   // if we can't look up the template name at all.
277   LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
278   if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
279                          /*EnteringContext*/ false,
280                          MemberOfUnknownSpecialization))
281     return false;
282
283   if (R.empty()) return false;
284   if (R.isAmbiguous()) {
285     // FIXME: Diagnose an ambiguity if we find at least one template.
286     R.suppressDiagnostics();
287     return false;
288   }
289
290   // We only treat template-names that name type templates as valid deduction
291   // guide names.
292   TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
293   if (!TD || !getAsTypeTemplateDecl(TD))
294     return false;
295
296   if (Template)
297     *Template = TemplateTy::make(TemplateName(TD));
298   return true;
299 }
300
301 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
302                                        SourceLocation IILoc,
303                                        Scope *S,
304                                        const CXXScopeSpec *SS,
305                                        TemplateTy &SuggestedTemplate,
306                                        TemplateNameKind &SuggestedKind) {
307   // We can't recover unless there's a dependent scope specifier preceding the
308   // template name.
309   // FIXME: Typo correction?
310   if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
311       computeDeclContext(*SS))
312     return false;
313
314   // The code is missing a 'template' keyword prior to the dependent template
315   // name.
316   NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
317   Diag(IILoc, diag::err_template_kw_missing)
318     << Qualifier << II.getName()
319     << FixItHint::CreateInsertion(IILoc, "template ");
320   SuggestedTemplate
321     = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
322   SuggestedKind = TNK_Dependent_template_name;
323   return true;
324 }
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                               AssumedTemplateKind *ATK) {
333   if (ATK)
334     *ATK = AssumedTemplateKind::None;
335
336   Found.setTemplateNameLookup(true);
337
338   // Determine where to perform name lookup
339   MemberOfUnknownSpecialization = false;
340   DeclContext *LookupCtx = nullptr;
341   bool IsDependent = false;
342   if (!ObjectType.isNull()) {
343     // This nested-name-specifier occurs in a member access expression, e.g.,
344     // x->B::f, and we are looking into the type of the object.
345     assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
346     LookupCtx = computeDeclContext(ObjectType);
347     IsDependent = !LookupCtx && ObjectType->isDependentType();
348     assert((IsDependent || !ObjectType->isIncompleteType() ||
349             ObjectType->castAs<TagType>()->isBeingDefined()) &&
350            "Caller should have completed object type");
351
352     // Template names cannot appear inside an Objective-C class or object type
353     // or a vector type.
354     //
355     // FIXME: This is wrong. For example:
356     //
357     //   template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
358     //   Vec<int> vi;
359     //   vi.Vec<int>::~Vec<int>();
360     //
361     // ... should be accepted but we will not treat 'Vec' as a template name
362     // here. The right thing to do would be to check if the name is a valid
363     // vector component name, and look up a template name if not. And similarly
364     // for lookups into Objective-C class and object types, where the same
365     // problem can arise.
366     if (ObjectType->isObjCObjectOrInterfaceType() ||
367         ObjectType->isVectorType()) {
368       Found.clear();
369       return false;
370     }
371   } else if (SS.isSet()) {
372     // This nested-name-specifier occurs after another nested-name-specifier,
373     // so long into the context associated with the prior nested-name-specifier.
374     LookupCtx = computeDeclContext(SS, EnteringContext);
375     IsDependent = !LookupCtx;
376
377     // The declaration context must be complete.
378     if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
379       return true;
380   }
381
382   bool ObjectTypeSearchedInScope = false;
383   bool AllowFunctionTemplatesInLookup = true;
384   if (LookupCtx) {
385     // Perform "qualified" name lookup into the declaration context we
386     // computed, which is either the type of the base of a member access
387     // expression or the declaration context associated with a prior
388     // nested-name-specifier.
389     LookupQualifiedName(Found, LookupCtx);
390
391     // FIXME: The C++ standard does not clearly specify what happens in the
392     // case where the object type is dependent, and implementations vary. In
393     // Clang, we treat a name after a . or -> as a template-name if lookup
394     // finds a non-dependent member or member of the current instantiation that
395     // is a type template, or finds no such members and lookup in the context
396     // of the postfix-expression finds a type template. In the latter case, the
397     // name is nonetheless dependent, and we may resolve it to a member of an
398     // unknown specialization when we come to instantiate the template.
399     IsDependent |= Found.wasNotFoundInCurrentInstantiation();
400   }
401
402   if (!SS.isSet() && (ObjectType.isNull() || Found.empty())) {
403     // C++ [basic.lookup.classref]p1:
404     //   In a class member access expression (5.2.5), if the . or -> token is
405     //   immediately followed by an identifier followed by a <, the
406     //   identifier must be looked up to determine whether the < is the
407     //   beginning of a template argument list (14.2) or a less-than operator.
408     //   The identifier is first looked up in the class of the object
409     //   expression. If the identifier is not found, it is then looked up in
410     //   the context of the entire postfix-expression and shall name a class
411     //   template.
412     if (S)
413       LookupName(Found, S);
414
415     if (!ObjectType.isNull()) {
416       //  FIXME: We should filter out all non-type templates here, particularly
417       //  variable templates and concepts. But the exclusion of alias templates
418       //  and template template parameters is a wording defect.
419       AllowFunctionTemplatesInLookup = false;
420       ObjectTypeSearchedInScope = true;
421     }
422
423     IsDependent |= Found.wasNotFoundInCurrentInstantiation();
424   }
425
426   if (Found.isAmbiguous())
427     return false;
428
429   if (ATK && !SS.isSet() && ObjectType.isNull() && TemplateKWLoc.isInvalid()) {
430     // C++2a [temp.names]p2:
431     //   A name is also considered to refer to a template if it is an
432     //   unqualified-id followed by a < and name lookup finds either one or more
433     //   functions or finds nothing.
434     //
435     // To keep our behavior consistent, we apply the "finds nothing" part in
436     // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
437     // successfully form a call to an undeclared template-id.
438     bool AllFunctions =
439         getLangOpts().CPlusPlus2a &&
440         std::all_of(Found.begin(), Found.end(), [](NamedDecl *ND) {
441           return isa<FunctionDecl>(ND->getUnderlyingDecl());
442         });
443     if (AllFunctions || (Found.empty() && !IsDependent)) {
444       // If lookup found any functions, or if this is a name that can only be
445       // used for a function, then strongly assume this is a function
446       // template-id.
447       *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
448                  ? AssumedTemplateKind::FoundNothing
449                  : AssumedTemplateKind::FoundFunctions;
450       Found.clear();
451       return false;
452     }
453   }
454
455   if (Found.empty() && !IsDependent) {
456     // If we did not find any names, attempt to correct any typos.
457     DeclarationName Name = Found.getLookupName();
458     Found.clear();
459     // Simple filter callback that, for keywords, only accepts the C++ *_cast
460     DefaultFilterCCC FilterCCC{};
461     FilterCCC.WantTypeSpecifiers = false;
462     FilterCCC.WantExpressionKeywords = false;
463     FilterCCC.WantRemainingKeywords = false;
464     FilterCCC.WantCXXNamedCasts = true;
465     if (TypoCorrection Corrected =
466             CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
467                         &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
468       if (auto *ND = Corrected.getFoundDecl())
469         Found.addDecl(ND);
470       FilterAcceptableTemplateNames(Found);
471       if (Found.isAmbiguous()) {
472         Found.clear();
473       } else if (!Found.empty()) {
474         Found.setLookupName(Corrected.getCorrection());
475         if (LookupCtx) {
476           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
477           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
478                                   Name.getAsString() == CorrectedStr;
479           diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
480                                     << Name << LookupCtx << DroppedSpecifier
481                                     << SS.getRange());
482         } else {
483           diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
484         }
485       }
486     }
487   }
488
489   NamedDecl *ExampleLookupResult =
490       Found.empty() ? nullptr : Found.getRepresentativeDecl();
491   FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
492   if (Found.empty()) {
493     if (IsDependent) {
494       MemberOfUnknownSpecialization = true;
495       return false;
496     }
497
498     // If a 'template' keyword was used, a lookup that finds only non-template
499     // names is an error.
500     if (ExampleLookupResult && TemplateKWLoc.isValid()) {
501       Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
502         << Found.getLookupName() << SS.getRange();
503       Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
504            diag::note_template_kw_refers_to_non_template)
505           << Found.getLookupName();
506       return true;
507     }
508
509     return false;
510   }
511
512   if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
513       !getLangOpts().CPlusPlus11) {
514     // C++03 [basic.lookup.classref]p1:
515     //   [...] If the lookup in the class of the object expression finds a
516     //   template, the name is also looked up in the context of the entire
517     //   postfix-expression and [...]
518     //
519     // Note: C++11 does not perform this second lookup.
520     LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
521                             LookupOrdinaryName);
522     FoundOuter.setTemplateNameLookup(true);
523     LookupName(FoundOuter, S);
524     // FIXME: We silently accept an ambiguous lookup here, in violation of
525     // [basic.lookup]/1.
526     FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
527
528     NamedDecl *OuterTemplate;
529     if (FoundOuter.empty()) {
530       //   - if the name is not found, the name found in the class of the
531       //     object expression is used, otherwise
532     } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
533                !(OuterTemplate =
534                      getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
535       //   - if the name is found in the context of the entire
536       //     postfix-expression and does not name a class template, the name
537       //     found in the class of the object expression is used, otherwise
538       FoundOuter.clear();
539     } else if (!Found.isSuppressingDiagnostics()) {
540       //   - if the name found is a class template, it must refer to the same
541       //     entity as the one found in the class of the object expression,
542       //     otherwise the program is ill-formed.
543       if (!Found.isSingleResult() ||
544           getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
545               OuterTemplate->getCanonicalDecl()) {
546         Diag(Found.getNameLoc(),
547              diag::ext_nested_name_member_ref_lookup_ambiguous)
548           << Found.getLookupName()
549           << ObjectType;
550         Diag(Found.getRepresentativeDecl()->getLocation(),
551              diag::note_ambig_member_ref_object_type)
552           << ObjectType;
553         Diag(FoundOuter.getFoundDecl()->getLocation(),
554              diag::note_ambig_member_ref_scope);
555
556         // Recover by taking the template that we found in the object
557         // expression's type.
558       }
559     }
560   }
561
562   return false;
563 }
564
565 void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
566                                               SourceLocation Less,
567                                               SourceLocation Greater) {
568   if (TemplateName.isInvalid())
569     return;
570
571   DeclarationNameInfo NameInfo;
572   CXXScopeSpec SS;
573   LookupNameKind LookupKind;
574
575   DeclContext *LookupCtx = nullptr;
576   NamedDecl *Found = nullptr;
577   bool MissingTemplateKeyword = false;
578
579   // Figure out what name we looked up.
580   if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
581     NameInfo = DRE->getNameInfo();
582     SS.Adopt(DRE->getQualifierLoc());
583     LookupKind = LookupOrdinaryName;
584     Found = DRE->getFoundDecl();
585   } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
586     NameInfo = ME->getMemberNameInfo();
587     SS.Adopt(ME->getQualifierLoc());
588     LookupKind = LookupMemberName;
589     LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
590     Found = ME->getMemberDecl();
591   } else if (auto *DSDRE =
592                  dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
593     NameInfo = DSDRE->getNameInfo();
594     SS.Adopt(DSDRE->getQualifierLoc());
595     MissingTemplateKeyword = true;
596   } else if (auto *DSME =
597                  dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
598     NameInfo = DSME->getMemberNameInfo();
599     SS.Adopt(DSME->getQualifierLoc());
600     MissingTemplateKeyword = true;
601   } else {
602     llvm_unreachable("unexpected kind of potential template name");
603   }
604
605   // If this is a dependent-scope lookup, diagnose that the 'template' keyword
606   // was missing.
607   if (MissingTemplateKeyword) {
608     Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
609         << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
610     return;
611   }
612
613   // Try to correct the name by looking for templates and C++ named casts.
614   struct TemplateCandidateFilter : CorrectionCandidateCallback {
615     Sema &S;
616     TemplateCandidateFilter(Sema &S) : S(S) {
617       WantTypeSpecifiers = false;
618       WantExpressionKeywords = false;
619       WantRemainingKeywords = false;
620       WantCXXNamedCasts = true;
621     };
622     bool ValidateCandidate(const TypoCorrection &Candidate) override {
623       if (auto *ND = Candidate.getCorrectionDecl())
624         return S.getAsTemplateNameDecl(ND);
625       return Candidate.isKeyword();
626     }
627
628     std::unique_ptr<CorrectionCandidateCallback> clone() override {
629       return std::make_unique<TemplateCandidateFilter>(*this);
630     }
631   };
632
633   DeclarationName Name = NameInfo.getName();
634   TemplateCandidateFilter CCC(*this);
635   if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
636                                              CTK_ErrorRecovery, LookupCtx)) {
637     auto *ND = Corrected.getFoundDecl();
638     if (ND)
639       ND = getAsTemplateNameDecl(ND);
640     if (ND || Corrected.isKeyword()) {
641       if (LookupCtx) {
642         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
643         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
644                                 Name.getAsString() == CorrectedStr;
645         diagnoseTypo(Corrected,
646                      PDiag(diag::err_non_template_in_member_template_id_suggest)
647                          << Name << LookupCtx << DroppedSpecifier
648                          << SS.getRange(), false);
649       } else {
650         diagnoseTypo(Corrected,
651                      PDiag(diag::err_non_template_in_template_id_suggest)
652                          << Name, false);
653       }
654       if (Found)
655         Diag(Found->getLocation(),
656              diag::note_non_template_in_template_id_found);
657       return;
658     }
659   }
660
661   Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
662     << Name << SourceRange(Less, Greater);
663   if (Found)
664     Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
665 }
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                            const TemplateArgumentListInfo *TemplateArgs) {
676   DeclContext *DC = getFunctionLevelDeclContext();
677
678   // C++11 [expr.prim.general]p12:
679   //   An id-expression that denotes a non-static data member or non-static
680   //   member function of a class can only be used:
681   //   (...)
682   //   - if that id-expression denotes a non-static data member and it
683   //     appears in an unevaluated operand.
684   //
685   // If this might be the case, form a DependentScopeDeclRefExpr instead of a
686   // CXXDependentScopeMemberExpr. The former can instantiate to either
687   // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
688   // always a MemberExpr.
689   bool MightBeCxx11UnevalField =
690       getLangOpts().CPlusPlus11 && isUnevaluatedContext();
691
692   // Check if the nested name specifier is an enum type.
693   bool IsEnum = false;
694   if (NestedNameSpecifier *NNS = SS.getScopeRep())
695     IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
696
697   if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
698       isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
699     QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType();
700
701     // Since the 'this' expression is synthesized, we don't need to
702     // perform the double-lookup check.
703     NamedDecl *FirstQualifierInScope = nullptr;
704
705     return CXXDependentScopeMemberExpr::Create(
706         Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
707         /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
708         FirstQualifierInScope, NameInfo, TemplateArgs);
709   }
710
711   return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
712 }
713
714 ExprResult
715 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
716                                 SourceLocation TemplateKWLoc,
717                                 const DeclarationNameInfo &NameInfo,
718                                 const TemplateArgumentListInfo *TemplateArgs) {
719   // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc
720   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
721   if (!QualifierLoc)
722     return ExprError();
723
724   return DependentScopeDeclRefExpr::Create(
725       Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs);
726 }
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                                           bool Complain /*= true*/) {
738   assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
739          isa<VarDecl>(Instantiation));
740
741   bool IsEntityBeingDefined = false;
742   if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
743     IsEntityBeingDefined = TD->isBeingDefined();
744
745   if (PatternDef && !IsEntityBeingDefined) {
746     NamedDecl *SuggestedDef = nullptr;
747     if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
748                               /*OnlyNeedComplete*/false)) {
749       // If we're allowed to diagnose this and recover, do so.
750       bool Recover = Complain && !isSFINAEContext();
751       if (Complain)
752         diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
753                               Sema::MissingImportKind::Definition, Recover);
754       return !Recover;
755     }
756     return false;
757   }
758
759   if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
760     return true;
761
762   llvm::Optional<unsigned> Note;
763   QualType InstantiationTy;
764   if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
765     InstantiationTy = Context.getTypeDeclType(TD);
766   if (PatternDef) {
767     Diag(PointOfInstantiation,
768          diag::err_template_instantiate_within_definition)
769       << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
770       << InstantiationTy;
771     // Not much point in noting the template declaration here, since
772     // we're lexically inside it.
773     Instantiation->setInvalidDecl();
774   } else if (InstantiatedFromMember) {
775     if (isa<FunctionDecl>(Instantiation)) {
776       Diag(PointOfInstantiation,
777            diag::err_explicit_instantiation_undefined_member)
778         << /*member function*/ 1 << Instantiation->getDeclName()
779         << Instantiation->getDeclContext();
780       Note = diag::note_explicit_instantiation_here;
781     } else {
782       assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
783       Diag(PointOfInstantiation,
784            diag::err_implicit_instantiate_member_undefined)
785         << InstantiationTy;
786       Note = diag::note_member_declared_at;
787     }
788   } else {
789     if (isa<FunctionDecl>(Instantiation)) {
790       Diag(PointOfInstantiation,
791            diag::err_explicit_instantiation_undefined_func_template)
792         << Pattern;
793       Note = diag::note_explicit_instantiation_here;
794     } else if (isa<TagDecl>(Instantiation)) {
795       Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
796         << (TSK != TSK_ImplicitInstantiation)
797         << InstantiationTy;
798       Note = diag::note_template_decl_here;
799     } else {
800       assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
801       if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
802         Diag(PointOfInstantiation,
803              diag::err_explicit_instantiation_undefined_var_template)
804           << Instantiation;
805         Instantiation->setInvalidDecl();
806       } else
807         Diag(PointOfInstantiation,
808              diag::err_explicit_instantiation_undefined_member)
809           << /*static data member*/ 2 << Instantiation->getDeclName()
810           << Instantiation->getDeclContext();
811       Note = diag::note_explicit_instantiation_here;
812     }
813   }
814   if (Note) // Diagnostics were emitted.
815     Diag(Pattern->getLocation(), Note.getValue());
816
817   // In general, Instantiation isn't marked invalid to get more than one
818   // error for multiple undefined instantiations. But the code that does
819   // explicit declaration -> explicit definition conversion can't handle
820   // invalid declarations, so mark as invalid in that case.
821   if (TSK == TSK_ExplicitInstantiationDeclaration)
822     Instantiation->setInvalidDecl();
823   return true;
824 }
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 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
831   assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
832
833   // C++ [temp.local]p4:
834   //   A template-parameter shall not be redeclared within its
835   //   scope (including nested scopes).
836   //
837   // Make this a warning when MSVC compatibility is requested.
838   unsigned DiagId = getLangOpts().MSVCCompat ? diag::ext_template_param_shadow
839                                              : diag::err_template_param_shadow;
840   Diag(Loc, DiagId) << cast<NamedDecl>(PrevDecl)->getDeclName();
841   Diag(PrevDecl->getLocation(), diag::note_template_param_here);
842 }
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 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
848   if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
849     D = Temp->getTemplatedDecl();
850     return Temp;
851   }
852   return nullptr;
853 }
854
855 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
856                                              SourceLocation EllipsisLoc) const {
857   assert(Kind == Template &&
858          "Only template template arguments can be pack expansions here");
859   assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
860          "Template template argument pack expansion without packs");
861   ParsedTemplateArgument Result(*this);
862   Result.EllipsisLoc = EllipsisLoc;
863   return Result;
864 }
865
866 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
867                                             const ParsedTemplateArgument &Arg) {
868
869   switch (Arg.getKind()) {
870   case ParsedTemplateArgument::Type: {
871     TypeSourceInfo *DI;
872     QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
873     if (!DI)
874       DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
875     return TemplateArgumentLoc(TemplateArgument(T), DI);
876   }
877
878   case ParsedTemplateArgument::NonType: {
879     Expr *E = static_cast<Expr *>(Arg.getAsExpr());
880     return TemplateArgumentLoc(TemplateArgument(E), E);
881   }
882
883   case ParsedTemplateArgument::Template: {
884     TemplateName Template = Arg.getAsTemplate().get();
885     TemplateArgument TArg;
886     if (Arg.getEllipsisLoc().isValid())
887       TArg = TemplateArgument(Template, Optional<unsigned int>());
888     else
889       TArg = Template;
890     return TemplateArgumentLoc(TArg,
891                                Arg.getScopeSpec().getWithLocInContext(
892                                                               SemaRef.Context),
893                                Arg.getLocation(),
894                                Arg.getEllipsisLoc());
895   }
896   }
897
898   llvm_unreachable("Unhandled parsed template argument");
899 }
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                                       TemplateArgumentListInfo &TemplateArgs) {
905  for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
906    TemplateArgs.addArgument(translateTemplateArgument(*this,
907                                                       TemplateArgsIn[I]));
908 }
909
910 static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
911                                                  SourceLocation Loc,
912                                                  IdentifierInfo *Name) {
913   NamedDecl *PrevDecl = SemaRef.LookupSingleName(
914       S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
915   if (PrevDecl && PrevDecl->isTemplateParameter())
916     SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
917 }
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 ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
924   TypeSourceInfo *TInfo;
925   QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
926   if (T.isNull())
927     return ParsedTemplateArgument();
928   assert(TInfo && "template argument with no location");
929
930   // If we might have formed a deduced template specialization type, convert
931   // it to a template template argument.
932   if (getLangOpts().CPlusPlus17) {
933     TypeLoc TL = TInfo->getTypeLoc();
934     SourceLocation EllipsisLoc;
935     if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
936       EllipsisLoc = PET.getEllipsisLoc();
937       TL = PET.getPatternLoc();
938     }
939
940     CXXScopeSpec SS;
941     if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
942       SS.Adopt(ET.getQualifierLoc());
943       TL = ET.getNamedTypeLoc();
944     }
945
946     if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
947       TemplateName Name = DTST.getTypePtr()->getTemplateName();
948       if (SS.isSet())
949         Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
950                                                 /*HasTemplateKeyword*/ false,
951                                                 Name.getAsTemplateDecl());
952       ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
953                                     DTST.getTemplateNameLoc());
954       if (EllipsisLoc.isValid())
955         Result = Result.getTemplatePackExpansion(EllipsisLoc);
956       return Result;
957     }
958   }
959
960   // This is a normal type template argument. Note, if the type template
961   // argument is an injected-class-name for a template, it has a dual nature
962   // and can be used as either a type or a template. We handle that in
963   // convertTypeTemplateArgumentToTemplate.
964   return ParsedTemplateArgument(ParsedTemplateArgument::Type,
965                                 ParsedType.get().getAsOpaquePtr(),
966                                 TInfo->getTypeLoc().getBeginLoc());
967 }
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                                     bool HasTypeConstraint) {
987   assert(S->isTemplateParamScope() &&
988          "Template type parameter not in template parameter scope!");
989
990   bool IsParameterPack = EllipsisLoc.isValid();
991   TemplateTypeParmDecl *Param
992     = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
993                                    KeyLoc, ParamNameLoc, Depth, Position,
994                                    ParamName, Typename, IsParameterPack,
995                                    HasTypeConstraint);
996   Param->setAccess(AS_public);
997
998   if (Param->isParameterPack())
999     if (auto *LSI = getEnclosingLambda())
1000       LSI->LocalPacks.push_back(Param);
1001
1002   if (ParamName) {
1003     maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1004
1005     // Add the template parameter into the current scope.
1006     S->AddDecl(Param);
1007     IdResolver.AddDecl(Param);
1008   }
1009
1010   // C++0x [temp.param]p9:
1011   //   A default template-argument may be specified for any kind of
1012   //   template-parameter that is not a template parameter pack.
1013   if (DefaultArg && IsParameterPack) {
1014     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1015     DefaultArg = nullptr;
1016   }
1017
1018   // Handle the default argument, if provided.
1019   if (DefaultArg) {
1020     TypeSourceInfo *DefaultTInfo;
1021     GetTypeFromParser(DefaultArg, &DefaultTInfo);
1022
1023     assert(DefaultTInfo && "expected source information for type");
1024
1025     // Check for unexpanded parameter packs.
1026     if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1027                                         UPPC_DefaultArgument))
1028       return Param;
1029
1030     // Check the template argument itself.
1031     if (CheckTemplateArgument(Param, DefaultTInfo)) {
1032       Param->setInvalidDecl();
1033       return Param;
1034     }
1035
1036     Param->setDefaultArgument(DefaultTInfo);
1037   }
1038
1039   return Param;
1040 }
1041
1042 /// Convert the parser's template argument list representation into our form.
1043 static TemplateArgumentListInfo
1044 makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
1045   TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1046                                         TemplateId.RAngleLoc);
1047   ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1048                                      TemplateId.NumArgs);
1049   S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1050   return TemplateArgs;
1051 }
1052
1053 bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS,
1054                                TemplateIdAnnotation *TypeConstr,
1055                                TemplateTypeParmDecl *ConstrainedParameter,
1056                                SourceLocation EllipsisLoc) {
1057   ConceptDecl *CD =
1058       cast<ConceptDecl>(TypeConstr->Template.get().getAsTemplateDecl());
1059
1060   // C++2a [temp.param]p4:
1061   //     [...] The concept designated by a type-constraint shall be a type
1062   //     concept ([temp.concept]).
1063   if (!CD->isTypeConcept()) {
1064     Diag(TypeConstr->TemplateNameLoc,
1065          diag::err_type_constraint_non_type_concept);
1066     return true;
1067   }
1068
1069   bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1070
1071   if (!WereArgsSpecified &&
1072       CD->getTemplateParameters()->getMinRequiredArguments() > 1) {
1073     Diag(TypeConstr->TemplateNameLoc,
1074          diag::err_type_constraint_missing_arguments) << CD;
1075     return true;
1076   }
1077
1078   TemplateArgumentListInfo TemplateArgs;
1079   if (TypeConstr->LAngleLoc.isValid()) {
1080     TemplateArgs =
1081         makeTemplateArgumentListInfo(*this, *TypeConstr);
1082   }
1083   return AttachTypeConstraint(
1084       SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1085       DeclarationNameInfo(DeclarationName(TypeConstr->Name),
1086                           TypeConstr->TemplateNameLoc), CD,
1087       TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1088       ConstrainedParameter, EllipsisLoc);
1089 }
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     SourceLocation EllipsisLoc) {
1098
1099   TemplateArgumentListInfo ConstraintArgs;
1100   ConstraintArgs.addArgument(
1101     S.getTrivialTemplateArgumentLoc(TemplateArgument(ConstrainedType),
1102                                     /*NTTPType=*/QualType(), ParamNameLoc));
1103
1104   ConstraintArgs.setRAngleLoc(RAngleLoc);
1105   ConstraintArgs.setLAngleLoc(LAngleLoc);
1106   Appender(ConstraintArgs);
1107
1108   // C++2a [temp.param]p4:
1109   //     [...] This constraint-expression E is called the immediately-declared
1110   //     constraint of T. [...]
1111   CXXScopeSpec SS;
1112   SS.Adopt(NS);
1113   ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1114       SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1115       /*FoundDecl=*/NamedConcept, NamedConcept, &ConstraintArgs);
1116   if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1117     return ImmediatelyDeclaredConstraint;
1118
1119   // C++2a [temp.param]p4:
1120   //     [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1121   //
1122   // We have the following case:
1123   //
1124   // template<typename T> concept C1 = true;
1125   // template<C1... T> struct s1;
1126   //
1127   // The constraint: (C1<T> && ...)
1128   return S.BuildCXXFoldExpr(/*LParenLoc=*/SourceLocation(),
1129                             ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1130                             EllipsisLoc, /*RHS=*/nullptr,
1131                             /*RParenLoc=*/SourceLocation(),
1132                             /*NumExpansions=*/None);
1133 }
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                                 SourceLocation EllipsisLoc) {
1145   // C++2a [temp.param]p4:
1146   //     [...] If Q is of the form C<A1, ..., An>, then let E' be
1147   //     C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1148   const ASTTemplateArgumentListInfo *ArgsAsWritten =
1149     TemplateArgs ? ASTTemplateArgumentListInfo::Create(Context,
1150                                                        *TemplateArgs) : nullptr;
1151
1152   QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1153
1154   ExprResult ImmediatelyDeclaredConstraint =
1155       formImmediatelyDeclaredConstraint(
1156           *this, NS, NameInfo, NamedConcept,
1157           TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1158           TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1159           ParamAsArgument, ConstrainedParameter->getLocation(),
1160           [&] (TemplateArgumentListInfo &ConstraintArgs) {
1161             if (TemplateArgs)
1162               for (const auto &ArgLoc : TemplateArgs->arguments())
1163                 ConstraintArgs.addArgument(ArgLoc);
1164           }, EllipsisLoc);
1165   if (ImmediatelyDeclaredConstraint.isInvalid())
1166     return true;
1167
1168   ConstrainedParameter->setTypeConstraint(NS, NameInfo,
1169                                           /*FoundDecl=*/NamedConcept,
1170                                           NamedConcept, ArgsAsWritten,
1171                                           ImmediatelyDeclaredConstraint.get());
1172   return false;
1173 }
1174
1175 bool Sema::AttachTypeConstraint(AutoTypeLoc TL, NonTypeTemplateParmDecl *NTTP,
1176                                 SourceLocation EllipsisLoc) {
1177   if (NTTP->getType() != TL.getType() ||
1178       TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
1179     Diag(NTTP->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1180          diag::err_unsupported_placeholder_constraint)
1181        << NTTP->getTypeSourceInfo()->getTypeLoc().getSourceRange();
1182     return true;
1183   }
1184   // FIXME: Concepts: This should be the type of the placeholder, but this is
1185   // unclear in the wording right now.
1186   DeclRefExpr *Ref = BuildDeclRefExpr(NTTP, NTTP->getType(), VK_RValue,
1187                                       NTTP->getLocation());
1188   if (!Ref)
1189     return true;
1190   ExprResult ImmediatelyDeclaredConstraint =
1191       formImmediatelyDeclaredConstraint(
1192           *this, TL.getNestedNameSpecifierLoc(), TL.getConceptNameInfo(),
1193           TL.getNamedConcept(), TL.getLAngleLoc(), TL.getRAngleLoc(),
1194           BuildDecltypeType(Ref, NTTP->getLocation()), NTTP->getLocation(),
1195           [&] (TemplateArgumentListInfo &ConstraintArgs) {
1196             for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1197               ConstraintArgs.addArgument(TL.getArgLoc(I));
1198           }, EllipsisLoc);
1199   if (ImmediatelyDeclaredConstraint.isInvalid() ||
1200      !ImmediatelyDeclaredConstraint.isUsable())
1201     return true;
1202
1203   NTTP->setPlaceholderTypeConstraint(ImmediatelyDeclaredConstraint.get());
1204   return false;
1205 }
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                                                  SourceLocation Loc) {
1214   if (TSI->getType()->isUndeducedType()) {
1215     // C++17 [temp.dep.expr]p3:
1216     //   An id-expression is type-dependent if it contains
1217     //    - an identifier associated by name lookup with a non-type
1218     //      template-parameter declared with a type that contains a
1219     //      placeholder type (7.1.7.4),
1220     TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
1221   }
1222
1223   return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1224 }
1225
1226 QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1227                                                  SourceLocation Loc) {
1228   // We don't allow variably-modified types as the type of non-type template
1229   // parameters.
1230   if (T->isVariablyModifiedType()) {
1231     Diag(Loc, diag::err_variably_modified_nontype_template_param)
1232       << T;
1233     return QualType();
1234   }
1235
1236   // C++ [temp.param]p4:
1237   //
1238   // A non-type template-parameter shall have one of the following
1239   // (optionally cv-qualified) types:
1240   //
1241   //       -- integral or enumeration type,
1242   if (T->isIntegralOrEnumerationType() ||
1243       //   -- pointer to object or pointer to function,
1244       T->isPointerType() ||
1245       //   -- reference to object or reference to function,
1246       T->isReferenceType() ||
1247       //   -- pointer to member,
1248       T->isMemberPointerType() ||
1249       //   -- std::nullptr_t.
1250       T->isNullPtrType() ||
1251       // Allow use of auto in template parameter declarations.
1252       T->isUndeducedType()) {
1253     // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1254     // are ignored when determining its type.
1255     return T.getUnqualifiedType();
1256   }
1257
1258   // C++ [temp.param]p8:
1259   //
1260   //   A non-type template-parameter of type "array of T" or
1261   //   "function returning T" is adjusted to be of type "pointer to
1262   //   T" or "pointer to function returning T", respectively.
1263   if (T->isArrayType() || T->isFunctionType())
1264     return Context.getDecayedType(T);
1265
1266   // If T is a dependent type, we can't do the check now, so we
1267   // assume that it is well-formed. Note that stripping off the
1268   // qualifiers here is not really correct if T turns out to be
1269   // an array type, but we'll recompute the type everywhere it's
1270   // used during instantiation, so that should be OK. (Using the
1271   // qualified type is equally wrong.)
1272   if (T->isDependentType())
1273     return T.getUnqualifiedType();
1274
1275   Diag(Loc, diag::err_template_nontype_parm_bad_type)
1276     << T;
1277
1278   return QualType();
1279 }
1280
1281 NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1282                                           unsigned Depth,
1283                                           unsigned Position,
1284                                           SourceLocation EqualLoc,
1285                                           Expr *Default) {
1286   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
1287
1288   // Check that we have valid decl-specifiers specified.
1289   auto CheckValidDeclSpecifiers = [this, &D] {
1290     // C++ [temp.param]
1291     // p1 
1292     //   template-parameter:
1293     //     ...
1294     //     parameter-declaration
1295     // p2 
1296     //   ... A storage class shall not be specified in a template-parameter
1297     //   declaration.
1298     // [dcl.typedef]p1:
1299     //   The typedef specifier [...] shall not be used in the decl-specifier-seq
1300     //   of a parameter-declaration
1301     const DeclSpec &DS = D.getDeclSpec();
1302     auto EmitDiag = [this](SourceLocation Loc) {
1303       Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1304           << FixItHint::CreateRemoval(Loc);
1305     };
1306     if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1307       EmitDiag(DS.getStorageClassSpecLoc());
1308
1309     if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1310       EmitDiag(DS.getThreadStorageClassSpecLoc());
1311
1312     // [dcl.inline]p1:
1313     //   The inline specifier can be applied only to the declaration or
1314     //   definition of a variable or function.
1315
1316     if (DS.isInlineSpecified())
1317       EmitDiag(DS.getInlineSpecLoc());
1318
1319     // [dcl.constexpr]p1:
1320     //   The constexpr specifier shall be applied only to the definition of a
1321     //   variable or variable template or the declaration of a function or
1322     //   function template.
1323
1324     if (DS.hasConstexprSpecifier())
1325       EmitDiag(DS.getConstexprSpecLoc());
1326
1327     // [dcl.fct.spec]p1:
1328     //   Function-specifiers can be used only in function declarations.
1329
1330     if (DS.isVirtualSpecified())
1331       EmitDiag(DS.getVirtualSpecLoc());
1332
1333     if (DS.hasExplicitSpecifier())
1334       EmitDiag(DS.getExplicitSpecLoc());
1335
1336     if (DS.isNoreturnSpecified())
1337       EmitDiag(DS.getNoreturnSpecLoc());
1338   };
1339
1340   CheckValidDeclSpecifiers();
1341
1342   if (TInfo->getType()->isUndeducedType()) {
1343     Diag(D.getIdentifierLoc(),
1344          diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1345       << QualType(TInfo->getType()->getContainedAutoType(), 0);
1346   }
1347
1348   assert(S->isTemplateParamScope() &&
1349          "Non-type template parameter not in template parameter scope!");
1350   bool Invalid = false;
1351
1352   QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
1353   if (T.isNull()) {
1354     T = Context.IntTy; // Recover with an 'int' type.
1355     Invalid = true;
1356   }
1357
1358   CheckFunctionOrTemplateParamDeclarator(S, D);
1359
1360   IdentifierInfo *ParamName = D.getIdentifier();
1361   bool IsParameterPack = D.hasEllipsis();
1362   NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1363       Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1364       D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1365       TInfo);
1366   Param->setAccess(AS_public);
1367
1368   if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())
1369     if (TL.isConstrained())
1370       if (AttachTypeConstraint(TL, Param, D.getEllipsisLoc()))
1371         Invalid = true;
1372
1373   if (Invalid)
1374     Param->setInvalidDecl();
1375
1376   if (Param->isParameterPack())
1377     if (auto *LSI = getEnclosingLambda())
1378       LSI->LocalPacks.push_back(Param);
1379
1380   if (ParamName) {
1381     maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1382                                          ParamName);
1383
1384     // Add the template parameter into the current scope.
1385     S->AddDecl(Param);
1386     IdResolver.AddDecl(Param);
1387   }
1388
1389   // C++0x [temp.param]p9:
1390   //   A default template-argument may be specified for any kind of
1391   //   template-parameter that is not a template parameter pack.
1392   if (Default && IsParameterPack) {
1393     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1394     Default = nullptr;
1395   }
1396
1397   // Check the well-formedness of the default template argument, if provided.
1398   if (Default) {
1399     // Check for unexpanded parameter packs.
1400     if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1401       return Param;
1402
1403     TemplateArgument Converted;
1404     ExprResult DefaultRes =
1405         CheckTemplateArgument(Param, Param->getType(), Default, Converted);
1406     if (DefaultRes.isInvalid()) {
1407       Param->setInvalidDecl();
1408       return Param;
1409     }
1410     Default = DefaultRes.get();
1411
1412     Param->setDefaultArgument(Default);
1413   }
1414
1415   return Param;
1416 }
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                                            ParsedTemplateArgument Default) {
1431   assert(S->isTemplateParamScope() &&
1432          "Template template parameter not in template parameter scope!");
1433
1434   // Construct the parameter object.
1435   bool IsParameterPack = EllipsisLoc.isValid();
1436   TemplateTemplateParmDecl *Param =
1437     TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1438                                      NameLoc.isInvalid()? TmpLoc : NameLoc,
1439                                      Depth, Position, IsParameterPack,
1440                                      Name, Params);
1441   Param->setAccess(AS_public);
1442
1443   if (Param->isParameterPack())
1444     if (auto *LSI = getEnclosingLambda())
1445       LSI->LocalPacks.push_back(Param);
1446
1447   // If the template template parameter has a name, then link the identifier
1448   // into the scope and lookup mechanisms.
1449   if (Name) {
1450     maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1451
1452     S->AddDecl(Param);
1453     IdResolver.AddDecl(Param);
1454   }
1455
1456   if (Params->size() == 0) {
1457     Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1458     << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1459     Param->setInvalidDecl();
1460   }
1461
1462   // C++0x [temp.param]p9:
1463   //   A default template-argument may be specified for any kind of
1464   //   template-parameter that is not a template parameter pack.
1465   if (IsParameterPack && !Default.isInvalid()) {
1466     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1467     Default = ParsedTemplateArgument();
1468   }
1469
1470   if (!Default.isInvalid()) {
1471     // Check only that we have a template template argument. We don't want to
1472     // try to check well-formedness now, because our template template parameter
1473     // might have dependent types in its template parameters, which we wouldn't
1474     // be able to match now.
1475     //
1476     // If none of the template template parameter's template arguments mention
1477     // other template parameters, we could actually perform more checking here.
1478     // However, it isn't worth doing.
1479     TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1480     if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1481       Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1482         << DefaultArg.getSourceRange();
1483       return Param;
1484     }
1485
1486     // Check for unexpanded parameter packs.
1487     if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1488                                         DefaultArg.getArgument().getAsTemplate(),
1489                                         UPPC_DefaultArgument))
1490       return Param;
1491
1492     Param->setDefaultArgument(Context, DefaultArg);
1493   }
1494
1495   return Param;
1496 }
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                                  Expr *RequiresClause) {
1509   if (ExportLoc.isValid())
1510     Diag(ExportLoc, diag::warn_template_export_unsupported);
1511
1512   return TemplateParameterList::Create(
1513       Context, TemplateLoc, LAngleLoc,
1514       llvm::makeArrayRef(Params.data(), Params.size()),
1515       RAngleLoc, RequiresClause);
1516 }
1517
1518 static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1519                                    const CXXScopeSpec &SS) {
1520   if (SS.isSet())
1521     T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1522 }
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     TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1531   assert(TemplateParams && TemplateParams->size() > 0 &&
1532          "No template parameters");
1533   assert(TUK != TUK_Reference && "Can only declare or define class templates");
1534   bool Invalid = false;
1535
1536   // Check that we can declare a template here.
1537   if (CheckTemplateDeclScope(S, TemplateParams))
1538     return true;
1539
1540   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1541   assert(Kind != TTK_Enum && "can't build template of enumerated type");
1542
1543   // There is no such thing as an unnamed class template.
1544   if (!Name) {
1545     Diag(KWLoc, diag::err_template_unnamed_class);
1546     return true;
1547   }
1548
1549   // Find any previous declaration with this name. For a friend with no
1550   // scope explicitly specified, we only look for tag declarations (per
1551   // C++11 [basic.lookup.elab]p2).
1552   DeclContext *SemanticContext;
1553   LookupResult Previous(*this, Name, NameLoc,
1554                         (SS.isEmpty() && TUK == TUK_Friend)
1555                           ? LookupTagName : LookupOrdinaryName,
1556                         forRedeclarationInCurContext());
1557   if (SS.isNotEmpty() && !SS.isInvalid()) {
1558     SemanticContext = computeDeclContext(SS, true);
1559     if (!SemanticContext) {
1560       // FIXME: Horrible, horrible hack! We can't currently represent this
1561       // in the AST, and historically we have just ignored such friend
1562       // class templates, so don't complain here.
1563       Diag(NameLoc, TUK == TUK_Friend
1564                         ? diag::warn_template_qualified_friend_ignored
1565                         : diag::err_template_qualified_declarator_no_match)
1566           << SS.getScopeRep() << SS.getRange();
1567       return TUK != TUK_Friend;
1568     }
1569
1570     if (RequireCompleteDeclContext(SS, SemanticContext))
1571       return true;
1572
1573     // If we're adding a template to a dependent context, we may need to
1574     // rebuilding some of the types used within the template parameter list,
1575     // now that we know what the current instantiation is.
1576     if (SemanticContext->isDependentContext()) {
1577       ContextRAII SavedContext(*this, SemanticContext);
1578       if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1579         Invalid = true;
1580     } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1581       diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
1582
1583     LookupQualifiedName(Previous, SemanticContext);
1584   } else {
1585     SemanticContext = CurContext;
1586
1587     // C++14 [class.mem]p14:
1588     //   If T is the name of a class, then each of the following shall have a
1589     //   name different from T:
1590     //    -- every member template of class T
1591     if (TUK != TUK_Friend &&
1592         DiagnoseClassNameShadow(SemanticContext,
1593                                 DeclarationNameInfo(Name, NameLoc)))
1594       return true;
1595
1596     LookupName(Previous, S);
1597   }
1598
1599   if (Previous.isAmbiguous())
1600     return true;
1601
1602   NamedDecl *PrevDecl = nullptr;
1603   if (Previous.begin() != Previous.end())
1604     PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1605
1606   if (PrevDecl && PrevDecl->isTemplateParameter()) {
1607     // Maybe we will complain about the shadowed template parameter.
1608     DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1609     // Just pretend that we didn't see the previous declaration.
1610     PrevDecl = nullptr;
1611   }
1612
1613   // If there is a previous declaration with the same name, check
1614   // whether this is a valid redeclaration.
1615   ClassTemplateDecl *PrevClassTemplate =
1616       dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1617
1618   // We may have found the injected-class-name of a class template,
1619   // class template partial specialization, or class template specialization.
1620   // In these cases, grab the template that is being defined or specialized.
1621   if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1622       cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1623     PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1624     PrevClassTemplate
1625       = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1626     if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1627       PrevClassTemplate
1628         = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1629             ->getSpecializedTemplate();
1630     }
1631   }
1632
1633   if (TUK == TUK_Friend) {
1634     // C++ [namespace.memdef]p3:
1635     //   [...] When looking for a prior declaration of a class or a function
1636     //   declared as a friend, and when the name of the friend class or
1637     //   function is neither a qualified name nor a template-id, scopes outside
1638     //   the innermost enclosing namespace scope are not considered.
1639     if (!SS.isSet()) {
1640       DeclContext *OutermostContext = CurContext;
1641       while (!OutermostContext->isFileContext())
1642         OutermostContext = OutermostContext->getLookupParent();
1643
1644       if (PrevDecl &&
1645           (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1646            OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1647         SemanticContext = PrevDecl->getDeclContext();
1648       } else {
1649         // Declarations in outer scopes don't matter. However, the outermost
1650         // context we computed is the semantic context for our new
1651         // declaration.
1652         PrevDecl = PrevClassTemplate = nullptr;
1653         SemanticContext = OutermostContext;
1654
1655         // Check that the chosen semantic context doesn't already contain a
1656         // declaration of this name as a non-tag type.
1657         Previous.clear(LookupOrdinaryName);
1658         DeclContext *LookupContext = SemanticContext;
1659         while (LookupContext->isTransparentContext())
1660           LookupContext = LookupContext->getLookupParent();
1661         LookupQualifiedName(Previous, LookupContext);
1662
1663         if (Previous.isAmbiguous())
1664           return true;
1665
1666         if (Previous.begin() != Previous.end())
1667           PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1668       }
1669     }
1670   } else if (PrevDecl &&
1671              !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1672                             S, SS.isValid()))
1673     PrevDecl = PrevClassTemplate = nullptr;
1674
1675   if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1676           PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1677     if (SS.isEmpty() &&
1678         !(PrevClassTemplate &&
1679           PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1680               SemanticContext->getRedeclContext()))) {
1681       Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1682       Diag(Shadow->getTargetDecl()->getLocation(),
1683            diag::note_using_decl_target);
1684       Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1685       // Recover by ignoring the old declaration.
1686       PrevDecl = PrevClassTemplate = nullptr;
1687     }
1688   }
1689
1690   if (PrevClassTemplate) {
1691     // Ensure that the template parameter lists are compatible. Skip this check
1692     // for a friend in a dependent context: the template parameter list itself
1693     // could be dependent.
1694     if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1695         !TemplateParameterListsAreEqual(TemplateParams,
1696                                    PrevClassTemplate->getTemplateParameters(),
1697                                         /*Complain=*/true,
1698                                         TPL_TemplateMatch))
1699       return true;
1700
1701     // C++ [temp.class]p4:
1702     //   In a redeclaration, partial specialization, explicit
1703     //   specialization or explicit instantiation of a class template,
1704     //   the class-key shall agree in kind with the original class
1705     //   template declaration (7.1.5.3).
1706     RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1707     if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1708                                       TUK == TUK_Definition,  KWLoc, Name)) {
1709       Diag(KWLoc, diag::err_use_with_wrong_tag)
1710         << Name
1711         << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1712       Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1713       Kind = PrevRecordDecl->getTagKind();
1714     }
1715
1716     // Check for redefinition of this class template.
1717     if (TUK == TUK_Definition) {
1718       if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1719         // If we have a prior definition that is not visible, treat this as
1720         // simply making that previous definition visible.
1721         NamedDecl *Hidden = nullptr;
1722         if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1723           SkipBody->ShouldSkip = true;
1724           SkipBody->Previous = Def;
1725           auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1726           assert(Tmpl && "original definition of a class template is not a "
1727                          "class template?");
1728           makeMergedDefinitionVisible(Hidden);
1729           makeMergedDefinitionVisible(Tmpl);
1730         } else {
1731           Diag(NameLoc, diag::err_redefinition) << Name;
1732           Diag(Def->getLocation(), diag::note_previous_definition);
1733           // FIXME: Would it make sense to try to "forget" the previous
1734           // definition, as part of error recovery?
1735           return true;
1736         }
1737       }
1738     }
1739   } else if (PrevDecl) {
1740     // C++ [temp]p5:
1741     //   A class template shall not have the same name as any other
1742     //   template, class, function, object, enumeration, enumerator,
1743     //   namespace, or type in the same scope (3.3), except as specified
1744     //   in (14.5.4).
1745     Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1746     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1747     return true;
1748   }
1749
1750   // Check the template parameter list of this declaration, possibly
1751   // merging in the template parameter list from the previous class
1752   // template declaration. Skip this check for a friend in a dependent
1753   // context, because the template parameter list might be dependent.
1754   if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1755       CheckTemplateParameterList(
1756           TemplateParams,
1757           PrevClassTemplate
1758               ? PrevClassTemplate->getMostRecentDecl()->getTemplateParameters()
1759               : nullptr,
1760           (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1761            SemanticContext->isDependentContext())
1762               ? TPC_ClassTemplateMember
1763               : TUK == TUK_Friend ? TPC_FriendClassTemplate : TPC_ClassTemplate,
1764           SkipBody))
1765     Invalid = true;
1766
1767   if (SS.isSet()) {
1768     // If the name of the template was qualified, we must be defining the
1769     // template out-of-line.
1770     if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1771       Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1772                                       : diag::err_member_decl_does_not_match)
1773         << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1774       Invalid = true;
1775     }
1776   }
1777
1778   // If this is a templated friend in a dependent context we should not put it
1779   // on the redecl chain. In some cases, the templated friend can be the most
1780   // recent declaration tricking the template instantiator to make substitutions
1781   // there.
1782   // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1783   bool ShouldAddRedecl
1784     = !(TUK == TUK_Friend && CurContext->isDependentContext());
1785
1786   CXXRecordDecl *NewClass =
1787     CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1788                           PrevClassTemplate && ShouldAddRedecl ?
1789                             PrevClassTemplate->getTemplatedDecl() : nullptr,
1790                           /*DelayTypeCreation=*/true);
1791   SetNestedNameSpecifier(*this, NewClass, SS);
1792   if (NumOuterTemplateParamLists > 0)
1793     NewClass->setTemplateParameterListsInfo(
1794         Context, llvm::makeArrayRef(OuterTemplateParamLists,
1795                                     NumOuterTemplateParamLists));
1796
1797   // Add alignment attributes if necessary; these attributes are checked when
1798   // the ASTContext lays out the structure.
1799   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
1800     AddAlignmentAttributesForRecord(NewClass);
1801     AddMsStructLayoutForRecord(NewClass);
1802   }
1803
1804   ClassTemplateDecl *NewTemplate
1805     = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1806                                 DeclarationName(Name), TemplateParams,
1807                                 NewClass);
1808
1809   if (ShouldAddRedecl)
1810     NewTemplate->setPreviousDecl(PrevClassTemplate);
1811
1812   NewClass->setDescribedClassTemplate(NewTemplate);
1813
1814   if (ModulePrivateLoc.isValid())
1815     NewTemplate->setModulePrivate();
1816
1817   // Build the type for the class template declaration now.
1818   QualType T = NewTemplate->getInjectedClassNameSpecialization();
1819   T = Context.getInjectedClassNameType(NewClass, T);
1820   assert(T->isDependentType() && "Class template type is not dependent?");
1821   (void)T;
1822
1823   // If we are providing an explicit specialization of a member that is a
1824   // class template, make a note of that.
1825   if (PrevClassTemplate &&
1826       PrevClassTemplate->getInstantiatedFromMemberTemplate())
1827     PrevClassTemplate->setMemberSpecialization();
1828
1829   // Set the access specifier.
1830   if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1831     SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1832
1833   // Set the lexical context of these templates
1834   NewClass->setLexicalDeclContext(CurContext);
1835   NewTemplate->setLexicalDeclContext(CurContext);
1836
1837   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
1838     NewClass->startDefinition();
1839
1840   ProcessDeclAttributeList(S, NewClass, Attr);
1841
1842   if (PrevClassTemplate)
1843     mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1844
1845   AddPushedVisibilityAttribute(NewClass);
1846   inferGslOwnerPointerAttribute(NewClass);
1847
1848   if (TUK != TUK_Friend) {
1849     // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1850     Scope *Outer = S;
1851     while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1852       Outer = Outer->getParent();
1853     PushOnScopeChains(NewTemplate, Outer);
1854   } else {
1855     if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1856       NewTemplate->setAccess(PrevClassTemplate->getAccess());
1857       NewClass->setAccess(PrevClassTemplate->getAccess());
1858     }
1859
1860     NewTemplate->setObjectOfFriendDecl();
1861
1862     // Friend templates are visible in fairly strange ways.
1863     if (!CurContext->isDependentContext()) {
1864       DeclContext *DC = SemanticContext->getRedeclContext();
1865       DC->makeDeclVisibleInContext(NewTemplate);
1866       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1867         PushOnScopeChains(NewTemplate, EnclosingScope,
1868                           /* AddToContext = */ false);
1869     }
1870
1871     FriendDecl *Friend = FriendDecl::Create(
1872         Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1873     Friend->setAccess(AS_public);
1874     CurContext->addDecl(Friend);
1875   }
1876
1877   if (PrevClassTemplate)
1878     CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate);
1879
1880   if (Invalid) {
1881     NewTemplate->setInvalidDecl();
1882     NewClass->setInvalidDecl();
1883   }
1884
1885   ActOnDocumentableDecl(NewTemplate);
1886
1887   if (SkipBody && SkipBody->ShouldSkip)
1888     return SkipBody->Previous;
1889
1890   return NewTemplate;
1891 }
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   ExtractTypeForDeductionGuide(Sema &SemaRef) : Base(SemaRef) {}
1901
1902   TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
1903
1904   QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
1905     return TransformType(
1906         TLB,
1907         TL.getTypedefNameDecl()->getTypeSourceInfo()->getTypeLoc());
1908   }
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       : 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                                   CXXConstructorDecl *CD) {
1935     SmallVector<TemplateArgument, 16> SubstArgs;
1936
1937     LocalInstantiationScope Scope(SemaRef);
1938
1939     // C++ [over.match.class.deduct]p1:
1940     // -- For each constructor of the class template designated by the
1941     //    template-name, a function template with the following properties:
1942
1943     //    -- The template parameters are the template parameters of the class
1944     //       template followed by the template parameters (including default
1945     //       template arguments) of the constructor, if any.
1946     TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1947     if (FTD) {
1948       TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1949       SmallVector<NamedDecl *, 16> AllParams;
1950       AllParams.reserve(TemplateParams->size() + InnerParams->size());
1951       AllParams.insert(AllParams.begin(),
1952                        TemplateParams->begin(), TemplateParams->end());
1953       SubstArgs.reserve(InnerParams->size());
1954
1955       // Later template parameters could refer to earlier ones, so build up
1956       // a list of substituted template arguments as we go.
1957       for (NamedDecl *Param : *InnerParams) {
1958         MultiLevelTemplateArgumentList Args;
1959         Args.addOuterTemplateArguments(SubstArgs);
1960         Args.addOuterRetainedLevel();
1961         NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1962         if (!NewParam)
1963           return nullptr;
1964         AllParams.push_back(NewParam);
1965         SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1966             SemaRef.Context.getInjectedTemplateArg(NewParam)));
1967       }
1968       TemplateParams = TemplateParameterList::Create(
1969           SemaRef.Context, InnerParams->getTemplateLoc(),
1970           InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1971           /*FIXME: RequiresClause*/ nullptr);
1972     }
1973
1974     // If we built a new template-parameter-list, track that we need to
1975     // substitute references to the old parameters into references to the
1976     // new ones.
1977     MultiLevelTemplateArgumentList Args;
1978     if (FTD) {
1979       Args.addOuterTemplateArguments(SubstArgs);
1980       Args.addOuterRetainedLevel();
1981     }
1982
1983     FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
1984                                    .getAsAdjusted<FunctionProtoTypeLoc>();
1985     assert(FPTL && "no prototype for constructor declaration");
1986
1987     // Transform the type of the function, adjusting the return type and
1988     // replacing references to the old parameters with references to the
1989     // new ones.
1990     TypeLocBuilder TLB;
1991     SmallVector<ParmVarDecl*, 8> Params;
1992     QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1993     if (NewType.isNull())
1994       return nullptr;
1995     TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1996
1997     return buildDeductionGuide(TemplateParams, CD->getExplicitSpecifier(),
1998                                NewTInfo, CD->getBeginLoc(), CD->getLocation(),
1999                                CD->getEndLoc());
2000   }
2001
2002   /// Build a deduction guide with the specified parameter types.
2003   NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
2004     SourceLocation Loc = Template->getLocation();
2005
2006     // Build the requested type.
2007     FunctionProtoType::ExtProtoInfo EPI;
2008     EPI.HasTrailingReturn = true;
2009     QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
2010                                                 DeductionGuideName, EPI);
2011     TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
2012
2013     FunctionProtoTypeLoc FPTL =
2014         TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
2015
2016     // Build the parameters, needed during deduction / substitution.
2017     SmallVector<ParmVarDecl*, 4> Params;
2018     for (auto T : ParamTypes) {
2019       ParmVarDecl *NewParam = ParmVarDecl::Create(
2020           SemaRef.Context, DC, Loc, Loc, nullptr, T,
2021           SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
2022       NewParam->setScopeInfo(0, Params.size());
2023       FPTL.setParam(Params.size(), NewParam);
2024       Params.push_back(NewParam);
2025     }
2026
2027     return buildDeductionGuide(Template->getTemplateParameters(),
2028                                ExplicitSpecifier(), TSI, Loc, Loc, Loc);
2029   }
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                                         MultiLevelTemplateArgumentList &Args) {
2037     if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
2038       // TemplateTypeParmDecl's index cannot be changed after creation, so
2039       // substitute it directly.
2040       auto *NewTTP = TemplateTypeParmDecl::Create(
2041           SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(),
2042           /*Depth*/ 0, Depth1IndexAdjustment + TTP->getIndex(),
2043           TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
2044           TTP->isParameterPack(), TTP->hasTypeConstraint(),
2045           TTP->isExpandedParameterPack() ?
2046           llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None);
2047       if (const auto *TC = TTP->getTypeConstraint()) {
2048         TemplateArgumentListInfo TransformedArgs;
2049         const auto *ArgsAsWritten = TC->getTemplateArgsAsWritten();
2050         if (!ArgsAsWritten ||
2051             SemaRef.Subst(ArgsAsWritten->getTemplateArgs(),
2052                           ArgsAsWritten->NumTemplateArgs, TransformedArgs,
2053                           Args))
2054           SemaRef.AttachTypeConstraint(
2055               TC->getNestedNameSpecifierLoc(), TC->getConceptNameInfo(),
2056               TC->getNamedConcept(), ArgsAsWritten ? &TransformedArgs : nullptr,
2057               NewTTP,
2058               NewTTP->isParameterPack()
2059                  ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2060                      ->getEllipsisLoc()
2061                  : SourceLocation());
2062       }
2063       if (TTP->hasDefaultArgument()) {
2064         TypeSourceInfo *InstantiatedDefaultArg =
2065             SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
2066                               TTP->getDefaultArgumentLoc(), TTP->getDeclName());
2067         if (InstantiatedDefaultArg)
2068           NewTTP->setDefaultArgument(InstantiatedDefaultArg);
2069       }
2070       SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
2071                                                            NewTTP);
2072       return NewTTP;
2073     }
2074
2075     if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
2076       return transformTemplateParameterImpl(TTP, Args);
2077
2078     return transformTemplateParameterImpl(
2079         cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
2080   }
2081   template<typename TemplateParmDecl>
2082   TemplateParmDecl *
2083   transformTemplateParameterImpl(TemplateParmDecl *OldParam,
2084                                  MultiLevelTemplateArgumentList &Args) {
2085     // Ask the template instantiator to do the heavy lifting for us, then adjust
2086     // the index of the parameter once it's done.
2087     auto *NewParam =
2088         cast<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
2089     assert(NewParam->getDepth() == 0 && "unexpected template param depth");
2090     NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
2091     return NewParam;
2092   }
2093
2094   QualType transformFunctionProtoType(TypeLocBuilder &TLB,
2095                                       FunctionProtoTypeLoc TL,
2096                                       SmallVectorImpl<ParmVarDecl*> &Params,
2097                                       MultiLevelTemplateArgumentList &Args) {
2098     SmallVector<QualType, 4> ParamTypes;
2099     const FunctionProtoType *T = TL.getTypePtr();
2100
2101     //    -- The types of the function parameters are those of the constructor.
2102     for (auto *OldParam : TL.getParams()) {
2103       ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
2104       if (!NewParam)
2105         return QualType();
2106       ParamTypes.push_back(NewParam->getType());
2107       Params.push_back(NewParam);
2108     }
2109
2110     //    -- The return type is the class template specialization designated by
2111     //       the template-name and template arguments corresponding to the
2112     //       template parameters obtained from the class template.
2113     //
2114     // We use the injected-class-name type of the primary template instead.
2115     // This has the convenient property that it is different from any type that
2116     // the user can write in a deduction-guide (because they cannot enter the
2117     // context of the template), so implicit deduction guides can never collide
2118     // with explicit ones.
2119     QualType ReturnType = DeducedType;
2120     TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
2121
2122     // Resolving a wording defect, we also inherit the variadicness of the
2123     // constructor.
2124     FunctionProtoType::ExtProtoInfo EPI;
2125     EPI.Variadic = T->isVariadic();
2126     EPI.HasTrailingReturn = true;
2127
2128     QualType Result = SemaRef.BuildFunctionType(
2129         ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
2130     if (Result.isNull())
2131       return QualType();
2132
2133     FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
2134     NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
2135     NewTL.setLParenLoc(TL.getLParenLoc());
2136     NewTL.setRParenLoc(TL.getRParenLoc());
2137     NewTL.setExceptionSpecRange(SourceRange());
2138     NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
2139     for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
2140       NewTL.setParam(I, Params[I]);
2141
2142     return Result;
2143   }
2144
2145   ParmVarDecl *
2146   transformFunctionTypeParam(ParmVarDecl *OldParam,
2147                              MultiLevelTemplateArgumentList &Args) {
2148     TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
2149     TypeSourceInfo *NewDI;
2150     if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
2151       // Expand out the one and only element in each inner pack.
2152       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
2153       NewDI =
2154           SemaRef.SubstType(PackTL.getPatternLoc(), Args,
2155                             OldParam->getLocation(), OldParam->getDeclName());
2156       if (!NewDI) return nullptr;
2157       NewDI =
2158           SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
2159                                      PackTL.getTypePtr()->getNumExpansions());
2160     } else
2161       NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
2162                                 OldParam->getDeclName());
2163     if (!NewDI)
2164       return nullptr;
2165
2166     // Extract the type. This (for instance) replaces references to typedef
2167     // members of the current instantiations with the definitions of those
2168     // typedefs, avoiding triggering instantiation of the deduced type during
2169     // deduction.
2170     NewDI = ExtractTypeForDeductionGuide(SemaRef).transform(NewDI);
2171
2172     // Resolving a wording defect, we also inherit default arguments from the
2173     // constructor.
2174     ExprResult NewDefArg;
2175     if (OldParam->hasDefaultArg()) {
2176       NewDefArg = SemaRef.SubstExpr(OldParam->getDefaultArg(), Args);
2177       if (NewDefArg.isInvalid())
2178         return nullptr;
2179     }
2180
2181     ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
2182                                                 OldParam->getInnerLocStart(),
2183                                                 OldParam->getLocation(),
2184                                                 OldParam->getIdentifier(),
2185                                                 NewDI->getType(),
2186                                                 NewDI,
2187                                                 OldParam->getStorageClass(),
2188                                                 NewDefArg.get());
2189     NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
2190                            OldParam->getFunctionScopeIndex());
2191     SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
2192     return NewParam;
2193   }
2194
2195   NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
2196                                  ExplicitSpecifier ES, TypeSourceInfo *TInfo,
2197                                  SourceLocation LocStart, SourceLocation Loc,
2198                                  SourceLocation LocEnd) {
2199     DeclarationNameInfo Name(DeductionGuideName, Loc);
2200     ArrayRef<ParmVarDecl *> Params =
2201         TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
2202
2203     // Build the implicit deduction guide template.
2204     auto *Guide =
2205         CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name,
2206                                       TInfo->getType(), TInfo, LocEnd);
2207     Guide->setImplicit();
2208     Guide->setParams(Params);
2209
2210     for (auto *Param : Params)
2211       Param->setDeclContext(Guide);
2212
2213     auto *GuideTemplate = FunctionTemplateDecl::Create(
2214         SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
2215     GuideTemplate->setImplicit();
2216     Guide->setDescribedFunctionTemplate(GuideTemplate);
2217
2218     if (isa<CXXRecordDecl>(DC)) {
2219       Guide->setAccess(AS_public);
2220       GuideTemplate->setAccess(AS_public);
2221     }
2222
2223     DC->addDecl(GuideTemplate);
2224     return GuideTemplate;
2225   }
2226 };
2227 }
2228
2229 void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
2230                                           SourceLocation Loc) {
2231   if (CXXRecordDecl *DefRecord =
2232           cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
2233     TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate();
2234     Template = DescribedTemplate ? DescribedTemplate : Template;
2235   }
2236
2237   DeclContext *DC = Template->getDeclContext();
2238   if (DC->isDependentContext())
2239     return;
2240
2241   ConvertConstructorToDeductionGuideTransform Transform(
2242       *this, cast<ClassTemplateDecl>(Template));
2243   if (!isCompleteType(Loc, Transform.DeducedType))
2244     return;
2245
2246   // Check whether we've already declared deduction guides for this template.
2247   // FIXME: Consider storing a flag on the template to indicate this.
2248   auto Existing = DC->lookup(Transform.DeductionGuideName);
2249   for (auto *D : Existing)
2250     if (D->isImplicit())
2251       return;
2252
2253   // In case we were expanding a pack when we attempted to declare deduction
2254   // guides, turn off pack expansion for everything we're about to do.
2255   ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2256   // Create a template instantiation record to track the "instantiation" of
2257   // constructors into deduction guides.
2258   // FIXME: Add a kind for this to give more meaningful diagnostics. But can
2259   // this substitution process actually fail?
2260   InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
2261   if (BuildingDeductionGuides.isInvalid())
2262     return;
2263
2264   // Convert declared constructors into deduction guide templates.
2265   // FIXME: Skip constructors for which deduction must necessarily fail (those
2266   // for which some class template parameter without a default argument never
2267   // appears in a deduced context).
2268   bool AddedAny = false;
2269   for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
2270     D = D->getUnderlyingDecl();
2271     if (D->isInvalidDecl() || D->isImplicit())
2272       continue;
2273     D = cast<NamedDecl>(D->getCanonicalDecl());
2274
2275     auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
2276     auto *CD =
2277         dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
2278     // Class-scope explicit specializations (MS extension) do not result in
2279     // deduction guides.
2280     if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
2281       continue;
2282
2283     Transform.transformConstructor(FTD, CD);
2284     AddedAny = true;
2285   }
2286
2287   // C++17 [over.match.class.deduct]
2288   //    --  If C is not defined or does not declare any constructors, an
2289   //    additional function template derived as above from a hypothetical
2290   //    constructor C().
2291   if (!AddedAny)
2292     Transform.buildSimpleDeductionGuide(None);
2293
2294   //    -- An additional function template derived as above from a hypothetical
2295   //    constructor C(C), called the copy deduction candidate.
2296   cast<CXXDeductionGuideDecl>(
2297       cast<FunctionTemplateDecl>(
2298           Transform.buildSimpleDeductionGuide(Transform.DeducedType))
2299           ->getTemplatedDecl())
2300       ->setIsCopyDeductionCandidate();
2301 }
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                                             SourceRange DefArgRange) {
2311   switch (TPC) {
2312   case Sema::TPC_ClassTemplate:
2313   case Sema::TPC_VarTemplate:
2314   case Sema::TPC_TypeAliasTemplate:
2315     return false;
2316
2317   case Sema::TPC_FunctionTemplate:
2318   case Sema::TPC_FriendFunctionTemplateDefinition:
2319     // C++ [temp.param]p9:
2320     //   A default template-argument shall not be specified in a
2321     //   function template declaration or a function template
2322     //   definition [...]
2323     //   If a friend function template declaration specifies a default
2324     //   template-argument, that declaration shall be a definition and shall be
2325     //   the only declaration of the function template in the translation unit.
2326     // (C++98/03 doesn't have this wording; see DR226).
2327     S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2328          diag::warn_cxx98_compat_template_parameter_default_in_function_template
2329            : diag::ext_template_parameter_default_in_function_template)
2330       << DefArgRange;
2331     return false;
2332
2333   case Sema::TPC_ClassTemplateMember:
2334     // C++0x [temp.param]p9:
2335     //   A default template-argument shall not be specified in the
2336     //   template-parameter-lists of the definition of a member of a
2337     //   class template that appears outside of the member's class.
2338     S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2339       << DefArgRange;
2340     return true;
2341
2342   case Sema::TPC_FriendClassTemplate:
2343   case Sema::TPC_FriendFunctionTemplate:
2344     // C++ [temp.param]p9:
2345     //   A default template-argument shall not be specified in a
2346     //   friend template declaration.
2347     S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2348       << DefArgRange;
2349     return true;
2350
2351     // FIXME: C++0x [temp.param]p9 allows default template-arguments
2352     // for friend function templates if there is only a single
2353     // declaration (and it is a definition). Strange!
2354   }
2355
2356   llvm_unreachable("Invalid TemplateParamListContext!");
2357 }
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                                              TemplateTemplateParmDecl *TTP) {
2363   // A template template parameter which is a parameter pack is also a pack
2364   // expansion.
2365   if (TTP->isParameterPack())
2366     return false;
2367
2368   TemplateParameterList *Params = TTP->getTemplateParameters();
2369   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2370     NamedDecl *P = Params->getParam(I);
2371     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2372       if (!TTP->isParameterPack())
2373         if (const TypeConstraint *TC = TTP->getTypeConstraint())
2374           if (TC->hasExplicitTemplateArgs())
2375             for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2376               if (S.DiagnoseUnexpandedParameterPack(ArgLoc,
2377                                                     Sema::UPPC_TypeConstraint))
2378                 return true;
2379       continue;
2380     }
2381
2382     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2383       if (!NTTP->isParameterPack() &&
2384           S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2385                                             NTTP->getTypeSourceInfo(),
2386                                       Sema::UPPC_NonTypeTemplateParameterType))
2387         return true;
2388
2389       continue;
2390     }
2391
2392     if (TemplateTemplateParmDecl *InnerTTP
2393                                         = dyn_cast<TemplateTemplateParmDecl>(P))
2394       if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2395         return true;
2396   }
2397
2398   return false;
2399 }
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                                       SkipBodyInfo *SkipBody) {
2433   bool Invalid = false;
2434
2435   // C++ [temp.param]p10:
2436   //   The set of default template-arguments available for use with a
2437   //   template declaration or definition is obtained by merging the
2438   //   default arguments from the definition (if in scope) and all
2439   //   declarations in scope in the same way default function
2440   //   arguments are (8.3.6).
2441   bool SawDefaultArgument = false;
2442   SourceLocation PreviousDefaultArgLoc;
2443
2444   // Dummy initialization to avoid warnings.
2445   TemplateParameterList::iterator OldParam = NewParams->end();
2446   if (OldParams)
2447     OldParam = OldParams->begin();
2448
2449   bool RemoveDefaultArguments = false;
2450   for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2451                                     NewParamEnd = NewParams->end();
2452        NewParam != NewParamEnd; ++NewParam) {
2453     // Variables used to diagnose redundant default arguments
2454     bool RedundantDefaultArg = false;
2455     SourceLocation OldDefaultLoc;
2456     SourceLocation NewDefaultLoc;
2457
2458     // Variable used to diagnose missing default arguments
2459     bool MissingDefaultArg = false;
2460
2461     // Variable used to diagnose non-final parameter packs
2462     bool SawParameterPack = false;
2463
2464     if (TemplateTypeParmDecl *NewTypeParm
2465           = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2466       // Check the presence of a default argument here.
2467       if (NewTypeParm->hasDefaultArgument() &&
2468           DiagnoseDefaultTemplateArgument(*this, TPC,
2469                                           NewTypeParm->getLocation(),
2470                NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
2471                                                        .getSourceRange()))
2472         NewTypeParm->removeDefaultArgument();
2473
2474       // Merge default arguments for template type parameters.
2475       TemplateTypeParmDecl *OldTypeParm
2476           = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2477       if (NewTypeParm->isParameterPack()) {
2478         assert(!NewTypeParm->hasDefaultArgument() &&
2479                "Parameter packs can't have a default argument!");
2480         SawParameterPack = true;
2481       } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2482                  NewTypeParm->hasDefaultArgument() &&
2483                  (!SkipBody || !SkipBody->ShouldSkip)) {
2484         OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2485         NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2486         SawDefaultArgument = true;
2487         RedundantDefaultArg = true;
2488         PreviousDefaultArgLoc = NewDefaultLoc;
2489       } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2490         // Merge the default argument from the old declaration to the
2491         // new declaration.
2492         NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2493         PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2494       } else if (NewTypeParm->hasDefaultArgument()) {
2495         SawDefaultArgument = true;
2496         PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2497       } else if (SawDefaultArgument)
2498         MissingDefaultArg = true;
2499     } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2500                = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2501       // Check for unexpanded parameter packs.
2502       if (!NewNonTypeParm->isParameterPack() &&
2503           DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2504                                           NewNonTypeParm->getTypeSourceInfo(),
2505                                           UPPC_NonTypeTemplateParameterType)) {
2506         Invalid = true;
2507         continue;
2508       }
2509
2510       // Check the presence of a default argument here.
2511       if (NewNonTypeParm->hasDefaultArgument() &&
2512           DiagnoseDefaultTemplateArgument(*this, TPC,
2513                                           NewNonTypeParm->getLocation(),
2514                     NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
2515         NewNonTypeParm->removeDefaultArgument();
2516       }
2517
2518       // Merge default arguments for non-type template parameters
2519       NonTypeTemplateParmDecl *OldNonTypeParm
2520         = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2521       if (NewNonTypeParm->isParameterPack()) {
2522         assert(!NewNonTypeParm->hasDefaultArgument() &&
2523                "Parameter packs can't have a default argument!");
2524         if (!NewNonTypeParm->isPackExpansion())
2525           SawParameterPack = true;
2526       } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2527                  NewNonTypeParm->hasDefaultArgument() &&
2528                  (!SkipBody || !SkipBody->ShouldSkip)) {
2529         OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2530         NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2531         SawDefaultArgument = true;
2532         RedundantDefaultArg = true;
2533         PreviousDefaultArgLoc = NewDefaultLoc;
2534       } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2535         // Merge the default argument from the old declaration to the
2536         // new declaration.
2537         NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2538         PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2539       } else if (NewNonTypeParm->hasDefaultArgument()) {
2540         SawDefaultArgument = true;
2541         PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2542       } else if (SawDefaultArgument)
2543         MissingDefaultArg = true;
2544     } else {
2545       TemplateTemplateParmDecl *NewTemplateParm
2546         = cast<TemplateTemplateParmDecl>(*NewParam);
2547
2548       // Check for unexpanded parameter packs, recursively.
2549       if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2550         Invalid = true;
2551         continue;
2552       }
2553
2554       // Check the presence of a default argument here.
2555       if (NewTemplateParm->hasDefaultArgument() &&
2556           DiagnoseDefaultTemplateArgument(*this, TPC,
2557                                           NewTemplateParm->getLocation(),
2558                      NewTemplateParm->getDefaultArgument().getSourceRange()))
2559         NewTemplateParm->removeDefaultArgument();
2560
2561       // Merge default arguments for template template parameters
2562       TemplateTemplateParmDecl *OldTemplateParm
2563         = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2564       if (NewTemplateParm->isParameterPack()) {
2565         assert(!NewTemplateParm->hasDefaultArgument() &&
2566                "Parameter packs can't have a default argument!");
2567         if (!NewTemplateParm->isPackExpansion())
2568           SawParameterPack = true;
2569       } else if (OldTemplateParm &&
2570                  hasVisibleDefaultArgument(OldTemplateParm) &&
2571                  NewTemplateParm->hasDefaultArgument() &&
2572                  (!SkipBody || !SkipBody->ShouldSkip)) {
2573         OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2574         NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2575         SawDefaultArgument = true;
2576         RedundantDefaultArg = true;
2577         PreviousDefaultArgLoc = NewDefaultLoc;
2578       } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2579         // Merge the default argument from the old declaration to the
2580         // new declaration.
2581         NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2582         PreviousDefaultArgLoc
2583           = OldTemplateParm->getDefaultArgument().getLocation();
2584       } else if (NewTemplateParm->hasDefaultArgument()) {
2585         SawDefaultArgument = true;
2586         PreviousDefaultArgLoc
2587           = NewTemplateParm->getDefaultArgument().getLocation();
2588       } else if (SawDefaultArgument)
2589         MissingDefaultArg = true;
2590     }
2591
2592     // C++11 [temp.param]p11:
2593     //   If a template parameter of a primary class template or alias template
2594     //   is a template parameter pack, it shall be the last template parameter.
2595     if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2596         (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2597          TPC == TPC_TypeAliasTemplate)) {
2598       Diag((*NewParam)->getLocation(),
2599            diag::err_template_param_pack_must_be_last_template_parameter);
2600       Invalid = true;
2601     }
2602
2603     if (RedundantDefaultArg) {
2604       // C++ [temp.param]p12:
2605       //   A template-parameter shall not be given default arguments
2606       //   by two different declarations in the same scope.
2607       Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2608       Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2609       Invalid = true;
2610     } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
2611       // C++ [temp.param]p11:
2612       //   If a template-parameter of a class template has a default
2613       //   template-argument, each subsequent template-parameter shall either
2614       //   have a default template-argument supplied or be a template parameter
2615       //   pack.
2616       Diag((*NewParam)->getLocation(),
2617            diag::err_template_param_default_arg_missing);
2618       Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2619       Invalid = true;
2620       RemoveDefaultArguments = true;
2621     }
2622
2623     // If we have an old template parameter list that we're merging
2624     // in, move on to the next parameter.
2625     if (OldParams)
2626       ++OldParam;
2627   }
2628
2629   // We were missing some default arguments at the end of the list, so remove
2630   // all of the default arguments.
2631   if (RemoveDefaultArguments) {
2632     for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2633                                       NewParamEnd = NewParams->end();
2634          NewParam != NewParamEnd; ++NewParam) {
2635       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2636         TTP->removeDefaultArgument();
2637       else if (NonTypeTemplateParmDecl *NTTP
2638                                 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2639         NTTP->removeDefaultArgument();
2640       else
2641         cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2642     }
2643   }
2644
2645   return Invalid;
2646 }
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         Match(false) {}
2669
2670   DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2671       : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2672     NamedDecl *ND = Params->getParam(0);
2673     if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2674       Depth = PD->getDepth();
2675     } else if (NonTypeTemplateParmDecl *PD =
2676                  dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2677       Depth = PD->getDepth();
2678     } else {
2679       Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2680     }
2681   }
2682
2683   bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2684     if (ParmDepth >= Depth) {
2685       Match = true;
2686       MatchLoc = Loc;
2687       return true;
2688     }
2689     return false;
2690   }
2691
2692   bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2693     // Prune out non-type-dependent expressions if requested. This can
2694     // sometimes result in us failing to find a template parameter reference
2695     // (if a value-dependent expression creates a dependent type), but this
2696     // mode is best-effort only.
2697     if (auto *E = dyn_cast_or_null<Expr>(S))
2698       if (IgnoreNonTypeDependent && !E->isTypeDependent())
2699         return true;
2700     return super::TraverseStmt(S, Q);
2701   }
2702
2703   bool TraverseTypeLoc(TypeLoc TL) {
2704     if (IgnoreNonTypeDependent && !TL.isNull() &&
2705         !TL.getType()->isDependentType())
2706       return true;
2707     return super::TraverseTypeLoc(TL);
2708   }
2709
2710   bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2711     return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2712   }
2713
2714   bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
2715     // For a best-effort search, keep looking until we find a location.
2716     return IgnoreNonTypeDependent || !Matches(T->getDepth());
2717   }
2718
2719   bool TraverseTemplateName(TemplateName N) {
2720     if (TemplateTemplateParmDecl *PD =
2721           dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2722       if (Matches(PD->getDepth()))
2723         return false;
2724     return super::TraverseTemplateName(N);
2725   }
2726
2727   bool VisitDeclRefExpr(DeclRefExpr *E) {
2728     if (NonTypeTemplateParmDecl *PD =
2729           dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2730       if (Matches(PD->getDepth(), E->getExprLoc()))
2731         return false;
2732     return super::VisitDeclRefExpr(E);
2733   }
2734
2735   bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2736     return TraverseType(T->getReplacementType());
2737   }
2738
2739   bool
2740   VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2741     return TraverseTemplateArgument(T->getArgumentPack());
2742   }
2743
2744   bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2745     return TraverseType(T->getInjectedSpecializationType());
2746   }
2747 };
2748 } // end anonymous namespace
2749
2750 /// Determines whether a given type depends on the given parameter
2751 /// list.
2752 static bool
2753 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2754   if (!Params->size())
2755     return false;
2756
2757   DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2758   Checker.TraverseType(T);
2759   return Checker.Match;
2760 }
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                                                        const CXXScopeSpec &SS) {
2767   NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2768   while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2769     if (const Type *CurType = NNS->getAsType()) {
2770       if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2771         return NNSLoc.getTypeLoc().getSourceRange();
2772     } else
2773       break;
2774
2775     NNSLoc = NNSLoc.getPrefix();
2776   }
2777
2778   return SourceRange();
2779 }
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     bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2819   IsMemberSpecialization = false;
2820   Invalid = false;
2821
2822   // The sequence of nested types to which we will match up the template
2823   // parameter lists. We first build this list by starting with the type named
2824   // by the nested-name-specifier and walking out until we run out of types.
2825   SmallVector<QualType, 4> NestedTypes;
2826   QualType T;
2827   if (SS.getScopeRep()) {
2828     if (CXXRecordDecl *Record
2829               = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2830       T = Context.getTypeDeclType(Record);
2831     else
2832       T = QualType(SS.getScopeRep()->getAsType(), 0);
2833   }
2834
2835   // If we found an explicit specialization that prevents us from needing
2836   // 'template<>' headers, this will be set to the location of that
2837   // explicit specialization.
2838   SourceLocation ExplicitSpecLoc;
2839
2840   while (!T.isNull()) {
2841     NestedTypes.push_back(T);
2842
2843     // Retrieve the parent of a record type.
2844     if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2845       // If this type is an explicit specialization, we're done.
2846       if (ClassTemplateSpecializationDecl *Spec
2847           = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2848         if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2849             Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2850           ExplicitSpecLoc = Spec->getLocation();
2851           break;
2852         }
2853       } else if (Record->getTemplateSpecializationKind()
2854                                                 == TSK_ExplicitSpecialization) {
2855         ExplicitSpecLoc = Record->getLocation();
2856         break;
2857       }
2858
2859       if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2860         T = Context.getTypeDeclType(Parent);
2861       else
2862         T = QualType();
2863       continue;
2864     }
2865
2866     if (const TemplateSpecializationType *TST
2867                                      = T->getAs<TemplateSpecializationType>()) {
2868       if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2869         if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2870           T = Context.getTypeDeclType(Parent);
2871         else
2872           T = QualType();
2873         continue;
2874       }
2875     }
2876
2877     // Look one step prior in a dependent template specialization type.
2878     if (const DependentTemplateSpecializationType *DependentTST
2879                           = T->getAs<DependentTemplateSpecializationType>()) {
2880       if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2881         T = QualType(NNS->getAsType(), 0);
2882       else
2883         T = QualType();
2884       continue;
2885     }
2886
2887     // Look one step prior in a dependent name type.
2888     if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2889       if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2890         T = QualType(NNS->getAsType(), 0);
2891       else
2892         T = QualType();
2893       continue;
2894     }
2895
2896     // Retrieve the parent of an enumeration type.
2897     if (const EnumType *EnumT = T->getAs<EnumType>()) {
2898       // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2899       // check here.
2900       EnumDecl *Enum = EnumT->getDecl();
2901
2902       // Get to the parent type.
2903       if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2904         T = Context.getTypeDeclType(Parent);
2905       else
2906         T = QualType();
2907       continue;
2908     }
2909
2910     T = QualType();
2911   }
2912   // Reverse the nested types list, since we want to traverse from the outermost
2913   // to the innermost while checking template-parameter-lists.
2914   std::reverse(NestedTypes.begin(), NestedTypes.end());
2915
2916   // C++0x [temp.expl.spec]p17:
2917   //   A member or a member template may be nested within many
2918   //   enclosing class templates. In an explicit specialization for
2919   //   such a member, the member declaration shall be preceded by a
2920   //   template<> for each enclosing class template that is
2921   //   explicitly specialized.
2922   bool SawNonEmptyTemplateParameterList = false;
2923
2924   auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2925     if (SawNonEmptyTemplateParameterList) {
2926       if (!SuppressDiagnostic)
2927         Diag(DeclLoc, diag::err_specialize_member_of_template)
2928           << !Recovery << Range;
2929       Invalid = true;
2930       IsMemberSpecialization = false;
2931       return true;
2932     }
2933
2934     return false;
2935   };
2936
2937   auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2938     // Check that we can have an explicit specialization here.
2939     if (CheckExplicitSpecialization(Range, true))
2940       return true;
2941
2942     // We don't have a template header, but we should.
2943     SourceLocation ExpectedTemplateLoc;
2944     if (!ParamLists.empty())
2945       ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2946     else
2947       ExpectedTemplateLoc = DeclStartLoc;
2948
2949     if (!SuppressDiagnostic)
2950       Diag(DeclLoc, diag::err_template_spec_needs_header)
2951         << Range
2952         << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2953     return false;
2954   };
2955
2956   unsigned ParamIdx = 0;
2957   for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2958        ++TypeIdx) {
2959     T = NestedTypes[TypeIdx];
2960
2961     // Whether we expect a 'template<>' header.
2962     bool NeedEmptyTemplateHeader = false;
2963
2964     // Whether we expect a template header with parameters.
2965     bool NeedNonemptyTemplateHeader = false;
2966
2967     // For a dependent type, the set of template parameters that we
2968     // expect to see.
2969     TemplateParameterList *ExpectedTemplateParams = nullptr;
2970
2971     // C++0x [temp.expl.spec]p15:
2972     //   A member or a member template may be nested within many enclosing
2973     //   class templates. In an explicit specialization for such a member, the
2974     //   member declaration shall be preceded by a template<> for each
2975     //   enclosing class template that is explicitly specialized.
2976     if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2977       if (ClassTemplatePartialSpecializationDecl *Partial
2978             = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2979         ExpectedTemplateParams = Partial->getTemplateParameters();
2980         NeedNonemptyTemplateHeader = true;
2981       } else if (Record->isDependentType()) {
2982         if (Record->getDescribedClassTemplate()) {
2983           ExpectedTemplateParams = Record->getDescribedClassTemplate()
2984                                                       ->getTemplateParameters();
2985           NeedNonemptyTemplateHeader = true;
2986         }
2987       } else if (ClassTemplateSpecializationDecl *Spec
2988                      = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2989         // C++0x [temp.expl.spec]p4:
2990         //   Members of an explicitly specialized class template are defined
2991         //   in the same manner as members of normal classes, and not using
2992         //   the template<> syntax.
2993         if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2994           NeedEmptyTemplateHeader = true;
2995         else
2996           continue;
2997       } else if (Record->getTemplateSpecializationKind()) {
2998         if (Record->getTemplateSpecializationKind()
2999                                                 != TSK_ExplicitSpecialization &&
3000             TypeIdx == NumTypes - 1)
3001           IsMemberSpecialization = true;
3002
3003         continue;
3004       }
3005     } else if (const TemplateSpecializationType *TST
3006                                      = T->getAs<TemplateSpecializationType>()) {
3007       if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
3008         ExpectedTemplateParams = Template->getTemplateParameters();
3009         NeedNonemptyTemplateHeader = true;
3010       }
3011     } else if (T->getAs<DependentTemplateSpecializationType>()) {
3012       // FIXME:  We actually could/should check the template arguments here
3013       // against the corresponding template parameter list.
3014       NeedNonemptyTemplateHeader = false;
3015     }
3016
3017     // C++ [temp.expl.spec]p16:
3018     //   In an explicit specialization declaration for a member of a class
3019     //   template or a member template that ap- pears in namespace scope, the
3020     //   member template and some of its enclosing class templates may remain
3021     //   unspecialized, except that the declaration shall not explicitly
3022     //   specialize a class member template if its en- closing class templates
3023     //   are not explicitly specialized as well.
3024     if (ParamIdx < ParamLists.size()) {
3025       if (ParamLists[ParamIdx]->size() == 0) {
3026         if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3027                                         false))
3028           return nullptr;
3029       } else
3030         SawNonEmptyTemplateParameterList = true;
3031     }
3032
3033     if (NeedEmptyTemplateHeader) {
3034       // If we're on the last of the types, and we need a 'template<>' header
3035       // here, then it's a member specialization.
3036       if (TypeIdx == NumTypes - 1)
3037         IsMemberSpecialization = true;
3038
3039       if (ParamIdx < ParamLists.size()) {
3040         if (ParamLists[ParamIdx]->size() > 0) {
3041           // The header has template parameters when it shouldn't. Complain.
3042           if (!SuppressDiagnostic)
3043             Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3044                  diag::err_template_param_list_matches_nontemplate)
3045               << T
3046               << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3047                              ParamLists[ParamIdx]->getRAngleLoc())
3048               << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3049           Invalid = true;
3050           return nullptr;
3051         }
3052
3053         // Consume this template header.
3054         ++ParamIdx;
3055         continue;
3056       }
3057
3058       if (!IsFriend)
3059         if (DiagnoseMissingExplicitSpecialization(
3060                 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
3061           return nullptr;
3062
3063       continue;
3064     }
3065
3066     if (NeedNonemptyTemplateHeader) {
3067       // In friend declarations we can have template-ids which don't
3068       // depend on the corresponding template parameter lists.  But
3069       // assume that empty parameter lists are supposed to match this
3070       // template-id.
3071       if (IsFriend && T->isDependentType()) {
3072         if (ParamIdx < ParamLists.size() &&
3073             DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
3074           ExpectedTemplateParams = nullptr;
3075         else
3076           continue;
3077       }
3078
3079       if (ParamIdx < ParamLists.size()) {
3080         // Check the template parameter list, if we can.
3081         if (ExpectedTemplateParams &&
3082             !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
3083                                             ExpectedTemplateParams,
3084                                             !SuppressDiagnostic, TPL_TemplateMatch))
3085           Invalid = true;
3086
3087         if (!Invalid &&
3088             CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3089                                        TPC_ClassTemplateMember))
3090           Invalid = true;
3091
3092         ++ParamIdx;
3093         continue;
3094       }
3095
3096       if (!SuppressDiagnostic)
3097         Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3098           << T
3099           << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3100       Invalid = true;
3101       continue;
3102     }
3103   }
3104
3105   // If there were at least as many template-ids as there were template
3106   // parameter lists, then there are no template parameter lists remaining for
3107   // the declaration itself.
3108   if (ParamIdx >= ParamLists.size()) {
3109     if (TemplateId && !IsFriend) {
3110       // We don't have a template header for the declaration itself, but we
3111       // should.
3112       DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3113                                                         TemplateId->RAngleLoc));
3114
3115       // Fabricate an empty template parameter list for the invented header.
3116       return TemplateParameterList::Create(Context, SourceLocation(),
3117                                            SourceLocation(), None,
3118                                            SourceLocation(), nullptr);
3119     }
3120
3121     return nullptr;
3122   }
3123
3124   // If there were too many template parameter lists, complain about that now.
3125   if (ParamIdx < ParamLists.size() - 1) {
3126     bool HasAnyExplicitSpecHeader = false;
3127     bool AllExplicitSpecHeaders = true;
3128     for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3129       if (ParamLists[I]->size() == 0)
3130         HasAnyExplicitSpecHeader = true;
3131       else
3132         AllExplicitSpecHeaders = false;
3133     }
3134
3135     if (!SuppressDiagnostic)
3136       Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3137            AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
3138                                   : diag::err_template_spec_extra_headers)
3139           << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3140                          ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3141
3142     // If there was a specialization somewhere, such that 'template<>' is
3143     // not required, and there were any 'template<>' headers, note where the
3144     // specialization occurred.
3145     if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3146         !SuppressDiagnostic)
3147       Diag(ExplicitSpecLoc,
3148            diag::note_explicit_template_spec_does_not_need_header)
3149         << NestedTypes.back();
3150
3151     // We have a template parameter list with no corresponding scope, which
3152     // means that the resulting template declaration can't be instantiated
3153     // properly (we'll end up with dependent nodes when we shouldn't).
3154     if (!AllExplicitSpecHeaders)
3155       Invalid = true;
3156   }
3157
3158   // C++ [temp.expl.spec]p16:
3159   //   In an explicit specialization declaration for a member of a class
3160   //   template or a member template that ap- pears in namespace scope, the
3161   //   member template and some of its enclosing class templates may remain
3162   //   unspecialized, except that the declaration shall not explicitly
3163   //   specialize a class member template if its en- closing class templates
3164   //   are not explicitly specialized as well.
3165   if (ParamLists.back()->size() == 0 &&
3166       CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3167                                   false))
3168     return nullptr;
3169
3170   // Return the last template parameter list, which corresponds to the
3171   // entity being declared.
3172   return ParamLists.back();
3173 }
3174
3175 void Sema::NoteAllFoundTemplates(TemplateName Name) {
3176   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3177     Diag(Template->getLocation(), diag::note_template_declared_here)
3178         << (isa<FunctionTemplateDecl>(Template)
3179                 ? 0
3180                 : isa<ClassTemplateDecl>(Template)
3181                       ? 1
3182                       : isa<VarTemplateDecl>(Template)
3183                             ? 2
3184                             : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
3185         << Template->getDeclName();
3186     return;
3187   }
3188
3189   if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3190     for (OverloadedTemplateStorage::iterator I = OST->begin(),
3191                                           IEnd = OST->end();
3192          I != IEnd; ++I)
3193       Diag((*I)->getLocation(), diag::note_template_declared_here)
3194         << 0 << (*I)->getDeclName();
3195
3196     return;
3197   }
3198 }
3199
3200 static QualType
3201 checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
3202                            const SmallVectorImpl<TemplateArgument> &Converted,
3203                            SourceLocation TemplateLoc,
3204                            TemplateArgumentListInfo &TemplateArgs) {
3205   ASTContext &Context = SemaRef.getASTContext();
3206   switch (BTD->getBuiltinTemplateKind()) {
3207   case BTK__make_integer_seq: {
3208     // Specializations of __make_integer_seq<S, T, N> are treated like
3209     // S<T, 0, ..., N-1>.
3210
3211     // C++14 [inteseq.intseq]p1:
3212     //   T shall be an integer type.
3213     if (!Converted[1].getAsType()->isIntegralType(Context)) {
3214       SemaRef.Diag(TemplateArgs[1].getLocation(),
3215                    diag::err_integer_sequence_integral_element_type);
3216       return QualType();
3217     }
3218
3219     // C++14 [inteseq.make]p1:
3220     //   If N is negative the program is ill-formed.
3221     TemplateArgument NumArgsArg = Converted[2];
3222     llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
3223     if (NumArgs < 0) {
3224       SemaRef.Diag(TemplateArgs[2].getLocation(),
3225                    diag::err_integer_sequence_negative_length);
3226       return QualType();
3227     }
3228
3229     QualType ArgTy = NumArgsArg.getIntegralType();
3230     TemplateArgumentListInfo SyntheticTemplateArgs;
3231     // The type argument gets reused as the first template argument in the
3232     // synthetic template argument list.
3233     SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
3234     // Expand N into 0 ... N-1.
3235     for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3236          I < NumArgs; ++I) {
3237       TemplateArgument TA(Context, I, ArgTy);
3238       SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3239           TA, ArgTy, TemplateArgs[2].getLocation()));
3240     }
3241     // The first template argument will be reused as the template decl that
3242     // our synthetic template arguments will be applied to.
3243     return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3244                                        TemplateLoc, SyntheticTemplateArgs);
3245   }
3246
3247   case BTK__type_pack_element:
3248     // Specializations of
3249     //    __type_pack_element<Index, T_1, ..., T_N>
3250     // are treated like T_Index.
3251     assert(Converted.size() == 2 &&
3252       "__type_pack_element should be given an index and a parameter pack");
3253
3254     // If the Index is out of bounds, the program is ill-formed.
3255     TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3256     llvm::APSInt Index = IndexArg.getAsIntegral();
3257     assert(Index >= 0 && "the index used with __type_pack_element should be of "
3258                          "type std::size_t, and hence be non-negative");
3259     if (Index >= Ts.pack_size()) {
3260       SemaRef.Diag(TemplateArgs[0].getLocation(),
3261                    diag::err_type_pack_element_out_of_bounds);
3262       return QualType();
3263     }
3264
3265     // We simply return the type at index `Index`.
3266     auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
3267     return Nth->getAsType();
3268   }
3269   llvm_unreachable("unexpected BuiltinTemplateDecl!");
3270 }
3271
3272 /// Determine whether this alias template is "enable_if_t".
3273 static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3274   return AliasTemplate->getName().equals("enable_if_t");
3275 }
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                                     SmallVectorImpl<Expr *> &Terms) {
3285   if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3286     if (BinOp->getOpcode() == BO_LAnd) {
3287       collectConjunctionTerms(BinOp->getLHS(), Terms);
3288       collectConjunctionTerms(BinOp->getRHS(), Terms);
3289     }
3290
3291     return;
3292   }
3293
3294   Terms.push_back(Clause);
3295 }
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 static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3301   // Top-level '||'.
3302   auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3303   if (!BinOp) return Cond;
3304
3305   if (BinOp->getOpcode() != BO_LOr) return Cond;
3306
3307   // With an inner '==' that has a literal on the right-hand side.
3308   Expr *LHS = BinOp->getLHS();
3309   auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3310   if (!InnerBinOp) return Cond;
3311
3312   if (InnerBinOp->getOpcode() != BO_EQ ||
3313       !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3314     return Cond;
3315
3316   // If the inner binary operation came from a macro expansion named
3317   // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3318   // of the '||', which is the real, user-provided condition.
3319   SourceLocation Loc = InnerBinOp->getExprLoc();
3320   if (!Loc.isMacroID()) return Cond;
3321
3322   StringRef MacroName = PP.getImmediateMacroName(Loc);
3323   if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3324     return BinOp->getRHS();
3325
3326   return Cond;
3327 }
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       : Policy(P) {}
3338
3339   bool handledStmt(Stmt *E, raw_ostream &OS) override {
3340     const auto *DR = dyn_cast<DeclRefExpr>(E);
3341     if (DR && DR->getQualifier()) {
3342       // If this is a qualified name, expand the template arguments in nested
3343       // qualifiers.
3344       DR->getQualifier()->print(OS, Policy, true);
3345       // Then print the decl itself.
3346       const ValueDecl *VD = DR->getDecl();
3347       OS << VD->getName();
3348       if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3349         // This is a template variable, print the expanded template arguments.
3350         printTemplateArgumentList(OS, IV->getTemplateArgs().asArray(), Policy);
3351       }
3352       return true;
3353     }
3354     return false;
3355   }
3356
3357 private:
3358   const PrintingPolicy Policy;
3359 };
3360
3361 } // end anonymous namespace
3362
3363 std::pair<Expr *, std::string>
3364 Sema::findFailedBooleanCondition(Expr *Cond) {
3365   Cond = lookThroughRangesV3Condition(PP, Cond);
3366
3367   // Separate out all of the terms in a conjunction.
3368   SmallVector<Expr *, 4> Terms;
3369   collectConjunctionTerms(Cond, Terms);
3370
3371   // Determine which term failed.
3372   Expr *FailedCond = nullptr;
3373   for (Expr *Term : Terms) {
3374     Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3375
3376     // Literals are uninteresting.
3377     if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3378         isa<IntegerLiteral>(TermAsWritten))
3379       continue;
3380
3381     // The initialization of the parameter from the argument is
3382     // a constant-evaluated context.
3383     EnterExpressionEvaluationContext ConstantEvaluated(
3384       *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3385
3386     bool Succeeded;
3387     if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3388         !Succeeded) {
3389       FailedCond = TermAsWritten;
3390       break;
3391     }
3392   }
3393   if (!FailedCond)
3394     FailedCond = Cond->IgnoreParenImpCasts();
3395
3396   std::string Description;
3397   {
3398     llvm::raw_string_ostream Out(Description);
3399     PrintingPolicy Policy = getPrintingPolicy();
3400     Policy.PrintCanonicalTypes = true;
3401     FailedBooleanConditionPrinterHelper Helper(Policy);
3402     FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3403   }
3404   return { FailedCond, Description };
3405 }
3406
3407 QualType Sema::CheckTemplateIdType(TemplateName Name,
3408                                    SourceLocation TemplateLoc,
3409                                    TemplateArgumentListInfo &TemplateArgs) {
3410   DependentTemplateName *DTN
3411     = Name.getUnderlying().getAsDependentTemplateName();
3412   if (DTN && DTN->isIdentifier())
3413     // When building a template-id where the template-name is dependent,
3414     // assume the template is a type template. Either our assumption is
3415     // correct, or the code is ill-formed and will be diagnosed when the
3416     // dependent name is substituted.
3417     return Context.getDependentTemplateSpecializationType(ETK_None,
3418                                                           DTN->getQualifier(),
3419                                                           DTN->getIdentifier(),
3420                                                           TemplateArgs);
3421
3422   TemplateDecl *Template = Name.getAsTemplateDecl();
3423   if (!Template || isa<FunctionTemplateDecl>(Template) ||
3424       isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
3425     // We might have a substituted template template parameter pack. If so,
3426     // build a template specialization type for it.
3427     if (Name.getAsSubstTemplateTemplateParmPack())
3428       return Context.getTemplateSpecializationType(Name, TemplateArgs);
3429
3430     Diag(TemplateLoc, diag::err_template_id_not_a_type)
3431       << Name;
3432     NoteAllFoundTemplates(Name);
3433     return QualType();
3434   }
3435
3436   // Check that the template argument list is well-formed for this
3437   // template.
3438   SmallVector<TemplateArgument, 4> Converted;
3439   if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3440                                 false, Converted,
3441                                 /*UpdateArgsWithConversion=*/true))
3442     return QualType();
3443
3444   QualType CanonType;
3445
3446   bool InstantiationDependent = false;
3447   if (TypeAliasTemplateDecl *AliasTemplate =
3448           dyn_cast<TypeAliasTemplateDecl>(Template)) {
3449
3450     // Find the canonical type for this type alias template specialization.
3451     TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3452     if (Pattern->isInvalidDecl())
3453       return QualType();
3454
3455     TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
3456                                            Converted);
3457
3458     // Only substitute for the innermost template argument list.
3459     MultiLevelTemplateArgumentList TemplateArgLists;
3460     TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
3461     unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
3462     for (unsigned I = 0; I < Depth; ++I)
3463       TemplateArgLists.addOuterTemplateArguments(None);
3464
3465     LocalInstantiationScope Scope(*this);
3466     InstantiatingTemplate Inst(*this, TemplateLoc, Template);
3467     if (Inst.isInvalid())
3468       return QualType();
3469
3470     CanonType = SubstType(Pattern->getUnderlyingType(),
3471                           TemplateArgLists, AliasTemplate->getLocation(),
3472                           AliasTemplate->getDeclName());
3473     if (CanonType.isNull()) {
3474       // If this was enable_if and we failed to find the nested type
3475       // within enable_if in a SFINAE context, dig out the specific
3476       // enable_if condition that failed and present that instead.
3477       if (isEnableIfAliasTemplate(AliasTemplate)) {
3478         if (auto DeductionInfo = isSFINAEContext()) {
3479           if (*DeductionInfo &&
3480               (*DeductionInfo)->hasSFINAEDiagnostic() &&
3481               (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3482                 diag::err_typename_nested_not_found_enable_if &&
3483               TemplateArgs[0].getArgument().getKind()
3484                 == TemplateArgument::Expression) {
3485             Expr *FailedCond;
3486             std::string FailedDescription;
3487             std::tie(FailedCond, FailedDescription) =
3488               findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3489
3490             // Remove the old SFINAE diagnostic.
3491             PartialDiagnosticAt OldDiag =
3492               {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3493             (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3494
3495             // Add a new SFINAE diagnostic specifying which condition
3496             // failed.
3497             (*DeductionInfo)->addSFINAEDiagnostic(
3498               OldDiag.first,
3499               PDiag(diag::err_typename_nested_not_found_requirement)
3500                 << FailedDescription
3501                 << FailedCond->getSourceRange());
3502           }
3503         }
3504       }
3505
3506       return QualType();
3507     }
3508   } else if (Name.isDependent() ||
3509              TemplateSpecializationType::anyDependentTemplateArguments(
3510                TemplateArgs, InstantiationDependent)) {
3511     // This class template specialization is a dependent
3512     // type. Therefore, its canonical type is another class template
3513     // specialization type that contains all of the converted
3514     // arguments in canonical form. This ensures that, e.g., A<T> and
3515     // A<T, T> have identical types when A is declared as:
3516     //
3517     //   template<typename T, typename U = T> struct A;
3518     CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
3519
3520     // This might work out to be a current instantiation, in which
3521     // case the canonical type needs to be the InjectedClassNameType.
3522     //
3523     // TODO: in theory this could be a simple hashtable lookup; most
3524     // changes to CurContext don't change the set of current
3525     // instantiations.
3526     if (isa<ClassTemplateDecl>(Template)) {
3527       for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3528         // If we get out to a namespace, we're done.
3529         if (Ctx->isFileContext()) break;
3530
3531         // If this isn't a record, keep looking.
3532         CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3533         if (!Record) continue;
3534
3535         // Look for one of the two cases with InjectedClassNameTypes
3536         // and check whether it's the same template.
3537         if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3538             !Record->getDescribedClassTemplate())
3539           continue;
3540
3541         // Fetch the injected class name type and check whether its
3542         // injected type is equal to the type we just built.
3543         QualType ICNT = Context.getTypeDeclType(Record);
3544         QualType Injected = cast<InjectedClassNameType>(ICNT)
3545           ->getInjectedSpecializationType();
3546
3547         if (CanonType != Injected->getCanonicalTypeInternal())
3548           continue;
3549
3550         // If so, the canonical type of this TST is the injected
3551         // class name type of the record we just found.
3552         assert(ICNT.isCanonical());
3553         CanonType = ICNT;
3554         break;
3555       }
3556     }
3557   } else if (ClassTemplateDecl *ClassTemplate
3558                = dyn_cast<ClassTemplateDecl>(Template)) {
3559     // Find the class template specialization declaration that
3560     // corresponds to these arguments.
3561     void *InsertPos = nullptr;
3562     ClassTemplateSpecializationDecl *Decl
3563       = ClassTemplate->findSpecialization(Converted, InsertPos);
3564     if (!Decl) {
3565       // This is the first time we have referenced this class template
3566       // specialization. Create the canonical declaration and add it to
3567       // the set of specializations.
3568       Decl = ClassTemplateSpecializationDecl::Create(
3569           Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3570           ClassTemplate->getDeclContext(),
3571           ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3572           ClassTemplate->getLocation(), ClassTemplate, Converted, nullptr);
3573       ClassTemplate->AddSpecialization(Decl, InsertPos);
3574       if (ClassTemplate->isOutOfLine())
3575         Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3576     }
3577
3578     if (Decl->getSpecializationKind() == TSK_Undeclared) {
3579       MultiLevelTemplateArgumentList TemplateArgLists;
3580       TemplateArgLists.addOuterTemplateArguments(Converted);
3581       InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3582                               Decl);
3583     }
3584
3585     // Diagnose uses of this specialization.
3586     (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3587
3588     CanonType = Context.getTypeDeclType(Decl);
3589     assert(isa<RecordType>(CanonType) &&
3590            "type of non-dependent specialization is not a RecordType");
3591   } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3592     CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3593                                            TemplateArgs);
3594   }
3595
3596   // Build the fully-sugared type for this class template
3597   // specialization, which refers back to the class template
3598   // specialization we created or found.
3599   return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
3600 }
3601
3602 void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
3603                                            TemplateNameKind &TNK,
3604                                            SourceLocation NameLoc,
3605                                            IdentifierInfo *&II) {
3606   assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3607
3608   TemplateName Name = ParsedName.get();
3609   auto *ATN = Name.getAsAssumedTemplateName();
3610   assert(ATN && "not an assumed template name");
3611   II = ATN->getDeclName().getAsIdentifierInfo();
3612
3613   if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3614     // Resolved to a type template name.
3615     ParsedName = TemplateTy::make(Name);
3616     TNK = TNK_Type_template;
3617   }
3618 }
3619
3620 bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
3621                                             SourceLocation NameLoc,
3622                                             bool Diagnose) {
3623   // We assumed this undeclared identifier to be an (ADL-only) function
3624   // template name, but it was used in a context where a type was required.
3625   // Try to typo-correct it now.
3626   AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
3627   assert(ATN && "not an assumed template name");
3628
3629   LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3630   struct CandidateCallback : CorrectionCandidateCallback {
3631     bool ValidateCandidate(const TypoCorrection &TC) override {
3632       return TC.getCorrectionDecl() &&
3633              getAsTypeTemplateDecl(TC.getCorrectionDecl());
3634     }
3635     std::unique_ptr<CorrectionCandidateCallback> clone() override {
3636       return std::make_unique<CandidateCallback>(*this);
3637     }
3638   } FilterCCC;
3639
3640   TypoCorrection Corrected =
3641       CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
3642                   FilterCCC, CTK_ErrorRecovery);
3643   if (Corrected && Corrected.getFoundDecl()) {
3644     diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3645                                 << ATN->getDeclName());
3646     Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
3647     return false;
3648   }
3649
3650   if (Diagnose)
3651     Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3652   return true;
3653 }
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     bool IsCtorOrDtorName, bool IsClassName) {
3661   if (SS.isInvalid())
3662     return true;
3663
3664   if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3665     DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3666
3667     // C++ [temp.res]p3:
3668     //   A qualified-id that refers to a type and in which the
3669     //   nested-name-specifier depends on a template-parameter (14.6.2)
3670     //   shall be prefixed by the keyword typename to indicate that the
3671     //   qualified-id denotes a type, forming an
3672     //   elaborated-type-specifier (7.1.5.3).
3673     if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3674       Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3675         << SS.getScopeRep() << TemplateII->getName();
3676       // Recover as if 'typename' were specified.
3677       // FIXME: This is not quite correct recovery as we don't transform SS
3678       // into the corresponding dependent form (and we don't diagnose missing
3679       // 'template' keywords within SS as a result).
3680       return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3681                                TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3682                                TemplateArgsIn, RAngleLoc);
3683     }
3684
3685     // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3686     // it's not actually allowed to be used as a type in most cases. Because
3687     // we annotate it before we know whether it's valid, we have to check for
3688     // this case here.
3689     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3690     if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3691       Diag(TemplateIILoc,
3692            TemplateKWLoc.isInvalid()
3693                ? diag::err_out_of_line_qualified_id_type_names_constructor
3694                : diag::ext_out_of_line_qualified_id_type_names_constructor)
3695         << TemplateII << 0 /*injected-class-name used as template name*/
3696         << 1 /*if any keyword was present, it was 'template'*/;
3697     }
3698   }
3699
3700   TemplateName Template = TemplateD.get();
3701   if (Template.getAsAssumedTemplateName() &&
3702       resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
3703     return true;
3704
3705   // Translate the parser's template argument list in our AST format.
3706   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3707   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3708
3709   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3710     QualType T
3711       = Context.getDependentTemplateSpecializationType(ETK_None,
3712                                                        DTN->getQualifier(),
3713                                                        DTN->getIdentifier(),
3714                                                        TemplateArgs);
3715     // Build type-source information.
3716     TypeLocBuilder TLB;
3717     DependentTemplateSpecializationTypeLoc SpecTL
3718       = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3719     SpecTL.setElaboratedKeywordLoc(SourceLocation());
3720     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3721     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3722     SpecTL.setTemplateNameLoc(TemplateIILoc);
3723     SpecTL.setLAngleLoc(LAngleLoc);
3724     SpecTL.setRAngleLoc(RAngleLoc);
3725     for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3726       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3727     return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3728   }
3729
3730   QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3731   if (Result.isNull())
3732     return true;
3733
3734   // Build type-source information.
3735   TypeLocBuilder TLB;
3736   TemplateSpecializationTypeLoc SpecTL
3737     = TLB.push<TemplateSpecializationTypeLoc>(Result);
3738   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3739   SpecTL.setTemplateNameLoc(TemplateIILoc);
3740   SpecTL.setLAngleLoc(LAngleLoc);
3741   SpecTL.setRAngleLoc(RAngleLoc);
3742   for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3743     SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3744
3745   // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3746   // constructor or destructor name (in such a case, the scope specifier
3747   // will be attached to the enclosing Decl or Expr node).
3748   if (SS.isNotEmpty() && !IsCtorOrDtorName) {
3749     // Create an elaborated-type-specifier containing the nested-name-specifier.
3750     Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3751     ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3752     ElabTL.setElaboratedKeywordLoc(SourceLocation());
3753     ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3754   }
3755
3756   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3757 }
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                                         SourceLocation RAngleLoc) {
3769   TemplateName Template = TemplateD.get();
3770
3771   // Translate the parser's template argument list in our AST format.
3772   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3773   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3774
3775   // Determine the tag kind
3776   TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3777   ElaboratedTypeKeyword Keyword
3778     = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
3779
3780   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3781     QualType T = Context.getDependentTemplateSpecializationType(Keyword,
3782                                                           DTN->getQualifier(),
3783                                                           DTN->getIdentifier(),
3784                                                                 TemplateArgs);
3785
3786     // Build type-source information.
3787     TypeLocBuilder TLB;
3788     DependentTemplateSpecializationTypeLoc SpecTL
3789       = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3790     SpecTL.setElaboratedKeywordLoc(TagLoc);
3791     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3792     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3793     SpecTL.setTemplateNameLoc(TemplateLoc);
3794     SpecTL.setLAngleLoc(LAngleLoc);
3795     SpecTL.setRAngleLoc(RAngleLoc);
3796     for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3797       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3798     return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3799   }
3800
3801   if (TypeAliasTemplateDecl *TAT =
3802         dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3803     // C++0x [dcl.type.elab]p2:
3804     //   If the identifier resolves to a typedef-name or the simple-template-id
3805     //   resolves to an alias template specialization, the
3806     //   elaborated-type-specifier is ill-formed.
3807     Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3808         << TAT << NTK_TypeAliasTemplate << TagKind;
3809     Diag(TAT->getLocation(), diag::note_declared_at);
3810   }
3811
3812   QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3813   if (Result.isNull())
3814     return TypeResult(true);
3815
3816   // Check the tag kind
3817   if (const RecordType *RT = Result->getAs<RecordType>()) {
3818     RecordDecl *D = RT->getDecl();
3819
3820     IdentifierInfo *Id = D->getIdentifier();
3821     assert(Id && "templated class must have an identifier");
3822
3823     if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
3824                                       TagLoc, Id)) {
3825       Diag(TagLoc, diag::err_use_with_wrong_tag)
3826         << Result
3827         << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
3828       Diag(D->getLocation(), diag::note_previous_use);
3829     }
3830   }
3831
3832   // Provide source-location information for the template specialization.
3833   TypeLocBuilder TLB;
3834   TemplateSpecializationTypeLoc SpecTL
3835     = TLB.push<TemplateSpecializationTypeLoc>(Result);
3836   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3837   SpecTL.setTemplateNameLoc(TemplateLoc);
3838   SpecTL.setLAngleLoc(LAngleLoc);
3839   SpecTL.setRAngleLoc(RAngleLoc);
3840   for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3841     SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3842
3843   // Construct an elaborated type containing the nested-name-specifier (if any)
3844   // and tag keyword.
3845   Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3846   ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3847   ElabTL.setElaboratedKeywordLoc(TagLoc);
3848   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3849   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3850 }
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     const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3861   switch (Arg.getKind()) {
3862   case TemplateArgument::Null:
3863   case TemplateArgument::NullPtr:
3864   case TemplateArgument::Integral:
3865   case TemplateArgument::Declaration:
3866   case TemplateArgument::Pack:
3867   case TemplateArgument::TemplateExpansion:
3868     return false;
3869
3870   case TemplateArgument::Type: {
3871     QualType Type = Arg.getAsType();
3872     const TemplateTypeParmType *TPT =
3873         Arg.getAsType()->getAs<TemplateTypeParmType>();
3874     return TPT && !Type.hasQualifiers() &&
3875            TPT->getDepth() == Depth && TPT->getIndex() == Index;
3876   }
3877
3878   case TemplateArgument::Expression: {
3879     DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3880     if (!DRE || !DRE->getDecl())
3881       return false;
3882     const NonTypeTemplateParmDecl *NTTP =
3883         dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3884     return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3885   }
3886
3887   case TemplateArgument::Template:
3888     const TemplateTemplateParmDecl *TTP =
3889         dyn_cast_or_null<TemplateTemplateParmDecl>(
3890             Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3891     return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3892   }
3893   llvm_unreachable("unexpected kind of template argument");
3894 }
3895
3896 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3897                                     ArrayRef<TemplateArgument> Args) {
3898   if (Params->size() != Args.size())
3899     return false;
3900
3901   unsigned Depth = Params->getDepth();
3902
3903   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3904     TemplateArgument Arg = Args[I];
3905
3906     // If the parameter is a pack expansion, the argument must be a pack
3907     // whose only element is a pack expansion.
3908     if (Params->getParam(I)->isParameterPack()) {
3909       if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3910           !Arg.pack_begin()->isPackExpansion())
3911         return false;
3912       Arg = Arg.pack_begin()->getPackExpansionPattern();
3913     }
3914
3915     if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3916       return false;
3917   }
3918
3919   return true;
3920 }
3921
3922 template<typename PartialSpecDecl>
3923 static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3924   if (Partial->getDeclContext()->isDependentContext())
3925     return;
3926
3927   // FIXME: Get the TDK from deduction in order to provide better diagnostics
3928   // for non-substitution-failure issues?
3929   TemplateDeductionInfo Info(Partial->getLocation());
3930   if (S.isMoreSpecializedThanPrimary(Partial, Info))
3931     return;
3932
3933   auto *Template = Partial->getSpecializedTemplate();
3934   S.Diag(Partial->getLocation(),
3935          diag::ext_partial_spec_not_more_specialized_than_primary)
3936       << isa<VarTemplateDecl>(Template);
3937
3938   if (Info.hasSFINAEDiagnostic()) {
3939     PartialDiagnosticAt Diag = {SourceLocation(),
3940                                 PartialDiagnostic::NullDiagnostic()};
3941     Info.takeSFINAEDiagnostic(Diag);
3942     SmallString<128> SFINAEArgString;
3943     Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3944     S.Diag(Diag.first,
3945            diag::note_partial_spec_not_more_specialized_than_primary)
3946       << SFINAEArgString;
3947   }
3948
3949   S.Diag(Template->getLocation(), diag::note_template_decl_here);
3950   SmallVector<const Expr *, 3> PartialAC, TemplateAC;
3951   Template->getAssociatedConstraints(TemplateAC);
3952   Partial->getAssociatedConstraints(PartialAC);
3953   S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
3954                                                   TemplateAC);
3955 }
3956
3957 static void
3958 noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3959                            const llvm::SmallBitVector &DeducibleParams) {
3960   for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3961     if (!DeducibleParams[I]) {
3962       NamedDecl *Param = TemplateParams->getParam(I);
3963       if (Param->getDeclName())
3964         S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3965             << Param->getDeclName();
3966       else
3967         S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3968             << "(anonymous)";
3969     }
3970   }
3971 }
3972
3973
3974 template<typename PartialSpecDecl>
3975 static void checkTemplatePartialSpecialization(Sema &S,
3976                                                PartialSpecDecl *Partial) {
3977   // C++1z [temp.class.spec]p8: (DR1495)
3978   //   - The specialization shall be more specialized than the primary
3979   //     template (14.5.5.2).
3980   checkMoreSpecializedThanPrimary(S, Partial);
3981
3982   // C++ [temp.class.spec]p8: (DR1315)
3983   //   - Each template-parameter shall appear at least once in the
3984   //     template-id outside a non-deduced context.
3985   // C++1z [temp.class.spec.match]p3 (P0127R2)
3986   //   If the template arguments of a partial specialization cannot be
3987   //   deduced because of the structure of its template-parameter-list
3988   //   and the template-id, the program is ill-formed.
3989   auto *TemplateParams = Partial->getTemplateParameters();
3990   llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3991   S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3992                                TemplateParams->getDepth(), DeducibleParams);
3993
3994   if (!DeducibleParams.all()) {
3995     unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3996     S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3997       << isa<VarTemplatePartialSpecializationDecl>(Partial)
3998       << (NumNonDeducible > 1)
3999       << SourceRange(Partial->getLocation(),
4000                      Partial->getTemplateArgsAsWritten()->RAngleLoc);
4001     noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4002   }
4003 }
4004
4005 void Sema::CheckTemplatePartialSpecialization(
4006     ClassTemplatePartialSpecializationDecl *Partial) {
4007   checkTemplatePartialSpecialization(*this, Partial);
4008 }
4009
4010 void Sema::CheckTemplatePartialSpecialization(
4011     VarTemplatePartialSpecializationDecl *Partial) {
4012   checkTemplatePartialSpecialization(*this, Partial);
4013 }
4014
4015 void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
4016   // C++1z [temp.param]p11:
4017   //   A template parameter of a deduction guide template that does not have a
4018   //   default-argument shall be deducible from the parameter-type-list of the
4019   //   deduction guide template.
4020   auto *TemplateParams = TD->getTemplateParameters();
4021   llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4022   MarkDeducedTemplateParameters(TD, DeducibleParams);
4023   for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4024     // A parameter pack is deducible (to an empty pack).
4025     auto *Param = TemplateParams->getParam(I);
4026     if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4027       DeducibleParams[I] = true;
4028   }
4029
4030   if (!DeducibleParams.all()) {
4031     unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4032     Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4033       << (NumNonDeducible > 1);
4034     noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4035   }
4036 }
4037
4038 DeclResult Sema::ActOnVarTemplateSpecialization(
4039     Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
4040     TemplateParameterList *TemplateParams, StorageClass SC,
4041     bool IsPartialSpecialization) {
4042   // D must be variable template id.
4043   assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
4044          "Variable template specialization is declared with a template it.");
4045
4046   TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4047   TemplateArgumentListInfo TemplateArgs =
4048       makeTemplateArgumentListInfo(*this, *TemplateId);
4049   SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4050   SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4051   SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4052
4053   TemplateName Name = TemplateId->Template.get();
4054
4055   // The template-id must name a variable template.
4056   VarTemplateDecl *VarTemplate =
4057       dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4058   if (!VarTemplate) {
4059     NamedDecl *FnTemplate;
4060     if (auto *OTS = Name.getAsOverloadedTemplate())
4061       FnTemplate = *OTS->begin();
4062     else
4063       FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4064     if (FnTemplate)
4065       return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4066                << FnTemplate->getDeclName();
4067     return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4068              << IsPartialSpecialization;
4069   }
4070
4071   // Check for unexpanded parameter packs in any of the template arguments.
4072   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4073     if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4074                                         UPPC_PartialSpecialization))
4075       return true;
4076
4077   // Check that the template argument list is well-formed for this
4078   // template.
4079   SmallVector<TemplateArgument, 4> Converted;
4080   if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4081                                 false, Converted,
4082                                 /*UpdateArgsWithConversion=*/true))
4083     return true;
4084
4085   // Find the variable template (partial) specialization declaration that
4086   // corresponds to these arguments.
4087   if (IsPartialSpecialization) {
4088     if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
4089                                                TemplateArgs.size(), Converted))
4090       return true;
4091
4092     // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
4093     // also do them during instantiation.
4094     bool InstantiationDependent;
4095     if (!Name.isDependent() &&
4096         !TemplateSpecializationType::anyDependentTemplateArguments(
4097             TemplateArgs.arguments(),
4098             InstantiationDependent)) {
4099       Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4100           << VarTemplate->getDeclName();
4101       IsPartialSpecialization = false;
4102     }
4103
4104     if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4105                                 Converted) &&
4106         (!Context.getLangOpts().CPlusPlus2a ||
4107          !TemplateParams->hasAssociatedConstraints())) {
4108       // C++ [temp.class.spec]p9b3:
4109       //
4110       //   -- The argument list of the specialization shall not be identical
4111       //      to the implicit argument list of the primary template.
4112       Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4113         << /*variable template*/ 1
4114         << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
4115         << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4116       // FIXME: Recover from this by treating the declaration as a redeclaration
4117       // of the primary template.
4118       return true;
4119     }
4120   }
4121
4122   void *InsertPos = nullptr;
4123   VarTemplateSpecializationDecl *PrevDecl = nullptr;
4124
4125   if (IsPartialSpecialization)
4126     PrevDecl = VarTemplate->findPartialSpecialization(Converted, TemplateParams,
4127                                                       InsertPos);
4128   else
4129     PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
4130
4131   VarTemplateSpecializationDecl *Specialization = nullptr;
4132
4133   // Check whether we can declare a variable template specialization in
4134   // the current scope.
4135   if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4136                                        TemplateNameLoc,
4137                                        IsPartialSpecialization))
4138     return true;
4139
4140   if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4141     // Since the only prior variable template specialization with these
4142     // arguments was referenced but not declared,  reuse that
4143     // declaration node as our own, updating its source location and
4144     // the list of outer template parameters to reflect our new declaration.
4145     Specialization = PrevDecl;
4146     Specialization->setLocation(TemplateNameLoc);
4147     PrevDecl = nullptr;
4148   } else if (IsPartialSpecialization) {
4149     // Create a new class template partial specialization declaration node.
4150     VarTemplatePartialSpecializationDecl *PrevPartial =
4151         cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4152     VarTemplatePartialSpecializationDecl *Partial =
4153         VarTemplatePartialSpecializationDecl::Create(
4154             Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4155             TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4156             Converted, TemplateArgs);
4157
4158     if (!PrevPartial)
4159       VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4160     Specialization = Partial;
4161
4162     // If we are providing an explicit specialization of a member variable
4163     // template specialization, make a note of that.
4164     if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4165       PrevPartial->setMemberSpecialization();
4166
4167     CheckTemplatePartialSpecialization(Partial);
4168   } else {
4169     // Create a new class template specialization declaration node for
4170     // this explicit specialization or friend declaration.
4171     Specialization = VarTemplateSpecializationDecl::Create(
4172         Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4173         VarTemplate, DI->getType(), DI, SC, Converted);
4174     Specialization->setTemplateArgsInfo(TemplateArgs);
4175
4176     if (!PrevDecl)
4177       VarTemplate->AddSpecialization(Specialization, InsertPos);
4178   }
4179
4180   // C++ [temp.expl.spec]p6:
4181   //   If a template, a member template or the member of a class template is
4182   //   explicitly specialized then that specialization shall be declared
4183   //   before the first use of that specialization that would cause an implicit
4184   //   instantiation to take place, in every translation unit in which such a
4185   //   use occurs; no diagnostic is required.
4186   if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4187     bool Okay = false;
4188     for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4189       // Is there any previous explicit specialization declaration?
4190       if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4191         Okay = true;
4192         break;
4193       }
4194     }
4195
4196     if (!Okay) {
4197       SourceRange Range(TemplateNameLoc, RAngleLoc);
4198       Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4199           << Name << Range;
4200
4201       Diag(PrevDecl->getPointOfInstantiation(),
4202            diag::note_instantiation_required_here)
4203           << (PrevDecl->getTemplateSpecializationKind() !=
4204               TSK_ImplicitInstantiation);
4205       return true;
4206     }
4207   }
4208
4209   Specialization->setTemplateKeywordLoc(TemplateKWLoc);
4210   Specialization->setLexicalDeclContext(CurContext);
4211
4212   // Add the specialization into its lexical context, so that it can
4213   // be seen when iterating through the list of declarations in that
4214   // context. However, specializations are not found by name lookup.
4215   CurContext->addDecl(Specialization);
4216
4217   // Note that this is an explicit specialization.
4218   Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4219
4220   if (PrevDecl) {
4221     // Check that this isn't a redefinition of this specialization,
4222     // merging with previous declarations.
4223     LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
4224                           forRedeclarationInCurContext());
4225     PrevSpec.addDecl(PrevDecl);
4226     D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
4227   } else if (Specialization->isStaticDataMember() &&
4228              Specialization->isOutOfLine()) {
4229     Specialization->setAccess(VarTemplate->getAccess());
4230   }
4231
4232   return Specialization;
4233 }
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                          const TemplateArgumentListInfo &TemplateArgs) {
4248   assert(Template && "A variable template id without template?");
4249
4250   // Check that the template argument list is well-formed for this template.
4251   SmallVector<TemplateArgument, 4> Converted;
4252   if (CheckTemplateArgumentList(
4253           Template, TemplateNameLoc,
4254           const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
4255           Converted, /*UpdateArgsWithConversion=*/true))
4256     return true;
4257
4258   // Find the variable template specialization declaration that
4259   // corresponds to these arguments.
4260   void *InsertPos = nullptr;
4261   if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
4262           Converted, InsertPos)) {
4263     checkSpecializationVisibility(TemplateNameLoc, Spec);
4264     // If we already have a variable template specialization, return it.
4265     return Spec;
4266   }
4267
4268   // This is the first time we have referenced this variable template
4269   // specialization. Create the canonical declaration and add it to
4270   // the set of specializations, based on the closest partial specialization
4271   // that it represents. That is,
4272   VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4273   TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
4274                                        Converted);
4275   TemplateArgumentList *InstantiationArgs = &TemplateArgList;
4276   bool AmbiguousPartialSpec = false;
4277   typedef PartialSpecMatchResult MatchResult;
4278   SmallVector<MatchResult, 4> Matched;
4279   SourceLocation PointOfInstantiation = TemplateNameLoc;
4280   TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4281                                             /*ForTakingAddress=*/false);
4282
4283   // 1. Attempt to find the closest partial specialization that this
4284   // specializes, if any.
4285   // If any of the template arguments is dependent, then this is probably
4286   // a placeholder for an incomplete declarative context; which must be
4287   // complete by instantiation time. Thus, do not search through the partial
4288   // specializations yet.
4289   // TODO: Unify with InstantiateClassTemplateSpecialization()?
4290   //       Perhaps better after unification of DeduceTemplateArguments() and
4291   //       getMoreSpecializedPartialSpecialization().
4292   bool InstantiationDependent = false;
4293   if (!TemplateSpecializationType::anyDependentTemplateArguments(
4294           TemplateArgs, InstantiationDependent)) {
4295
4296     SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4297     Template->getPartialSpecializations(PartialSpecs);
4298
4299     for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
4300       VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
4301       TemplateDeductionInfo Info(FailedCandidates.getLocation());
4302
4303       if (TemplateDeductionResult Result =
4304               DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
4305         // Store the failed-deduction information for use in diagnostics, later.
4306         // TODO: Actually use the failed-deduction info?
4307         FailedCandidates.addCandidate().set(
4308             DeclAccessPair::make(Template, AS_public), Partial,
4309             MakeDeductionFailureInfo(Context, Result, Info));
4310         (void)Result;
4311       } else {
4312         Matched.push_back(PartialSpecMatchResult());
4313         Matched.back().Partial = Partial;
4314         Matched.back().Args = Info.take();
4315       }
4316     }
4317
4318     if (Matched.size() >= 1) {
4319       SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4320       if (Matched.size() == 1) {
4321         //   -- If exactly one matching specialization is found, the
4322         //      instantiation is generated from that specialization.
4323         // We don't need to do anything for this.
4324       } else {
4325         //   -- If more than one matching specialization is found, the
4326         //      partial order rules (14.5.4.2) are used to determine
4327         //      whether one of the specializations is more specialized
4328         //      than the others. If none of the specializations is more
4329         //      specialized than all of the other matching
4330         //      specializations, then the use of the variable template is
4331         //      ambiguous and the program is ill-formed.
4332         for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4333                                                    PEnd = Matched.end();
4334              P != PEnd; ++P) {
4335           if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4336                                                       PointOfInstantiation) ==
4337               P->Partial)
4338             Best = P;
4339         }
4340
4341         // Determine if the best partial specialization is more specialized than
4342         // the others.
4343         for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4344                                                    PEnd = Matched.end();
4345              P != PEnd; ++P) {
4346           if (P != Best && getMoreSpecializedPartialSpecialization(
4347                                P->Partial, Best->Partial,
4348                                PointOfInstantiation) != Best->Partial) {
4349             AmbiguousPartialSpec = true;
4350             break;
4351           }
4352         }
4353       }
4354
4355       // Instantiate using the best variable template partial specialization.
4356       InstantiationPattern = Best->Partial;
4357       InstantiationArgs = Best->Args;
4358     } else {
4359       //   -- If no match is found, the instantiation is generated
4360       //      from the primary template.
4361       // InstantiationPattern = Template->getTemplatedDecl();
4362     }
4363   }
4364
4365   // 2. Create the canonical declaration.
4366   // Note that we do not instantiate a definition until we see an odr-use
4367   // in DoMarkVarDeclReferenced().
4368   // FIXME: LateAttrs et al.?
4369   VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4370       Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
4371       Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
4372   if (!Decl)
4373     return true;
4374
4375   if (AmbiguousPartialSpec) {
4376     // Partial ordering did not produce a clear winner. Complain.
4377     Decl->setInvalidDecl();
4378     Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4379         << Decl;
4380
4381     // Print the matching partial specializations.
4382     for (MatchResult P : Matched)
4383       Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4384           << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4385                                              *P.Args);
4386     return true;
4387   }
4388
4389   if (VarTemplatePartialSpecializationDecl *D =
4390           dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4391     Decl->setInstantiationOf(D, InstantiationArgs);
4392
4393   checkSpecializationVisibility(TemplateNameLoc, Decl);
4394
4395   assert(Decl && "No variable template specialization?");
4396   return Decl;
4397 }
4398
4399 ExprResult
4400 Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
4401                          const DeclarationNameInfo &NameInfo,
4402                          VarTemplateDecl *Template, SourceLocation TemplateLoc,
4403                          const TemplateArgumentListInfo *TemplateArgs) {
4404
4405   DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4406                                        *TemplateArgs);
4407   if (Decl.isInvalid())
4408     return ExprError();
4409
4410   VarDecl *Var = cast<VarDecl>(Decl.get());
4411   if (!Var->getTemplateSpecializationKind())
4412     Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
4413                                        NameInfo.getLoc());
4414
4415   // Build an ordinary singleton decl ref.
4416   return BuildDeclarationNameExpr(SS, NameInfo, Var,
4417                                   /*FoundD=*/nullptr, TemplateArgs);
4418 }
4419
4420 void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4421                                             SourceLocation Loc) {
4422   Diag(Loc, diag::err_template_missing_args)
4423     << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4424   if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4425     Diag(TD->getLocation(), diag::note_template_decl_here)
4426       << TD->getTemplateParameters()->getSourceRange();
4427   }
4428 }
4429
4430 ExprResult
4431 Sema::CheckConceptTemplateId(const CXXScopeSpec &SS,
4432                              SourceLocation TemplateKWLoc,
4433                              const DeclarationNameInfo &ConceptNameInfo,
4434                              NamedDecl *FoundDecl,
4435                              ConceptDecl *NamedConcept,
4436                              const TemplateArgumentListInfo *TemplateArgs) {
4437   assert(NamedConcept && "A concept template id without a template?");
4438
4439   llvm::SmallVector<TemplateArgument, 4> Converted;
4440   if (CheckTemplateArgumentList(NamedConcept, ConceptNameInfo.getLoc(),
4441                            const_cast<TemplateArgumentListInfo&>(*TemplateArgs),
4442                                 /*PartialTemplateArgs=*/false, Converted,
4443                                 /*UpdateArgsWithConversion=*/false))
4444     return ExprError();
4445
4446   ConstraintSatisfaction Satisfaction;
4447   bool AreArgsDependent = false;
4448   for (TemplateArgument &Arg : Converted) {
4449     if (Arg.isDependent()) {
4450       AreArgsDependent = true;
4451       break;
4452     }
4453   }
4454   if (!AreArgsDependent &&
4455       CheckConstraintSatisfaction(NamedConcept,
4456                                   {NamedConcept->getConstraintExpr()},
4457                                   Converted,
4458                                   SourceRange(SS.isSet() ? SS.getBeginLoc() :
4459                                                        ConceptNameInfo.getLoc(),
4460                                                 TemplateArgs->getRAngleLoc()),
4461                                     Satisfaction))
4462       return ExprError();
4463
4464   return ConceptSpecializationExpr::Create(Context,
4465       SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
4466       TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4467       ASTTemplateArgumentListInfo::Create(Context, *TemplateArgs), Converted,
4468       AreArgsDependent ? nullptr : &Satisfaction);
4469 }
4470
4471 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
4472                                      SourceLocation TemplateKWLoc,
4473                                      LookupResult &R,
4474                                      bool RequiresADL,
4475                                  const TemplateArgumentListInfo *TemplateArgs) {
4476   // FIXME: Can we do any checking at this point? I guess we could check the
4477   // template arguments that we have against the template name, if the template
4478   // name refers to a single template. That's not a terribly common case,
4479   // though.
4480   // foo<int> could identify a single function unambiguously
4481   // This approach does NOT work, since f<int>(1);
4482   // gets resolved prior to resorting to overload resolution
4483   // i.e., template<class T> void f(double);
4484   //       vs template<class T, class U> void f(U);
4485
4486   // These should be filtered out by our callers.
4487   assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4488
4489   // Non-function templates require a template argument list.
4490   if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4491     if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4492       diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
4493       return ExprError();
4494     }
4495   }
4496
4497   auto AnyDependentArguments = [&]() -> bool {
4498     bool InstantiationDependent;
4499     return TemplateArgs &&
4500            TemplateSpecializationType::anyDependentTemplateArguments(
4501                *TemplateArgs, InstantiationDependent);
4502   };
4503
4504   // In C++1y, check variable template ids.
4505   if (R.getAsSingle<VarTemplateDecl>() && !AnyDependentArguments()) {
4506     return CheckVarTemplateId(SS, R.getLookupNameInfo(),
4507                               R.getAsSingle<VarTemplateDecl>(),
4508                               TemplateKWLoc, TemplateArgs);
4509   }
4510
4511   if (R.getAsSingle<ConceptDecl>()) {
4512     return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4513                                   R.getFoundDecl(),
4514                                   R.getAsSingle<ConceptDecl>(), TemplateArgs);
4515   }
4516
4517   // We don't want lookup warnings at this point.
4518   R.suppressDiagnostics();
4519
4520   UnresolvedLookupExpr *ULE
4521     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
4522                                    SS.getWithLocInContext(Context),
4523                                    TemplateKWLoc,
4524                                    R.getLookupNameInfo(),
4525                                    RequiresADL, TemplateArgs,
4526                                    R.begin(), R.end());
4527
4528   return ULE;
4529 }
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                              const TemplateArgumentListInfo *TemplateArgs) {
4537
4538   assert(TemplateArgs || TemplateKWLoc.isValid());
4539   DeclContext *DC;
4540   if (!(DC = computeDeclContext(SS, false)) ||
4541       DC->isDependentContext() ||
4542       RequireCompleteDeclContext(SS, DC))
4543     return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4544
4545   bool MemberOfUnknownSpecialization;
4546   LookupResult R(*this, NameInfo, LookupOrdinaryName);
4547   if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
4548                          /*Entering*/false, MemberOfUnknownSpecialization,
4549                          TemplateKWLoc))
4550     return ExprError();
4551
4552   if (R.isAmbiguous())
4553     return ExprError();
4554
4555   if (R.empty()) {
4556     Diag(NameInfo.getLoc(), diag::err_no_member)
4557       << NameInfo.getName() << DC << SS.getRange();
4558     return ExprError();
4559   }
4560
4561   if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
4562     Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
4563       << SS.getScopeRep()
4564       << NameInfo.getName().getAsString() << SS.getRange();
4565     Diag(Temp->getLocation(), diag::note_referenced_class_template);
4566     return ExprError();
4567   }
4568
4569   return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
4570 }
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                                                   bool AllowInjectedClassName) {
4587   if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4588     Diag(TemplateKWLoc,
4589          getLangOpts().CPlusPlus11 ?
4590            diag::warn_cxx98_compat_template_outside_of_template :
4591            diag::ext_template_outside_of_template)
4592       << FixItHint::CreateRemoval(TemplateKWLoc);
4593
4594   DeclContext *LookupCtx = nullptr;
4595   if (SS.isSet())
4596     LookupCtx = computeDeclContext(SS, EnteringContext);
4597   if (!LookupCtx && ObjectType)
4598     LookupCtx = computeDeclContext(ObjectType.get());
4599   if (LookupCtx) {
4600     // C++0x [temp.names]p5:
4601     //   If a name prefixed by the keyword template is not the name of
4602     //   a template, the program is ill-formed. [Note: the keyword
4603     //   template may not be applied to non-template members of class
4604     //   templates. -end note ] [ Note: as is the case with the
4605     //   typename prefix, the template prefix is allowed in cases
4606     //   where it is not strictly necessary; i.e., when the
4607     //   nested-name-specifier or the expression on the left of the ->
4608     //   or . is not dependent on a template-parameter, or the use
4609     //   does not appear in the scope of a template. -end note]
4610     //
4611     // Note: C++03 was more strict here, because it banned the use of
4612     // the "template" keyword prior to a template-name that was not a
4613     // dependent name. C++ DR468 relaxed this requirement (the
4614     // "template" keyword is now permitted). We follow the C++0x
4615     // rules, even in C++03 mode with a warning, retroactively applying the DR.
4616     bool MemberOfUnknownSpecialization;
4617     TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4618                                           ObjectType, EnteringContext, Result,
4619                                           MemberOfUnknownSpecialization);
4620     if (TNK == TNK_Non_template && MemberOfUnknownSpecialization) {
4621       // This is a dependent template. Handle it below.
4622     } else if (TNK == TNK_Non_template) {
4623       // Do the lookup again to determine if this is a "nothing found" case or
4624       // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4625       // need to do this.
4626       DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
4627       LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
4628                      LookupOrdinaryName);
4629       bool MOUS;
4630       if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext,
4631                               MOUS, TemplateKWLoc) && !R.isAmbiguous())
4632         Diag(Name.getBeginLoc(), diag::err_no_member)
4633             << DNI.getName() << LookupCtx << SS.getRange();
4634       return TNK_Non_template;
4635     } else {
4636       // We found something; return it.
4637       auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
4638       if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
4639           Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4640           Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4641         // C++14 [class.qual]p2:
4642         //   In a lookup in which function names are not ignored and the
4643         //   nested-name-specifier nominates a class C, if the name specified
4644         //   [...] is the injected-class-name of C, [...] the name is instead
4645         //   considered to name the constructor
4646         //
4647         // We don't get here if naming the constructor would be valid, so we
4648         // just reject immediately and recover by treating the
4649         // injected-class-name as naming the template.
4650         Diag(Name.getBeginLoc(),
4651              diag::ext_out_of_line_qualified_id_type_names_constructor)
4652             << Name.Identifier
4653             << 0 /*injected-class-name used as template name*/
4654             << 1 /*'template' keyword was used*/;
4655       }
4656       return TNK;
4657     }
4658   }
4659
4660   NestedNameSpecifier *Qualifier = SS.getScopeRep();
4661
4662   switch (Name.getKind()) {
4663   case UnqualifiedIdKind::IK_Identifier:
4664     Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4665                                                               Name.Identifier));
4666     return TNK_Dependent_template_name;
4667
4668   case UnqualifiedIdKind::IK_OperatorFunctionId:
4669     Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4670                                              Name.OperatorFunctionId.Operator));
4671     return TNK_Function_template;
4672
4673   case UnqualifiedIdKind::IK_LiteralOperatorId:
4674     llvm_unreachable("literal operator id cannot have a dependent scope");
4675
4676   default:
4677     break;
4678   }
4679
4680   Diag(Name.getBeginLoc(), diag::err_template_kw_refers_to_non_template)
4681       << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4682       << TemplateKWLoc;
4683   return TNK_Non_template;
4684 }
4685
4686 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
4687                                      TemplateArgumentLoc &AL,
4688                           SmallVectorImpl<TemplateArgument> &Converted) {
4689   const TemplateArgument &Arg = AL.getArgument();
4690   QualType ArgType;
4691   TypeSourceInfo *TSI = nullptr;
4692
4693   // Check template type parameter.
4694   switch(Arg.getKind()) {
4695   case TemplateArgument::Type:
4696     // C++ [temp.arg.type]p1:
4697     //   A template-argument for a template-parameter which is a
4698     //   type shall be a type-id.
4699     ArgType = Arg.getAsType();
4700     TSI = AL.getTypeSourceInfo();
4701     break;
4702   case TemplateArgument::Template:
4703   case TemplateArgument::TemplateExpansion: {
4704     // We have a template type parameter but the template argument
4705     // is a template without any arguments.
4706     SourceRange SR = AL.getSourceRange();
4707     TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
4708     diagnoseMissingTemplateArguments(Name, SR.getEnd());
4709     return true;
4710   }
4711   case TemplateArgument::Expression: {
4712     // We have a template type parameter but the template argument is an
4713     // expression; see if maybe it is missing the "typename" keyword.
4714     CXXScopeSpec SS;
4715     DeclarationNameInfo NameInfo;
4716
4717     if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
4718       SS.Adopt(ArgExpr->getQualifierLoc());
4719       NameInfo = ArgExpr->getNameInfo();
4720     } else if (DependentScopeDeclRefExpr *ArgExpr =
4721                dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4722       SS.Adopt(ArgExpr->getQualifierLoc());
4723       NameInfo = ArgExpr->getNameInfo();
4724     } else if (CXXDependentScopeMemberExpr *ArgExpr =
4725                dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
4726       if (ArgExpr->isImplicitAccess()) {
4727         SS.Adopt(ArgExpr->getQualifierLoc());
4728         NameInfo = ArgExpr->getMemberNameInfo();
4729       }
4730     }
4731
4732     if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
4733       LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4734       LookupParsedName(Result, CurScope, &SS);
4735
4736       if (Result.getAsSingle<TypeDecl>() ||
4737           Result.getResultKind() ==
4738               LookupResult::NotFoundInCurrentInstantiation) {
4739         // Suggest that the user add 'typename' before the NNS.
4740         SourceLocation Loc = AL.getSourceRange().getBegin();
4741         Diag(Loc, getLangOpts().MSVCCompat
4742                       ? diag::ext_ms_template_type_arg_missing_typename
4743                       : diag::err_template_arg_must_be_type_suggest)
4744             << FixItHint::CreateInsertion(Loc, "typename ");
4745         Diag(Param->getLocation(), diag::note_template_param_here);
4746
4747         // Recover by synthesizing a type using the location information that we
4748         // already have.
4749         ArgType =
4750             Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4751         TypeLocBuilder TLB;
4752         DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4753         TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4754         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4755         TL.setNameLoc(NameInfo.getLoc());
4756         TSI = TLB.getTypeSourceInfo(Context, ArgType);
4757
4758         // Overwrite our input TemplateArgumentLoc so that we can recover
4759         // properly.
4760         AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4761                                  TemplateArgumentLocInfo(TSI));
4762
4763         break;
4764       }
4765     }
4766     // fallthrough
4767     LLVM_FALLTHROUGH;
4768   }
4769   default: {
4770     // We have a template type parameter but the template argument
4771     // is not a type.
4772     SourceRange SR = AL.getSourceRange();
4773     Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4774     Diag(Param->getLocation(), diag::note_template_param_here);
4775
4776     return true;
4777   }
4778   }
4779
4780   if (CheckTemplateArgument(Param, TSI))
4781     return true;
4782
4783   // Add the converted template type argument.
4784   ArgType = Context.getCanonicalType(ArgType);
4785
4786   // Objective-C ARC:
4787   //   If an explicitly-specified template argument type is a lifetime type
4788   //   with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4789   if (getLangOpts().ObjCAutoRefCount &&
4790       ArgType->isObjCLifetimeType() &&
4791       !ArgType.getObjCLifetime()) {
4792     Qualifiers Qs;
4793     Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4794     ArgType = Context.getQualifiedType(ArgType, Qs);
4795   }
4796
4797   Converted.push_back(TemplateArgument(ArgType));
4798   return false;
4799 }
4800
4801 /// Substitute template arguments into the default template argument for
4802 /// the given template type parameter.
4803 ///
4804 /// \param SemaRef the semantic analysis object for which we are performing
4805 /// the substitution.
4806 ///
4807 /// \param Template the template that we are synthesizing template arguments
4808 /// for.
4809 ///
4810 /// \param TemplateLoc the location of the template name that started the
4811 /// template-id we are checking.
4812 ///
4813 /// \param RAngleLoc the location of the right angle bracket ('>') that
4814 /// terminates the template-id.
4815 ///
4816 /// \param Param the template template parameter whose default we are
4817 /// substituting into.
4818 ///
4819 /// \param Converted the list of template arguments provided for template
4820 /// parameters that precede \p Param in the template parameter list.
4821 /// \returns the substituted template argument, or NULL if an error occurred.
4822 static TypeSourceInfo *
4823 SubstDefaultTemplateArgument(Sema &SemaRef,
4824                              TemplateDecl *Template,
4825                              SourceLocation TemplateLoc,
4826                              SourceLocation RAngleLoc,
4827                              TemplateTypeParmDecl *Param,
4828                              SmallVectorImpl<TemplateArgument> &Converted) {
4829   TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
4830
4831   // If the argument type is dependent, instantiate it now based
4832   // on the previously-computed template arguments.
4833   if (ArgType->getType()->isInstantiationDependentType()) {
4834     Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4835                                      Param, Template, Converted,
4836                                      SourceRange(TemplateLoc, RAngleLoc));
4837     if (Inst.isInvalid())
4838       return nullptr;
4839
4840     TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4841
4842     // Only substitute for the innermost template argument list.
4843     MultiLevelTemplateArgumentList TemplateArgLists;
4844     TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4845     for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4846       TemplateArgLists.addOuterTemplateArguments(None);
4847
4848     Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4849     ArgType =
4850         SemaRef.SubstType(ArgType, TemplateArgLists,
4851                           Param->getDefaultArgumentLoc(), Param->getDeclName());
4852   }
4853
4854   return ArgType;
4855 }
4856
4857 /// Substitute template arguments into the default template argument for
4858 /// the given non-type template parameter.
4859 ///
4860 /// \param SemaRef the semantic analysis object for which we are performing
4861 /// the substitution.
4862 ///
4863 /// \param Template the template that we are synthesizing template arguments
4864 /// for.
4865 ///
4866 /// \param TemplateLoc the location of the template name that started the
4867 /// template-id we are checking.
4868 ///
4869 /// \param RAngleLoc the location of the right angle bracket ('>') that
4870 /// terminates the template-id.
4871 ///
4872 /// \param Param the non-type template parameter whose default we are
4873 /// substituting into.
4874 ///
4875 /// \param Converted the list of template arguments provided for template
4876 /// parameters that precede \p Param in the template parameter list.
4877 ///
4878 /// \returns the substituted template argument, or NULL if an error occurred.
4879 static ExprResult
4880 SubstDefaultTemplateArgument(Sema &SemaRef,
4881                              TemplateDecl *Template,
4882                              SourceLocation TemplateLoc,
4883                              SourceLocation RAngleLoc,
4884                              NonTypeTemplateParmDecl *Param,
4885                         SmallVectorImpl<TemplateArgument> &Converted) {
4886   Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4887                                    Param, Template, Converted,
4888                                    SourceRange(TemplateLoc, RAngleLoc));
4889   if (Inst.isInvalid())
4890     return ExprError();
4891
4892   TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4893
4894   // Only substitute for the innermost template argument list.
4895   MultiLevelTemplateArgumentList TemplateArgLists;
4896   TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4897   for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4898     TemplateArgLists.addOuterTemplateArguments(None);
4899
4900   Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4901   EnterExpressionEvaluationContext ConstantEvaluated(
4902       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4903   return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
4904 }
4905
4906 /// Substitute template arguments into the default template argument for
4907 /// the given template template parameter.
4908 ///
4909 /// \param SemaRef the semantic analysis object for which we are performing
4910 /// the substitution.
4911 ///
4912 /// \param Template the template that we are synthesizing template arguments
4913 /// for.
4914 ///
4915 /// \param TemplateLoc the location of the template name that started the
4916 /// template-id we are checking.
4917 ///
4918 /// \param RAngleLoc the location of the right angle bracket ('>') that
4919 /// terminates the template-id.
4920 ///
4921 /// \param Param the template template parameter whose default we are
4922 /// substituting into.
4923 ///
4924 /// \param Converted the list of template arguments provided for template
4925 /// parameters that precede \p Param in the template parameter list.
4926 ///
4927 /// \param QualifierLoc Will be set to the nested-name-specifier (with
4928 /// source-location information) that precedes the template name.
4929 ///
4930 /// \returns the substituted template argument, or NULL if an error occurred.
4931 static TemplateName
4932 SubstDefaultTemplateArgument(Sema &SemaRef,
4933                              TemplateDecl *Template,
4934                              SourceLocation TemplateLoc,
4935                              SourceLocation RAngleLoc,
4936                              TemplateTemplateParmDecl *Param,
4937                        SmallVectorImpl<TemplateArgument> &Converted,
4938                              NestedNameSpecifierLoc &QualifierLoc) {
4939   Sema::InstantiatingTemplate Inst(
4940       SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4941       SourceRange(TemplateLoc, RAngleLoc));
4942   if (Inst.isInvalid())
4943     return TemplateName();
4944
4945   TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4946
4947   // Only substitute for the innermost template argument list.
4948   MultiLevelTemplateArgumentList TemplateArgLists;
4949   TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4950   for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4951     TemplateArgLists.addOuterTemplateArguments(None);
4952
4953   Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4954   // Substitute into the nested-name-specifier first,
4955   QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
4956   if (QualifierLoc) {
4957     QualifierLoc =
4958         SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
4959     if (!QualifierLoc)
4960       return TemplateName();
4961   }
4962
4963   return SemaRef.SubstTemplateName(
4964              QualifierLoc,
4965              Param->getDefaultArgument().getArgument().getAsTemplate(),
4966              Param->getDefaultArgument().getTemplateNameLoc(),
4967              TemplateArgLists);
4968 }
4969
4970 /// If the given template parameter has a default template
4971 /// argument, substitute into that default template argument and
4972 /// return the corresponding template argument.
4973 TemplateArgumentLoc
4974 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4975                                               SourceLocation TemplateLoc,
4976                                               SourceLocation RAngleLoc,
4977                                               Decl *Param,
4978                                               SmallVectorImpl<TemplateArgument>
4979                                                 &Converted,
4980                                               bool &HasDefaultArg) {
4981   HasDefaultArg = false;
4982
4983   if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
4984     if (!hasVisibleDefaultArgument(TypeParm))
4985       return TemplateArgumentLoc();
4986
4987     HasDefaultArg = true;
4988     TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
4989                                                       TemplateLoc,
4990                                                       RAngleLoc,
4991                                                       TypeParm,
4992                                                       Converted);
4993     if (DI)
4994       return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4995
4996     return TemplateArgumentLoc();
4997   }
4998
4999   if (NonTypeTemplateParmDecl *NonTypeParm
5000         = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5001     if (!hasVisibleDefaultArgument(NonTypeParm))
5002       return TemplateArgumentLoc();
5003
5004     HasDefaultArg = true;
5005     ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
5006                                                   TemplateLoc,
5007                                                   RAngleLoc,
5008                                                   NonTypeParm,
5009                                                   Converted);
5010     if (Arg.isInvalid())
5011       return TemplateArgumentLoc();
5012
5013     Expr *ArgE = Arg.getAs<Expr>();
5014     return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
5015   }
5016
5017   TemplateTemplateParmDecl *TempTempParm
5018     = cast<TemplateTemplateParmDecl>(Param);
5019   if (!hasVisibleDefaultArgument(TempTempParm))
5020     return TemplateArgumentLoc();
5021
5022   HasDefaultArg = true;
5023   NestedNameSpecifierLoc QualifierLoc;
5024   TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
5025                                                     TemplateLoc,
5026                                                     RAngleLoc,
5027                                                     TempTempParm,
5028                                                     Converted,
5029                                                     QualifierLoc);
5030   if (TName.isNull())
5031     return TemplateArgumentLoc();
5032
5033   return TemplateArgumentLoc(TemplateArgument(TName),
5034                 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
5035                 TempTempParm->getDefaultArgument().getTemplateNameLoc());
5036 }
5037
5038 /// Convert a template-argument that we parsed as a type into a template, if
5039 /// possible. C++ permits injected-class-names to perform dual service as
5040 /// template template arguments and as template type arguments.
5041 static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
5042   // Extract and step over any surrounding nested-name-specifier.
5043   NestedNameSpecifierLoc QualLoc;
5044   if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
5045     if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
5046       return TemplateArgumentLoc();
5047
5048     QualLoc = ETLoc.getQualifierLoc();
5049     TLoc = ETLoc.getNamedTypeLoc();
5050   }
5051
5052   // If this type was written as an injected-class-name, it can be used as a
5053   // template template argument.
5054   if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
5055     return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
5056                                QualLoc, InjLoc.getNameLoc());
5057
5058   // If this type was written as an injected-class-name, it may have been
5059   // converted to a RecordType during instantiation. If the RecordType is
5060   // *not* wrapped in a TemplateSpecializationType and denotes a class
5061   // template specialization, it must have come from an injected-class-name.
5062   if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
5063     if (auto *CTSD =
5064             dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
5065       return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
5066                                  QualLoc, RecLoc.getNameLoc());
5067
5068   return TemplateArgumentLoc();
5069 }
5070
5071 /// Check that the given template argument corresponds to the given
5072 /// template parameter.
5073 ///
5074 /// \param Param The template parameter against which the argument will be
5075 /// checked.
5076 ///
5077 /// \param Arg The template argument, which may be updated due to conversions.
5078 ///
5079 /// \param Template The template in which the template argument resides.
5080 ///
5081 /// \param TemplateLoc The location of the template name for the template
5082 /// whose argument list we're matching.
5083 ///
5084 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
5085 /// the template argument list.
5086 ///
5087 /// \param ArgumentPackIndex The index into the argument pack where this
5088 /// argument will be placed. Only valid if the parameter is a parameter pack.
5089 ///
5090 /// \param Converted The checked, converted argument will be added to the
5091 /// end of this small vector.
5092 ///
5093 /// \param CTAK Describes how we arrived at this particular template argument:
5094 /// explicitly written, deduced, etc.
5095 ///
5096 /// \returns true on error, false otherwise.
5097 bool Sema::CheckTemplateArgument(NamedDecl *Param,
5098                                  TemplateArgumentLoc &Arg,
5099                                  NamedDecl *Template,
5100                                  SourceLocation TemplateLoc,
5101                                  SourceLocation RAngleLoc,
5102                                  unsigned ArgumentPackIndex,
5103                             SmallVectorImpl<TemplateArgument> &Converted,
5104                                  CheckTemplateArgumentKind CTAK) {
5105   // Check template type parameters.
5106   if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5107     return CheckTemplateTypeArgument(TTP, Arg, Converted);
5108
5109   // Check non-type template parameters.
5110   if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5111     // Do substitution on the type of the non-type template parameter
5112     // with the template arguments we've seen thus far.  But if the
5113     // template has a dependent context then we cannot substitute yet.
5114     QualType NTTPType = NTTP->getType();
5115     if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5116       NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5117
5118     if (NTTPType->isInstantiationDependentType() &&
5119         !isa<TemplateTemplateParmDecl>(Template) &&
5120         !Template->getDeclContext()->isDependentContext()) {
5121       // Do substitution on the type of the non-type template parameter.
5122       InstantiatingTemplate Inst(*this, TemplateLoc, Template,
5123                                  NTTP, Converted,
5124                                  SourceRange(TemplateLoc, RAngleLoc));
5125       if (Inst.isInvalid())
5126         return true;
5127
5128       TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
5129                                         Converted);
5130
5131       // If the parameter is a pack expansion, expand this slice of the pack.
5132       if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5133         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
5134                                                            ArgumentPackIndex);
5135         NTTPType = SubstType(PET->getPattern(),
5136                              MultiLevelTemplateArgumentList(TemplateArgs),
5137                              NTTP->getLocation(),
5138                              NTTP->getDeclName());
5139       } else {
5140         NTTPType = SubstType(NTTPType,
5141                              MultiLevelTemplateArgumentList(TemplateArgs),
5142                              NTTP->getLocation(),
5143                              NTTP->getDeclName());
5144       }
5145
5146       // If that worked, check the non-type template parameter type
5147       // for validity.
5148       if (!NTTPType.isNull())
5149         NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5150                                                      NTTP->getLocation());
5151       if (NTTPType.isNull())
5152         return true;
5153     }
5154
5155     switch (Arg.getArgument().getKind()) {
5156     case TemplateArgument::Null:
5157       llvm_unreachable("Should never see a NULL template argument here");
5158
5159     case TemplateArgument::Expression: {
5160       TemplateArgument Result;
5161       unsigned CurSFINAEErrors = NumSFINAEErrors;
5162       ExprResult Res =
5163         CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
5164                               Result, CTAK);
5165       if (Res.isInvalid())
5166         return true;
5167       // If the current template argument causes an error, give up now.
5168       if (CurSFINAEErrors < NumSFINAEErrors)
5169         return true;
5170
5171       // If the resulting expression is new, then use it in place of the
5172       // old expression in the template argument.
5173       if (Res.get() != Arg.getArgument().getAsExpr()) {
5174         TemplateArgument TA(Res.get());
5175         Arg = TemplateArgumentLoc(TA, Res.get());
5176       }
5177
5178       Converted.push_back(Result);
5179       break;
5180     }
5181
5182     case TemplateArgument::Declaration:
5183     case TemplateArgument::Integral:
5184     case TemplateArgument::NullPtr:
5185       // We've already checked this template argument, so just copy
5186       // it to the list of converted arguments.
5187       Converted.push_back(Arg.getArgument());
5188       break;
5189
5190     case TemplateArgument::Template:
5191     case TemplateArgument::TemplateExpansion:
5192       // We were given a template template argument. It may not be ill-formed;
5193       // see below.
5194       if (DependentTemplateName *DTN
5195             = Arg.getArgument().getAsTemplateOrTemplatePattern()
5196                                               .getAsDependentTemplateName()) {
5197         // We have a template argument such as \c T::template X, which we
5198         // parsed as a template template argument. However, since we now
5199         // know that we need a non-type template argument, convert this
5200         // template name into an expression.
5201
5202         DeclarationNameInfo NameInfo(DTN->getIdentifier(),
5203                                      Arg.getTemplateNameLoc());
5204
5205         CXXScopeSpec SS;
5206         SS.Adopt(Arg.getTemplateQualifierLoc());
5207         // FIXME: the template-template arg was a DependentTemplateName,
5208         // so it was provided with a template keyword. However, its source
5209         // location is not stored in the template argument structure.
5210         SourceLocation TemplateKWLoc;
5211         ExprResult E = DependentScopeDeclRefExpr::Create(
5212             Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5213             nullptr);
5214
5215         // If we parsed the template argument as a pack expansion, create a
5216         // pack expansion expression.
5217         if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
5218           E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
5219           if (E.isInvalid())
5220             return true;
5221         }
5222
5223         TemplateArgument Result;
5224         E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
5225         if (E.isInvalid())
5226           return true;
5227
5228         Converted.push_back(Result);
5229         break;
5230       }
5231
5232       // We have a template argument that actually does refer to a class
5233       // template, alias template, or template template parameter, and
5234       // therefore cannot be a non-type template argument.
5235       Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
5236         << Arg.getSourceRange();
5237
5238       Diag(Param->getLocation(), diag::note_template_param_here);
5239       return true;
5240
5241     case TemplateArgument::Type: {
5242       // We have a non-type template parameter but the template
5243       // argument is a type.
5244
5245       // C++ [temp.arg]p2:
5246       //   In a template-argument, an ambiguity between a type-id and
5247       //   an expression is resolved to a type-id, regardless of the
5248       //   form of the corresponding template-parameter.
5249       //
5250       // We warn specifically about this case, since it can be rather
5251       // confusing for users.
5252       QualType T = Arg.getArgument().getAsType();
5253       SourceRange SR = Arg.getSourceRange();
5254       if (T->isFunctionType())
5255         Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5256       else
5257         Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5258       Diag(Param->getLocation(), diag::note_template_param_here);
5259       return true;
5260     }
5261
5262     case TemplateArgument::Pack:
5263       llvm_unreachable("Caller must expand template argument packs");
5264     }
5265
5266     return false;
5267   }
5268
5269
5270   // Check template template parameters.
5271   TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
5272
5273   TemplateParameterList *Params = TempParm->getTemplateParameters();
5274   if (TempParm->isExpandedParameterPack())
5275     Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5276
5277   // Substitute into the template parameter list of the template
5278   // template parameter, since previously-supplied template arguments
5279   // may appear within the template template parameter.
5280   //
5281   // FIXME: Skip this if the parameters aren't instantiation-dependent.
5282   {
5283     // Set up a template instantiation context.
5284     LocalInstantiationScope Scope(*this);
5285     InstantiatingTemplate Inst(*this, TemplateLoc, Template,
5286                                TempParm, Converted,
5287                                SourceRange(TemplateLoc, RAngleLoc));
5288     if (Inst.isInvalid())
5289       return true;
5290
5291     TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
5292     Params = SubstTemplateParams(Params, CurContext,
5293                                  MultiLevelTemplateArgumentList(TemplateArgs));
5294     if (!Params)
5295       return true;
5296   }
5297
5298   // C++1z [temp.local]p1: (DR1004)
5299   //   When [the injected-class-name] is used [...] as a template-argument for
5300   //   a template template-parameter [...] it refers to the class template
5301   //   itself.
5302   if (Arg.getArgument().getKind() == TemplateArgument::Type) {
5303     TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5304         Arg.getTypeSourceInfo()->getTypeLoc());
5305     if (!ConvertedArg.getArgument().isNull())
5306       Arg = ConvertedArg;
5307   }
5308
5309   switch (Arg.getArgument().getKind()) {
5310   case TemplateArgument::Null:
5311     llvm_unreachable("Should never see a NULL template argument here");
5312
5313   case TemplateArgument::Template:
5314   case TemplateArgument::TemplateExpansion:
5315     if (CheckTemplateTemplateArgument(TempParm, Params, Arg))
5316       return true;
5317
5318     Converted.push_back(Arg.getArgument());
5319     break;
5320
5321   case TemplateArgument::Expression:
5322   case TemplateArgument::Type:
5323     // We have a template template parameter but the template
5324     // argument does not refer to a template.
5325     Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
5326       << getLangOpts().CPlusPlus11;
5327     return true;
5328
5329   case TemplateArgument::Declaration:
5330     llvm_unreachable("Declaration argument with template template parameter");
5331   case TemplateArgument::Integral:
5332     llvm_unreachable("Integral argument with template template parameter");
5333   case TemplateArgument::NullPtr:
5334     llvm_unreachable("Null pointer argument with template template parameter");
5335
5336   case TemplateArgument::Pack:
5337     llvm_unreachable("Caller must expand template argument packs");
5338   }
5339
5340   return false;
5341 }
5342
5343 /// Check whether the template parameter is a pack expansion, and if so,
5344 /// determine the number of parameters produced by that expansion. For instance:
5345 ///
5346 /// \code
5347 /// template<typename ...Ts> struct A {
5348 ///   template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
5349 /// };
5350 /// \endcode
5351 ///
5352 /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
5353 /// is not a pack expansion, so returns an empty Optional.
5354 static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
5355   if (TemplateTypeParmDecl *TTP
5356         = dyn_cast<TemplateTypeParmDecl>(Param)) {
5357     if (TTP->isExpandedParameterPack())
5358       return TTP->getNumExpansionParameters();
5359   }
5360
5361   if (NonTypeTemplateParmDecl *NTTP
5362         = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5363     if (NTTP->isExpandedParameterPack())
5364       return NTTP->getNumExpansionTypes();
5365   }
5366
5367   if (TemplateTemplateParmDecl *TTP
5368         = dyn_cast<TemplateTemplateParmDecl>(Param)) {
5369     if (TTP->isExpandedParameterPack())
5370       return TTP->getNumExpansionTemplateParameters();
5371   }
5372
5373   return None;
5374 }
5375
5376 /// Diagnose a missing template argument.
5377 template<typename TemplateParmDecl>
5378 static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5379                                     TemplateDecl *TD,
5380                                     const TemplateParmDecl *D,
5381                                     TemplateArgumentListInfo &Args) {
5382   // Dig out the most recent declaration of the template parameter; there may be
5383   // declarations of the template that are more recent than TD.
5384   D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5385                                  ->getTemplateParameters()
5386                                  ->getParam(D->getIndex()));
5387
5388   // If there's a default argument that's not visible, diagnose that we're
5389   // missing a module import.
5390   llvm::SmallVector<Module*, 8> Modules;
5391   if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
5392     S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5393                             D->getDefaultArgumentLoc(), Modules,
5394                             Sema::MissingImportKind::DefaultArgument,
5395                             /*Recover*/true);
5396     return true;
5397   }
5398
5399   // FIXME: If there's a more recent default argument that *is* visible,
5400   // diagnose that it was declared too late.
5401
5402   TemplateParameterList *Params = TD->getTemplateParameters();
5403
5404   S.Diag(Loc, diag::err_template_arg_list_different_arity)
5405     << /*not enough args*/0
5406     << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
5407     << TD;
5408   S.Diag(TD->getLocation(), diag::note_template_decl_here)
5409     << Params->getSourceRange();
5410   return true;
5411 }
5412
5413 /// Check that the given template argument list is well-formed
5414 /// for specializing the given template.
5415 bool Sema::CheckTemplateArgumentList(
5416     TemplateDecl *Template, SourceLocation TemplateLoc,
5417     TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
5418     SmallVectorImpl<TemplateArgument> &Converted,
5419     bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5420
5421   if (ConstraintsNotSatisfied)
5422     *ConstraintsNotSatisfied = false;
5423
5424   // Make a copy of the template arguments for processing.  Only make the
5425   // changes at the end when successful in matching the arguments to the
5426   // template.
5427   TemplateArgumentListInfo NewArgs = TemplateArgs;
5428
5429   // Make sure we get the template parameter list from the most
5430   // recentdeclaration, since that is the only one that has is guaranteed to
5431   // have all the default template argument information.
5432   TemplateParameterList *Params =
5433       cast<TemplateDecl>(Template->getMostRecentDecl())
5434           ->getTemplateParameters();
5435
5436   SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5437
5438   // C++ [temp.arg]p1:
5439   //   [...] The type and form of each template-argument specified in
5440   //   a template-id shall match the type and form specified for the
5441   //   corresponding parameter declared by the template in its
5442   //   template-parameter-list.
5443   bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5444   SmallVector<TemplateArgument, 2> ArgumentPack;
5445   unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5446   LocalInstantiationScope InstScope(*this, true);
5447   for (TemplateParameterList::iterator Param = Params->begin(),
5448                                        ParamEnd = Params->end();
5449        Param != ParamEnd; /* increment in loop */) {
5450     // If we have an expanded parameter pack, make sure we don't have too
5451     // many arguments.
5452     if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
5453       if (*Expansions == ArgumentPack.size()) {
5454         // We're done with this parameter pack. Pack up its arguments and add
5455         // them to the list.
5456         Converted.push_back(
5457             TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5458         ArgumentPack.clear();
5459
5460         // This argument is assigned to the next parameter.
5461         ++Param;
5462         continue;
5463       } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5464         // Not enough arguments for this parameter pack.
5465         Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5466           << /*not enough args*/0
5467           << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5468           << Template;
5469         Diag(Template->getLocation(), diag::note_template_decl_here)
5470           << Params->getSourceRange();
5471         return true;
5472       }
5473     }
5474
5475     if (ArgIdx < NumArgs) {
5476       // Check the template argument we were given.
5477       if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
5478                                 TemplateLoc, RAngleLoc,
5479                                 ArgumentPack.size(), Converted))
5480         return true;
5481
5482       bool PackExpansionIntoNonPack =
5483           NewArgs[ArgIdx].getArgument().isPackExpansion() &&
5484           (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5485       if (PackExpansionIntoNonPack && (isa<TypeAliasTemplateDecl>(Template) ||
5486                                        isa<ConceptDecl>(Template))) {
5487         // Core issue 1430: we have a pack expansion as an argument to an
5488         // alias template, and it's not part of a parameter pack. This
5489         // can't be canonicalized, so reject it now.
5490         // As for concepts - we cannot normalize constraints where this
5491         // situation exists.
5492         Diag(NewArgs[ArgIdx].getLocation(),
5493              diag::err_template_expansion_into_fixed_list)
5494           << (isa<ConceptDecl>(Template) ? 1 : 0)
5495           << NewArgs[ArgIdx].getSourceRange();
5496         Diag((*Param)->getLocation(), diag::note_template_param_here);
5497         return true;
5498       }
5499
5500       // We're now done with this argument.
5501       ++ArgIdx;
5502
5503       if ((*Param)->isTemplateParameterPack()) {
5504         // The template parameter was a template parameter pack, so take the
5505         // deduced argument and place it on the argument pack. Note that we
5506         // stay on the same template parameter so that we can deduce more
5507         // arguments.
5508         ArgumentPack.push_back(Converted.pop_back_val());
5509       } else {
5510         // Move to the next template parameter.
5511         ++Param;
5512       }
5513
5514       // If we just saw a pack expansion into a non-pack, then directly convert
5515       // the remaining arguments, because we don't know what parameters they'll
5516       // match up with.
5517       if (PackExpansionIntoNonPack) {
5518         if (!ArgumentPack.empty()) {
5519           // If we were part way through filling in an expanded parameter pack,
5520           // fall back to just producing individual arguments.
5521           Converted.insert(Converted.end(),
5522                            ArgumentPack.begin(), ArgumentPack.end());
5523           ArgumentPack.clear();
5524         }
5525
5526         while (ArgIdx < NumArgs) {
5527           Converted.push_back(NewArgs[ArgIdx].getArgument());
5528           ++ArgIdx;
5529         }
5530
5531         return false;
5532       }
5533
5534       continue;
5535     }
5536
5537     // If we're checking a partial template argument list, we're done.
5538     if (PartialTemplateArgs) {
5539       if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
5540         Converted.push_back(
5541             TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5542       return false;
5543     }
5544
5545     // If we have a template parameter pack with no more corresponding
5546     // arguments, just break out now and we'll fill in the argument pack below.
5547     if ((*Param)->isTemplateParameterPack()) {
5548       assert(!getExpandedPackSize(*Param) &&
5549              "Should have dealt with this already");
5550
5551       // A non-expanded parameter pack before the end of the parameter list
5552       // only occurs for an ill-formed template parameter list, unless we've
5553       // got a partial argument list for a function template, so just bail out.
5554       if (Param + 1 != ParamEnd)
5555         return true;
5556
5557       Converted.push_back(
5558           TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5559       ArgumentPack.clear();
5560
5561       ++Param;
5562       continue;
5563     }
5564
5565     // Check whether we have a default argument.
5566     TemplateArgumentLoc Arg;
5567
5568     // Retrieve the default template argument from the template
5569     // parameter. For each kind of template parameter, we substitute the
5570     // template arguments provided thus far and any "outer" template arguments
5571     // (when the template parameter was part of a nested template) into
5572     // the default argument.
5573     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
5574       if (!hasVisibleDefaultArgument(TTP))
5575         return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5576                                        NewArgs);
5577
5578       TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
5579                                                              Template,
5580                                                              TemplateLoc,
5581                                                              RAngleLoc,
5582                                                              TTP,
5583                                                              Converted);
5584       if (!ArgType)
5585         return true;
5586
5587       Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
5588                                 ArgType);
5589     } else if (NonTypeTemplateParmDecl *NTTP
5590                  = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
5591       if (!hasVisibleDefaultArgument(NTTP))
5592         return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5593                                        NewArgs);
5594
5595       ExprResult E = SubstDefaultTemplateArgument(*this, Template,
5596                                                               TemplateLoc,
5597                                                               RAngleLoc,
5598                                                               NTTP,
5599                                                               Converted);
5600       if (E.isInvalid())
5601         return true;
5602
5603       Expr *Ex = E.getAs<Expr>();
5604       Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
5605     } else {
5606       TemplateTemplateParmDecl *TempParm
5607         = cast<TemplateTemplateParmDecl>(*Param);
5608
5609       if (!hasVisibleDefaultArgument(TempParm))
5610         return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
5611                                        NewArgs);
5612
5613       NestedNameSpecifierLoc QualifierLoc;
5614       TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
5615                                                        TemplateLoc,
5616                                                        RAngleLoc,
5617                                                        TempParm,
5618                                                        Converted,
5619                                                        QualifierLoc);
5620       if (Name.isNull())
5621         return true;
5622
5623       Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
5624                            TempParm->getDefaultArgument().getTemplateNameLoc());
5625     }
5626
5627     // Introduce an instantiation record that describes where we are using
5628     // the default template argument. We're not actually instantiating a
5629     // template here, we just create this object to put a note into the
5630     // context stack.
5631     InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
5632                                SourceRange(TemplateLoc, RAngleLoc));
5633     if (Inst.isInvalid())
5634       return true;
5635
5636     // Check the default template argument.
5637     if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
5638                               RAngleLoc, 0, Converted))
5639       return true;
5640
5641     // Core issue 150 (assumed resolution): if this is a template template
5642     // parameter, keep track of the default template arguments from the
5643     // template definition.
5644     if (isTemplateTemplateParameter)
5645       NewArgs.addArgument(Arg);
5646
5647     // Move to the next template parameter and argument.
5648     ++Param;
5649     ++ArgIdx;
5650   }
5651
5652   // If we're performing a partial argument substitution, allow any trailing
5653   // pack expansions; they might be empty. This can happen even if
5654   // PartialTemplateArgs is false (the list of arguments is complete but
5655   // still dependent).
5656   if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5657       CurrentInstantiationScope->getPartiallySubstitutedPack()) {
5658     while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5659       Converted.push_back(NewArgs[ArgIdx++].getArgument());
5660   }
5661
5662   // If we have any leftover arguments, then there were too many arguments.
5663   // Complain and fail.
5664   if (ArgIdx < NumArgs) {
5665     Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5666         << /*too many args*/1
5667         << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5668         << Template
5669         << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5670     Diag(Template->getLocation(), diag::note_template_decl_here)
5671         << Params->getSourceRange();
5672     return true;
5673   }
5674
5675   // No problems found with the new argument list, propagate changes back
5676   // to caller.
5677   if (UpdateArgsWithConversions)
5678     TemplateArgs = std::move(NewArgs);
5679
5680   if (!PartialTemplateArgs &&
5681       EnsureTemplateArgumentListConstraints(
5682         Template, Converted, SourceRange(TemplateLoc,
5683                                          TemplateArgs.getRAngleLoc()))) {
5684     if (ConstraintsNotSatisfied)
5685       *ConstraintsNotSatisfied = true;
5686     return true;
5687   }
5688
5689   return false;
5690 }
5691
5692 namespace {
5693   class UnnamedLocalNoLinkageFinder
5694     : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
5695   {
5696     Sema &S;
5697     SourceRange SR;
5698
5699     typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
5700
5701   public:
5702     UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5703
5704     bool Visit(QualType T) {
5705       return T.isNull() ? false : inherited::Visit(T.getTypePtr());
5706     }
5707
5708 #define TYPE(Class, Parent) \
5709     bool Visit##Class##Type(const Class##Type *);
5710 #define ABSTRACT_TYPE(Class, Parent) \
5711     bool Visit##Class##Type(const Class##Type *) { return false; }
5712 #define NON_CANONICAL_TYPE(Class, Parent) \
5713     bool Visit##Class##Type(const Class##Type *) { return false; }
5714 #include "clang/AST/TypeNodes.inc"
5715
5716     bool VisitTagDecl(const TagDecl *Tag);
5717     bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5718   };
5719 } // end anonymous namespace
5720
5721 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
5722   return false;
5723 }
5724
5725 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5726   return Visit(T->getElementType());
5727 }
5728
5729 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
5730   return Visit(T->getPointeeType());
5731 }
5732
5733 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
5734                                                     const BlockPointerType* T) {
5735   return Visit(T->getPointeeType());
5736 }
5737
5738 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
5739                                                 const LValueReferenceType* T) {
5740   return Visit(T->getPointeeType());
5741 }
5742
5743 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
5744                                                 const RValueReferenceType* T) {
5745   return Visit(T->getPointeeType());
5746 }
5747
5748 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
5749                                                   const MemberPointerType* T) {
5750   return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5751 }
5752
5753 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
5754                                                   const ConstantArrayType* T) {
5755   return Visit(T->getElementType());
5756 }
5757
5758 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
5759                                                  const IncompleteArrayType* T) {
5760   return Visit(T->getElementType());
5761 }
5762
5763 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
5764                                                    const VariableArrayType* T) {
5765   return Visit(T->getElementType());
5766 }
5767
5768 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
5769                                             const DependentSizedArrayType* T) {
5770   return Visit(T->getElementType());
5771 }
5772
5773 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
5774                                          const DependentSizedExtVectorType* T) {
5775   return Visit(T->getElementType());
5776 }
5777
5778 bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5779     const DependentAddressSpaceType *T) {
5780   return Visit(T->getPointeeType());
5781 }
5782
5783 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5784   return Visit(T->getElementType());
5785 }
5786
5787 bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
5788     const DependentVectorType *T) {
5789   return Visit(T->getElementType());
5790 }
5791
5792 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5793   return Visit(T->getElementType());
5794 }
5795
5796 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5797                                                   const FunctionProtoType* T) {
5798   for (const auto &A : T->param_types()) {
5799     if (Visit(A))
5800       return true;
5801   }
5802
5803   return Visit(T->getReturnType());
5804 }
5805
5806 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5807                                                const FunctionNoProtoType* T) {
5808   return Visit(T->getReturnType());
5809 }
5810
5811 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5812                                                   const UnresolvedUsingType*) {
5813   return false;
5814 }
5815
5816 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5817   return false;
5818 }
5819
5820 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5821   return Visit(T->getUnderlyingType());
5822 }
5823
5824 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5825   return false;
5826 }
5827
5828 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5829                                                     const UnaryTransformType*) {
5830   return false;
5831 }
5832
5833 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5834   return Visit(T->getDeducedType());
5835 }
5836
5837 bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5838     const DeducedTemplateSpecializationType *T) {
5839   return Visit(T->getDeducedType());
5840 }
5841
5842 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5843   return VisitTagDecl(T->getDecl());
5844 }
5845
5846 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5847   return VisitTagDecl(T->getDecl());
5848 }
5849
5850 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5851                                                  const TemplateTypeParmType*) {
5852   return false;
5853 }
5854
5855 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5856                                         const SubstTemplateTypeParmPackType *) {
5857   return false;
5858 }
5859
5860 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5861                                             const TemplateSpecializationType*) {
5862   return false;
5863 }
5864
5865 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5866                                               const InjectedClassNameType* T) {
5867   return VisitTagDecl(T->getDecl());
5868 }
5869
5870 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5871                                                    const DependentNameType* T) {
5872   return VisitNestedNameSpecifier(T->getQualifier());
5873 }
5874
5875 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5876                                  const DependentTemplateSpecializationType* T) {
5877   return VisitNestedNameSpecifier(T->getQualifier());
5878 }
5879
5880 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5881                                                    const PackExpansionType* T) {
5882   return Visit(T->getPattern());
5883 }
5884
5885 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5886   return false;
5887 }
5888
5889 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5890                                                    const ObjCInterfaceType *) {
5891   return false;
5892 }
5893
5894 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5895                                                 const ObjCObjectPointerType *) {
5896   return false;
5897 }
5898
5899 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5900   return Visit(T->getValueType());
5901 }
5902
5903 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5904   return false;
5905 }
5906
5907 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5908   if (Tag->getDeclContext()->isFunctionOrMethod()) {
5909     S.Diag(SR.getBegin(),
5910            S.getLangOpts().CPlusPlus11 ?
5911              diag::warn_cxx98_compat_template_arg_local_type :
5912              diag::ext_template_arg_local_type)
5913       << S.Context.getTypeDeclType(Tag) << SR;
5914     return true;
5915   }
5916
5917   if (!Tag->hasNameForLinkage()) {
5918     S.Diag(SR.getBegin(),
5919            S.getLangOpts().CPlusPlus11 ?
5920              diag::warn_cxx98_compat_template_arg_unnamed_type :
5921              diag::ext_template_arg_unnamed_type) << SR;
5922     S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5923     return true;
5924   }
5925
5926   return false;
5927 }
5928
5929 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5930                                                     NestedNameSpecifier *NNS) {
5931   if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5932     return true;
5933
5934   switch (NNS->getKind()) {
5935   case NestedNameSpecifier::Identifier:
5936   case NestedNameSpecifier::Namespace:
5937   case NestedNameSpecifier::NamespaceAlias:
5938   case NestedNameSpecifier::Global:
5939   case NestedNameSpecifier::Super:
5940     return false;
5941
5942   case NestedNameSpecifier::TypeSpec:
5943   case NestedNameSpecifier::TypeSpecWithTemplate:
5944     return Visit(QualType(NNS->getAsType(), 0));
5945   }
5946   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
5947 }
5948
5949 /// Check a template argument against its corresponding
5950 /// template type parameter.
5951 ///
5952 /// This routine implements the semantics of C++ [temp.arg.type]. It
5953 /// returns true if an error occurred, and false otherwise.
5954 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
5955                                  TypeSourceInfo *ArgInfo) {
5956   assert(ArgInfo && "invalid TypeSourceInfo");
5957   QualType Arg = ArgInfo->getType();
5958   SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
5959
5960   if (Arg->isVariablyModifiedType()) {
5961     return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
5962   } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
5963     return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
5964   }
5965
5966   // C++03 [temp.arg.type]p2:
5967   //   A local type, a type with no linkage, an unnamed type or a type
5968   //   compounded from any of these types shall not be used as a
5969   //   template-argument for a template type-parameter.
5970   //
5971   // C++11 allows these, and even in C++03 we allow them as an extension with
5972   // a warning.
5973   if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
5974     UnnamedLocalNoLinkageFinder Finder(*this, SR);
5975     (void)Finder.Visit(Context.getCanonicalType(Arg));
5976   }
5977
5978   return false;
5979 }
5980
5981 enum NullPointerValueKind {
5982   NPV_NotNullPointer,
5983   NPV_NullPointer,
5984   NPV_Error
5985 };
5986
5987 /// Determine whether the given template argument is a null pointer
5988 /// value of the appropriate type.
5989 static NullPointerValueKind
5990 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
5991                                    QualType ParamType, Expr *Arg,
5992                                    Decl *Entity = nullptr) {
5993   if (Arg->isValueDependent() || Arg->isTypeDependent())
5994     return NPV_NotNullPointer;
5995
5996   // dllimport'd entities aren't constant but are available inside of template
5997   // arguments.
5998   if (Entity && Entity->hasAttr<DLLImportAttr>())
5999     return NPV_NotNullPointer;
6000
6001   if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6002     llvm_unreachable(
6003         "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6004
6005   if (!S.getLangOpts().CPlusPlus11)
6006     return NPV_NotNullPointer;
6007
6008   // Determine whether we have a constant expression.
6009   ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
6010   if (ArgRV.isInvalid())
6011     return NPV_Error;
6012   Arg = ArgRV.get();
6013
6014   Expr::EvalResult EvalResult;
6015   SmallVector<PartialDiagnosticAt, 8> Notes;
6016   EvalResult.Diag = &Notes;
6017   if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6018       EvalResult.HasSideEffects) {
6019     SourceLocation DiagLoc = Arg->getExprLoc();
6020
6021     // If our only note is the usual "invalid subexpression" note, just point
6022     // the caret at its location rather than producing an essentially
6023     // redundant note.
6024     if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6025         diag::note_invalid_subexpr_in_const_expr) {
6026       DiagLoc = Notes[0].first;
6027       Notes.clear();
6028     }
6029
6030     S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6031       << Arg->getType() << Arg->getSourceRange();
6032     for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6033       S.Diag(Notes[I].first, Notes[I].second);
6034
6035     S.Diag(Param->getLocation(), diag::note_template_param_here);
6036     return NPV_Error;
6037   }
6038
6039   // C++11 [temp.arg.nontype]p1:
6040   //   - an address constant expression of type std::nullptr_t
6041   if (Arg->getType()->isNullPtrType())
6042     return NPV_NullPointer;
6043
6044   //   - a constant expression that evaluates to a null pointer value (4.10); or
6045   //   - a constant expression that evaluates to a null member pointer value
6046   //     (4.11); or
6047   if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
6048       (EvalResult.Val.isMemberPointer() &&
6049        !EvalResult.Val.getMemberPointerDecl())) {
6050     // If our expression has an appropriate type, we've succeeded.
6051     bool ObjCLifetimeConversion;
6052     if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6053         S.IsQualificationConversion(Arg->getType(), ParamType, false,
6054                                      ObjCLifetimeConversion))
6055       return NPV_NullPointer;
6056
6057     // The types didn't match, but we know we got a null pointer; complain,
6058     // then recover as if the types were correct.
6059     S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6060       << Arg->getType() << ParamType << Arg->getSourceRange();
6061     S.Diag(Param->getLocation(), diag::note_template_param_here);
6062     return NPV_NullPointer;
6063   }
6064
6065   // If we don't have a null pointer value, but we do have a NULL pointer
6066   // constant, suggest a cast to the appropriate type.
6067   if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
6068     std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6069     S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6070         << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6071         << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()),
6072                                       ")");
6073     S.Diag(Param->getLocation(), diag::note_template_param_here);
6074     return NPV_NullPointer;
6075   }
6076
6077   // FIXME: If we ever want to support general, address-constant expressions
6078   // as non-type template arguments, we should return the ExprResult here to
6079   // be interpreted by the caller.
6080   return NPV_NotNullPointer;
6081 }
6082
6083 /// Checks whether the given template argument is compatible with its
6084 /// template parameter.
6085 static bool CheckTemplateArgumentIsCompatibleWithParameter(
6086     Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6087     Expr *Arg, QualType ArgType) {
6088   bool ObjCLifetimeConversion;
6089   if (ParamType->isPointerType() &&
6090       !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6091       S.IsQualificationConversion(ArgType, ParamType, false,
6092                                   ObjCLifetimeConversion)) {
6093     // For pointer-to-object types, qualification conversions are
6094     // permitted.
6095   } else {
6096     if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6097       if (!ParamRef->getPointeeType()->isFunctionType()) {
6098         // C++ [temp.arg.nontype]p5b3:
6099         //   For a non-type template-parameter of type reference to
6100         //   object, no conversions apply. The type referred to by the
6101         //   reference may be more cv-qualified than the (otherwise
6102         //   identical) type of the template- argument. The
6103         //   template-parameter is bound directly to the
6104         //   template-argument, which shall be an lvalue.
6105
6106         // FIXME: Other qualifiers?
6107         unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6108         unsigned ArgQuals = ArgType.getCVRQualifiers();
6109
6110         if ((ParamQuals | ArgQuals) != ParamQuals) {
6111           S.Diag(Arg->getBeginLoc(),
6112                  diag::err_template_arg_ref_bind_ignores_quals)
6113               << ParamType << Arg->getType() << Arg->getSourceRange();
6114           S.Diag(Param->getLocation(), diag::note_template_param_here);
6115           return true;
6116         }
6117       }
6118     }
6119
6120     // At this point, the template argument refers to an object or
6121     // function with external linkage. We now need to check whether the
6122     // argument and parameter types are compatible.
6123     if (!S.Context.hasSameUnqualifiedType(ArgType,
6124                                           ParamType.getNonReferenceType())) {
6125       // We can't perform this conversion or binding.
6126       if (ParamType->isReferenceType())
6127         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6128             << ParamType << ArgIn->getType() << Arg->getSourceRange();
6129       else
6130         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6131             << ArgIn->getType() << ParamType << Arg->getSourceRange();
6132       S.Diag(Param->getLocation(), diag::note_template_param_here);
6133       return true;
6134     }
6135   }
6136
6137   return false;
6138 }
6139
6140 /// Checks whether the given template argument is the address
6141 /// of an object or function according to C++ [temp.arg.nontype]p1.
6142 static bool
6143 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
6144                                                NonTypeTemplateParmDecl *Param,
6145                                                QualType ParamType,
6146                                                Expr *ArgIn,
6147                                                TemplateArgument &Converted) {
6148   bool Invalid = false;
6149   Expr *Arg = ArgIn;
6150   QualType ArgType = Arg->getType();
6151
6152   bool AddressTaken = false;
6153   SourceLocation AddrOpLoc;
6154   if (S.getLangOpts().MicrosoftExt) {
6155     // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6156     // dereference and address-of operators.
6157     Arg = Arg->IgnoreParenCasts();
6158
6159     bool ExtWarnMSTemplateArg = false;
6160     UnaryOperatorKind FirstOpKind;
6161     SourceLocation FirstOpLoc;
6162     while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6163       UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6164       if (UnOpKind == UO_Deref)
6165         ExtWarnMSTemplateArg = true;
6166       if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6167         Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6168         if (!AddrOpLoc.isValid()) {
6169           FirstOpKind = UnOpKind;
6170           FirstOpLoc = UnOp->getOperatorLoc();
6171         }
6172       } else
6173         break;
6174     }
6175     if (FirstOpLoc.isValid()) {
6176       if (ExtWarnMSTemplateArg)
6177         S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6178             << ArgIn->getSourceRange();
6179
6180       if (FirstOpKind == UO_AddrOf)
6181         AddressTaken = true;
6182       else if (Arg->getType()->isPointerType()) {
6183         // We cannot let pointers get dereferenced here, that is obviously not a
6184         // constant expression.
6185         assert(FirstOpKind == UO_Deref);
6186         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6187             << Arg->getSourceRange();
6188       }
6189     }
6190   } else {
6191     // See through any implicit casts we added to fix the type.
6192     Arg = Arg->IgnoreImpCasts();
6193
6194     // C++ [temp.arg.nontype]p1:
6195     //
6196     //   A template-argument for a non-type, non-template
6197     //   template-parameter shall be one of: [...]
6198     //
6199     //     -- the address of an object or function with external
6200     //        linkage, including function templates and function
6201     //        template-ids but excluding non-static class members,
6202     //        expressed as & id-expression where the & is optional if
6203     //        the name refers to a function or array, or if the
6204     //        corresponding template-parameter is a reference; or
6205
6206     // In C++98/03 mode, give an extension warning on any extra parentheses.
6207     // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6208     bool ExtraParens = false;
6209     while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6210       if (!Invalid && !ExtraParens) {
6211         S.Diag(Arg->getBeginLoc(),
6212                S.getLangOpts().CPlusPlus11
6213                    ? diag::warn_cxx98_compat_template_arg_extra_parens
6214                    : diag::ext_template_arg_extra_parens)
6215             << Arg->getSourceRange();
6216         ExtraParens = true;
6217       }
6218
6219       Arg = Parens->getSubExpr();
6220     }
6221
6222     while (SubstNonTypeTemplateParmExpr *subst =
6223                dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6224       Arg = subst->getReplacement()->IgnoreImpCasts();
6225
6226     if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6227       if (UnOp->getOpcode() == UO_AddrOf) {
6228         Arg = UnOp->getSubExpr();
6229         AddressTaken = true;
6230         AddrOpLoc = UnOp->getOperatorLoc();
6231       }
6232     }
6233
6234     while (SubstNonTypeTemplateParmExpr *subst =
6235                dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6236       Arg = subst->getReplacement()->IgnoreImpCasts();
6237   }
6238
6239   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
6240   ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6241
6242   // If our parameter has pointer type, check for a null template value.
6243   if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6244     switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6245                                                Entity)) {
6246     case NPV_NullPointer:
6247       S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6248       Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6249                                    /*isNullPtr=*/true);
6250       return false;
6251
6252     case NPV_Error:
6253       return true;
6254
6255     case NPV_NotNullPointer:
6256       break;
6257     }
6258   }
6259
6260   // Stop checking the precise nature of the argument if it is value dependent,
6261   // it should be checked when instantiated.
6262   if (Arg->isValueDependent()) {
6263     Converted = TemplateArgument(ArgIn);
6264     return false;
6265   }
6266
6267   if (isa<CXXUuidofExpr>(Arg)) {
6268     if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
6269                                                        ArgIn, Arg, ArgType))
6270       return true;
6271
6272     Converted = TemplateArgument(ArgIn);
6273     return false;
6274   }
6275
6276   if (!DRE) {
6277     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6278         << Arg->getSourceRange();
6279     S.Diag(Param->getLocation(), diag::note_template_param_here);
6280     return true;
6281   }
6282
6283   // Cannot refer to non-static data members
6284   if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6285     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6286         << Entity << Arg->getSourceRange();
6287     S.Diag(Param->getLocation(), diag::note_template_param_here);
6288     return true;
6289   }
6290
6291   // Cannot refer to non-static member functions
6292   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6293     if (!Method->isStatic()) {
6294       S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6295           << Method << Arg->getSourceRange();
6296       S.Diag(Param->getLocation(), diag::note_template_param_here);
6297       return true;
6298     }
6299   }
6300
6301   FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6302   VarDecl *Var = dyn_cast<VarDecl>(Entity);
6303
6304   // A non-type template argument must refer to an object or function.
6305   if (!Func && !Var) {
6306     // We found something, but we don't know specifically what it is.
6307     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6308         << Arg->getSourceRange();
6309     S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6310     return true;
6311   }
6312
6313   // Address / reference template args must have external linkage in C++98.
6314   if (Entity->getFormalLinkage() == InternalLinkage) {
6315     S.Diag(Arg->getBeginLoc(),
6316            S.getLangOpts().CPlusPlus11
6317                ? diag::warn_cxx98_compat_template_arg_object_internal
6318                : diag::ext_template_arg_object_internal)
6319         << !Func << Entity << Arg->getSourceRange();
6320     S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6321       << !Func;
6322   } else if (!Entity->hasLinkage()) {
6323     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6324         << !Func << Entity << Arg->getSourceRange();
6325     S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6326       << !Func;
6327     return true;
6328   }
6329
6330   if (Func) {
6331     // If the template parameter has pointer type, the function decays.
6332     if (ParamType->isPointerType() && !AddressTaken)
6333       ArgType = S.Context.getPointerType(Func->getType());
6334     else if (AddressTaken && ParamType->isReferenceType()) {
6335       // If we originally had an address-of operator, but the
6336       // parameter has reference type, complain and (if things look
6337       // like they will work) drop the address-of operator.
6338       if (!S.Context.hasSameUnqualifiedType(Func->getType(),
6339                                             ParamType.getNonReferenceType())) {
6340         S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6341           << ParamType;
6342         S.Diag(Param->getLocation(), diag::note_template_param_here);
6343         return true;
6344       }
6345
6346       S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6347         << ParamType
6348         << FixItHint::CreateRemoval(AddrOpLoc);
6349       S.Diag(Param->getLocation(), diag::note_template_param_here);
6350
6351       ArgType = Func->getType();
6352     }
6353   } else {
6354     // A value of reference type is not an object.
6355     if (Var->getType()->isReferenceType()) {
6356       S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6357           << Var->getType() << Arg->getSourceRange();
6358       S.Diag(Param->getLocation(), diag::note_template_param_here);
6359       return true;
6360     }
6361
6362     // A template argument must have static storage duration.
6363     if (Var->getTLSKind()) {
6364       S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6365           << Arg->getSourceRange();
6366       S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6367       return true;
6368     }
6369
6370     // If the template parameter has pointer type, we must have taken
6371     // the address of this object.
6372     if (ParamType->isReferenceType()) {
6373       if (AddressTaken) {
6374         // If we originally had an address-of operator, but the
6375         // parameter has reference type, complain and (if things look
6376         // like they will work) drop the address-of operator.
6377         if (!S.Context.hasSameUnqualifiedType(Var->getType(),
6378                                             ParamType.getNonReferenceType())) {
6379           S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6380             << ParamType;
6381           S.Diag(Param->getLocation(), diag::note_template_param_here);
6382           return true;
6383         }
6384
6385         S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6386           << ParamType
6387           << FixItHint::CreateRemoval(AddrOpLoc);
6388         S.Diag(Param->getLocation(), diag::note_template_param_here);
6389
6390         ArgType = Var->getType();
6391       }
6392     } else if (!AddressTaken && ParamType->isPointerType()) {
6393       if (Var->getType()->isArrayType()) {
6394         // Array-to-pointer decay.
6395         ArgType = S.Context.getArrayDecayedType(Var->getType());
6396       } else {
6397         // If the template parameter has pointer type but the address of
6398         // this object was not taken, complain and (possibly) recover by
6399         // taking the address of the entity.
6400         ArgType = S.Context.getPointerType(Var->getType());
6401         if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6402           S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6403               << ParamType;
6404           S.Diag(Param->getLocation(), diag::note_template_param_here);
6405           return true;
6406         }
6407
6408         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6409             << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6410
6411         S.Diag(Param->getLocation(), diag::note_template_param_here);
6412       }
6413     }
6414   }
6415
6416   if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6417                                                      Arg, ArgType))
6418     return true;
6419
6420   // Create the template argument.
6421   Converted =
6422       TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
6423   S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
6424   return false;
6425 }
6426
6427 /// Checks whether the given template argument is a pointer to
6428 /// member constant according to C++ [temp.arg.nontype]p1.
6429 static bool CheckTemplateArgumentPointerToMember(Sema &S,
6430                                                  NonTypeTemplateParmDecl *Param,
6431                                                  QualType ParamType,
6432                                                  Expr *&ResultArg,
6433                                                  TemplateArgument &Converted) {
6434   bool Invalid = false;
6435
6436   Expr *Arg = ResultArg;
6437   bool ObjCLifetimeConversion;
6438
6439   // C++ [temp.arg.nontype]p1:
6440   //
6441   //   A template-argument for a non-type, non-template
6442   //   template-parameter shall be one of: [...]
6443   //
6444   //     -- a pointer to member expressed as described in 5.3.1.
6445   DeclRefExpr *DRE = nullptr;
6446
6447   // In C++98/03 mode, give an extension warning on any extra parentheses.
6448   // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6449   bool ExtraParens = false;
6450   while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6451     if (!Invalid && !ExtraParens) {
6452       S.Diag(Arg->getBeginLoc(),
6453              S.getLangOpts().CPlusPlus11
6454                  ? diag::warn_cxx98_compat_template_arg_extra_parens
6455                  : diag::ext_template_arg_extra_parens)
6456           << Arg->getSourceRange();
6457       ExtraParens = true;
6458     }
6459
6460     Arg = Parens->getSubExpr();
6461   }
6462
6463   while (SubstNonTypeTemplateParmExpr *subst =
6464            dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6465     Arg = subst->getReplacement()->IgnoreImpCasts();
6466
6467   // A pointer-to-member constant written &Class::member.
6468   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6469     if (UnOp->getOpcode() == UO_AddrOf) {
6470       DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6471       if (DRE && !DRE->getQualifier())
6472         DRE = nullptr;
6473     }
6474   }
6475   // A constant of pointer-to-member type.
6476   else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
6477     ValueDecl *VD = DRE->getDecl();
6478     if (VD->getType()->isMemberPointerType()) {
6479       if (isa<NonTypeTemplateParmDecl>(VD)) {
6480         if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6481           Converted = TemplateArgument(Arg);
6482         } else {
6483           VD = cast<ValueDecl>(VD->getCanonicalDecl());
6484           Converted = TemplateArgument(VD, ParamType);
6485         }
6486         return Invalid;
6487       }
6488     }
6489
6490     DRE = nullptr;
6491   }
6492
6493   ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6494
6495   // Check for a null pointer value.
6496   switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6497                                              Entity)) {
6498   case NPV_Error:
6499     return true;
6500   case NPV_NullPointer:
6501     S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6502     Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6503                                  /*isNullPtr*/true);
6504     return false;
6505   case NPV_NotNullPointer:
6506     break;
6507   }
6508
6509   if (S.IsQualificationConversion(ResultArg->getType(),
6510                                   ParamType.getNonReferenceType(), false,
6511                                   ObjCLifetimeConversion)) {
6512     ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6513                                     ResultArg->getValueKind())
6514                     .get();
6515   } else if (!S.Context.hasSameUnqualifiedType(
6516                  ResultArg->getType(), ParamType.getNonReferenceType())) {
6517     // We can't perform this conversion.
6518     S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
6519         << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6520     S.Diag(Param->getLocation(), diag::note_template_param_here);
6521     return true;
6522   }
6523
6524   if (!DRE)
6525     return S.Diag(Arg->getBeginLoc(),
6526                   diag::err_template_arg_not_pointer_to_member_form)
6527            << Arg->getSourceRange();
6528
6529   if (isa<FieldDecl>(DRE->getDecl()) ||
6530       isa<IndirectFieldDecl>(DRE->getDecl()) ||
6531       isa<CXXMethodDecl>(DRE->getDecl())) {
6532     assert((isa<FieldDecl>(DRE->getDecl()) ||
6533             isa<IndirectFieldDecl>(DRE->getDecl()) ||
6534             !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
6535            "Only non-static member pointers can make it here");
6536
6537     // Okay: this is the address of a non-static member, and therefore
6538     // a member pointer constant.
6539     if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6540       Converted = TemplateArgument(Arg);
6541     } else {
6542       ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
6543       Converted = TemplateArgument(D, ParamType);
6544     }
6545     return Invalid;
6546   }
6547
6548   // We found something else, but we don't know specifically what it is.
6549   S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
6550       << Arg->getSourceRange();
6551   S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6552   return true;
6553 }
6554
6555 /// Check a template argument against its corresponding
6556 /// non-type template parameter.
6557 ///
6558 /// This routine implements the semantics of C++ [temp.arg.nontype].
6559 /// If an error occurred, it returns ExprError(); otherwise, it
6560 /// returns the converted template argument. \p ParamType is the
6561 /// type of the non-type template parameter after it has been instantiated.
6562 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6563                                        QualType ParamType, Expr *Arg,
6564                                        TemplateArgument &Converted,
6565                                        CheckTemplateArgumentKind CTAK) {
6566   SourceLocation StartLoc = Arg->getBeginLoc();
6567
6568   // If the parameter type somehow involves auto, deduce the type now.
6569   if (getLangOpts().CPlusPlus17 && ParamType->isUndeducedType()) {
6570     // During template argument deduction, we allow 'decltype(auto)' to
6571     // match an arbitrary dependent argument.
6572     // FIXME: The language rules don't say what happens in this case.
6573     // FIXME: We get an opaque dependent type out of decltype(auto) if the
6574     // expression is merely instantiation-dependent; is this enough?
6575     if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
6576       auto *AT = dyn_cast<AutoType>(ParamType);
6577       if (AT && AT->isDecltypeAuto()) {
6578         Converted = TemplateArgument(Arg);
6579         return Arg;
6580       }
6581     }
6582
6583     // When checking a deduced template argument, deduce from its type even if
6584     // the type is dependent, in order to check the types of non-type template
6585     // arguments line up properly in partial ordering.
6586     Optional<unsigned> Depth = Param->getDepth() + 1;
6587     Expr *DeductionArg = Arg;
6588     if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg))
6589       DeductionArg = PE->getPattern();
6590     if (DeduceAutoType(
6591             Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
6592             DeductionArg, ParamType, Depth,
6593             // We do not check constraints right now because the
6594             // immediately-declared constraint of the auto type is also an
6595             // associated constraint, and will be checked along with the other
6596             // associated constraints after checking the template argument list.
6597             /*IgnoreConstraints=*/true) == DAR_Failed) {
6598       Diag(Arg->getExprLoc(),
6599            diag::err_non_type_template_parm_type_deduction_failure)
6600         << Param->getDeclName() << Param->getType() << Arg->getType()
6601         << Arg->getSourceRange();
6602       Diag(Param->getLocation(), diag::note_template_param_here);
6603       return ExprError();
6604     }
6605     // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6606     // an error. The error message normally references the parameter
6607     // declaration, but here we'll pass the argument location because that's
6608     // where the parameter type is deduced.
6609     ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6610     if (ParamType.isNull()) {
6611       Diag(Param->getLocation(), diag::note_template_param_here);
6612       return ExprError();
6613     }
6614   }
6615
6616   // We should have already dropped all cv-qualifiers by now.
6617   assert(!ParamType.hasQualifiers() &&
6618          "non-type template parameter type cannot be qualified");
6619
6620   if (CTAK == CTAK_Deduced &&
6621       !Context.hasSameType(ParamType.getNonLValueExprType(Context),
6622                            Arg->getType())) {
6623     // FIXME: If either type is dependent, we skip the check. This isn't
6624     // correct, since during deduction we're supposed to have replaced each
6625     // template parameter with some unique (non-dependent) placeholder.
6626     // FIXME: If the argument type contains 'auto', we carry on and fail the
6627     // type check in order to force specific types to be more specialized than
6628     // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6629     // work.
6630     if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6631         !Arg->getType()->getContainedAutoType()) {
6632       Converted = TemplateArgument(Arg);
6633       return Arg;
6634     }
6635     // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6636     // we should actually be checking the type of the template argument in P,
6637     // not the type of the template argument deduced from A, against the
6638     // template parameter type.
6639     Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
6640       << Arg->getType()
6641       << ParamType.getUnqualifiedType();
6642     Diag(Param->getLocation(), diag::note_template_param_here);
6643     return ExprError();
6644   }
6645
6646   // If either the parameter has a dependent type or the argument is
6647   // type-dependent, there's nothing we can check now. The argument only
6648   // contains an unexpanded pack during partial ordering, and there's
6649   // nothing more we can check in that case.
6650   if (ParamType->isDependentType() || Arg->isTypeDependent() ||
6651       Arg->containsUnexpandedParameterPack()) {
6652     // Force the argument to the type of the parameter to maintain invariants.
6653     auto *PE = dyn_cast<PackExpansionExpr>(Arg);
6654     if (PE)
6655       Arg = PE->getPattern();
6656     ExprResult E = ImpCastExprToType(
6657         Arg, ParamType.getNonLValueExprType(Context), CK_Dependent,
6658         ParamType->isLValueReferenceType() ? VK_LValue :
6659         ParamType->isRValueReferenceType() ? VK_XValue : VK_RValue);
6660     if (E.isInvalid())
6661       return ExprError();
6662     if (PE) {
6663       // Recreate a pack expansion if we unwrapped one.
6664       E = new (Context)
6665           PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(),
6666                             PE->getNumExpansions());
6667     }
6668     Converted = TemplateArgument(E.get());
6669     return E;
6670   }
6671
6672   // The initialization of the parameter from the argument is
6673   // a constant-evaluated context.
6674   EnterExpressionEvaluationContext ConstantEvaluated(
6675       *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6676
6677   if (getLangOpts().CPlusPlus17) {
6678     // C++17 [temp.arg.nontype]p1:
6679     //   A template-argument for a non-type template parameter shall be
6680     //   a converted constant expression of the type of the template-parameter.
6681     APValue Value;
6682     ExprResult ArgResult = CheckConvertedConstantExpression(
6683         Arg, ParamType, Value, CCEK_TemplateArg);
6684     if (ArgResult.isInvalid())
6685       return ExprError();
6686
6687     // For a value-dependent argument, CheckConvertedConstantExpression is
6688     // permitted (and expected) to be unable to determine a value.
6689     if (ArgResult.get()->isValueDependent()) {
6690       Converted = TemplateArgument(ArgResult.get());
6691       return ArgResult;
6692     }
6693
6694     QualType CanonParamType = Context.getCanonicalType(ParamType);
6695
6696     // Convert the APValue to a TemplateArgument.
6697     switch (Value.getKind()) {
6698     case APValue::None:
6699       assert(ParamType->isNullPtrType());
6700       Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
6701       break;
6702     case APValue::Indeterminate:
6703       llvm_unreachable("result of constant evaluation should be initialized");
6704       break;
6705     case APValue::Int:
6706       assert(ParamType->isIntegralOrEnumerationType());
6707       Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
6708       break;
6709     case APValue::MemberPointer: {
6710       assert(ParamType->isMemberPointerType());
6711
6712       // FIXME: We need TemplateArgument representation and mangling for these.
6713       if (!Value.getMemberPointerPath().empty()) {
6714         Diag(Arg->getBeginLoc(),
6715              diag::err_template_arg_member_ptr_base_derived_not_supported)
6716             << Value.getMemberPointerDecl() << ParamType
6717             << Arg->getSourceRange();
6718         return ExprError();
6719       }
6720
6721       auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
6722       Converted = VD ? TemplateArgument(VD, CanonParamType)
6723                      : TemplateArgument(CanonParamType, /*isNullPtr*/true);
6724       break;
6725     }
6726     case APValue::LValue: {
6727       //   For a non-type template-parameter of pointer or reference type,
6728       //   the value of the constant expression shall not refer to
6729       assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
6730              ParamType->isNullPtrType());
6731       // -- a temporary object
6732       // -- a string literal
6733       // -- the result of a typeid expression, or
6734       // -- a predefined __func__ variable
6735       APValue::LValueBase Base = Value.getLValueBase();
6736       auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
6737       if (Base && !VD) {
6738         auto *E = Base.dyn_cast<const Expr *>();
6739         if (E && isa<CXXUuidofExpr>(E)) {
6740           Converted = TemplateArgument(ArgResult.get()->IgnoreImpCasts());
6741           break;
6742         }
6743         Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6744             << Arg->getSourceRange();
6745         return ExprError();
6746       }
6747       // -- a subobject
6748       if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
6749           VD && VD->getType()->isArrayType() &&
6750           Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
6751           !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6752         // Per defect report (no number yet):
6753         //   ... other than a pointer to the first element of a complete array
6754         //       object.
6755       } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6756                  Value.isLValueOnePastTheEnd()) {
6757         Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6758           << Value.getAsString(Context, ParamType);
6759         return ExprError();
6760       }
6761       assert((VD || !ParamType->isReferenceType()) &&
6762              "null reference should not be a constant expression");
6763       assert((!VD || !ParamType->isNullPtrType()) &&
6764              "non-null value of type nullptr_t?");
6765       Converted = VD ? TemplateArgument(VD, CanonParamType)
6766                      : TemplateArgument(CanonParamType, /*isNullPtr*/true);
6767       break;
6768     }
6769     case APValue::AddrLabelDiff:
6770       return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
6771     case APValue::FixedPoint:
6772     case APValue::Float:
6773     case APValue::ComplexInt:
6774     case APValue::ComplexFloat:
6775     case APValue::Vector:
6776     case APValue::Array:
6777     case APValue::Struct:
6778     case APValue::Union:
6779       llvm_unreachable("invalid kind for template argument");
6780     }
6781
6782     return ArgResult.get();
6783   }
6784
6785   // C++ [temp.arg.nontype]p5:
6786   //   The following conversions are performed on each expression used
6787   //   as a non-type template-argument. If a non-type
6788   //   template-argument cannot be converted to the type of the
6789   //   corresponding template-parameter then the program is
6790   //   ill-formed.
6791   if (ParamType->isIntegralOrEnumerationType()) {
6792     // C++11:
6793     //   -- for a non-type template-parameter of integral or
6794     //      enumeration type, conversions permitted in a converted
6795     //      constant expression are applied.
6796     //
6797     // C++98:
6798     //   -- for a non-type template-parameter of integral or
6799     //      enumeration type, integral promotions (4.5) and integral
6800     //      conversions (4.7) are applied.
6801
6802     if (getLangOpts().CPlusPlus11) {
6803       // C++ [temp.arg.nontype]p1:
6804       //   A template-argument for a non-type, non-template template-parameter
6805       //   shall be one of:
6806       //
6807       //     -- for a non-type template-parameter of integral or enumeration
6808       //        type, a converted constant expression of the type of the
6809       //        template-parameter; or
6810       llvm::APSInt Value;
6811       ExprResult ArgResult =
6812         CheckConvertedConstantExpression(Arg, ParamType, Value,
6813                                          CCEK_TemplateArg);
6814       if (ArgResult.isInvalid())
6815         return ExprError();
6816
6817       // We can't check arbitrary value-dependent arguments.
6818       if (ArgResult.get()->isValueDependent()) {
6819         Converted = TemplateArgument(ArgResult.get());
6820         return ArgResult;
6821       }
6822
6823       // Widen the argument value to sizeof(parameter type). This is almost
6824       // always a no-op, except when the parameter type is bool. In
6825       // that case, this may extend the argument from 1 bit to 8 bits.
6826       QualType IntegerType = ParamType;
6827       if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6828         IntegerType = Enum->getDecl()->getIntegerType();
6829       Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
6830
6831       Converted = TemplateArgument(Context, Value,
6832                                    Context.getCanonicalType(ParamType));
6833       return ArgResult;
6834     }
6835
6836     ExprResult ArgResult = DefaultLvalueConversion(Arg);
6837     if (ArgResult.isInvalid())
6838       return ExprError();
6839     Arg = ArgResult.get();
6840
6841     QualType ArgType = Arg->getType();
6842
6843     // C++ [temp.arg.nontype]p1:
6844     //   A template-argument for a non-type, non-template
6845     //   template-parameter shall be one of:
6846     //
6847     //     -- an integral constant-expression of integral or enumeration
6848     //        type; or
6849     //     -- the name of a non-type template-parameter; or
6850     llvm::APSInt Value;
6851     if (!ArgType->isIntegralOrEnumerationType()) {
6852       Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
6853           << ArgType << Arg->getSourceRange();
6854       Diag(Param->getLocation(), diag::note_template_param_here);
6855       return ExprError();
6856     } else if (!Arg->isValueDependent()) {
6857       class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6858         QualType T;
6859
6860       public:
6861         TmplArgICEDiagnoser(QualType T) : T(T) { }
6862
6863         void diagnoseNotICE(Sema &S, SourceLocation Loc,
6864                             SourceRange SR) override {
6865           S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
6866         }
6867       } Diagnoser(ArgType);
6868
6869       Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
6870                                             false).get();
6871       if (!Arg)
6872         return ExprError();
6873     }
6874
6875     // From here on out, all we care about is the unqualified form
6876     // of the argument type.
6877     ArgType = ArgType.getUnqualifiedType();
6878
6879     // Try to convert the argument to the parameter's type.
6880     if (Context.hasSameType(ParamType, ArgType)) {
6881       // Okay: no conversion necessary
6882     } else if (ParamType->isBooleanType()) {
6883       // This is an integral-to-boolean conversion.
6884       Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
6885     } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6886                !ParamType->isEnumeralType()) {
6887       // This is an integral promotion or conversion.
6888       Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
6889     } else {
6890       // We can't perform this conversion.
6891       Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6892           << Arg->getType() << ParamType << Arg->getSourceRange();
6893       Diag(Param->getLocation(), diag::note_template_param_here);
6894       return ExprError();
6895     }
6896
6897     // Add the value of this argument to the list of converted
6898     // arguments. We use the bitwidth and signedness of the template
6899     // parameter.
6900     if (Arg->isValueDependent()) {
6901       // The argument is value-dependent. Create a new
6902       // TemplateArgument with the converted expression.
6903       Converted = TemplateArgument(Arg);
6904       return Arg;
6905     }
6906
6907     QualType IntegerType = Context.getCanonicalType(ParamType);
6908     if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6909       IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
6910
6911     if (ParamType->isBooleanType()) {
6912       // Value must be zero or one.
6913       Value = Value != 0;
6914       unsigned AllowedBits = Context.getTypeSize(IntegerType);
6915       if (Value.getBitWidth() != AllowedBits)
6916         Value = Value.extOrTrunc(AllowedBits);
6917       Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6918     } else {
6919       llvm::APSInt OldValue = Value;
6920
6921       // Coerce the template argument's value to the value it will have
6922       // based on the template parameter's type.
6923       unsigned AllowedBits = Context.getTypeSize(IntegerType);
6924       if (Value.getBitWidth() != AllowedBits)
6925         Value = Value.extOrTrunc(AllowedBits);
6926       Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6927
6928       // Complain if an unsigned parameter received a negative value.
6929       if (IntegerType->isUnsignedIntegerOrEnumerationType()
6930                && (OldValue.isSigned() && OldValue.isNegative())) {
6931         Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
6932             << OldValue.toString(10) << Value.toString(10) << Param->getType()
6933             << Arg->getSourceRange();
6934         Diag(Param->getLocation(), diag::note_template_param_here);
6935       }
6936
6937       // Complain if we overflowed the template parameter's type.
6938       unsigned RequiredBits;
6939       if (IntegerType->isUnsignedIntegerOrEnumerationType())
6940         RequiredBits = OldValue.getActiveBits();
6941       else if (OldValue.isUnsigned())
6942         RequiredBits = OldValue.getActiveBits() + 1;
6943       else
6944         RequiredBits = OldValue.getMinSignedBits();
6945       if (RequiredBits > AllowedBits) {
6946         Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
6947             << OldValue.toString(10) << Value.toString(10) << Param->getType()
6948             << Arg->getSourceRange();
6949         Diag(Param->getLocation(), diag::note_template_param_here);
6950       }
6951     }
6952
6953     Converted = TemplateArgument(Context, Value,
6954                                  ParamType->isEnumeralType()
6955                                    ? Context.getCanonicalType(ParamType)
6956                                    : IntegerType);
6957     return Arg;
6958   }
6959
6960   QualType ArgType = Arg->getType();
6961   DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6962
6963   // Handle pointer-to-function, reference-to-function, and
6964   // pointer-to-member-function all in (roughly) the same way.
6965   if (// -- For a non-type template-parameter of type pointer to
6966       //    function, only the function-to-pointer conversion (4.3) is
6967       //    applied. If the template-argument represents a set of
6968       //    overloaded functions (or a pointer to such), the matching
6969       //    function is selected from the set (13.4).
6970       (ParamType->isPointerType() &&
6971        ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
6972       // -- For a non-type template-parameter of type reference to
6973       //    function, no conversions apply. If the template-argument
6974       //    represents a set of overloaded functions, the matching
6975       //    function is selected from the set (13.4).
6976       (ParamType->isReferenceType() &&
6977        ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
6978       // -- For a non-type template-parameter of type pointer to
6979       //    member function, no conversions apply. If the
6980       //    template-argument represents a set of overloaded member
6981       //    functions, the matching member function is selected from
6982       //    the set (13.4).
6983       (ParamType->isMemberPointerType() &&
6984        ParamType->castAs<MemberPointerType>()->getPointeeType()
6985          ->isFunctionType())) {
6986
6987     if (Arg->getType() == Context.OverloadTy) {
6988       if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
6989                                                                 true,
6990                                                                 FoundResult)) {
6991         if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
6992           return ExprError();
6993
6994         Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6995         ArgType = Arg->getType();
6996       } else
6997         return ExprError();
6998     }
6999
7000     if (!ParamType->isMemberPointerType()) {
7001       if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
7002                                                          ParamType,
7003                                                          Arg, Converted))
7004         return ExprError();
7005       return Arg;
7006     }
7007
7008     if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
7009                                              Converted))
7010       return ExprError();
7011     return Arg;
7012   }
7013
7014   if (ParamType->isPointerType()) {
7015     //   -- for a non-type template-parameter of type pointer to
7016     //      object, qualification conversions (4.4) and the
7017     //      array-to-pointer conversion (4.2) are applied.
7018     // C++0x also allows a value of std::nullptr_t.
7019     assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7020            "Only object pointers allowed here");
7021
7022     if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
7023                                                        ParamType,
7024                                                        Arg, Converted))
7025       return ExprError();
7026     return Arg;
7027   }
7028
7029   if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7030     //   -- For a non-type template-parameter of type reference to
7031     //      object, no conversions apply. The type referred to by the
7032     //      reference may be more cv-qualified than the (otherwise
7033     //      identical) type of the template-argument. The
7034     //      template-parameter is bound directly to the
7035     //      template-argument, which must be an lvalue.
7036     assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7037            "Only object references allowed here");
7038
7039     if (Arg->getType() == Context.OverloadTy) {
7040       if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
7041                                                  ParamRefType->getPointeeType(),
7042                                                                 true,
7043                                                                 FoundResult)) {
7044         if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7045           return ExprError();
7046
7047         Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7048         ArgType = Arg->getType();
7049       } else
7050         return ExprError();
7051     }
7052
7053     if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
7054                                                        ParamType,
7055                                                        Arg, Converted))
7056       return ExprError();
7057     return Arg;
7058   }
7059
7060   // Deal with parameters of type std::nullptr_t.
7061   if (ParamType->isNullPtrType()) {
7062     if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7063       Converted = TemplateArgument(Arg);
7064       return Arg;
7065     }
7066
7067     switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7068     case NPV_NotNullPointer:
7069       Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7070         << Arg->getType() << ParamType;
7071       Diag(Param->getLocation(), diag::note_template_param_here);
7072       return ExprError();
7073
7074     case NPV_Error:
7075       return ExprError();
7076
7077     case NPV_NullPointer:
7078       Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7079       Converted = TemplateArgument(Context.getCanonicalType(ParamType),
7080                                    /*isNullPtr*/true);
7081       return Arg;
7082     }
7083   }
7084
7085   //     -- For a non-type template-parameter of type pointer to data
7086   //        member, qualification conversions (4.4) are applied.
7087   assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7088
7089   if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
7090                                            Converted))
7091     return ExprError();
7092   return Arg;
7093 }
7094
7095 static void DiagnoseTemplateParameterListArityMismatch(
7096     Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
7097     Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
7098
7099 /// Check a template argument against its corresponding
7100 /// template template parameter.
7101 ///
7102 /// This routine implements the semantics of C++ [temp.arg.template].
7103 /// It returns true if an error occurred, and false otherwise.
7104 bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7105                                          TemplateParameterList *Params,
7106                                          TemplateArgumentLoc &Arg) {
7107   TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
7108   TemplateDecl *Template = Name.getAsTemplateDecl();
7109   if (!Template) {
7110     // Any dependent template name is fine.
7111     assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7112     return false;
7113   }
7114
7115   if (Template->isInvalidDecl())
7116     return true;
7117
7118   // C++0x [temp.arg.template]p1:
7119   //   A template-argument for a template template-parameter shall be
7120   //   the name of a class template or an alias template, expressed as an
7121   //   id-expression. When the template-argument names a class template, only
7122   //   primary class templates are considered when matching the
7123   //   template template argument with the corresponding parameter;
7124   //   partial specializations are not considered even if their
7125   //   parameter lists match that of the template template parameter.
7126   //
7127   // Note that we also allow template template parameters here, which
7128   // will happen when we are dealing with, e.g., class template
7129   // partial specializations.
7130   if (!isa<ClassTemplateDecl>(Template) &&
7131       !isa<TemplateTemplateParmDecl>(Template) &&
7132       !isa<TypeAliasTemplateDecl>(Template) &&
7133       !isa<BuiltinTemplateDecl>(Template)) {
7134     assert(isa<FunctionTemplateDecl>(Template) &&
7135            "Only function templates are possible here");
7136     Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
7137     Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
7138       << Template;
7139   }
7140
7141   // C++1z [temp.arg.template]p3: (DR 150)
7142   //   A template-argument matches a template template-parameter P when P
7143   //   is at least as specialized as the template-argument A.
7144   // FIXME: We should enable RelaxedTemplateTemplateArgs by default as it is a
7145   //  defect report resolution from C++17 and shouldn't be introduced by
7146   //  concepts.
7147   if (getLangOpts().RelaxedTemplateTemplateArgs) {
7148     // Quick check for the common case:
7149     //   If P contains a parameter pack, then A [...] matches P if each of A's
7150     //   template parameters matches the corresponding template parameter in
7151     //   the template-parameter-list of P.
7152     if (TemplateParameterListsAreEqual(
7153             Template->getTemplateParameters(), Params, false,
7154             TPL_TemplateTemplateArgumentMatch, Arg.getLocation()) &&
7155         // If the argument has no associated constraints, then the parameter is
7156         // definitely at least as specialized as the argument.
7157         // Otherwise - we need a more thorough check.
7158         !Template->hasAssociatedConstraints())
7159       return false;
7160
7161     if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
7162                                                           Arg.getLocation())) {
7163       // C++2a[temp.func.order]p2
7164       //   [...] If both deductions succeed, the partial ordering selects the
7165       //   more constrained template as described by the rules in
7166       //   [temp.constr.order].
7167       SmallVector<const Expr *, 3> ParamsAC, TemplateAC;
7168       Params->getAssociatedConstraints(ParamsAC);
7169       // C++2a[temp.arg.template]p3
7170       //   [...] In this comparison, if P is unconstrained, the constraints on A
7171       //   are not considered.
7172       if (ParamsAC.empty())
7173         return false;
7174       Template->getAssociatedConstraints(TemplateAC);
7175       bool IsParamAtLeastAsConstrained;
7176       if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7177                                  IsParamAtLeastAsConstrained))
7178         return true;
7179       if (!IsParamAtLeastAsConstrained) {
7180         Diag(Arg.getLocation(),
7181              diag::err_template_template_parameter_not_at_least_as_constrained)
7182             << Template << Param << Arg.getSourceRange();
7183         Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7184         Diag(Template->getLocation(), diag::note_entity_declared_at)
7185             << Template;
7186         MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template,
7187                                                       TemplateAC);
7188         return true;
7189       }
7190       return false;
7191     }
7192     // FIXME: Produce better diagnostics for deduction failures.
7193   }
7194
7195   return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
7196                                          Params,
7197                                          true,
7198                                          TPL_TemplateTemplateArgumentMatch,
7199                                          Arg.getLocation());
7200 }
7201
7202 /// Given a non-type template argument that refers to a
7203 /// declaration and the type of its corresponding non-type template
7204 /// parameter, produce an expression that properly refers to that
7205 /// declaration.
7206 ExprResult
7207 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
7208                                               QualType ParamType,
7209                                               SourceLocation Loc) {
7210   // C++ [temp.param]p8:
7211   //
7212   //   A non-type template-parameter of type "array of T" or
7213   //   "function returning T" is adjusted to be of type "pointer to
7214   //   T" or "pointer to function returning T", respectively.
7215   if (ParamType->isArrayType())
7216     ParamType = Context.getArrayDecayedType(ParamType);
7217   else if (ParamType->isFunctionType())
7218     ParamType = Context.getPointerType(ParamType);
7219
7220   // For a NULL non-type template argument, return nullptr casted to the
7221   // parameter's type.
7222   if (Arg.getKind() == TemplateArgument::NullPtr) {
7223     return ImpCastExprToType(
7224              new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7225                              ParamType,
7226                              ParamType->getAs<MemberPointerType>()
7227                                ? CK_NullToMemberPointer
7228                                : CK_NullToPointer);
7229   }
7230   assert(Arg.getKind() == TemplateArgument::Declaration &&
7231          "Only declaration template arguments permitted here");
7232
7233   ValueDecl *VD = Arg.getAsDecl();
7234
7235   CXXScopeSpec SS;
7236   if (ParamType->isMemberPointerType()) {
7237     // If this is a pointer to member, we need to use a qualified name to
7238     // form a suitable pointer-to-member constant.
7239     assert(VD->getDeclContext()->isRecord() &&
7240            (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7241             isa<IndirectFieldDecl>(VD)));
7242     QualType ClassType
7243       = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
7244     NestedNameSpecifier *Qualifier
7245       = NestedNameSpecifier::Create(Context, nullptr, false,
7246                                     ClassType.getTypePtr());
7247     SS.MakeTrivial(Context, Qualifier, Loc);
7248   }
7249
7250   ExprResult RefExpr = BuildDeclarationNameExpr(
7251       SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7252   if (RefExpr.isInvalid())
7253     return ExprError();
7254
7255   // For a pointer, the argument declaration is the pointee. Take its address.
7256   QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7257   if (ParamType->isPointerType() && !ElemT.isNull() &&
7258       Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
7259     // Decay an array argument if we want a pointer to its first element.
7260     RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
7261     if (RefExpr.isInvalid())
7262       return ExprError();
7263   } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7264     // For any other pointer, take the address (or form a pointer-to-member).
7265     RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
7266     if (RefExpr.isInvalid())
7267       return ExprError();
7268   } else {
7269     assert(ParamType->isReferenceType() &&
7270            "unexpected type for decl template argument");
7271   }
7272
7273   // At this point we should have the right value category.
7274   assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
7275          "value kind mismatch for non-type template argument");
7276
7277   // The type of the template parameter can differ from the type of the
7278   // argument in various ways; convert it now if necessary.
7279   QualType DestExprType = ParamType.getNonLValueExprType(Context);
7280   if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
7281     CastKind CK;
7282     QualType Ignored;
7283     if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
7284         IsFunctionConversion(RefExpr.get()->getType(), DestExprType, Ignored)) {
7285       CK = CK_NoOp;
7286     } else if (ParamType->isVoidPointerType() &&
7287                RefExpr.get()->getType()->isPointerType()) {
7288       CK = CK_BitCast;
7289     } else {
7290       // FIXME: Pointers to members can need conversion derived-to-base or
7291       // base-to-derived conversions. We currently don't retain enough
7292       // information to convert properly (we need to track a cast path or
7293       // subobject number in the template argument).
7294       llvm_unreachable(
7295           "unexpected conversion required for non-type template argument");
7296     }
7297     RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
7298                                 RefExpr.get()->getValueKind());
7299   }
7300
7301   return RefExpr;
7302 }
7303
7304 /// Construct a new expression that refers to the given
7305 /// integral template argument with the given source-location
7306 /// information.
7307 ///
7308 /// This routine takes care of the mapping from an integral template
7309 /// argument (which may have any integral type) to the appropriate
7310 /// literal value.
7311 ExprResult
7312 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
7313                                                   SourceLocation Loc) {
7314   assert(Arg.getKind() == TemplateArgument::Integral &&
7315          "Operation is only valid for integral template arguments");
7316   QualType OrigT = Arg.getIntegralType();
7317
7318   // If this is an enum type that we're instantiating, we need to use an integer
7319   // type the same size as the enumerator.  We don't want to build an
7320   // IntegerLiteral with enum type.  The integer type of an enum type can be of
7321   // any integral type with C++11 enum classes, make sure we create the right
7322   // type of literal for it.
7323   QualType T = OrigT;
7324   if (const EnumType *ET = OrigT->getAs<EnumType>())
7325     T = ET->getDecl()->getIntegerType();
7326
7327   Expr *E;
7328   if (T->isAnyCharacterType()) {
7329     CharacterLiteral::CharacterKind Kind;
7330     if (T->isWideCharType())
7331       Kind = CharacterLiteral::Wide;
7332     else if (T->isChar8Type() && getLangOpts().Char8)
7333       Kind = CharacterLiteral::UTF8;
7334     else if (T->isChar16Type())
7335       Kind = CharacterLiteral::UTF16;
7336     else if (T->isChar32Type())
7337       Kind = CharacterLiteral::UTF32;
7338     else
7339       Kind = CharacterLiteral::Ascii;
7340
7341     E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
7342                                        Kind, T, Loc);
7343   } else if (T->isBooleanType()) {
7344     E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
7345                                          T, Loc);
7346   } else if (T->isNullPtrType()) {
7347     E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
7348   } else {
7349     E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
7350   }
7351
7352   if (OrigT->isEnumeralType()) {
7353     // FIXME: This is a hack. We need a better way to handle substituted
7354     // non-type template parameters.
7355     E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
7356                                nullptr,
7357                                Context.getTrivialTypeSourceInfo(OrigT, Loc),
7358                                Loc, Loc);
7359   }
7360
7361   return E;
7362 }
7363
7364 /// Match two template parameters within template parameter lists.
7365 static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
7366                                        bool Complain,
7367                                      Sema::TemplateParameterListEqualKind Kind,
7368                                        SourceLocation TemplateArgLoc) {
7369   // Check the actual kind (type, non-type, template).
7370   if (Old->getKind() != New->getKind()) {
7371     if (Complain) {
7372       unsigned NextDiag = diag::err_template_param_different_kind;
7373       if (TemplateArgLoc.isValid()) {
7374         S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7375         NextDiag = diag::note_template_param_different_kind;
7376       }
7377       S.Diag(New->getLocation(), NextDiag)
7378         << (Kind != Sema::TPL_TemplateMatch);
7379       S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
7380         << (Kind != Sema::TPL_TemplateMatch);
7381     }
7382
7383     return false;
7384   }
7385
7386   // Check that both are parameter packs or neither are parameter packs.
7387   // However, if we are matching a template template argument to a
7388   // template template parameter, the template template parameter can have
7389   // a parameter pack where the template template argument does not.
7390   if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
7391       !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
7392         Old->isTemplateParameterPack())) {
7393     if (Complain) {
7394       unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
7395       if (TemplateArgLoc.isValid()) {
7396         S.Diag(TemplateArgLoc,
7397              diag::err_template_arg_template_params_mismatch);
7398         NextDiag = diag::note_template_parameter_pack_non_pack;
7399       }
7400
7401       unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
7402                       : isa<NonTypeTemplateParmDecl>(New)? 1
7403                       : 2;
7404       S.Diag(New->getLocation(), NextDiag)
7405         << ParamKind << New->isParameterPack();
7406       S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
7407         << ParamKind << Old->isParameterPack();
7408     }
7409
7410     return false;
7411   }
7412
7413   // For non-type template parameters, check the type of the parameter.
7414   if (NonTypeTemplateParmDecl *OldNTTP
7415                                     = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
7416     NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
7417
7418     // If we are matching a template template argument to a template
7419     // template parameter and one of the non-type template parameter types
7420     // is dependent, then we must wait until template instantiation time
7421     // to actually compare the arguments.
7422     if (Kind != Sema::TPL_TemplateTemplateArgumentMatch ||
7423         (!OldNTTP->getType()->isDependentType() &&
7424          !NewNTTP->getType()->isDependentType()))
7425       if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
7426         if (Complain) {
7427           unsigned NextDiag = diag::err_template_nontype_parm_different_type;
7428           if (TemplateArgLoc.isValid()) {
7429             S.Diag(TemplateArgLoc,
7430                    diag::err_template_arg_template_params_mismatch);
7431             NextDiag = diag::note_template_nontype_parm_different_type;
7432           }
7433           S.Diag(NewNTTP->getLocation(), NextDiag)
7434             << NewNTTP->getType()
7435             << (Kind != Sema::TPL_TemplateMatch);
7436           S.Diag(OldNTTP->getLocation(),
7437                  diag::note_template_nontype_parm_prev_declaration)
7438             << OldNTTP->getType();
7439         }
7440
7441         return false;
7442       }
7443   }
7444   // For template template parameters, check the template parameter types.
7445   // The template parameter lists of template template
7446   // parameters must agree.
7447   else if (TemplateTemplateParmDecl *OldTTP
7448                                     = dyn_cast<TemplateTemplateParmDecl>(Old)) {
7449     TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
7450     if (!S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
7451                                           OldTTP->getTemplateParameters(),
7452                                           Complain,
7453                                         (Kind == Sema::TPL_TemplateMatch
7454                                            ? Sema::TPL_TemplateTemplateParmMatch
7455                                            : Kind),
7456                                           TemplateArgLoc))
7457       return false;
7458   } else if (Kind != Sema::TPL_TemplateTemplateArgumentMatch) {
7459     const Expr *NewC = nullptr, *OldC = nullptr;
7460     if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
7461       NewC = TC->getImmediatelyDeclaredConstraint();
7462     if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
7463       OldC = TC->getImmediatelyDeclaredConstraint();
7464
7465     auto Diagnose = [&] {
7466       S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
7467            diag::err_template_different_type_constraint);
7468       S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
7469            diag::note_template_prev_declaration) << /*declaration*/0;
7470     };
7471
7472     if (!NewC != !OldC) {
7473       if (Complain)
7474         Diagnose();
7475       return false;
7476     }
7477
7478     if (NewC) {
7479       llvm::FoldingSetNodeID OldCID, NewCID;
7480       OldC->Profile(OldCID, S.Context, /*Canonical=*/true);
7481       NewC->Profile(NewCID, S.Context, /*Canonical=*/true);
7482       if (OldCID != NewCID) {
7483         if (Complain)
7484           Diagnose();
7485         return false;
7486       }
7487     }
7488   }
7489
7490   return true;
7491 }
7492
7493 /// Diagnose a known arity mismatch when comparing template argument
7494 /// lists.
7495 static
7496 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
7497                                                 TemplateParameterList *New,
7498                                                 TemplateParameterList *Old,
7499                                       Sema::TemplateParameterListEqualKind Kind,
7500                                                 SourceLocation TemplateArgLoc) {
7501   unsigned NextDiag = diag::err_template_param_list_different_arity;
7502   if (TemplateArgLoc.isValid()) {
7503     S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7504     NextDiag = diag::note_template_param_list_different_arity;
7505   }
7506   S.Diag(New->getTemplateLoc(), NextDiag)
7507     << (New->size() > Old->size())
7508     << (Kind != Sema::TPL_TemplateMatch)
7509     << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
7510   S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
7511     << (Kind != Sema::TPL_TemplateMatch)
7512     << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
7513 }
7514
7515 /// Determine whether the given template parameter lists are
7516 /// equivalent.
7517 ///
7518 /// \param New  The new template parameter list, typically written in the
7519 /// source code as part of a new template declaration.
7520 ///
7521 /// \param Old  The old template parameter list, typically found via
7522 /// name lookup of the template declared with this template parameter
7523 /// list.
7524 ///
7525 /// \param Complain  If true, this routine will produce a diagnostic if
7526 /// the template parameter lists are not equivalent.
7527 ///
7528 /// \param Kind describes how we are to match the template parameter lists.
7529 ///
7530 /// \param TemplateArgLoc If this source location is valid, then we
7531 /// are actually checking the template parameter list of a template
7532 /// argument (New) against the template parameter list of its
7533 /// corresponding template template parameter (Old). We produce
7534 /// slightly different diagnostics in this scenario.
7535 ///
7536 /// \returns True if the template parameter lists are equal, false
7537 /// otherwise.
7538 bool
7539 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
7540                                      TemplateParameterList *Old,
7541                                      bool Complain,
7542                                      TemplateParameterListEqualKind Kind,
7543                                      SourceLocation TemplateArgLoc) {
7544   if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
7545     if (Complain)
7546       DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7547                                                  TemplateArgLoc);
7548
7549     return false;
7550   }
7551
7552   // C++0x [temp.arg.template]p3:
7553   //   A template-argument matches a template template-parameter (call it P)
7554   //   when each of the template parameters in the template-parameter-list of
7555   //   the template-argument's corresponding class template or alias template
7556   //   (call it A) matches the corresponding template parameter in the
7557   //   template-parameter-list of P. [...]
7558   TemplateParameterList::iterator NewParm = New->begin();
7559   TemplateParameterList::iterator NewParmEnd = New->end();
7560   for (TemplateParameterList::iterator OldParm = Old->begin(),
7561                                     OldParmEnd = Old->end();
7562        OldParm != OldParmEnd; ++OldParm) {
7563     if (Kind != TPL_TemplateTemplateArgumentMatch ||
7564         !(*OldParm)->isTemplateParameterPack()) {
7565       if (NewParm == NewParmEnd) {
7566         if (Complain)
7567           DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7568                                                      TemplateArgLoc);
7569
7570         return false;
7571       }
7572
7573       if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7574                                       Kind, TemplateArgLoc))
7575         return false;
7576
7577       ++NewParm;
7578       continue;
7579     }
7580
7581     // C++0x [temp.arg.template]p3:
7582     //   [...] When P's template- parameter-list contains a template parameter
7583     //   pack (14.5.3), the template parameter pack will match zero or more
7584     //   template parameters or template parameter packs in the
7585     //   template-parameter-list of A with the same type and form as the
7586     //   template parameter pack in P (ignoring whether those template
7587     //   parameters are template parameter packs).
7588     for (; NewParm != NewParmEnd; ++NewParm) {
7589       if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7590                                       Kind, TemplateArgLoc))
7591         return false;
7592     }
7593   }
7594
7595   // Make sure we exhausted all of the arguments.
7596   if (NewParm != NewParmEnd) {
7597     if (Complain)
7598       DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7599                                                  TemplateArgLoc);
7600
7601     return false;
7602   }
7603
7604   if (Kind != TPL_TemplateTemplateArgumentMatch) {
7605     const Expr *NewRC = New->getRequiresClause();
7606     const Expr *OldRC = Old->getRequiresClause();
7607
7608     auto Diagnose = [&] {
7609       Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
7610            diag::err_template_different_requires_clause);
7611       Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
7612            diag::note_template_prev_declaration) << /*declaration*/0;
7613     };
7614
7615     if (!NewRC != !OldRC) {
7616       if (Complain)
7617         Diagnose();
7618       return false;
7619     }
7620
7621     if (NewRC) {
7622       llvm::FoldingSetNodeID OldRCID, NewRCID;
7623       OldRC->Profile(OldRCID, Context, /*Canonical=*/true);
7624       NewRC->Profile(NewRCID, Context, /*Canonical=*/true);
7625       if (OldRCID != NewRCID) {
7626         if (Complain)
7627           Diagnose();
7628         return false;
7629       }
7630     }
7631   }
7632
7633   return true;
7634 }
7635
7636 /// Check whether a template can be declared within this scope.
7637 ///
7638 /// If the template declaration is valid in this scope, returns
7639 /// false. Otherwise, issues a diagnostic and returns true.
7640 bool
7641 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
7642   if (!S)
7643     return false;
7644
7645   // Find the nearest enclosing declaration scope.
7646   while ((S->getFlags() & Scope::DeclScope) == 0 ||
7647          (S->getFlags() & Scope::TemplateParamScope) != 0)
7648     S = S->getParent();
7649
7650   // C++ [temp]p4:
7651   //   A template [...] shall not have C linkage.
7652   DeclContext *Ctx = S->getEntity();
7653   assert(Ctx && "Unknown context");
7654   if (Ctx->isExternCContext()) {
7655     Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
7656         << TemplateParams->getSourceRange();
7657     if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
7658       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
7659     return true;
7660   }
7661   Ctx = Ctx->getRedeclContext();
7662
7663   // C++ [temp]p2:
7664   //   A template-declaration can appear only as a namespace scope or
7665   //   class scope declaration.
7666   if (Ctx) {
7667     if (Ctx->isFileContext())
7668       return false;
7669     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
7670       // C++ [temp.mem]p2:
7671       //   A local class shall not have member templates.
7672       if (RD->isLocalClass())
7673         return Diag(TemplateParams->getTemplateLoc(),
7674                     diag::err_template_inside_local_class)
7675           << TemplateParams->getSourceRange();
7676       else
7677         return false;
7678     }
7679   }
7680
7681   return Diag(TemplateParams->getTemplateLoc(),
7682               diag::err_template_outside_namespace_or_class_scope)
7683     << TemplateParams->getSourceRange();
7684 }
7685
7686 /// Determine what kind of template specialization the given declaration
7687 /// is.
7688 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
7689   if (!D)
7690     return TSK_Undeclared;
7691
7692   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
7693     return Record->getTemplateSpecializationKind();
7694   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
7695     return Function->getTemplateSpecializationKind();
7696   if (VarDecl *Var = dyn_cast<VarDecl>(D))
7697     return Var->getTemplateSpecializationKind();
7698
7699   return TSK_Undeclared;
7700 }
7701
7702 /// Check whether a specialization is well-formed in the current
7703 /// context.
7704 ///
7705 /// This routine determines whether a template specialization can be declared
7706 /// in the current context (C++ [temp.expl.spec]p2).
7707 ///
7708 /// \param S the semantic analysis object for which this check is being
7709 /// performed.
7710 ///
7711 /// \param Specialized the entity being specialized or instantiated, which
7712 /// may be a kind of template (class template, function template, etc.) or
7713 /// a member of a class template (member function, static data member,
7714 /// member class).
7715 ///
7716 /// \param PrevDecl the previous declaration of this entity, if any.
7717 ///
7718 /// \param Loc the location of the explicit specialization or instantiation of
7719 /// this entity.
7720 ///
7721 /// \param IsPartialSpecialization whether this is a partial specialization of
7722 /// a class template.
7723 ///
7724 /// \returns true if there was an error that we cannot recover from, false
7725 /// otherwise.
7726 static bool CheckTemplateSpecializationScope(Sema &S,
7727                                              NamedDecl *Specialized,
7728                                              NamedDecl *PrevDecl,
7729                                              SourceLocation Loc,
7730                                              bool IsPartialSpecialization) {
7731   // Keep these "kind" numbers in sync with the %select statements in the
7732   // various diagnostics emitted by this routine.
7733   int EntityKind = 0;
7734   if (isa<ClassTemplateDecl>(Specialized))
7735     EntityKind = IsPartialSpecialization? 1 : 0;
7736   else if (isa<VarTemplateDecl>(Specialized))
7737     EntityKind = IsPartialSpecialization ? 3 : 2;
7738   else if (isa<FunctionTemplateDecl>(Specialized))
7739     EntityKind = 4;
7740   else if (isa<CXXMethodDecl>(Specialized))
7741     EntityKind = 5;
7742   else if (isa<VarDecl>(Specialized))
7743     EntityKind = 6;
7744   else if (isa<RecordDecl>(Specialized))
7745     EntityKind = 7;
7746   else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
7747     EntityKind = 8;
7748   else {
7749     S.Diag(Loc, diag::err_template_spec_unknown_kind)
7750       << S.getLangOpts().CPlusPlus11;
7751     S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7752     return true;
7753   }
7754
7755   // C++ [temp.expl.spec]p2:
7756   //   An explicit specialization may be declared in any scope in which
7757   //   the corresponding primary template may be defined.
7758   if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7759     S.Diag(Loc, diag::err_template_spec_decl_function_scope)
7760       << Specialized;
7761     return true;
7762   }
7763
7764   // C++ [temp.class.spec]p6:
7765   //   A class template partial specialization may be declared in any
7766   //   scope in which the primary template may be defined.
7767   DeclContext *SpecializedContext =
7768       Specialized->getDeclContext()->getRedeclContext();
7769   DeclContext *DC = S.CurContext->getRedeclContext();
7770
7771   // Make sure that this redeclaration (or definition) occurs in the same
7772   // scope or an enclosing namespace.
7773   if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
7774                             : DC->Equals(SpecializedContext))) {
7775     if (isa<TranslationUnitDecl>(SpecializedContext))
7776       S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
7777         << EntityKind << Specialized;
7778     else {
7779       auto *ND = cast<NamedDecl>(SpecializedContext);
7780       int Diag = diag::err_template_spec_redecl_out_of_scope;
7781       if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
7782         Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
7783       S.Diag(Loc, Diag) << EntityKind << Specialized
7784                         << ND << isa<CXXRecordDecl>(ND);
7785     }
7786
7787     S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7788
7789     // Don't allow specializing in the wrong class during error recovery.
7790     // Otherwise, things can go horribly wrong.
7791     if (DC->isRecord())
7792       return true;
7793   }
7794
7795   return false;
7796 }
7797
7798 static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
7799   if (!E->isTypeDependent())
7800     return SourceLocation();
7801   DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7802   Checker.TraverseStmt(E);
7803   if (Checker.MatchLoc.isInvalid())
7804     return E->getSourceRange();
7805   return Checker.MatchLoc;
7806 }
7807
7808 static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
7809   if (!TL.getType()->isDependentType())
7810     return SourceLocation();
7811   DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7812   Checker.TraverseTypeLoc(TL);
7813   if (Checker.MatchLoc.isInvalid())
7814     return TL.getSourceRange();
7815   return Checker.MatchLoc;
7816 }
7817
7818 /// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
7819 /// that checks non-type template partial specialization arguments.
7820 static bool CheckNonTypeTemplatePartialSpecializationArgs(
7821     Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7822     const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
7823   for (unsigned I = 0; I != NumArgs; ++I) {
7824     if (Args[I].getKind() == TemplateArgument::Pack) {
7825       if (CheckNonTypeTemplatePartialSpecializationArgs(
7826               S, TemplateNameLoc, Param, Args[I].pack_begin(),
7827               Args[I].pack_size(), IsDefaultArgument))
7828         return true;
7829
7830       continue;
7831     }
7832
7833     if (Args[I].getKind() != TemplateArgument::Expression)
7834       continue;
7835
7836     Expr *ArgExpr = Args[I].getAsExpr();
7837
7838     // We can have a pack expansion of any of the bullets below.
7839     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7840       ArgExpr = Expansion->getPattern();
7841
7842     // Strip off any implicit casts we added as part of type checking.
7843     while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7844       ArgExpr = ICE->getSubExpr();
7845
7846     // C++ [temp.class.spec]p8:
7847     //   A non-type argument is non-specialized if it is the name of a
7848     //   non-type parameter. All other non-type arguments are
7849     //   specialized.
7850     //
7851     // Below, we check the two conditions that only apply to
7852     // specialized non-type arguments, so skip any non-specialized
7853     // arguments.
7854     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
7855       if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
7856         continue;
7857
7858     // C++ [temp.class.spec]p9:
7859     //   Within the argument list of a class template partial
7860     //   specialization, the following restrictions apply:
7861     //     -- A partially specialized non-type argument expression
7862     //        shall not involve a template parameter of the partial
7863     //        specialization except when the argument expression is a
7864     //        simple identifier.
7865     //     -- The type of a template parameter corresponding to a
7866     //        specialized non-type argument shall not be dependent on a
7867     //        parameter of the specialization.
7868     // DR1315 removes the first bullet, leaving an incoherent set of rules.
7869     // We implement a compromise between the original rules and DR1315:
7870     //     --  A specialized non-type template argument shall not be
7871     //         type-dependent and the corresponding template parameter
7872     //         shall have a non-dependent type.
7873     SourceRange ParamUseRange =
7874         findTemplateParameterInType(Param->getDepth(), ArgExpr);
7875     if (ParamUseRange.isValid()) {
7876       if (IsDefaultArgument) {
7877         S.Diag(TemplateNameLoc,
7878                diag::err_dependent_non_type_arg_in_partial_spec);
7879         S.Diag(ParamUseRange.getBegin(),
7880                diag::note_dependent_non_type_default_arg_in_partial_spec)
7881           << ParamUseRange;
7882       } else {
7883         S.Diag(ParamUseRange.getBegin(),
7884                diag::err_dependent_non_type_arg_in_partial_spec)
7885           << ParamUseRange;
7886       }
7887       return true;
7888     }
7889
7890     ParamUseRange = findTemplateParameter(
7891         Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
7892     if (ParamUseRange.isValid()) {
7893       S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
7894              diag::err_dependent_typed_non_type_arg_in_partial_spec)
7895           << Param->getType();
7896       S.Diag(Param->getLocation(), diag::note_template_param_here)
7897         << (IsDefaultArgument ? ParamUseRange : SourceRange())
7898         << ParamUseRange;
7899       return true;
7900     }
7901   }
7902
7903   return false;
7904 }
7905
7906 /// Check the non-type template arguments of a class template
7907 /// partial specialization according to C++ [temp.class.spec]p9.
7908 ///
7909 /// \param TemplateNameLoc the location of the template name.
7910 /// \param PrimaryTemplate the template parameters of the primary class
7911 ///        template.
7912 /// \param NumExplicit the number of explicitly-specified template arguments.
7913 /// \param TemplateArgs the template arguments of the class template
7914 ///        partial specialization.
7915 ///
7916 /// \returns \c true if there was an error, \c false otherwise.
7917 bool Sema::CheckTemplatePartialSpecializationArgs(
7918     SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7919     unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7920   // We have to be conservative when checking a template in a dependent
7921   // context.
7922   if (PrimaryTemplate->getDeclContext()->isDependentContext())
7923     return false;
7924
7925   TemplateParameterList *TemplateParams =
7926       PrimaryTemplate->getTemplateParameters();
7927   for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7928     NonTypeTemplateParmDecl *Param
7929       = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7930     if (!Param)
7931       continue;
7932
7933     if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7934                                                       Param, &TemplateArgs[I],
7935                                                       1, I >= NumExplicit))
7936       return true;
7937   }
7938
7939   return false;
7940 }
7941
7942 DeclResult Sema::ActOnClassTemplateSpecialization(
7943     Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7944     SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
7945     TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
7946     MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
7947   assert(TUK != TUK_Reference && "References are not specializations");
7948
7949   // NOTE: KWLoc is the location of the tag keyword. This will instead
7950   // store the location of the outermost template keyword in the declaration.
7951   SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
7952     ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7953   SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7954   SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7955   SourceLocation RAngleLoc = TemplateId.RAngleLoc;
7956
7957   // Find the class template we're specializing
7958   TemplateName Name = TemplateId.Template.get();
7959   ClassTemplateDecl *ClassTemplate
7960     = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7961
7962   if (!ClassTemplate) {
7963     Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
7964       << (Name.getAsTemplateDecl() &&
7965           isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7966     return true;
7967   }
7968
7969   bool isMemberSpecialization = false;
7970   bool isPartialSpecialization = false;
7971
7972   // Check the validity of the template headers that introduce this
7973   // template.
7974   // FIXME: We probably shouldn't complain about these headers for
7975   // friend declarations.
7976   bool Invalid = false;
7977   TemplateParameterList *TemplateParams =
7978       MatchTemplateParametersToScopeSpecifier(
7979           KWLoc, TemplateNameLoc, SS, &TemplateId,
7980           TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
7981           Invalid);
7982   if (Invalid)
7983     return true;
7984
7985   if (TemplateParams && TemplateParams->size() > 0) {
7986     isPartialSpecialization = true;
7987
7988     if (TUK == TUK_Friend) {
7989       Diag(KWLoc, diag::err_partial_specialization_friend)
7990         << SourceRange(LAngleLoc, RAngleLoc);
7991       return true;
7992     }
7993
7994     // C++ [temp.class.spec]p10:
7995     //   The template parameter list of a specialization shall not
7996     //   contain default template argument values.
7997     for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7998       Decl *Param = TemplateParams->getParam(I);
7999       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8000         if (TTP->hasDefaultArgument()) {
8001           Diag(TTP->getDefaultArgumentLoc(),
8002                diag::err_default_arg_in_partial_spec);
8003           TTP->removeDefaultArgument();
8004         }
8005       } else if (NonTypeTemplateParmDecl *NTTP
8006                    = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8007         if (Expr *DefArg = NTTP->getDefaultArgument()) {
8008           Diag(NTTP->getDefaultArgumentLoc(),
8009                diag::err_default_arg_in_partial_spec)
8010             << DefArg->getSourceRange();
8011           NTTP->removeDefaultArgument();
8012         }
8013       } else {
8014         TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
8015         if (TTP->hasDefaultArgument()) {
8016           Diag(TTP->getDefaultArgument().getLocation(),
8017                diag::err_default_arg_in_partial_spec)
8018             << TTP->getDefaultArgument().getSourceRange();
8019           TTP->removeDefaultArgument();
8020         }
8021       }
8022     }
8023   } else if (TemplateParams) {
8024     if (TUK == TUK_Friend)
8025       Diag(KWLoc, diag::err_template_spec_friend)
8026         << FixItHint::CreateRemoval(
8027                                 SourceRange(TemplateParams->getTemplateLoc(),
8028                                             TemplateParams->getRAngleLoc()))
8029         << SourceRange(LAngleLoc, RAngleLoc);
8030   } else {
8031     assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
8032   }
8033
8034   // Check that the specialization uses the same tag kind as the
8035   // original template.
8036   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8037   assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
8038   if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
8039                                     Kind, TUK == TUK_Definition, KWLoc,
8040                                     ClassTemplate->getIdentifier())) {
8041     Diag(KWLoc, diag::err_use_with_wrong_tag)
8042       << ClassTemplate
8043       << FixItHint::CreateReplacement(KWLoc,
8044                             ClassTemplate->getTemplatedDecl()->getKindName());
8045     Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8046          diag::note_previous_use);
8047     Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8048   }
8049
8050   // Translate the parser's template argument list in our AST format.
8051   TemplateArgumentListInfo TemplateArgs =
8052       makeTemplateArgumentListInfo(*this, TemplateId);
8053
8054   // Check for unexpanded parameter packs in any of the template arguments.
8055   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8056     if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8057                                         UPPC_PartialSpecialization))
8058       return true;
8059
8060   // Check that the template argument list is well-formed for this
8061   // template.
8062   SmallVector<TemplateArgument, 4> Converted;
8063   if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
8064                                 TemplateArgs, false, Converted,
8065                                 /*UpdateArgsWithConversion=*/true))
8066     return true;
8067
8068   // Find the class template (partial) specialization declaration that
8069   // corresponds to these arguments.
8070   if (isPartialSpecialization) {
8071     if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
8072                                                TemplateArgs.size(), Converted))
8073       return true;
8074
8075     // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8076     // also do it during instantiation.
8077     bool InstantiationDependent;
8078     if (!Name.isDependent() &&
8079         !TemplateSpecializationType::anyDependentTemplateArguments(
8080             TemplateArgs.arguments(), InstantiationDependent)) {
8081       Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8082         << ClassTemplate->getDeclName();
8083       isPartialSpecialization = false;
8084     }
8085   }
8086
8087   void *InsertPos = nullptr;
8088   ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8089
8090   if (isPartialSpecialization)
8091     PrevDecl = ClassTemplate->findPartialSpecialization(Converted,
8092                                                         TemplateParams,
8093                                                         InsertPos);
8094   else
8095     PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
8096
8097   ClassTemplateSpecializationDecl *Specialization = nullptr;
8098
8099   // Check whether we can declare a class template specialization in
8100   // the current scope.
8101   if (TUK != TUK_Friend &&
8102       CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
8103                                        TemplateNameLoc,
8104                                        isPartialSpecialization))
8105     return true;
8106
8107   // The canonical type
8108   QualType CanonType;
8109   if (isPartialSpecialization) {
8110     // Build the canonical type that describes the converted template
8111     // arguments of the class template partial specialization.
8112     TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8113     CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8114                                                       Converted);
8115
8116     if (Context.hasSameType(CanonType,
8117                         ClassTemplate->getInjectedClassNameSpecialization()) &&
8118         (!Context.getLangOpts().CPlusPlus2a ||
8119          !TemplateParams->hasAssociatedConstraints())) {
8120       // C++ [temp.class.spec]p9b3:
8121       //
8122       //   -- The argument list of the specialization shall not be identical
8123       //      to the implicit argument list of the primary template.
8124       //
8125       // This rule has since been removed, because it's redundant given DR1495,
8126       // but we keep it because it produces better diagnostics and recovery.
8127       Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
8128         << /*class template*/0 << (TUK == TUK_Definition)
8129         << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
8130       return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
8131                                 ClassTemplate->getIdentifier(),
8132                                 TemplateNameLoc,
8133                                 Attr,
8134                                 TemplateParams,
8135                                 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
8136                                 /*FriendLoc*/SourceLocation(),
8137                                 TemplateParameterLists.size() - 1,
8138                                 TemplateParameterLists.data());
8139     }
8140
8141     // Create a new class template partial specialization declaration node.
8142     ClassTemplatePartialSpecializationDecl *PrevPartial
8143       = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
8144     ClassTemplatePartialSpecializationDecl *Partial
8145       = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
8146                                              ClassTemplate->getDeclContext(),
8147                                                        KWLoc, TemplateNameLoc,
8148                                                        TemplateParams,
8149                                                        ClassTemplate,
8150                                                        Converted,
8151                                                        TemplateArgs,
8152                                                        CanonType,
8153                                                        PrevPartial);
8154     SetNestedNameSpecifier(*this, Partial, SS);
8155     if (TemplateParameterLists.size() > 1 && SS.isSet()) {
8156       Partial->setTemplateParameterListsInfo(
8157           Context, TemplateParameterLists.drop_back(1));
8158     }
8159
8160     if (!PrevPartial)
8161       ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
8162     Specialization = Partial;
8163
8164     // If we are providing an explicit specialization of a member class
8165     // template specialization, make a note of that.
8166     if (PrevPartial && PrevPartial->getInstantiatedFromMember())
8167       PrevPartial->setMemberSpecialization();
8168
8169     CheckTemplatePartialSpecialization(Partial);
8170   } else {
8171     // Create a new class template specialization declaration node for
8172     // this explicit specialization or friend declaration.
8173     Specialization
8174       = ClassTemplateSpecializationDecl::Create(Context, Kind,
8175                                              ClassTemplate->getDeclContext(),
8176                                                 KWLoc, TemplateNameLoc,
8177                                                 ClassTemplate,
8178                                                 Converted,
8179                                                 PrevDecl);
8180     SetNestedNameSpecifier(*this, Specialization, SS);
8181     if (TemplateParameterLists.size() > 0) {
8182       Specialization->setTemplateParameterListsInfo(Context,
8183                                                     TemplateParameterLists);
8184     }
8185
8186     if (!PrevDecl)
8187       ClassTemplate->AddSpecialization(Specialization, InsertPos);
8188
8189     if (CurContext->isDependentContext()) {
8190       TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8191       CanonType = Context.getTemplateSpecializationType(
8192           CanonTemplate, Converted);
8193     } else {
8194       CanonType = Context.getTypeDeclType(Specialization);
8195     }
8196   }
8197
8198   // C++ [temp.expl.spec]p6:
8199   //   If a template, a member template or the member of a class template is
8200   //   explicitly specialized then that specialization shall be declared
8201   //   before the first use of that specialization that would cause an implicit
8202   //   instantiation to take place, in every translation unit in which such a
8203   //   use occurs; no diagnostic is required.
8204   if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
8205     bool Okay = false;
8206     for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8207       // Is there any previous explicit specialization declaration?
8208       if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
8209         Okay = true;
8210         break;
8211       }
8212     }
8213
8214     if (!Okay) {
8215       SourceRange Range(TemplateNameLoc, RAngleLoc);
8216       Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
8217         << Context.getTypeDeclType(Specialization) << Range;
8218
8219       Diag(PrevDecl->getPointOfInstantiation(),
8220            diag::note_instantiation_required_here)
8221         << (PrevDecl->getTemplateSpecializationKind()
8222                                                 != TSK_ImplicitInstantiation);
8223       return true;
8224     }
8225   }
8226
8227   // If this is not a friend, note that this is an explicit specialization.
8228   if (TUK != TUK_Friend)
8229     Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
8230
8231   // Check that this isn't a redefinition of this specialization.
8232   if (TUK == TUK_Definition) {
8233     RecordDecl *Def = Specialization->getDefinition();
8234     NamedDecl *Hidden = nullptr;
8235     if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
8236       SkipBody->ShouldSkip = true;
8237       SkipBody->Previous = Def;
8238       makeMergedDefinitionVisible(Hidden);
8239     } else if (Def) {
8240       SourceRange Range(TemplateNameLoc, RAngleLoc);
8241       Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
8242       Diag(Def->getLocation(), diag::note_previous_definition);
8243       Specialization->setInvalidDecl();
8244       return true;
8245     }
8246   }
8247
8248   ProcessDeclAttributeList(S, Specialization, Attr);
8249
8250   // Add alignment attributes if necessary; these attributes are checked when
8251   // the ASTContext lays out the structure.
8252   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
8253     AddAlignmentAttributesForRecord(Specialization);
8254     AddMsStructLayoutForRecord(Specialization);
8255   }
8256
8257   if (ModulePrivateLoc.isValid())
8258     Diag(Specialization->getLocation(), diag::err_module_private_specialization)
8259       << (isPartialSpecialization? 1 : 0)
8260       << FixItHint::CreateRemoval(ModulePrivateLoc);
8261
8262   // Build the fully-sugared type for this class template
8263   // specialization as the user wrote in the specialization
8264   // itself. This means that we'll pretty-print the type retrieved
8265   // from the specialization's declaration the way that the user
8266   // actually wrote the specialization, rather than formatting the
8267   // name based on the "canonical" representation used to store the
8268   // template arguments in the specialization.
8269   TypeSourceInfo *WrittenTy
8270     = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8271                                                 TemplateArgs, CanonType);
8272   if (TUK != TUK_Friend) {
8273     Specialization->setTypeAsWritten(WrittenTy);
8274     Specialization->setTemplateKeywordLoc(TemplateKWLoc);
8275   }
8276
8277   // C++ [temp.expl.spec]p9:
8278   //   A template explicit specialization is in the scope of the
8279   //   namespace in which the template was defined.
8280   //
8281   // We actually implement this paragraph where we set the semantic
8282   // context (in the creation of the ClassTemplateSpecializationDecl),
8283   // but we also maintain the lexical context where the actual
8284   // definition occurs.
8285   Specialization->setLexicalDeclContext(CurContext);
8286
8287   // We may be starting the definition of this specialization.
8288   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
8289     Specialization->startDefinition();
8290
8291   if (TUK == TUK_Friend) {
8292     FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
8293                                             TemplateNameLoc,
8294                                             WrittenTy,
8295                                             /*FIXME:*/KWLoc);
8296     Friend->setAccess(AS_public);
8297     CurContext->addDecl(Friend);
8298   } else {
8299     // Add the specialization into its lexical context, so that it can
8300     // be seen when iterating through the list of declarations in that
8301     // context. However, specializations are not found by name lookup.
8302     CurContext->addDecl(Specialization);
8303   }
8304
8305   if (SkipBody && SkipBody->ShouldSkip)
8306     return SkipBody->Previous;
8307
8308   return Specialization;
8309 }
8310
8311 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
8312                               MultiTemplateParamsArg TemplateParameterLists,
8313                                     Declarator &D) {
8314   Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
8315   ActOnDocumentableDecl(NewDecl);
8316   return NewDecl;
8317 }
8318
8319 Decl *Sema::ActOnConceptDefinition(Scope *S,
8320                               MultiTemplateParamsArg TemplateParameterLists,
8321                                    IdentifierInfo *Name, SourceLocation NameLoc,
8322                                    Expr *ConstraintExpr) {
8323   DeclContext *DC = CurContext;
8324
8325   if (!DC->getRedeclContext()->isFileContext()) {
8326     Diag(NameLoc,
8327       diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
8328     return nullptr;
8329   }
8330
8331   if (TemplateParameterLists.size() > 1) {
8332     Diag(NameLoc, diag::err_concept_extra_headers);
8333     return nullptr;
8334   }
8335
8336   if (TemplateParameterLists.front()->size() == 0) {
8337     Diag(NameLoc, diag::err_concept_no_parameters);
8338     return nullptr;
8339   }
8340
8341   ConceptDecl *NewDecl = ConceptDecl::Create(Context, DC, NameLoc, Name,
8342                                              TemplateParameterLists.front(),
8343                                              ConstraintExpr);
8344                                              
8345   if (NewDecl->hasAssociatedConstraints()) {
8346     // C++2a [temp.concept]p4:
8347     // A concept shall not have associated constraints.
8348     Diag(NameLoc, diag::err_concept_no_associated_constraints);
8349     NewDecl->setInvalidDecl();
8350   }
8351
8352   // Check for conflicting previous declaration.
8353   DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NameLoc);
8354   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8355                         ForVisibleRedeclaration);
8356   LookupName(Previous, S);
8357
8358   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage=*/false,
8359                        /*AllowInlineNamespace*/false);
8360   if (!Previous.empty()) {
8361     auto *Old = Previous.getRepresentativeDecl();
8362     Diag(NameLoc, isa<ConceptDecl>(Old) ? diag::err_redefinition :
8363          diag::err_redefinition_different_kind) << NewDecl->getDeclName();
8364     Diag(Old->getLocation(), diag::note_previous_definition);
8365   }
8366
8367   ActOnDocumentableDecl(NewDecl);
8368   PushOnScopeChains(NewDecl, S);
8369   return NewDecl;
8370 }
8371
8372 /// \brief Strips various properties off an implicit instantiation
8373 /// that has just been explicitly specialized.
8374 static void StripImplicitInstantiation(NamedDecl *D) {
8375   D->dropAttr<DLLImportAttr>();
8376   D->dropAttr<DLLExportAttr>();
8377
8378   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8379     FD->setInlineSpecified(false);
8380 }
8381
8382 /// Compute the diagnostic location for an explicit instantiation
8383 //  declaration or definition.
8384 static SourceLocation DiagLocForExplicitInstantiation(
8385     NamedDecl* D, SourceLocation PointOfInstantiation) {
8386   // Explicit instantiations following a specialization have no effect and
8387   // hence no PointOfInstantiation. In that case, walk decl backwards
8388   // until a valid name loc is found.
8389   SourceLocation PrevDiagLoc = PointOfInstantiation;
8390   for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
8391        Prev = Prev->getPreviousDecl()) {
8392     PrevDiagLoc = Prev->getLocation();
8393   }
8394   assert(PrevDiagLoc.isValid() &&
8395          "Explicit instantiation without point of instantiation?");
8396   return PrevDiagLoc;
8397 }
8398
8399 /// Diagnose cases where we have an explicit template specialization
8400 /// before/after an explicit template instantiation, producing diagnostics
8401 /// for those cases where they are required and determining whether the
8402 /// new specialization/instantiation will have any effect.
8403 ///
8404 /// \param NewLoc the location of the new explicit specialization or
8405 /// instantiation.
8406 ///
8407 /// \param NewTSK the kind of the new explicit specialization or instantiation.
8408 ///
8409 /// \param PrevDecl the previous declaration of the entity.
8410 ///
8411 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
8412 ///
8413 /// \param PrevPointOfInstantiation if valid, indicates where the previus
8414 /// declaration was instantiated (either implicitly or explicitly).
8415 ///
8416 /// \param HasNoEffect will be set to true to indicate that the new
8417 /// specialization or instantiation has no effect and should be ignored.
8418 ///
8419 /// \returns true if there was an error that should prevent the introduction of
8420 /// the new declaration into the AST, false otherwise.
8421 bool
8422 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
8423                                              TemplateSpecializationKind NewTSK,
8424                                              NamedDecl *PrevDecl,
8425                                              TemplateSpecializationKind PrevTSK,
8426                                         SourceLocation PrevPointOfInstantiation,
8427                                              bool &HasNoEffect) {
8428   HasNoEffect = false;
8429
8430   switch (NewTSK) {
8431   case TSK_Undeclared:
8432   case TSK_ImplicitInstantiation:
8433     assert(
8434         (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
8435         "previous declaration must be implicit!");
8436     return false;
8437
8438   case TSK_ExplicitSpecialization:
8439     switch (PrevTSK) {
8440     case TSK_Undeclared:
8441     case TSK_ExplicitSpecialization:
8442       // Okay, we're just specializing something that is either already
8443       // explicitly specialized or has merely been mentioned without any
8444       // instantiation.
8445       return false;
8446
8447     case TSK_ImplicitInstantiation:
8448       if (PrevPointOfInstantiation.isInvalid()) {
8449         // The declaration itself has not actually been instantiated, so it is
8450         // still okay to specialize it.
8451         StripImplicitInstantiation(PrevDecl);
8452         return false;
8453       }
8454       // Fall through
8455       LLVM_FALLTHROUGH;
8456
8457     case TSK_ExplicitInstantiationDeclaration:
8458     case TSK_ExplicitInstantiationDefinition:
8459       assert((PrevTSK == TSK_ImplicitInstantiation ||
8460               PrevPointOfInstantiation.isValid()) &&
8461              "Explicit instantiation without point of instantiation?");
8462
8463       // C++ [temp.expl.spec]p6:
8464       //   If a template, a member template or the member of a class template
8465       //   is explicitly specialized then that specialization shall be declared
8466       //   before the first use of that specialization that would cause an
8467       //   implicit instantiation to take place, in every translation unit in
8468       //   which such a use occurs; no diagnostic is required.
8469       for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8470         // Is there any previous explicit specialization declaration?
8471         if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
8472           return false;
8473       }
8474
8475       Diag(NewLoc, diag::err_specialization_after_instantiation)
8476         << PrevDecl;
8477       Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
8478         << (PrevTSK != TSK_ImplicitInstantiation);
8479
8480       return true;
8481     }
8482     llvm_unreachable("The switch over PrevTSK must be exhaustive.");
8483
8484   case TSK_ExplicitInstantiationDeclaration:
8485     switch (PrevTSK) {
8486     case TSK_ExplicitInstantiationDeclaration:
8487       // This explicit instantiation declaration is redundant (that's okay).
8488       HasNoEffect = true;
8489       return false;
8490
8491     case TSK_Undeclared:
8492     case TSK_ImplicitInstantiation:
8493       // We're explicitly instantiating something that may have already been
8494       // implicitly instantiated; that's fine.
8495       return false;
8496
8497     case TSK_ExplicitSpecialization:
8498       // C++0x [temp.explicit]p4:
8499       //   For a given set of template parameters, if an explicit instantiation
8500       //   of a template appears after a declaration of an explicit
8501       //   specialization for that template, the explicit instantiation has no
8502       //   effect.
8503       HasNoEffect = true;
8504       return false;
8505
8506     case TSK_ExplicitInstantiationDefinition:
8507       // C++0x [temp.explicit]p10:
8508       //   If an entity is the subject of both an explicit instantiation
8509       //   declaration and an explicit instantiation definition in the same
8510       //   translation unit, the definition shall follow the declaration.
8511       Diag(NewLoc,
8512            diag::err_explicit_instantiation_declaration_after_definition);
8513
8514       // Explicit instantiations following a specialization have no effect and
8515       // hence no PrevPointOfInstantiation. In that case, walk decl backwards
8516       // until a valid name loc is found.
8517       Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8518            diag::note_explicit_instantiation_definition_here);
8519       HasNoEffect = true;
8520       return false;
8521     }
8522     llvm_unreachable("Unexpected TemplateSpecializationKind!");
8523
8524   case TSK_ExplicitInstantiationDefinition:
8525     switch (PrevTSK) {
8526     case TSK_Undeclared:
8527     case TSK_ImplicitInstantiation:
8528       // We're explicitly instantiating something that may have already been
8529       // implicitly instantiated; that's fine.
8530       return false;
8531
8532     case TSK_ExplicitSpecialization:
8533       // C++ DR 259, C++0x [temp.explicit]p4:
8534       //   For a given set of template parameters, if an explicit
8535       //   instantiation of a template appears after a declaration of
8536       //   an explicit specialization for that template, the explicit
8537       //   instantiation has no effect.
8538       Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
8539         << PrevDecl;
8540       Diag(PrevDecl->getLocation(),
8541            diag::note_previous_template_specialization);
8542       HasNoEffect = true;
8543       return false;
8544
8545     case TSK_ExplicitInstantiationDeclaration:
8546       // We're explicitly instantiating a definition for something for which we
8547       // were previously asked to suppress instantiations. That's fine.
8548
8549       // C++0x [temp.explicit]p4:
8550       //   For a given set of template parameters, if an explicit instantiation
8551       //   of a template appears after a declaration of an explicit
8552       //   specialization for that template, the explicit instantiation has no
8553       //   effect.
8554       for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8555         // Is there any previous explicit specialization declaration?
8556         if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
8557           HasNoEffect = true;
8558           break;
8559         }
8560       }
8561
8562       return false;
8563
8564     case TSK_ExplicitInstantiationDefinition:
8565       // C++0x [temp.spec]p5:
8566       //   For a given template and a given set of template-arguments,
8567       //     - an explicit instantiation definition shall appear at most once
8568       //       in a program,
8569
8570       // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
8571       Diag(NewLoc, (getLangOpts().MSVCCompat)
8572                        ? diag::ext_explicit_instantiation_duplicate
8573                        : diag::err_explicit_instantiation_duplicate)
8574           << PrevDecl;
8575       Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8576            diag::note_previous_explicit_instantiation);
8577       HasNoEffect = true;
8578       return false;
8579     }
8580   }
8581
8582   llvm_unreachable("Missing specialization/instantiation case?");
8583 }
8584
8585 /// Perform semantic analysis for the given dependent function
8586 /// template specialization.
8587 ///
8588 /// The only possible way to get a dependent function template specialization
8589 /// is with a friend declaration, like so:
8590 ///
8591 /// \code
8592 ///   template \<class T> void foo(T);
8593 ///   template \<class T> class A {
8594 ///     friend void foo<>(T);
8595 ///   };
8596 /// \endcode
8597 ///
8598 /// There really isn't any useful analysis we can do here, so we
8599 /// just store the information.
8600 bool
8601 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
8602                    const TemplateArgumentListInfo &ExplicitTemplateArgs,
8603                                                    LookupResult &Previous) {
8604   // Remove anything from Previous that isn't a function template in
8605   // the correct context.
8606   DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
8607   LookupResult::Filter F = Previous.makeFilter();
8608   enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
8609   SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
8610   while (F.hasNext()) {
8611     NamedDecl *D = F.next()->getUnderlyingDecl();
8612     if (!isa<FunctionTemplateDecl>(D)) {
8613       F.erase();
8614       DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
8615       continue;
8616     }
8617
8618     if (!FDLookupContext->InEnclosingNamespaceSetOf(
8619             D->getDeclContext()->getRedeclContext())) {
8620       F.erase();
8621       DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
8622       continue;
8623     }
8624   }
8625   F.done();
8626
8627   if (Previous.empty()) {
8628     Diag(FD->getLocation(),
8629          diag::err_dependent_function_template_spec_no_match);
8630     for (auto &P : DiscardedCandidates)
8631       Diag(P.second->getLocation(),
8632            diag::note_dependent_function_template_spec_discard_reason)
8633           << P.first;
8634     return true;
8635   }
8636
8637   FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
8638                                          ExplicitTemplateArgs);
8639   return false;
8640 }
8641
8642 /// Perform semantic analysis for the given function template
8643 /// specialization.
8644 ///
8645 /// This routine performs all of the semantic analysis required for an
8646 /// explicit function template specialization. On successful completion,
8647 /// the function declaration \p FD will become a function template
8648 /// specialization.
8649 ///
8650 /// \param FD the function declaration, which will be updated to become a
8651 /// function template specialization.
8652 ///
8653 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
8654 /// if any. Note that this may be valid info even when 0 arguments are
8655 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
8656 /// as it anyway contains info on the angle brackets locations.
8657 ///
8658 /// \param Previous the set of declarations that may be specialized by
8659 /// this function specialization.
8660 ///
8661 /// \param QualifiedFriend whether this is a lookup for a qualified friend
8662 /// declaration with no explicit template argument list that might be
8663 /// befriending a function template specialization.
8664 bool Sema::CheckFunctionTemplateSpecialization(
8665     FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
8666     LookupResult &Previous, bool QualifiedFriend) {
8667   // The set of function template specializations that could match this
8668   // explicit function template specialization.
8669   UnresolvedSet<8> Candidates;
8670   TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
8671                                             /*ForTakingAddress=*/false);
8672
8673   llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
8674       ConvertedTemplateArgs;
8675
8676   DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
8677   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8678          I != E; ++I) {
8679     NamedDecl *Ovl = (*I)->getUnderlyingDecl();
8680     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
8681       // Only consider templates found within the same semantic lookup scope as
8682       // FD.
8683       if (!FDLookupContext->InEnclosingNamespaceSetOf(
8684                                 Ovl->getDeclContext()->getRedeclContext()))
8685         continue;
8686
8687       // When matching a constexpr member function template specialization
8688       // against the primary template, we don't yet know whether the
8689       // specialization has an implicit 'const' (because we don't know whether
8690       // it will be a static member function until we know which template it
8691       // specializes), so adjust it now assuming it specializes this template.
8692       QualType FT = FD->getType();
8693       if (FD->isConstexpr()) {
8694         CXXMethodDecl *OldMD =
8695           dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
8696         if (OldMD && OldMD->isConst()) {
8697           const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
8698           FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8699           EPI.TypeQuals.addConst();
8700           FT = Context.getFunctionType(FPT->getReturnType(),
8701                                        FPT->getParamTypes(), EPI);
8702         }
8703       }
8704
8705       TemplateArgumentListInfo Args;
8706       if (ExplicitTemplateArgs)
8707         Args = *ExplicitTemplateArgs;
8708
8709       // C++ [temp.expl.spec]p11:
8710       //   A trailing template-argument can be left unspecified in the
8711       //   template-id naming an explicit function template specialization
8712       //   provided it can be deduced from the function argument type.
8713       // Perform template argument deduction to determine whether we may be
8714       // specializing this template.
8715       // FIXME: It is somewhat wasteful to build
8716       TemplateDeductionInfo Info(FailedCandidates.getLocation());
8717       FunctionDecl *Specialization = nullptr;
8718       if (TemplateDeductionResult TDK = DeduceTemplateArguments(
8719               cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
8720               ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
8721               Info)) {
8722         // Template argument deduction failed; record why it failed, so
8723         // that we can provide nifty diagnostics.
8724         FailedCandidates.addCandidate().set(
8725             I.getPair(), FunTmpl->getTemplatedDecl(),
8726             MakeDeductionFailureInfo(Context, TDK, Info));
8727         (void)TDK;
8728         continue;
8729       }
8730
8731       // Target attributes are part of the cuda function signature, so
8732       // the deduced template's cuda target must match that of the
8733       // specialization.  Given that C++ template deduction does not
8734       // take target attributes into account, we reject candidates
8735       // here that have a different target.
8736       if (LangOpts.CUDA &&
8737           IdentifyCUDATarget(Specialization,
8738                              /* IgnoreImplicitHDAttr = */ true) !=
8739               IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
8740         FailedCandidates.addCandidate().set(
8741             I.getPair(), FunTmpl->getTemplatedDecl(),
8742             MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8743         continue;
8744       }
8745
8746       // Record this candidate.
8747       if (ExplicitTemplateArgs)
8748         ConvertedTemplateArgs[Specialization] = std::move(Args);
8749       Candidates.addDecl(Specialization, I.getAccess());
8750     }
8751   }
8752
8753   // For a qualified friend declaration (with no explicit marker to indicate
8754   // that a template specialization was intended), note all (template and
8755   // non-template) candidates.
8756   if (QualifiedFriend && Candidates.empty()) {
8757     Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
8758         << FD->getDeclName() << FDLookupContext;
8759     // FIXME: We should form a single candidate list and diagnose all
8760     // candidates at once, to get proper sorting and limiting.
8761     for (auto *OldND : Previous) {
8762       if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
8763         NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
8764     }
8765     FailedCandidates.NoteCandidates(*this, FD->getLocation());
8766     return true;
8767   }
8768
8769   // Find the most specialized function template.
8770   UnresolvedSetIterator Result = getMostSpecialized(
8771       Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
8772       PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
8773       PDiag(diag::err_function_template_spec_ambiguous)
8774           << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
8775       PDiag(diag::note_function_template_spec_matched));
8776
8777   if (Result == Candidates.end())
8778     return true;
8779
8780   // Ignore access information;  it doesn't figure into redeclaration checking.
8781   FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
8782
8783   FunctionTemplateSpecializationInfo *SpecInfo
8784     = Specialization->getTemplateSpecializationInfo();
8785   assert(SpecInfo && "Function template specialization info missing?");
8786
8787   // Note: do not overwrite location info if previous template
8788   // specialization kind was explicit.
8789   TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
8790   if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
8791     Specialization->setLocation(FD->getLocation());
8792     Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
8793     // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
8794     // function can differ from the template declaration with respect to
8795     // the constexpr specifier.
8796     // FIXME: We need an update record for this AST mutation.
8797     // FIXME: What if there are multiple such prior declarations (for instance,
8798     // from different modules)?
8799     Specialization->setConstexprKind(FD->getConstexprKind());
8800   }
8801
8802   // FIXME: Check if the prior specialization has a point of instantiation.
8803   // If so, we have run afoul of .
8804
8805   // If this is a friend declaration, then we're not really declaring
8806   // an explicit specialization.
8807   bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
8808
8809   // Check the scope of this explicit specialization.
8810   if (!isFriend &&
8811       CheckTemplateSpecializationScope(*this,
8812                                        Specialization->getPrimaryTemplate(),
8813                                        Specialization, FD->getLocation(),
8814                                        false))
8815     return true;
8816
8817   // C++ [temp.expl.spec]p6:
8818   //   If a template, a member template or the member of a class template is
8819   //   explicitly specialized then that specialization shall be declared
8820   //   before the first use of that specialization that would cause an implicit
8821   //   instantiation to take place, in every translation unit in which such a
8822   //   use occurs; no diagnostic is required.
8823   bool HasNoEffect = false;
8824   if (!isFriend &&
8825       CheckSpecializationInstantiationRedecl(FD->getLocation(),
8826                                              TSK_ExplicitSpecialization,
8827                                              Specialization,
8828                                    SpecInfo->getTemplateSpecializationKind(),
8829                                          SpecInfo->getPointOfInstantiation(),
8830                                              HasNoEffect))
8831     return true;
8832
8833   // Mark the prior declaration as an explicit specialization, so that later
8834   // clients know that this is an explicit specialization.
8835   if (!isFriend) {
8836     // Since explicit specializations do not inherit '=delete' from their
8837     // primary function template - check if the 'specialization' that was
8838     // implicitly generated (during template argument deduction for partial
8839     // ordering) from the most specialized of all the function templates that
8840     // 'FD' could have been specializing, has a 'deleted' definition.  If so,
8841     // first check that it was implicitly generated during template argument
8842     // deduction by making sure it wasn't referenced, and then reset the deleted
8843     // flag to not-deleted, so that we can inherit that information from 'FD'.
8844     if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
8845         !Specialization->getCanonicalDecl()->isReferenced()) {
8846       // FIXME: This assert will not hold in the presence of modules.
8847       assert(
8848           Specialization->getCanonicalDecl() == Specialization &&
8849           "This must be the only existing declaration of this specialization");
8850       // FIXME: We need an update record for this AST mutation.
8851       Specialization->setDeletedAsWritten(false);
8852     }
8853     // FIXME: We need an update record for this AST mutation.
8854     SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8855     MarkUnusedFileScopedDecl(Specialization);
8856   }
8857
8858   // Turn the given function declaration into a function template
8859   // specialization, with the template arguments from the previous
8860   // specialization.
8861   // Take copies of (semantic and syntactic) template argument lists.
8862   const TemplateArgumentList* TemplArgs = new (Context)
8863     TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
8864   FD->setFunctionTemplateSpecialization(
8865       Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
8866       SpecInfo->getTemplateSpecializationKind(),
8867       ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
8868
8869   // A function template specialization inherits the target attributes
8870   // of its template.  (We require the attributes explicitly in the
8871   // code to match, but a template may have implicit attributes by
8872   // virtue e.g. of being constexpr, and it passes these implicit
8873   // attributes on to its specializations.)
8874   if (LangOpts.CUDA)
8875     inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
8876
8877   // The "previous declaration" for this function template specialization is
8878   // the prior function template specialization.
8879   Previous.clear();
8880   Previous.addDecl(Specialization);
8881   return false;
8882 }
8883
8884 /// Perform semantic analysis for the given non-template member
8885 /// specialization.
8886 ///
8887 /// This routine performs all of the semantic analysis required for an
8888 /// explicit member function specialization. On successful completion,
8889 /// the function declaration \p FD will become a member function
8890 /// specialization.
8891 ///
8892 /// \param Member the member declaration, which will be updated to become a
8893 /// specialization.
8894 ///
8895 /// \param Previous the set of declarations, one of which may be specialized
8896 /// by this function specialization;  the set will be modified to contain the
8897 /// redeclared member.
8898 bool
8899 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
8900   assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
8901
8902   // Try to find the member we are instantiating.
8903   NamedDecl *FoundInstantiation = nullptr;
8904   NamedDecl *Instantiation = nullptr;
8905   NamedDecl *InstantiatedFrom = nullptr;
8906   MemberSpecializationInfo *MSInfo = nullptr;
8907
8908   if (Previous.empty()) {
8909     // Nowhere to look anyway.
8910   } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
8911     for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8912            I != E; ++I) {
8913       NamedDecl *D = (*I)->getUnderlyingDecl();
8914       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
8915         QualType Adjusted = Function->getType();
8916         if (!hasExplicitCallingConv(Adjusted))
8917           Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
8918         // This doesn't handle deduced return types, but both function
8919         // declarations should be undeduced at this point.
8920         if (Context.hasSameType(Adjusted, Method->getType())) {
8921           FoundInstantiation = *I;
8922           Instantiation = Method;
8923           InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
8924           MSInfo = Method->getMemberSpecializationInfo();
8925           break;
8926         }
8927       }
8928     }
8929   } else if (isa<VarDecl>(Member)) {
8930     VarDecl *PrevVar;
8931     if (Previous.isSingleResult() &&
8932         (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
8933       if (PrevVar->isStaticDataMember()) {
8934         FoundInstantiation = Previous.getRepresentativeDecl();
8935         Instantiation = PrevVar;
8936         InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
8937         MSInfo = PrevVar->getMemberSpecializationInfo();
8938       }
8939   } else if (isa<RecordDecl>(Member)) {
8940     CXXRecordDecl *PrevRecord;
8941     if (Previous.isSingleResult() &&
8942         (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
8943       FoundInstantiation = Previous.getRepresentativeDecl();
8944       Instantiation = PrevRecord;
8945       InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
8946       MSInfo = PrevRecord->getMemberSpecializationInfo();
8947     }
8948   } else if (isa<EnumDecl>(Member)) {
8949     EnumDecl *PrevEnum;
8950     if (Previous.isSingleResult() &&
8951         (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
8952       FoundInstantiation = Previous.getRepresentativeDecl();
8953       Instantiation = PrevEnum;
8954       InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
8955       MSInfo = PrevEnum->getMemberSpecializationInfo();
8956     }
8957   }
8958
8959   if (!Instantiation) {
8960     // There is no previous declaration that matches. Since member
8961     // specializations are always out-of-line, the caller will complain about
8962     // this mismatch later.
8963     return false;
8964   }
8965
8966   // A member specialization in a friend declaration isn't really declaring
8967   // an explicit specialization, just identifying a specific (possibly implicit)
8968   // specialization. Don't change the template specialization kind.
8969   //
8970   // FIXME: Is this really valid? Other compilers reject.
8971   if (Member->getFriendObjectKind() != Decl::FOK_None) {
8972     // Preserve instantiation information.
8973     if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
8974       cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
8975                                       cast<CXXMethodDecl>(InstantiatedFrom),
8976         cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
8977     } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
8978       cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8979                                       cast<CXXRecordDecl>(InstantiatedFrom),
8980         cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
8981     }
8982
8983     Previous.clear();
8984     Previous.addDecl(FoundInstantiation);
8985     return false;
8986   }
8987
8988   // Make sure that this is a specialization of a member.
8989   if (!InstantiatedFrom) {
8990     Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8991       << Member;
8992     Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8993     return true;
8994   }
8995
8996   // C++ [temp.expl.spec]p6:
8997   //   If a template, a member template or the member of a class template is
8998   //   explicitly specialized then that specialization shall be declared
8999   //   before the first use of that specialization that would cause an implicit
9000   //   instantiation to take place, in every translation unit in which such a
9001   //   use occurs; no diagnostic is required.
9002   assert(MSInfo && "Member specialization info missing?");
9003
9004   bool HasNoEffect = false;
9005   if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
9006                                              TSK_ExplicitSpecialization,
9007                                              Instantiation,
9008                                      MSInfo->getTemplateSpecializationKind(),
9009                                            MSInfo->getPointOfInstantiation(),
9010                                              HasNoEffect))
9011     return true;
9012
9013   // Check the scope of this explicit specialization.
9014   if (CheckTemplateSpecializationScope(*this,
9015                                        InstantiatedFrom,
9016                                        Instantiation, Member->getLocation(),
9017                                        false))
9018     return true;
9019
9020   // Note that this member specialization is an "instantiation of" the
9021   // corresponding member of the original template.
9022   if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
9023     FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
9024     if (InstantiationFunction->getTemplateSpecializationKind() ==
9025           TSK_ImplicitInstantiation) {
9026       // Explicit specializations of member functions of class templates do not
9027       // inherit '=delete' from the member function they are specializing.
9028       if (InstantiationFunction->isDeleted()) {
9029         // FIXME: This assert will not hold in the presence of modules.
9030         assert(InstantiationFunction->getCanonicalDecl() ==
9031                InstantiationFunction);
9032         // FIXME: We need an update record for this AST mutation.
9033         InstantiationFunction->setDeletedAsWritten(false);
9034       }
9035     }
9036
9037     MemberFunction->setInstantiationOfMemberFunction(
9038         cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9039   } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
9040     MemberVar->setInstantiationOfStaticDataMember(
9041         cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9042   } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
9043     MemberClass->setInstantiationOfMemberClass(
9044         cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9045   } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
9046     MemberEnum->setInstantiationOfMemberEnum(
9047         cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9048   } else {
9049     llvm_unreachable("unknown member specialization kind");
9050   }
9051
9052   // Save the caller the trouble of having to figure out which declaration
9053   // this specialization matches.
9054   Previous.clear();
9055   Previous.addDecl(FoundInstantiation);
9056   return false;
9057 }
9058
9059 /// Complete the explicit specialization of a member of a class template by
9060 /// updating the instantiated member to be marked as an explicit specialization.
9061 ///
9062 /// \param OrigD The member declaration instantiated from the template.
9063 /// \param Loc The location of the explicit specialization of the member.
9064 template<typename DeclT>
9065 static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
9066                                              SourceLocation Loc) {
9067   if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
9068     return;
9069
9070   // FIXME: Inform AST mutation listeners of this AST mutation.
9071   // FIXME: If there are multiple in-class declarations of the member (from
9072   // multiple modules, or a declaration and later definition of a member type),
9073   // should we update all of them?
9074   OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9075   OrigD->setLocation(Loc);
9076 }
9077
9078 void Sema::CompleteMemberSpecialization(NamedDecl *Member,
9079                                         LookupResult &Previous) {
9080   NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
9081   if (Instantiation == Member)
9082     return;
9083
9084   if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
9085     completeMemberSpecializationImpl(*this, Function, Member->getLocation());
9086   else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
9087     completeMemberSpecializationImpl(*this, Var, Member->getLocation());
9088   else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
9089     completeMemberSpecializationImpl(*this, Record, Member->getLocation());
9090   else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
9091     completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
9092   else
9093     llvm_unreachable("unknown member specialization kind");
9094 }
9095
9096 /// Check the scope of an explicit instantiation.
9097 ///
9098 /// \returns true if a serious error occurs, false otherwise.
9099 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
9100                                             SourceLocation InstLoc,
9101                                             bool WasQualifiedName) {
9102   DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
9103   DeclContext *CurContext = S.CurContext->getRedeclContext();
9104
9105   if (CurContext->isRecord()) {
9106     S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
9107       << D;
9108     return true;
9109   }
9110
9111   // C++11 [temp.explicit]p3:
9112   //   An explicit instantiation shall appear in an enclosing namespace of its
9113   //   template. If the name declared in the explicit instantiation is an
9114   //   unqualified name, the explicit instantiation shall appear in the
9115   //   namespace where its template is declared or, if that namespace is inline
9116   //   (7.3.1), any namespace from its enclosing namespace set.
9117   //
9118   // This is DR275, which we do not retroactively apply to C++98/03.
9119   if (WasQualifiedName) {
9120     if (CurContext->Encloses(OrigContext))
9121       return false;
9122   } else {
9123     if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
9124       return false;
9125   }
9126
9127   if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
9128     if (WasQualifiedName)
9129       S.Diag(InstLoc,
9130              S.getLangOpts().CPlusPlus11?
9131                diag::err_explicit_instantiation_out_of_scope :
9132                diag::warn_explicit_instantiation_out_of_scope_0x)
9133         << D << NS;
9134     else
9135       S.Diag(InstLoc,
9136              S.getLangOpts().CPlusPlus11?
9137                diag::err_explicit_instantiation_unqualified_wrong_namespace :
9138                diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
9139         << D << NS;
9140   } else
9141     S.Diag(InstLoc,
9142            S.getLangOpts().CPlusPlus11?
9143              diag::err_explicit_instantiation_must_be_global :
9144              diag::warn_explicit_instantiation_must_be_global_0x)
9145       << D;
9146   S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
9147   return false;
9148 }
9149
9150 /// Common checks for whether an explicit instantiation of \p D is valid.
9151 static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
9152                                        SourceLocation InstLoc,
9153                                        bool WasQualifiedName,
9154                                        TemplateSpecializationKind TSK) {
9155   // C++ [temp.explicit]p13:
9156   //   An explicit instantiation declaration shall not name a specialization of
9157   //   a template with internal linkage.
9158   if (TSK == TSK_ExplicitInstantiationDeclaration &&
9159       D->getFormalLinkage() == InternalLinkage) {
9160     S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
9161     return true;
9162   }
9163
9164   // C++11 [temp.explicit]p3: [DR 275]
9165   //   An explicit instantiation shall appear in an enclosing namespace of its
9166   //   template.
9167   if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
9168     return true;
9169
9170   return false;
9171 }
9172
9173 /// Determine whether the given scope specifier has a template-id in it.
9174 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
9175   if (!SS.isSet())
9176     return false;
9177
9178   // C++11 [temp.explicit]p3:
9179   //   If the explicit instantiation is for a member function, a member class
9180   //   or a static data member of a class template specialization, the name of
9181   //   the class template specialization in the qualified-id for the member
9182   //   name shall be a simple-template-id.
9183   //
9184   // C++98 has the same restriction, just worded differently.
9185   for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
9186        NNS = NNS->getPrefix())
9187     if (const Type *T = NNS->getAsType())
9188       if (isa<TemplateSpecializationType>(T))
9189         return true;
9190
9191   return false;
9192 }
9193
9194 /// Make a dllexport or dllimport attr on a class template specialization take
9195 /// effect.
9196 static void dllExportImportClassTemplateSpecialization(
9197     Sema &S, ClassTemplateSpecializationDecl *Def) {
9198   auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
9199   assert(A && "dllExportImportClassTemplateSpecialization called "
9200               "on Def without dllexport or dllimport");
9201
9202   // We reject explicit instantiations in class scope, so there should
9203   // never be any delayed exported classes to worry about.
9204   assert(S.DelayedDllExportClasses.empty() &&
9205          "delayed exports present at explicit instantiation");
9206   S.checkClassLevelDLLAttribute(Def);
9207
9208   // Propagate attribute to base class templates.
9209   for (auto &B : Def->bases()) {
9210     if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
9211             B.getType()->getAsCXXRecordDecl()))
9212       S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc());
9213   }
9214
9215   S.referenceDLLExportedClassMethods();
9216 }
9217
9218 // Explicit instantiation of a class template specialization
9219 DeclResult Sema::ActOnExplicitInstantiation(
9220     Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
9221     unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
9222     TemplateTy TemplateD, SourceLocation TemplateNameLoc,
9223     SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
9224     SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
9225   // Find the class template we're specializing
9226   TemplateName Name = TemplateD.get();
9227   TemplateDecl *TD = Name.getAsTemplateDecl();
9228   // Check that the specialization uses the same tag kind as the
9229   // original template.
9230   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9231   assert(Kind != TTK_Enum &&
9232          "Invalid enum tag in class template explicit instantiation!");
9233
9234   ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
9235
9236   if (!ClassTemplate) {
9237     NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
9238     Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
9239     Diag(TD->getLocation(), diag::note_previous_use);
9240     return true;
9241   }
9242
9243   if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
9244                                     Kind, /*isDefinition*/false, KWLoc,
9245                                     ClassTemplate->getIdentifier())) {
9246     Diag(KWLoc, diag::err_use_with_wrong_tag)
9247       << ClassTemplate
9248       << FixItHint::CreateReplacement(KWLoc,
9249                             ClassTemplate->getTemplatedDecl()->getKindName());
9250     Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
9251          diag::note_previous_use);
9252     Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
9253   }
9254
9255   // C++0x [temp.explicit]p2:
9256   //   There are two forms of explicit instantiation: an explicit instantiation
9257   //   definition and an explicit instantiation declaration. An explicit
9258   //   instantiation declaration begins with the extern keyword. [...]
9259   TemplateSpecializationKind TSK = ExternLoc.isInvalid()
9260                                        ? TSK_ExplicitInstantiationDefinition
9261                                        : TSK_ExplicitInstantiationDeclaration;
9262
9263   if (TSK == TSK_ExplicitInstantiationDeclaration &&
9264       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9265     // Check for dllexport class template instantiation declarations,
9266     // except for MinGW mode.
9267     for (const ParsedAttr &AL : Attr) {
9268       if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9269         Diag(ExternLoc,
9270              diag::warn_attribute_dllexport_explicit_instantiation_decl);
9271         Diag(AL.getLoc(), diag::note_attribute);
9272         break;
9273       }
9274     }
9275
9276     if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
9277       Diag(ExternLoc,
9278            diag::warn_attribute_dllexport_explicit_instantiation_decl);
9279       Diag(A->getLocation(), diag::note_attribute);
9280     }
9281   }
9282
9283   // In MSVC mode, dllimported explicit instantiation definitions are treated as
9284   // instantiation declarations for most purposes.
9285   bool DLLImportExplicitInstantiationDef = false;
9286   if (TSK == TSK_ExplicitInstantiationDefinition &&
9287       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9288     // Check for dllimport class template instantiation definitions.
9289     bool DLLImport =
9290         ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
9291     for (const ParsedAttr &AL : Attr) {
9292       if (AL.getKind() == ParsedAttr::AT_DLLImport)
9293         DLLImport = true;
9294       if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9295         // dllexport trumps dllimport here.
9296         DLLImport = false;
9297         break;
9298       }
9299     }
9300     if (DLLImport) {
9301       TSK = TSK_ExplicitInstantiationDeclaration;
9302       DLLImportExplicitInstantiationDef = true;
9303     }
9304   }
9305
9306   // Translate the parser's template argument list in our AST format.
9307   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9308   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9309
9310   // Check that the template argument list is well-formed for this
9311   // template.
9312   SmallVector<TemplateArgument, 4> Converted;
9313   if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
9314                                 TemplateArgs, false, Converted,
9315                                 /*UpdateArgsWithConversion=*/true))
9316     return true;
9317
9318   // Find the class template specialization declaration that
9319   // corresponds to these arguments.
9320   void *InsertPos = nullptr;
9321   ClassTemplateSpecializationDecl *PrevDecl
9322     = ClassTemplate->findSpecialization(Converted, InsertPos);
9323
9324   TemplateSpecializationKind PrevDecl_TSK
9325     = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
9326
9327   if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
9328       Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9329     // Check for dllexport class template instantiation definitions in MinGW
9330     // mode, if a previous declaration of the instantiation was seen.
9331     for (const ParsedAttr &AL : Attr) {
9332       if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9333         Diag(AL.getLoc(),
9334              diag::warn_attribute_dllexport_explicit_instantiation_def);
9335         break;
9336       }
9337     }
9338   }
9339
9340   if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
9341                                  SS.isSet(), TSK))
9342     return true;
9343
9344   ClassTemplateSpecializationDecl *Specialization = nullptr;
9345
9346   bool HasNoEffect = false;
9347   if (PrevDecl) {
9348     if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
9349                                                PrevDecl, PrevDecl_TSK,
9350                                             PrevDecl->getPointOfInstantiation(),
9351                                                HasNoEffect))
9352       return PrevDecl;
9353
9354     // Even though HasNoEffect == true means that this explicit instantiation
9355     // has no effect on semantics, we go on to put its syntax in the AST.
9356
9357     if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
9358         PrevDecl_TSK == TSK_Undeclared) {
9359       // Since the only prior class template specialization with these
9360       // arguments was referenced but not declared, reuse that
9361       // declaration node as our own, updating the source location
9362       // for the template name to reflect our new declaration.
9363       // (Other source locations will be updated later.)
9364       Specialization = PrevDecl;
9365       Specialization->setLocation(TemplateNameLoc);
9366       PrevDecl = nullptr;
9367     }
9368
9369     if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9370         DLLImportExplicitInstantiationDef) {
9371       // The new specialization might add a dllimport attribute.
9372       HasNoEffect = false;
9373     }
9374   }
9375
9376   if (!Specialization) {
9377     // Create a new class template specialization declaration node for
9378     // this explicit specialization.
9379     Specialization
9380       = ClassTemplateSpecializationDecl::Create(Context, Kind,
9381                                              ClassTemplate->getDeclContext(),
9382                                                 KWLoc, TemplateNameLoc,
9383                                                 ClassTemplate,
9384                                                 Converted,
9385                                                 PrevDecl);
9386     SetNestedNameSpecifier(*this, Specialization, SS);
9387
9388     if (!HasNoEffect && !PrevDecl) {
9389       // Insert the new specialization.
9390       ClassTemplate->AddSpecialization(Specialization, InsertPos);
9391     }
9392   }
9393
9394   // Build the fully-sugared type for this explicit instantiation as
9395   // the user wrote in the explicit instantiation itself. This means
9396   // that we'll pretty-print the type retrieved from the
9397   // specialization's declaration the way that the user actually wrote
9398   // the explicit instantiation, rather than formatting the name based
9399   // on the "canonical" representation used to store the template
9400   // arguments in the specialization.
9401   TypeSourceInfo *WrittenTy
9402     = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
9403                                                 TemplateArgs,
9404                                   Context.getTypeDeclType(Specialization));
9405   Specialization->setTypeAsWritten(WrittenTy);
9406
9407   // Set source locations for keywords.
9408   Specialization->setExternLoc(ExternLoc);
9409   Specialization->setTemplateKeywordLoc(TemplateLoc);
9410   Specialization->setBraceRange(SourceRange());
9411
9412   bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
9413   ProcessDeclAttributeList(S, Specialization, Attr);
9414
9415   // Add the explicit instantiation into its lexical context. However,
9416   // since explicit instantiations are never found by name lookup, we
9417   // just put it into the declaration context directly.
9418   Specialization->setLexicalDeclContext(CurContext);
9419   CurContext->addDecl(Specialization);
9420
9421   // Syntax is now OK, so return if it has no other effect on semantics.
9422   if (HasNoEffect) {
9423     // Set the template specialization kind.
9424     Specialization->setTemplateSpecializationKind(TSK);
9425     return Specialization;
9426   }
9427
9428   // C++ [temp.explicit]p3:
9429   //   A definition of a class template or class member template
9430   //   shall be in scope at the point of the explicit instantiation of
9431   //   the class template or class member template.
9432   //
9433   // This check comes when we actually try to perform the
9434   // instantiation.
9435   ClassTemplateSpecializationDecl *Def
9436     = cast_or_null<ClassTemplateSpecializationDecl>(
9437                                               Specialization->getDefinition());
9438   if (!Def)
9439     InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
9440   else if (TSK == TSK_ExplicitInstantiationDefinition) {
9441     MarkVTableUsed(TemplateNameLoc, Specialization, true);
9442     Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
9443   }
9444
9445   // Instantiate the members of this class template specialization.
9446   Def = cast_or_null<ClassTemplateSpecializationDecl>(
9447                                        Specialization->getDefinition());
9448   if (Def) {
9449     TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
9450     // Fix a TSK_ExplicitInstantiationDeclaration followed by a
9451     // TSK_ExplicitInstantiationDefinition
9452     if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
9453         (TSK == TSK_ExplicitInstantiationDefinition ||
9454          DLLImportExplicitInstantiationDef)) {
9455       // FIXME: Need to notify the ASTMutationListener that we did this.
9456       Def->setTemplateSpecializationKind(TSK);
9457
9458       if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
9459           (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
9460            Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
9461         // In the MS ABI, an explicit instantiation definition can add a dll
9462         // attribute to a template with a previous instantiation declaration.
9463         // MinGW doesn't allow this.
9464         auto *A = cast<InheritableAttr>(
9465             getDLLAttr(Specialization)->clone(getASTContext()));
9466         A->setInherited(true);
9467         Def->addAttr(A);
9468         dllExportImportClassTemplateSpecialization(*this, Def);
9469       }
9470     }
9471
9472     // Fix a TSK_ImplicitInstantiation followed by a
9473     // TSK_ExplicitInstantiationDefinition
9474     bool NewlyDLLExported =
9475         !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
9476     if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
9477         (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
9478          Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
9479       // In the MS ABI, an explicit instantiation definition can add a dll
9480       // attribute to a template with a previous implicit instantiation.
9481       // MinGW doesn't allow this. We limit clang to only adding dllexport, to
9482       // avoid potentially strange codegen behavior.  For example, if we extend
9483       // this conditional to dllimport, and we have a source file calling a
9484       // method on an implicitly instantiated template class instance and then
9485       // declaring a dllimport explicit instantiation definition for the same
9486       // template class, the codegen for the method call will not respect the
9487       // dllimport, while it will with cl. The Def will already have the DLL
9488       // attribute, since the Def and Specialization will be the same in the
9489       // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
9490       // attribute to the Specialization; we just need to make it take effect.
9491       assert(Def == Specialization &&
9492              "Def and Specialization should match for implicit instantiation");
9493       dllExportImportClassTemplateSpecialization(*this, Def);
9494     }
9495
9496     // In MinGW mode, export the template instantiation if the declaration
9497     // was marked dllexport.
9498     if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9499         Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
9500         PrevDecl->hasAttr<DLLExportAttr>()) {
9501       dllExportImportClassTemplateSpecialization(*this, Def);
9502     }
9503
9504     // Set the template specialization kind. Make sure it is set before
9505     // instantiating the members which will trigger ASTConsumer callbacks.
9506     Specialization->setTemplateSpecializationKind(TSK);
9507     InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
9508   } else {
9509
9510     // Set the template specialization kind.
9511     Specialization->setTemplateSpecializationKind(TSK);
9512   }
9513
9514   return Specialization;
9515 }
9516
9517 // Explicit instantiation of a member class of a class template.
9518 DeclResult
9519 Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
9520                                  SourceLocation TemplateLoc, unsigned TagSpec,
9521                                  SourceLocation KWLoc, CXXScopeSpec &SS,
9522                                  IdentifierInfo *Name, SourceLocation NameLoc,
9523                                  const ParsedAttributesView &Attr) {
9524
9525   bool Owned = false;
9526   bool IsDependent = false;
9527   Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
9528                         KWLoc, SS, Name, NameLoc, Attr, AS_none,
9529                         /*ModulePrivateLoc=*/SourceLocation(),
9530                         MultiTemplateParamsArg(), Owned, IsDependent,
9531                         SourceLocation(), false, TypeResult(),
9532                         /*IsTypeSpecifier*/false,
9533                         /*IsTemplateParamOrArg*/false);
9534   assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
9535
9536   if (!TagD)
9537     return true;
9538
9539   TagDecl *Tag = cast<TagDecl>(TagD);
9540   assert(!Tag->isEnum() && "shouldn't see enumerations here");
9541
9542   if (Tag->isInvalidDecl())
9543     return true;
9544
9545   CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
9546   CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
9547   if (!Pattern) {
9548     Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
9549       << Context.getTypeDeclType(Record);
9550     Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
9551     return true;
9552   }
9553
9554   // C++0x [temp.explicit]p2:
9555   //   If the explicit instantiation is for a class or member class, the
9556   //   elaborated-type-specifier in the declaration shall include a
9557   //   simple-template-id.
9558   //
9559   // C++98 has the same restriction, just worded differently.
9560   if (!ScopeSpecifierHasTemplateId(SS))
9561     Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
9562       << Record << SS.getRange();
9563
9564   // C++0x [temp.explicit]p2:
9565   //   There are two forms of explicit instantiation: an explicit instantiation
9566   //   definition and an explicit instantiation declaration. An explicit
9567   //   instantiation declaration begins with the extern keyword. [...]
9568   TemplateSpecializationKind TSK
9569     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9570                            : TSK_ExplicitInstantiationDeclaration;
9571
9572   CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
9573
9574   // Verify that it is okay to explicitly instantiate here.
9575   CXXRecordDecl *PrevDecl
9576     = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
9577   if (!PrevDecl && Record->getDefinition())
9578     PrevDecl = Record;
9579   if (PrevDecl) {
9580     MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
9581     bool HasNoEffect = false;
9582     assert(MSInfo && "No member specialization information?");
9583     if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
9584                                                PrevDecl,
9585                                         MSInfo->getTemplateSpecializationKind(),
9586                                              MSInfo->getPointOfInstantiation(),
9587                                                HasNoEffect))
9588       return true;
9589     if (HasNoEffect)
9590       return TagD;
9591   }
9592
9593   CXXRecordDecl *RecordDef
9594     = cast_or_null<CXXRecordDecl>(Record->getDefinition());
9595   if (!RecordDef) {
9596     // C++ [temp.explicit]p3:
9597     //   A definition of a member class of a class template shall be in scope
9598     //   at the point of an explicit instantiation of the member class.
9599     CXXRecordDecl *Def
9600       = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
9601     if (!Def) {
9602       Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
9603         << 0 << Record->getDeclName() << Record->getDeclContext();
9604       Diag(Pattern->getLocation(), diag::note_forward_declaration)
9605         << Pattern;
9606       return true;
9607     } else {
9608       if (InstantiateClass(NameLoc, Record, Def,
9609                            getTemplateInstantiationArgs(Record),
9610                            TSK))
9611         return true;
9612
9613       RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
9614       if (!RecordDef)
9615         return true;
9616     }
9617   }
9618
9619   // Instantiate all of the members of the class.
9620   InstantiateClassMembers(NameLoc, RecordDef,
9621                           getTemplateInstantiationArgs(Record), TSK);
9622
9623   if (TSK == TSK_ExplicitInstantiationDefinition)
9624     MarkVTableUsed(NameLoc, RecordDef, true);
9625
9626   // FIXME: We don't have any representation for explicit instantiations of
9627   // member classes. Such a representation is not needed for compilation, but it
9628   // should be available for clients that want to see all of the declarations in
9629   // the source code.
9630   return TagD;
9631 }
9632
9633 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
9634                                             SourceLocation ExternLoc,
9635                                             SourceLocation TemplateLoc,
9636                                             Declarator &D) {
9637   // Explicit instantiations always require a name.
9638   // TODO: check if/when DNInfo should replace Name.
9639   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9640   DeclarationName Name = NameInfo.getName();
9641   if (!Name) {
9642     if (!D.isInvalidType())
9643       Diag(D.getDeclSpec().getBeginLoc(),
9644            diag::err_explicit_instantiation_requires_name)
9645           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
9646
9647     return true;
9648   }
9649
9650   // The scope passed in may not be a decl scope.  Zip up the scope tree until
9651   // we find one that is.
9652   while ((S->getFlags() & Scope::DeclScope) == 0 ||
9653          (S->getFlags() & Scope::TemplateParamScope) != 0)
9654     S = S->getParent();
9655
9656   // Determine the type of the declaration.
9657   TypeSourceInfo *T = GetTypeForDeclarator(D, S);
9658   QualType R = T->getType();
9659   if (R.isNull())
9660     return true;
9661
9662   // C++ [dcl.stc]p1:
9663   //   A storage-class-specifier shall not be specified in [...] an explicit
9664   //   instantiation (14.7.2) directive.
9665   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
9666     Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
9667       << Name;
9668     return true;
9669   } else if (D.getDeclSpec().getStorageClassSpec()
9670                                                 != DeclSpec::SCS_unspecified) {
9671     // Complain about then remove the storage class specifier.
9672     Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
9673       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9674
9675     D.getMutableDeclSpec().ClearStorageClassSpecs();
9676   }
9677
9678   // C++0x [temp.explicit]p1:
9679   //   [...] An explicit instantiation of a function template shall not use the
9680   //   inline or constexpr specifiers.
9681   // Presumably, this also applies to member functions of class templates as
9682   // well.
9683   if (D.getDeclSpec().isInlineSpecified())
9684     Diag(D.getDeclSpec().getInlineSpecLoc(),
9685          getLangOpts().CPlusPlus11 ?
9686            diag::err_explicit_instantiation_inline :
9687            diag::warn_explicit_instantiation_inline_0x)
9688       << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9689   if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
9690     // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
9691     // not already specified.
9692     Diag(D.getDeclSpec().getConstexprSpecLoc(),
9693          diag::err_explicit_instantiation_constexpr);
9694
9695   // A deduction guide is not on the list of entities that can be explicitly
9696   // instantiated.
9697   if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9698     Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
9699         << /*explicit instantiation*/ 0;
9700     return true;
9701   }
9702
9703   // C++0x [temp.explicit]p2:
9704   //   There are two forms of explicit instantiation: an explicit instantiation
9705   //   definition and an explicit instantiation declaration. An explicit
9706   //   instantiation declaration begins with the extern keyword. [...]
9707   TemplateSpecializationKind TSK
9708     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9709                            : TSK_ExplicitInstantiationDeclaration;
9710
9711   LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
9712   LookupParsedName(Previous, S, &D.getCXXScopeSpec());
9713
9714   if (!R->isFunctionType()) {
9715     // C++ [temp.explicit]p1:
9716     //   A [...] static data member of a class template can be explicitly
9717     //   instantiated from the member definition associated with its class
9718     //   template.
9719     // C++1y [temp.explicit]p1:
9720     //   A [...] variable [...] template specialization can be explicitly
9721     //   instantiated from its template.
9722     if (Previous.isAmbiguous())
9723       return true;
9724
9725     VarDecl *Prev = Previous.getAsSingle<VarDecl>();
9726     VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
9727
9728     if (!PrevTemplate) {
9729       if (!Prev || !Prev->isStaticDataMember()) {
9730         // We expect to see a static data member here.
9731         Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
9732             << Name;
9733         for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9734              P != PEnd; ++P)
9735           Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
9736         return true;
9737       }
9738
9739       if (!Prev->getInstantiatedFromStaticDataMember()) {
9740         // FIXME: Check for explicit specialization?
9741         Diag(D.getIdentifierLoc(),
9742              diag::err_explicit_instantiation_data_member_not_instantiated)
9743             << Prev;
9744         Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
9745         // FIXME: Can we provide a note showing where this was declared?
9746         return true;
9747       }
9748     } else {
9749       // Explicitly instantiate a variable template.
9750
9751       // C++1y [dcl.spec.auto]p6:
9752       //   ... A program that uses auto or decltype(auto) in a context not
9753       //   explicitly allowed in this section is ill-formed.
9754       //
9755       // This includes auto-typed variable template instantiations.
9756       if (R->isUndeducedType()) {
9757         Diag(T->getTypeLoc().getBeginLoc(),
9758              diag::err_auto_not_allowed_var_inst);
9759         return true;
9760       }
9761
9762       if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9763         // C++1y [temp.explicit]p3:
9764         //   If the explicit instantiation is for a variable, the unqualified-id
9765         //   in the declaration shall be a template-id.
9766         Diag(D.getIdentifierLoc(),
9767              diag::err_explicit_instantiation_without_template_id)
9768           << PrevTemplate;
9769         Diag(PrevTemplate->getLocation(),
9770              diag::note_explicit_instantiation_here);
9771         return true;
9772       }
9773
9774       // Translate the parser's template argument list into our AST format.
9775       TemplateArgumentListInfo TemplateArgs =
9776           makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
9777
9778       DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
9779                                           D.getIdentifierLoc(), TemplateArgs);
9780       if (Res.isInvalid())
9781         return true;
9782
9783       // Ignore access control bits, we don't need them for redeclaration
9784       // checking.
9785       Prev = cast<VarDecl>(Res.get());
9786     }
9787
9788     // C++0x [temp.explicit]p2:
9789     //   If the explicit instantiation is for a member function, a member class
9790     //   or a static data member of a class template specialization, the name of
9791     //   the class template specialization in the qualified-id for the member
9792     //   name shall be a simple-template-id.
9793     //
9794     // C++98 has the same restriction, just worded differently.
9795     //
9796     // This does not apply to variable template specializations, where the
9797     // template-id is in the unqualified-id instead.
9798     if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
9799       Diag(D.getIdentifierLoc(),
9800            diag::ext_explicit_instantiation_without_qualified_id)
9801         << Prev << D.getCXXScopeSpec().getRange();
9802
9803     CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
9804
9805     // Verify that it is okay to explicitly instantiate here.
9806     TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
9807     SourceLocation POI = Prev->getPointOfInstantiation();
9808     bool HasNoEffect = false;
9809     if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
9810                                                PrevTSK, POI, HasNoEffect))
9811       return true;
9812
9813     if (!HasNoEffect) {
9814       // Instantiate static data member or variable template.
9815       Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9816       // Merge attributes.
9817       ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
9818       if (TSK == TSK_ExplicitInstantiationDefinition)
9819         InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
9820     }
9821
9822     // Check the new variable specialization against the parsed input.
9823     if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
9824       Diag(T->getTypeLoc().getBeginLoc(),
9825            diag::err_invalid_var_template_spec_type)
9826           << 0 << PrevTemplate << R << Prev->getType();
9827       Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
9828           << 2 << PrevTemplate->getDeclName();
9829       return true;
9830     }
9831
9832     // FIXME: Create an ExplicitInstantiation node?
9833     return (Decl*) nullptr;
9834   }
9835
9836   // If the declarator is a template-id, translate the parser's template
9837   // argument list into our AST format.
9838   bool HasExplicitTemplateArgs = false;
9839   TemplateArgumentListInfo TemplateArgs;
9840   if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9841     TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
9842     HasExplicitTemplateArgs = true;
9843   }
9844
9845   // C++ [temp.explicit]p1:
9846   //   A [...] function [...] can be explicitly instantiated from its template.
9847   //   A member function [...] of a class template can be explicitly
9848   //  instantiated from the member definition associated with its class
9849   //  template.
9850   UnresolvedSet<8> TemplateMatches;
9851   FunctionDecl *NonTemplateMatch = nullptr;
9852   TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
9853   for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9854        P != PEnd; ++P) {
9855     NamedDecl *Prev = *P;
9856     if (!HasExplicitTemplateArgs) {
9857       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
9858         QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
9859                                                 /*AdjustExceptionSpec*/true);
9860         if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
9861           if (Method->getPrimaryTemplate()) {
9862             TemplateMatches.addDecl(Method, P.getAccess());
9863           } else {
9864             // FIXME: Can this assert ever happen?  Needs a test.
9865             assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
9866             NonTemplateMatch = Method;
9867           }
9868         }
9869       }
9870     }
9871
9872     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
9873     if (!FunTmpl)
9874       continue;
9875
9876     TemplateDeductionInfo Info(FailedCandidates.getLocation());
9877     FunctionDecl *Specialization = nullptr;
9878     if (TemplateDeductionResult TDK
9879           = DeduceTemplateArguments(FunTmpl,
9880                                (HasExplicitTemplateArgs ? &TemplateArgs
9881                                                         : nullptr),
9882                                     R, Specialization, Info)) {
9883       // Keep track of almost-matches.
9884       FailedCandidates.addCandidate()
9885           .set(P.getPair(), FunTmpl->getTemplatedDecl(),
9886                MakeDeductionFailureInfo(Context, TDK, Info));
9887       (void)TDK;
9888       continue;
9889     }
9890
9891     // Target attributes are part of the cuda function signature, so
9892     // the cuda target of the instantiated function must match that of its
9893     // template.  Given that C++ template deduction does not take
9894     // target attributes into account, we reject candidates here that
9895     // have a different target.
9896     if (LangOpts.CUDA &&
9897         IdentifyCUDATarget(Specialization,
9898                            /* IgnoreImplicitHDAttr = */ true) !=
9899             IdentifyCUDATarget(D.getDeclSpec().getAttributes())) {
9900       FailedCandidates.addCandidate().set(
9901           P.getPair(), FunTmpl->getTemplatedDecl(),
9902           MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9903       continue;
9904     }
9905
9906     TemplateMatches.addDecl(Specialization, P.getAccess());
9907   }
9908
9909   FunctionDecl *Specialization = NonTemplateMatch;
9910   if (!Specialization) {
9911     // Find the most specialized function template specialization.
9912     UnresolvedSetIterator Result = getMostSpecialized(
9913         TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
9914         D.getIdentifierLoc(),
9915         PDiag(diag::err_explicit_instantiation_not_known) << Name,
9916         PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
9917         PDiag(diag::note_explicit_instantiation_candidate));
9918
9919     if (Result == TemplateMatches.end())
9920       return true;
9921
9922     // Ignore access control bits, we don't need them for redeclaration checking.
9923     Specialization = cast<FunctionDecl>(*Result);
9924   }
9925
9926   // C++11 [except.spec]p4
9927   // In an explicit instantiation an exception-specification may be specified,
9928   // but is not required.
9929   // If an exception-specification is specified in an explicit instantiation
9930   // directive, it shall be compatible with the exception-specifications of
9931   // other declarations of that function.
9932   if (auto *FPT = R->getAs<FunctionProtoType>())
9933     if (FPT->hasExceptionSpec()) {
9934       unsigned DiagID =
9935           diag::err_mismatched_exception_spec_explicit_instantiation;
9936       if (getLangOpts().MicrosoftExt)
9937         DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
9938       bool Result = CheckEquivalentExceptionSpec(
9939           PDiag(DiagID) << Specialization->getType(),
9940           PDiag(diag::note_explicit_instantiation_here),
9941           Specialization->getType()->getAs<FunctionProtoType>(),
9942           Specialization->getLocation(), FPT, D.getBeginLoc());
9943       // In Microsoft mode, mismatching exception specifications just cause a
9944       // warning.
9945       if (!getLangOpts().MicrosoftExt && Result)
9946         return true;
9947     }
9948
9949   if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
9950     Diag(D.getIdentifierLoc(),
9951          diag::err_explicit_instantiation_member_function_not_instantiated)
9952       << Specialization
9953       << (Specialization->getTemplateSpecializationKind() ==
9954           TSK_ExplicitSpecialization);
9955     Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
9956     return true;
9957   }
9958
9959   FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
9960   if (!PrevDecl && Specialization->isThisDeclarationADefinition())
9961     PrevDecl = Specialization;
9962
9963   if (PrevDecl) {
9964     bool HasNoEffect = false;
9965     if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
9966                                                PrevDecl,
9967                                      PrevDecl->getTemplateSpecializationKind(),
9968                                           PrevDecl->getPointOfInstantiation(),
9969                                                HasNoEffect))
9970       return true;
9971
9972     // FIXME: We may still want to build some representation of this
9973     // explicit specialization.
9974     if (HasNoEffect)
9975       return (Decl*) nullptr;
9976   }
9977
9978   // HACK: libc++ has a bug where it attempts to explicitly instantiate the
9979   // functions
9980   //     valarray<size_t>::valarray(size_t) and
9981   //     valarray<size_t>::~valarray()
9982   // that it declared to have internal linkage with the internal_linkage
9983   // attribute. Ignore the explicit instantiation declaration in this case.
9984   if (Specialization->hasAttr<InternalLinkageAttr>() &&
9985       TSK == TSK_ExplicitInstantiationDeclaration) {
9986     if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
9987       if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
9988           RD->isInStdNamespace())
9989         return (Decl*) nullptr;
9990   }
9991
9992   ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
9993
9994   // In MSVC mode, dllimported explicit instantiation definitions are treated as
9995   // instantiation declarations.
9996   if (TSK == TSK_ExplicitInstantiationDefinition &&
9997       Specialization->hasAttr<DLLImportAttr>() &&
9998       Context.getTargetInfo().getCXXABI().isMicrosoft())
9999     TSK = TSK_ExplicitInstantiationDeclaration;
10000
10001   Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10002
10003   if (Specialization->isDefined()) {
10004     // Let the ASTConsumer know that this function has been explicitly
10005     // instantiated now, and its linkage might have changed.
10006     Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
10007   } else if (TSK == TSK_ExplicitInstantiationDefinition)
10008     InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
10009
10010   // C++0x [temp.explicit]p2:
10011   //   If the explicit instantiation is for a member function, a member class
10012   //   or a static data member of a class template specialization, the name of
10013   //   the class template specialization in the qualified-id for the member
10014   //   name shall be a simple-template-id.
10015   //
10016   // C++98 has the same restriction, just worded differently.
10017   FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
10018   if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
10019       D.getCXXScopeSpec().isSet() &&
10020       !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
10021     Diag(D.getIdentifierLoc(),
10022          diag::ext_explicit_instantiation_without_qualified_id)
10023     << Specialization << D.getCXXScopeSpec().getRange();
10024
10025   CheckExplicitInstantiation(
10026       *this,
10027       FunTmpl ? (NamedDecl *)FunTmpl
10028               : Specialization->getInstantiatedFromMemberFunction(),
10029       D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
10030
10031   // FIXME: Create some kind of ExplicitInstantiationDecl here.
10032   return (Decl*) nullptr;
10033 }
10034
10035 TypeResult
10036 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
10037                         const CXXScopeSpec &SS, IdentifierInfo *Name,
10038                         SourceLocation TagLoc, SourceLocation NameLoc) {
10039   // This has to hold, because SS is expected to be defined.
10040   assert(Name && "Expected a name in a dependent tag");
10041
10042   NestedNameSpecifier *NNS = SS.getScopeRep();
10043   if (!NNS)
10044     return true;
10045
10046   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10047
10048   if (TUK == TUK_Declaration || TUK == TUK_Definition) {
10049     Diag(NameLoc, diag::err_dependent_tag_decl)
10050       << (TUK == TUK_Definition) << Kind << SS.getRange();
10051     return true;
10052   }
10053
10054   // Create the resulting type.
10055   ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10056   QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
10057
10058   // Create type-source location information for this type.
10059   TypeLocBuilder TLB;
10060   DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
10061   TL.setElaboratedKeywordLoc(TagLoc);
10062   TL.setQualifierLoc(SS.getWithLocInContext(Context));
10063   TL.setNameLoc(NameLoc);
10064   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
10065 }
10066
10067 TypeResult
10068 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
10069                         const CXXScopeSpec &SS, const IdentifierInfo &II,
10070                         SourceLocation IdLoc) {
10071   if (SS.isInvalid())
10072     return true;
10073
10074   if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10075     Diag(TypenameLoc,
10076          getLangOpts().CPlusPlus11 ?
10077            diag::warn_cxx98_compat_typename_outside_of_template :
10078            diag::ext_typename_outside_of_template)
10079       << FixItHint::CreateRemoval(TypenameLoc);
10080
10081   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10082   TypeSourceInfo *TSI = nullptr;
10083   QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
10084                                  TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
10085                                  /*DeducedTSTContext=*/true);
10086   if (T.isNull())
10087     return true;
10088   return CreateParsedType(T, TSI);
10089 }
10090
10091 TypeResult
10092 Sema::ActOnTypenameType(Scope *S,
10093                         SourceLocation TypenameLoc,
10094                         const CXXScopeSpec &SS,
10095                         SourceLocation TemplateKWLoc,
10096                         TemplateTy TemplateIn,
10097                         IdentifierInfo *TemplateII,
10098                         SourceLocation TemplateIILoc,
10099                         SourceLocation LAngleLoc,
10100                         ASTTemplateArgsPtr TemplateArgsIn,
10101                         SourceLocation RAngleLoc) {
10102   if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10103     Diag(TypenameLoc,
10104          getLangOpts().CPlusPlus11 ?
10105            diag::warn_cxx98_compat_typename_outside_of_template :
10106            diag::ext_typename_outside_of_template)
10107       << FixItHint::CreateRemoval(TypenameLoc);
10108
10109   // Strangely, non-type results are not ignored by this lookup, so the
10110   // program is ill-formed if it finds an injected-class-name.
10111   if (TypenameLoc.isValid()) {
10112     auto *LookupRD =
10113         dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
10114     if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
10115       Diag(TemplateIILoc,
10116            diag::ext_out_of_line_qualified_id_type_names_constructor)
10117         << TemplateII << 0 /*injected-class-name used as template name*/
10118         << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
10119     }
10120   }
10121
10122   // Translate the parser's template argument list in our AST format.
10123   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10124   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10125
10126   TemplateName Template = TemplateIn.get();
10127   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
10128     // Construct a dependent template specialization type.
10129     assert(DTN && "dependent template has non-dependent name?");
10130     assert(DTN->getQualifier() == SS.getScopeRep());
10131     QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
10132                                                           DTN->getQualifier(),
10133                                                           DTN->getIdentifier(),
10134                                                                 TemplateArgs);
10135
10136     // Create source-location information for this type.
10137     TypeLocBuilder Builder;
10138     DependentTemplateSpecializationTypeLoc SpecTL
10139     = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
10140     SpecTL.setElaboratedKeywordLoc(TypenameLoc);
10141     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
10142     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10143     SpecTL.setTemplateNameLoc(TemplateIILoc);
10144     SpecTL.setLAngleLoc(LAngleLoc);
10145     SpecTL.setRAngleLoc(RAngleLoc);
10146     for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10147       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10148     return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
10149   }
10150
10151   QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
10152   if (T.isNull())
10153     return true;
10154
10155   // Provide source-location information for the template specialization type.
10156   TypeLocBuilder Builder;
10157   TemplateSpecializationTypeLoc SpecTL
10158     = Builder.push<TemplateSpecializationTypeLoc>(T);
10159   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10160   SpecTL.setTemplateNameLoc(TemplateIILoc);
10161   SpecTL.setLAngleLoc(LAngleLoc);
10162   SpecTL.setRAngleLoc(RAngleLoc);
10163   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10164     SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10165
10166   T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
10167   ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
10168   TL.setElaboratedKeywordLoc(TypenameLoc);
10169   TL.setQualifierLoc(SS.getWithLocInContext(Context));
10170
10171   TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
10172   return CreateParsedType(T, TSI);
10173 }
10174
10175
10176 /// Determine whether this failed name lookup should be treated as being
10177 /// disabled by a usage of std::enable_if.
10178 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
10179                        SourceRange &CondRange, Expr *&Cond) {
10180   // We must be looking for a ::type...
10181   if (!II.isStr("type"))
10182     return false;
10183
10184   // ... within an explicitly-written template specialization...
10185   if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
10186     return false;
10187   TypeLoc EnableIfTy = NNS.getTypeLoc();
10188   TemplateSpecializationTypeLoc EnableIfTSTLoc =
10189       EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
10190   if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
10191     return false;
10192   const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
10193
10194   // ... which names a complete class template declaration...
10195   const TemplateDecl *EnableIfDecl =
10196     EnableIfTST->getTemplateName().getAsTemplateDecl();
10197   if (!EnableIfDecl || EnableIfTST->isIncompleteType())
10198     return false;
10199
10200   // ... called "enable_if".
10201   const IdentifierInfo *EnableIfII =
10202     EnableIfDecl->getDeclName().getAsIdentifierInfo();
10203   if (!EnableIfII || !EnableIfII->isStr("enable_if"))
10204     return false;
10205
10206   // Assume the first template argument is the condition.
10207   CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
10208
10209   // Dig out the condition.
10210   Cond = nullptr;
10211   if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
10212         != TemplateArgument::Expression)
10213     return true;
10214
10215   Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
10216
10217   // Ignore Boolean literals; they add no value.
10218   if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
10219     Cond = nullptr;
10220
10221   return true;
10222 }
10223
10224 QualType
10225 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
10226                         SourceLocation KeywordLoc,
10227                         NestedNameSpecifierLoc QualifierLoc,
10228                         const IdentifierInfo &II,
10229                         SourceLocation IILoc,
10230                         TypeSourceInfo **TSI,
10231                         bool DeducedTSTContext) {
10232   QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
10233                                  DeducedTSTContext);
10234   if (T.isNull())
10235     return QualType();
10236
10237   *TSI = Context.CreateTypeSourceInfo(T);
10238   if (isa<DependentNameType>(T)) {
10239     DependentNameTypeLoc TL =
10240         (*TSI)->getTypeLoc().castAs<DependentNameTypeLoc>();
10241     TL.setElaboratedKeywordLoc(KeywordLoc);
10242     TL.setQualifierLoc(QualifierLoc);
10243     TL.setNameLoc(IILoc);
10244   } else {
10245     ElaboratedTypeLoc TL = (*TSI)->getTypeLoc().castAs<ElaboratedTypeLoc>();
10246     TL.setElaboratedKeywordLoc(KeywordLoc);
10247     TL.setQualifierLoc(QualifierLoc);
10248     TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IILoc);
10249   }
10250   return T;
10251 }
10252
10253 /// Build the type that describes a C++ typename specifier,
10254 /// e.g., "typename T::type".
10255 QualType
10256 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
10257                         SourceLocation KeywordLoc,
10258                         NestedNameSpecifierLoc QualifierLoc,
10259                         const IdentifierInfo &II,
10260                         SourceLocation IILoc, bool DeducedTSTContext) {
10261   CXXScopeSpec SS;
10262   SS.Adopt(QualifierLoc);
10263
10264   DeclContext *Ctx = nullptr;
10265   if (QualifierLoc) {
10266     Ctx = computeDeclContext(SS);
10267     if (!Ctx) {
10268       // If the nested-name-specifier is dependent and couldn't be
10269       // resolved to a type, build a typename type.
10270       assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
10271       return Context.getDependentNameType(Keyword,
10272                                           QualifierLoc.getNestedNameSpecifier(),
10273                                           &II);
10274     }
10275
10276     // If the nested-name-specifier refers to the current instantiation,
10277     // the "typename" keyword itself is superfluous. In C++03, the
10278     // program is actually ill-formed. However, DR 382 (in C++0x CD1)
10279     // allows such extraneous "typename" keywords, and we retroactively
10280     // apply this DR to C++03 code with only a warning. In any case we continue.
10281
10282     if (RequireCompleteDeclContext(SS, Ctx))
10283       return QualType();
10284   }
10285
10286   DeclarationName Name(&II);
10287   LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
10288   if (Ctx)
10289     LookupQualifiedName(Result, Ctx, SS);
10290   else
10291     LookupName(Result, CurScope);
10292   unsigned DiagID = 0;
10293   Decl *Referenced = nullptr;
10294   switch (Result.getResultKind()) {
10295   case LookupResult::NotFound: {
10296     // If we're looking up 'type' within a template named 'enable_if', produce
10297     // a more specific diagnostic.
10298     SourceRange CondRange;
10299     Expr *Cond = nullptr;
10300     if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
10301       // If we have a condition, narrow it down to the specific failed
10302       // condition.
10303       if (Cond) {
10304         Expr *FailedCond;
10305         std::string FailedDescription;
10306         std::tie(FailedCond, FailedDescription) =
10307           findFailedBooleanCondition(Cond);
10308
10309         Diag(FailedCond->getExprLoc(),
10310              diag::err_typename_nested_not_found_requirement)
10311           << FailedDescription
10312           << FailedCond->getSourceRange();
10313         return QualType();
10314       }
10315
10316       Diag(CondRange.getBegin(),
10317            diag::err_typename_nested_not_found_enable_if)
10318           << Ctx << CondRange;
10319       return QualType();
10320     }
10321
10322     DiagID = Ctx ? diag::err_typename_nested_not_found
10323                  : diag::err_unknown_typename;
10324     break;
10325   }
10326
10327   case LookupResult::FoundUnresolvedValue: {
10328     // We found a using declaration that is a value. Most likely, the using
10329     // declaration itself is meant to have the 'typename' keyword.
10330     SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10331                           IILoc);
10332     Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
10333       << Name << Ctx << FullRange;
10334     if (UnresolvedUsingValueDecl *Using
10335           = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
10336       SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
10337       Diag(Loc, diag::note_using_value_decl_missing_typename)
10338         << FixItHint::CreateInsertion(Loc, "typename ");
10339     }
10340   }
10341   // Fall through to create a dependent typename type, from which we can recover
10342   // better.
10343   LLVM_FALLTHROUGH;
10344
10345   case LookupResult::NotFoundInCurrentInstantiation:
10346     // Okay, it's a member of an unknown instantiation.
10347     return Context.getDependentNameType(Keyword,
10348                                         QualifierLoc.getNestedNameSpecifier(),
10349                                         &II);
10350
10351   case LookupResult::Found:
10352     if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
10353       // C++ [class.qual]p2:
10354       //   In a lookup in which function names are not ignored and the
10355       //   nested-name-specifier nominates a class C, if the name specified
10356       //   after the nested-name-specifier, when looked up in C, is the
10357       //   injected-class-name of C [...] then the name is instead considered
10358       //   to name the constructor of class C.
10359       //
10360       // Unlike in an elaborated-type-specifier, function names are not ignored
10361       // in typename-specifier lookup. However, they are ignored in all the
10362       // contexts where we form a typename type with no keyword (that is, in
10363       // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
10364       //
10365       // FIXME: That's not strictly true: mem-initializer-id lookup does not
10366       // ignore functions, but that appears to be an oversight.
10367       auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
10368       auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
10369       if (Keyword == ETK_Typename && LookupRD && FoundRD &&
10370           FoundRD->isInjectedClassName() &&
10371           declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
10372         Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
10373             << &II << 1 << 0 /*'typename' keyword used*/;
10374
10375       // We found a type. Build an ElaboratedType, since the
10376       // typename-specifier was just sugar.
10377       MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
10378       return Context.getElaboratedType(Keyword,
10379                                        QualifierLoc.getNestedNameSpecifier(),
10380                                        Context.getTypeDeclType(Type));
10381     }
10382
10383     // C++ [dcl.type.simple]p2:
10384     //   A type-specifier of the form
10385     //     typename[opt] nested-name-specifier[opt] template-name
10386     //   is a placeholder for a deduced class type [...].
10387     if (getLangOpts().CPlusPlus17) {
10388       if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
10389         if (!DeducedTSTContext) {
10390           QualType T(QualifierLoc
10391                          ? QualifierLoc.getNestedNameSpecifier()->getAsType()
10392                          : nullptr, 0);
10393           if (!T.isNull())
10394             Diag(IILoc, diag::err_dependent_deduced_tst)
10395               << (int)getTemplateNameKindForDiagnostics(TemplateName(TD)) << T;
10396           else
10397             Diag(IILoc, diag::err_deduced_tst)
10398               << (int)getTemplateNameKindForDiagnostics(TemplateName(TD));
10399           Diag(TD->getLocation(), diag::note_template_decl_here);
10400           return QualType();
10401         }
10402         return Context.getElaboratedType(
10403             Keyword, QualifierLoc.getNestedNameSpecifier(),
10404             Context.getDeducedTemplateSpecializationType(TemplateName(TD),
10405                                                          QualType(), false));
10406       }
10407     }
10408
10409     DiagID = Ctx ? diag::err_typename_nested_not_type
10410                  : diag::err_typename_not_type;
10411     Referenced = Result.getFoundDecl();
10412     break;
10413
10414   case LookupResult::FoundOverloaded:
10415     DiagID = Ctx ? diag::err_typename_nested_not_type
10416                  : diag::err_typename_not_type;
10417     Referenced = *Result.begin();
10418     break;
10419
10420   case LookupResult::Ambiguous:
10421     return QualType();
10422   }
10423
10424   // If we get here, it's because name lookup did not find a
10425   // type. Emit an appropriate diagnostic and return an error.
10426   SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10427                         IILoc);
10428   if (Ctx)
10429     Diag(IILoc, DiagID) << FullRange << Name << Ctx;
10430   else
10431     Diag(IILoc, DiagID) << FullRange << Name;
10432   if (Referenced)
10433     Diag(Referenced->getLocation(),
10434          Ctx ? diag::note_typename_member_refers_here
10435              : diag::note_typename_refers_here)
10436       << Name;
10437   return QualType();
10438 }
10439
10440 namespace {
10441   // See Sema::RebuildTypeInCurrentInstantiation
10442   class CurrentInstantiationRebuilder
10443     : public TreeTransform<CurrentInstantiationRebuilder> {
10444     SourceLocation Loc;
10445     DeclarationName Entity;
10446
10447   public:
10448     typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
10449
10450     CurrentInstantiationRebuilder(Sema &SemaRef,
10451                                   SourceLocation Loc,
10452                                   DeclarationName Entity)
10453     : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
10454       Loc(Loc), Entity(Entity) { }
10455
10456     /// Determine whether the given type \p T has already been
10457     /// transformed.
10458     ///
10459     /// For the purposes of type reconstruction, a type has already been
10460     /// transformed if it is NULL or if it is not dependent.
10461     bool AlreadyTransformed(QualType T) {
10462       return T.isNull() || !T->isDependentType();
10463     }
10464
10465     /// Returns the location of the entity whose type is being
10466     /// rebuilt.
10467     SourceLocation getBaseLocation() { return Loc; }
10468
10469     /// Returns the name of the entity whose type is being rebuilt.
10470     DeclarationName getBaseEntity() { return Entity; }
10471
10472     /// Sets the "base" location and entity when that
10473     /// information is known based on another transformation.
10474     void setBase(SourceLocation Loc, DeclarationName Entity) {
10475       this->Loc = Loc;
10476       this->Entity = Entity;
10477     }
10478
10479     ExprResult TransformLambdaExpr(LambdaExpr *E) {
10480       // Lambdas never need to be transformed.
10481       return E;
10482     }
10483   };
10484 } // end anonymous namespace
10485
10486 /// Rebuilds a type within the context of the current instantiation.
10487 ///
10488 /// The type \p T is part of the type of an out-of-line member definition of
10489 /// a class template (or class template partial specialization) that was parsed
10490 /// and constructed before we entered the scope of the class template (or
10491 /// partial specialization thereof). This routine will rebuild that type now
10492 /// that we have entered the declarator's scope, which may produce different
10493 /// canonical types, e.g.,
10494 ///
10495 /// \code
10496 /// template<typename T>
10497 /// struct X {
10498 ///   typedef T* pointer;
10499 ///   pointer data();
10500 /// };
10501 ///
10502 /// template<typename T>
10503 /// typename X<T>::pointer X<T>::data() { ... }
10504 /// \endcode
10505 ///
10506 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
10507 /// since we do not know that we can look into X<T> when we parsed the type.
10508 /// This function will rebuild the type, performing the lookup of "pointer"
10509 /// in X<T> and returning an ElaboratedType whose canonical type is the same
10510 /// as the canonical type of T*, allowing the return types of the out-of-line
10511 /// definition and the declaration to match.
10512 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
10513                                                         SourceLocation Loc,
10514                                                         DeclarationName Name) {
10515   if (!T || !T->getType()->isDependentType())
10516     return T;
10517
10518   CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
10519   return Rebuilder.TransformType(T);
10520 }
10521
10522 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
10523   CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
10524                                           DeclarationName());
10525   return Rebuilder.TransformExpr(E);
10526 }
10527
10528 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
10529   if (SS.isInvalid())
10530     return true;
10531
10532   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10533   CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
10534                                           DeclarationName());
10535   NestedNameSpecifierLoc Rebuilt
10536     = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
10537   if (!Rebuilt)
10538     return true;
10539
10540   SS.Adopt(Rebuilt);
10541   return false;
10542 }
10543
10544 /// Rebuild the template parameters now that we know we're in a current
10545 /// instantiation.
10546 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
10547                                                TemplateParameterList *Params) {
10548   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
10549     Decl *Param = Params->getParam(I);
10550
10551     // There is nothing to rebuild in a type parameter.
10552     if (isa<TemplateTypeParmDecl>(Param))
10553       continue;
10554
10555     // Rebuild the template parameter list of a template template parameter.
10556     if (TemplateTemplateParmDecl *TTP
10557         = dyn_cast<TemplateTemplateParmDecl>(Param)) {
10558       if (RebuildTemplateParamsInCurrentInstantiation(
10559             TTP->getTemplateParameters()))
10560         return true;
10561
10562       continue;
10563     }
10564
10565     // Rebuild the type of a non-type template parameter.
10566     NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
10567     TypeSourceInfo *NewTSI
10568       = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
10569                                           NTTP->getLocation(),
10570                                           NTTP->getDeclName());
10571     if (!NewTSI)
10572       return true;
10573
10574     if (NewTSI->getType()->isUndeducedType()) {
10575       // C++17 [temp.dep.expr]p3:
10576       //   An id-expression is type-dependent if it contains
10577       //    - an identifier associated by name lookup with a non-type
10578       //      template-parameter declared with a type that contains a
10579       //      placeholder type (7.1.7.4),
10580       NewTSI = SubstAutoTypeSourceInfo(NewTSI, Context.DependentTy);
10581     }
10582
10583     if (NewTSI != NTTP->getTypeSourceInfo()) {
10584       NTTP->setTypeSourceInfo(NewTSI);
10585       NTTP->setType(NewTSI->getType());
10586     }
10587   }
10588
10589   return false;
10590 }
10591
10592 /// Produces a formatted string that describes the binding of
10593 /// template parameters to template arguments.
10594 std::string
10595 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
10596                                       const TemplateArgumentList &Args) {
10597   return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
10598 }
10599
10600 std::string
10601 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
10602                                       const TemplateArgument *Args,
10603                                       unsigned NumArgs) {
10604   SmallString<128> Str;
10605   llvm::raw_svector_ostream Out(Str);
10606
10607   if (!Params || Params->size() == 0 || NumArgs == 0)
10608     return std::string();
10609
10610   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
10611     if (I >= NumArgs)
10612       break;
10613
10614     if (I == 0)
10615       Out << "[with ";
10616     else
10617       Out << ", ";
10618
10619     if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
10620       Out << Id->getName();
10621     } else {
10622       Out << '$' << I;
10623     }
10624
10625     Out << " = ";
10626     Args[I].print(getPrintingPolicy(), Out);
10627   }
10628
10629   Out << ']';
10630   return Out.str();
10631 }
10632
10633 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
10634                                     CachedTokens &Toks) {
10635   if (!FD)
10636     return;
10637
10638   auto LPT = std::make_unique<LateParsedTemplate>();
10639
10640   // Take tokens to avoid allocations
10641   LPT->Toks.swap(Toks);
10642   LPT->D = FnD;
10643   LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
10644
10645   FD->setLateTemplateParsed(true);
10646 }
10647
10648 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
10649   if (!FD)
10650     return;
10651   FD->setLateTemplateParsed(false);
10652 }
10653
10654 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
10655   DeclContext *DC = CurContext;
10656
10657   while (DC) {
10658     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
10659       const FunctionDecl *FD = RD->isLocalClass();
10660       return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
10661     } else if (DC->isTranslationUnit() || DC->isNamespace())
10662       return false;
10663
10664     DC = DC->getParent();
10665   }
10666   return false;
10667 }
10668
10669 namespace {
10670 /// Walk the path from which a declaration was instantiated, and check
10671 /// that every explicit specialization along that path is visible. This enforces
10672 /// C++ [temp.expl.spec]/6:
10673 ///
10674 ///   If a template, a member template or a member of a class template is
10675 ///   explicitly specialized then that specialization shall be declared before
10676 ///   the first use of that specialization that would cause an implicit
10677 ///   instantiation to take place, in every translation unit in which such a
10678 ///   use occurs; no diagnostic is required.
10679 ///
10680 /// and also C++ [temp.class.spec]/1:
10681 ///
10682 ///   A partial specialization shall be declared before the first use of a
10683 ///   class template specialization that would make use of the partial
10684 ///   specialization as the result of an implicit or explicit instantiation
10685 ///   in every translation unit in which such a use occurs; no diagnostic is
10686 ///   required.
10687 class ExplicitSpecializationVisibilityChecker {
10688   Sema &S;
10689   SourceLocation Loc;
10690   llvm::SmallVector<Module *, 8> Modules;
10691
10692 public:
10693   ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
10694       : S(S), Loc(Loc) {}
10695
10696   void check(NamedDecl *ND) {
10697     if (auto *FD = dyn_cast<FunctionDecl>(ND))
10698       return checkImpl(FD);
10699     if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
10700       return checkImpl(RD);
10701     if (auto *VD = dyn_cast<VarDecl>(ND))
10702       return checkImpl(VD);
10703     if (auto *ED = dyn_cast<EnumDecl>(ND))
10704       return checkImpl(ED);
10705   }
10706
10707 private:
10708   void diagnose(NamedDecl *D, bool IsPartialSpec) {
10709     auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
10710                               : Sema::MissingImportKind::ExplicitSpecialization;
10711     const bool Recover = true;
10712
10713     // If we got a custom set of modules (because only a subset of the
10714     // declarations are interesting), use them, otherwise let
10715     // diagnoseMissingImport intelligently pick some.
10716     if (Modules.empty())
10717       S.diagnoseMissingImport(Loc, D, Kind, Recover);
10718     else
10719       S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
10720   }
10721
10722   // Check a specific declaration. There are three problematic cases:
10723   //
10724   //  1) The declaration is an explicit specialization of a template
10725   //     specialization.
10726   //  2) The declaration is an explicit specialization of a member of an
10727   //     templated class.
10728   //  3) The declaration is an instantiation of a template, and that template
10729   //     is an explicit specialization of a member of a templated class.
10730   //
10731   // We don't need to go any deeper than that, as the instantiation of the
10732   // surrounding class / etc is not triggered by whatever triggered this
10733   // instantiation, and thus should be checked elsewhere.
10734   template<typename SpecDecl>
10735   void checkImpl(SpecDecl *Spec) {
10736     bool IsHiddenExplicitSpecialization = false;
10737     if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
10738       IsHiddenExplicitSpecialization =
10739           Spec->getMemberSpecializationInfo()
10740               ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
10741               : !S.hasVisibleExplicitSpecialization(Spec, &Modules);
10742     } else {
10743       checkInstantiated(Spec);
10744     }
10745
10746     if (IsHiddenExplicitSpecialization)
10747       diagnose(Spec->getMostRecentDecl(), false);
10748   }
10749
10750   void checkInstantiated(FunctionDecl *FD) {
10751     if (auto *TD = FD->getPrimaryTemplate())
10752       checkTemplate(TD);
10753   }
10754
10755   void checkInstantiated(CXXRecordDecl *RD) {
10756     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
10757     if (!SD)
10758       return;
10759
10760     auto From = SD->getSpecializedTemplateOrPartial();
10761     if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
10762       checkTemplate(TD);
10763     else if (auto *TD =
10764                  From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
10765       if (!S.hasVisibleDeclaration(TD))
10766         diagnose(TD, true);
10767       checkTemplate(TD);
10768     }
10769   }
10770
10771   void checkInstantiated(VarDecl *RD) {
10772     auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
10773     if (!SD)
10774       return;
10775
10776     auto From = SD->getSpecializedTemplateOrPartial();
10777     if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
10778       checkTemplate(TD);
10779     else if (auto *TD =
10780                  From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
10781       if (!S.hasVisibleDeclaration(TD))
10782         diagnose(TD, true);
10783       checkTemplate(TD);
10784     }
10785   }
10786
10787   void checkInstantiated(EnumDecl *FD) {}
10788
10789   template<typename TemplDecl>
10790   void checkTemplate(TemplDecl *TD) {
10791     if (TD->isMemberSpecialization()) {
10792       if (!S.hasVisibleMemberSpecialization(TD, &Modules))
10793         diagnose(TD->getMostRecentDecl(), false);
10794     }
10795   }
10796 };
10797 } // end anonymous namespace
10798
10799 void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
10800   if (!getLangOpts().Modules)
10801     return;
10802
10803   ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
10804 }
10805
10806 /// Check whether a template partial specialization that we've discovered
10807 /// is hidden, and produce suitable diagnostics if so.
10808 void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
10809                                                 NamedDecl *Spec) {
10810   llvm::SmallVector<Module *, 8> Modules;
10811   if (!hasVisibleDeclaration(Spec, &Modules))
10812     diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
10813                           MissingImportKind::PartialSpecialization,
10814                           /*Recover*/true);
10815 }