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