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