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