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 namespace {
3056 
3057 // A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3058 // within failing boolean expression, such as substituting template parameters
3059 // for actual types.
3060 class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3061 public:
3062   explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3063       : Policy(P) {}
3064 
3065   bool handledStmt(Stmt *E, raw_ostream &OS) override {
3066     const auto *DR = dyn_cast<DeclRefExpr>(E);
3067     if (DR && DR->getQualifier()) {
3068       // If this is a qualified name, expand the template arguments in nested
3069       // qualifiers.
3070       DR->getQualifier()->print(OS, Policy, true);
3071       // Then print the decl itself.
3072       const ValueDecl *VD = DR->getDecl();
3073       OS << VD->getName();
3074       if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3075         // This is a template variable, print the expanded template arguments.
3076         printTemplateArgumentList(OS, IV->getTemplateArgs().asArray(), Policy);
3077       }
3078       return true;
3079     }
3080     return false;
3081   }
3082 
3083 private:
3084   const PrintingPolicy Policy;
3085 };
3086 
3087 } // end anonymous namespace
3088 
3089 std::pair<Expr *, std::string>
3090 Sema::findFailedBooleanCondition(Expr *Cond) {
3091   Cond = lookThroughRangesV3Condition(PP, Cond);
3092 
3093   // Separate out all of the terms in a conjunction.
3094   SmallVector<Expr *, 4> Terms;
3095   collectConjunctionTerms(Cond, Terms);
3096 
3097   // Determine which term failed.
3098   Expr *FailedCond = nullptr;
3099   for (Expr *Term : Terms) {
3100     Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3101 
3102     // Literals are uninteresting.
3103     if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3104         isa<IntegerLiteral>(TermAsWritten))
3105       continue;
3106 
3107     // The initialization of the parameter from the argument is
3108     // a constant-evaluated context.
3109     EnterExpressionEvaluationContext ConstantEvaluated(
3110       *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3111 
3112     bool Succeeded;
3113     if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3114         !Succeeded) {
3115       FailedCond = TermAsWritten;
3116       break;
3117     }
3118   }
3119   if (!FailedCond)
3120     FailedCond = Cond->IgnoreParenImpCasts();
3121 
3122   std::string Description;
3123   {
3124     llvm::raw_string_ostream Out(Description);
3125     FailedBooleanConditionPrinterHelper Helper(getPrintingPolicy());
3126     FailedCond->printPretty(Out, &Helper, getPrintingPolicy());
3127   }
3128   return { FailedCond, Description };
3129 }
3130 
3131 QualType Sema::CheckTemplateIdType(TemplateName Name,
3132                                    SourceLocation TemplateLoc,
3133                                    TemplateArgumentListInfo &TemplateArgs) {
3134   DependentTemplateName *DTN
3135     = Name.getUnderlying().getAsDependentTemplateName();
3136   if (DTN && DTN->isIdentifier())
3137     // When building a template-id where the template-name is dependent,
3138     // assume the template is a type template. Either our assumption is
3139     // correct, or the code is ill-formed and will be diagnosed when the
3140     // dependent name is substituted.
3141     return Context.getDependentTemplateSpecializationType(ETK_None,
3142                                                           DTN->getQualifier(),
3143                                                           DTN->getIdentifier(),
3144                                                           TemplateArgs);
3145 
3146   TemplateDecl *Template = Name.getAsTemplateDecl();
3147   if (!Template || isa<FunctionTemplateDecl>(Template) ||
3148       isa<VarTemplateDecl>(Template)) {
3149     // We might have a substituted template template parameter pack. If so,
3150     // build a template specialization type for it.
3151     if (Name.getAsSubstTemplateTemplateParmPack())
3152       return Context.getTemplateSpecializationType(Name, TemplateArgs);
3153 
3154     Diag(TemplateLoc, diag::err_template_id_not_a_type)
3155       << Name;
3156     NoteAllFoundTemplates(Name);
3157     return QualType();
3158   }
3159 
3160   // Check that the template argument list is well-formed for this
3161   // template.
3162   SmallVector<TemplateArgument, 4> Converted;
3163   if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3164                                 false, Converted))
3165     return QualType();
3166 
3167   QualType CanonType;
3168 
3169   bool InstantiationDependent = false;
3170   if (TypeAliasTemplateDecl *AliasTemplate =
3171           dyn_cast<TypeAliasTemplateDecl>(Template)) {
3172     // Find the canonical type for this type alias template specialization.
3173     TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3174     if (Pattern->isInvalidDecl())
3175       return QualType();
3176 
3177     TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
3178                                            Converted);
3179 
3180     // Only substitute for the innermost template argument list.
3181     MultiLevelTemplateArgumentList TemplateArgLists;
3182     TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
3183     unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
3184     for (unsigned I = 0; I < Depth; ++I)
3185       TemplateArgLists.addOuterTemplateArguments(None);
3186 
3187     LocalInstantiationScope Scope(*this);
3188     InstantiatingTemplate Inst(*this, TemplateLoc, Template);
3189     if (Inst.isInvalid())
3190       return QualType();
3191 
3192     CanonType = SubstType(Pattern->getUnderlyingType(),
3193                           TemplateArgLists, AliasTemplate->getLocation(),
3194                           AliasTemplate->getDeclName());
3195     if (CanonType.isNull()) {
3196       // If this was enable_if and we failed to find the nested type
3197       // within enable_if in a SFINAE context, dig out the specific
3198       // enable_if condition that failed and present that instead.
3199       if (isEnableIfAliasTemplate(AliasTemplate)) {
3200         if (auto DeductionInfo = isSFINAEContext()) {
3201           if (*DeductionInfo &&
3202               (*DeductionInfo)->hasSFINAEDiagnostic() &&
3203               (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3204                 diag::err_typename_nested_not_found_enable_if &&
3205               TemplateArgs[0].getArgument().getKind()
3206                 == TemplateArgument::Expression) {
3207             Expr *FailedCond;
3208             std::string FailedDescription;
3209             std::tie(FailedCond, FailedDescription) =
3210               findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3211 
3212             // Remove the old SFINAE diagnostic.
3213             PartialDiagnosticAt OldDiag =
3214               {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3215             (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3216 
3217             // Add a new SFINAE diagnostic specifying which condition
3218             // failed.
3219             (*DeductionInfo)->addSFINAEDiagnostic(
3220               OldDiag.first,
3221               PDiag(diag::err_typename_nested_not_found_requirement)
3222                 << FailedDescription
3223                 << FailedCond->getSourceRange());
3224           }
3225         }
3226       }
3227 
3228       return QualType();
3229     }
3230   } else if (Name.isDependent() ||
3231              TemplateSpecializationType::anyDependentTemplateArguments(
3232                TemplateArgs, InstantiationDependent)) {
3233     // This class template specialization is a dependent
3234     // type. Therefore, its canonical type is another class template
3235     // specialization type that contains all of the converted
3236     // arguments in canonical form. This ensures that, e.g., A<T> and
3237     // A<T, T> have identical types when A is declared as:
3238     //
3239     //   template<typename T, typename U = T> struct A;
3240     CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
3241 
3242     // This might work out to be a current instantiation, in which
3243     // case the canonical type needs to be the InjectedClassNameType.
3244     //
3245     // TODO: in theory this could be a simple hashtable lookup; most
3246     // changes to CurContext don't change the set of current
3247     // instantiations.
3248     if (isa<ClassTemplateDecl>(Template)) {
3249       for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3250         // If we get out to a namespace, we're done.
3251         if (Ctx->isFileContext()) break;
3252 
3253         // If this isn't a record, keep looking.
3254         CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3255         if (!Record) continue;
3256 
3257         // Look for one of the two cases with InjectedClassNameTypes
3258         // and check whether it's the same template.
3259         if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3260             !Record->getDescribedClassTemplate())
3261           continue;
3262 
3263         // Fetch the injected class name type and check whether its
3264         // injected type is equal to the type we just built.
3265         QualType ICNT = Context.getTypeDeclType(Record);
3266         QualType Injected = cast<InjectedClassNameType>(ICNT)
3267           ->getInjectedSpecializationType();
3268 
3269         if (CanonType != Injected->getCanonicalTypeInternal())
3270           continue;
3271 
3272         // If so, the canonical type of this TST is the injected
3273         // class name type of the record we just found.
3274         assert(ICNT.isCanonical());
3275         CanonType = ICNT;
3276         break;
3277       }
3278     }
3279   } else if (ClassTemplateDecl *ClassTemplate
3280                = dyn_cast<ClassTemplateDecl>(Template)) {
3281     // Find the class template specialization declaration that
3282     // corresponds to these arguments.
3283     void *InsertPos = nullptr;
3284     ClassTemplateSpecializationDecl *Decl
3285       = ClassTemplate->findSpecialization(Converted, InsertPos);
3286     if (!Decl) {
3287       // This is the first time we have referenced this class template
3288       // specialization. Create the canonical declaration and add it to
3289       // the set of specializations.
3290       Decl = ClassTemplateSpecializationDecl::Create(
3291           Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3292           ClassTemplate->getDeclContext(),
3293           ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3294           ClassTemplate->getLocation(), ClassTemplate, Converted, nullptr);
3295       ClassTemplate->AddSpecialization(Decl, InsertPos);
3296       if (ClassTemplate->isOutOfLine())
3297         Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3298     }
3299 
3300     if (Decl->getSpecializationKind() == TSK_Undeclared) {
3301       MultiLevelTemplateArgumentList TemplateArgLists;
3302       TemplateArgLists.addOuterTemplateArguments(Converted);
3303       InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3304                               Decl);
3305     }
3306 
3307     // Diagnose uses of this specialization.
3308     (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3309 
3310     CanonType = Context.getTypeDeclType(Decl);
3311     assert(isa<RecordType>(CanonType) &&
3312            "type of non-dependent specialization is not a RecordType");
3313   } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3314     CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3315                                            TemplateArgs);
3316   }
3317 
3318   // Build the fully-sugared type for this class template
3319   // specialization, which refers back to the class template
3320   // specialization we created or found.
3321   return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
3322 }
3323 
3324 TypeResult
3325 Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3326                           TemplateTy TemplateD, IdentifierInfo *TemplateII,
3327                           SourceLocation TemplateIILoc,
3328                           SourceLocation LAngleLoc,
3329                           ASTTemplateArgsPtr TemplateArgsIn,
3330                           SourceLocation RAngleLoc,
3331                           bool IsCtorOrDtorName, bool IsClassName) {
3332   if (SS.isInvalid())
3333     return true;
3334 
3335   if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3336     DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3337 
3338     // C++ [temp.res]p3:
3339     //   A qualified-id that refers to a type and in which the
3340     //   nested-name-specifier depends on a template-parameter (14.6.2)
3341     //   shall be prefixed by the keyword typename to indicate that the
3342     //   qualified-id denotes a type, forming an
3343     //   elaborated-type-specifier (7.1.5.3).
3344     if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3345       Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3346         << SS.getScopeRep() << TemplateII->getName();
3347       // Recover as if 'typename' were specified.
3348       // FIXME: This is not quite correct recovery as we don't transform SS
3349       // into the corresponding dependent form (and we don't diagnose missing
3350       // 'template' keywords within SS as a result).
3351       return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3352                                TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3353                                TemplateArgsIn, RAngleLoc);
3354     }
3355 
3356     // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3357     // it's not actually allowed to be used as a type in most cases. Because
3358     // we annotate it before we know whether it's valid, we have to check for
3359     // this case here.
3360     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3361     if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3362       Diag(TemplateIILoc,
3363            TemplateKWLoc.isInvalid()
3364                ? diag::err_out_of_line_qualified_id_type_names_constructor
3365                : diag::ext_out_of_line_qualified_id_type_names_constructor)
3366         << TemplateII << 0 /*injected-class-name used as template name*/
3367         << 1 /*if any keyword was present, it was 'template'*/;
3368     }
3369   }
3370 
3371   TemplateName Template = TemplateD.get();
3372 
3373   // Translate the parser's template argument list in our AST format.
3374   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3375   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3376 
3377   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3378     QualType T
3379       = Context.getDependentTemplateSpecializationType(ETK_None,
3380                                                        DTN->getQualifier(),
3381                                                        DTN->getIdentifier(),
3382                                                        TemplateArgs);
3383     // Build type-source information.
3384     TypeLocBuilder TLB;
3385     DependentTemplateSpecializationTypeLoc SpecTL
3386       = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3387     SpecTL.setElaboratedKeywordLoc(SourceLocation());
3388     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3389     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3390     SpecTL.setTemplateNameLoc(TemplateIILoc);
3391     SpecTL.setLAngleLoc(LAngleLoc);
3392     SpecTL.setRAngleLoc(RAngleLoc);
3393     for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3394       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3395     return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3396   }
3397 
3398   QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3399   if (Result.isNull())
3400     return true;
3401 
3402   // Build type-source information.
3403   TypeLocBuilder TLB;
3404   TemplateSpecializationTypeLoc SpecTL
3405     = TLB.push<TemplateSpecializationTypeLoc>(Result);
3406   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3407   SpecTL.setTemplateNameLoc(TemplateIILoc);
3408   SpecTL.setLAngleLoc(LAngleLoc);
3409   SpecTL.setRAngleLoc(RAngleLoc);
3410   for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3411     SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3412 
3413   // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3414   // constructor or destructor name (in such a case, the scope specifier
3415   // will be attached to the enclosing Decl or Expr node).
3416   if (SS.isNotEmpty() && !IsCtorOrDtorName) {
3417     // Create an elaborated-type-specifier containing the nested-name-specifier.
3418     Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3419     ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3420     ElabTL.setElaboratedKeywordLoc(SourceLocation());
3421     ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3422   }
3423 
3424   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3425 }
3426 
3427 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
3428                                         TypeSpecifierType TagSpec,
3429                                         SourceLocation TagLoc,
3430                                         CXXScopeSpec &SS,
3431                                         SourceLocation TemplateKWLoc,
3432                                         TemplateTy TemplateD,
3433                                         SourceLocation TemplateLoc,
3434                                         SourceLocation LAngleLoc,
3435                                         ASTTemplateArgsPtr TemplateArgsIn,
3436                                         SourceLocation RAngleLoc) {
3437   TemplateName Template = TemplateD.get();
3438 
3439   // Translate the parser's template argument list in our AST format.
3440   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3441   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3442 
3443   // Determine the tag kind
3444   TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3445   ElaboratedTypeKeyword Keyword
3446     = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
3447 
3448   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3449     QualType T = Context.getDependentTemplateSpecializationType(Keyword,
3450                                                           DTN->getQualifier(),
3451                                                           DTN->getIdentifier(),
3452                                                                 TemplateArgs);
3453 
3454     // Build type-source information.
3455     TypeLocBuilder TLB;
3456     DependentTemplateSpecializationTypeLoc SpecTL
3457       = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3458     SpecTL.setElaboratedKeywordLoc(TagLoc);
3459     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3460     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3461     SpecTL.setTemplateNameLoc(TemplateLoc);
3462     SpecTL.setLAngleLoc(LAngleLoc);
3463     SpecTL.setRAngleLoc(RAngleLoc);
3464     for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3465       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3466     return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3467   }
3468 
3469   if (TypeAliasTemplateDecl *TAT =
3470         dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3471     // C++0x [dcl.type.elab]p2:
3472     //   If the identifier resolves to a typedef-name or the simple-template-id
3473     //   resolves to an alias template specialization, the
3474     //   elaborated-type-specifier is ill-formed.
3475     Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3476         << TAT << NTK_TypeAliasTemplate << TagKind;
3477     Diag(TAT->getLocation(), diag::note_declared_at);
3478   }
3479 
3480   QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3481   if (Result.isNull())
3482     return TypeResult(true);
3483 
3484   // Check the tag kind
3485   if (const RecordType *RT = Result->getAs<RecordType>()) {
3486     RecordDecl *D = RT->getDecl();
3487 
3488     IdentifierInfo *Id = D->getIdentifier();
3489     assert(Id && "templated class must have an identifier");
3490 
3491     if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
3492                                       TagLoc, Id)) {
3493       Diag(TagLoc, diag::err_use_with_wrong_tag)
3494         << Result
3495         << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
3496       Diag(D->getLocation(), diag::note_previous_use);
3497     }
3498   }
3499 
3500   // Provide source-location information for the template specialization.
3501   TypeLocBuilder TLB;
3502   TemplateSpecializationTypeLoc SpecTL
3503     = TLB.push<TemplateSpecializationTypeLoc>(Result);
3504   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3505   SpecTL.setTemplateNameLoc(TemplateLoc);
3506   SpecTL.setLAngleLoc(LAngleLoc);
3507   SpecTL.setRAngleLoc(RAngleLoc);
3508   for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3509     SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3510 
3511   // Construct an elaborated type containing the nested-name-specifier (if any)
3512   // and tag keyword.
3513   Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3514   ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3515   ElabTL.setElaboratedKeywordLoc(TagLoc);
3516   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3517   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3518 }
3519 
3520 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3521                                              NamedDecl *PrevDecl,
3522                                              SourceLocation Loc,
3523                                              bool IsPartialSpecialization);
3524 
3525 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
3526 
3527 static bool isTemplateArgumentTemplateParameter(
3528     const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3529   switch (Arg.getKind()) {
3530   case TemplateArgument::Null:
3531   case TemplateArgument::NullPtr:
3532   case TemplateArgument::Integral:
3533   case TemplateArgument::Declaration:
3534   case TemplateArgument::Pack:
3535   case TemplateArgument::TemplateExpansion:
3536     return false;
3537 
3538   case TemplateArgument::Type: {
3539     QualType Type = Arg.getAsType();
3540     const TemplateTypeParmType *TPT =
3541         Arg.getAsType()->getAs<TemplateTypeParmType>();
3542     return TPT && !Type.hasQualifiers() &&
3543            TPT->getDepth() == Depth && TPT->getIndex() == Index;
3544   }
3545 
3546   case TemplateArgument::Expression: {
3547     DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3548     if (!DRE || !DRE->getDecl())
3549       return false;
3550     const NonTypeTemplateParmDecl *NTTP =
3551         dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3552     return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3553   }
3554 
3555   case TemplateArgument::Template:
3556     const TemplateTemplateParmDecl *TTP =
3557         dyn_cast_or_null<TemplateTemplateParmDecl>(
3558             Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3559     return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3560   }
3561   llvm_unreachable("unexpected kind of template argument");
3562 }
3563 
3564 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3565                                     ArrayRef<TemplateArgument> Args) {
3566   if (Params->size() != Args.size())
3567     return false;
3568 
3569   unsigned Depth = Params->getDepth();
3570 
3571   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3572     TemplateArgument Arg = Args[I];
3573 
3574     // If the parameter is a pack expansion, the argument must be a pack
3575     // whose only element is a pack expansion.
3576     if (Params->getParam(I)->isParameterPack()) {
3577       if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3578           !Arg.pack_begin()->isPackExpansion())
3579         return false;
3580       Arg = Arg.pack_begin()->getPackExpansionPattern();
3581     }
3582 
3583     if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3584       return false;
3585   }
3586 
3587   return true;
3588 }
3589 
3590 /// Convert the parser's template argument list representation into our form.
3591 static TemplateArgumentListInfo
3592 makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3593   TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3594                                         TemplateId.RAngleLoc);
3595   ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3596                                      TemplateId.NumArgs);
3597   S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3598   return TemplateArgs;
3599 }
3600 
3601 template<typename PartialSpecDecl>
3602 static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3603   if (Partial->getDeclContext()->isDependentContext())
3604     return;
3605 
3606   // FIXME: Get the TDK from deduction in order to provide better diagnostics
3607   // for non-substitution-failure issues?
3608   TemplateDeductionInfo Info(Partial->getLocation());
3609   if (S.isMoreSpecializedThanPrimary(Partial, Info))
3610     return;
3611 
3612   auto *Template = Partial->getSpecializedTemplate();
3613   S.Diag(Partial->getLocation(),
3614          diag::ext_partial_spec_not_more_specialized_than_primary)
3615       << isa<VarTemplateDecl>(Template);
3616 
3617   if (Info.hasSFINAEDiagnostic()) {
3618     PartialDiagnosticAt Diag = {SourceLocation(),
3619                                 PartialDiagnostic::NullDiagnostic()};
3620     Info.takeSFINAEDiagnostic(Diag);
3621     SmallString<128> SFINAEArgString;
3622     Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3623     S.Diag(Diag.first,
3624            diag::note_partial_spec_not_more_specialized_than_primary)
3625       << SFINAEArgString;
3626   }
3627 
3628   S.Diag(Template->getLocation(), diag::note_template_decl_here);
3629 }
3630 
3631 static void
3632 noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3633                            const llvm::SmallBitVector &DeducibleParams) {
3634   for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3635     if (!DeducibleParams[I]) {
3636       NamedDecl *Param = TemplateParams->getParam(I);
3637       if (Param->getDeclName())
3638         S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3639             << Param->getDeclName();
3640       else
3641         S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3642             << "(anonymous)";
3643     }
3644   }
3645 }
3646 
3647 
3648 template<typename PartialSpecDecl>
3649 static void checkTemplatePartialSpecialization(Sema &S,
3650                                                PartialSpecDecl *Partial) {
3651   // C++1z [temp.class.spec]p8: (DR1495)
3652   //   - The specialization shall be more specialized than the primary
3653   //     template (14.5.5.2).
3654   checkMoreSpecializedThanPrimary(S, Partial);
3655 
3656   // C++ [temp.class.spec]p8: (DR1315)
3657   //   - Each template-parameter shall appear at least once in the
3658   //     template-id outside a non-deduced context.
3659   // C++1z [temp.class.spec.match]p3 (P0127R2)
3660   //   If the template arguments of a partial specialization cannot be
3661   //   deduced because of the structure of its template-parameter-list
3662   //   and the template-id, the program is ill-formed.
3663   auto *TemplateParams = Partial->getTemplateParameters();
3664   llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3665   S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3666                                TemplateParams->getDepth(), DeducibleParams);
3667 
3668   if (!DeducibleParams.all()) {
3669     unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3670     S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3671       << isa<VarTemplatePartialSpecializationDecl>(Partial)
3672       << (NumNonDeducible > 1)
3673       << SourceRange(Partial->getLocation(),
3674                      Partial->getTemplateArgsAsWritten()->RAngleLoc);
3675     noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
3676   }
3677 }
3678 
3679 void Sema::CheckTemplatePartialSpecialization(
3680     ClassTemplatePartialSpecializationDecl *Partial) {
3681   checkTemplatePartialSpecialization(*this, Partial);
3682 }
3683 
3684 void Sema::CheckTemplatePartialSpecialization(
3685     VarTemplatePartialSpecializationDecl *Partial) {
3686   checkTemplatePartialSpecialization(*this, Partial);
3687 }
3688 
3689 void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3690   // C++1z [temp.param]p11:
3691   //   A template parameter of a deduction guide template that does not have a
3692   //   default-argument shall be deducible from the parameter-type-list of the
3693   //   deduction guide template.
3694   auto *TemplateParams = TD->getTemplateParameters();
3695   llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3696   MarkDeducedTemplateParameters(TD, DeducibleParams);
3697   for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3698     // A parameter pack is deducible (to an empty pack).
3699     auto *Param = TemplateParams->getParam(I);
3700     if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3701       DeducibleParams[I] = true;
3702   }
3703 
3704   if (!DeducibleParams.all()) {
3705     unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3706     Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3707       << (NumNonDeducible > 1);
3708     noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3709   }
3710 }
3711 
3712 DeclResult Sema::ActOnVarTemplateSpecialization(
3713     Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
3714     TemplateParameterList *TemplateParams, StorageClass SC,
3715     bool IsPartialSpecialization) {
3716   // D must be variable template id.
3717   assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
3718          "Variable template specialization is declared with a template it.");
3719 
3720   TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3721   TemplateArgumentListInfo TemplateArgs =
3722       makeTemplateArgumentListInfo(*this, *TemplateId);
3723   SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3724   SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3725   SourceLocation RAngleLoc = TemplateId->RAngleLoc;
3726 
3727   TemplateName Name = TemplateId->Template.get();
3728 
3729   // The template-id must name a variable template.
3730   VarTemplateDecl *VarTemplate =
3731       dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3732   if (!VarTemplate) {
3733     NamedDecl *FnTemplate;
3734     if (auto *OTS = Name.getAsOverloadedTemplate())
3735       FnTemplate = *OTS->begin();
3736     else
3737       FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3738     if (FnTemplate)
3739       return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3740                << FnTemplate->getDeclName();
3741     return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3742              << IsPartialSpecialization;
3743   }
3744 
3745   // Check for unexpanded parameter packs in any of the template arguments.
3746   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3747     if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3748                                         UPPC_PartialSpecialization))
3749       return true;
3750 
3751   // Check that the template argument list is well-formed for this
3752   // template.
3753   SmallVector<TemplateArgument, 4> Converted;
3754   if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3755                                 false, Converted))
3756     return true;
3757 
3758   // Find the variable template (partial) specialization declaration that
3759   // corresponds to these arguments.
3760   if (IsPartialSpecialization) {
3761     if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3762                                                TemplateArgs.size(), Converted))
3763       return true;
3764 
3765     // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3766     // also do them during instantiation.
3767     bool InstantiationDependent;
3768     if (!Name.isDependent() &&
3769         !TemplateSpecializationType::anyDependentTemplateArguments(
3770             TemplateArgs.arguments(),
3771             InstantiationDependent)) {
3772       Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3773           << VarTemplate->getDeclName();
3774       IsPartialSpecialization = false;
3775     }
3776 
3777     if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3778                                 Converted)) {
3779       // C++ [temp.class.spec]p9b3:
3780       //
3781       //   -- The argument list of the specialization shall not be identical
3782       //      to the implicit argument list of the primary template.
3783       Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3784         << /*variable template*/ 1
3785         << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3786         << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3787       // FIXME: Recover from this by treating the declaration as a redeclaration
3788       // of the primary template.
3789       return true;
3790     }
3791   }
3792 
3793   void *InsertPos = nullptr;
3794   VarTemplateSpecializationDecl *PrevDecl = nullptr;
3795 
3796   if (IsPartialSpecialization)
3797     // FIXME: Template parameter list matters too
3798     PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
3799   else
3800     PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
3801 
3802   VarTemplateSpecializationDecl *Specialization = nullptr;
3803 
3804   // Check whether we can declare a variable template specialization in
3805   // the current scope.
3806   if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3807                                        TemplateNameLoc,
3808                                        IsPartialSpecialization))
3809     return true;
3810 
3811   if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3812     // Since the only prior variable template specialization with these
3813     // arguments was referenced but not declared,  reuse that
3814     // declaration node as our own, updating its source location and
3815     // the list of outer template parameters to reflect our new declaration.
3816     Specialization = PrevDecl;
3817     Specialization->setLocation(TemplateNameLoc);
3818     PrevDecl = nullptr;
3819   } else if (IsPartialSpecialization) {
3820     // Create a new class template partial specialization declaration node.
3821     VarTemplatePartialSpecializationDecl *PrevPartial =
3822         cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
3823     VarTemplatePartialSpecializationDecl *Partial =
3824         VarTemplatePartialSpecializationDecl::Create(
3825             Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3826             TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
3827             Converted, TemplateArgs);
3828 
3829     if (!PrevPartial)
3830       VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3831     Specialization = Partial;
3832 
3833     // If we are providing an explicit specialization of a member variable
3834     // template specialization, make a note of that.
3835     if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3836       PrevPartial->setMemberSpecialization();
3837 
3838     CheckTemplatePartialSpecialization(Partial);
3839   } else {
3840     // Create a new class template specialization declaration node for
3841     // this explicit specialization or friend declaration.
3842     Specialization = VarTemplateSpecializationDecl::Create(
3843         Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
3844         VarTemplate, DI->getType(), DI, SC, Converted);
3845     Specialization->setTemplateArgsInfo(TemplateArgs);
3846 
3847     if (!PrevDecl)
3848       VarTemplate->AddSpecialization(Specialization, InsertPos);
3849   }
3850 
3851   // C++ [temp.expl.spec]p6:
3852   //   If a template, a member template or the member of a class template is
3853   //   explicitly specialized then that specialization shall be declared
3854   //   before the first use of that specialization that would cause an implicit
3855   //   instantiation to take place, in every translation unit in which such a
3856   //   use occurs; no diagnostic is required.
3857   if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3858     bool Okay = false;
3859     for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3860       // Is there any previous explicit specialization declaration?
3861       if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3862         Okay = true;
3863         break;
3864       }
3865     }
3866 
3867     if (!Okay) {
3868       SourceRange Range(TemplateNameLoc, RAngleLoc);
3869       Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3870           << Name << Range;
3871 
3872       Diag(PrevDecl->getPointOfInstantiation(),
3873            diag::note_instantiation_required_here)
3874           << (PrevDecl->getTemplateSpecializationKind() !=
3875               TSK_ImplicitInstantiation);
3876       return true;
3877     }
3878   }
3879 
3880   Specialization->setTemplateKeywordLoc(TemplateKWLoc);
3881   Specialization->setLexicalDeclContext(CurContext);
3882 
3883   // Add the specialization into its lexical context, so that it can
3884   // be seen when iterating through the list of declarations in that
3885   // context. However, specializations are not found by name lookup.
3886   CurContext->addDecl(Specialization);
3887 
3888   // Note that this is an explicit specialization.
3889   Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3890 
3891   if (PrevDecl) {
3892     // Check that this isn't a redefinition of this specialization,
3893     // merging with previous declarations.
3894     LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
3895                           forRedeclarationInCurContext());
3896     PrevSpec.addDecl(PrevDecl);
3897     D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
3898   } else if (Specialization->isStaticDataMember() &&
3899              Specialization->isOutOfLine()) {
3900     Specialization->setAccess(VarTemplate->getAccess());
3901   }
3902 
3903   // Link instantiations of static data members back to the template from
3904   // which they were instantiated.
3905   if (Specialization->isStaticDataMember())
3906     Specialization->setInstantiationOfStaticDataMember(
3907         VarTemplate->getTemplatedDecl(),
3908         Specialization->getSpecializationKind());
3909 
3910   return Specialization;
3911 }
3912 
3913 namespace {
3914 /// A partial specialization whose template arguments have matched
3915 /// a given template-id.
3916 struct PartialSpecMatchResult {
3917   VarTemplatePartialSpecializationDecl *Partial;
3918   TemplateArgumentList *Args;
3919 };
3920 } // end anonymous namespace
3921 
3922 DeclResult
3923 Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
3924                          SourceLocation TemplateNameLoc,
3925                          const TemplateArgumentListInfo &TemplateArgs) {
3926   assert(Template && "A variable template id without template?");
3927 
3928   // Check that the template argument list is well-formed for this template.
3929   SmallVector<TemplateArgument, 4> Converted;
3930   if (CheckTemplateArgumentList(
3931           Template, TemplateNameLoc,
3932           const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
3933           Converted))
3934     return true;
3935 
3936   // Find the variable template specialization declaration that
3937   // corresponds to these arguments.
3938   void *InsertPos = nullptr;
3939   if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
3940           Converted, InsertPos)) {
3941     checkSpecializationVisibility(TemplateNameLoc, Spec);
3942     // If we already have a variable template specialization, return it.
3943     return Spec;
3944   }
3945 
3946   // This is the first time we have referenced this variable template
3947   // specialization. Create the canonical declaration and add it to
3948   // the set of specializations, based on the closest partial specialization
3949   // that it represents. That is,
3950   VarDecl *InstantiationPattern = Template->getTemplatedDecl();
3951   TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
3952                                        Converted);
3953   TemplateArgumentList *InstantiationArgs = &TemplateArgList;
3954   bool AmbiguousPartialSpec = false;
3955   typedef PartialSpecMatchResult MatchResult;
3956   SmallVector<MatchResult, 4> Matched;
3957   SourceLocation PointOfInstantiation = TemplateNameLoc;
3958   TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
3959                                             /*ForTakingAddress=*/false);
3960 
3961   // 1. Attempt to find the closest partial specialization that this
3962   // specializes, if any.
3963   // If any of the template arguments is dependent, then this is probably
3964   // a placeholder for an incomplete declarative context; which must be
3965   // complete by instantiation time. Thus, do not search through the partial
3966   // specializations yet.
3967   // TODO: Unify with InstantiateClassTemplateSpecialization()?
3968   //       Perhaps better after unification of DeduceTemplateArguments() and
3969   //       getMoreSpecializedPartialSpecialization().
3970   bool InstantiationDependent = false;
3971   if (!TemplateSpecializationType::anyDependentTemplateArguments(
3972           TemplateArgs, InstantiationDependent)) {
3973 
3974     SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3975     Template->getPartialSpecializations(PartialSpecs);
3976 
3977     for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3978       VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3979       TemplateDeductionInfo Info(FailedCandidates.getLocation());
3980 
3981       if (TemplateDeductionResult Result =
3982               DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
3983         // Store the failed-deduction information for use in diagnostics, later.
3984         // TODO: Actually use the failed-deduction info?
3985         FailedCandidates.addCandidate().set(
3986             DeclAccessPair::make(Template, AS_public), Partial,
3987             MakeDeductionFailureInfo(Context, Result, Info));
3988         (void)Result;
3989       } else {
3990         Matched.push_back(PartialSpecMatchResult());
3991         Matched.back().Partial = Partial;
3992         Matched.back().Args = Info.take();
3993       }
3994     }
3995 
3996     if (Matched.size() >= 1) {
3997       SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
3998       if (Matched.size() == 1) {
3999         //   -- If exactly one matching specialization is found, the
4000         //      instantiation is generated from that specialization.
4001         // We don't need to do anything for this.
4002       } else {
4003         //   -- If more than one matching specialization is found, the
4004         //      partial order rules (14.5.4.2) are used to determine
4005         //      whether one of the specializations is more specialized
4006         //      than the others. If none of the specializations is more
4007         //      specialized than all of the other matching
4008         //      specializations, then the use of the variable template is
4009         //      ambiguous and the program is ill-formed.
4010         for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4011                                                    PEnd = Matched.end();
4012              P != PEnd; ++P) {
4013           if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4014                                                       PointOfInstantiation) ==
4015               P->Partial)
4016             Best = P;
4017         }
4018 
4019         // Determine if the best partial specialization is more specialized than
4020         // the others.
4021         for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4022                                                    PEnd = Matched.end();
4023              P != PEnd; ++P) {
4024           if (P != Best && getMoreSpecializedPartialSpecialization(
4025                                P->Partial, Best->Partial,
4026                                PointOfInstantiation) != Best->Partial) {
4027             AmbiguousPartialSpec = true;
4028             break;
4029           }
4030         }
4031       }
4032 
4033       // Instantiate using the best variable template partial specialization.
4034       InstantiationPattern = Best->Partial;
4035       InstantiationArgs = Best->Args;
4036     } else {
4037       //   -- If no match is found, the instantiation is generated
4038       //      from the primary template.
4039       // InstantiationPattern = Template->getTemplatedDecl();
4040     }
4041   }
4042 
4043   // 2. Create the canonical declaration.
4044   // Note that we do not instantiate a definition until we see an odr-use
4045   // in DoMarkVarDeclReferenced().
4046   // FIXME: LateAttrs et al.?
4047   VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4048       Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
4049       Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
4050   if (!Decl)
4051     return true;
4052 
4053   if (AmbiguousPartialSpec) {
4054     // Partial ordering did not produce a clear winner. Complain.
4055     Decl->setInvalidDecl();
4056     Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4057         << Decl;
4058 
4059     // Print the matching partial specializations.
4060     for (MatchResult P : Matched)
4061       Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4062           << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4063                                              *P.Args);
4064     return true;
4065   }
4066 
4067   if (VarTemplatePartialSpecializationDecl *D =
4068           dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4069     Decl->setInstantiationOf(D, InstantiationArgs);
4070 
4071   checkSpecializationVisibility(TemplateNameLoc, Decl);
4072 
4073   assert(Decl && "No variable template specialization?");
4074   return Decl;
4075 }
4076 
4077 ExprResult
4078 Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
4079                          const DeclarationNameInfo &NameInfo,
4080                          VarTemplateDecl *Template, SourceLocation TemplateLoc,
4081                          const TemplateArgumentListInfo *TemplateArgs) {
4082 
4083   DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4084                                        *TemplateArgs);
4085   if (Decl.isInvalid())
4086     return ExprError();
4087 
4088   VarDecl *Var = cast<VarDecl>(Decl.get());
4089   if (!Var->getTemplateSpecializationKind())
4090     Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
4091                                        NameInfo.getLoc());
4092 
4093   // Build an ordinary singleton decl ref.
4094   return BuildDeclarationNameExpr(SS, NameInfo, Var,
4095                                   /*FoundD=*/nullptr, TemplateArgs);
4096 }
4097 
4098 void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4099                                             SourceLocation Loc) {
4100   Diag(Loc, diag::err_template_missing_args)
4101     << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4102   if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4103     Diag(TD->getLocation(), diag::note_template_decl_here)
4104       << TD->getTemplateParameters()->getSourceRange();
4105   }
4106 }
4107 
4108 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
4109                                      SourceLocation TemplateKWLoc,
4110                                      LookupResult &R,
4111                                      bool RequiresADL,
4112                                  const TemplateArgumentListInfo *TemplateArgs) {
4113   // FIXME: Can we do any checking at this point? I guess we could check the
4114   // template arguments that we have against the template name, if the template
4115   // name refers to a single template. That's not a terribly common case,
4116   // though.
4117   // foo<int> could identify a single function unambiguously
4118   // This approach does NOT work, since f<int>(1);
4119   // gets resolved prior to resorting to overload resolution
4120   // i.e., template<class T> void f(double);
4121   //       vs template<class T, class U> void f(U);
4122 
4123   // These should be filtered out by our callers.
4124   assert(!R.empty() && "empty lookup results when building templateid");
4125   assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4126 
4127   // Non-function templates require a template argument list.
4128   if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4129     if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4130       diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
4131       return ExprError();
4132     }
4133   }
4134 
4135   auto AnyDependentArguments = [&]() -> bool {
4136     bool InstantiationDependent;
4137     return TemplateArgs &&
4138            TemplateSpecializationType::anyDependentTemplateArguments(
4139                *TemplateArgs, InstantiationDependent);
4140   };
4141 
4142   // In C++1y, check variable template ids.
4143   if (R.getAsSingle<VarTemplateDecl>() && !AnyDependentArguments()) {
4144     return CheckVarTemplateId(SS, R.getLookupNameInfo(),
4145                               R.getAsSingle<VarTemplateDecl>(),
4146                               TemplateKWLoc, TemplateArgs);
4147   }
4148 
4149   // We don't want lookup warnings at this point.
4150   R.suppressDiagnostics();
4151 
4152   UnresolvedLookupExpr *ULE
4153     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
4154                                    SS.getWithLocInContext(Context),
4155                                    TemplateKWLoc,
4156                                    R.getLookupNameInfo(),
4157                                    RequiresADL, TemplateArgs,
4158                                    R.begin(), R.end());
4159 
4160   return ULE;
4161 }
4162 
4163 // We actually only call this from template instantiation.
4164 ExprResult
4165 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
4166                                    SourceLocation TemplateKWLoc,
4167                                    const DeclarationNameInfo &NameInfo,
4168                              const TemplateArgumentListInfo *TemplateArgs) {
4169 
4170   assert(TemplateArgs || TemplateKWLoc.isValid());
4171   DeclContext *DC;
4172   if (!(DC = computeDeclContext(SS, false)) ||
4173       DC->isDependentContext() ||
4174       RequireCompleteDeclContext(SS, DC))
4175     return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4176 
4177   bool MemberOfUnknownSpecialization;
4178   LookupResult R(*this, NameInfo, LookupOrdinaryName);
4179   if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
4180                          /*Entering*/false, MemberOfUnknownSpecialization,
4181                          TemplateKWLoc))
4182     return ExprError();
4183 
4184   if (R.isAmbiguous())
4185     return ExprError();
4186 
4187   if (R.empty()) {
4188     Diag(NameInfo.getLoc(), diag::err_no_member)
4189       << NameInfo.getName() << DC << SS.getRange();
4190     return ExprError();
4191   }
4192 
4193   if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
4194     Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
4195       << SS.getScopeRep()
4196       << NameInfo.getName().getAsString() << SS.getRange();
4197     Diag(Temp->getLocation(), diag::note_referenced_class_template);
4198     return ExprError();
4199   }
4200 
4201   return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
4202 }
4203 
4204 /// Form a dependent template name.
4205 ///
4206 /// This action forms a dependent template name given the template
4207 /// name and its (presumably dependent) scope specifier. For
4208 /// example, given "MetaFun::template apply", the scope specifier \p
4209 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
4210 /// of the "template" keyword, and "apply" is the \p Name.
4211 TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
4212                                                   CXXScopeSpec &SS,
4213                                                   SourceLocation TemplateKWLoc,
4214                                                   const UnqualifiedId &Name,
4215                                                   ParsedType ObjectType,
4216                                                   bool EnteringContext,
4217                                                   TemplateTy &Result,
4218                                                   bool AllowInjectedClassName) {
4219   if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4220     Diag(TemplateKWLoc,
4221          getLangOpts().CPlusPlus11 ?
4222            diag::warn_cxx98_compat_template_outside_of_template :
4223            diag::ext_template_outside_of_template)
4224       << FixItHint::CreateRemoval(TemplateKWLoc);
4225 
4226   DeclContext *LookupCtx = nullptr;
4227   if (SS.isSet())
4228     LookupCtx = computeDeclContext(SS, EnteringContext);
4229   if (!LookupCtx && ObjectType)
4230     LookupCtx = computeDeclContext(ObjectType.get());
4231   if (LookupCtx) {
4232     // C++0x [temp.names]p5:
4233     //   If a name prefixed by the keyword template is not the name of
4234     //   a template, the program is ill-formed. [Note: the keyword
4235     //   template may not be applied to non-template members of class
4236     //   templates. -end note ] [ Note: as is the case with the
4237     //   typename prefix, the template prefix is allowed in cases
4238     //   where it is not strictly necessary; i.e., when the
4239     //   nested-name-specifier or the expression on the left of the ->
4240     //   or . is not dependent on a template-parameter, or the use
4241     //   does not appear in the scope of a template. -end note]
4242     //
4243     // Note: C++03 was more strict here, because it banned the use of
4244     // the "template" keyword prior to a template-name that was not a
4245     // dependent name. C++ DR468 relaxed this requirement (the
4246     // "template" keyword is now permitted). We follow the C++0x
4247     // rules, even in C++03 mode with a warning, retroactively applying the DR.
4248     bool MemberOfUnknownSpecialization;
4249     TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4250                                           ObjectType, EnteringContext, Result,
4251                                           MemberOfUnknownSpecialization);
4252     if (TNK == TNK_Non_template && MemberOfUnknownSpecialization) {
4253       // This is a dependent template. Handle it below.
4254     } else if (TNK == TNK_Non_template) {
4255       // Do the lookup again to determine if this is a "nothing found" case or
4256       // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4257       // need to do this.
4258       DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
4259       LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
4260                      LookupOrdinaryName);
4261       bool MOUS;
4262       if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext,
4263                               MOUS, TemplateKWLoc))
4264         Diag(Name.getBeginLoc(), diag::err_no_member)
4265             << DNI.getName() << LookupCtx << SS.getRange();
4266       return TNK_Non_template;
4267     } else {
4268       // We found something; return it.
4269       auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
4270       if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
4271           Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4272           Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4273         // C++14 [class.qual]p2:
4274         //   In a lookup in which function names are not ignored and the
4275         //   nested-name-specifier nominates a class C, if the name specified
4276         //   [...] is the injected-class-name of C, [...] the name is instead
4277         //   considered to name the constructor
4278         //
4279         // We don't get here if naming the constructor would be valid, so we
4280         // just reject immediately and recover by treating the
4281         // injected-class-name as naming the template.
4282         Diag(Name.getBeginLoc(),
4283              diag::ext_out_of_line_qualified_id_type_names_constructor)
4284             << Name.Identifier
4285             << 0 /*injected-class-name used as template name*/
4286             << 1 /*'template' keyword was used*/;
4287       }
4288       return TNK;
4289     }
4290   }
4291 
4292   NestedNameSpecifier *Qualifier = SS.getScopeRep();
4293 
4294   switch (Name.getKind()) {
4295   case UnqualifiedIdKind::IK_Identifier:
4296     Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4297                                                               Name.Identifier));
4298     return TNK_Dependent_template_name;
4299 
4300   case UnqualifiedIdKind::IK_OperatorFunctionId:
4301     Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4302                                              Name.OperatorFunctionId.Operator));
4303     return TNK_Function_template;
4304 
4305   case UnqualifiedIdKind::IK_LiteralOperatorId:
4306     llvm_unreachable("literal operator id cannot have a dependent scope");
4307 
4308   default:
4309     break;
4310   }
4311 
4312   Diag(Name.getBeginLoc(), diag::err_template_kw_refers_to_non_template)
4313       << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4314       << TemplateKWLoc;
4315   return TNK_Non_template;
4316 }
4317 
4318 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
4319                                      TemplateArgumentLoc &AL,
4320                           SmallVectorImpl<TemplateArgument> &Converted) {
4321   const TemplateArgument &Arg = AL.getArgument();
4322   QualType ArgType;
4323   TypeSourceInfo *TSI = nullptr;
4324 
4325   // Check template type parameter.
4326   switch(Arg.getKind()) {
4327   case TemplateArgument::Type:
4328     // C++ [temp.arg.type]p1:
4329     //   A template-argument for a template-parameter which is a
4330     //   type shall be a type-id.
4331     ArgType = Arg.getAsType();
4332     TSI = AL.getTypeSourceInfo();
4333     break;
4334   case TemplateArgument::Template:
4335   case TemplateArgument::TemplateExpansion: {
4336     // We have a template type parameter but the template argument
4337     // is a template without any arguments.
4338     SourceRange SR = AL.getSourceRange();
4339     TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
4340     diagnoseMissingTemplateArguments(Name, SR.getEnd());
4341     return true;
4342   }
4343   case TemplateArgument::Expression: {
4344     // We have a template type parameter but the template argument is an
4345     // expression; see if maybe it is missing the "typename" keyword.
4346     CXXScopeSpec SS;
4347     DeclarationNameInfo NameInfo;
4348 
4349     if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
4350       SS.Adopt(ArgExpr->getQualifierLoc());
4351       NameInfo = ArgExpr->getNameInfo();
4352     } else if (DependentScopeDeclRefExpr *ArgExpr =
4353                dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4354       SS.Adopt(ArgExpr->getQualifierLoc());
4355       NameInfo = ArgExpr->getNameInfo();
4356     } else if (CXXDependentScopeMemberExpr *ArgExpr =
4357                dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
4358       if (ArgExpr->isImplicitAccess()) {
4359         SS.Adopt(ArgExpr->getQualifierLoc());
4360         NameInfo = ArgExpr->getMemberNameInfo();
4361       }
4362     }
4363 
4364     if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
4365       LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4366       LookupParsedName(Result, CurScope, &SS);
4367 
4368       if (Result.getAsSingle<TypeDecl>() ||
4369           Result.getResultKind() ==
4370               LookupResult::NotFoundInCurrentInstantiation) {
4371         // Suggest that the user add 'typename' before the NNS.
4372         SourceLocation Loc = AL.getSourceRange().getBegin();
4373         Diag(Loc, getLangOpts().MSVCCompat
4374                       ? diag::ext_ms_template_type_arg_missing_typename
4375                       : diag::err_template_arg_must_be_type_suggest)
4376             << FixItHint::CreateInsertion(Loc, "typename ");
4377         Diag(Param->getLocation(), diag::note_template_param_here);
4378 
4379         // Recover by synthesizing a type using the location information that we
4380         // already have.
4381         ArgType =
4382             Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4383         TypeLocBuilder TLB;
4384         DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4385         TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4386         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4387         TL.setNameLoc(NameInfo.getLoc());
4388         TSI = TLB.getTypeSourceInfo(Context, ArgType);
4389 
4390         // Overwrite our input TemplateArgumentLoc so that we can recover
4391         // properly.
4392         AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4393                                  TemplateArgumentLocInfo(TSI));
4394 
4395         break;
4396       }
4397     }
4398     // fallthrough
4399     LLVM_FALLTHROUGH;
4400   }
4401   default: {
4402     // We have a template type parameter but the template argument
4403     // is not a type.
4404     SourceRange SR = AL.getSourceRange();
4405     Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4406     Diag(Param->getLocation(), diag::note_template_param_here);
4407 
4408     return true;
4409   }
4410   }
4411 
4412   if (CheckTemplateArgument(Param, TSI))
4413     return true;
4414 
4415   // Add the converted template type argument.
4416   ArgType = Context.getCanonicalType(ArgType);
4417 
4418   // Objective-C ARC:
4419   //   If an explicitly-specified template argument type is a lifetime type
4420   //   with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4421   if (getLangOpts().ObjCAutoRefCount &&
4422       ArgType->isObjCLifetimeType() &&
4423       !ArgType.getObjCLifetime()) {
4424     Qualifiers Qs;
4425     Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4426     ArgType = Context.getQualifiedType(ArgType, Qs);
4427   }
4428 
4429   Converted.push_back(TemplateArgument(ArgType));
4430   return false;
4431 }
4432 
4433 /// Substitute template arguments into the default template argument for
4434 /// the given template type parameter.
4435 ///
4436 /// \param SemaRef the semantic analysis object for which we are performing
4437 /// the substitution.
4438 ///
4439 /// \param Template the template that we are synthesizing template arguments
4440 /// for.
4441 ///
4442 /// \param TemplateLoc the location of the template name that started the
4443 /// template-id we are checking.
4444 ///
4445 /// \param RAngleLoc the location of the right angle bracket ('>') that
4446 /// terminates the template-id.
4447 ///
4448 /// \param Param the template template parameter whose default we are
4449 /// substituting into.
4450 ///
4451 /// \param Converted the list of template arguments provided for template
4452 /// parameters that precede \p Param in the template parameter list.
4453 /// \returns the substituted template argument, or NULL if an error occurred.
4454 static TypeSourceInfo *
4455 SubstDefaultTemplateArgument(Sema &SemaRef,
4456                              TemplateDecl *Template,
4457                              SourceLocation TemplateLoc,
4458                              SourceLocation RAngleLoc,
4459                              TemplateTypeParmDecl *Param,
4460                              SmallVectorImpl<TemplateArgument> &Converted) {
4461   TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
4462 
4463   // If the argument type is dependent, instantiate it now based
4464   // on the previously-computed template arguments.
4465   if (ArgType->getType()->isInstantiationDependentType()) {
4466     Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4467                                      Param, Template, Converted,
4468                                      SourceRange(TemplateLoc, RAngleLoc));
4469     if (Inst.isInvalid())
4470       return nullptr;
4471 
4472     TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4473 
4474     // Only substitute for the innermost template argument list.
4475     MultiLevelTemplateArgumentList TemplateArgLists;
4476     TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4477     for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4478       TemplateArgLists.addOuterTemplateArguments(None);
4479 
4480     Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4481     ArgType =
4482         SemaRef.SubstType(ArgType, TemplateArgLists,
4483                           Param->getDefaultArgumentLoc(), Param->getDeclName());
4484   }
4485 
4486   return ArgType;
4487 }
4488 
4489 /// Substitute template arguments into the default template argument for
4490 /// the given non-type template parameter.
4491 ///
4492 /// \param SemaRef the semantic analysis object for which we are performing
4493 /// the substitution.
4494 ///
4495 /// \param Template the template that we are synthesizing template arguments
4496 /// for.
4497 ///
4498 /// \param TemplateLoc the location of the template name that started the
4499 /// template-id we are checking.
4500 ///
4501 /// \param RAngleLoc the location of the right angle bracket ('>') that
4502 /// terminates the template-id.
4503 ///
4504 /// \param Param the non-type template parameter whose default we are
4505 /// substituting into.
4506 ///
4507 /// \param Converted the list of template arguments provided for template
4508 /// parameters that precede \p Param in the template parameter list.
4509 ///
4510 /// \returns the substituted template argument, or NULL if an error occurred.
4511 static ExprResult
4512 SubstDefaultTemplateArgument(Sema &SemaRef,
4513                              TemplateDecl *Template,
4514                              SourceLocation TemplateLoc,
4515                              SourceLocation RAngleLoc,
4516                              NonTypeTemplateParmDecl *Param,
4517                         SmallVectorImpl<TemplateArgument> &Converted) {
4518   Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4519                                    Param, Template, Converted,
4520                                    SourceRange(TemplateLoc, RAngleLoc));
4521   if (Inst.isInvalid())
4522     return ExprError();
4523 
4524   TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4525 
4526   // Only substitute for the innermost template argument list.
4527   MultiLevelTemplateArgumentList TemplateArgLists;
4528   TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4529   for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4530     TemplateArgLists.addOuterTemplateArguments(None);
4531 
4532   EnterExpressionEvaluationContext ConstantEvaluated(
4533       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4534   return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
4535 }
4536 
4537 /// Substitute template arguments into the default template argument for
4538 /// the given template template parameter.
4539 ///
4540 /// \param SemaRef the semantic analysis object for which we are performing
4541 /// the substitution.
4542 ///
4543 /// \param Template the template that we are synthesizing template arguments
4544 /// for.
4545 ///
4546 /// \param TemplateLoc the location of the template name that started the
4547 /// template-id we are checking.
4548 ///
4549 /// \param RAngleLoc the location of the right angle bracket ('>') that
4550 /// terminates the template-id.
4551 ///
4552 /// \param Param the template template parameter whose default we are
4553 /// substituting into.
4554 ///
4555 /// \param Converted the list of template arguments provided for template
4556 /// parameters that precede \p Param in the template parameter list.
4557 ///
4558 /// \param QualifierLoc Will be set to the nested-name-specifier (with
4559 /// source-location information) that precedes the template name.
4560 ///
4561 /// \returns the substituted template argument, or NULL if an error occurred.
4562 static TemplateName
4563 SubstDefaultTemplateArgument(Sema &SemaRef,
4564                              TemplateDecl *Template,
4565                              SourceLocation TemplateLoc,
4566                              SourceLocation RAngleLoc,
4567                              TemplateTemplateParmDecl *Param,
4568                        SmallVectorImpl<TemplateArgument> &Converted,
4569                              NestedNameSpecifierLoc &QualifierLoc) {
4570   Sema::InstantiatingTemplate Inst(
4571       SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4572       SourceRange(TemplateLoc, RAngleLoc));
4573   if (Inst.isInvalid())
4574     return TemplateName();
4575 
4576   TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4577 
4578   // Only substitute for the innermost template argument list.
4579   MultiLevelTemplateArgumentList TemplateArgLists;
4580   TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4581   for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4582     TemplateArgLists.addOuterTemplateArguments(None);
4583 
4584   Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4585   // Substitute into the nested-name-specifier first,
4586   QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
4587   if (QualifierLoc) {
4588     QualifierLoc =
4589         SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
4590     if (!QualifierLoc)
4591       return TemplateName();
4592   }
4593 
4594   return SemaRef.SubstTemplateName(
4595              QualifierLoc,
4596              Param->getDefaultArgument().getArgument().getAsTemplate(),
4597              Param->getDefaultArgument().getTemplateNameLoc(),
4598              TemplateArgLists);
4599 }
4600 
4601 /// If the given template parameter has a default template
4602 /// argument, substitute into that default template argument and
4603 /// return the corresponding template argument.
4604 TemplateArgumentLoc
4605 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4606                                               SourceLocation TemplateLoc,
4607                                               SourceLocation RAngleLoc,
4608                                               Decl *Param,
4609                                               SmallVectorImpl<TemplateArgument>
4610                                                 &Converted,
4611                                               bool &HasDefaultArg) {
4612   HasDefaultArg = false;
4613 
4614   if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
4615     if (!hasVisibleDefaultArgument(TypeParm))
4616       return TemplateArgumentLoc();
4617 
4618     HasDefaultArg = true;
4619     TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
4620                                                       TemplateLoc,
4621                                                       RAngleLoc,
4622                                                       TypeParm,
4623                                                       Converted);
4624     if (DI)
4625       return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4626 
4627     return TemplateArgumentLoc();
4628   }
4629 
4630   if (NonTypeTemplateParmDecl *NonTypeParm
4631         = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4632     if (!hasVisibleDefaultArgument(NonTypeParm))
4633       return TemplateArgumentLoc();
4634 
4635     HasDefaultArg = true;
4636     ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
4637                                                   TemplateLoc,
4638                                                   RAngleLoc,
4639                                                   NonTypeParm,
4640                                                   Converted);
4641     if (Arg.isInvalid())
4642       return TemplateArgumentLoc();
4643 
4644     Expr *ArgE = Arg.getAs<Expr>();
4645     return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4646   }
4647 
4648   TemplateTemplateParmDecl *TempTempParm
4649     = cast<TemplateTemplateParmDecl>(Param);
4650   if (!hasVisibleDefaultArgument(TempTempParm))
4651     return TemplateArgumentLoc();
4652 
4653   HasDefaultArg = true;
4654   NestedNameSpecifierLoc QualifierLoc;
4655   TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
4656                                                     TemplateLoc,
4657                                                     RAngleLoc,
4658                                                     TempTempParm,
4659                                                     Converted,
4660                                                     QualifierLoc);
4661   if (TName.isNull())
4662     return TemplateArgumentLoc();
4663 
4664   return TemplateArgumentLoc(TemplateArgument(TName),
4665                 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
4666                 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4667 }
4668 
4669 /// Convert a template-argument that we parsed as a type into a template, if
4670 /// possible. C++ permits injected-class-names to perform dual service as
4671 /// template template arguments and as template type arguments.
4672 static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4673   // Extract and step over any surrounding nested-name-specifier.
4674   NestedNameSpecifierLoc QualLoc;
4675   if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4676     if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4677       return TemplateArgumentLoc();
4678 
4679     QualLoc = ETLoc.getQualifierLoc();
4680     TLoc = ETLoc.getNamedTypeLoc();
4681   }
4682 
4683   // If this type was written as an injected-class-name, it can be used as a
4684   // template template argument.
4685   if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4686     return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4687                                QualLoc, InjLoc.getNameLoc());
4688 
4689   // If this type was written as an injected-class-name, it may have been
4690   // converted to a RecordType during instantiation. If the RecordType is
4691   // *not* wrapped in a TemplateSpecializationType and denotes a class
4692   // template specialization, it must have come from an injected-class-name.
4693   if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4694     if (auto *CTSD =
4695             dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4696       return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4697                                  QualLoc, RecLoc.getNameLoc());
4698 
4699   return TemplateArgumentLoc();
4700 }
4701 
4702 /// Check that the given template argument corresponds to the given
4703 /// template parameter.
4704 ///
4705 /// \param Param The template parameter against which the argument will be
4706 /// checked.
4707 ///
4708 /// \param Arg The template argument, which may be updated due to conversions.
4709 ///
4710 /// \param Template The template in which the template argument resides.
4711 ///
4712 /// \param TemplateLoc The location of the template name for the template
4713 /// whose argument list we're matching.
4714 ///
4715 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
4716 /// the template argument list.
4717 ///
4718 /// \param ArgumentPackIndex The index into the argument pack where this
4719 /// argument will be placed. Only valid if the parameter is a parameter pack.
4720 ///
4721 /// \param Converted The checked, converted argument will be added to the
4722 /// end of this small vector.
4723 ///
4724 /// \param CTAK Describes how we arrived at this particular template argument:
4725 /// explicitly written, deduced, etc.
4726 ///
4727 /// \returns true on error, false otherwise.
4728 bool Sema::CheckTemplateArgument(NamedDecl *Param,
4729                                  TemplateArgumentLoc &Arg,
4730                                  NamedDecl *Template,
4731                                  SourceLocation TemplateLoc,
4732                                  SourceLocation RAngleLoc,
4733                                  unsigned ArgumentPackIndex,
4734                             SmallVectorImpl<TemplateArgument> &Converted,
4735                                  CheckTemplateArgumentKind CTAK) {
4736   // Check template type parameters.
4737   if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4738     return CheckTemplateTypeArgument(TTP, Arg, Converted);
4739 
4740   // Check non-type template parameters.
4741   if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4742     // Do substitution on the type of the non-type template parameter
4743     // with the template arguments we've seen thus far.  But if the
4744     // template has a dependent context then we cannot substitute yet.
4745     QualType NTTPType = NTTP->getType();
4746     if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4747       NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
4748 
4749     // FIXME: Do we need to substitute into parameters here if they're
4750     // instantiation-dependent but not dependent?
4751     if (NTTPType->isDependentType() &&
4752         !isa<TemplateTemplateParmDecl>(Template) &&
4753         !Template->getDeclContext()->isDependentContext()) {
4754       // Do substitution on the type of the non-type template parameter.
4755       InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4756                                  NTTP, Converted,
4757                                  SourceRange(TemplateLoc, RAngleLoc));
4758       if (Inst.isInvalid())
4759         return true;
4760 
4761       TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
4762                                         Converted);
4763       NTTPType = SubstType(NTTPType,
4764                            MultiLevelTemplateArgumentList(TemplateArgs),
4765                            NTTP->getLocation(),
4766                            NTTP->getDeclName());
4767       // If that worked, check the non-type template parameter type
4768       // for validity.
4769       if (!NTTPType.isNull())
4770         NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4771                                                      NTTP->getLocation());
4772       if (NTTPType.isNull())
4773         return true;
4774     }
4775 
4776     switch (Arg.getArgument().getKind()) {
4777     case TemplateArgument::Null:
4778       llvm_unreachable("Should never see a NULL template argument here");
4779 
4780     case TemplateArgument::Expression: {
4781       TemplateArgument Result;
4782       unsigned CurSFINAEErrors = NumSFINAEErrors;
4783       ExprResult Res =
4784         CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4785                               Result, CTAK);
4786       if (Res.isInvalid())
4787         return true;
4788       // If the current template argument causes an error, give up now.
4789       if (CurSFINAEErrors < NumSFINAEErrors)
4790         return true;
4791 
4792       // If the resulting expression is new, then use it in place of the
4793       // old expression in the template argument.
4794       if (Res.get() != Arg.getArgument().getAsExpr()) {
4795         TemplateArgument TA(Res.get());
4796         Arg = TemplateArgumentLoc(TA, Res.get());
4797       }
4798 
4799       Converted.push_back(Result);
4800       break;
4801     }
4802 
4803     case TemplateArgument::Declaration:
4804     case TemplateArgument::Integral:
4805     case TemplateArgument::NullPtr:
4806       // We've already checked this template argument, so just copy
4807       // it to the list of converted arguments.
4808       Converted.push_back(Arg.getArgument());
4809       break;
4810 
4811     case TemplateArgument::Template:
4812     case TemplateArgument::TemplateExpansion:
4813       // We were given a template template argument. It may not be ill-formed;
4814       // see below.
4815       if (DependentTemplateName *DTN
4816             = Arg.getArgument().getAsTemplateOrTemplatePattern()
4817                                               .getAsDependentTemplateName()) {
4818         // We have a template argument such as \c T::template X, which we
4819         // parsed as a template template argument. However, since we now
4820         // know that we need a non-type template argument, convert this
4821         // template name into an expression.
4822 
4823         DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4824                                      Arg.getTemplateNameLoc());
4825 
4826         CXXScopeSpec SS;
4827         SS.Adopt(Arg.getTemplateQualifierLoc());
4828         // FIXME: the template-template arg was a DependentTemplateName,
4829         // so it was provided with a template keyword. However, its source
4830         // location is not stored in the template argument structure.
4831         SourceLocation TemplateKWLoc;
4832         ExprResult E = DependentScopeDeclRefExpr::Create(
4833             Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4834             nullptr);
4835 
4836         // If we parsed the template argument as a pack expansion, create a
4837         // pack expansion expression.
4838         if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
4839           E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
4840           if (E.isInvalid())
4841             return true;
4842         }
4843 
4844         TemplateArgument Result;
4845         E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
4846         if (E.isInvalid())
4847           return true;
4848 
4849         Converted.push_back(Result);
4850         break;
4851       }
4852 
4853       // We have a template argument that actually does refer to a class
4854       // template, alias template, or template template parameter, and
4855       // therefore cannot be a non-type template argument.
4856       Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4857         << Arg.getSourceRange();
4858 
4859       Diag(Param->getLocation(), diag::note_template_param_here);
4860       return true;
4861 
4862     case TemplateArgument::Type: {
4863       // We have a non-type template parameter but the template
4864       // argument is a type.
4865 
4866       // C++ [temp.arg]p2:
4867       //   In a template-argument, an ambiguity between a type-id and
4868       //   an expression is resolved to a type-id, regardless of the
4869       //   form of the corresponding template-parameter.
4870       //
4871       // We warn specifically about this case, since it can be rather
4872       // confusing for users.
4873       QualType T = Arg.getArgument().getAsType();
4874       SourceRange SR = Arg.getSourceRange();
4875       if (T->isFunctionType())
4876         Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
4877       else
4878         Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4879       Diag(Param->getLocation(), diag::note_template_param_here);
4880       return true;
4881     }
4882 
4883     case TemplateArgument::Pack:
4884       llvm_unreachable("Caller must expand template argument packs");
4885     }
4886 
4887     return false;
4888   }
4889 
4890 
4891   // Check template template parameters.
4892   TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
4893 
4894   TemplateParameterList *Params = TempParm->getTemplateParameters();
4895   if (TempParm->isExpandedParameterPack())
4896     Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
4897 
4898   // Substitute into the template parameter list of the template
4899   // template parameter, since previously-supplied template arguments
4900   // may appear within the template template parameter.
4901   //
4902   // FIXME: Skip this if the parameters aren't instantiation-dependent.
4903   {
4904     // Set up a template instantiation context.
4905     LocalInstantiationScope Scope(*this);
4906     InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4907                                TempParm, Converted,
4908                                SourceRange(TemplateLoc, RAngleLoc));
4909     if (Inst.isInvalid())
4910       return true;
4911 
4912     TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4913     Params = SubstTemplateParams(Params, CurContext,
4914                                  MultiLevelTemplateArgumentList(TemplateArgs));
4915     if (!Params)
4916       return true;
4917   }
4918 
4919   // C++1z [temp.local]p1: (DR1004)
4920   //   When [the injected-class-name] is used [...] as a template-argument for
4921   //   a template template-parameter [...] it refers to the class template
4922   //   itself.
4923   if (Arg.getArgument().getKind() == TemplateArgument::Type) {
4924     TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
4925         Arg.getTypeSourceInfo()->getTypeLoc());
4926     if (!ConvertedArg.getArgument().isNull())
4927       Arg = ConvertedArg;
4928   }
4929 
4930   switch (Arg.getArgument().getKind()) {
4931   case TemplateArgument::Null:
4932     llvm_unreachable("Should never see a NULL template argument here");
4933 
4934   case TemplateArgument::Template:
4935   case TemplateArgument::TemplateExpansion:
4936     if (CheckTemplateTemplateArgument(Params, Arg))
4937       return true;
4938 
4939     Converted.push_back(Arg.getArgument());
4940     break;
4941 
4942   case TemplateArgument::Expression:
4943   case TemplateArgument::Type:
4944     // We have a template template parameter but the template
4945     // argument does not refer to a template.
4946     Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
4947       << getLangOpts().CPlusPlus11;
4948     return true;
4949 
4950   case TemplateArgument::Declaration:
4951     llvm_unreachable("Declaration argument with template template parameter");
4952   case TemplateArgument::Integral:
4953     llvm_unreachable("Integral argument with template template parameter");
4954   case TemplateArgument::NullPtr:
4955     llvm_unreachable("Null pointer argument with template template parameter");
4956 
4957   case TemplateArgument::Pack:
4958     llvm_unreachable("Caller must expand template argument packs");
4959   }
4960 
4961   return false;
4962 }
4963 
4964 /// Check whether the template parameter is a pack expansion, and if so,
4965 /// determine the number of parameters produced by that expansion. For instance:
4966 ///
4967 /// \code
4968 /// template<typename ...Ts> struct A {
4969 ///   template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
4970 /// };
4971 /// \endcode
4972 ///
4973 /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
4974 /// is not a pack expansion, so returns an empty Optional.
4975 static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
4976   if (NonTypeTemplateParmDecl *NTTP
4977         = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4978     if (NTTP->isExpandedParameterPack())
4979       return NTTP->getNumExpansionTypes();
4980   }
4981 
4982   if (TemplateTemplateParmDecl *TTP
4983         = dyn_cast<TemplateTemplateParmDecl>(Param)) {
4984     if (TTP->isExpandedParameterPack())
4985       return TTP->getNumExpansionTemplateParameters();
4986   }
4987 
4988   return None;
4989 }
4990 
4991 /// Diagnose a missing template argument.
4992 template<typename TemplateParmDecl>
4993 static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
4994                                     TemplateDecl *TD,
4995                                     const TemplateParmDecl *D,
4996                                     TemplateArgumentListInfo &Args) {
4997   // Dig out the most recent declaration of the template parameter; there may be
4998   // declarations of the template that are more recent than TD.
4999   D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5000                                  ->getTemplateParameters()
5001                                  ->getParam(D->getIndex()));
5002 
5003   // If there's a default argument that's not visible, diagnose that we're
5004   // missing a module import.
5005   llvm::SmallVector<Module*, 8> Modules;
5006   if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
5007     S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5008                             D->getDefaultArgumentLoc(), Modules,
5009                             Sema::MissingImportKind::DefaultArgument,
5010                             /*Recover*/true);
5011     return true;
5012   }
5013 
5014   // FIXME: If there's a more recent default argument that *is* visible,
5015   // diagnose that it was declared too late.
5016 
5017   TemplateParameterList *Params = TD->getTemplateParameters();
5018 
5019   S.Diag(Loc, diag::err_template_arg_list_different_arity)
5020     << /*not enough args*/0
5021     << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
5022     << TD;
5023   S.Diag(TD->getLocation(), diag::note_template_decl_here)
5024     << Params->getSourceRange();
5025   return true;
5026 }
5027 
5028 /// Check that the given template argument list is well-formed
5029 /// for specializing the given template.
5030 bool Sema::CheckTemplateArgumentList(
5031     TemplateDecl *Template, SourceLocation TemplateLoc,
5032     TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
5033     SmallVectorImpl<TemplateArgument> &Converted,
5034     bool UpdateArgsWithConversions) {
5035   // Make a copy of the template arguments for processing.  Only make the
5036   // changes at the end when successful in matching the arguments to the
5037   // template.
5038   TemplateArgumentListInfo NewArgs = TemplateArgs;
5039 
5040   // Make sure we get the template parameter list from the most
5041   // recentdeclaration, since that is the only one that has is guaranteed to
5042   // have all the default template argument information.
5043   TemplateParameterList *Params =
5044       cast<TemplateDecl>(Template->getMostRecentDecl())
5045           ->getTemplateParameters();
5046 
5047   SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5048 
5049   // C++ [temp.arg]p1:
5050   //   [...] The type and form of each template-argument specified in
5051   //   a template-id shall match the type and form specified for the
5052   //   corresponding parameter declared by the template in its
5053   //   template-parameter-list.
5054   bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5055   SmallVector<TemplateArgument, 2> ArgumentPack;
5056   unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5057   LocalInstantiationScope InstScope(*this, true);
5058   for (TemplateParameterList::iterator Param = Params->begin(),
5059                                        ParamEnd = Params->end();
5060        Param != ParamEnd; /* increment in loop */) {
5061     // If we have an expanded parameter pack, make sure we don't have too
5062     // many arguments.
5063     if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
5064       if (*Expansions == ArgumentPack.size()) {
5065         // We're done with this parameter pack. Pack up its arguments and add
5066         // them to the list.
5067         Converted.push_back(
5068             TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5069         ArgumentPack.clear();
5070 
5071         // This argument is assigned to the next parameter.
5072         ++Param;
5073         continue;
5074       } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5075         // Not enough arguments for this parameter pack.
5076         Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5077           << /*not enough args*/0
5078           << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5079           << Template;
5080         Diag(Template->getLocation(), diag::note_template_decl_here)
5081           << Params->getSourceRange();
5082         return true;
5083       }
5084     }
5085 
5086     if (ArgIdx < NumArgs) {
5087       // Check the template argument we were given.
5088       if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
5089                                 TemplateLoc, RAngleLoc,
5090                                 ArgumentPack.size(), Converted))
5091         return true;
5092 
5093       bool PackExpansionIntoNonPack =
5094           NewArgs[ArgIdx].getArgument().isPackExpansion() &&
5095           (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5096       if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
5097         // Core issue 1430: we have a pack expansion as an argument to an
5098         // alias template, and it's not part of a parameter pack. This
5099         // can't be canonicalized, so reject it now.
5100         Diag(NewArgs[ArgIdx].getLocation(),
5101              diag::err_alias_template_expansion_into_fixed_list)
5102           << NewArgs[ArgIdx].getSourceRange();
5103         Diag((*Param)->getLocation(), diag::note_template_param_here);
5104         return true;
5105       }
5106 
5107       // We're now done with this argument.
5108       ++ArgIdx;
5109 
5110       if ((*Param)->isTemplateParameterPack()) {
5111         // The template parameter was a template parameter pack, so take the
5112         // deduced argument and place it on the argument pack. Note that we
5113         // stay on the same template parameter so that we can deduce more
5114         // arguments.
5115         ArgumentPack.push_back(Converted.pop_back_val());
5116       } else {
5117         // Move to the next template parameter.
5118         ++Param;
5119       }
5120 
5121       // If we just saw a pack expansion into a non-pack, then directly convert
5122       // the remaining arguments, because we don't know what parameters they'll
5123       // match up with.
5124       if (PackExpansionIntoNonPack) {
5125         if (!ArgumentPack.empty()) {
5126           // If we were part way through filling in an expanded parameter pack,
5127           // fall back to just producing individual arguments.
5128           Converted.insert(Converted.end(),
5129                            ArgumentPack.begin(), ArgumentPack.end());
5130           ArgumentPack.clear();
5131         }
5132 
5133         while (ArgIdx < NumArgs) {
5134           Converted.push_back(NewArgs[ArgIdx].getArgument());
5135           ++ArgIdx;
5136         }
5137 
5138         return false;
5139       }
5140 
5141       continue;
5142     }
5143 
5144     // If we're checking a partial template argument list, we're done.
5145     if (PartialTemplateArgs) {
5146       if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
5147         Converted.push_back(
5148             TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5149 
5150       return false;
5151     }
5152 
5153     // If we have a template parameter pack with no more corresponding
5154     // arguments, just break out now and we'll fill in the argument pack below.
5155     if ((*Param)->isTemplateParameterPack()) {
5156       assert(!getExpandedPackSize(*Param) &&
5157              "Should have dealt with this already");
5158 
5159       // A non-expanded parameter pack before the end of the parameter list
5160       // only occurs for an ill-formed template parameter list, unless we've
5161       // got a partial argument list for a function template, so just bail out.
5162       if (Param + 1 != ParamEnd)
5163         return true;
5164 
5165       Converted.push_back(
5166           TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5167       ArgumentPack.clear();
5168 
5169       ++Param;
5170       continue;
5171     }
5172 
5173     // Check whether we have a default argument.
5174     TemplateArgumentLoc Arg;
5175 
5176     // Retrieve the default template argument from the template
5177     // parameter. For each kind of template parameter, we substitute the
5178     // template arguments provided thus far and any "outer" template arguments
5179     // (when the template parameter was part of a nested template) into
5180     // the default argument.
5181     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
5182       if (!hasVisibleDefaultArgument(TTP))
5183         return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5184                                        NewArgs);
5185 
5186       TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
5187                                                              Template,
5188                                                              TemplateLoc,
5189                                                              RAngleLoc,
5190                                                              TTP,
5191                                                              Converted);
5192       if (!ArgType)
5193         return true;
5194 
5195       Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
5196                                 ArgType);
5197     } else if (NonTypeTemplateParmDecl *NTTP
5198                  = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
5199       if (!hasVisibleDefaultArgument(NTTP))
5200         return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5201                                        NewArgs);
5202 
5203       ExprResult E = SubstDefaultTemplateArgument(*this, Template,
5204                                                               TemplateLoc,
5205                                                               RAngleLoc,
5206                                                               NTTP,
5207                                                               Converted);
5208       if (E.isInvalid())
5209         return true;
5210 
5211       Expr *Ex = E.getAs<Expr>();
5212       Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
5213     } else {
5214       TemplateTemplateParmDecl *TempParm
5215         = cast<TemplateTemplateParmDecl>(*Param);
5216 
5217       if (!hasVisibleDefaultArgument(TempParm))
5218         return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
5219                                        NewArgs);
5220 
5221       NestedNameSpecifierLoc QualifierLoc;
5222       TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
5223                                                        TemplateLoc,
5224                                                        RAngleLoc,
5225                                                        TempParm,
5226                                                        Converted,
5227                                                        QualifierLoc);
5228       if (Name.isNull())
5229         return true;
5230 
5231       Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
5232                            TempParm->getDefaultArgument().getTemplateNameLoc());
5233     }
5234 
5235     // Introduce an instantiation record that describes where we are using
5236     // the default template argument. We're not actually instantiating a
5237     // template here, we just create this object to put a note into the
5238     // context stack.
5239     InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
5240                                SourceRange(TemplateLoc, RAngleLoc));
5241     if (Inst.isInvalid())
5242       return true;
5243 
5244     // Check the default template argument.
5245     if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
5246                               RAngleLoc, 0, Converted))
5247       return true;
5248 
5249     // Core issue 150 (assumed resolution): if this is a template template
5250     // parameter, keep track of the default template arguments from the
5251     // template definition.
5252     if (isTemplateTemplateParameter)
5253       NewArgs.addArgument(Arg);
5254 
5255     // Move to the next template parameter and argument.
5256     ++Param;
5257     ++ArgIdx;
5258   }
5259 
5260   // If we're performing a partial argument substitution, allow any trailing
5261   // pack expansions; they might be empty. This can happen even if
5262   // PartialTemplateArgs is false (the list of arguments is complete but
5263   // still dependent).
5264   if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5265       CurrentInstantiationScope->getPartiallySubstitutedPack()) {
5266     while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5267       Converted.push_back(NewArgs[ArgIdx++].getArgument());
5268   }
5269 
5270   // If we have any leftover arguments, then there were too many arguments.
5271   // Complain and fail.
5272   if (ArgIdx < NumArgs) {
5273     Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5274         << /*too many args*/1
5275         << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5276         << Template
5277         << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5278     Diag(Template->getLocation(), diag::note_template_decl_here)
5279         << Params->getSourceRange();
5280     return true;
5281   }
5282 
5283   // No problems found with the new argument list, propagate changes back
5284   // to caller.
5285   if (UpdateArgsWithConversions)
5286     TemplateArgs = std::move(NewArgs);
5287 
5288   return false;
5289 }
5290 
5291 namespace {
5292   class UnnamedLocalNoLinkageFinder
5293     : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
5294   {
5295     Sema &S;
5296     SourceRange SR;
5297 
5298     typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
5299 
5300   public:
5301     UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5302 
5303     bool Visit(QualType T) {
5304       return T.isNull() ? false : inherited::Visit(T.getTypePtr());
5305     }
5306 
5307 #define TYPE(Class, Parent) \
5308     bool Visit##Class##Type(const Class##Type *);
5309 #define ABSTRACT_TYPE(Class, Parent) \
5310     bool Visit##Class##Type(const Class##Type *) { return false; }
5311 #define NON_CANONICAL_TYPE(Class, Parent) \
5312     bool Visit##Class##Type(const Class##Type *) { return false; }
5313 #include "clang/AST/TypeNodes.def"
5314 
5315     bool VisitTagDecl(const TagDecl *Tag);
5316     bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5317   };
5318 } // end anonymous namespace
5319 
5320 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
5321   return false;
5322 }
5323 
5324 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5325   return Visit(T->getElementType());
5326 }
5327 
5328 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
5329   return Visit(T->getPointeeType());
5330 }
5331 
5332 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
5333                                                     const BlockPointerType* T) {
5334   return Visit(T->getPointeeType());
5335 }
5336 
5337 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
5338                                                 const LValueReferenceType* T) {
5339   return Visit(T->getPointeeType());
5340 }
5341 
5342 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
5343                                                 const RValueReferenceType* T) {
5344   return Visit(T->getPointeeType());
5345 }
5346 
5347 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
5348                                                   const MemberPointerType* T) {
5349   return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5350 }
5351 
5352 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
5353                                                   const ConstantArrayType* T) {
5354   return Visit(T->getElementType());
5355 }
5356 
5357 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
5358                                                  const IncompleteArrayType* T) {
5359   return Visit(T->getElementType());
5360 }
5361 
5362 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
5363                                                    const VariableArrayType* T) {
5364   return Visit(T->getElementType());
5365 }
5366 
5367 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
5368                                             const DependentSizedArrayType* T) {
5369   return Visit(T->getElementType());
5370 }
5371 
5372 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
5373                                          const DependentSizedExtVectorType* T) {
5374   return Visit(T->getElementType());
5375 }
5376 
5377 bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5378     const DependentAddressSpaceType *T) {
5379   return Visit(T->getPointeeType());
5380 }
5381 
5382 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5383   return Visit(T->getElementType());
5384 }
5385 
5386 bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
5387     const DependentVectorType *T) {
5388   return Visit(T->getElementType());
5389 }
5390 
5391 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5392   return Visit(T->getElementType());
5393 }
5394 
5395 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5396                                                   const FunctionProtoType* T) {
5397   for (const auto &A : T->param_types()) {
5398     if (Visit(A))
5399       return true;
5400   }
5401 
5402   return Visit(T->getReturnType());
5403 }
5404 
5405 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5406                                                const FunctionNoProtoType* T) {
5407   return Visit(T->getReturnType());
5408 }
5409 
5410 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5411                                                   const UnresolvedUsingType*) {
5412   return false;
5413 }
5414 
5415 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5416   return false;
5417 }
5418 
5419 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5420   return Visit(T->getUnderlyingType());
5421 }
5422 
5423 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5424   return false;
5425 }
5426 
5427 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5428                                                     const UnaryTransformType*) {
5429   return false;
5430 }
5431 
5432 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5433   return Visit(T->getDeducedType());
5434 }
5435 
5436 bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5437     const DeducedTemplateSpecializationType *T) {
5438   return Visit(T->getDeducedType());
5439 }
5440 
5441 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5442   return VisitTagDecl(T->getDecl());
5443 }
5444 
5445 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5446   return VisitTagDecl(T->getDecl());
5447 }
5448 
5449 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5450                                                  const TemplateTypeParmType*) {
5451   return false;
5452 }
5453 
5454 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5455                                         const SubstTemplateTypeParmPackType *) {
5456   return false;
5457 }
5458 
5459 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5460                                             const TemplateSpecializationType*) {
5461   return false;
5462 }
5463 
5464 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5465                                               const InjectedClassNameType* T) {
5466   return VisitTagDecl(T->getDecl());
5467 }
5468 
5469 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5470                                                    const DependentNameType* T) {
5471   return VisitNestedNameSpecifier(T->getQualifier());
5472 }
5473 
5474 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5475                                  const DependentTemplateSpecializationType* T) {
5476   return VisitNestedNameSpecifier(T->getQualifier());
5477 }
5478 
5479 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5480                                                    const PackExpansionType* T) {
5481   return Visit(T->getPattern());
5482 }
5483 
5484 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5485   return false;
5486 }
5487 
5488 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5489                                                    const ObjCInterfaceType *) {
5490   return false;
5491 }
5492 
5493 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5494                                                 const ObjCObjectPointerType *) {
5495   return false;
5496 }
5497 
5498 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5499   return Visit(T->getValueType());
5500 }
5501 
5502 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5503   return false;
5504 }
5505 
5506 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5507   if (Tag->getDeclContext()->isFunctionOrMethod()) {
5508     S.Diag(SR.getBegin(),
5509            S.getLangOpts().CPlusPlus11 ?
5510              diag::warn_cxx98_compat_template_arg_local_type :
5511              diag::ext_template_arg_local_type)
5512       << S.Context.getTypeDeclType(Tag) << SR;
5513     return true;
5514   }
5515 
5516   if (!Tag->hasNameForLinkage()) {
5517     S.Diag(SR.getBegin(),
5518            S.getLangOpts().CPlusPlus11 ?
5519              diag::warn_cxx98_compat_template_arg_unnamed_type :
5520              diag::ext_template_arg_unnamed_type) << SR;
5521     S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5522     return true;
5523   }
5524 
5525   return false;
5526 }
5527 
5528 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5529                                                     NestedNameSpecifier *NNS) {
5530   if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5531     return true;
5532 
5533   switch (NNS->getKind()) {
5534   case NestedNameSpecifier::Identifier:
5535   case NestedNameSpecifier::Namespace:
5536   case NestedNameSpecifier::NamespaceAlias:
5537   case NestedNameSpecifier::Global:
5538   case NestedNameSpecifier::Super:
5539     return false;
5540 
5541   case NestedNameSpecifier::TypeSpec:
5542   case NestedNameSpecifier::TypeSpecWithTemplate:
5543     return Visit(QualType(NNS->getAsType(), 0));
5544   }
5545   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
5546 }
5547 
5548 /// Check a template argument against its corresponding
5549 /// template type parameter.
5550 ///
5551 /// This routine implements the semantics of C++ [temp.arg.type]. It
5552 /// returns true if an error occurred, and false otherwise.
5553 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
5554                                  TypeSourceInfo *ArgInfo) {
5555   assert(ArgInfo && "invalid TypeSourceInfo");
5556   QualType Arg = ArgInfo->getType();
5557   SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
5558 
5559   if (Arg->isVariablyModifiedType()) {
5560     return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
5561   } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
5562     return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
5563   }
5564 
5565   // C++03 [temp.arg.type]p2:
5566   //   A local type, a type with no linkage, an unnamed type or a type
5567   //   compounded from any of these types shall not be used as a
5568   //   template-argument for a template type-parameter.
5569   //
5570   // C++11 allows these, and even in C++03 we allow them as an extension with
5571   // a warning.
5572   if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
5573     UnnamedLocalNoLinkageFinder Finder(*this, SR);
5574     (void)Finder.Visit(Context.getCanonicalType(Arg));
5575   }
5576 
5577   return false;
5578 }
5579 
5580 enum NullPointerValueKind {
5581   NPV_NotNullPointer,
5582   NPV_NullPointer,
5583   NPV_Error
5584 };
5585 
5586 /// Determine whether the given template argument is a null pointer
5587 /// value of the appropriate type.
5588 static NullPointerValueKind
5589 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
5590                                    QualType ParamType, Expr *Arg,
5591                                    Decl *Entity = nullptr) {
5592   if (Arg->isValueDependent() || Arg->isTypeDependent())
5593     return NPV_NotNullPointer;
5594 
5595   // dllimport'd entities aren't constant but are available inside of template
5596   // arguments.
5597   if (Entity && Entity->hasAttr<DLLImportAttr>())
5598     return NPV_NotNullPointer;
5599 
5600   if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
5601     llvm_unreachable(
5602         "Incomplete parameter type in isNullPointerValueTemplateArgument!");
5603 
5604   if (!S.getLangOpts().CPlusPlus11)
5605     return NPV_NotNullPointer;
5606 
5607   // Determine whether we have a constant expression.
5608   ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5609   if (ArgRV.isInvalid())
5610     return NPV_Error;
5611   Arg = ArgRV.get();
5612 
5613   Expr::EvalResult EvalResult;
5614   SmallVector<PartialDiagnosticAt, 8> Notes;
5615   EvalResult.Diag = &Notes;
5616   if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
5617       EvalResult.HasSideEffects) {
5618     SourceLocation DiagLoc = Arg->getExprLoc();
5619 
5620     // If our only note is the usual "invalid subexpression" note, just point
5621     // the caret at its location rather than producing an essentially
5622     // redundant note.
5623     if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5624         diag::note_invalid_subexpr_in_const_expr) {
5625       DiagLoc = Notes[0].first;
5626       Notes.clear();
5627     }
5628 
5629     S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5630       << Arg->getType() << Arg->getSourceRange();
5631     for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5632       S.Diag(Notes[I].first, Notes[I].second);
5633 
5634     S.Diag(Param->getLocation(), diag::note_template_param_here);
5635     return NPV_Error;
5636   }
5637 
5638   // C++11 [temp.arg.nontype]p1:
5639   //   - an address constant expression of type std::nullptr_t
5640   if (Arg->getType()->isNullPtrType())
5641     return NPV_NullPointer;
5642 
5643   //   - a constant expression that evaluates to a null pointer value (4.10); or
5644   //   - a constant expression that evaluates to a null member pointer value
5645   //     (4.11); or
5646   if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5647       (EvalResult.Val.isMemberPointer() &&
5648        !EvalResult.Val.getMemberPointerDecl())) {
5649     // If our expression has an appropriate type, we've succeeded.
5650     bool ObjCLifetimeConversion;
5651     if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5652         S.IsQualificationConversion(Arg->getType(), ParamType, false,
5653                                      ObjCLifetimeConversion))
5654       return NPV_NullPointer;
5655 
5656     // The types didn't match, but we know we got a null pointer; complain,
5657     // then recover as if the types were correct.
5658     S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5659       << Arg->getType() << ParamType << Arg->getSourceRange();
5660     S.Diag(Param->getLocation(), diag::note_template_param_here);
5661     return NPV_NullPointer;
5662   }
5663 
5664   // If we don't have a null pointer value, but we do have a NULL pointer
5665   // constant, suggest a cast to the appropriate type.
5666   if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5667     std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5668     S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
5669         << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
5670         << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()),
5671                                       ")");
5672     S.Diag(Param->getLocation(), diag::note_template_param_here);
5673     return NPV_NullPointer;
5674   }
5675 
5676   // FIXME: If we ever want to support general, address-constant expressions
5677   // as non-type template arguments, we should return the ExprResult here to
5678   // be interpreted by the caller.
5679   return NPV_NotNullPointer;
5680 }
5681 
5682 /// Checks whether the given template argument is compatible with its
5683 /// template parameter.
5684 static bool CheckTemplateArgumentIsCompatibleWithParameter(
5685     Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5686     Expr *Arg, QualType ArgType) {
5687   bool ObjCLifetimeConversion;
5688   if (ParamType->isPointerType() &&
5689       !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5690       S.IsQualificationConversion(ArgType, ParamType, false,
5691                                   ObjCLifetimeConversion)) {
5692     // For pointer-to-object types, qualification conversions are
5693     // permitted.
5694   } else {
5695     if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5696       if (!ParamRef->getPointeeType()->isFunctionType()) {
5697         // C++ [temp.arg.nontype]p5b3:
5698         //   For a non-type template-parameter of type reference to
5699         //   object, no conversions apply. The type referred to by the
5700         //   reference may be more cv-qualified than the (otherwise
5701         //   identical) type of the template- argument. The
5702         //   template-parameter is bound directly to the
5703         //   template-argument, which shall be an lvalue.
5704 
5705         // FIXME: Other qualifiers?
5706         unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5707         unsigned ArgQuals = ArgType.getCVRQualifiers();
5708 
5709         if ((ParamQuals | ArgQuals) != ParamQuals) {
5710           S.Diag(Arg->getBeginLoc(),
5711                  diag::err_template_arg_ref_bind_ignores_quals)
5712               << ParamType << Arg->getType() << Arg->getSourceRange();
5713           S.Diag(Param->getLocation(), diag::note_template_param_here);
5714           return true;
5715         }
5716       }
5717     }
5718 
5719     // At this point, the template argument refers to an object or
5720     // function with external linkage. We now need to check whether the
5721     // argument and parameter types are compatible.
5722     if (!S.Context.hasSameUnqualifiedType(ArgType,
5723                                           ParamType.getNonReferenceType())) {
5724       // We can't perform this conversion or binding.
5725       if (ParamType->isReferenceType())
5726         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
5727             << ParamType << ArgIn->getType() << Arg->getSourceRange();
5728       else
5729         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
5730             << ArgIn->getType() << ParamType << Arg->getSourceRange();
5731       S.Diag(Param->getLocation(), diag::note_template_param_here);
5732       return true;
5733     }
5734   }
5735 
5736   return false;
5737 }
5738 
5739 /// Checks whether the given template argument is the address
5740 /// of an object or function according to C++ [temp.arg.nontype]p1.
5741 static bool
5742 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5743                                                NonTypeTemplateParmDecl *Param,
5744                                                QualType ParamType,
5745                                                Expr *ArgIn,
5746                                                TemplateArgument &Converted) {
5747   bool Invalid = false;
5748   Expr *Arg = ArgIn;
5749   QualType ArgType = Arg->getType();
5750 
5751   bool AddressTaken = false;
5752   SourceLocation AddrOpLoc;
5753   if (S.getLangOpts().MicrosoftExt) {
5754     // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5755     // dereference and address-of operators.
5756     Arg = Arg->IgnoreParenCasts();
5757 
5758     bool ExtWarnMSTemplateArg = false;
5759     UnaryOperatorKind FirstOpKind;
5760     SourceLocation FirstOpLoc;
5761     while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5762       UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5763       if (UnOpKind == UO_Deref)
5764         ExtWarnMSTemplateArg = true;
5765       if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5766         Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5767         if (!AddrOpLoc.isValid()) {
5768           FirstOpKind = UnOpKind;
5769           FirstOpLoc = UnOp->getOperatorLoc();
5770         }
5771       } else
5772         break;
5773     }
5774     if (FirstOpLoc.isValid()) {
5775       if (ExtWarnMSTemplateArg)
5776         S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
5777             << ArgIn->getSourceRange();
5778 
5779       if (FirstOpKind == UO_AddrOf)
5780         AddressTaken = true;
5781       else if (Arg->getType()->isPointerType()) {
5782         // We cannot let pointers get dereferenced here, that is obviously not a
5783         // constant expression.
5784         assert(FirstOpKind == UO_Deref);
5785         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
5786             << Arg->getSourceRange();
5787       }
5788     }
5789   } else {
5790     // See through any implicit casts we added to fix the type.
5791     Arg = Arg->IgnoreImpCasts();
5792 
5793     // C++ [temp.arg.nontype]p1:
5794     //
5795     //   A template-argument for a non-type, non-template
5796     //   template-parameter shall be one of: [...]
5797     //
5798     //     -- the address of an object or function with external
5799     //        linkage, including function templates and function
5800     //        template-ids but excluding non-static class members,
5801     //        expressed as & id-expression where the & is optional if
5802     //        the name refers to a function or array, or if the
5803     //        corresponding template-parameter is a reference; or
5804 
5805     // In C++98/03 mode, give an extension warning on any extra parentheses.
5806     // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5807     bool ExtraParens = false;
5808     while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5809       if (!Invalid && !ExtraParens) {
5810         S.Diag(Arg->getBeginLoc(),
5811                S.getLangOpts().CPlusPlus11
5812                    ? diag::warn_cxx98_compat_template_arg_extra_parens
5813                    : diag::ext_template_arg_extra_parens)
5814             << Arg->getSourceRange();
5815         ExtraParens = true;
5816       }
5817 
5818       Arg = Parens->getSubExpr();
5819     }
5820 
5821     while (SubstNonTypeTemplateParmExpr *subst =
5822                dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5823       Arg = subst->getReplacement()->IgnoreImpCasts();
5824 
5825     if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5826       if (UnOp->getOpcode() == UO_AddrOf) {
5827         Arg = UnOp->getSubExpr();
5828         AddressTaken = true;
5829         AddrOpLoc = UnOp->getOperatorLoc();
5830       }
5831     }
5832 
5833     while (SubstNonTypeTemplateParmExpr *subst =
5834                dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5835       Arg = subst->getReplacement()->IgnoreImpCasts();
5836   }
5837 
5838   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5839   ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5840 
5841   // If our parameter has pointer type, check for a null template value.
5842   if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
5843     switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
5844                                                Entity)) {
5845     case NPV_NullPointer:
5846       S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5847       Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5848                                    /*isNullPtr=*/true);
5849       return false;
5850 
5851     case NPV_Error:
5852       return true;
5853 
5854     case NPV_NotNullPointer:
5855       break;
5856     }
5857   }
5858 
5859   // Stop checking the precise nature of the argument if it is value dependent,
5860   // it should be checked when instantiated.
5861   if (Arg->isValueDependent()) {
5862     Converted = TemplateArgument(ArgIn);
5863     return false;
5864   }
5865 
5866   if (isa<CXXUuidofExpr>(Arg)) {
5867     if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5868                                                        ArgIn, Arg, ArgType))
5869       return true;
5870 
5871     Converted = TemplateArgument(ArgIn);
5872     return false;
5873   }
5874 
5875   if (!DRE) {
5876     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
5877         << Arg->getSourceRange();
5878     S.Diag(Param->getLocation(), diag::note_template_param_here);
5879     return true;
5880   }
5881 
5882   // Cannot refer to non-static data members
5883   if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
5884     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
5885         << Entity << Arg->getSourceRange();
5886     S.Diag(Param->getLocation(), diag::note_template_param_here);
5887     return true;
5888   }
5889 
5890   // Cannot refer to non-static member functions
5891   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
5892     if (!Method->isStatic()) {
5893       S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
5894           << Method << Arg->getSourceRange();
5895       S.Diag(Param->getLocation(), diag::note_template_param_here);
5896       return true;
5897     }
5898   }
5899 
5900   FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
5901   VarDecl *Var = dyn_cast<VarDecl>(Entity);
5902 
5903   // A non-type template argument must refer to an object or function.
5904   if (!Func && !Var) {
5905     // We found something, but we don't know specifically what it is.
5906     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
5907         << Arg->getSourceRange();
5908     S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5909     return true;
5910   }
5911 
5912   // Address / reference template args must have external linkage in C++98.
5913   if (Entity->getFormalLinkage() == InternalLinkage) {
5914     S.Diag(Arg->getBeginLoc(),
5915            S.getLangOpts().CPlusPlus11
5916                ? diag::warn_cxx98_compat_template_arg_object_internal
5917                : diag::ext_template_arg_object_internal)
5918         << !Func << Entity << Arg->getSourceRange();
5919     S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5920       << !Func;
5921   } else if (!Entity->hasLinkage()) {
5922     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
5923         << !Func << Entity << Arg->getSourceRange();
5924     S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5925       << !Func;
5926     return true;
5927   }
5928 
5929   if (Func) {
5930     // If the template parameter has pointer type, the function decays.
5931     if (ParamType->isPointerType() && !AddressTaken)
5932       ArgType = S.Context.getPointerType(Func->getType());
5933     else if (AddressTaken && ParamType->isReferenceType()) {
5934       // If we originally had an address-of operator, but the
5935       // parameter has reference type, complain and (if things look
5936       // like they will work) drop the address-of operator.
5937       if (!S.Context.hasSameUnqualifiedType(Func->getType(),
5938                                             ParamType.getNonReferenceType())) {
5939         S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5940           << ParamType;
5941         S.Diag(Param->getLocation(), diag::note_template_param_here);
5942         return true;
5943       }
5944 
5945       S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5946         << ParamType
5947         << FixItHint::CreateRemoval(AddrOpLoc);
5948       S.Diag(Param->getLocation(), diag::note_template_param_here);
5949 
5950       ArgType = Func->getType();
5951     }
5952   } else {
5953     // A value of reference type is not an object.
5954     if (Var->getType()->isReferenceType()) {
5955       S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
5956           << Var->getType() << Arg->getSourceRange();
5957       S.Diag(Param->getLocation(), diag::note_template_param_here);
5958       return true;
5959     }
5960 
5961     // A template argument must have static storage duration.
5962     if (Var->getTLSKind()) {
5963       S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
5964           << Arg->getSourceRange();
5965       S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
5966       return true;
5967     }
5968 
5969     // If the template parameter has pointer type, we must have taken
5970     // the address of this object.
5971     if (ParamType->isReferenceType()) {
5972       if (AddressTaken) {
5973         // If we originally had an address-of operator, but the
5974         // parameter has reference type, complain and (if things look
5975         // like they will work) drop the address-of operator.
5976         if (!S.Context.hasSameUnqualifiedType(Var->getType(),
5977                                             ParamType.getNonReferenceType())) {
5978           S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5979             << ParamType;
5980           S.Diag(Param->getLocation(), diag::note_template_param_here);
5981           return true;
5982         }
5983 
5984         S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5985           << ParamType
5986           << FixItHint::CreateRemoval(AddrOpLoc);
5987         S.Diag(Param->getLocation(), diag::note_template_param_here);
5988 
5989         ArgType = Var->getType();
5990       }
5991     } else if (!AddressTaken && ParamType->isPointerType()) {
5992       if (Var->getType()->isArrayType()) {
5993         // Array-to-pointer decay.
5994         ArgType = S.Context.getArrayDecayedType(Var->getType());
5995       } else {
5996         // If the template parameter has pointer type but the address of
5997         // this object was not taken, complain and (possibly) recover by
5998         // taking the address of the entity.
5999         ArgType = S.Context.getPointerType(Var->getType());
6000         if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6001           S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6002               << ParamType;
6003           S.Diag(Param->getLocation(), diag::note_template_param_here);
6004           return true;
6005         }
6006 
6007         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6008             << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6009 
6010         S.Diag(Param->getLocation(), diag::note_template_param_here);
6011       }
6012     }
6013   }
6014 
6015   if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6016                                                      Arg, ArgType))
6017     return true;
6018 
6019   // Create the template argument.
6020   Converted =
6021       TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
6022   S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
6023   return false;
6024 }
6025 
6026 /// Checks whether the given template argument is a pointer to
6027 /// member constant according to C++ [temp.arg.nontype]p1.
6028 static bool CheckTemplateArgumentPointerToMember(Sema &S,
6029                                                  NonTypeTemplateParmDecl *Param,
6030                                                  QualType ParamType,
6031                                                  Expr *&ResultArg,
6032                                                  TemplateArgument &Converted) {
6033   bool Invalid = false;
6034 
6035   Expr *Arg = ResultArg;
6036   bool ObjCLifetimeConversion;
6037 
6038   // C++ [temp.arg.nontype]p1:
6039   //
6040   //   A template-argument for a non-type, non-template
6041   //   template-parameter shall be one of: [...]
6042   //
6043   //     -- a pointer to member expressed as described in 5.3.1.
6044   DeclRefExpr *DRE = nullptr;
6045 
6046   // In C++98/03 mode, give an extension warning on any extra parentheses.
6047   // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6048   bool ExtraParens = false;
6049   while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6050     if (!Invalid && !ExtraParens) {
6051       S.Diag(Arg->getBeginLoc(),
6052              S.getLangOpts().CPlusPlus11
6053                  ? diag::warn_cxx98_compat_template_arg_extra_parens
6054                  : diag::ext_template_arg_extra_parens)
6055           << Arg->getSourceRange();
6056       ExtraParens = true;
6057     }
6058 
6059     Arg = Parens->getSubExpr();
6060   }
6061 
6062   while (SubstNonTypeTemplateParmExpr *subst =
6063            dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6064     Arg = subst->getReplacement()->IgnoreImpCasts();
6065 
6066   // A pointer-to-member constant written &Class::member.
6067   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6068     if (UnOp->getOpcode() == UO_AddrOf) {
6069       DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6070       if (DRE && !DRE->getQualifier())
6071         DRE = nullptr;
6072     }
6073   }
6074   // A constant of pointer-to-member type.
6075   else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
6076     ValueDecl *VD = DRE->getDecl();
6077     if (VD->getType()->isMemberPointerType()) {
6078       if (isa<NonTypeTemplateParmDecl>(VD)) {
6079         if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6080           Converted = TemplateArgument(Arg);
6081         } else {
6082           VD = cast<ValueDecl>(VD->getCanonicalDecl());
6083           Converted = TemplateArgument(VD, ParamType);
6084         }
6085         return Invalid;
6086       }
6087     }
6088 
6089     DRE = nullptr;
6090   }
6091 
6092   ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6093 
6094   // Check for a null pointer value.
6095   switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6096                                              Entity)) {
6097   case NPV_Error:
6098     return true;
6099   case NPV_NullPointer:
6100     S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6101     Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6102                                  /*isNullPtr*/true);
6103     return false;
6104   case NPV_NotNullPointer:
6105     break;
6106   }
6107 
6108   if (S.IsQualificationConversion(ResultArg->getType(),
6109                                   ParamType.getNonReferenceType(), false,
6110                                   ObjCLifetimeConversion)) {
6111     ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6112                                     ResultArg->getValueKind())
6113                     .get();
6114   } else if (!S.Context.hasSameUnqualifiedType(
6115                  ResultArg->getType(), ParamType.getNonReferenceType())) {
6116     // We can't perform this conversion.
6117     S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
6118         << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6119     S.Diag(Param->getLocation(), diag::note_template_param_here);
6120     return true;
6121   }
6122 
6123   if (!DRE)
6124     return S.Diag(Arg->getBeginLoc(),
6125                   diag::err_template_arg_not_pointer_to_member_form)
6126            << Arg->getSourceRange();
6127 
6128   if (isa<FieldDecl>(DRE->getDecl()) ||
6129       isa<IndirectFieldDecl>(DRE->getDecl()) ||
6130       isa<CXXMethodDecl>(DRE->getDecl())) {
6131     assert((isa<FieldDecl>(DRE->getDecl()) ||
6132             isa<IndirectFieldDecl>(DRE->getDecl()) ||
6133             !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
6134            "Only non-static member pointers can make it here");
6135 
6136     // Okay: this is the address of a non-static member, and therefore
6137     // a member pointer constant.
6138     if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6139       Converted = TemplateArgument(Arg);
6140     } else {
6141       ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
6142       Converted = TemplateArgument(D, ParamType);
6143     }
6144     return Invalid;
6145   }
6146 
6147   // We found something else, but we don't know specifically what it is.
6148   S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
6149       << Arg->getSourceRange();
6150   S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6151   return true;
6152 }
6153 
6154 /// Check a template argument against its corresponding
6155 /// non-type template parameter.
6156 ///
6157 /// This routine implements the semantics of C++ [temp.arg.nontype].
6158 /// If an error occurred, it returns ExprError(); otherwise, it
6159 /// returns the converted template argument. \p ParamType is the
6160 /// type of the non-type template parameter after it has been instantiated.
6161 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6162                                        QualType ParamType, Expr *Arg,
6163                                        TemplateArgument &Converted,
6164                                        CheckTemplateArgumentKind CTAK) {
6165   SourceLocation StartLoc = Arg->getBeginLoc();
6166 
6167   // If the parameter type somehow involves auto, deduce the type now.
6168   if (getLangOpts().CPlusPlus17 && ParamType->isUndeducedType()) {
6169     // During template argument deduction, we allow 'decltype(auto)' to
6170     // match an arbitrary dependent argument.
6171     // FIXME: The language rules don't say what happens in this case.
6172     // FIXME: We get an opaque dependent type out of decltype(auto) if the
6173     // expression is merely instantiation-dependent; is this enough?
6174     if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
6175       auto *AT = dyn_cast<AutoType>(ParamType);
6176       if (AT && AT->isDecltypeAuto()) {
6177         Converted = TemplateArgument(Arg);
6178         return Arg;
6179       }
6180     }
6181 
6182     // When checking a deduced template argument, deduce from its type even if
6183     // the type is dependent, in order to check the types of non-type template
6184     // arguments line up properly in partial ordering.
6185     Optional<unsigned> Depth;
6186     if (CTAK != CTAK_Specified)
6187       Depth = Param->getDepth() + 1;
6188     if (DeduceAutoType(
6189             Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
6190             Arg, ParamType, Depth) == DAR_Failed) {
6191       Diag(Arg->getExprLoc(),
6192            diag::err_non_type_template_parm_type_deduction_failure)
6193         << Param->getDeclName() << Param->getType() << Arg->getType()
6194         << Arg->getSourceRange();
6195       Diag(Param->getLocation(), diag::note_template_param_here);
6196       return ExprError();
6197     }
6198     // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6199     // an error. The error message normally references the parameter
6200     // declaration, but here we'll pass the argument location because that's
6201     // where the parameter type is deduced.
6202     ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6203     if (ParamType.isNull()) {
6204       Diag(Param->getLocation(), diag::note_template_param_here);
6205       return ExprError();
6206     }
6207   }
6208 
6209   // We should have already dropped all cv-qualifiers by now.
6210   assert(!ParamType.hasQualifiers() &&
6211          "non-type template parameter type cannot be qualified");
6212 
6213   if (CTAK == CTAK_Deduced &&
6214       !Context.hasSameType(ParamType.getNonLValueExprType(Context),
6215                            Arg->getType())) {
6216     // FIXME: If either type is dependent, we skip the check. This isn't
6217     // correct, since during deduction we're supposed to have replaced each
6218     // template parameter with some unique (non-dependent) placeholder.
6219     // FIXME: If the argument type contains 'auto', we carry on and fail the
6220     // type check in order to force specific types to be more specialized than
6221     // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6222     // work.
6223     if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6224         !Arg->getType()->getContainedAutoType()) {
6225       Converted = TemplateArgument(Arg);
6226       return Arg;
6227     }
6228     // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6229     // we should actually be checking the type of the template argument in P,
6230     // not the type of the template argument deduced from A, against the
6231     // template parameter type.
6232     Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
6233       << Arg->getType()
6234       << ParamType.getUnqualifiedType();
6235     Diag(Param->getLocation(), diag::note_template_param_here);
6236     return ExprError();
6237   }
6238 
6239   // If either the parameter has a dependent type or the argument is
6240   // type-dependent, there's nothing we can check now.
6241   if (ParamType->isDependentType() || Arg->isTypeDependent()) {
6242     // FIXME: Produce a cloned, canonical expression?
6243     Converted = TemplateArgument(Arg);
6244     return Arg;
6245   }
6246 
6247   // The initialization of the parameter from the argument is
6248   // a constant-evaluated context.
6249   EnterExpressionEvaluationContext ConstantEvaluated(
6250       *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6251 
6252   if (getLangOpts().CPlusPlus17) {
6253     // C++17 [temp.arg.nontype]p1:
6254     //   A template-argument for a non-type template parameter shall be
6255     //   a converted constant expression of the type of the template-parameter.
6256     APValue Value;
6257     ExprResult ArgResult = CheckConvertedConstantExpression(
6258         Arg, ParamType, Value, CCEK_TemplateArg);
6259     if (ArgResult.isInvalid())
6260       return ExprError();
6261 
6262     // For a value-dependent argument, CheckConvertedConstantExpression is
6263     // permitted (and expected) to be unable to determine a value.
6264     if (ArgResult.get()->isValueDependent()) {
6265       Converted = TemplateArgument(ArgResult.get());
6266       return ArgResult;
6267     }
6268 
6269     QualType CanonParamType = Context.getCanonicalType(ParamType);
6270 
6271     // Convert the APValue to a TemplateArgument.
6272     switch (Value.getKind()) {
6273     case APValue::Uninitialized:
6274       assert(ParamType->isNullPtrType());
6275       Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
6276       break;
6277     case APValue::Int:
6278       assert(ParamType->isIntegralOrEnumerationType());
6279       Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
6280       break;
6281     case APValue::MemberPointer: {
6282       assert(ParamType->isMemberPointerType());
6283 
6284       // FIXME: We need TemplateArgument representation and mangling for these.
6285       if (!Value.getMemberPointerPath().empty()) {
6286         Diag(Arg->getBeginLoc(),
6287              diag::err_template_arg_member_ptr_base_derived_not_supported)
6288             << Value.getMemberPointerDecl() << ParamType
6289             << Arg->getSourceRange();
6290         return ExprError();
6291       }
6292 
6293       auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
6294       Converted = VD ? TemplateArgument(VD, CanonParamType)
6295                      : TemplateArgument(CanonParamType, /*isNullPtr*/true);
6296       break;
6297     }
6298     case APValue::LValue: {
6299       //   For a non-type template-parameter of pointer or reference type,
6300       //   the value of the constant expression shall not refer to
6301       assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
6302              ParamType->isNullPtrType());
6303       // -- a temporary object
6304       // -- a string literal
6305       // -- the result of a typeid expression, or
6306       // -- a predefined __func__ variable
6307       if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
6308         if (isa<CXXUuidofExpr>(E)) {
6309           Converted = TemplateArgument(ArgResult.get());
6310           break;
6311         }
6312         Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6313             << Arg->getSourceRange();
6314         return ExprError();
6315       }
6316       auto *VD = const_cast<ValueDecl *>(
6317           Value.getLValueBase().dyn_cast<const ValueDecl *>());
6318       // -- a subobject
6319       if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
6320           VD && VD->getType()->isArrayType() &&
6321           Value.getLValuePath()[0].ArrayIndex == 0 &&
6322           !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6323         // Per defect report (no number yet):
6324         //   ... other than a pointer to the first element of a complete array
6325         //       object.
6326       } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6327                  Value.isLValueOnePastTheEnd()) {
6328         Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6329           << Value.getAsString(Context, ParamType);
6330         return ExprError();
6331       }
6332       assert((VD || !ParamType->isReferenceType()) &&
6333              "null reference should not be a constant expression");
6334       assert((!VD || !ParamType->isNullPtrType()) &&
6335              "non-null value of type nullptr_t?");
6336       Converted = VD ? TemplateArgument(VD, CanonParamType)
6337                      : TemplateArgument(CanonParamType, /*isNullPtr*/true);
6338       break;
6339     }
6340     case APValue::AddrLabelDiff:
6341       return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
6342     case APValue::Float:
6343     case APValue::ComplexInt:
6344     case APValue::ComplexFloat:
6345     case APValue::Vector:
6346     case APValue::Array:
6347     case APValue::Struct:
6348     case APValue::Union:
6349       llvm_unreachable("invalid kind for template argument");
6350     }
6351 
6352     return ArgResult.get();
6353   }
6354 
6355   // C++ [temp.arg.nontype]p5:
6356   //   The following conversions are performed on each expression used
6357   //   as a non-type template-argument. If a non-type
6358   //   template-argument cannot be converted to the type of the
6359   //   corresponding template-parameter then the program is
6360   //   ill-formed.
6361   if (ParamType->isIntegralOrEnumerationType()) {
6362     // C++11:
6363     //   -- for a non-type template-parameter of integral or
6364     //      enumeration type, conversions permitted in a converted
6365     //      constant expression are applied.
6366     //
6367     // C++98:
6368     //   -- for a non-type template-parameter of integral or
6369     //      enumeration type, integral promotions (4.5) and integral
6370     //      conversions (4.7) are applied.
6371 
6372     if (getLangOpts().CPlusPlus11) {
6373       // C++ [temp.arg.nontype]p1:
6374       //   A template-argument for a non-type, non-template template-parameter
6375       //   shall be one of:
6376       //
6377       //     -- for a non-type template-parameter of integral or enumeration
6378       //        type, a converted constant expression of the type of the
6379       //        template-parameter; or
6380       llvm::APSInt Value;
6381       ExprResult ArgResult =
6382         CheckConvertedConstantExpression(Arg, ParamType, Value,
6383                                          CCEK_TemplateArg);
6384       if (ArgResult.isInvalid())
6385         return ExprError();
6386 
6387       // We can't check arbitrary value-dependent arguments.
6388       if (ArgResult.get()->isValueDependent()) {
6389         Converted = TemplateArgument(ArgResult.get());
6390         return ArgResult;
6391       }
6392 
6393       // Widen the argument value to sizeof(parameter type). This is almost
6394       // always a no-op, except when the parameter type is bool. In
6395       // that case, this may extend the argument from 1 bit to 8 bits.
6396       QualType IntegerType = ParamType;
6397       if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6398         IntegerType = Enum->getDecl()->getIntegerType();
6399       Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
6400 
6401       Converted = TemplateArgument(Context, Value,
6402                                    Context.getCanonicalType(ParamType));
6403       return ArgResult;
6404     }
6405 
6406     ExprResult ArgResult = DefaultLvalueConversion(Arg);
6407     if (ArgResult.isInvalid())
6408       return ExprError();
6409     Arg = ArgResult.get();
6410 
6411     QualType ArgType = Arg->getType();
6412 
6413     // C++ [temp.arg.nontype]p1:
6414     //   A template-argument for a non-type, non-template
6415     //   template-parameter shall be one of:
6416     //
6417     //     -- an integral constant-expression of integral or enumeration
6418     //        type; or
6419     //     -- the name of a non-type template-parameter; or
6420     llvm::APSInt Value;
6421     if (!ArgType->isIntegralOrEnumerationType()) {
6422       Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
6423           << ArgType << Arg->getSourceRange();
6424       Diag(Param->getLocation(), diag::note_template_param_here);
6425       return ExprError();
6426     } else if (!Arg->isValueDependent()) {
6427       class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6428         QualType T;
6429 
6430       public:
6431         TmplArgICEDiagnoser(QualType T) : T(T) { }
6432 
6433         void diagnoseNotICE(Sema &S, SourceLocation Loc,
6434                             SourceRange SR) override {
6435           S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
6436         }
6437       } Diagnoser(ArgType);
6438 
6439       Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
6440                                             false).get();
6441       if (!Arg)
6442         return ExprError();
6443     }
6444 
6445     // From here on out, all we care about is the unqualified form
6446     // of the argument type.
6447     ArgType = ArgType.getUnqualifiedType();
6448 
6449     // Try to convert the argument to the parameter's type.
6450     if (Context.hasSameType(ParamType, ArgType)) {
6451       // Okay: no conversion necessary
6452     } else if (ParamType->isBooleanType()) {
6453       // This is an integral-to-boolean conversion.
6454       Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
6455     } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6456                !ParamType->isEnumeralType()) {
6457       // This is an integral promotion or conversion.
6458       Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
6459     } else {
6460       // We can't perform this conversion.
6461       Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6462           << Arg->getType() << ParamType << Arg->getSourceRange();
6463       Diag(Param->getLocation(), diag::note_template_param_here);
6464       return ExprError();
6465     }
6466 
6467     // Add the value of this argument to the list of converted
6468     // arguments. We use the bitwidth and signedness of the template
6469     // parameter.
6470     if (Arg->isValueDependent()) {
6471       // The argument is value-dependent. Create a new
6472       // TemplateArgument with the converted expression.
6473       Converted = TemplateArgument(Arg);
6474       return Arg;
6475     }
6476 
6477     QualType IntegerType = Context.getCanonicalType(ParamType);
6478     if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6479       IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
6480 
6481     if (ParamType->isBooleanType()) {
6482       // Value must be zero or one.
6483       Value = Value != 0;
6484       unsigned AllowedBits = Context.getTypeSize(IntegerType);
6485       if (Value.getBitWidth() != AllowedBits)
6486         Value = Value.extOrTrunc(AllowedBits);
6487       Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6488     } else {
6489       llvm::APSInt OldValue = Value;
6490 
6491       // Coerce the template argument's value to the value it will have
6492       // based on the template parameter's type.
6493       unsigned AllowedBits = Context.getTypeSize(IntegerType);
6494       if (Value.getBitWidth() != AllowedBits)
6495         Value = Value.extOrTrunc(AllowedBits);
6496       Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6497 
6498       // Complain if an unsigned parameter received a negative value.
6499       if (IntegerType->isUnsignedIntegerOrEnumerationType()
6500                && (OldValue.isSigned() && OldValue.isNegative())) {
6501         Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
6502             << OldValue.toString(10) << Value.toString(10) << Param->getType()
6503             << Arg->getSourceRange();
6504         Diag(Param->getLocation(), diag::note_template_param_here);
6505       }
6506 
6507       // Complain if we overflowed the template parameter's type.
6508       unsigned RequiredBits;
6509       if (IntegerType->isUnsignedIntegerOrEnumerationType())
6510         RequiredBits = OldValue.getActiveBits();
6511       else if (OldValue.isUnsigned())
6512         RequiredBits = OldValue.getActiveBits() + 1;
6513       else
6514         RequiredBits = OldValue.getMinSignedBits();
6515       if (RequiredBits > AllowedBits) {
6516         Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
6517             << OldValue.toString(10) << Value.toString(10) << Param->getType()
6518             << Arg->getSourceRange();
6519         Diag(Param->getLocation(), diag::note_template_param_here);
6520       }
6521     }
6522 
6523     Converted = TemplateArgument(Context, Value,
6524                                  ParamType->isEnumeralType()
6525                                    ? Context.getCanonicalType(ParamType)
6526                                    : IntegerType);
6527     return Arg;
6528   }
6529 
6530   QualType ArgType = Arg->getType();
6531   DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6532 
6533   // Handle pointer-to-function, reference-to-function, and
6534   // pointer-to-member-function all in (roughly) the same way.
6535   if (// -- For a non-type template-parameter of type pointer to
6536       //    function, only the function-to-pointer conversion (4.3) is
6537       //    applied. If the template-argument represents a set of
6538       //    overloaded functions (or a pointer to such), the matching
6539       //    function is selected from the set (13.4).
6540       (ParamType->isPointerType() &&
6541        ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
6542       // -- For a non-type template-parameter of type reference to
6543       //    function, no conversions apply. If the template-argument
6544       //    represents a set of overloaded functions, the matching
6545       //    function is selected from the set (13.4).
6546       (ParamType->isReferenceType() &&
6547        ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
6548       // -- For a non-type template-parameter of type pointer to
6549       //    member function, no conversions apply. If the
6550       //    template-argument represents a set of overloaded member
6551       //    functions, the matching member function is selected from
6552       //    the set (13.4).
6553       (ParamType->isMemberPointerType() &&
6554        ParamType->getAs<MemberPointerType>()->getPointeeType()
6555          ->isFunctionType())) {
6556 
6557     if (Arg->getType() == Context.OverloadTy) {
6558       if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
6559                                                                 true,
6560                                                                 FoundResult)) {
6561         if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
6562           return ExprError();
6563 
6564         Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6565         ArgType = Arg->getType();
6566       } else
6567         return ExprError();
6568     }
6569 
6570     if (!ParamType->isMemberPointerType()) {
6571       if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6572                                                          ParamType,
6573                                                          Arg, Converted))
6574         return ExprError();
6575       return Arg;
6576     }
6577 
6578     if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6579                                              Converted))
6580       return ExprError();
6581     return Arg;
6582   }
6583 
6584   if (ParamType->isPointerType()) {
6585     //   -- for a non-type template-parameter of type pointer to
6586     //      object, qualification conversions (4.4) and the
6587     //      array-to-pointer conversion (4.2) are applied.
6588     // C++0x also allows a value of std::nullptr_t.
6589     assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
6590            "Only object pointers allowed here");
6591 
6592     if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6593                                                        ParamType,
6594                                                        Arg, Converted))
6595       return ExprError();
6596     return Arg;
6597   }
6598 
6599   if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
6600     //   -- For a non-type template-parameter of type reference to
6601     //      object, no conversions apply. The type referred to by the
6602     //      reference may be more cv-qualified than the (otherwise
6603     //      identical) type of the template-argument. The
6604     //      template-parameter is bound directly to the
6605     //      template-argument, which must be an lvalue.
6606     assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
6607            "Only object references allowed here");
6608 
6609     if (Arg->getType() == Context.OverloadTy) {
6610       if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6611                                                  ParamRefType->getPointeeType(),
6612                                                                 true,
6613                                                                 FoundResult)) {
6614         if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
6615           return ExprError();
6616 
6617         Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6618         ArgType = Arg->getType();
6619       } else
6620         return ExprError();
6621     }
6622 
6623     if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6624                                                        ParamType,
6625                                                        Arg, Converted))
6626       return ExprError();
6627     return Arg;
6628   }
6629 
6630   // Deal with parameters of type std::nullptr_t.
6631   if (ParamType->isNullPtrType()) {
6632     if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6633       Converted = TemplateArgument(Arg);
6634       return Arg;
6635     }
6636 
6637     switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6638     case NPV_NotNullPointer:
6639       Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6640         << Arg->getType() << ParamType;
6641       Diag(Param->getLocation(), diag::note_template_param_here);
6642       return ExprError();
6643 
6644     case NPV_Error:
6645       return ExprError();
6646 
6647     case NPV_NullPointer:
6648       Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6649       Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6650                                    /*isNullPtr*/true);
6651       return Arg;
6652     }
6653   }
6654 
6655   //     -- For a non-type template-parameter of type pointer to data
6656   //        member, qualification conversions (4.4) are applied.
6657   assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
6658 
6659   if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6660                                            Converted))
6661     return ExprError();
6662   return Arg;
6663 }
6664 
6665 static void DiagnoseTemplateParameterListArityMismatch(
6666     Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
6667     Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
6668 
6669 /// Check a template argument against its corresponding
6670 /// template template parameter.
6671 ///
6672 /// This routine implements the semantics of C++ [temp.arg.template].
6673 /// It returns true if an error occurred, and false otherwise.
6674 bool Sema::CheckTemplateTemplateArgument(TemplateParameterList *Params,
6675                                          TemplateArgumentLoc &Arg) {
6676   TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
6677   TemplateDecl *Template = Name.getAsTemplateDecl();
6678   if (!Template) {
6679     // Any dependent template name is fine.
6680     assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
6681     return false;
6682   }
6683 
6684   if (Template->isInvalidDecl())
6685     return true;
6686 
6687   // C++0x [temp.arg.template]p1:
6688   //   A template-argument for a template template-parameter shall be
6689   //   the name of a class template or an alias template, expressed as an
6690   //   id-expression. When the template-argument names a class template, only
6691   //   primary class templates are considered when matching the
6692   //   template template argument with the corresponding parameter;
6693   //   partial specializations are not considered even if their
6694   //   parameter lists match that of the template template parameter.
6695   //
6696   // Note that we also allow template template parameters here, which
6697   // will happen when we are dealing with, e.g., class template
6698   // partial specializations.
6699   if (!isa<ClassTemplateDecl>(Template) &&
6700       !isa<TemplateTemplateParmDecl>(Template) &&
6701       !isa<TypeAliasTemplateDecl>(Template) &&
6702       !isa<BuiltinTemplateDecl>(Template)) {
6703     assert(isa<FunctionTemplateDecl>(Template) &&
6704            "Only function templates are possible here");
6705     Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
6706     Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6707       << Template;
6708   }
6709 
6710   // C++1z [temp.arg.template]p3: (DR 150)
6711   //   A template-argument matches a template template-parameter P when P
6712   //   is at least as specialized as the template-argument A.
6713   if (getLangOpts().RelaxedTemplateTemplateArgs) {
6714     // Quick check for the common case:
6715     //   If P contains a parameter pack, then A [...] matches P if each of A's
6716     //   template parameters matches the corresponding template parameter in
6717     //   the template-parameter-list of P.
6718     if (TemplateParameterListsAreEqual(
6719             Template->getTemplateParameters(), Params, false,
6720             TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6721       return false;
6722 
6723     if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6724                                                           Arg.getLocation()))
6725       return false;
6726     // FIXME: Produce better diagnostics for deduction failures.
6727   }
6728 
6729   return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
6730                                          Params,
6731                                          true,
6732                                          TPL_TemplateTemplateArgumentMatch,
6733                                          Arg.getLocation());
6734 }
6735 
6736 /// Given a non-type template argument that refers to a
6737 /// declaration and the type of its corresponding non-type template
6738 /// parameter, produce an expression that properly refers to that
6739 /// declaration.
6740 ExprResult
6741 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6742                                               QualType ParamType,
6743                                               SourceLocation Loc) {
6744   // C++ [temp.param]p8:
6745   //
6746   //   A non-type template-parameter of type "array of T" or
6747   //   "function returning T" is adjusted to be of type "pointer to
6748   //   T" or "pointer to function returning T", respectively.
6749   if (ParamType->isArrayType())
6750     ParamType = Context.getArrayDecayedType(ParamType);
6751   else if (ParamType->isFunctionType())
6752     ParamType = Context.getPointerType(ParamType);
6753 
6754   // For a NULL non-type template argument, return nullptr casted to the
6755   // parameter's type.
6756   if (Arg.getKind() == TemplateArgument::NullPtr) {
6757     return ImpCastExprToType(
6758              new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6759                              ParamType,
6760                              ParamType->getAs<MemberPointerType>()
6761                                ? CK_NullToMemberPointer
6762                                : CK_NullToPointer);
6763   }
6764   assert(Arg.getKind() == TemplateArgument::Declaration &&
6765          "Only declaration template arguments permitted here");
6766 
6767   ValueDecl *VD = Arg.getAsDecl();
6768 
6769   if (VD->getDeclContext()->isRecord() &&
6770       (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6771        isa<IndirectFieldDecl>(VD))) {
6772     // If the value is a class member, we might have a pointer-to-member.
6773     // Determine whether the non-type template template parameter is of
6774     // pointer-to-member type. If so, we need to build an appropriate
6775     // expression for a pointer-to-member, since a "normal" DeclRefExpr
6776     // would refer to the member itself.
6777     if (ParamType->isMemberPointerType()) {
6778       QualType ClassType
6779         = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6780       NestedNameSpecifier *Qualifier
6781         = NestedNameSpecifier::Create(Context, nullptr, false,
6782                                       ClassType.getTypePtr());
6783       CXXScopeSpec SS;
6784       SS.MakeTrivial(Context, Qualifier, Loc);
6785 
6786       // The actual value-ness of this is unimportant, but for
6787       // internal consistency's sake, references to instance methods
6788       // are r-values.
6789       ExprValueKind VK = VK_LValue;
6790       if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
6791         VK = VK_RValue;
6792 
6793       ExprResult RefExpr = BuildDeclRefExpr(VD,
6794                                             VD->getType().getNonReferenceType(),
6795                                             VK,
6796                                             Loc,
6797                                             &SS);
6798       if (RefExpr.isInvalid())
6799         return ExprError();
6800 
6801       RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
6802 
6803       // We might need to perform a trailing qualification conversion, since
6804       // the element type on the parameter could be more qualified than the
6805       // element type in the expression we constructed.
6806       bool ObjCLifetimeConversion;
6807       if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
6808                                     ParamType.getUnqualifiedType(), false,
6809                                     ObjCLifetimeConversion))
6810         RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
6811 
6812       assert(!RefExpr.isInvalid() &&
6813              Context.hasSameType(((Expr*) RefExpr.get())->getType(),
6814                                  ParamType.getUnqualifiedType()));
6815       return RefExpr;
6816     }
6817   }
6818 
6819   QualType T = VD->getType().getNonReferenceType();
6820 
6821   if (ParamType->isPointerType()) {
6822     // When the non-type template parameter is a pointer, take the
6823     // address of the declaration.
6824     ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
6825     if (RefExpr.isInvalid())
6826       return ExprError();
6827 
6828     if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
6829         (T->isFunctionType() || T->isArrayType())) {
6830       // Decay functions and arrays unless we're forming a pointer to array.
6831       RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
6832       if (RefExpr.isInvalid())
6833         return ExprError();
6834 
6835       return RefExpr;
6836     }
6837 
6838     // Take the address of everything else
6839     return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
6840   }
6841 
6842   ExprValueKind VK = VK_RValue;
6843 
6844   // If the non-type template parameter has reference type, qualify the
6845   // resulting declaration reference with the extra qualifiers on the
6846   // type that the reference refers to.
6847   if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
6848     VK = VK_LValue;
6849     T = Context.getQualifiedType(T,
6850                               TargetRef->getPointeeType().getQualifiers());
6851   } else if (isa<FunctionDecl>(VD)) {
6852     // References to functions are always lvalues.
6853     VK = VK_LValue;
6854   }
6855 
6856   return BuildDeclRefExpr(VD, T, VK, Loc);
6857 }
6858 
6859 /// Construct a new expression that refers to the given
6860 /// integral template argument with the given source-location
6861 /// information.
6862 ///
6863 /// This routine takes care of the mapping from an integral template
6864 /// argument (which may have any integral type) to the appropriate
6865 /// literal value.
6866 ExprResult
6867 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6868                                                   SourceLocation Loc) {
6869   assert(Arg.getKind() == TemplateArgument::Integral &&
6870          "Operation is only valid for integral template arguments");
6871   QualType OrigT = Arg.getIntegralType();
6872 
6873   // If this is an enum type that we're instantiating, we need to use an integer
6874   // type the same size as the enumerator.  We don't want to build an
6875   // IntegerLiteral with enum type.  The integer type of an enum type can be of
6876   // any integral type with C++11 enum classes, make sure we create the right
6877   // type of literal for it.
6878   QualType T = OrigT;
6879   if (const EnumType *ET = OrigT->getAs<EnumType>())
6880     T = ET->getDecl()->getIntegerType();
6881 
6882   Expr *E;
6883   if (T->isAnyCharacterType()) {
6884     CharacterLiteral::CharacterKind Kind;
6885     if (T->isWideCharType())
6886       Kind = CharacterLiteral::Wide;
6887     else if (T->isChar8Type() && getLangOpts().Char8)
6888       Kind = CharacterLiteral::UTF8;
6889     else if (T->isChar16Type())
6890       Kind = CharacterLiteral::UTF16;
6891     else if (T->isChar32Type())
6892       Kind = CharacterLiteral::UTF32;
6893     else
6894       Kind = CharacterLiteral::Ascii;
6895 
6896     E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
6897                                        Kind, T, Loc);
6898   } else if (T->isBooleanType()) {
6899     E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
6900                                          T, Loc);
6901   } else if (T->isNullPtrType()) {
6902     E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
6903   } else {
6904     E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
6905   }
6906 
6907   if (OrigT->isEnumeralType()) {
6908     // FIXME: This is a hack. We need a better way to handle substituted
6909     // non-type template parameters.
6910     E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
6911                                nullptr,
6912                                Context.getTrivialTypeSourceInfo(OrigT, Loc),
6913                                Loc, Loc);
6914   }
6915 
6916   return E;
6917 }
6918 
6919 /// Match two template parameters within template parameter lists.
6920 static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
6921                                        bool Complain,
6922                                      Sema::TemplateParameterListEqualKind Kind,
6923                                        SourceLocation TemplateArgLoc) {
6924   // Check the actual kind (type, non-type, template).
6925   if (Old->getKind() != New->getKind()) {
6926     if (Complain) {
6927       unsigned NextDiag = diag::err_template_param_different_kind;
6928       if (TemplateArgLoc.isValid()) {
6929         S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6930         NextDiag = diag::note_template_param_different_kind;
6931       }
6932       S.Diag(New->getLocation(), NextDiag)
6933         << (Kind != Sema::TPL_TemplateMatch);
6934       S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
6935         << (Kind != Sema::TPL_TemplateMatch);
6936     }
6937 
6938     return false;
6939   }
6940 
6941   // Check that both are parameter packs or neither are parameter packs.
6942   // However, if we are matching a template template argument to a
6943   // template template parameter, the template template parameter can have
6944   // a parameter pack where the template template argument does not.
6945   if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
6946       !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6947         Old->isTemplateParameterPack())) {
6948     if (Complain) {
6949       unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
6950       if (TemplateArgLoc.isValid()) {
6951         S.Diag(TemplateArgLoc,
6952              diag::err_template_arg_template_params_mismatch);
6953         NextDiag = diag::note_template_parameter_pack_non_pack;
6954       }
6955 
6956       unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
6957                       : isa<NonTypeTemplateParmDecl>(New)? 1
6958                       : 2;
6959       S.Diag(New->getLocation(), NextDiag)
6960         << ParamKind << New->isParameterPack();
6961       S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
6962         << ParamKind << Old->isParameterPack();
6963     }
6964 
6965     return false;
6966   }
6967 
6968   // For non-type template parameters, check the type of the parameter.
6969   if (NonTypeTemplateParmDecl *OldNTTP
6970                                     = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
6971     NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
6972 
6973     // If we are matching a template template argument to a template
6974     // template parameter and one of the non-type template parameter types
6975     // is dependent, then we must wait until template instantiation time
6976     // to actually compare the arguments.
6977     if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6978         (OldNTTP->getType()->isDependentType() ||
6979          NewNTTP->getType()->isDependentType()))
6980       return true;
6981 
6982     if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
6983       if (Complain) {
6984         unsigned NextDiag = diag::err_template_nontype_parm_different_type;
6985         if (TemplateArgLoc.isValid()) {
6986           S.Diag(TemplateArgLoc,
6987                  diag::err_template_arg_template_params_mismatch);
6988           NextDiag = diag::note_template_nontype_parm_different_type;
6989         }
6990         S.Diag(NewNTTP->getLocation(), NextDiag)
6991           << NewNTTP->getType()
6992           << (Kind != Sema::TPL_TemplateMatch);
6993         S.Diag(OldNTTP->getLocation(),
6994                diag::note_template_nontype_parm_prev_declaration)
6995           << OldNTTP->getType();
6996       }
6997 
6998       return false;
6999     }
7000 
7001     return true;
7002   }
7003 
7004   // For template template parameters, check the template parameter types.
7005   // The template parameter lists of template template
7006   // parameters must agree.
7007   if (TemplateTemplateParmDecl *OldTTP
7008                                     = dyn_cast<TemplateTemplateParmDecl>(Old)) {
7009     TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
7010     return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
7011                                             OldTTP->getTemplateParameters(),
7012                                             Complain,
7013                                         (Kind == Sema::TPL_TemplateMatch
7014                                            ? Sema::TPL_TemplateTemplateParmMatch
7015                                            : Kind),
7016                                             TemplateArgLoc);
7017   }
7018 
7019   return true;
7020 }
7021 
7022 /// Diagnose a known arity mismatch when comparing template argument
7023 /// lists.
7024 static
7025 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
7026                                                 TemplateParameterList *New,
7027                                                 TemplateParameterList *Old,
7028                                       Sema::TemplateParameterListEqualKind Kind,
7029                                                 SourceLocation TemplateArgLoc) {
7030   unsigned NextDiag = diag::err_template_param_list_different_arity;
7031   if (TemplateArgLoc.isValid()) {
7032     S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7033     NextDiag = diag::note_template_param_list_different_arity;
7034   }
7035   S.Diag(New->getTemplateLoc(), NextDiag)
7036     << (New->size() > Old->size())
7037     << (Kind != Sema::TPL_TemplateMatch)
7038     << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
7039   S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
7040     << (Kind != Sema::TPL_TemplateMatch)
7041     << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
7042 }
7043 
7044 /// Determine whether the given template parameter lists are
7045 /// equivalent.
7046 ///
7047 /// \param New  The new template parameter list, typically written in the
7048 /// source code as part of a new template declaration.
7049 ///
7050 /// \param Old  The old template parameter list, typically found via
7051 /// name lookup of the template declared with this template parameter
7052 /// list.
7053 ///
7054 /// \param Complain  If true, this routine will produce a diagnostic if
7055 /// the template parameter lists are not equivalent.
7056 ///
7057 /// \param Kind describes how we are to match the template parameter lists.
7058 ///
7059 /// \param TemplateArgLoc If this source location is valid, then we
7060 /// are actually checking the template parameter list of a template
7061 /// argument (New) against the template parameter list of its
7062 /// corresponding template template parameter (Old). We produce
7063 /// slightly different diagnostics in this scenario.
7064 ///
7065 /// \returns True if the template parameter lists are equal, false
7066 /// otherwise.
7067 bool
7068 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
7069                                      TemplateParameterList *Old,
7070                                      bool Complain,
7071                                      TemplateParameterListEqualKind Kind,
7072                                      SourceLocation TemplateArgLoc) {
7073   if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
7074     if (Complain)
7075       DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7076                                                  TemplateArgLoc);
7077 
7078     return false;
7079   }
7080 
7081   // C++0x [temp.arg.template]p3:
7082   //   A template-argument matches a template template-parameter (call it P)
7083   //   when each of the template parameters in the template-parameter-list of
7084   //   the template-argument's corresponding class template or alias template
7085   //   (call it A) matches the corresponding template parameter in the
7086   //   template-parameter-list of P. [...]
7087   TemplateParameterList::iterator NewParm = New->begin();
7088   TemplateParameterList::iterator NewParmEnd = New->end();
7089   for (TemplateParameterList::iterator OldParm = Old->begin(),
7090                                     OldParmEnd = Old->end();
7091        OldParm != OldParmEnd; ++OldParm) {
7092     if (Kind != TPL_TemplateTemplateArgumentMatch ||
7093         !(*OldParm)->isTemplateParameterPack()) {
7094       if (NewParm == NewParmEnd) {
7095         if (Complain)
7096           DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7097                                                      TemplateArgLoc);
7098 
7099         return false;
7100       }
7101 
7102       if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7103                                       Kind, TemplateArgLoc))
7104         return false;
7105 
7106       ++NewParm;
7107       continue;
7108     }
7109 
7110     // C++0x [temp.arg.template]p3:
7111     //   [...] When P's template- parameter-list contains a template parameter
7112     //   pack (14.5.3), the template parameter pack will match zero or more
7113     //   template parameters or template parameter packs in the
7114     //   template-parameter-list of A with the same type and form as the
7115     //   template parameter pack in P (ignoring whether those template
7116     //   parameters are template parameter packs).
7117     for (; NewParm != NewParmEnd; ++NewParm) {
7118       if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7119                                       Kind, TemplateArgLoc))
7120         return false;
7121     }
7122   }
7123 
7124   // Make sure we exhausted all of the arguments.
7125   if (NewParm != NewParmEnd) {
7126     if (Complain)
7127       DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7128                                                  TemplateArgLoc);
7129 
7130     return false;
7131   }
7132 
7133   return true;
7134 }
7135 
7136 /// Check whether a template can be declared within this scope.
7137 ///
7138 /// If the template declaration is valid in this scope, returns
7139 /// false. Otherwise, issues a diagnostic and returns true.
7140 bool
7141 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
7142   if (!S)
7143     return false;
7144 
7145   // Find the nearest enclosing declaration scope.
7146   while ((S->getFlags() & Scope::DeclScope) == 0 ||
7147          (S->getFlags() & Scope::TemplateParamScope) != 0)
7148     S = S->getParent();
7149 
7150   // C++ [temp]p4:
7151   //   A template [...] shall not have C linkage.
7152   DeclContext *Ctx = S->getEntity();
7153   if (Ctx && Ctx->isExternCContext()) {
7154     Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
7155         << TemplateParams->getSourceRange();
7156     if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
7157       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
7158     return true;
7159   }
7160   Ctx = Ctx->getRedeclContext();
7161 
7162   // C++ [temp]p2:
7163   //   A template-declaration can appear only as a namespace scope or
7164   //   class scope declaration.
7165   if (Ctx) {
7166     if (Ctx->isFileContext())
7167       return false;
7168     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
7169       // C++ [temp.mem]p2:
7170       //   A local class shall not have member templates.
7171       if (RD->isLocalClass())
7172         return Diag(TemplateParams->getTemplateLoc(),
7173                     diag::err_template_inside_local_class)
7174           << TemplateParams->getSourceRange();
7175       else
7176         return false;
7177     }
7178   }
7179 
7180   return Diag(TemplateParams->getTemplateLoc(),
7181               diag::err_template_outside_namespace_or_class_scope)
7182     << TemplateParams->getSourceRange();
7183 }
7184 
7185 /// Determine what kind of template specialization the given declaration
7186 /// is.
7187 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
7188   if (!D)
7189     return TSK_Undeclared;
7190 
7191   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
7192     return Record->getTemplateSpecializationKind();
7193   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
7194     return Function->getTemplateSpecializationKind();
7195   if (VarDecl *Var = dyn_cast<VarDecl>(D))
7196     return Var->getTemplateSpecializationKind();
7197 
7198   return TSK_Undeclared;
7199 }
7200 
7201 /// Check whether a specialization is well-formed in the current
7202 /// context.
7203 ///
7204 /// This routine determines whether a template specialization can be declared
7205 /// in the current context (C++ [temp.expl.spec]p2).
7206 ///
7207 /// \param S the semantic analysis object for which this check is being
7208 /// performed.
7209 ///
7210 /// \param Specialized the entity being specialized or instantiated, which
7211 /// may be a kind of template (class template, function template, etc.) or
7212 /// a member of a class template (member function, static data member,
7213 /// member class).
7214 ///
7215 /// \param PrevDecl the previous declaration of this entity, if any.
7216 ///
7217 /// \param Loc the location of the explicit specialization or instantiation of
7218 /// this entity.
7219 ///
7220 /// \param IsPartialSpecialization whether this is a partial specialization of
7221 /// a class template.
7222 ///
7223 /// \returns true if there was an error that we cannot recover from, false
7224 /// otherwise.
7225 static bool CheckTemplateSpecializationScope(Sema &S,
7226                                              NamedDecl *Specialized,
7227                                              NamedDecl *PrevDecl,
7228                                              SourceLocation Loc,
7229                                              bool IsPartialSpecialization) {
7230   // Keep these "kind" numbers in sync with the %select statements in the
7231   // various diagnostics emitted by this routine.
7232   int EntityKind = 0;
7233   if (isa<ClassTemplateDecl>(Specialized))
7234     EntityKind = IsPartialSpecialization? 1 : 0;
7235   else if (isa<VarTemplateDecl>(Specialized))
7236     EntityKind = IsPartialSpecialization ? 3 : 2;
7237   else if (isa<FunctionTemplateDecl>(Specialized))
7238     EntityKind = 4;
7239   else if (isa<CXXMethodDecl>(Specialized))
7240     EntityKind = 5;
7241   else if (isa<VarDecl>(Specialized))
7242     EntityKind = 6;
7243   else if (isa<RecordDecl>(Specialized))
7244     EntityKind = 7;
7245   else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
7246     EntityKind = 8;
7247   else {
7248     S.Diag(Loc, diag::err_template_spec_unknown_kind)
7249       << S.getLangOpts().CPlusPlus11;
7250     S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7251     return true;
7252   }
7253 
7254   // C++ [temp.expl.spec]p2:
7255   //   An explicit specialization may be declared in any scope in which
7256   //   the corresponding primary template may be defined.
7257   if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7258     S.Diag(Loc, diag::err_template_spec_decl_function_scope)
7259       << Specialized;
7260     return true;
7261   }
7262 
7263   // C++ [temp.class.spec]p6:
7264   //   A class template partial specialization may be declared in any
7265   //   scope in which the primary template may be defined.
7266   DeclContext *SpecializedContext =
7267       Specialized->getDeclContext()->getRedeclContext();
7268   DeclContext *DC = S.CurContext->getRedeclContext();
7269 
7270   // Make sure that this redeclaration (or definition) occurs in the same
7271   // scope or an enclosing namespace.
7272   if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
7273                             : DC->Equals(SpecializedContext))) {
7274     if (isa<TranslationUnitDecl>(SpecializedContext))
7275       S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
7276         << EntityKind << Specialized;
7277     else {
7278       auto *ND = cast<NamedDecl>(SpecializedContext);
7279       int Diag = diag::err_template_spec_redecl_out_of_scope;
7280       if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
7281         Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
7282       S.Diag(Loc, Diag) << EntityKind << Specialized
7283                         << ND << isa<CXXRecordDecl>(ND);
7284     }
7285 
7286     S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7287 
7288     // Don't allow specializing in the wrong class during error recovery.
7289     // Otherwise, things can go horribly wrong.
7290     if (DC->isRecord())
7291       return true;
7292   }
7293 
7294   return false;
7295 }
7296 
7297 static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
7298   if (!E->isTypeDependent())
7299     return SourceLocation();
7300   DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7301   Checker.TraverseStmt(E);
7302   if (Checker.MatchLoc.isInvalid())
7303     return E->getSourceRange();
7304   return Checker.MatchLoc;
7305 }
7306 
7307 static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
7308   if (!TL.getType()->isDependentType())
7309     return SourceLocation();
7310   DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7311   Checker.TraverseTypeLoc(TL);
7312   if (Checker.MatchLoc.isInvalid())
7313     return TL.getSourceRange();
7314   return Checker.MatchLoc;
7315 }
7316 
7317 /// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
7318 /// that checks non-type template partial specialization arguments.
7319 static bool CheckNonTypeTemplatePartialSpecializationArgs(
7320     Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7321     const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
7322   for (unsigned I = 0; I != NumArgs; ++I) {
7323     if (Args[I].getKind() == TemplateArgument::Pack) {
7324       if (CheckNonTypeTemplatePartialSpecializationArgs(
7325               S, TemplateNameLoc, Param, Args[I].pack_begin(),
7326               Args[I].pack_size(), IsDefaultArgument))
7327         return true;
7328 
7329       continue;
7330     }
7331 
7332     if (Args[I].getKind() != TemplateArgument::Expression)
7333       continue;
7334 
7335     Expr *ArgExpr = Args[I].getAsExpr();
7336 
7337     // We can have a pack expansion of any of the bullets below.
7338     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7339       ArgExpr = Expansion->getPattern();
7340 
7341     // Strip off any implicit casts we added as part of type checking.
7342     while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7343       ArgExpr = ICE->getSubExpr();
7344 
7345     // C++ [temp.class.spec]p8:
7346     //   A non-type argument is non-specialized if it is the name of a
7347     //   non-type parameter. All other non-type arguments are
7348     //   specialized.
7349     //
7350     // Below, we check the two conditions that only apply to
7351     // specialized non-type arguments, so skip any non-specialized
7352     // arguments.
7353     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
7354       if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
7355         continue;
7356 
7357     // C++ [temp.class.spec]p9:
7358     //   Within the argument list of a class template partial
7359     //   specialization, the following restrictions apply:
7360     //     -- A partially specialized non-type argument expression
7361     //        shall not involve a template parameter of the partial
7362     //        specialization except when the argument expression is a
7363     //        simple identifier.
7364     //     -- The type of a template parameter corresponding to a
7365     //        specialized non-type argument shall not be dependent on a
7366     //        parameter of the specialization.
7367     // DR1315 removes the first bullet, leaving an incoherent set of rules.
7368     // We implement a compromise between the original rules and DR1315:
7369     //     --  A specialized non-type template argument shall not be
7370     //         type-dependent and the corresponding template parameter
7371     //         shall have a non-dependent type.
7372     SourceRange ParamUseRange =
7373         findTemplateParameterInType(Param->getDepth(), ArgExpr);
7374     if (ParamUseRange.isValid()) {
7375       if (IsDefaultArgument) {
7376         S.Diag(TemplateNameLoc,
7377                diag::err_dependent_non_type_arg_in_partial_spec);
7378         S.Diag(ParamUseRange.getBegin(),
7379                diag::note_dependent_non_type_default_arg_in_partial_spec)
7380           << ParamUseRange;
7381       } else {
7382         S.Diag(ParamUseRange.getBegin(),
7383                diag::err_dependent_non_type_arg_in_partial_spec)
7384           << ParamUseRange;
7385       }
7386       return true;
7387     }
7388 
7389     ParamUseRange = findTemplateParameter(
7390         Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
7391     if (ParamUseRange.isValid()) {
7392       S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
7393              diag::err_dependent_typed_non_type_arg_in_partial_spec)
7394           << Param->getType();
7395       S.Diag(Param->getLocation(), diag::note_template_param_here)
7396         << (IsDefaultArgument ? ParamUseRange : SourceRange())
7397         << ParamUseRange;
7398       return true;
7399     }
7400   }
7401 
7402   return false;
7403 }
7404 
7405 /// Check the non-type template arguments of a class template
7406 /// partial specialization according to C++ [temp.class.spec]p9.
7407 ///
7408 /// \param TemplateNameLoc the location of the template name.
7409 /// \param PrimaryTemplate the template parameters of the primary class
7410 ///        template.
7411 /// \param NumExplicit the number of explicitly-specified template arguments.
7412 /// \param TemplateArgs the template arguments of the class template
7413 ///        partial specialization.
7414 ///
7415 /// \returns \c true if there was an error, \c false otherwise.
7416 bool Sema::CheckTemplatePartialSpecializationArgs(
7417     SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7418     unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7419   // We have to be conservative when checking a template in a dependent
7420   // context.
7421   if (PrimaryTemplate->getDeclContext()->isDependentContext())
7422     return false;
7423 
7424   TemplateParameterList *TemplateParams =
7425       PrimaryTemplate->getTemplateParameters();
7426   for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7427     NonTypeTemplateParmDecl *Param
7428       = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7429     if (!Param)
7430       continue;
7431 
7432     if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7433                                                       Param, &TemplateArgs[I],
7434                                                       1, I >= NumExplicit))
7435       return true;
7436   }
7437 
7438   return false;
7439 }
7440 
7441 DeclResult Sema::ActOnClassTemplateSpecialization(
7442     Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7443     SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId,
7444     const ParsedAttributesView &Attr,
7445     MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
7446   assert(TUK != TUK_Reference && "References are not specializations");
7447 
7448   CXXScopeSpec &SS = TemplateId.SS;
7449 
7450   // NOTE: KWLoc is the location of the tag keyword. This will instead
7451   // store the location of the outermost template keyword in the declaration.
7452   SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
7453     ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7454   SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7455   SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7456   SourceLocation RAngleLoc = TemplateId.RAngleLoc;
7457 
7458   // Find the class template we're specializing
7459   TemplateName Name = TemplateId.Template.get();
7460   ClassTemplateDecl *ClassTemplate
7461     = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7462 
7463   if (!ClassTemplate) {
7464     Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
7465       << (Name.getAsTemplateDecl() &&
7466           isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7467     return true;
7468   }
7469 
7470   bool isMemberSpecialization = false;
7471   bool isPartialSpecialization = false;
7472 
7473   // Check the validity of the template headers that introduce this
7474   // template.
7475   // FIXME: We probably shouldn't complain about these headers for
7476   // friend declarations.
7477   bool Invalid = false;
7478   TemplateParameterList *TemplateParams =
7479       MatchTemplateParametersToScopeSpecifier(
7480           KWLoc, TemplateNameLoc, SS, &TemplateId,
7481           TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
7482           Invalid);
7483   if (Invalid)
7484     return true;
7485 
7486   if (TemplateParams && TemplateParams->size() > 0) {
7487     isPartialSpecialization = true;
7488 
7489     if (TUK == TUK_Friend) {
7490       Diag(KWLoc, diag::err_partial_specialization_friend)
7491         << SourceRange(LAngleLoc, RAngleLoc);
7492       return true;
7493     }
7494 
7495     // C++ [temp.class.spec]p10:
7496     //   The template parameter list of a specialization shall not
7497     //   contain default template argument values.
7498     for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7499       Decl *Param = TemplateParams->getParam(I);
7500       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7501         if (TTP->hasDefaultArgument()) {
7502           Diag(TTP->getDefaultArgumentLoc(),
7503                diag::err_default_arg_in_partial_spec);
7504           TTP->removeDefaultArgument();
7505         }
7506       } else if (NonTypeTemplateParmDecl *NTTP
7507                    = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7508         if (Expr *DefArg = NTTP->getDefaultArgument()) {
7509           Diag(NTTP->getDefaultArgumentLoc(),
7510                diag::err_default_arg_in_partial_spec)
7511             << DefArg->getSourceRange();
7512           NTTP->removeDefaultArgument();
7513         }
7514       } else {
7515         TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
7516         if (TTP->hasDefaultArgument()) {
7517           Diag(TTP->getDefaultArgument().getLocation(),
7518                diag::err_default_arg_in_partial_spec)
7519             << TTP->getDefaultArgument().getSourceRange();
7520           TTP->removeDefaultArgument();
7521         }
7522       }
7523     }
7524   } else if (TemplateParams) {
7525     if (TUK == TUK_Friend)
7526       Diag(KWLoc, diag::err_template_spec_friend)
7527         << FixItHint::CreateRemoval(
7528                                 SourceRange(TemplateParams->getTemplateLoc(),
7529                                             TemplateParams->getRAngleLoc()))
7530         << SourceRange(LAngleLoc, RAngleLoc);
7531   } else {
7532     assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
7533   }
7534 
7535   // Check that the specialization uses the same tag kind as the
7536   // original template.
7537   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7538   assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
7539   if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
7540                                     Kind, TUK == TUK_Definition, KWLoc,
7541                                     ClassTemplate->getIdentifier())) {
7542     Diag(KWLoc, diag::err_use_with_wrong_tag)
7543       << ClassTemplate
7544       << FixItHint::CreateReplacement(KWLoc,
7545                             ClassTemplate->getTemplatedDecl()->getKindName());
7546     Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
7547          diag::note_previous_use);
7548     Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7549   }
7550 
7551   // Translate the parser's template argument list in our AST format.
7552   TemplateArgumentListInfo TemplateArgs =
7553       makeTemplateArgumentListInfo(*this, TemplateId);
7554 
7555   // Check for unexpanded parameter packs in any of the template arguments.
7556   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7557     if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
7558                                         UPPC_PartialSpecialization))
7559       return true;
7560 
7561   // Check that the template argument list is well-formed for this
7562   // template.
7563   SmallVector<TemplateArgument, 4> Converted;
7564   if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7565                                 TemplateArgs, false, Converted))
7566     return true;
7567 
7568   // Find the class template (partial) specialization declaration that
7569   // corresponds to these arguments.
7570   if (isPartialSpecialization) {
7571     if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7572                                                TemplateArgs.size(), Converted))
7573       return true;
7574 
7575     // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7576     // also do it during instantiation.
7577     bool InstantiationDependent;
7578     if (!Name.isDependent() &&
7579         !TemplateSpecializationType::anyDependentTemplateArguments(
7580             TemplateArgs.arguments(), InstantiationDependent)) {
7581       Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7582         << ClassTemplate->getDeclName();
7583       isPartialSpecialization = false;
7584     }
7585   }
7586 
7587   void *InsertPos = nullptr;
7588   ClassTemplateSpecializationDecl *PrevDecl = nullptr;
7589 
7590   if (isPartialSpecialization)
7591     // FIXME: Template parameter list matters, too
7592     PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
7593   else
7594     PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
7595 
7596   ClassTemplateSpecializationDecl *Specialization = nullptr;
7597 
7598   // Check whether we can declare a class template specialization in
7599   // the current scope.
7600   if (TUK != TUK_Friend &&
7601       CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7602                                        TemplateNameLoc,
7603                                        isPartialSpecialization))
7604     return true;
7605 
7606   // The canonical type
7607   QualType CanonType;
7608   if (isPartialSpecialization) {
7609     // Build the canonical type that describes the converted template
7610     // arguments of the class template partial specialization.
7611     TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7612     CanonType = Context.getTemplateSpecializationType(CanonTemplate,
7613                                                       Converted);
7614 
7615     if (Context.hasSameType(CanonType,
7616                         ClassTemplate->getInjectedClassNameSpecialization())) {
7617       // C++ [temp.class.spec]p9b3:
7618       //
7619       //   -- The argument list of the specialization shall not be identical
7620       //      to the implicit argument list of the primary template.
7621       //
7622       // This rule has since been removed, because it's redundant given DR1495,
7623       // but we keep it because it produces better diagnostics and recovery.
7624       Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
7625         << /*class template*/0 << (TUK == TUK_Definition)
7626         << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
7627       return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7628                                 ClassTemplate->getIdentifier(),
7629                                 TemplateNameLoc,
7630                                 Attr,
7631                                 TemplateParams,
7632                                 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
7633                                 /*FriendLoc*/SourceLocation(),
7634                                 TemplateParameterLists.size() - 1,
7635                                 TemplateParameterLists.data());
7636     }
7637 
7638     // Create a new class template partial specialization declaration node.
7639     ClassTemplatePartialSpecializationDecl *PrevPartial
7640       = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
7641     ClassTemplatePartialSpecializationDecl *Partial
7642       = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
7643                                              ClassTemplate->getDeclContext(),
7644                                                        KWLoc, TemplateNameLoc,
7645                                                        TemplateParams,
7646                                                        ClassTemplate,
7647                                                        Converted,
7648                                                        TemplateArgs,
7649                                                        CanonType,
7650                                                        PrevPartial);
7651     SetNestedNameSpecifier(Partial, SS);
7652     if (TemplateParameterLists.size() > 1 && SS.isSet()) {
7653       Partial->setTemplateParameterListsInfo(
7654           Context, TemplateParameterLists.drop_back(1));
7655     }
7656 
7657     if (!PrevPartial)
7658       ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
7659     Specialization = Partial;
7660 
7661     // If we are providing an explicit specialization of a member class
7662     // template specialization, make a note of that.
7663     if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7664       PrevPartial->setMemberSpecialization();
7665 
7666     CheckTemplatePartialSpecialization(Partial);
7667   } else {
7668     // Create a new class template specialization declaration node for
7669     // this explicit specialization or friend declaration.
7670     Specialization
7671       = ClassTemplateSpecializationDecl::Create(Context, Kind,
7672                                              ClassTemplate->getDeclContext(),
7673                                                 KWLoc, TemplateNameLoc,
7674                                                 ClassTemplate,
7675                                                 Converted,
7676                                                 PrevDecl);
7677     SetNestedNameSpecifier(Specialization, SS);
7678     if (TemplateParameterLists.size() > 0) {
7679       Specialization->setTemplateParameterListsInfo(Context,
7680                                                     TemplateParameterLists);
7681     }
7682 
7683     if (!PrevDecl)
7684       ClassTemplate->AddSpecialization(Specialization, InsertPos);
7685 
7686     if (CurContext->isDependentContext()) {
7687       TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7688       CanonType = Context.getTemplateSpecializationType(
7689           CanonTemplate, Converted);
7690     } else {
7691       CanonType = Context.getTypeDeclType(Specialization);
7692     }
7693   }
7694 
7695   // C++ [temp.expl.spec]p6:
7696   //   If a template, a member template or the member of a class template is
7697   //   explicitly specialized then that specialization shall be declared
7698   //   before the first use of that specialization that would cause an implicit
7699   //   instantiation to take place, in every translation unit in which such a
7700   //   use occurs; no diagnostic is required.
7701   if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
7702     bool Okay = false;
7703     for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7704       // Is there any previous explicit specialization declaration?
7705       if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7706         Okay = true;
7707         break;
7708       }
7709     }
7710 
7711     if (!Okay) {
7712       SourceRange Range(TemplateNameLoc, RAngleLoc);
7713       Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7714         << Context.getTypeDeclType(Specialization) << Range;
7715 
7716       Diag(PrevDecl->getPointOfInstantiation(),
7717            diag::note_instantiation_required_here)
7718         << (PrevDecl->getTemplateSpecializationKind()
7719                                                 != TSK_ImplicitInstantiation);
7720       return true;
7721     }
7722   }
7723 
7724   // If this is not a friend, note that this is an explicit specialization.
7725   if (TUK != TUK_Friend)
7726     Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
7727 
7728   // Check that this isn't a redefinition of this specialization.
7729   if (TUK == TUK_Definition) {
7730     RecordDecl *Def = Specialization->getDefinition();
7731     NamedDecl *Hidden = nullptr;
7732     if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7733       SkipBody->ShouldSkip = true;
7734       SkipBody->Previous = Def;
7735       makeMergedDefinitionVisible(Hidden);
7736     } else if (Def) {
7737       SourceRange Range(TemplateNameLoc, RAngleLoc);
7738       Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
7739       Diag(Def->getLocation(), diag::note_previous_definition);
7740       Specialization->setInvalidDecl();
7741       return true;
7742     }
7743   }
7744 
7745   ProcessDeclAttributeList(S, Specialization, Attr);
7746 
7747   // Add alignment attributes if necessary; these attributes are checked when
7748   // the ASTContext lays out the structure.
7749   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
7750     AddAlignmentAttributesForRecord(Specialization);
7751     AddMsStructLayoutForRecord(Specialization);
7752   }
7753 
7754   if (ModulePrivateLoc.isValid())
7755     Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7756       << (isPartialSpecialization? 1 : 0)
7757       << FixItHint::CreateRemoval(ModulePrivateLoc);
7758 
7759   // Build the fully-sugared type for this class template
7760   // specialization as the user wrote in the specialization
7761   // itself. This means that we'll pretty-print the type retrieved
7762   // from the specialization's declaration the way that the user
7763   // actually wrote the specialization, rather than formatting the
7764   // name based on the "canonical" representation used to store the
7765   // template arguments in the specialization.
7766   TypeSourceInfo *WrittenTy
7767     = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7768                                                 TemplateArgs, CanonType);
7769   if (TUK != TUK_Friend) {
7770     Specialization->setTypeAsWritten(WrittenTy);
7771     Specialization->setTemplateKeywordLoc(TemplateKWLoc);
7772   }
7773 
7774   // C++ [temp.expl.spec]p9:
7775   //   A template explicit specialization is in the scope of the
7776   //   namespace in which the template was defined.
7777   //
7778   // We actually implement this paragraph where we set the semantic
7779   // context (in the creation of the ClassTemplateSpecializationDecl),
7780   // but we also maintain the lexical context where the actual
7781   // definition occurs.
7782   Specialization->setLexicalDeclContext(CurContext);
7783 
7784   // We may be starting the definition of this specialization.
7785   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
7786     Specialization->startDefinition();
7787 
7788   if (TUK == TUK_Friend) {
7789     FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
7790                                             TemplateNameLoc,
7791                                             WrittenTy,
7792                                             /*FIXME:*/KWLoc);
7793     Friend->setAccess(AS_public);
7794     CurContext->addDecl(Friend);
7795   } else {
7796     // Add the specialization into its lexical context, so that it can
7797     // be seen when iterating through the list of declarations in that
7798     // context. However, specializations are not found by name lookup.
7799     CurContext->addDecl(Specialization);
7800   }
7801 
7802   if (SkipBody && SkipBody->ShouldSkip)
7803     return SkipBody->Previous;
7804 
7805   return Specialization;
7806 }
7807 
7808 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
7809                               MultiTemplateParamsArg TemplateParameterLists,
7810                                     Declarator &D) {
7811   Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
7812   ActOnDocumentableDecl(NewDecl);
7813   return NewDecl;
7814 }
7815 
7816 /// Strips various properties off an implicit instantiation
7817 /// that has just been explicitly specialized.
7818 static void StripImplicitInstantiation(NamedDecl *D) {
7819   D->dropAttr<DLLImportAttr>();
7820   D->dropAttr<DLLExportAttr>();
7821 
7822   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7823     FD->setInlineSpecified(false);
7824 }
7825 
7826 /// Compute the diagnostic location for an explicit instantiation
7827 //  declaration or definition.
7828 static SourceLocation DiagLocForExplicitInstantiation(
7829     NamedDecl* D, SourceLocation PointOfInstantiation) {
7830   // Explicit instantiations following a specialization have no effect and
7831   // hence no PointOfInstantiation. In that case, walk decl backwards
7832   // until a valid name loc is found.
7833   SourceLocation PrevDiagLoc = PointOfInstantiation;
7834   for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7835        Prev = Prev->getPreviousDecl()) {
7836     PrevDiagLoc = Prev->getLocation();
7837   }
7838   assert(PrevDiagLoc.isValid() &&
7839          "Explicit instantiation without point of instantiation?");
7840   return PrevDiagLoc;
7841 }
7842 
7843 /// Diagnose cases where we have an explicit template specialization
7844 /// before/after an explicit template instantiation, producing diagnostics
7845 /// for those cases where they are required and determining whether the
7846 /// new specialization/instantiation will have any effect.
7847 ///
7848 /// \param NewLoc the location of the new explicit specialization or
7849 /// instantiation.
7850 ///
7851 /// \param NewTSK the kind of the new explicit specialization or instantiation.
7852 ///
7853 /// \param PrevDecl the previous declaration of the entity.
7854 ///
7855 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7856 ///
7857 /// \param PrevPointOfInstantiation if valid, indicates where the previus
7858 /// declaration was instantiated (either implicitly or explicitly).
7859 ///
7860 /// \param HasNoEffect will be set to true to indicate that the new
7861 /// specialization or instantiation has no effect and should be ignored.
7862 ///
7863 /// \returns true if there was an error that should prevent the introduction of
7864 /// the new declaration into the AST, false otherwise.
7865 bool
7866 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7867                                              TemplateSpecializationKind NewTSK,
7868                                              NamedDecl *PrevDecl,
7869                                              TemplateSpecializationKind PrevTSK,
7870                                         SourceLocation PrevPointOfInstantiation,
7871                                              bool &HasNoEffect) {
7872   HasNoEffect = false;
7873 
7874   switch (NewTSK) {
7875   case TSK_Undeclared:
7876   case TSK_ImplicitInstantiation:
7877     assert(
7878         (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
7879         "previous declaration must be implicit!");
7880     return false;
7881 
7882   case TSK_ExplicitSpecialization:
7883     switch (PrevTSK) {
7884     case TSK_Undeclared:
7885     case TSK_ExplicitSpecialization:
7886       // Okay, we're just specializing something that is either already
7887       // explicitly specialized or has merely been mentioned without any
7888       // instantiation.
7889       return false;
7890 
7891     case TSK_ImplicitInstantiation:
7892       if (PrevPointOfInstantiation.isInvalid()) {
7893         // The declaration itself has not actually been instantiated, so it is
7894         // still okay to specialize it.
7895         StripImplicitInstantiation(PrevDecl);
7896         return false;
7897       }
7898       // Fall through
7899       LLVM_FALLTHROUGH;
7900 
7901     case TSK_ExplicitInstantiationDeclaration:
7902     case TSK_ExplicitInstantiationDefinition:
7903       assert((PrevTSK == TSK_ImplicitInstantiation ||
7904               PrevPointOfInstantiation.isValid()) &&
7905              "Explicit instantiation without point of instantiation?");
7906 
7907       // C++ [temp.expl.spec]p6:
7908       //   If a template, a member template or the member of a class template
7909       //   is explicitly specialized then that specialization shall be declared
7910       //   before the first use of that specialization that would cause an
7911       //   implicit instantiation to take place, in every translation unit in
7912       //   which such a use occurs; no diagnostic is required.
7913       for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7914         // Is there any previous explicit specialization declaration?
7915         if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
7916           return false;
7917       }
7918 
7919       Diag(NewLoc, diag::err_specialization_after_instantiation)
7920         << PrevDecl;
7921       Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
7922         << (PrevTSK != TSK_ImplicitInstantiation);
7923 
7924       return true;
7925     }
7926     llvm_unreachable("The switch over PrevTSK must be exhaustive.");
7927 
7928   case TSK_ExplicitInstantiationDeclaration:
7929     switch (PrevTSK) {
7930     case TSK_ExplicitInstantiationDeclaration:
7931       // This explicit instantiation declaration is redundant (that's okay).
7932       HasNoEffect = true;
7933       return false;
7934 
7935     case TSK_Undeclared:
7936     case TSK_ImplicitInstantiation:
7937       // We're explicitly instantiating something that may have already been
7938       // implicitly instantiated; that's fine.
7939       return false;
7940 
7941     case TSK_ExplicitSpecialization:
7942       // C++0x [temp.explicit]p4:
7943       //   For a given set of template parameters, if an explicit instantiation
7944       //   of a template appears after a declaration of an explicit
7945       //   specialization for that template, the explicit instantiation has no
7946       //   effect.
7947       HasNoEffect = true;
7948       return false;
7949 
7950     case TSK_ExplicitInstantiationDefinition:
7951       // C++0x [temp.explicit]p10:
7952       //   If an entity is the subject of both an explicit instantiation
7953       //   declaration and an explicit instantiation definition in the same
7954       //   translation unit, the definition shall follow the declaration.
7955       Diag(NewLoc,
7956            diag::err_explicit_instantiation_declaration_after_definition);
7957 
7958       // Explicit instantiations following a specialization have no effect and
7959       // hence no PrevPointOfInstantiation. In that case, walk decl backwards
7960       // until a valid name loc is found.
7961       Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7962            diag::note_explicit_instantiation_definition_here);
7963       HasNoEffect = true;
7964       return false;
7965     }
7966 
7967   case TSK_ExplicitInstantiationDefinition:
7968     switch (PrevTSK) {
7969     case TSK_Undeclared:
7970     case TSK_ImplicitInstantiation:
7971       // We're explicitly instantiating something that may have already been
7972       // implicitly instantiated; that's fine.
7973       return false;
7974 
7975     case TSK_ExplicitSpecialization:
7976       // C++ DR 259, C++0x [temp.explicit]p4:
7977       //   For a given set of template parameters, if an explicit
7978       //   instantiation of a template appears after a declaration of
7979       //   an explicit specialization for that template, the explicit
7980       //   instantiation has no effect.
7981       Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
7982         << PrevDecl;
7983       Diag(PrevDecl->getLocation(),
7984            diag::note_previous_template_specialization);
7985       HasNoEffect = true;
7986       return false;
7987 
7988     case TSK_ExplicitInstantiationDeclaration:
7989       // We're explicitly instantiating a definition for something for which we
7990       // were previously asked to suppress instantiations. That's fine.
7991 
7992       // C++0x [temp.explicit]p4:
7993       //   For a given set of template parameters, if an explicit instantiation
7994       //   of a template appears after a declaration of an explicit
7995       //   specialization for that template, the explicit instantiation has no
7996       //   effect.
7997       for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7998         // Is there any previous explicit specialization declaration?
7999         if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
8000           HasNoEffect = true;
8001           break;
8002         }
8003       }
8004 
8005       return false;
8006 
8007     case TSK_ExplicitInstantiationDefinition:
8008       // C++0x [temp.spec]p5:
8009       //   For a given template and a given set of template-arguments,
8010       //     - an explicit instantiation definition shall appear at most once
8011       //       in a program,
8012 
8013       // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
8014       Diag(NewLoc, (getLangOpts().MSVCCompat)
8015                        ? diag::ext_explicit_instantiation_duplicate
8016                        : diag::err_explicit_instantiation_duplicate)
8017           << PrevDecl;
8018       Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8019            diag::note_previous_explicit_instantiation);
8020       HasNoEffect = true;
8021       return false;
8022     }
8023   }
8024 
8025   llvm_unreachable("Missing specialization/instantiation case?");
8026 }
8027 
8028 /// Perform semantic analysis for the given dependent function
8029 /// template specialization.
8030 ///
8031 /// The only possible way to get a dependent function template specialization
8032 /// is with a friend declaration, like so:
8033 ///
8034 /// \code
8035 ///   template \<class T> void foo(T);
8036 ///   template \<class T> class A {
8037 ///     friend void foo<>(T);
8038 ///   };
8039 /// \endcode
8040 ///
8041 /// There really isn't any useful analysis we can do here, so we
8042 /// just store the information.
8043 bool
8044 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
8045                    const TemplateArgumentListInfo &ExplicitTemplateArgs,
8046                                                    LookupResult &Previous) {
8047   // Remove anything from Previous that isn't a function template in
8048   // the correct context.
8049   DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
8050   LookupResult::Filter F = Previous.makeFilter();
8051   enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
8052   SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
8053   while (F.hasNext()) {
8054     NamedDecl *D = F.next()->getUnderlyingDecl();
8055     if (!isa<FunctionTemplateDecl>(D)) {
8056       F.erase();
8057       DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
8058       continue;
8059     }
8060 
8061     if (!FDLookupContext->InEnclosingNamespaceSetOf(
8062             D->getDeclContext()->getRedeclContext())) {
8063       F.erase();
8064       DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
8065       continue;
8066     }
8067   }
8068   F.done();
8069 
8070   if (Previous.empty()) {
8071     Diag(FD->getLocation(),
8072          diag::err_dependent_function_template_spec_no_match);
8073     for (auto &P : DiscardedCandidates)
8074       Diag(P.second->getLocation(),
8075            diag::note_dependent_function_template_spec_discard_reason)
8076           << P.first;
8077     return true;
8078   }
8079 
8080   FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
8081                                          ExplicitTemplateArgs);
8082   return false;
8083 }
8084 
8085 /// Perform semantic analysis for the given function template
8086 /// specialization.
8087 ///
8088 /// This routine performs all of the semantic analysis required for an
8089 /// explicit function template specialization. On successful completion,
8090 /// the function declaration \p FD will become a function template
8091 /// specialization.
8092 ///
8093 /// \param FD the function declaration, which will be updated to become a
8094 /// function template specialization.
8095 ///
8096 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
8097 /// if any. Note that this may be valid info even when 0 arguments are
8098 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
8099 /// as it anyway contains info on the angle brackets locations.
8100 ///
8101 /// \param Previous the set of declarations that may be specialized by
8102 /// this function specialization.
8103 bool Sema::CheckFunctionTemplateSpecialization(
8104     FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
8105     LookupResult &Previous) {
8106   // The set of function template specializations that could match this
8107   // explicit function template specialization.
8108   UnresolvedSet<8> Candidates;
8109   TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
8110                                             /*ForTakingAddress=*/false);
8111 
8112   llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
8113       ConvertedTemplateArgs;
8114 
8115   DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
8116   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8117          I != E; ++I) {
8118     NamedDecl *Ovl = (*I)->getUnderlyingDecl();
8119     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
8120       // Only consider templates found within the same semantic lookup scope as
8121       // FD.
8122       if (!FDLookupContext->InEnclosingNamespaceSetOf(
8123                                 Ovl->getDeclContext()->getRedeclContext()))
8124         continue;
8125 
8126       // When matching a constexpr member function template specialization
8127       // against the primary template, we don't yet know whether the
8128       // specialization has an implicit 'const' (because we don't know whether
8129       // it will be a static member function until we know which template it
8130       // specializes), so adjust it now assuming it specializes this template.
8131       QualType FT = FD->getType();
8132       if (FD->isConstexpr()) {
8133         CXXMethodDecl *OldMD =
8134           dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
8135         if (OldMD && OldMD->isConst()) {
8136           const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
8137           FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8138           EPI.TypeQuals |= Qualifiers::Const;
8139           FT = Context.getFunctionType(FPT->getReturnType(),
8140                                        FPT->getParamTypes(), EPI);
8141         }
8142       }
8143 
8144       TemplateArgumentListInfo Args;
8145       if (ExplicitTemplateArgs)
8146         Args = *ExplicitTemplateArgs;
8147 
8148       // C++ [temp.expl.spec]p11:
8149       //   A trailing template-argument can be left unspecified in the
8150       //   template-id naming an explicit function template specialization
8151       //   provided it can be deduced from the function argument type.
8152       // Perform template argument deduction to determine whether we may be
8153       // specializing this template.
8154       // FIXME: It is somewhat wasteful to build
8155       TemplateDeductionInfo Info(FailedCandidates.getLocation());
8156       FunctionDecl *Specialization = nullptr;
8157       if (TemplateDeductionResult TDK = DeduceTemplateArguments(
8158               cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
8159               ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
8160               Info)) {
8161         // Template argument deduction failed; record why it failed, so
8162         // that we can provide nifty diagnostics.
8163         FailedCandidates.addCandidate().set(
8164             I.getPair(), FunTmpl->getTemplatedDecl(),
8165             MakeDeductionFailureInfo(Context, TDK, Info));
8166         (void)TDK;
8167         continue;
8168       }
8169 
8170       // Target attributes are part of the cuda function signature, so
8171       // the deduced template's cuda target must match that of the
8172       // specialization.  Given that C++ template deduction does not
8173       // take target attributes into account, we reject candidates
8174       // here that have a different target.
8175       if (LangOpts.CUDA &&
8176           IdentifyCUDATarget(Specialization,
8177                              /* IgnoreImplicitHDAttributes = */ true) !=
8178               IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
8179         FailedCandidates.addCandidate().set(
8180             I.getPair(), FunTmpl->getTemplatedDecl(),
8181             MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8182         continue;
8183       }
8184 
8185       // Record this candidate.
8186       if (ExplicitTemplateArgs)
8187         ConvertedTemplateArgs[Specialization] = std::move(Args);
8188       Candidates.addDecl(Specialization, I.getAccess());
8189     }
8190   }
8191 
8192   // Find the most specialized function template.
8193   UnresolvedSetIterator Result = getMostSpecialized(
8194       Candidates.begin(), Candidates.end(), FailedCandidates,
8195       FD->getLocation(),
8196       PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
8197       PDiag(diag::err_function_template_spec_ambiguous)
8198           << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
8199       PDiag(diag::note_function_template_spec_matched));
8200 
8201   if (Result == Candidates.end())
8202     return true;
8203 
8204   // Ignore access information;  it doesn't figure into redeclaration checking.
8205   FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
8206 
8207   FunctionTemplateSpecializationInfo *SpecInfo
8208     = Specialization->getTemplateSpecializationInfo();
8209   assert(SpecInfo && "Function template specialization info missing?");
8210 
8211   // Note: do not overwrite location info if previous template
8212   // specialization kind was explicit.
8213   TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
8214   if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
8215     Specialization->setLocation(FD->getLocation());
8216     Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
8217     // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
8218     // function can differ from the template declaration with respect to
8219     // the constexpr specifier.
8220     // FIXME: We need an update record for this AST mutation.
8221     // FIXME: What if there are multiple such prior declarations (for instance,
8222     // from different modules)?
8223     Specialization->setConstexpr(FD->isConstexpr());
8224   }
8225 
8226   // FIXME: Check if the prior specialization has a point of instantiation.
8227   // If so, we have run afoul of .
8228 
8229   // If this is a friend declaration, then we're not really declaring
8230   // an explicit specialization.
8231   bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
8232 
8233   // Check the scope of this explicit specialization.
8234   if (!isFriend &&
8235       CheckTemplateSpecializationScope(*this,
8236                                        Specialization->getPrimaryTemplate(),
8237                                        Specialization, FD->getLocation(),
8238                                        false))
8239     return true;
8240 
8241   // C++ [temp.expl.spec]p6:
8242   //   If a template, a member template or the member of a class template is
8243   //   explicitly specialized then that specialization shall be declared
8244   //   before the first use of that specialization that would cause an implicit
8245   //   instantiation to take place, in every translation unit in which such a
8246   //   use occurs; no diagnostic is required.
8247   bool HasNoEffect = false;
8248   if (!isFriend &&
8249       CheckSpecializationInstantiationRedecl(FD->getLocation(),
8250                                              TSK_ExplicitSpecialization,
8251                                              Specialization,
8252                                    SpecInfo->getTemplateSpecializationKind(),
8253                                          SpecInfo->getPointOfInstantiation(),
8254                                              HasNoEffect))
8255     return true;
8256 
8257   // Mark the prior declaration as an explicit specialization, so that later
8258   // clients know that this is an explicit specialization.
8259   if (!isFriend) {
8260     // Since explicit specializations do not inherit '=delete' from their
8261     // primary function template - check if the 'specialization' that was
8262     // implicitly generated (during template argument deduction for partial
8263     // ordering) from the most specialized of all the function templates that
8264     // 'FD' could have been specializing, has a 'deleted' definition.  If so,
8265     // first check that it was implicitly generated during template argument
8266     // deduction by making sure it wasn't referenced, and then reset the deleted
8267     // flag to not-deleted, so that we can inherit that information from 'FD'.
8268     if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
8269         !Specialization->getCanonicalDecl()->isReferenced()) {
8270       // FIXME: This assert will not hold in the presence of modules.
8271       assert(
8272           Specialization->getCanonicalDecl() == Specialization &&
8273           "This must be the only existing declaration of this specialization");
8274       // FIXME: We need an update record for this AST mutation.
8275       Specialization->setDeletedAsWritten(false);
8276     }
8277     // FIXME: We need an update record for this AST mutation.
8278     SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8279     MarkUnusedFileScopedDecl(Specialization);
8280   }
8281 
8282   // Turn the given function declaration into a function template
8283   // specialization, with the template arguments from the previous
8284   // specialization.
8285   // Take copies of (semantic and syntactic) template argument lists.
8286   const TemplateArgumentList* TemplArgs = new (Context)
8287     TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
8288   FD->setFunctionTemplateSpecialization(
8289       Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
8290       SpecInfo->getTemplateSpecializationKind(),
8291       ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
8292 
8293   // A function template specialization inherits the target attributes
8294   // of its template.  (We require the attributes explicitly in the
8295   // code to match, but a template may have implicit attributes by
8296   // virtue e.g. of being constexpr, and it passes these implicit
8297   // attributes on to its specializations.)
8298   if (LangOpts.CUDA)
8299     inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
8300 
8301   // The "previous declaration" for this function template specialization is
8302   // the prior function template specialization.
8303   Previous.clear();
8304   Previous.addDecl(Specialization);
8305   return false;
8306 }
8307 
8308 /// Perform semantic analysis for the given non-template member
8309 /// specialization.
8310 ///
8311 /// This routine performs all of the semantic analysis required for an
8312 /// explicit member function specialization. On successful completion,
8313 /// the function declaration \p FD will become a member function
8314 /// specialization.
8315 ///
8316 /// \param Member the member declaration, which will be updated to become a
8317 /// specialization.
8318 ///
8319 /// \param Previous the set of declarations, one of which may be specialized
8320 /// by this function specialization;  the set will be modified to contain the
8321 /// redeclared member.
8322 bool
8323 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
8324   assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
8325 
8326   // Try to find the member we are instantiating.
8327   NamedDecl *FoundInstantiation = nullptr;
8328   NamedDecl *Instantiation = nullptr;
8329   NamedDecl *InstantiatedFrom = nullptr;
8330   MemberSpecializationInfo *MSInfo = nullptr;
8331 
8332   if (Previous.empty()) {
8333     // Nowhere to look anyway.
8334   } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
8335     for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8336            I != E; ++I) {
8337       NamedDecl *D = (*I)->getUnderlyingDecl();
8338       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
8339         QualType Adjusted = Function->getType();
8340         if (!hasExplicitCallingConv(Adjusted))
8341           Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
8342         // This doesn't handle deduced return types, but both function
8343         // declarations should be undeduced at this point.
8344         if (Context.hasSameType(Adjusted, Method->getType())) {
8345           FoundInstantiation = *I;
8346           Instantiation = Method;
8347           InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
8348           MSInfo = Method->getMemberSpecializationInfo();
8349           break;
8350         }
8351       }
8352     }
8353   } else if (isa<VarDecl>(Member)) {
8354     VarDecl *PrevVar;
8355     if (Previous.isSingleResult() &&
8356         (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
8357       if (PrevVar->isStaticDataMember()) {
8358         FoundInstantiation = Previous.getRepresentativeDecl();
8359         Instantiation = PrevVar;
8360         InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
8361         MSInfo = PrevVar->getMemberSpecializationInfo();
8362       }
8363   } else if (isa<RecordDecl>(Member)) {
8364     CXXRecordDecl *PrevRecord;
8365     if (Previous.isSingleResult() &&
8366         (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
8367       FoundInstantiation = Previous.getRepresentativeDecl();
8368       Instantiation = PrevRecord;
8369       InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
8370       MSInfo = PrevRecord->getMemberSpecializationInfo();
8371     }
8372   } else if (isa<EnumDecl>(Member)) {
8373     EnumDecl *PrevEnum;
8374     if (Previous.isSingleResult() &&
8375         (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
8376       FoundInstantiation = Previous.getRepresentativeDecl();
8377       Instantiation = PrevEnum;
8378       InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
8379       MSInfo = PrevEnum->getMemberSpecializationInfo();
8380     }
8381   }
8382 
8383   if (!Instantiation) {
8384     // There is no previous declaration that matches. Since member
8385     // specializations are always out-of-line, the caller will complain about
8386     // this mismatch later.
8387     return false;
8388   }
8389 
8390   // A member specialization in a friend declaration isn't really declaring
8391   // an explicit specialization, just identifying a specific (possibly implicit)
8392   // specialization. Don't change the template specialization kind.
8393   //
8394   // FIXME: Is this really valid? Other compilers reject.
8395   if (Member->getFriendObjectKind() != Decl::FOK_None) {
8396     // Preserve instantiation information.
8397     if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
8398       cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
8399                                       cast<CXXMethodDecl>(InstantiatedFrom),
8400         cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
8401     } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
8402       cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8403                                       cast<CXXRecordDecl>(InstantiatedFrom),
8404         cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
8405     }
8406 
8407     Previous.clear();
8408     Previous.addDecl(FoundInstantiation);
8409     return false;
8410   }
8411 
8412   // Make sure that this is a specialization of a member.
8413   if (!InstantiatedFrom) {
8414     Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8415       << Member;
8416     Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8417     return true;
8418   }
8419 
8420   // C++ [temp.expl.spec]p6:
8421   //   If a template, a member template or the member of a class template is
8422   //   explicitly specialized then that specialization shall be declared
8423   //   before the first use of that specialization that would cause an implicit
8424   //   instantiation to take place, in every translation unit in which such a
8425   //   use occurs; no diagnostic is required.
8426   assert(MSInfo && "Member specialization info missing?");
8427 
8428   bool HasNoEffect = false;
8429   if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
8430                                              TSK_ExplicitSpecialization,
8431                                              Instantiation,
8432                                      MSInfo->getTemplateSpecializationKind(),
8433                                            MSInfo->getPointOfInstantiation(),
8434                                              HasNoEffect))
8435     return true;
8436 
8437   // Check the scope of this explicit specialization.
8438   if (CheckTemplateSpecializationScope(*this,
8439                                        InstantiatedFrom,
8440                                        Instantiation, Member->getLocation(),
8441                                        false))
8442     return true;
8443 
8444   // Note that this member specialization is an "instantiation of" the
8445   // corresponding member of the original template.
8446   if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
8447     FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8448     if (InstantiationFunction->getTemplateSpecializationKind() ==
8449           TSK_ImplicitInstantiation) {
8450       // Explicit specializations of member functions of class templates do not
8451       // inherit '=delete' from the member function they are specializing.
8452       if (InstantiationFunction->isDeleted()) {
8453         // FIXME: This assert will not hold in the presence of modules.
8454         assert(InstantiationFunction->getCanonicalDecl() ==
8455                InstantiationFunction);
8456         // FIXME: We need an update record for this AST mutation.
8457         InstantiationFunction->setDeletedAsWritten(false);
8458       }
8459     }
8460 
8461     MemberFunction->setInstantiationOfMemberFunction(
8462         cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8463   } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
8464     MemberVar->setInstantiationOfStaticDataMember(
8465         cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8466   } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
8467     MemberClass->setInstantiationOfMemberClass(
8468         cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8469   } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
8470     MemberEnum->setInstantiationOfMemberEnum(
8471         cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8472   } else {
8473     llvm_unreachable("unknown member specialization kind");
8474   }
8475 
8476   // Save the caller the trouble of having to figure out which declaration
8477   // this specialization matches.
8478   Previous.clear();
8479   Previous.addDecl(FoundInstantiation);
8480   return false;
8481 }
8482 
8483 /// Complete the explicit specialization of a member of a class template by
8484 /// updating the instantiated member to be marked as an explicit specialization.
8485 ///
8486 /// \param OrigD The member declaration instantiated from the template.
8487 /// \param Loc The location of the explicit specialization of the member.
8488 template<typename DeclT>
8489 static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
8490                                              SourceLocation Loc) {
8491   if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
8492     return;
8493 
8494   // FIXME: Inform AST mutation listeners of this AST mutation.
8495   // FIXME: If there are multiple in-class declarations of the member (from
8496   // multiple modules, or a declaration and later definition of a member type),
8497   // should we update all of them?
8498   OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8499   OrigD->setLocation(Loc);
8500 }
8501 
8502 void Sema::CompleteMemberSpecialization(NamedDecl *Member,
8503                                         LookupResult &Previous) {
8504   NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
8505   if (Instantiation == Member)
8506     return;
8507 
8508   if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
8509     completeMemberSpecializationImpl(*this, Function, Member->getLocation());
8510   else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
8511     completeMemberSpecializationImpl(*this, Var, Member->getLocation());
8512   else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
8513     completeMemberSpecializationImpl(*this, Record, Member->getLocation());
8514   else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
8515     completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
8516   else
8517     llvm_unreachable("unknown member specialization kind");
8518 }
8519 
8520 /// Check the scope of an explicit instantiation.
8521 ///
8522 /// \returns true if a serious error occurs, false otherwise.
8523 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
8524                                             SourceLocation InstLoc,
8525                                             bool WasQualifiedName) {
8526   DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
8527   DeclContext *CurContext = S.CurContext->getRedeclContext();
8528 
8529   if (CurContext->isRecord()) {
8530     S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8531       << D;
8532     return true;
8533   }
8534 
8535   // C++11 [temp.explicit]p3:
8536   //   An explicit instantiation shall appear in an enclosing namespace of its
8537   //   template. If the name declared in the explicit instantiation is an
8538   //   unqualified name, the explicit instantiation shall appear in the
8539   //   namespace where its template is declared or, if that namespace is inline
8540   //   (7.3.1), any namespace from its enclosing namespace set.
8541   //
8542   // This is DR275, which we do not retroactively apply to C++98/03.
8543   if (WasQualifiedName) {
8544     if (CurContext->Encloses(OrigContext))
8545       return false;
8546   } else {
8547     if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8548       return false;
8549   }
8550 
8551   if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8552     if (WasQualifiedName)
8553       S.Diag(InstLoc,
8554              S.getLangOpts().CPlusPlus11?
8555                diag::err_explicit_instantiation_out_of_scope :
8556                diag::warn_explicit_instantiation_out_of_scope_0x)
8557         << D << NS;
8558     else
8559       S.Diag(InstLoc,
8560              S.getLangOpts().CPlusPlus11?
8561                diag::err_explicit_instantiation_unqualified_wrong_namespace :
8562                diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8563         << D << NS;
8564   } else
8565     S.Diag(InstLoc,
8566            S.getLangOpts().CPlusPlus11?
8567              diag::err_explicit_instantiation_must_be_global :
8568              diag::warn_explicit_instantiation_must_be_global_0x)
8569       << D;
8570   S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
8571   return false;
8572 }
8573 
8574 /// Determine whether the given scope specifier has a template-id in it.
8575 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
8576   if (!SS.isSet())
8577     return false;
8578 
8579   // C++11 [temp.explicit]p3:
8580   //   If the explicit instantiation is for a member function, a member class
8581   //   or a static data member of a class template specialization, the name of
8582   //   the class template specialization in the qualified-id for the member
8583   //   name shall be a simple-template-id.
8584   //
8585   // C++98 has the same restriction, just worded differently.
8586   for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8587        NNS = NNS->getPrefix())
8588     if (const Type *T = NNS->getAsType())
8589       if (isa<TemplateSpecializationType>(T))
8590         return true;
8591 
8592   return false;
8593 }
8594 
8595 /// Make a dllexport or dllimport attr on a class template specialization take
8596 /// effect.
8597 static void dllExportImportClassTemplateSpecialization(
8598     Sema &S, ClassTemplateSpecializationDecl *Def) {
8599   auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8600   assert(A && "dllExportImportClassTemplateSpecialization called "
8601               "on Def without dllexport or dllimport");
8602 
8603   // We reject explicit instantiations in class scope, so there should
8604   // never be any delayed exported classes to worry about.
8605   assert(S.DelayedDllExportClasses.empty() &&
8606          "delayed exports present at explicit instantiation");
8607   S.checkClassLevelDLLAttribute(Def);
8608 
8609   // Propagate attribute to base class templates.
8610   for (auto &B : Def->bases()) {
8611     if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8612             B.getType()->getAsCXXRecordDecl()))
8613       S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc());
8614   }
8615 
8616   S.referenceDLLExportedClassMethods();
8617 }
8618 
8619 // Explicit instantiation of a class template specialization
8620 DeclResult Sema::ActOnExplicitInstantiation(
8621     Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
8622     unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
8623     TemplateTy TemplateD, SourceLocation TemplateNameLoc,
8624     SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
8625     SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
8626   // Find the class template we're specializing
8627   TemplateName Name = TemplateD.get();
8628   TemplateDecl *TD = Name.getAsTemplateDecl();
8629   // Check that the specialization uses the same tag kind as the
8630   // original template.
8631   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8632   assert(Kind != TTK_Enum &&
8633          "Invalid enum tag in class template explicit instantiation!");
8634 
8635   ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8636 
8637   if (!ClassTemplate) {
8638     NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8639     Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
8640     Diag(TD->getLocation(), diag::note_previous_use);
8641     return true;
8642   }
8643 
8644   if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
8645                                     Kind, /*isDefinition*/false, KWLoc,
8646                                     ClassTemplate->getIdentifier())) {
8647     Diag(KWLoc, diag::err_use_with_wrong_tag)
8648       << ClassTemplate
8649       << FixItHint::CreateReplacement(KWLoc,
8650                             ClassTemplate->getTemplatedDecl()->getKindName());
8651     Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8652          diag::note_previous_use);
8653     Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8654   }
8655 
8656   // C++0x [temp.explicit]p2:
8657   //   There are two forms of explicit instantiation: an explicit instantiation
8658   //   definition and an explicit instantiation declaration. An explicit
8659   //   instantiation declaration begins with the extern keyword. [...]
8660   TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8661                                        ? TSK_ExplicitInstantiationDefinition
8662                                        : TSK_ExplicitInstantiationDeclaration;
8663 
8664   if (TSK == TSK_ExplicitInstantiationDeclaration) {
8665     // Check for dllexport class template instantiation declarations.
8666     for (const ParsedAttr &AL : Attr) {
8667       if (AL.getKind() == ParsedAttr::AT_DLLExport) {
8668         Diag(ExternLoc,
8669              diag::warn_attribute_dllexport_explicit_instantiation_decl);
8670         Diag(AL.getLoc(), diag::note_attribute);
8671         break;
8672       }
8673     }
8674 
8675     if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
8676       Diag(ExternLoc,
8677            diag::warn_attribute_dllexport_explicit_instantiation_decl);
8678       Diag(A->getLocation(), diag::note_attribute);
8679     }
8680   }
8681 
8682   // In MSVC mode, dllimported explicit instantiation definitions are treated as
8683   // instantiation declarations for most purposes.
8684   bool DLLImportExplicitInstantiationDef = false;
8685   if (TSK == TSK_ExplicitInstantiationDefinition &&
8686       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8687     // Check for dllimport class template instantiation definitions.
8688     bool DLLImport =
8689         ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
8690     for (const ParsedAttr &AL : Attr) {
8691       if (AL.getKind() == ParsedAttr::AT_DLLImport)
8692         DLLImport = true;
8693       if (AL.getKind() == ParsedAttr::AT_DLLExport) {
8694         // dllexport trumps dllimport here.
8695         DLLImport = false;
8696         break;
8697       }
8698     }
8699     if (DLLImport) {
8700       TSK = TSK_ExplicitInstantiationDeclaration;
8701       DLLImportExplicitInstantiationDef = true;
8702     }
8703   }
8704 
8705   // Translate the parser's template argument list in our AST format.
8706   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8707   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
8708 
8709   // Check that the template argument list is well-formed for this
8710   // template.
8711   SmallVector<TemplateArgument, 4> Converted;
8712   if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
8713                                 TemplateArgs, false, Converted))
8714     return true;
8715 
8716   // Find the class template specialization declaration that
8717   // corresponds to these arguments.
8718   void *InsertPos = nullptr;
8719   ClassTemplateSpecializationDecl *PrevDecl
8720     = ClassTemplate->findSpecialization(Converted, InsertPos);
8721 
8722   TemplateSpecializationKind PrevDecl_TSK
8723     = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
8724 
8725   // C++0x [temp.explicit]p2:
8726   //   [...] An explicit instantiation shall appear in an enclosing
8727   //   namespace of its template. [...]
8728   //
8729   // This is C++ DR 275.
8730   if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
8731                                       SS.isSet()))
8732     return true;
8733 
8734   ClassTemplateSpecializationDecl *Specialization = nullptr;
8735 
8736   bool HasNoEffect = false;
8737   if (PrevDecl) {
8738     if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
8739                                                PrevDecl, PrevDecl_TSK,
8740                                             PrevDecl->getPointOfInstantiation(),
8741                                                HasNoEffect))
8742       return PrevDecl;
8743 
8744     // Even though HasNoEffect == true means that this explicit instantiation
8745     // has no effect on semantics, we go on to put its syntax in the AST.
8746 
8747     if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
8748         PrevDecl_TSK == TSK_Undeclared) {
8749       // Since the only prior class template specialization with these
8750       // arguments was referenced but not declared, reuse that
8751       // declaration node as our own, updating the source location
8752       // for the template name to reflect our new declaration.
8753       // (Other source locations will be updated later.)
8754       Specialization = PrevDecl;
8755       Specialization->setLocation(TemplateNameLoc);
8756       PrevDecl = nullptr;
8757     }
8758 
8759     if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
8760         DLLImportExplicitInstantiationDef) {
8761       // The new specialization might add a dllimport attribute.
8762       HasNoEffect = false;
8763     }
8764   }
8765 
8766   if (!Specialization) {
8767     // Create a new class template specialization declaration node for
8768     // this explicit specialization.
8769     Specialization
8770       = ClassTemplateSpecializationDecl::Create(Context, Kind,
8771                                              ClassTemplate->getDeclContext(),
8772                                                 KWLoc, TemplateNameLoc,
8773                                                 ClassTemplate,
8774                                                 Converted,
8775                                                 PrevDecl);
8776     SetNestedNameSpecifier(Specialization, SS);
8777 
8778     if (!HasNoEffect && !PrevDecl) {
8779       // Insert the new specialization.
8780       ClassTemplate->AddSpecialization(Specialization, InsertPos);
8781     }
8782   }
8783 
8784   // Build the fully-sugared type for this explicit instantiation as
8785   // the user wrote in the explicit instantiation itself. This means
8786   // that we'll pretty-print the type retrieved from the
8787   // specialization's declaration the way that the user actually wrote
8788   // the explicit instantiation, rather than formatting the name based
8789   // on the "canonical" representation used to store the template
8790   // arguments in the specialization.
8791   TypeSourceInfo *WrittenTy
8792     = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8793                                                 TemplateArgs,
8794                                   Context.getTypeDeclType(Specialization));
8795   Specialization->setTypeAsWritten(WrittenTy);
8796 
8797   // Set source locations for keywords.
8798   Specialization->setExternLoc(ExternLoc);
8799   Specialization->setTemplateKeywordLoc(TemplateLoc);
8800   Specialization->setBraceRange(SourceRange());
8801 
8802   bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
8803   ProcessDeclAttributeList(S, Specialization, Attr);
8804 
8805   // Add the explicit instantiation into its lexical context. However,
8806   // since explicit instantiations are never found by name lookup, we
8807   // just put it into the declaration context directly.
8808   Specialization->setLexicalDeclContext(CurContext);
8809   CurContext->addDecl(Specialization);
8810 
8811   // Syntax is now OK, so return if it has no other effect on semantics.
8812   if (HasNoEffect) {
8813     // Set the template specialization kind.
8814     Specialization->setTemplateSpecializationKind(TSK);
8815     return Specialization;
8816   }
8817 
8818   // C++ [temp.explicit]p3:
8819   //   A definition of a class template or class member template
8820   //   shall be in scope at the point of the explicit instantiation of
8821   //   the class template or class member template.
8822   //
8823   // This check comes when we actually try to perform the
8824   // instantiation.
8825   ClassTemplateSpecializationDecl *Def
8826     = cast_or_null<ClassTemplateSpecializationDecl>(
8827                                               Specialization->getDefinition());
8828   if (!Def)
8829     InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
8830   else if (TSK == TSK_ExplicitInstantiationDefinition) {
8831     MarkVTableUsed(TemplateNameLoc, Specialization, true);
8832     Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
8833   }
8834 
8835   // Instantiate the members of this class template specialization.
8836   Def = cast_or_null<ClassTemplateSpecializationDecl>(
8837                                        Specialization->getDefinition());
8838   if (Def) {
8839     TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
8840     // Fix a TSK_ExplicitInstantiationDeclaration followed by a
8841     // TSK_ExplicitInstantiationDefinition
8842     if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
8843         (TSK == TSK_ExplicitInstantiationDefinition ||
8844          DLLImportExplicitInstantiationDef)) {
8845       // FIXME: Need to notify the ASTMutationListener that we did this.
8846       Def->setTemplateSpecializationKind(TSK);
8847 
8848       if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
8849           (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8850            Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8851         // In the MS ABI, an explicit instantiation definition can add a dll
8852         // attribute to a template with a previous instantiation declaration.
8853         // MinGW doesn't allow this.
8854         auto *A = cast<InheritableAttr>(
8855             getDLLAttr(Specialization)->clone(getASTContext()));
8856         A->setInherited(true);
8857         Def->addAttr(A);
8858         dllExportImportClassTemplateSpecialization(*this, Def);
8859       }
8860     }
8861 
8862     // Fix a TSK_ImplicitInstantiation followed by a
8863     // TSK_ExplicitInstantiationDefinition
8864     bool NewlyDLLExported =
8865         !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
8866     if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
8867         (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8868          Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8869       // In the MS ABI, an explicit instantiation definition can add a dll
8870       // attribute to a template with a previous implicit instantiation.
8871       // MinGW doesn't allow this. We limit clang to only adding dllexport, to
8872       // avoid potentially strange codegen behavior.  For example, if we extend
8873       // this conditional to dllimport, and we have a source file calling a
8874       // method on an implicitly instantiated template class instance and then
8875       // declaring a dllimport explicit instantiation definition for the same
8876       // template class, the codegen for the method call will not respect the
8877       // dllimport, while it will with cl. The Def will already have the DLL
8878       // attribute, since the Def and Specialization will be the same in the
8879       // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
8880       // attribute to the Specialization; we just need to make it take effect.
8881       assert(Def == Specialization &&
8882              "Def and Specialization should match for implicit instantiation");
8883       dllExportImportClassTemplateSpecialization(*this, Def);
8884     }
8885 
8886     // Set the template specialization kind. Make sure it is set before
8887     // instantiating the members which will trigger ASTConsumer callbacks.
8888     Specialization->setTemplateSpecializationKind(TSK);
8889     InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
8890   } else {
8891 
8892     // Set the template specialization kind.
8893     Specialization->setTemplateSpecializationKind(TSK);
8894   }
8895 
8896   return Specialization;
8897 }
8898 
8899 // Explicit instantiation of a member class of a class template.
8900 DeclResult
8901 Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
8902                                  SourceLocation TemplateLoc, unsigned TagSpec,
8903                                  SourceLocation KWLoc, CXXScopeSpec &SS,
8904                                  IdentifierInfo *Name, SourceLocation NameLoc,
8905                                  const ParsedAttributesView &Attr) {
8906 
8907   bool Owned = false;
8908   bool IsDependent = false;
8909   Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
8910                         KWLoc, SS, Name, NameLoc, Attr, AS_none,
8911                         /*ModulePrivateLoc=*/SourceLocation(),
8912                         MultiTemplateParamsArg(), Owned, IsDependent,
8913                         SourceLocation(), false, TypeResult(),
8914                         /*IsTypeSpecifier*/false,
8915                         /*IsTemplateParamOrArg*/false);
8916   assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
8917 
8918   if (!TagD)
8919     return true;
8920 
8921   TagDecl *Tag = cast<TagDecl>(TagD);
8922   assert(!Tag->isEnum() && "shouldn't see enumerations here");
8923 
8924   if (Tag->isInvalidDecl())
8925     return true;
8926 
8927   CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
8928   CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
8929   if (!Pattern) {
8930     Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
8931       << Context.getTypeDeclType(Record);
8932     Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
8933     return true;
8934   }
8935 
8936   // C++0x [temp.explicit]p2:
8937   //   If the explicit instantiation is for a class or member class, the
8938   //   elaborated-type-specifier in the declaration shall include a
8939   //   simple-template-id.
8940   //
8941   // C++98 has the same restriction, just worded differently.
8942   if (!ScopeSpecifierHasTemplateId(SS))
8943     Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
8944       << Record << SS.getRange();
8945 
8946   // C++0x [temp.explicit]p2:
8947   //   There are two forms of explicit instantiation: an explicit instantiation
8948   //   definition and an explicit instantiation declaration. An explicit
8949   //   instantiation declaration begins with the extern keyword. [...]
8950   TemplateSpecializationKind TSK
8951     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8952                            : TSK_ExplicitInstantiationDeclaration;
8953 
8954   // C++0x [temp.explicit]p2:
8955   //   [...] An explicit instantiation shall appear in an enclosing
8956   //   namespace of its template. [...]
8957   //
8958   // This is C++ DR 275.
8959   CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
8960 
8961   // Verify that it is okay to explicitly instantiate here.
8962   CXXRecordDecl *PrevDecl
8963     = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
8964   if (!PrevDecl && Record->getDefinition())
8965     PrevDecl = Record;
8966   if (PrevDecl) {
8967     MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
8968     bool HasNoEffect = false;
8969     assert(MSInfo && "No member specialization information?");
8970     if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
8971                                                PrevDecl,
8972                                         MSInfo->getTemplateSpecializationKind(),
8973                                              MSInfo->getPointOfInstantiation(),
8974                                                HasNoEffect))
8975       return true;
8976     if (HasNoEffect)
8977       return TagD;
8978   }
8979 
8980   CXXRecordDecl *RecordDef
8981     = cast_or_null<CXXRecordDecl>(Record->getDefinition());
8982   if (!RecordDef) {
8983     // C++ [temp.explicit]p3:
8984     //   A definition of a member class of a class template shall be in scope
8985     //   at the point of an explicit instantiation of the member class.
8986     CXXRecordDecl *Def
8987       = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
8988     if (!Def) {
8989       Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
8990         << 0 << Record->getDeclName() << Record->getDeclContext();
8991       Diag(Pattern->getLocation(), diag::note_forward_declaration)
8992         << Pattern;
8993       return true;
8994     } else {
8995       if (InstantiateClass(NameLoc, Record, Def,
8996                            getTemplateInstantiationArgs(Record),
8997                            TSK))
8998         return true;
8999 
9000       RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
9001       if (!RecordDef)
9002         return true;
9003     }
9004   }
9005 
9006   // Instantiate all of the members of the class.
9007   InstantiateClassMembers(NameLoc, RecordDef,
9008                           getTemplateInstantiationArgs(Record), TSK);
9009 
9010   if (TSK == TSK_ExplicitInstantiationDefinition)
9011     MarkVTableUsed(NameLoc, RecordDef, true);
9012 
9013   // FIXME: We don't have any representation for explicit instantiations of
9014   // member classes. Such a representation is not needed for compilation, but it
9015   // should be available for clients that want to see all of the declarations in
9016   // the source code.
9017   return TagD;
9018 }
9019 
9020 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
9021                                             SourceLocation ExternLoc,
9022                                             SourceLocation TemplateLoc,
9023                                             Declarator &D) {
9024   // Explicit instantiations always require a name.
9025   // TODO: check if/when DNInfo should replace Name.
9026   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9027   DeclarationName Name = NameInfo.getName();
9028   if (!Name) {
9029     if (!D.isInvalidType())
9030       Diag(D.getDeclSpec().getBeginLoc(),
9031            diag::err_explicit_instantiation_requires_name)
9032           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
9033 
9034     return true;
9035   }
9036 
9037   // The scope passed in may not be a decl scope.  Zip up the scope tree until
9038   // we find one that is.
9039   while ((S->getFlags() & Scope::DeclScope) == 0 ||
9040          (S->getFlags() & Scope::TemplateParamScope) != 0)
9041     S = S->getParent();
9042 
9043   // Determine the type of the declaration.
9044   TypeSourceInfo *T = GetTypeForDeclarator(D, S);
9045   QualType R = T->getType();
9046   if (R.isNull())
9047     return true;
9048 
9049   // C++ [dcl.stc]p1:
9050   //   A storage-class-specifier shall not be specified in [...] an explicit
9051   //   instantiation (14.7.2) directive.
9052   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
9053     Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
9054       << Name;
9055     return true;
9056   } else if (D.getDeclSpec().getStorageClassSpec()
9057                                                 != DeclSpec::SCS_unspecified) {
9058     // Complain about then remove the storage class specifier.
9059     Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
9060       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9061 
9062     D.getMutableDeclSpec().ClearStorageClassSpecs();
9063   }
9064 
9065   // C++0x [temp.explicit]p1:
9066   //   [...] An explicit instantiation of a function template shall not use the
9067   //   inline or constexpr specifiers.
9068   // Presumably, this also applies to member functions of class templates as
9069   // well.
9070   if (D.getDeclSpec().isInlineSpecified())
9071     Diag(D.getDeclSpec().getInlineSpecLoc(),
9072          getLangOpts().CPlusPlus11 ?
9073            diag::err_explicit_instantiation_inline :
9074            diag::warn_explicit_instantiation_inline_0x)
9075       << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9076   if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
9077     // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
9078     // not already specified.
9079     Diag(D.getDeclSpec().getConstexprSpecLoc(),
9080          diag::err_explicit_instantiation_constexpr);
9081 
9082   // A deduction guide is not on the list of entities that can be explicitly
9083   // instantiated.
9084   if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9085     Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
9086         << /*explicit instantiation*/ 0;
9087     return true;
9088   }
9089 
9090   // C++0x [temp.explicit]p2:
9091   //   There are two forms of explicit instantiation: an explicit instantiation
9092   //   definition and an explicit instantiation declaration. An explicit
9093   //   instantiation declaration begins with the extern keyword. [...]
9094   TemplateSpecializationKind TSK
9095     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9096                            : TSK_ExplicitInstantiationDeclaration;
9097 
9098   LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
9099   LookupParsedName(Previous, S, &D.getCXXScopeSpec());
9100 
9101   if (!R->isFunctionType()) {
9102     // C++ [temp.explicit]p1:
9103     //   A [...] static data member of a class template can be explicitly
9104     //   instantiated from the member definition associated with its class
9105     //   template.
9106     // C++1y [temp.explicit]p1:
9107     //   A [...] variable [...] template specialization can be explicitly
9108     //   instantiated from its template.
9109     if (Previous.isAmbiguous())
9110       return true;
9111 
9112     VarDecl *Prev = Previous.getAsSingle<VarDecl>();
9113     VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
9114 
9115     if (!PrevTemplate) {
9116       if (!Prev || !Prev->isStaticDataMember()) {
9117         // We expect to see a data data member here.
9118         Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
9119             << Name;
9120         for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9121              P != PEnd; ++P)
9122           Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
9123         return true;
9124       }
9125 
9126       if (!Prev->getInstantiatedFromStaticDataMember()) {
9127         // FIXME: Check for explicit specialization?
9128         Diag(D.getIdentifierLoc(),
9129              diag::err_explicit_instantiation_data_member_not_instantiated)
9130             << Prev;
9131         Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
9132         // FIXME: Can we provide a note showing where this was declared?
9133         return true;
9134       }
9135     } else {
9136       // Explicitly instantiate a variable template.
9137 
9138       // C++1y [dcl.spec.auto]p6:
9139       //   ... A program that uses auto or decltype(auto) in a context not
9140       //   explicitly allowed in this section is ill-formed.
9141       //
9142       // This includes auto-typed variable template instantiations.
9143       if (R->isUndeducedType()) {
9144         Diag(T->getTypeLoc().getBeginLoc(),
9145              diag::err_auto_not_allowed_var_inst);
9146         return true;
9147       }
9148 
9149       if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9150         // C++1y [temp.explicit]p3:
9151         //   If the explicit instantiation is for a variable, the unqualified-id
9152         //   in the declaration shall be a template-id.
9153         Diag(D.getIdentifierLoc(),
9154              diag::err_explicit_instantiation_without_template_id)
9155           << PrevTemplate;
9156         Diag(PrevTemplate->getLocation(),
9157              diag::note_explicit_instantiation_here);
9158         return true;
9159       }
9160 
9161       // Translate the parser's template argument list into our AST format.
9162       TemplateArgumentListInfo TemplateArgs =
9163           makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
9164 
9165       DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
9166                                           D.getIdentifierLoc(), TemplateArgs);
9167       if (Res.isInvalid())
9168         return true;
9169 
9170       // Ignore access control bits, we don't need them for redeclaration
9171       // checking.
9172       Prev = cast<VarDecl>(Res.get());
9173     }
9174 
9175     // C++0x [temp.explicit]p2:
9176     //   If the explicit instantiation is for a member function, a member class
9177     //   or a static data member of a class template specialization, the name of
9178     //   the class template specialization in the qualified-id for the member
9179     //   name shall be a simple-template-id.
9180     //
9181     // C++98 has the same restriction, just worded differently.
9182     //
9183     // This does not apply to variable template specializations, where the
9184     // template-id is in the unqualified-id instead.
9185     if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
9186       Diag(D.getIdentifierLoc(),
9187            diag::ext_explicit_instantiation_without_qualified_id)
9188         << Prev << D.getCXXScopeSpec().getRange();
9189 
9190     // Check the scope of this explicit instantiation.
9191     CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
9192 
9193     // Verify that it is okay to explicitly instantiate here.
9194     TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
9195     SourceLocation POI = Prev->getPointOfInstantiation();
9196     bool HasNoEffect = false;
9197     if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
9198                                                PrevTSK, POI, HasNoEffect))
9199       return true;
9200 
9201     if (!HasNoEffect) {
9202       // Instantiate static data member or variable template.
9203       Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9204       // Merge attributes.
9205       ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
9206       if (TSK == TSK_ExplicitInstantiationDefinition)
9207         InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
9208     }
9209 
9210     // Check the new variable specialization against the parsed input.
9211     if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
9212       Diag(T->getTypeLoc().getBeginLoc(),
9213            diag::err_invalid_var_template_spec_type)
9214           << 0 << PrevTemplate << R << Prev->getType();
9215       Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
9216           << 2 << PrevTemplate->getDeclName();
9217       return true;
9218     }
9219 
9220     // FIXME: Create an ExplicitInstantiation node?
9221     return (Decl*) nullptr;
9222   }
9223 
9224   // If the declarator is a template-id, translate the parser's template
9225   // argument list into our AST format.
9226   bool HasExplicitTemplateArgs = false;
9227   TemplateArgumentListInfo TemplateArgs;
9228   if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9229     TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
9230     HasExplicitTemplateArgs = true;
9231   }
9232 
9233   // C++ [temp.explicit]p1:
9234   //   A [...] function [...] can be explicitly instantiated from its template.
9235   //   A member function [...] of a class template can be explicitly
9236   //  instantiated from the member definition associated with its class
9237   //  template.
9238   UnresolvedSet<8> TemplateMatches;
9239   FunctionDecl *NonTemplateMatch = nullptr;
9240   TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
9241   for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9242        P != PEnd; ++P) {
9243     NamedDecl *Prev = *P;
9244     if (!HasExplicitTemplateArgs) {
9245       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
9246         QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
9247                                                 /*AdjustExceptionSpec*/true);
9248         if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
9249           if (Method->getPrimaryTemplate()) {
9250             TemplateMatches.addDecl(Method, P.getAccess());
9251           } else {
9252             // FIXME: Can this assert ever happen?  Needs a test.
9253             assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
9254             NonTemplateMatch = Method;
9255           }
9256         }
9257       }
9258     }
9259 
9260     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
9261     if (!FunTmpl)
9262       continue;
9263 
9264     TemplateDeductionInfo Info(FailedCandidates.getLocation());
9265     FunctionDecl *Specialization = nullptr;
9266     if (TemplateDeductionResult TDK
9267           = DeduceTemplateArguments(FunTmpl,
9268                                (HasExplicitTemplateArgs ? &TemplateArgs
9269                                                         : nullptr),
9270                                     R, Specialization, Info)) {
9271       // Keep track of almost-matches.
9272       FailedCandidates.addCandidate()
9273           .set(P.getPair(), FunTmpl->getTemplatedDecl(),
9274                MakeDeductionFailureInfo(Context, TDK, Info));
9275       (void)TDK;
9276       continue;
9277     }
9278 
9279     // Target attributes are part of the cuda function signature, so
9280     // the cuda target of the instantiated function must match that of its
9281     // template.  Given that C++ template deduction does not take
9282     // target attributes into account, we reject candidates here that
9283     // have a different target.
9284     if (LangOpts.CUDA &&
9285         IdentifyCUDATarget(Specialization,
9286                            /* IgnoreImplicitHDAttributes = */ true) !=
9287             IdentifyCUDATarget(D.getDeclSpec().getAttributes())) {
9288       FailedCandidates.addCandidate().set(
9289           P.getPair(), FunTmpl->getTemplatedDecl(),
9290           MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9291       continue;
9292     }
9293 
9294     TemplateMatches.addDecl(Specialization, P.getAccess());
9295   }
9296 
9297   FunctionDecl *Specialization = NonTemplateMatch;
9298   if (!Specialization) {
9299     // Find the most specialized function template specialization.
9300     UnresolvedSetIterator Result = getMostSpecialized(
9301         TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
9302         D.getIdentifierLoc(),
9303         PDiag(diag::err_explicit_instantiation_not_known) << Name,
9304         PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
9305         PDiag(diag::note_explicit_instantiation_candidate));
9306 
9307     if (Result == TemplateMatches.end())
9308       return true;
9309 
9310     // Ignore access control bits, we don't need them for redeclaration checking.
9311     Specialization = cast<FunctionDecl>(*Result);
9312   }
9313 
9314   // C++11 [except.spec]p4
9315   // In an explicit instantiation an exception-specification may be specified,
9316   // but is not required.
9317   // If an exception-specification is specified in an explicit instantiation
9318   // directive, it shall be compatible with the exception-specifications of
9319   // other declarations of that function.
9320   if (auto *FPT = R->getAs<FunctionProtoType>())
9321     if (FPT->hasExceptionSpec()) {
9322       unsigned DiagID =
9323           diag::err_mismatched_exception_spec_explicit_instantiation;
9324       if (getLangOpts().MicrosoftExt)
9325         DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
9326       bool Result = CheckEquivalentExceptionSpec(
9327           PDiag(DiagID) << Specialization->getType(),
9328           PDiag(diag::note_explicit_instantiation_here),
9329           Specialization->getType()->getAs<FunctionProtoType>(),
9330           Specialization->getLocation(), FPT, D.getBeginLoc());
9331       // In Microsoft mode, mismatching exception specifications just cause a
9332       // warning.
9333       if (!getLangOpts().MicrosoftExt && Result)
9334         return true;
9335     }
9336 
9337   if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
9338     Diag(D.getIdentifierLoc(),
9339          diag::err_explicit_instantiation_member_function_not_instantiated)
9340       << Specialization
9341       << (Specialization->getTemplateSpecializationKind() ==
9342           TSK_ExplicitSpecialization);
9343     Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
9344     return true;
9345   }
9346 
9347   FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
9348   if (!PrevDecl && Specialization->isThisDeclarationADefinition())
9349     PrevDecl = Specialization;
9350 
9351   if (PrevDecl) {
9352     bool HasNoEffect = false;
9353     if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
9354                                                PrevDecl,
9355                                      PrevDecl->getTemplateSpecializationKind(),
9356                                           PrevDecl->getPointOfInstantiation(),
9357                                                HasNoEffect))
9358       return true;
9359 
9360     // FIXME: We may still want to build some representation of this
9361     // explicit specialization.
9362     if (HasNoEffect)
9363       return (Decl*) nullptr;
9364   }
9365 
9366   ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
9367 
9368   // In MSVC mode, dllimported explicit instantiation definitions are treated as
9369   // instantiation declarations.
9370   if (TSK == TSK_ExplicitInstantiationDefinition &&
9371       Specialization->hasAttr<DLLImportAttr>() &&
9372       Context.getTargetInfo().getCXXABI().isMicrosoft())
9373     TSK = TSK_ExplicitInstantiationDeclaration;
9374 
9375   Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9376 
9377   if (Specialization->isDefined()) {
9378     // Let the ASTConsumer know that this function has been explicitly
9379     // instantiated now, and its linkage might have changed.
9380     Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
9381   } else if (TSK == TSK_ExplicitInstantiationDefinition)
9382     InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
9383 
9384   // C++0x [temp.explicit]p2:
9385   //   If the explicit instantiation is for a member function, a member class
9386   //   or a static data member of a class template specialization, the name of
9387   //   the class template specialization in the qualified-id for the member
9388   //   name shall be a simple-template-id.
9389   //
9390   // C++98 has the same restriction, just worded differently.
9391   FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
9392   if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
9393       D.getCXXScopeSpec().isSet() &&
9394       !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
9395     Diag(D.getIdentifierLoc(),
9396          diag::ext_explicit_instantiation_without_qualified_id)
9397     << Specialization << D.getCXXScopeSpec().getRange();
9398 
9399   CheckExplicitInstantiationScope(*this,
9400                    FunTmpl? (NamedDecl *)FunTmpl
9401                           : Specialization->getInstantiatedFromMemberFunction(),
9402                                   D.getIdentifierLoc(),
9403                                   D.getCXXScopeSpec().isSet());
9404 
9405   // FIXME: Create some kind of ExplicitInstantiationDecl here.
9406   return (Decl*) nullptr;
9407 }
9408 
9409 TypeResult
9410 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
9411                         const CXXScopeSpec &SS, IdentifierInfo *Name,
9412                         SourceLocation TagLoc, SourceLocation NameLoc) {
9413   // This has to hold, because SS is expected to be defined.
9414   assert(Name && "Expected a name in a dependent tag");
9415 
9416   NestedNameSpecifier *NNS = SS.getScopeRep();
9417   if (!NNS)
9418     return true;
9419 
9420   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9421 
9422   if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9423     Diag(NameLoc, diag::err_dependent_tag_decl)
9424       << (TUK == TUK_Definition) << Kind << SS.getRange();
9425     return true;
9426   }
9427 
9428   // Create the resulting type.
9429   ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9430   QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
9431 
9432   // Create type-source location information for this type.
9433   TypeLocBuilder TLB;
9434   DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
9435   TL.setElaboratedKeywordLoc(TagLoc);
9436   TL.setQualifierLoc(SS.getWithLocInContext(Context));
9437   TL.setNameLoc(NameLoc);
9438   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
9439 }
9440 
9441 TypeResult
9442 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
9443                         const CXXScopeSpec &SS, const IdentifierInfo &II,
9444                         SourceLocation IdLoc) {
9445   if (SS.isInvalid())
9446     return true;
9447 
9448   if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9449     Diag(TypenameLoc,
9450          getLangOpts().CPlusPlus11 ?
9451            diag::warn_cxx98_compat_typename_outside_of_template :
9452            diag::ext_typename_outside_of_template)
9453       << FixItHint::CreateRemoval(TypenameLoc);
9454 
9455   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9456   QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9457                                  TypenameLoc, QualifierLoc, II, IdLoc);
9458   if (T.isNull())
9459     return true;
9460 
9461   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9462   if (isa<DependentNameType>(T)) {
9463     DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
9464     TL.setElaboratedKeywordLoc(TypenameLoc);
9465     TL.setQualifierLoc(QualifierLoc);
9466     TL.setNameLoc(IdLoc);
9467   } else {
9468     ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
9469     TL.setElaboratedKeywordLoc(TypenameLoc);
9470     TL.setQualifierLoc(QualifierLoc);
9471     TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
9472   }
9473 
9474   return CreateParsedType(T, TSI);
9475 }
9476 
9477 TypeResult
9478 Sema::ActOnTypenameType(Scope *S,
9479                         SourceLocation TypenameLoc,
9480                         const CXXScopeSpec &SS,
9481                         SourceLocation TemplateKWLoc,
9482                         TemplateTy TemplateIn,
9483                         IdentifierInfo *TemplateII,
9484                         SourceLocation TemplateIILoc,
9485                         SourceLocation LAngleLoc,
9486                         ASTTemplateArgsPtr TemplateArgsIn,
9487                         SourceLocation RAngleLoc) {
9488   if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9489     Diag(TypenameLoc,
9490          getLangOpts().CPlusPlus11 ?
9491            diag::warn_cxx98_compat_typename_outside_of_template :
9492            diag::ext_typename_outside_of_template)
9493       << FixItHint::CreateRemoval(TypenameLoc);
9494 
9495   // Strangely, non-type results are not ignored by this lookup, so the
9496   // program is ill-formed if it finds an injected-class-name.
9497   if (TypenameLoc.isValid()) {
9498     auto *LookupRD =
9499         dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9500     if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9501       Diag(TemplateIILoc,
9502            diag::ext_out_of_line_qualified_id_type_names_constructor)
9503         << TemplateII << 0 /*injected-class-name used as template name*/
9504         << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9505     }
9506   }
9507 
9508   // Translate the parser's template argument list in our AST format.
9509   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9510   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9511 
9512   TemplateName Template = TemplateIn.get();
9513   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9514     // Construct a dependent template specialization type.
9515     assert(DTN && "dependent template has non-dependent name?");
9516     assert(DTN->getQualifier() == SS.getScopeRep());
9517     QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
9518                                                           DTN->getQualifier(),
9519                                                           DTN->getIdentifier(),
9520                                                                 TemplateArgs);
9521 
9522     // Create source-location information for this type.
9523     TypeLocBuilder Builder;
9524     DependentTemplateSpecializationTypeLoc SpecTL
9525     = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
9526     SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9527     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
9528     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
9529     SpecTL.setTemplateNameLoc(TemplateIILoc);
9530     SpecTL.setLAngleLoc(LAngleLoc);
9531     SpecTL.setRAngleLoc(RAngleLoc);
9532     for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9533       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
9534     return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
9535   }
9536 
9537   QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
9538   if (T.isNull())
9539     return true;
9540 
9541   // Provide source-location information for the template specialization type.
9542   TypeLocBuilder Builder;
9543   TemplateSpecializationTypeLoc SpecTL
9544     = Builder.push<TemplateSpecializationTypeLoc>(T);
9545   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
9546   SpecTL.setTemplateNameLoc(TemplateIILoc);
9547   SpecTL.setLAngleLoc(LAngleLoc);
9548   SpecTL.setRAngleLoc(RAngleLoc);
9549   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9550     SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
9551 
9552   T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
9553   ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
9554   TL.setElaboratedKeywordLoc(TypenameLoc);
9555   TL.setQualifierLoc(SS.getWithLocInContext(Context));
9556 
9557   TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9558   return CreateParsedType(T, TSI);
9559 }
9560 
9561 
9562 /// Determine whether this failed name lookup should be treated as being
9563 /// disabled by a usage of std::enable_if.
9564 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
9565                        SourceRange &CondRange, Expr *&Cond) {
9566   // We must be looking for a ::type...
9567   if (!II.isStr("type"))
9568     return false;
9569 
9570   // ... within an explicitly-written template specialization...
9571   if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9572     return false;
9573   TypeLoc EnableIfTy = NNS.getTypeLoc();
9574   TemplateSpecializationTypeLoc EnableIfTSTLoc =
9575       EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9576   if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
9577     return false;
9578   const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
9579 
9580   // ... which names a complete class template declaration...
9581   const TemplateDecl *EnableIfDecl =
9582     EnableIfTST->getTemplateName().getAsTemplateDecl();
9583   if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9584     return false;
9585 
9586   // ... called "enable_if".
9587   const IdentifierInfo *EnableIfII =
9588     EnableIfDecl->getDeclName().getAsIdentifierInfo();
9589   if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9590     return false;
9591 
9592   // Assume the first template argument is the condition.
9593   CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
9594 
9595   // Dig out the condition.
9596   Cond = nullptr;
9597   if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
9598         != TemplateArgument::Expression)
9599     return true;
9600 
9601   Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
9602 
9603   // Ignore Boolean literals; they add no value.
9604   if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
9605     Cond = nullptr;
9606 
9607   return true;
9608 }
9609 
9610 /// Build the type that describes a C++ typename specifier,
9611 /// e.g., "typename T::type".
9612 QualType
9613 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
9614                         SourceLocation KeywordLoc,
9615                         NestedNameSpecifierLoc QualifierLoc,
9616                         const IdentifierInfo &II,
9617                         SourceLocation IILoc) {
9618   CXXScopeSpec SS;
9619   SS.Adopt(QualifierLoc);
9620 
9621   DeclContext *Ctx = computeDeclContext(SS);
9622   if (!Ctx) {
9623     // If the nested-name-specifier is dependent and couldn't be
9624     // resolved to a type, build a typename type.
9625     assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
9626     return Context.getDependentNameType(Keyword,
9627                                         QualifierLoc.getNestedNameSpecifier(),
9628                                         &II);
9629   }
9630 
9631   // If the nested-name-specifier refers to the current instantiation,
9632   // the "typename" keyword itself is superfluous. In C++03, the
9633   // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9634   // allows such extraneous "typename" keywords, and we retroactively
9635   // apply this DR to C++03 code with only a warning. In any case we continue.
9636 
9637   if (RequireCompleteDeclContext(SS, Ctx))
9638     return QualType();
9639 
9640   DeclarationName Name(&II);
9641   LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
9642   LookupQualifiedName(Result, Ctx, SS);
9643   unsigned DiagID = 0;
9644   Decl *Referenced = nullptr;
9645   switch (Result.getResultKind()) {
9646   case LookupResult::NotFound: {
9647     // If we're looking up 'type' within a template named 'enable_if', produce
9648     // a more specific diagnostic.
9649     SourceRange CondRange;
9650     Expr *Cond = nullptr;
9651     if (isEnableIf(QualifierLoc, II, CondRange, Cond)) {
9652       // If we have a condition, narrow it down to the specific failed
9653       // condition.
9654       if (Cond) {
9655         Expr *FailedCond;
9656         std::string FailedDescription;
9657         std::tie(FailedCond, FailedDescription) =
9658           findFailedBooleanCondition(Cond);
9659 
9660         Diag(FailedCond->getExprLoc(),
9661              diag::err_typename_nested_not_found_requirement)
9662           << FailedDescription
9663           << FailedCond->getSourceRange();
9664         return QualType();
9665       }
9666 
9667       Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
9668           << Ctx << CondRange;
9669       return QualType();
9670     }
9671 
9672     DiagID = diag::err_typename_nested_not_found;
9673     break;
9674   }
9675 
9676   case LookupResult::FoundUnresolvedValue: {
9677     // We found a using declaration that is a value. Most likely, the using
9678     // declaration itself is meant to have the 'typename' keyword.
9679     SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
9680                           IILoc);
9681     Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
9682       << Name << Ctx << FullRange;
9683     if (UnresolvedUsingValueDecl *Using
9684           = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
9685       SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
9686       Diag(Loc, diag::note_using_value_decl_missing_typename)
9687         << FixItHint::CreateInsertion(Loc, "typename ");
9688     }
9689   }
9690   // Fall through to create a dependent typename type, from which we can recover
9691   // better.
9692   LLVM_FALLTHROUGH;
9693 
9694   case LookupResult::NotFoundInCurrentInstantiation:
9695     // Okay, it's a member of an unknown instantiation.
9696     return Context.getDependentNameType(Keyword,
9697                                         QualifierLoc.getNestedNameSpecifier(),
9698                                         &II);
9699 
9700   case LookupResult::Found:
9701     if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
9702       // C++ [class.qual]p2:
9703       //   In a lookup in which function names are not ignored and the
9704       //   nested-name-specifier nominates a class C, if the name specified
9705       //   after the nested-name-specifier, when looked up in C, is the
9706       //   injected-class-name of C [...] then the name is instead considered
9707       //   to name the constructor of class C.
9708       //
9709       // Unlike in an elaborated-type-specifier, function names are not ignored
9710       // in typename-specifier lookup. However, they are ignored in all the
9711       // contexts where we form a typename type with no keyword (that is, in
9712       // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
9713       //
9714       // FIXME: That's not strictly true: mem-initializer-id lookup does not
9715       // ignore functions, but that appears to be an oversight.
9716       auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
9717       auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
9718       if (Keyword == ETK_Typename && LookupRD && FoundRD &&
9719           FoundRD->isInjectedClassName() &&
9720           declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
9721         Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
9722             << &II << 1 << 0 /*'typename' keyword used*/;
9723 
9724       // We found a type. Build an ElaboratedType, since the
9725       // typename-specifier was just sugar.
9726       MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
9727       return Context.getElaboratedType(Keyword,
9728                                        QualifierLoc.getNestedNameSpecifier(),
9729                                        Context.getTypeDeclType(Type));
9730     }
9731 
9732     // C++ [dcl.type.simple]p2:
9733     //   A type-specifier of the form
9734     //     typename[opt] nested-name-specifier[opt] template-name
9735     //   is a placeholder for a deduced class type [...].
9736     if (getLangOpts().CPlusPlus17) {
9737       if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
9738         return Context.getElaboratedType(
9739             Keyword, QualifierLoc.getNestedNameSpecifier(),
9740             Context.getDeducedTemplateSpecializationType(TemplateName(TD),
9741                                                          QualType(), false));
9742       }
9743     }
9744 
9745     DiagID = diag::err_typename_nested_not_type;
9746     Referenced = Result.getFoundDecl();
9747     break;
9748 
9749   case LookupResult::FoundOverloaded:
9750     DiagID = diag::err_typename_nested_not_type;
9751     Referenced = *Result.begin();
9752     break;
9753 
9754   case LookupResult::Ambiguous:
9755     return QualType();
9756   }
9757 
9758   // If we get here, it's because name lookup did not find a
9759   // type. Emit an appropriate diagnostic and return an error.
9760   SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
9761                         IILoc);
9762   Diag(IILoc, DiagID) << FullRange << Name << Ctx;
9763   if (Referenced)
9764     Diag(Referenced->getLocation(), diag::note_typename_refers_here)
9765       << Name;
9766   return QualType();
9767 }
9768 
9769 namespace {
9770   // See Sema::RebuildTypeInCurrentInstantiation
9771   class CurrentInstantiationRebuilder
9772     : public TreeTransform<CurrentInstantiationRebuilder> {
9773     SourceLocation Loc;
9774     DeclarationName Entity;
9775 
9776   public:
9777     typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
9778 
9779     CurrentInstantiationRebuilder(Sema &SemaRef,
9780                                   SourceLocation Loc,
9781                                   DeclarationName Entity)
9782     : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
9783       Loc(Loc), Entity(Entity) { }
9784 
9785     /// Determine whether the given type \p T has already been
9786     /// transformed.
9787     ///
9788     /// For the purposes of type reconstruction, a type has already been
9789     /// transformed if it is NULL or if it is not dependent.
9790     bool AlreadyTransformed(QualType T) {
9791       return T.isNull() || !T->isDependentType();
9792     }
9793 
9794     /// Returns the location of the entity whose type is being
9795     /// rebuilt.
9796     SourceLocation getBaseLocation() { return Loc; }
9797 
9798     /// Returns the name of the entity whose type is being rebuilt.
9799     DeclarationName getBaseEntity() { return Entity; }
9800 
9801     /// Sets the "base" location and entity when that
9802     /// information is known based on another transformation.
9803     void setBase(SourceLocation Loc, DeclarationName Entity) {
9804       this->Loc = Loc;
9805       this->Entity = Entity;
9806     }
9807 
9808     ExprResult TransformLambdaExpr(LambdaExpr *E) {
9809       // Lambdas never need to be transformed.
9810       return E;
9811     }
9812   };
9813 } // end anonymous namespace
9814 
9815 /// Rebuilds a type within the context of the current instantiation.
9816 ///
9817 /// The type \p T is part of the type of an out-of-line member definition of
9818 /// a class template (or class template partial specialization) that was parsed
9819 /// and constructed before we entered the scope of the class template (or
9820 /// partial specialization thereof). This routine will rebuild that type now
9821 /// that we have entered the declarator's scope, which may produce different
9822 /// canonical types, e.g.,
9823 ///
9824 /// \code
9825 /// template<typename T>
9826 /// struct X {
9827 ///   typedef T* pointer;
9828 ///   pointer data();
9829 /// };
9830 ///
9831 /// template<typename T>
9832 /// typename X<T>::pointer X<T>::data() { ... }
9833 /// \endcode
9834 ///
9835 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
9836 /// since we do not know that we can look into X<T> when we parsed the type.
9837 /// This function will rebuild the type, performing the lookup of "pointer"
9838 /// in X<T> and returning an ElaboratedType whose canonical type is the same
9839 /// as the canonical type of T*, allowing the return types of the out-of-line
9840 /// definition and the declaration to match.
9841 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
9842                                                         SourceLocation Loc,
9843                                                         DeclarationName Name) {
9844   if (!T || !T->getType()->isDependentType())
9845     return T;
9846 
9847   CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
9848   return Rebuilder.TransformType(T);
9849 }
9850 
9851 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
9852   CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
9853                                           DeclarationName());
9854   return Rebuilder.TransformExpr(E);
9855 }
9856 
9857 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
9858   if (SS.isInvalid())
9859     return true;
9860 
9861   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9862   CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
9863                                           DeclarationName());
9864   NestedNameSpecifierLoc Rebuilt
9865     = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
9866   if (!Rebuilt)
9867     return true;
9868 
9869   SS.Adopt(Rebuilt);
9870   return false;
9871 }
9872 
9873 /// Rebuild the template parameters now that we know we're in a current
9874 /// instantiation.
9875 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
9876                                                TemplateParameterList *Params) {
9877   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9878     Decl *Param = Params->getParam(I);
9879 
9880     // There is nothing to rebuild in a type parameter.
9881     if (isa<TemplateTypeParmDecl>(Param))
9882       continue;
9883 
9884     // Rebuild the template parameter list of a template template parameter.
9885     if (TemplateTemplateParmDecl *TTP
9886         = dyn_cast<TemplateTemplateParmDecl>(Param)) {
9887       if (RebuildTemplateParamsInCurrentInstantiation(
9888             TTP->getTemplateParameters()))
9889         return true;
9890 
9891       continue;
9892     }
9893 
9894     // Rebuild the type of a non-type template parameter.
9895     NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
9896     TypeSourceInfo *NewTSI
9897       = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
9898                                           NTTP->getLocation(),
9899                                           NTTP->getDeclName());
9900     if (!NewTSI)
9901       return true;
9902 
9903     if (NewTSI->getType()->isUndeducedType()) {
9904       // C++17 [temp.dep.expr]p3:
9905       //   An id-expression is type-dependent if it contains
9906       //    - an identifier associated by name lookup with a non-type
9907       //      template-parameter declared with a type that contains a
9908       //      placeholder type (7.1.7.4),
9909       NewTSI = SubstAutoTypeSourceInfo(NewTSI, Context.DependentTy);
9910     }
9911 
9912     if (NewTSI != NTTP->getTypeSourceInfo()) {
9913       NTTP->setTypeSourceInfo(NewTSI);
9914       NTTP->setType(NewTSI->getType());
9915     }
9916   }
9917 
9918   return false;
9919 }
9920 
9921 /// Produces a formatted string that describes the binding of
9922 /// template parameters to template arguments.
9923 std::string
9924 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9925                                       const TemplateArgumentList &Args) {
9926   return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
9927 }
9928 
9929 std::string
9930 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9931                                       const TemplateArgument *Args,
9932                                       unsigned NumArgs) {
9933   SmallString<128> Str;
9934   llvm::raw_svector_ostream Out(Str);
9935 
9936   if (!Params || Params->size() == 0 || NumArgs == 0)
9937     return std::string();
9938 
9939   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9940     if (I >= NumArgs)
9941       break;
9942 
9943     if (I == 0)
9944       Out << "[with ";
9945     else
9946       Out << ", ";
9947 
9948     if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
9949       Out << Id->getName();
9950     } else {
9951       Out << '$' << I;
9952     }
9953 
9954     Out << " = ";
9955     Args[I].print(getPrintingPolicy(), Out);
9956   }
9957 
9958   Out << ']';
9959   return Out.str();
9960 }
9961 
9962 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
9963                                     CachedTokens &Toks) {
9964   if (!FD)
9965     return;
9966 
9967   auto LPT = llvm::make_unique<LateParsedTemplate>();
9968 
9969   // Take tokens to avoid allocations
9970   LPT->Toks.swap(Toks);
9971   LPT->D = FnD;
9972   LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
9973 
9974   FD->setLateTemplateParsed(true);
9975 }
9976 
9977 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
9978   if (!FD)
9979     return;
9980   FD->setLateTemplateParsed(false);
9981 }
9982 
9983 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
9984   DeclContext *DC = CurContext;
9985 
9986   while (DC) {
9987     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
9988       const FunctionDecl *FD = RD->isLocalClass();
9989       return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
9990     } else if (DC->isTranslationUnit() || DC->isNamespace())
9991       return false;
9992 
9993     DC = DC->getParent();
9994   }
9995   return false;
9996 }
9997 
9998 namespace {
9999 /// Walk the path from which a declaration was instantiated, and check
10000 /// that every explicit specialization along that path is visible. This enforces
10001 /// C++ [temp.expl.spec]/6:
10002 ///
10003 ///   If a template, a member template or a member of a class template is
10004 ///   explicitly specialized then that specialization shall be declared before
10005 ///   the first use of that specialization that would cause an implicit
10006 ///   instantiation to take place, in every translation unit in which such a
10007 ///   use occurs; no diagnostic is required.
10008 ///
10009 /// and also C++ [temp.class.spec]/1:
10010 ///
10011 ///   A partial specialization shall be declared before the first use of a
10012 ///   class template specialization that would make use of the partial
10013 ///   specialization as the result of an implicit or explicit instantiation
10014 ///   in every translation unit in which such a use occurs; no diagnostic is
10015 ///   required.
10016 class ExplicitSpecializationVisibilityChecker {
10017   Sema &S;
10018   SourceLocation Loc;
10019   llvm::SmallVector<Module *, 8> Modules;
10020 
10021 public:
10022   ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
10023       : S(S), Loc(Loc) {}
10024 
10025   void check(NamedDecl *ND) {
10026     if (auto *FD = dyn_cast<FunctionDecl>(ND))
10027       return checkImpl(FD);
10028     if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
10029       return checkImpl(RD);
10030     if (auto *VD = dyn_cast<VarDecl>(ND))
10031       return checkImpl(VD);
10032     if (auto *ED = dyn_cast<EnumDecl>(ND))
10033       return checkImpl(ED);
10034   }
10035 
10036 private:
10037   void diagnose(NamedDecl *D, bool IsPartialSpec) {
10038     auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
10039                               : Sema::MissingImportKind::ExplicitSpecialization;
10040     const bool Recover = true;
10041 
10042     // If we got a custom set of modules (because only a subset of the
10043     // declarations are interesting), use them, otherwise let
10044     // diagnoseMissingImport intelligently pick some.
10045     if (Modules.empty())
10046       S.diagnoseMissingImport(Loc, D, Kind, Recover);
10047     else
10048       S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
10049   }
10050 
10051   // Check a specific declaration. There are three problematic cases:
10052   //
10053   //  1) The declaration is an explicit specialization of a template
10054   //     specialization.
10055   //  2) The declaration is an explicit specialization of a member of an
10056   //     templated class.
10057   //  3) The declaration is an instantiation of a template, and that template
10058   //     is an explicit specialization of a member of a templated class.
10059   //
10060   // We don't need to go any deeper than that, as the instantiation of the
10061   // surrounding class / etc is not triggered by whatever triggered this
10062   // instantiation, and thus should be checked elsewhere.
10063   template<typename SpecDecl>
10064   void checkImpl(SpecDecl *Spec) {
10065     bool IsHiddenExplicitSpecialization = false;
10066     if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
10067       IsHiddenExplicitSpecialization =
10068           Spec->getMemberSpecializationInfo()
10069               ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
10070               : !S.hasVisibleExplicitSpecialization(Spec, &Modules);
10071     } else {
10072       checkInstantiated(Spec);
10073     }
10074 
10075     if (IsHiddenExplicitSpecialization)
10076       diagnose(Spec->getMostRecentDecl(), false);
10077   }
10078 
10079   void checkInstantiated(FunctionDecl *FD) {
10080     if (auto *TD = FD->getPrimaryTemplate())
10081       checkTemplate(TD);
10082   }
10083 
10084   void checkInstantiated(CXXRecordDecl *RD) {
10085     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
10086     if (!SD)
10087       return;
10088 
10089     auto From = SD->getSpecializedTemplateOrPartial();
10090     if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
10091       checkTemplate(TD);
10092     else if (auto *TD =
10093                  From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
10094       if (!S.hasVisibleDeclaration(TD))
10095         diagnose(TD, true);
10096       checkTemplate(TD);
10097     }
10098   }
10099 
10100   void checkInstantiated(VarDecl *RD) {
10101     auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
10102     if (!SD)
10103       return;
10104 
10105     auto From = SD->getSpecializedTemplateOrPartial();
10106     if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
10107       checkTemplate(TD);
10108     else if (auto *TD =
10109                  From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
10110       if (!S.hasVisibleDeclaration(TD))
10111         diagnose(TD, true);
10112       checkTemplate(TD);
10113     }
10114   }
10115 
10116   void checkInstantiated(EnumDecl *FD) {}
10117 
10118   template<typename TemplDecl>
10119   void checkTemplate(TemplDecl *TD) {
10120     if (TD->isMemberSpecialization()) {
10121       if (!S.hasVisibleMemberSpecialization(TD, &Modules))
10122         diagnose(TD->getMostRecentDecl(), false);
10123     }
10124   }
10125 };
10126 } // end anonymous namespace
10127 
10128 void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
10129   if (!getLangOpts().Modules)
10130     return;
10131 
10132   ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
10133 }
10134 
10135 /// Check whether a template partial specialization that we've discovered
10136 /// is hidden, and produce suitable diagnostics if so.
10137 void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
10138                                                 NamedDecl *Spec) {
10139   llvm::SmallVector<Module *, 8> Modules;
10140   if (!hasVisibleDeclaration(Spec, &Modules))
10141     diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
10142                           MissingImportKind::PartialSpecialization,
10143                           /*Recover*/true);
10144 }
10145