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/ASTContext.h"
14 #include "clang/AST/DeclFriend.h"
15 #include "clang/AST/DeclTemplate.h"
16 #include "clang/AST/Expr.h"
17 #include "clang/AST/ExprCXX.h"
18 #include "clang/AST/RecursiveASTVisitor.h"
19 #include "clang/AST/TypeVisitor.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "clang/Basic/PartialDiagnostic.h"
22 #include "clang/Sema/DeclSpec.h"
23 #include "clang/Sema/Lookup.h"
24 #include "clang/Sema/ParsedTemplate.h"
25 #include "clang/Sema/Scope.h"
26 #include "clang/Sema/SemaInternal.h"
27 #include "clang/Sema/Template.h"
28 #include "clang/Sema/TemplateDeduction.h"
29 #include "llvm/ADT/SmallBitVector.h"
30 #include "llvm/ADT/SmallString.h"
31 #include "llvm/ADT/StringExtras.h"
32 using namespace clang;
33 using namespace sema;
34 
35 // Exported for use by Parser.
36 SourceRange
37 clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
38                               unsigned N) {
39   if (!N) return SourceRange();
40   return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
41 }
42 
43 /// \brief Determine whether the declaration found is acceptable as the name
44 /// of a template and, if so, return that template declaration. Otherwise,
45 /// returns NULL.
46 static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
47                                            NamedDecl *Orig,
48                                            bool AllowFunctionTemplates) {
49   NamedDecl *D = Orig->getUnderlyingDecl();
50 
51   if (isa<TemplateDecl>(D)) {
52     if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
53       return 0;
54 
55     return Orig;
56   }
57 
58   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
59     // C++ [temp.local]p1:
60     //   Like normal (non-template) classes, class templates have an
61     //   injected-class-name (Clause 9). The injected-class-name
62     //   can be used with or without a template-argument-list. When
63     //   it is used without a template-argument-list, it is
64     //   equivalent to the injected-class-name followed by the
65     //   template-parameters of the class template enclosed in
66     //   <>. When it is used with a template-argument-list, it
67     //   refers to the specified class template specialization,
68     //   which could be the current specialization or another
69     //   specialization.
70     if (Record->isInjectedClassName()) {
71       Record = cast<CXXRecordDecl>(Record->getDeclContext());
72       if (Record->getDescribedClassTemplate())
73         return Record->getDescribedClassTemplate();
74 
75       if (ClassTemplateSpecializationDecl *Spec
76             = dyn_cast<ClassTemplateSpecializationDecl>(Record))
77         return Spec->getSpecializedTemplate();
78     }
79 
80     return 0;
81   }
82 
83   return 0;
84 }
85 
86 void Sema::FilterAcceptableTemplateNames(LookupResult &R,
87                                          bool AllowFunctionTemplates) {
88   // The set of class templates we've already seen.
89   llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
90   LookupResult::Filter filter = R.makeFilter();
91   while (filter.hasNext()) {
92     NamedDecl *Orig = filter.next();
93     NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
94                                                AllowFunctionTemplates);
95     if (!Repl)
96       filter.erase();
97     else if (Repl != Orig) {
98 
99       // C++ [temp.local]p3:
100       //   A lookup that finds an injected-class-name (10.2) can result in an
101       //   ambiguity in certain cases (for example, if it is found in more than
102       //   one base class). If all of the injected-class-names that are found
103       //   refer to specializations of the same class template, and if the name
104       //   is used as a template-name, the reference refers to the class
105       //   template itself and not a specialization thereof, and is not
106       //   ambiguous.
107       if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
108         if (!ClassTemplates.insert(ClassTmpl)) {
109           filter.erase();
110           continue;
111         }
112 
113       // FIXME: we promote access to public here as a workaround to
114       // the fact that LookupResult doesn't let us remember that we
115       // found this template through a particular injected class name,
116       // which means we end up doing nasty things to the invariants.
117       // Pretending that access is public is *much* safer.
118       filter.replace(Repl, AS_public);
119     }
120   }
121   filter.done();
122 }
123 
124 bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
125                                          bool AllowFunctionTemplates) {
126   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
127     if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
128       return true;
129 
130   return false;
131 }
132 
133 TemplateNameKind Sema::isTemplateName(Scope *S,
134                                       CXXScopeSpec &SS,
135                                       bool hasTemplateKeyword,
136                                       UnqualifiedId &Name,
137                                       ParsedType ObjectTypePtr,
138                                       bool EnteringContext,
139                                       TemplateTy &TemplateResult,
140                                       bool &MemberOfUnknownSpecialization) {
141   assert(getLangOpts().CPlusPlus && "No template names in C!");
142 
143   DeclarationName TName;
144   MemberOfUnknownSpecialization = false;
145 
146   switch (Name.getKind()) {
147   case UnqualifiedId::IK_Identifier:
148     TName = DeclarationName(Name.Identifier);
149     break;
150 
151   case UnqualifiedId::IK_OperatorFunctionId:
152     TName = Context.DeclarationNames.getCXXOperatorName(
153                                               Name.OperatorFunctionId.Operator);
154     break;
155 
156   case UnqualifiedId::IK_LiteralOperatorId:
157     TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
158     break;
159 
160   default:
161     return TNK_Non_template;
162   }
163 
164   QualType ObjectType = ObjectTypePtr.get();
165 
166   LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
167   LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
168                      MemberOfUnknownSpecialization);
169   if (R.empty()) return TNK_Non_template;
170   if (R.isAmbiguous()) {
171     // Suppress diagnostics;  we'll redo this lookup later.
172     R.suppressDiagnostics();
173 
174     // FIXME: we might have ambiguous templates, in which case we
175     // should at least parse them properly!
176     return TNK_Non_template;
177   }
178 
179   TemplateName Template;
180   TemplateNameKind TemplateKind;
181 
182   unsigned ResultCount = R.end() - R.begin();
183   if (ResultCount > 1) {
184     // We assume that we'll preserve the qualifier from a function
185     // template name in other ways.
186     Template = Context.getOverloadedTemplateName(R.begin(), R.end());
187     TemplateKind = TNK_Function_template;
188 
189     // We'll do this lookup again later.
190     R.suppressDiagnostics();
191   } else {
192     TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
193 
194     if (SS.isSet() && !SS.isInvalid()) {
195       NestedNameSpecifier *Qualifier
196         = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
197       Template = Context.getQualifiedTemplateName(Qualifier,
198                                                   hasTemplateKeyword, TD);
199     } else {
200       Template = TemplateName(TD);
201     }
202 
203     if (isa<FunctionTemplateDecl>(TD)) {
204       TemplateKind = TNK_Function_template;
205 
206       // We'll do this lookup again later.
207       R.suppressDiagnostics();
208     } else {
209       assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
210              isa<TypeAliasTemplateDecl>(TD));
211       TemplateKind = TNK_Type_template;
212     }
213   }
214 
215   TemplateResult = TemplateTy::make(Template);
216   return TemplateKind;
217 }
218 
219 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
220                                        SourceLocation IILoc,
221                                        Scope *S,
222                                        const CXXScopeSpec *SS,
223                                        TemplateTy &SuggestedTemplate,
224                                        TemplateNameKind &SuggestedKind) {
225   // We can't recover unless there's a dependent scope specifier preceding the
226   // template name.
227   // FIXME: Typo correction?
228   if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
229       computeDeclContext(*SS))
230     return false;
231 
232   // The code is missing a 'template' keyword prior to the dependent template
233   // name.
234   NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
235   Diag(IILoc, diag::err_template_kw_missing)
236     << Qualifier << II.getName()
237     << FixItHint::CreateInsertion(IILoc, "template ");
238   SuggestedTemplate
239     = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
240   SuggestedKind = TNK_Dependent_template_name;
241   return true;
242 }
243 
244 void Sema::LookupTemplateName(LookupResult &Found,
245                               Scope *S, CXXScopeSpec &SS,
246                               QualType ObjectType,
247                               bool EnteringContext,
248                               bool &MemberOfUnknownSpecialization) {
249   // Determine where to perform name lookup
250   MemberOfUnknownSpecialization = false;
251   DeclContext *LookupCtx = 0;
252   bool isDependent = false;
253   if (!ObjectType.isNull()) {
254     // This nested-name-specifier occurs in a member access expression, e.g.,
255     // x->B::f, and we are looking into the type of the object.
256     assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
257     LookupCtx = computeDeclContext(ObjectType);
258     isDependent = ObjectType->isDependentType();
259     assert((isDependent || !ObjectType->isIncompleteType() ||
260             ObjectType->castAs<TagType>()->isBeingDefined()) &&
261            "Caller should have completed object type");
262 
263     // Template names cannot appear inside an Objective-C class or object type.
264     if (ObjectType->isObjCObjectOrInterfaceType()) {
265       Found.clear();
266       return;
267     }
268   } else if (SS.isSet()) {
269     // This nested-name-specifier occurs after another nested-name-specifier,
270     // so long into the context associated with the prior nested-name-specifier.
271     LookupCtx = computeDeclContext(SS, EnteringContext);
272     isDependent = isDependentScopeSpecifier(SS);
273 
274     // The declaration context must be complete.
275     if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
276       return;
277   }
278 
279   bool ObjectTypeSearchedInScope = false;
280   bool AllowFunctionTemplatesInLookup = true;
281   if (LookupCtx) {
282     // Perform "qualified" name lookup into the declaration context we
283     // computed, which is either the type of the base of a member access
284     // expression or the declaration context associated with a prior
285     // nested-name-specifier.
286     LookupQualifiedName(Found, LookupCtx);
287     if (!ObjectType.isNull() && Found.empty()) {
288       // C++ [basic.lookup.classref]p1:
289       //   In a class member access expression (5.2.5), if the . or -> token is
290       //   immediately followed by an identifier followed by a <, the
291       //   identifier must be looked up to determine whether the < is the
292       //   beginning of a template argument list (14.2) or a less-than operator.
293       //   The identifier is first looked up in the class of the object
294       //   expression. If the identifier is not found, it is then looked up in
295       //   the context of the entire postfix-expression and shall name a class
296       //   or function template.
297       if (S) LookupName(Found, S);
298       ObjectTypeSearchedInScope = true;
299       AllowFunctionTemplatesInLookup = false;
300     }
301   } else if (isDependent && (!S || ObjectType.isNull())) {
302     // We cannot look into a dependent object type or nested nme
303     // specifier.
304     MemberOfUnknownSpecialization = true;
305     return;
306   } else {
307     // Perform unqualified name lookup in the current scope.
308     LookupName(Found, S);
309 
310     if (!ObjectType.isNull())
311       AllowFunctionTemplatesInLookup = false;
312   }
313 
314   if (Found.empty() && !isDependent) {
315     // If we did not find any names, attempt to correct any typos.
316     DeclarationName Name = Found.getLookupName();
317     Found.clear();
318     // Simple filter callback that, for keywords, only accepts the C++ *_cast
319     CorrectionCandidateCallback FilterCCC;
320     FilterCCC.WantTypeSpecifiers = false;
321     FilterCCC.WantExpressionKeywords = false;
322     FilterCCC.WantRemainingKeywords = false;
323     FilterCCC.WantCXXNamedCasts = true;
324     if (TypoCorrection Corrected = CorrectTypo(Found.getLookupNameInfo(),
325                                                Found.getLookupKind(), S, &SS,
326                                                FilterCCC, LookupCtx)) {
327       Found.setLookupName(Corrected.getCorrection());
328       if (Corrected.getCorrectionDecl())
329         Found.addDecl(Corrected.getCorrectionDecl());
330       FilterAcceptableTemplateNames(Found);
331       if (!Found.empty()) {
332         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
333         std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
334         if (LookupCtx)
335           Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
336             << Name << LookupCtx << CorrectedQuotedStr << SS.getRange()
337             << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
338                                             CorrectedStr);
339         else
340           Diag(Found.getNameLoc(), diag::err_no_template_suggest)
341             << Name << CorrectedQuotedStr
342             << FixItHint::CreateReplacement(Found.getNameLoc(), CorrectedStr);
343         if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
344           Diag(Template->getLocation(), diag::note_previous_decl)
345             << CorrectedQuotedStr;
346       }
347     } else {
348       Found.setLookupName(Name);
349     }
350   }
351 
352   FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
353   if (Found.empty()) {
354     if (isDependent)
355       MemberOfUnknownSpecialization = true;
356     return;
357   }
358 
359   if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
360       !(getLangOpts().CPlusPlus11 && !Found.empty())) {
361     // C++03 [basic.lookup.classref]p1:
362     //   [...] If the lookup in the class of the object expression finds a
363     //   template, the name is also looked up in the context of the entire
364     //   postfix-expression and [...]
365     //
366     // Note: C++11 does not perform this second lookup.
367     LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
368                             LookupOrdinaryName);
369     LookupName(FoundOuter, S);
370     FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
371 
372     if (FoundOuter.empty()) {
373       //   - if the name is not found, the name found in the class of the
374       //     object expression is used, otherwise
375     } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
376                FoundOuter.isAmbiguous()) {
377       //   - if the name is found in the context of the entire
378       //     postfix-expression and does not name a class template, the name
379       //     found in the class of the object expression is used, otherwise
380       FoundOuter.clear();
381     } else if (!Found.isSuppressingDiagnostics()) {
382       //   - if the name found is a class template, it must refer to the same
383       //     entity as the one found in the class of the object expression,
384       //     otherwise the program is ill-formed.
385       if (!Found.isSingleResult() ||
386           Found.getFoundDecl()->getCanonicalDecl()
387             != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
388         Diag(Found.getNameLoc(),
389              diag::ext_nested_name_member_ref_lookup_ambiguous)
390           << Found.getLookupName()
391           << ObjectType;
392         Diag(Found.getRepresentativeDecl()->getLocation(),
393              diag::note_ambig_member_ref_object_type)
394           << ObjectType;
395         Diag(FoundOuter.getFoundDecl()->getLocation(),
396              diag::note_ambig_member_ref_scope);
397 
398         // Recover by taking the template that we found in the object
399         // expression's type.
400       }
401     }
402   }
403 }
404 
405 /// ActOnDependentIdExpression - Handle a dependent id-expression that
406 /// was just parsed.  This is only possible with an explicit scope
407 /// specifier naming a dependent type.
408 ExprResult
409 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
410                                  SourceLocation TemplateKWLoc,
411                                  const DeclarationNameInfo &NameInfo,
412                                  bool isAddressOfOperand,
413                            const TemplateArgumentListInfo *TemplateArgs) {
414   DeclContext *DC = getFunctionLevelDeclContext();
415 
416   if (!isAddressOfOperand &&
417       isa<CXXMethodDecl>(DC) &&
418       cast<CXXMethodDecl>(DC)->isInstance()) {
419     QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
420 
421     // Since the 'this' expression is synthesized, we don't need to
422     // perform the double-lookup check.
423     NamedDecl *FirstQualifierInScope = 0;
424 
425     return Owned(CXXDependentScopeMemberExpr::Create(Context,
426                                                      /*This*/ 0, ThisType,
427                                                      /*IsArrow*/ true,
428                                                      /*Op*/ SourceLocation(),
429                                                SS.getWithLocInContext(Context),
430                                                      TemplateKWLoc,
431                                                      FirstQualifierInScope,
432                                                      NameInfo,
433                                                      TemplateArgs));
434   }
435 
436   return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
437 }
438 
439 ExprResult
440 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
441                                 SourceLocation TemplateKWLoc,
442                                 const DeclarationNameInfo &NameInfo,
443                                 const TemplateArgumentListInfo *TemplateArgs) {
444   return Owned(DependentScopeDeclRefExpr::Create(Context,
445                                                SS.getWithLocInContext(Context),
446                                                  TemplateKWLoc,
447                                                  NameInfo,
448                                                  TemplateArgs));
449 }
450 
451 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
452 /// that the template parameter 'PrevDecl' is being shadowed by a new
453 /// declaration at location Loc. Returns true to indicate that this is
454 /// an error, and false otherwise.
455 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
456   assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
457 
458   // Microsoft Visual C++ permits template parameters to be shadowed.
459   if (getLangOpts().MicrosoftExt)
460     return;
461 
462   // C++ [temp.local]p4:
463   //   A template-parameter shall not be redeclared within its
464   //   scope (including nested scopes).
465   Diag(Loc, diag::err_template_param_shadow)
466     << cast<NamedDecl>(PrevDecl)->getDeclName();
467   Diag(PrevDecl->getLocation(), diag::note_template_param_here);
468   return;
469 }
470 
471 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
472 /// the parameter D to reference the templated declaration and return a pointer
473 /// to the template declaration. Otherwise, do nothing to D and return null.
474 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
475   if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
476     D = Temp->getTemplatedDecl();
477     return Temp;
478   }
479   return 0;
480 }
481 
482 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
483                                              SourceLocation EllipsisLoc) const {
484   assert(Kind == Template &&
485          "Only template template arguments can be pack expansions here");
486   assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
487          "Template template argument pack expansion without packs");
488   ParsedTemplateArgument Result(*this);
489   Result.EllipsisLoc = EllipsisLoc;
490   return Result;
491 }
492 
493 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
494                                             const ParsedTemplateArgument &Arg) {
495 
496   switch (Arg.getKind()) {
497   case ParsedTemplateArgument::Type: {
498     TypeSourceInfo *DI;
499     QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
500     if (!DI)
501       DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
502     return TemplateArgumentLoc(TemplateArgument(T), DI);
503   }
504 
505   case ParsedTemplateArgument::NonType: {
506     Expr *E = static_cast<Expr *>(Arg.getAsExpr());
507     return TemplateArgumentLoc(TemplateArgument(E), E);
508   }
509 
510   case ParsedTemplateArgument::Template: {
511     TemplateName Template = Arg.getAsTemplate().get();
512     TemplateArgument TArg;
513     if (Arg.getEllipsisLoc().isValid())
514       TArg = TemplateArgument(Template, Optional<unsigned int>());
515     else
516       TArg = Template;
517     return TemplateArgumentLoc(TArg,
518                                Arg.getScopeSpec().getWithLocInContext(
519                                                               SemaRef.Context),
520                                Arg.getLocation(),
521                                Arg.getEllipsisLoc());
522   }
523   }
524 
525   llvm_unreachable("Unhandled parsed template argument");
526 }
527 
528 /// \brief Translates template arguments as provided by the parser
529 /// into template arguments used by semantic analysis.
530 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
531                                       TemplateArgumentListInfo &TemplateArgs) {
532  for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
533    TemplateArgs.addArgument(translateTemplateArgument(*this,
534                                                       TemplateArgsIn[I]));
535 }
536 
537 /// ActOnTypeParameter - Called when a C++ template type parameter
538 /// (e.g., "typename T") has been parsed. Typename specifies whether
539 /// the keyword "typename" was used to declare the type parameter
540 /// (otherwise, "class" was used), and KeyLoc is the location of the
541 /// "class" or "typename" keyword. ParamName is the name of the
542 /// parameter (NULL indicates an unnamed template parameter) and
543 /// ParamNameLoc is the location of the parameter name (if any).
544 /// If the type parameter has a default argument, it will be added
545 /// later via ActOnTypeParameterDefault.
546 Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
547                                SourceLocation EllipsisLoc,
548                                SourceLocation KeyLoc,
549                                IdentifierInfo *ParamName,
550                                SourceLocation ParamNameLoc,
551                                unsigned Depth, unsigned Position,
552                                SourceLocation EqualLoc,
553                                ParsedType DefaultArg) {
554   assert(S->isTemplateParamScope() &&
555          "Template type parameter not in template parameter scope!");
556   bool Invalid = false;
557 
558   if (ParamName) {
559     NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
560                                            LookupOrdinaryName,
561                                            ForRedeclaration);
562     if (PrevDecl && PrevDecl->isTemplateParameter()) {
563       DiagnoseTemplateParameterShadow(ParamNameLoc, PrevDecl);
564       PrevDecl = 0;
565     }
566   }
567 
568   SourceLocation Loc = ParamNameLoc;
569   if (!ParamName)
570     Loc = KeyLoc;
571 
572   TemplateTypeParmDecl *Param
573     = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
574                                    KeyLoc, Loc, Depth, Position, ParamName,
575                                    Typename, Ellipsis);
576   Param->setAccess(AS_public);
577   if (Invalid)
578     Param->setInvalidDecl();
579 
580   if (ParamName) {
581     // Add the template parameter into the current scope.
582     S->AddDecl(Param);
583     IdResolver.AddDecl(Param);
584   }
585 
586   // C++0x [temp.param]p9:
587   //   A default template-argument may be specified for any kind of
588   //   template-parameter that is not a template parameter pack.
589   if (DefaultArg && Ellipsis) {
590     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
591     DefaultArg = ParsedType();
592   }
593 
594   // Handle the default argument, if provided.
595   if (DefaultArg) {
596     TypeSourceInfo *DefaultTInfo;
597     GetTypeFromParser(DefaultArg, &DefaultTInfo);
598 
599     assert(DefaultTInfo && "expected source information for type");
600 
601     // Check for unexpanded parameter packs.
602     if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
603                                         UPPC_DefaultArgument))
604       return Param;
605 
606     // Check the template argument itself.
607     if (CheckTemplateArgument(Param, DefaultTInfo)) {
608       Param->setInvalidDecl();
609       return Param;
610     }
611 
612     Param->setDefaultArgument(DefaultTInfo, false);
613   }
614 
615   return Param;
616 }
617 
618 /// \brief Check that the type of a non-type template parameter is
619 /// well-formed.
620 ///
621 /// \returns the (possibly-promoted) parameter type if valid;
622 /// otherwise, produces a diagnostic and returns a NULL type.
623 QualType
624 Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
625   // We don't allow variably-modified types as the type of non-type template
626   // parameters.
627   if (T->isVariablyModifiedType()) {
628     Diag(Loc, diag::err_variably_modified_nontype_template_param)
629       << T;
630     return QualType();
631   }
632 
633   // C++ [temp.param]p4:
634   //
635   // A non-type template-parameter shall have one of the following
636   // (optionally cv-qualified) types:
637   //
638   //       -- integral or enumeration type,
639   if (T->isIntegralOrEnumerationType() ||
640       //   -- pointer to object or pointer to function,
641       T->isPointerType() ||
642       //   -- reference to object or reference to function,
643       T->isReferenceType() ||
644       //   -- pointer to member,
645       T->isMemberPointerType() ||
646       //   -- std::nullptr_t.
647       T->isNullPtrType() ||
648       // If T is a dependent type, we can't do the check now, so we
649       // assume that it is well-formed.
650       T->isDependentType()) {
651     // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
652     // are ignored when determining its type.
653     return T.getUnqualifiedType();
654   }
655 
656   // C++ [temp.param]p8:
657   //
658   //   A non-type template-parameter of type "array of T" or
659   //   "function returning T" is adjusted to be of type "pointer to
660   //   T" or "pointer to function returning T", respectively.
661   else if (T->isArrayType())
662     // FIXME: Keep the type prior to promotion?
663     return Context.getArrayDecayedType(T);
664   else if (T->isFunctionType())
665     // FIXME: Keep the type prior to promotion?
666     return Context.getPointerType(T);
667 
668   Diag(Loc, diag::err_template_nontype_parm_bad_type)
669     << T;
670 
671   return QualType();
672 }
673 
674 Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
675                                           unsigned Depth,
676                                           unsigned Position,
677                                           SourceLocation EqualLoc,
678                                           Expr *Default) {
679   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
680   QualType T = TInfo->getType();
681 
682   assert(S->isTemplateParamScope() &&
683          "Non-type template parameter not in template parameter scope!");
684   bool Invalid = false;
685 
686   IdentifierInfo *ParamName = D.getIdentifier();
687   if (ParamName) {
688     NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
689                                            LookupOrdinaryName,
690                                            ForRedeclaration);
691     if (PrevDecl && PrevDecl->isTemplateParameter()) {
692       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
693       PrevDecl = 0;
694     }
695   }
696 
697   T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
698   if (T.isNull()) {
699     T = Context.IntTy; // Recover with an 'int' type.
700     Invalid = true;
701   }
702 
703   bool IsParameterPack = D.hasEllipsis();
704   NonTypeTemplateParmDecl *Param
705     = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
706                                       D.getLocStart(),
707                                       D.getIdentifierLoc(),
708                                       Depth, Position, ParamName, T,
709                                       IsParameterPack, TInfo);
710   Param->setAccess(AS_public);
711 
712   if (Invalid)
713     Param->setInvalidDecl();
714 
715   if (D.getIdentifier()) {
716     // Add the template parameter into the current scope.
717     S->AddDecl(Param);
718     IdResolver.AddDecl(Param);
719   }
720 
721   // C++0x [temp.param]p9:
722   //   A default template-argument may be specified for any kind of
723   //   template-parameter that is not a template parameter pack.
724   if (Default && IsParameterPack) {
725     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
726     Default = 0;
727   }
728 
729   // Check the well-formedness of the default template argument, if provided.
730   if (Default) {
731     // Check for unexpanded parameter packs.
732     if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
733       return Param;
734 
735     TemplateArgument Converted;
736     ExprResult DefaultRes = CheckTemplateArgument(Param, Param->getType(), Default, Converted);
737     if (DefaultRes.isInvalid()) {
738       Param->setInvalidDecl();
739       return Param;
740     }
741     Default = DefaultRes.take();
742 
743     Param->setDefaultArgument(Default, false);
744   }
745 
746   return Param;
747 }
748 
749 /// ActOnTemplateTemplateParameter - Called when a C++ template template
750 /// parameter (e.g. T in template <template \<typename> class T> class array)
751 /// has been parsed. S is the current scope.
752 Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
753                                            SourceLocation TmpLoc,
754                                            TemplateParameterList *Params,
755                                            SourceLocation EllipsisLoc,
756                                            IdentifierInfo *Name,
757                                            SourceLocation NameLoc,
758                                            unsigned Depth,
759                                            unsigned Position,
760                                            SourceLocation EqualLoc,
761                                            ParsedTemplateArgument Default) {
762   assert(S->isTemplateParamScope() &&
763          "Template template parameter not in template parameter scope!");
764 
765   // Construct the parameter object.
766   bool IsParameterPack = EllipsisLoc.isValid();
767   TemplateTemplateParmDecl *Param =
768     TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
769                                      NameLoc.isInvalid()? TmpLoc : NameLoc,
770                                      Depth, Position, IsParameterPack,
771                                      Name, Params);
772   Param->setAccess(AS_public);
773 
774   // If the template template parameter has a name, then link the identifier
775   // into the scope and lookup mechanisms.
776   if (Name) {
777     S->AddDecl(Param);
778     IdResolver.AddDecl(Param);
779   }
780 
781   if (Params->size() == 0) {
782     Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
783     << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
784     Param->setInvalidDecl();
785   }
786 
787   // C++0x [temp.param]p9:
788   //   A default template-argument may be specified for any kind of
789   //   template-parameter that is not a template parameter pack.
790   if (IsParameterPack && !Default.isInvalid()) {
791     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
792     Default = ParsedTemplateArgument();
793   }
794 
795   if (!Default.isInvalid()) {
796     // Check only that we have a template template argument. We don't want to
797     // try to check well-formedness now, because our template template parameter
798     // might have dependent types in its template parameters, which we wouldn't
799     // be able to match now.
800     //
801     // If none of the template template parameter's template arguments mention
802     // other template parameters, we could actually perform more checking here.
803     // However, it isn't worth doing.
804     TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
805     if (DefaultArg.getArgument().getAsTemplate().isNull()) {
806       Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
807         << DefaultArg.getSourceRange();
808       return Param;
809     }
810 
811     // Check for unexpanded parameter packs.
812     if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
813                                         DefaultArg.getArgument().getAsTemplate(),
814                                         UPPC_DefaultArgument))
815       return Param;
816 
817     Param->setDefaultArgument(DefaultArg, false);
818   }
819 
820   return Param;
821 }
822 
823 /// ActOnTemplateParameterList - Builds a TemplateParameterList that
824 /// contains the template parameters in Params/NumParams.
825 TemplateParameterList *
826 Sema::ActOnTemplateParameterList(unsigned Depth,
827                                  SourceLocation ExportLoc,
828                                  SourceLocation TemplateLoc,
829                                  SourceLocation LAngleLoc,
830                                  Decl **Params, unsigned NumParams,
831                                  SourceLocation RAngleLoc) {
832   if (ExportLoc.isValid())
833     Diag(ExportLoc, diag::warn_template_export_unsupported);
834 
835   return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
836                                        (NamedDecl**)Params, NumParams,
837                                        RAngleLoc);
838 }
839 
840 static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
841   if (SS.isSet())
842     T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
843 }
844 
845 DeclResult
846 Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
847                          SourceLocation KWLoc, CXXScopeSpec &SS,
848                          IdentifierInfo *Name, SourceLocation NameLoc,
849                          AttributeList *Attr,
850                          TemplateParameterList *TemplateParams,
851                          AccessSpecifier AS, SourceLocation ModulePrivateLoc,
852                          unsigned NumOuterTemplateParamLists,
853                          TemplateParameterList** OuterTemplateParamLists) {
854   assert(TemplateParams && TemplateParams->size() > 0 &&
855          "No template parameters");
856   assert(TUK != TUK_Reference && "Can only declare or define class templates");
857   bool Invalid = false;
858 
859   // Check that we can declare a template here.
860   if (CheckTemplateDeclScope(S, TemplateParams))
861     return true;
862 
863   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
864   assert(Kind != TTK_Enum && "can't build template of enumerated type");
865 
866   // There is no such thing as an unnamed class template.
867   if (!Name) {
868     Diag(KWLoc, diag::err_template_unnamed_class);
869     return true;
870   }
871 
872   // Find any previous declaration with this name. For a friend with no
873   // scope explicitly specified, we only look for tag declarations (per
874   // C++11 [basic.lookup.elab]p2).
875   DeclContext *SemanticContext;
876   LookupResult Previous(*this, Name, NameLoc,
877                         (SS.isEmpty() && TUK == TUK_Friend)
878                           ? LookupTagName : LookupOrdinaryName,
879                         ForRedeclaration);
880   if (SS.isNotEmpty() && !SS.isInvalid()) {
881     SemanticContext = computeDeclContext(SS, true);
882     if (!SemanticContext) {
883       // FIXME: Horrible, horrible hack! We can't currently represent this
884       // in the AST, and historically we have just ignored such friend
885       // class templates, so don't complain here.
886       if (TUK != TUK_Friend)
887         Diag(NameLoc, diag::err_template_qualified_declarator_no_match)
888           << SS.getScopeRep() << SS.getRange();
889       return true;
890     }
891 
892     if (RequireCompleteDeclContext(SS, SemanticContext))
893       return true;
894 
895     // If we're adding a template to a dependent context, we may need to
896     // rebuilding some of the types used within the template parameter list,
897     // now that we know what the current instantiation is.
898     if (SemanticContext->isDependentContext()) {
899       ContextRAII SavedContext(*this, SemanticContext);
900       if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
901         Invalid = true;
902     } else if (TUK != TUK_Friend && TUK != TUK_Reference)
903       diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
904 
905     LookupQualifiedName(Previous, SemanticContext);
906   } else {
907     SemanticContext = CurContext;
908     LookupName(Previous, S);
909   }
910 
911   if (Previous.isAmbiguous())
912     return true;
913 
914   NamedDecl *PrevDecl = 0;
915   if (Previous.begin() != Previous.end())
916     PrevDecl = (*Previous.begin())->getUnderlyingDecl();
917 
918   // If there is a previous declaration with the same name, check
919   // whether this is a valid redeclaration.
920   ClassTemplateDecl *PrevClassTemplate
921     = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
922 
923   // We may have found the injected-class-name of a class template,
924   // class template partial specialization, or class template specialization.
925   // In these cases, grab the template that is being defined or specialized.
926   if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
927       cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
928     PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
929     PrevClassTemplate
930       = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
931     if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
932       PrevClassTemplate
933         = cast<ClassTemplateSpecializationDecl>(PrevDecl)
934             ->getSpecializedTemplate();
935     }
936   }
937 
938   if (TUK == TUK_Friend) {
939     // C++ [namespace.memdef]p3:
940     //   [...] When looking for a prior declaration of a class or a function
941     //   declared as a friend, and when the name of the friend class or
942     //   function is neither a qualified name nor a template-id, scopes outside
943     //   the innermost enclosing namespace scope are not considered.
944     if (!SS.isSet()) {
945       DeclContext *OutermostContext = CurContext;
946       while (!OutermostContext->isFileContext())
947         OutermostContext = OutermostContext->getLookupParent();
948 
949       if (PrevDecl &&
950           (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
951            OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
952         SemanticContext = PrevDecl->getDeclContext();
953       } else {
954         // Declarations in outer scopes don't matter. However, the outermost
955         // context we computed is the semantic context for our new
956         // declaration.
957         PrevDecl = PrevClassTemplate = 0;
958         SemanticContext = OutermostContext;
959 
960         // Check that the chosen semantic context doesn't already contain a
961         // declaration of this name as a non-tag type.
962         LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
963                               ForRedeclaration);
964         DeclContext *LookupContext = SemanticContext;
965         while (LookupContext->isTransparentContext())
966           LookupContext = LookupContext->getLookupParent();
967         LookupQualifiedName(Previous, LookupContext);
968 
969         if (Previous.isAmbiguous())
970           return true;
971 
972         if (Previous.begin() != Previous.end())
973           PrevDecl = (*Previous.begin())->getUnderlyingDecl();
974       }
975     }
976   } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
977     PrevDecl = PrevClassTemplate = 0;
978 
979   if (PrevClassTemplate) {
980     // Ensure that the template parameter lists are compatible. Skip this check
981     // for a friend in a dependent context: the template parameter list itself
982     // could be dependent.
983     if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
984         !TemplateParameterListsAreEqual(TemplateParams,
985                                    PrevClassTemplate->getTemplateParameters(),
986                                         /*Complain=*/true,
987                                         TPL_TemplateMatch))
988       return true;
989 
990     // C++ [temp.class]p4:
991     //   In a redeclaration, partial specialization, explicit
992     //   specialization or explicit instantiation of a class template,
993     //   the class-key shall agree in kind with the original class
994     //   template declaration (7.1.5.3).
995     RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
996     if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
997                                       TUK == TUK_Definition,  KWLoc, *Name)) {
998       Diag(KWLoc, diag::err_use_with_wrong_tag)
999         << Name
1000         << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1001       Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1002       Kind = PrevRecordDecl->getTagKind();
1003     }
1004 
1005     // Check for redefinition of this class template.
1006     if (TUK == TUK_Definition) {
1007       if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1008         Diag(NameLoc, diag::err_redefinition) << Name;
1009         Diag(Def->getLocation(), diag::note_previous_definition);
1010         // FIXME: Would it make sense to try to "forget" the previous
1011         // definition, as part of error recovery?
1012         return true;
1013       }
1014     }
1015   } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
1016     // Maybe we will complain about the shadowed template parameter.
1017     DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1018     // Just pretend that we didn't see the previous declaration.
1019     PrevDecl = 0;
1020   } else if (PrevDecl) {
1021     // C++ [temp]p5:
1022     //   A class template shall not have the same name as any other
1023     //   template, class, function, object, enumeration, enumerator,
1024     //   namespace, or type in the same scope (3.3), except as specified
1025     //   in (14.5.4).
1026     Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1027     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1028     return true;
1029   }
1030 
1031   // Check the template parameter list of this declaration, possibly
1032   // merging in the template parameter list from the previous class
1033   // template declaration. Skip this check for a friend in a dependent
1034   // context, because the template parameter list might be dependent.
1035   if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1036       CheckTemplateParameterList(TemplateParams,
1037             PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
1038                                  (SS.isSet() && SemanticContext &&
1039                                   SemanticContext->isRecord() &&
1040                                   SemanticContext->isDependentContext())
1041                                    ? TPC_ClassTemplateMember
1042                                    : TPC_ClassTemplate))
1043     Invalid = true;
1044 
1045   if (SS.isSet()) {
1046     // If the name of the template was qualified, we must be defining the
1047     // template out-of-line.
1048     if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1049       Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1050                                       : diag::err_member_def_does_not_match)
1051         << Name << SemanticContext << SS.getRange();
1052       Invalid = true;
1053     }
1054   }
1055 
1056   CXXRecordDecl *NewClass =
1057     CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1058                           PrevClassTemplate?
1059                             PrevClassTemplate->getTemplatedDecl() : 0,
1060                           /*DelayTypeCreation=*/true);
1061   SetNestedNameSpecifier(NewClass, SS);
1062   if (NumOuterTemplateParamLists > 0)
1063     NewClass->setTemplateParameterListsInfo(Context,
1064                                             NumOuterTemplateParamLists,
1065                                             OuterTemplateParamLists);
1066 
1067   // Add alignment attributes if necessary; these attributes are checked when
1068   // the ASTContext lays out the structure.
1069   if (TUK == TUK_Definition) {
1070     AddAlignmentAttributesForRecord(NewClass);
1071     AddMsStructLayoutForRecord(NewClass);
1072   }
1073 
1074   ClassTemplateDecl *NewTemplate
1075     = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1076                                 DeclarationName(Name), TemplateParams,
1077                                 NewClass, PrevClassTemplate);
1078   NewClass->setDescribedClassTemplate(NewTemplate);
1079 
1080   if (ModulePrivateLoc.isValid())
1081     NewTemplate->setModulePrivate();
1082 
1083   // Build the type for the class template declaration now.
1084   QualType T = NewTemplate->getInjectedClassNameSpecialization();
1085   T = Context.getInjectedClassNameType(NewClass, T);
1086   assert(T->isDependentType() && "Class template type is not dependent?");
1087   (void)T;
1088 
1089   // If we are providing an explicit specialization of a member that is a
1090   // class template, make a note of that.
1091   if (PrevClassTemplate &&
1092       PrevClassTemplate->getInstantiatedFromMemberTemplate())
1093     PrevClassTemplate->setMemberSpecialization();
1094 
1095   // Set the access specifier.
1096   if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1097     SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1098 
1099   // Set the lexical context of these templates
1100   NewClass->setLexicalDeclContext(CurContext);
1101   NewTemplate->setLexicalDeclContext(CurContext);
1102 
1103   if (TUK == TUK_Definition)
1104     NewClass->startDefinition();
1105 
1106   if (Attr)
1107     ProcessDeclAttributeList(S, NewClass, Attr);
1108 
1109   if (PrevClassTemplate)
1110     mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1111 
1112   AddPushedVisibilityAttribute(NewClass);
1113 
1114   if (TUK != TUK_Friend)
1115     PushOnScopeChains(NewTemplate, S);
1116   else {
1117     if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1118       NewTemplate->setAccess(PrevClassTemplate->getAccess());
1119       NewClass->setAccess(PrevClassTemplate->getAccess());
1120     }
1121 
1122     NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
1123                                        PrevClassTemplate != NULL);
1124 
1125     // Friend templates are visible in fairly strange ways.
1126     if (!CurContext->isDependentContext()) {
1127       DeclContext *DC = SemanticContext->getRedeclContext();
1128       DC->makeDeclVisibleInContext(NewTemplate);
1129       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1130         PushOnScopeChains(NewTemplate, EnclosingScope,
1131                           /* AddToContext = */ false);
1132     }
1133 
1134     FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
1135                                             NewClass->getLocation(),
1136                                             NewTemplate,
1137                                     /*FIXME:*/NewClass->getLocation());
1138     Friend->setAccess(AS_public);
1139     CurContext->addDecl(Friend);
1140   }
1141 
1142   if (Invalid) {
1143     NewTemplate->setInvalidDecl();
1144     NewClass->setInvalidDecl();
1145   }
1146 
1147   ActOnDocumentableDecl(NewTemplate);
1148 
1149   return NewTemplate;
1150 }
1151 
1152 /// \brief Diagnose the presence of a default template argument on a
1153 /// template parameter, which is ill-formed in certain contexts.
1154 ///
1155 /// \returns true if the default template argument should be dropped.
1156 static bool DiagnoseDefaultTemplateArgument(Sema &S,
1157                                             Sema::TemplateParamListContext TPC,
1158                                             SourceLocation ParamLoc,
1159                                             SourceRange DefArgRange) {
1160   switch (TPC) {
1161   case Sema::TPC_ClassTemplate:
1162   case Sema::TPC_TypeAliasTemplate:
1163     return false;
1164 
1165   case Sema::TPC_FunctionTemplate:
1166   case Sema::TPC_FriendFunctionTemplateDefinition:
1167     // C++ [temp.param]p9:
1168     //   A default template-argument shall not be specified in a
1169     //   function template declaration or a function template
1170     //   definition [...]
1171     //   If a friend function template declaration specifies a default
1172     //   template-argument, that declaration shall be a definition and shall be
1173     //   the only declaration of the function template in the translation unit.
1174     // (C++98/03 doesn't have this wording; see DR226).
1175     S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
1176          diag::warn_cxx98_compat_template_parameter_default_in_function_template
1177            : diag::ext_template_parameter_default_in_function_template)
1178       << DefArgRange;
1179     return false;
1180 
1181   case Sema::TPC_ClassTemplateMember:
1182     // C++0x [temp.param]p9:
1183     //   A default template-argument shall not be specified in the
1184     //   template-parameter-lists of the definition of a member of a
1185     //   class template that appears outside of the member's class.
1186     S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1187       << DefArgRange;
1188     return true;
1189 
1190   case Sema::TPC_FriendFunctionTemplate:
1191     // C++ [temp.param]p9:
1192     //   A default template-argument shall not be specified in a
1193     //   friend template declaration.
1194     S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1195       << DefArgRange;
1196     return true;
1197 
1198     // FIXME: C++0x [temp.param]p9 allows default template-arguments
1199     // for friend function templates if there is only a single
1200     // declaration (and it is a definition). Strange!
1201   }
1202 
1203   llvm_unreachable("Invalid TemplateParamListContext!");
1204 }
1205 
1206 /// \brief Check for unexpanded parameter packs within the template parameters
1207 /// of a template template parameter, recursively.
1208 static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1209                                              TemplateTemplateParmDecl *TTP) {
1210   // A template template parameter which is a parameter pack is also a pack
1211   // expansion.
1212   if (TTP->isParameterPack())
1213     return false;
1214 
1215   TemplateParameterList *Params = TTP->getTemplateParameters();
1216   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1217     NamedDecl *P = Params->getParam(I);
1218     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1219       if (!NTTP->isParameterPack() &&
1220           S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1221                                             NTTP->getTypeSourceInfo(),
1222                                       Sema::UPPC_NonTypeTemplateParameterType))
1223         return true;
1224 
1225       continue;
1226     }
1227 
1228     if (TemplateTemplateParmDecl *InnerTTP
1229                                         = dyn_cast<TemplateTemplateParmDecl>(P))
1230       if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1231         return true;
1232   }
1233 
1234   return false;
1235 }
1236 
1237 /// \brief Checks the validity of a template parameter list, possibly
1238 /// considering the template parameter list from a previous
1239 /// declaration.
1240 ///
1241 /// If an "old" template parameter list is provided, it must be
1242 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
1243 /// template parameter list.
1244 ///
1245 /// \param NewParams Template parameter list for a new template
1246 /// declaration. This template parameter list will be updated with any
1247 /// default arguments that are carried through from the previous
1248 /// template parameter list.
1249 ///
1250 /// \param OldParams If provided, template parameter list from a
1251 /// previous declaration of the same template. Default template
1252 /// arguments will be merged from the old template parameter list to
1253 /// the new template parameter list.
1254 ///
1255 /// \param TPC Describes the context in which we are checking the given
1256 /// template parameter list.
1257 ///
1258 /// \returns true if an error occurred, false otherwise.
1259 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
1260                                       TemplateParameterList *OldParams,
1261                                       TemplateParamListContext TPC) {
1262   bool Invalid = false;
1263 
1264   // C++ [temp.param]p10:
1265   //   The set of default template-arguments available for use with a
1266   //   template declaration or definition is obtained by merging the
1267   //   default arguments from the definition (if in scope) and all
1268   //   declarations in scope in the same way default function
1269   //   arguments are (8.3.6).
1270   bool SawDefaultArgument = false;
1271   SourceLocation PreviousDefaultArgLoc;
1272 
1273   // Dummy initialization to avoid warnings.
1274   TemplateParameterList::iterator OldParam = NewParams->end();
1275   if (OldParams)
1276     OldParam = OldParams->begin();
1277 
1278   bool RemoveDefaultArguments = false;
1279   for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1280                                     NewParamEnd = NewParams->end();
1281        NewParam != NewParamEnd; ++NewParam) {
1282     // Variables used to diagnose redundant default arguments
1283     bool RedundantDefaultArg = false;
1284     SourceLocation OldDefaultLoc;
1285     SourceLocation NewDefaultLoc;
1286 
1287     // Variable used to diagnose missing default arguments
1288     bool MissingDefaultArg = false;
1289 
1290     // Variable used to diagnose non-final parameter packs
1291     bool SawParameterPack = false;
1292 
1293     if (TemplateTypeParmDecl *NewTypeParm
1294           = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
1295       // Check the presence of a default argument here.
1296       if (NewTypeParm->hasDefaultArgument() &&
1297           DiagnoseDefaultTemplateArgument(*this, TPC,
1298                                           NewTypeParm->getLocation(),
1299                NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1300                                                        .getSourceRange()))
1301         NewTypeParm->removeDefaultArgument();
1302 
1303       // Merge default arguments for template type parameters.
1304       TemplateTypeParmDecl *OldTypeParm
1305           = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
1306 
1307       if (NewTypeParm->isParameterPack()) {
1308         assert(!NewTypeParm->hasDefaultArgument() &&
1309                "Parameter packs can't have a default argument!");
1310         SawParameterPack = true;
1311       } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
1312                  NewTypeParm->hasDefaultArgument()) {
1313         OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1314         NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1315         SawDefaultArgument = true;
1316         RedundantDefaultArg = true;
1317         PreviousDefaultArgLoc = NewDefaultLoc;
1318       } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1319         // Merge the default argument from the old declaration to the
1320         // new declaration.
1321         SawDefaultArgument = true;
1322         NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
1323                                         true);
1324         PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1325       } else if (NewTypeParm->hasDefaultArgument()) {
1326         SawDefaultArgument = true;
1327         PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1328       } else if (SawDefaultArgument)
1329         MissingDefaultArg = true;
1330     } else if (NonTypeTemplateParmDecl *NewNonTypeParm
1331                = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
1332       // Check for unexpanded parameter packs.
1333       if (!NewNonTypeParm->isParameterPack() &&
1334           DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
1335                                           NewNonTypeParm->getTypeSourceInfo(),
1336                                           UPPC_NonTypeTemplateParameterType)) {
1337         Invalid = true;
1338         continue;
1339       }
1340 
1341       // Check the presence of a default argument here.
1342       if (NewNonTypeParm->hasDefaultArgument() &&
1343           DiagnoseDefaultTemplateArgument(*this, TPC,
1344                                           NewNonTypeParm->getLocation(),
1345                     NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1346         NewNonTypeParm->removeDefaultArgument();
1347       }
1348 
1349       // Merge default arguments for non-type template parameters
1350       NonTypeTemplateParmDecl *OldNonTypeParm
1351         = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
1352       if (NewNonTypeParm->isParameterPack()) {
1353         assert(!NewNonTypeParm->hasDefaultArgument() &&
1354                "Parameter packs can't have a default argument!");
1355         if (!NewNonTypeParm->isPackExpansion())
1356           SawParameterPack = true;
1357       } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
1358           NewNonTypeParm->hasDefaultArgument()) {
1359         OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1360         NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1361         SawDefaultArgument = true;
1362         RedundantDefaultArg = true;
1363         PreviousDefaultArgLoc = NewDefaultLoc;
1364       } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1365         // Merge the default argument from the old declaration to the
1366         // new declaration.
1367         SawDefaultArgument = true;
1368         // FIXME: We need to create a new kind of "default argument"
1369         // expression that points to a previous non-type template
1370         // parameter.
1371         NewNonTypeParm->setDefaultArgument(
1372                                          OldNonTypeParm->getDefaultArgument(),
1373                                          /*Inherited=*/ true);
1374         PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1375       } else if (NewNonTypeParm->hasDefaultArgument()) {
1376         SawDefaultArgument = true;
1377         PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1378       } else if (SawDefaultArgument)
1379         MissingDefaultArg = true;
1380     } else {
1381       TemplateTemplateParmDecl *NewTemplateParm
1382         = cast<TemplateTemplateParmDecl>(*NewParam);
1383 
1384       // Check for unexpanded parameter packs, recursively.
1385       if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
1386         Invalid = true;
1387         continue;
1388       }
1389 
1390       // Check the presence of a default argument here.
1391       if (NewTemplateParm->hasDefaultArgument() &&
1392           DiagnoseDefaultTemplateArgument(*this, TPC,
1393                                           NewTemplateParm->getLocation(),
1394                      NewTemplateParm->getDefaultArgument().getSourceRange()))
1395         NewTemplateParm->removeDefaultArgument();
1396 
1397       // Merge default arguments for template template parameters
1398       TemplateTemplateParmDecl *OldTemplateParm
1399         = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
1400       if (NewTemplateParm->isParameterPack()) {
1401         assert(!NewTemplateParm->hasDefaultArgument() &&
1402                "Parameter packs can't have a default argument!");
1403         if (!NewTemplateParm->isPackExpansion())
1404           SawParameterPack = true;
1405       } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
1406           NewTemplateParm->hasDefaultArgument()) {
1407         OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1408         NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
1409         SawDefaultArgument = true;
1410         RedundantDefaultArg = true;
1411         PreviousDefaultArgLoc = NewDefaultLoc;
1412       } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1413         // Merge the default argument from the old declaration to the
1414         // new declaration.
1415         SawDefaultArgument = true;
1416         // FIXME: We need to create a new kind of "default argument" expression
1417         // that points to a previous template template parameter.
1418         NewTemplateParm->setDefaultArgument(
1419                                           OldTemplateParm->getDefaultArgument(),
1420                                           /*Inherited=*/ true);
1421         PreviousDefaultArgLoc
1422           = OldTemplateParm->getDefaultArgument().getLocation();
1423       } else if (NewTemplateParm->hasDefaultArgument()) {
1424         SawDefaultArgument = true;
1425         PreviousDefaultArgLoc
1426           = NewTemplateParm->getDefaultArgument().getLocation();
1427       } else if (SawDefaultArgument)
1428         MissingDefaultArg = true;
1429     }
1430 
1431     // C++11 [temp.param]p11:
1432     //   If a template parameter of a primary class template or alias template
1433     //   is a template parameter pack, it shall be the last template parameter.
1434     if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
1435         (TPC == TPC_ClassTemplate || TPC == TPC_TypeAliasTemplate)) {
1436       Diag((*NewParam)->getLocation(),
1437            diag::err_template_param_pack_must_be_last_template_parameter);
1438       Invalid = true;
1439     }
1440 
1441     if (RedundantDefaultArg) {
1442       // C++ [temp.param]p12:
1443       //   A template-parameter shall not be given default arguments
1444       //   by two different declarations in the same scope.
1445       Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1446       Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1447       Invalid = true;
1448     } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
1449       // C++ [temp.param]p11:
1450       //   If a template-parameter of a class template has a default
1451       //   template-argument, each subsequent template-parameter shall either
1452       //   have a default template-argument supplied or be a template parameter
1453       //   pack.
1454       Diag((*NewParam)->getLocation(),
1455            diag::err_template_param_default_arg_missing);
1456       Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1457       Invalid = true;
1458       RemoveDefaultArguments = true;
1459     }
1460 
1461     // If we have an old template parameter list that we're merging
1462     // in, move on to the next parameter.
1463     if (OldParams)
1464       ++OldParam;
1465   }
1466 
1467   // We were missing some default arguments at the end of the list, so remove
1468   // all of the default arguments.
1469   if (RemoveDefaultArguments) {
1470     for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1471                                       NewParamEnd = NewParams->end();
1472          NewParam != NewParamEnd; ++NewParam) {
1473       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1474         TTP->removeDefaultArgument();
1475       else if (NonTypeTemplateParmDecl *NTTP
1476                                 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1477         NTTP->removeDefaultArgument();
1478       else
1479         cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1480     }
1481   }
1482 
1483   return Invalid;
1484 }
1485 
1486 namespace {
1487 
1488 /// A class which looks for a use of a certain level of template
1489 /// parameter.
1490 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1491   typedef RecursiveASTVisitor<DependencyChecker> super;
1492 
1493   unsigned Depth;
1494   bool Match;
1495 
1496   DependencyChecker(TemplateParameterList *Params) : Match(false) {
1497     NamedDecl *ND = Params->getParam(0);
1498     if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1499       Depth = PD->getDepth();
1500     } else if (NonTypeTemplateParmDecl *PD =
1501                  dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1502       Depth = PD->getDepth();
1503     } else {
1504       Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1505     }
1506   }
1507 
1508   bool Matches(unsigned ParmDepth) {
1509     if (ParmDepth >= Depth) {
1510       Match = true;
1511       return true;
1512     }
1513     return false;
1514   }
1515 
1516   bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1517     return !Matches(T->getDepth());
1518   }
1519 
1520   bool TraverseTemplateName(TemplateName N) {
1521     if (TemplateTemplateParmDecl *PD =
1522           dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1523       if (Matches(PD->getDepth())) return false;
1524     return super::TraverseTemplateName(N);
1525   }
1526 
1527   bool VisitDeclRefExpr(DeclRefExpr *E) {
1528     if (NonTypeTemplateParmDecl *PD =
1529           dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) {
1530       if (PD->getDepth() == Depth) {
1531         Match = true;
1532         return false;
1533       }
1534     }
1535     return super::VisitDeclRefExpr(E);
1536   }
1537 
1538   bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1539     return TraverseType(T->getInjectedSpecializationType());
1540   }
1541 };
1542 }
1543 
1544 /// Determines whether a given type depends on the given parameter
1545 /// list.
1546 static bool
1547 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
1548   DependencyChecker Checker(Params);
1549   Checker.TraverseType(T);
1550   return Checker.Match;
1551 }
1552 
1553 // Find the source range corresponding to the named type in the given
1554 // nested-name-specifier, if any.
1555 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1556                                                        QualType T,
1557                                                        const CXXScopeSpec &SS) {
1558   NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1559   while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1560     if (const Type *CurType = NNS->getAsType()) {
1561       if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1562         return NNSLoc.getTypeLoc().getSourceRange();
1563     } else
1564       break;
1565 
1566     NNSLoc = NNSLoc.getPrefix();
1567   }
1568 
1569   return SourceRange();
1570 }
1571 
1572 /// \brief Match the given template parameter lists to the given scope
1573 /// specifier, returning the template parameter list that applies to the
1574 /// name.
1575 ///
1576 /// \param DeclStartLoc the start of the declaration that has a scope
1577 /// specifier or a template parameter list.
1578 ///
1579 /// \param DeclLoc The location of the declaration itself.
1580 ///
1581 /// \param SS the scope specifier that will be matched to the given template
1582 /// parameter lists. This scope specifier precedes a qualified name that is
1583 /// being declared.
1584 ///
1585 /// \param ParamLists the template parameter lists, from the outermost to the
1586 /// innermost template parameter lists.
1587 ///
1588 /// \param NumParamLists the number of template parameter lists in ParamLists.
1589 ///
1590 /// \param IsFriend Whether to apply the slightly different rules for
1591 /// matching template parameters to scope specifiers in friend
1592 /// declarations.
1593 ///
1594 /// \param IsExplicitSpecialization will be set true if the entity being
1595 /// declared is an explicit specialization, false otherwise.
1596 ///
1597 /// \returns the template parameter list, if any, that corresponds to the
1598 /// name that is preceded by the scope specifier @p SS. This template
1599 /// parameter list may have template parameters (if we're declaring a
1600 /// template) or may have no template parameters (if we're declaring a
1601 /// template specialization), or may be NULL (if what we're declaring isn't
1602 /// itself a template).
1603 TemplateParameterList *
1604 Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1605                                               SourceLocation DeclLoc,
1606                                               const CXXScopeSpec &SS,
1607                                           TemplateParameterList **ParamLists,
1608                                               unsigned NumParamLists,
1609                                               bool IsFriend,
1610                                               bool &IsExplicitSpecialization,
1611                                               bool &Invalid) {
1612   IsExplicitSpecialization = false;
1613   Invalid = false;
1614 
1615   // The sequence of nested types to which we will match up the template
1616   // parameter lists. We first build this list by starting with the type named
1617   // by the nested-name-specifier and walking out until we run out of types.
1618   SmallVector<QualType, 4> NestedTypes;
1619   QualType T;
1620   if (SS.getScopeRep()) {
1621     if (CXXRecordDecl *Record
1622               = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1623       T = Context.getTypeDeclType(Record);
1624     else
1625       T = QualType(SS.getScopeRep()->getAsType(), 0);
1626   }
1627 
1628   // If we found an explicit specialization that prevents us from needing
1629   // 'template<>' headers, this will be set to the location of that
1630   // explicit specialization.
1631   SourceLocation ExplicitSpecLoc;
1632 
1633   while (!T.isNull()) {
1634     NestedTypes.push_back(T);
1635 
1636     // Retrieve the parent of a record type.
1637     if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1638       // If this type is an explicit specialization, we're done.
1639       if (ClassTemplateSpecializationDecl *Spec
1640           = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1641         if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1642             Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1643           ExplicitSpecLoc = Spec->getLocation();
1644           break;
1645         }
1646       } else if (Record->getTemplateSpecializationKind()
1647                                                 == TSK_ExplicitSpecialization) {
1648         ExplicitSpecLoc = Record->getLocation();
1649         break;
1650       }
1651 
1652       if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1653         T = Context.getTypeDeclType(Parent);
1654       else
1655         T = QualType();
1656       continue;
1657     }
1658 
1659     if (const TemplateSpecializationType *TST
1660                                      = T->getAs<TemplateSpecializationType>()) {
1661       if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1662         if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1663           T = Context.getTypeDeclType(Parent);
1664         else
1665           T = QualType();
1666         continue;
1667       }
1668     }
1669 
1670     // Look one step prior in a dependent template specialization type.
1671     if (const DependentTemplateSpecializationType *DependentTST
1672                           = T->getAs<DependentTemplateSpecializationType>()) {
1673       if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1674         T = QualType(NNS->getAsType(), 0);
1675       else
1676         T = QualType();
1677       continue;
1678     }
1679 
1680     // Look one step prior in a dependent name type.
1681     if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1682       if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1683         T = QualType(NNS->getAsType(), 0);
1684       else
1685         T = QualType();
1686       continue;
1687     }
1688 
1689     // Retrieve the parent of an enumeration type.
1690     if (const EnumType *EnumT = T->getAs<EnumType>()) {
1691       // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1692       // check here.
1693       EnumDecl *Enum = EnumT->getDecl();
1694 
1695       // Get to the parent type.
1696       if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1697         T = Context.getTypeDeclType(Parent);
1698       else
1699         T = QualType();
1700       continue;
1701     }
1702 
1703     T = QualType();
1704   }
1705   // Reverse the nested types list, since we want to traverse from the outermost
1706   // to the innermost while checking template-parameter-lists.
1707   std::reverse(NestedTypes.begin(), NestedTypes.end());
1708 
1709   // C++0x [temp.expl.spec]p17:
1710   //   A member or a member template may be nested within many
1711   //   enclosing class templates. In an explicit specialization for
1712   //   such a member, the member declaration shall be preceded by a
1713   //   template<> for each enclosing class template that is
1714   //   explicitly specialized.
1715   bool SawNonEmptyTemplateParameterList = false;
1716   unsigned ParamIdx = 0;
1717   for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1718        ++TypeIdx) {
1719     T = NestedTypes[TypeIdx];
1720 
1721     // Whether we expect a 'template<>' header.
1722     bool NeedEmptyTemplateHeader = false;
1723 
1724     // Whether we expect a template header with parameters.
1725     bool NeedNonemptyTemplateHeader = false;
1726 
1727     // For a dependent type, the set of template parameters that we
1728     // expect to see.
1729     TemplateParameterList *ExpectedTemplateParams = 0;
1730 
1731     // C++0x [temp.expl.spec]p15:
1732     //   A member or a member template may be nested within many enclosing
1733     //   class templates. In an explicit specialization for such a member, the
1734     //   member declaration shall be preceded by a template<> for each
1735     //   enclosing class template that is explicitly specialized.
1736     if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1737       if (ClassTemplatePartialSpecializationDecl *Partial
1738             = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1739         ExpectedTemplateParams = Partial->getTemplateParameters();
1740         NeedNonemptyTemplateHeader = true;
1741       } else if (Record->isDependentType()) {
1742         if (Record->getDescribedClassTemplate()) {
1743           ExpectedTemplateParams = Record->getDescribedClassTemplate()
1744                                                       ->getTemplateParameters();
1745           NeedNonemptyTemplateHeader = true;
1746         }
1747       } else if (ClassTemplateSpecializationDecl *Spec
1748                      = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1749         // C++0x [temp.expl.spec]p4:
1750         //   Members of an explicitly specialized class template are defined
1751         //   in the same manner as members of normal classes, and not using
1752         //   the template<> syntax.
1753         if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1754           NeedEmptyTemplateHeader = true;
1755         else
1756           continue;
1757       } else if (Record->getTemplateSpecializationKind()) {
1758         if (Record->getTemplateSpecializationKind()
1759                                                 != TSK_ExplicitSpecialization &&
1760             TypeIdx == NumTypes - 1)
1761           IsExplicitSpecialization = true;
1762 
1763         continue;
1764       }
1765     } else if (const TemplateSpecializationType *TST
1766                                      = T->getAs<TemplateSpecializationType>()) {
1767       if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1768         ExpectedTemplateParams = Template->getTemplateParameters();
1769         NeedNonemptyTemplateHeader = true;
1770       }
1771     } else if (T->getAs<DependentTemplateSpecializationType>()) {
1772       // FIXME:  We actually could/should check the template arguments here
1773       // against the corresponding template parameter list.
1774       NeedNonemptyTemplateHeader = false;
1775     }
1776 
1777     // C++ [temp.expl.spec]p16:
1778     //   In an explicit specialization declaration for a member of a class
1779     //   template or a member template that ap- pears in namespace scope, the
1780     //   member template and some of its enclosing class templates may remain
1781     //   unspecialized, except that the declaration shall not explicitly
1782     //   specialize a class member template if its en- closing class templates
1783     //   are not explicitly specialized as well.
1784     if (ParamIdx < NumParamLists) {
1785       if (ParamLists[ParamIdx]->size() == 0) {
1786         if (SawNonEmptyTemplateParameterList) {
1787           Diag(DeclLoc, diag::err_specialize_member_of_template)
1788             << ParamLists[ParamIdx]->getSourceRange();
1789           Invalid = true;
1790           IsExplicitSpecialization = false;
1791           return 0;
1792         }
1793       } else
1794         SawNonEmptyTemplateParameterList = true;
1795     }
1796 
1797     if (NeedEmptyTemplateHeader) {
1798       // If we're on the last of the types, and we need a 'template<>' header
1799       // here, then it's an explicit specialization.
1800       if (TypeIdx == NumTypes - 1)
1801         IsExplicitSpecialization = true;
1802 
1803       if (ParamIdx < NumParamLists) {
1804         if (ParamLists[ParamIdx]->size() > 0) {
1805           // The header has template parameters when it shouldn't. Complain.
1806           Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1807                diag::err_template_param_list_matches_nontemplate)
1808             << T
1809             << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1810                            ParamLists[ParamIdx]->getRAngleLoc())
1811             << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1812           Invalid = true;
1813           return 0;
1814         }
1815 
1816         // Consume this template header.
1817         ++ParamIdx;
1818         continue;
1819       }
1820 
1821       if (!IsFriend) {
1822         // We don't have a template header, but we should.
1823         SourceLocation ExpectedTemplateLoc;
1824         if (NumParamLists > 0)
1825           ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1826         else
1827           ExpectedTemplateLoc = DeclStartLoc;
1828 
1829         Diag(DeclLoc, diag::err_template_spec_needs_header)
1830           << getRangeOfTypeInNestedNameSpecifier(Context, T, SS)
1831           << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1832       }
1833 
1834       continue;
1835     }
1836 
1837     if (NeedNonemptyTemplateHeader) {
1838       // In friend declarations we can have template-ids which don't
1839       // depend on the corresponding template parameter lists.  But
1840       // assume that empty parameter lists are supposed to match this
1841       // template-id.
1842       if (IsFriend && T->isDependentType()) {
1843         if (ParamIdx < NumParamLists &&
1844             DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
1845           ExpectedTemplateParams = 0;
1846         else
1847           continue;
1848       }
1849 
1850       if (ParamIdx < NumParamLists) {
1851         // Check the template parameter list, if we can.
1852         if (ExpectedTemplateParams &&
1853             !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1854                                             ExpectedTemplateParams,
1855                                             true, TPL_TemplateMatch))
1856           Invalid = true;
1857 
1858         if (!Invalid &&
1859             CheckTemplateParameterList(ParamLists[ParamIdx], 0,
1860                                        TPC_ClassTemplateMember))
1861           Invalid = true;
1862 
1863         ++ParamIdx;
1864         continue;
1865       }
1866 
1867       Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1868         << T
1869         << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1870       Invalid = true;
1871       continue;
1872     }
1873   }
1874 
1875   // If there were at least as many template-ids as there were template
1876   // parameter lists, then there are no template parameter lists remaining for
1877   // the declaration itself.
1878   if (ParamIdx >= NumParamLists)
1879     return 0;
1880 
1881   // If there were too many template parameter lists, complain about that now.
1882   if (ParamIdx < NumParamLists - 1) {
1883     bool HasAnyExplicitSpecHeader = false;
1884     bool AllExplicitSpecHeaders = true;
1885     for (unsigned I = ParamIdx; I != NumParamLists - 1; ++I) {
1886       if (ParamLists[I]->size() == 0)
1887         HasAnyExplicitSpecHeader = true;
1888       else
1889         AllExplicitSpecHeaders = false;
1890     }
1891 
1892     Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1893          AllExplicitSpecHeaders? diag::warn_template_spec_extra_headers
1894                                : diag::err_template_spec_extra_headers)
1895       << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1896                      ParamLists[NumParamLists - 2]->getRAngleLoc());
1897 
1898     // If there was a specialization somewhere, such that 'template<>' is
1899     // not required, and there were any 'template<>' headers, note where the
1900     // specialization occurred.
1901     if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1902       Diag(ExplicitSpecLoc,
1903            diag::note_explicit_template_spec_does_not_need_header)
1904         << NestedTypes.back();
1905 
1906     // We have a template parameter list with no corresponding scope, which
1907     // means that the resulting template declaration can't be instantiated
1908     // properly (we'll end up with dependent nodes when we shouldn't).
1909     if (!AllExplicitSpecHeaders)
1910       Invalid = true;
1911   }
1912 
1913   // C++ [temp.expl.spec]p16:
1914   //   In an explicit specialization declaration for a member of a class
1915   //   template or a member template that ap- pears in namespace scope, the
1916   //   member template and some of its enclosing class templates may remain
1917   //   unspecialized, except that the declaration shall not explicitly
1918   //   specialize a class member template if its en- closing class templates
1919   //   are not explicitly specialized as well.
1920   if (ParamLists[NumParamLists - 1]->size() == 0 &&
1921       SawNonEmptyTemplateParameterList) {
1922     Diag(DeclLoc, diag::err_specialize_member_of_template)
1923       << ParamLists[ParamIdx]->getSourceRange();
1924     Invalid = true;
1925     IsExplicitSpecialization = false;
1926     return 0;
1927   }
1928 
1929   // Return the last template parameter list, which corresponds to the
1930   // entity being declared.
1931   return ParamLists[NumParamLists - 1];
1932 }
1933 
1934 void Sema::NoteAllFoundTemplates(TemplateName Name) {
1935   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
1936     Diag(Template->getLocation(), diag::note_template_declared_here)
1937       << (isa<FunctionTemplateDecl>(Template)? 0
1938           : isa<ClassTemplateDecl>(Template)? 1
1939           : isa<TypeAliasTemplateDecl>(Template)? 2
1940           : 3)
1941       << Template->getDeclName();
1942     return;
1943   }
1944 
1945   if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
1946     for (OverloadedTemplateStorage::iterator I = OST->begin(),
1947                                           IEnd = OST->end();
1948          I != IEnd; ++I)
1949       Diag((*I)->getLocation(), diag::note_template_declared_here)
1950         << 0 << (*I)->getDeclName();
1951 
1952     return;
1953   }
1954 }
1955 
1956 QualType Sema::CheckTemplateIdType(TemplateName Name,
1957                                    SourceLocation TemplateLoc,
1958                                    TemplateArgumentListInfo &TemplateArgs) {
1959   DependentTemplateName *DTN
1960     = Name.getUnderlying().getAsDependentTemplateName();
1961   if (DTN && DTN->isIdentifier())
1962     // When building a template-id where the template-name is dependent,
1963     // assume the template is a type template. Either our assumption is
1964     // correct, or the code is ill-formed and will be diagnosed when the
1965     // dependent name is substituted.
1966     return Context.getDependentTemplateSpecializationType(ETK_None,
1967                                                           DTN->getQualifier(),
1968                                                           DTN->getIdentifier(),
1969                                                           TemplateArgs);
1970 
1971   TemplateDecl *Template = Name.getAsTemplateDecl();
1972   if (!Template || isa<FunctionTemplateDecl>(Template)) {
1973     // We might have a substituted template template parameter pack. If so,
1974     // build a template specialization type for it.
1975     if (Name.getAsSubstTemplateTemplateParmPack())
1976       return Context.getTemplateSpecializationType(Name, TemplateArgs);
1977 
1978     Diag(TemplateLoc, diag::err_template_id_not_a_type)
1979       << Name;
1980     NoteAllFoundTemplates(Name);
1981     return QualType();
1982   }
1983 
1984   // Check that the template argument list is well-formed for this
1985   // template.
1986   SmallVector<TemplateArgument, 4> Converted;
1987   bool ExpansionIntoFixedList = false;
1988   if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
1989                                 false, Converted, &ExpansionIntoFixedList))
1990     return QualType();
1991 
1992   QualType CanonType;
1993 
1994   bool InstantiationDependent = false;
1995   TypeAliasTemplateDecl *AliasTemplate = 0;
1996   if (!ExpansionIntoFixedList &&
1997       (AliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Template))) {
1998     // Find the canonical type for this type alias template specialization.
1999     TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2000     if (Pattern->isInvalidDecl())
2001       return QualType();
2002 
2003     TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2004                                       Converted.data(), Converted.size());
2005 
2006     // Only substitute for the innermost template argument list.
2007     MultiLevelTemplateArgumentList TemplateArgLists;
2008     TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
2009     unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2010     for (unsigned I = 0; I < Depth; ++I)
2011       TemplateArgLists.addOuterTemplateArguments(None);
2012 
2013     LocalInstantiationScope Scope(*this);
2014     InstantiatingTemplate Inst(*this, TemplateLoc, Template);
2015     if (Inst)
2016       return QualType();
2017 
2018     CanonType = SubstType(Pattern->getUnderlyingType(),
2019                           TemplateArgLists, AliasTemplate->getLocation(),
2020                           AliasTemplate->getDeclName());
2021     if (CanonType.isNull())
2022       return QualType();
2023   } else if (Name.isDependent() ||
2024              TemplateSpecializationType::anyDependentTemplateArguments(
2025                TemplateArgs, InstantiationDependent)) {
2026     // This class template specialization is a dependent
2027     // type. Therefore, its canonical type is another class template
2028     // specialization type that contains all of the converted
2029     // arguments in canonical form. This ensures that, e.g., A<T> and
2030     // A<T, T> have identical types when A is declared as:
2031     //
2032     //   template<typename T, typename U = T> struct A;
2033     TemplateName CanonName = Context.getCanonicalTemplateName(Name);
2034     CanonType = Context.getTemplateSpecializationType(CanonName,
2035                                                       Converted.data(),
2036                                                       Converted.size());
2037 
2038     // FIXME: CanonType is not actually the canonical type, and unfortunately
2039     // it is a TemplateSpecializationType that we will never use again.
2040     // In the future, we need to teach getTemplateSpecializationType to only
2041     // build the canonical type and return that to us.
2042     CanonType = Context.getCanonicalType(CanonType);
2043 
2044     // This might work out to be a current instantiation, in which
2045     // case the canonical type needs to be the InjectedClassNameType.
2046     //
2047     // TODO: in theory this could be a simple hashtable lookup; most
2048     // changes to CurContext don't change the set of current
2049     // instantiations.
2050     if (isa<ClassTemplateDecl>(Template)) {
2051       for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2052         // If we get out to a namespace, we're done.
2053         if (Ctx->isFileContext()) break;
2054 
2055         // If this isn't a record, keep looking.
2056         CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2057         if (!Record) continue;
2058 
2059         // Look for one of the two cases with InjectedClassNameTypes
2060         // and check whether it's the same template.
2061         if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2062             !Record->getDescribedClassTemplate())
2063           continue;
2064 
2065         // Fetch the injected class name type and check whether its
2066         // injected type is equal to the type we just built.
2067         QualType ICNT = Context.getTypeDeclType(Record);
2068         QualType Injected = cast<InjectedClassNameType>(ICNT)
2069           ->getInjectedSpecializationType();
2070 
2071         if (CanonType != Injected->getCanonicalTypeInternal())
2072           continue;
2073 
2074         // If so, the canonical type of this TST is the injected
2075         // class name type of the record we just found.
2076         assert(ICNT.isCanonical());
2077         CanonType = ICNT;
2078         break;
2079       }
2080     }
2081   } else if (ClassTemplateDecl *ClassTemplate
2082                = dyn_cast<ClassTemplateDecl>(Template)) {
2083     // Find the class template specialization declaration that
2084     // corresponds to these arguments.
2085     void *InsertPos = 0;
2086     ClassTemplateSpecializationDecl *Decl
2087       = ClassTemplate->findSpecialization(Converted.data(), Converted.size(),
2088                                           InsertPos);
2089     if (!Decl) {
2090       // This is the first time we have referenced this class template
2091       // specialization. Create the canonical declaration and add it to
2092       // the set of specializations.
2093       Decl = ClassTemplateSpecializationDecl::Create(Context,
2094                             ClassTemplate->getTemplatedDecl()->getTagKind(),
2095                                                 ClassTemplate->getDeclContext(),
2096                             ClassTemplate->getTemplatedDecl()->getLocStart(),
2097                                                 ClassTemplate->getLocation(),
2098                                                      ClassTemplate,
2099                                                      Converted.data(),
2100                                                      Converted.size(), 0);
2101       ClassTemplate->AddSpecialization(Decl, InsertPos);
2102       if (ClassTemplate->isOutOfLine())
2103         Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
2104     }
2105 
2106     CanonType = Context.getTypeDeclType(Decl);
2107     assert(isa<RecordType>(CanonType) &&
2108            "type of non-dependent specialization is not a RecordType");
2109   }
2110 
2111   // Build the fully-sugared type for this class template
2112   // specialization, which refers back to the class template
2113   // specialization we created or found.
2114   return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
2115 }
2116 
2117 TypeResult
2118 Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
2119                           TemplateTy TemplateD, SourceLocation TemplateLoc,
2120                           SourceLocation LAngleLoc,
2121                           ASTTemplateArgsPtr TemplateArgsIn,
2122                           SourceLocation RAngleLoc,
2123                           bool IsCtorOrDtorName) {
2124   if (SS.isInvalid())
2125     return true;
2126 
2127   TemplateName Template = TemplateD.getAsVal<TemplateName>();
2128 
2129   // Translate the parser's template argument list in our AST format.
2130   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2131   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2132 
2133   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2134     QualType T
2135       = Context.getDependentTemplateSpecializationType(ETK_None,
2136                                                        DTN->getQualifier(),
2137                                                        DTN->getIdentifier(),
2138                                                        TemplateArgs);
2139     // Build type-source information.
2140     TypeLocBuilder TLB;
2141     DependentTemplateSpecializationTypeLoc SpecTL
2142       = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2143     SpecTL.setElaboratedKeywordLoc(SourceLocation());
2144     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2145     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2146     SpecTL.setTemplateNameLoc(TemplateLoc);
2147     SpecTL.setLAngleLoc(LAngleLoc);
2148     SpecTL.setRAngleLoc(RAngleLoc);
2149     for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2150       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2151     return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2152   }
2153 
2154   QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2155 
2156   if (Result.isNull())
2157     return true;
2158 
2159   // Build type-source information.
2160   TypeLocBuilder TLB;
2161   TemplateSpecializationTypeLoc SpecTL
2162     = TLB.push<TemplateSpecializationTypeLoc>(Result);
2163   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2164   SpecTL.setTemplateNameLoc(TemplateLoc);
2165   SpecTL.setLAngleLoc(LAngleLoc);
2166   SpecTL.setRAngleLoc(RAngleLoc);
2167   for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2168     SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2169 
2170   // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2171   // constructor or destructor name (in such a case, the scope specifier
2172   // will be attached to the enclosing Decl or Expr node).
2173   if (SS.isNotEmpty() && !IsCtorOrDtorName) {
2174     // Create an elaborated-type-specifier containing the nested-name-specifier.
2175     Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2176     ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2177     ElabTL.setElaboratedKeywordLoc(SourceLocation());
2178     ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2179   }
2180 
2181   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2182 }
2183 
2184 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
2185                                         TypeSpecifierType TagSpec,
2186                                         SourceLocation TagLoc,
2187                                         CXXScopeSpec &SS,
2188                                         SourceLocation TemplateKWLoc,
2189                                         TemplateTy TemplateD,
2190                                         SourceLocation TemplateLoc,
2191                                         SourceLocation LAngleLoc,
2192                                         ASTTemplateArgsPtr TemplateArgsIn,
2193                                         SourceLocation RAngleLoc) {
2194   TemplateName Template = TemplateD.getAsVal<TemplateName>();
2195 
2196   // Translate the parser's template argument list in our AST format.
2197   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2198   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2199 
2200   // Determine the tag kind
2201   TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
2202   ElaboratedTypeKeyword Keyword
2203     = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
2204 
2205   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2206     QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2207                                                           DTN->getQualifier(),
2208                                                           DTN->getIdentifier(),
2209                                                                 TemplateArgs);
2210 
2211     // Build type-source information.
2212     TypeLocBuilder TLB;
2213     DependentTemplateSpecializationTypeLoc SpecTL
2214       = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2215     SpecTL.setElaboratedKeywordLoc(TagLoc);
2216     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2217     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2218     SpecTL.setTemplateNameLoc(TemplateLoc);
2219     SpecTL.setLAngleLoc(LAngleLoc);
2220     SpecTL.setRAngleLoc(RAngleLoc);
2221     for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2222       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2223     return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2224   }
2225 
2226   if (TypeAliasTemplateDecl *TAT =
2227         dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2228     // C++0x [dcl.type.elab]p2:
2229     //   If the identifier resolves to a typedef-name or the simple-template-id
2230     //   resolves to an alias template specialization, the
2231     //   elaborated-type-specifier is ill-formed.
2232     Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2233     Diag(TAT->getLocation(), diag::note_declared_at);
2234   }
2235 
2236   QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2237   if (Result.isNull())
2238     return TypeResult(true);
2239 
2240   // Check the tag kind
2241   if (const RecordType *RT = Result->getAs<RecordType>()) {
2242     RecordDecl *D = RT->getDecl();
2243 
2244     IdentifierInfo *Id = D->getIdentifier();
2245     assert(Id && "templated class must have an identifier");
2246 
2247     if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
2248                                       TagLoc, *Id)) {
2249       Diag(TagLoc, diag::err_use_with_wrong_tag)
2250         << Result
2251         << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
2252       Diag(D->getLocation(), diag::note_previous_use);
2253     }
2254   }
2255 
2256   // Provide source-location information for the template specialization.
2257   TypeLocBuilder TLB;
2258   TemplateSpecializationTypeLoc SpecTL
2259     = TLB.push<TemplateSpecializationTypeLoc>(Result);
2260   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2261   SpecTL.setTemplateNameLoc(TemplateLoc);
2262   SpecTL.setLAngleLoc(LAngleLoc);
2263   SpecTL.setRAngleLoc(RAngleLoc);
2264   for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2265     SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2266 
2267   // Construct an elaborated type containing the nested-name-specifier (if any)
2268   // and tag keyword.
2269   Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2270   ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2271   ElabTL.setElaboratedKeywordLoc(TagLoc);
2272   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2273   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2274 }
2275 
2276 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
2277                                      SourceLocation TemplateKWLoc,
2278                                      LookupResult &R,
2279                                      bool RequiresADL,
2280                                  const TemplateArgumentListInfo *TemplateArgs) {
2281   // FIXME: Can we do any checking at this point? I guess we could check the
2282   // template arguments that we have against the template name, if the template
2283   // name refers to a single template. That's not a terribly common case,
2284   // though.
2285   // foo<int> could identify a single function unambiguously
2286   // This approach does NOT work, since f<int>(1);
2287   // gets resolved prior to resorting to overload resolution
2288   // i.e., template<class T> void f(double);
2289   //       vs template<class T, class U> void f(U);
2290 
2291   // These should be filtered out by our callers.
2292   assert(!R.empty() && "empty lookup results when building templateid");
2293   assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2294 
2295   // We don't want lookup warnings at this point.
2296   R.suppressDiagnostics();
2297 
2298   UnresolvedLookupExpr *ULE
2299     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2300                                    SS.getWithLocInContext(Context),
2301                                    TemplateKWLoc,
2302                                    R.getLookupNameInfo(),
2303                                    RequiresADL, TemplateArgs,
2304                                    R.begin(), R.end());
2305 
2306   return Owned(ULE);
2307 }
2308 
2309 // We actually only call this from template instantiation.
2310 ExprResult
2311 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
2312                                    SourceLocation TemplateKWLoc,
2313                                    const DeclarationNameInfo &NameInfo,
2314                              const TemplateArgumentListInfo *TemplateArgs) {
2315   assert(TemplateArgs || TemplateKWLoc.isValid());
2316   DeclContext *DC;
2317   if (!(DC = computeDeclContext(SS, false)) ||
2318       DC->isDependentContext() ||
2319       RequireCompleteDeclContext(SS, DC))
2320     return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
2321 
2322   bool MemberOfUnknownSpecialization;
2323   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2324   LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
2325                      MemberOfUnknownSpecialization);
2326 
2327   if (R.isAmbiguous())
2328     return ExprError();
2329 
2330   if (R.empty()) {
2331     Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2332       << NameInfo.getName() << SS.getRange();
2333     return ExprError();
2334   }
2335 
2336   if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
2337     Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
2338       << (NestedNameSpecifier*) SS.getScopeRep()
2339       << NameInfo.getName() << SS.getRange();
2340     Diag(Temp->getLocation(), diag::note_referenced_class_template);
2341     return ExprError();
2342   }
2343 
2344   return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
2345 }
2346 
2347 /// \brief Form a dependent template name.
2348 ///
2349 /// This action forms a dependent template name given the template
2350 /// name and its (presumably dependent) scope specifier. For
2351 /// example, given "MetaFun::template apply", the scope specifier \p
2352 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2353 /// of the "template" keyword, and "apply" is the \p Name.
2354 TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
2355                                                   CXXScopeSpec &SS,
2356                                                   SourceLocation TemplateKWLoc,
2357                                                   UnqualifiedId &Name,
2358                                                   ParsedType ObjectType,
2359                                                   bool EnteringContext,
2360                                                   TemplateTy &Result) {
2361   if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
2362     Diag(TemplateKWLoc,
2363          getLangOpts().CPlusPlus11 ?
2364            diag::warn_cxx98_compat_template_outside_of_template :
2365            diag::ext_template_outside_of_template)
2366       << FixItHint::CreateRemoval(TemplateKWLoc);
2367 
2368   DeclContext *LookupCtx = 0;
2369   if (SS.isSet())
2370     LookupCtx = computeDeclContext(SS, EnteringContext);
2371   if (!LookupCtx && ObjectType)
2372     LookupCtx = computeDeclContext(ObjectType.get());
2373   if (LookupCtx) {
2374     // C++0x [temp.names]p5:
2375     //   If a name prefixed by the keyword template is not the name of
2376     //   a template, the program is ill-formed. [Note: the keyword
2377     //   template may not be applied to non-template members of class
2378     //   templates. -end note ] [ Note: as is the case with the
2379     //   typename prefix, the template prefix is allowed in cases
2380     //   where it is not strictly necessary; i.e., when the
2381     //   nested-name-specifier or the expression on the left of the ->
2382     //   or . is not dependent on a template-parameter, or the use
2383     //   does not appear in the scope of a template. -end note]
2384     //
2385     // Note: C++03 was more strict here, because it banned the use of
2386     // the "template" keyword prior to a template-name that was not a
2387     // dependent name. C++ DR468 relaxed this requirement (the
2388     // "template" keyword is now permitted). We follow the C++0x
2389     // rules, even in C++03 mode with a warning, retroactively applying the DR.
2390     bool MemberOfUnknownSpecialization;
2391     TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
2392                                           ObjectType, EnteringContext, Result,
2393                                           MemberOfUnknownSpecialization);
2394     if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
2395         isa<CXXRecordDecl>(LookupCtx) &&
2396         (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
2397          cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
2398       // This is a dependent template. Handle it below.
2399     } else if (TNK == TNK_Non_template) {
2400       Diag(Name.getLocStart(),
2401            diag::err_template_kw_refers_to_non_template)
2402         << GetNameFromUnqualifiedId(Name).getName()
2403         << Name.getSourceRange()
2404         << TemplateKWLoc;
2405       return TNK_Non_template;
2406     } else {
2407       // We found something; return it.
2408       return TNK;
2409     }
2410   }
2411 
2412   NestedNameSpecifier *Qualifier
2413     = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2414 
2415   switch (Name.getKind()) {
2416   case UnqualifiedId::IK_Identifier:
2417     Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
2418                                                               Name.Identifier));
2419     return TNK_Dependent_template_name;
2420 
2421   case UnqualifiedId::IK_OperatorFunctionId:
2422     Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
2423                                              Name.OperatorFunctionId.Operator));
2424     return TNK_Dependent_template_name;
2425 
2426   case UnqualifiedId::IK_LiteralOperatorId:
2427     llvm_unreachable(
2428             "We don't support these; Parse shouldn't have allowed propagation");
2429 
2430   default:
2431     break;
2432   }
2433 
2434   Diag(Name.getLocStart(),
2435        diag::err_template_kw_refers_to_non_template)
2436     << GetNameFromUnqualifiedId(Name).getName()
2437     << Name.getSourceRange()
2438     << TemplateKWLoc;
2439   return TNK_Non_template;
2440 }
2441 
2442 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
2443                                      const TemplateArgumentLoc &AL,
2444                           SmallVectorImpl<TemplateArgument> &Converted) {
2445   const TemplateArgument &Arg = AL.getArgument();
2446 
2447   // Check template type parameter.
2448   switch(Arg.getKind()) {
2449   case TemplateArgument::Type:
2450     // C++ [temp.arg.type]p1:
2451     //   A template-argument for a template-parameter which is a
2452     //   type shall be a type-id.
2453     break;
2454   case TemplateArgument::Template: {
2455     // We have a template type parameter but the template argument
2456     // is a template without any arguments.
2457     SourceRange SR = AL.getSourceRange();
2458     TemplateName Name = Arg.getAsTemplate();
2459     Diag(SR.getBegin(), diag::err_template_missing_args)
2460       << Name << SR;
2461     if (TemplateDecl *Decl = Name.getAsTemplateDecl())
2462       Diag(Decl->getLocation(), diag::note_template_decl_here);
2463 
2464     return true;
2465   }
2466   case TemplateArgument::Expression: {
2467     // We have a template type parameter but the template argument is an
2468     // expression; see if maybe it is missing the "typename" keyword.
2469     CXXScopeSpec SS;
2470     DeclarationNameInfo NameInfo;
2471 
2472     if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
2473       SS.Adopt(ArgExpr->getQualifierLoc());
2474       NameInfo = ArgExpr->getNameInfo();
2475     } else if (DependentScopeDeclRefExpr *ArgExpr =
2476                dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
2477       SS.Adopt(ArgExpr->getQualifierLoc());
2478       NameInfo = ArgExpr->getNameInfo();
2479     } else if (CXXDependentScopeMemberExpr *ArgExpr =
2480                dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
2481       if (ArgExpr->isImplicitAccess()) {
2482         SS.Adopt(ArgExpr->getQualifierLoc());
2483         NameInfo = ArgExpr->getMemberNameInfo();
2484       }
2485     }
2486 
2487     if (NameInfo.getName().isIdentifier()) {
2488       LookupResult Result(*this, NameInfo, LookupOrdinaryName);
2489       LookupParsedName(Result, CurScope, &SS);
2490 
2491       if (Result.getAsSingle<TypeDecl>() ||
2492           Result.getResultKind() ==
2493             LookupResult::NotFoundInCurrentInstantiation) {
2494         // FIXME: Add a FixIt and fix up the template argument for recovery.
2495         SourceLocation Loc = AL.getSourceRange().getBegin();
2496         Diag(Loc, diag::err_template_arg_must_be_type_suggest);
2497         Diag(Param->getLocation(), diag::note_template_param_here);
2498         return true;
2499       }
2500     }
2501     // fallthrough
2502   }
2503   default: {
2504     // We have a template type parameter but the template argument
2505     // is not a type.
2506     SourceRange SR = AL.getSourceRange();
2507     Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
2508     Diag(Param->getLocation(), diag::note_template_param_here);
2509 
2510     return true;
2511   }
2512   }
2513 
2514   if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
2515     return true;
2516 
2517   // Add the converted template type argument.
2518   QualType ArgType = Context.getCanonicalType(Arg.getAsType());
2519 
2520   // Objective-C ARC:
2521   //   If an explicitly-specified template argument type is a lifetime type
2522   //   with no lifetime qualifier, the __strong lifetime qualifier is inferred.
2523   if (getLangOpts().ObjCAutoRefCount &&
2524       ArgType->isObjCLifetimeType() &&
2525       !ArgType.getObjCLifetime()) {
2526     Qualifiers Qs;
2527     Qs.setObjCLifetime(Qualifiers::OCL_Strong);
2528     ArgType = Context.getQualifiedType(ArgType, Qs);
2529   }
2530 
2531   Converted.push_back(TemplateArgument(ArgType));
2532   return false;
2533 }
2534 
2535 /// \brief Substitute template arguments into the default template argument for
2536 /// the given template type parameter.
2537 ///
2538 /// \param SemaRef the semantic analysis object for which we are performing
2539 /// the substitution.
2540 ///
2541 /// \param Template the template that we are synthesizing template arguments
2542 /// for.
2543 ///
2544 /// \param TemplateLoc the location of the template name that started the
2545 /// template-id we are checking.
2546 ///
2547 /// \param RAngleLoc the location of the right angle bracket ('>') that
2548 /// terminates the template-id.
2549 ///
2550 /// \param Param the template template parameter whose default we are
2551 /// substituting into.
2552 ///
2553 /// \param Converted the list of template arguments provided for template
2554 /// parameters that precede \p Param in the template parameter list.
2555 /// \returns the substituted template argument, or NULL if an error occurred.
2556 static TypeSourceInfo *
2557 SubstDefaultTemplateArgument(Sema &SemaRef,
2558                              TemplateDecl *Template,
2559                              SourceLocation TemplateLoc,
2560                              SourceLocation RAngleLoc,
2561                              TemplateTypeParmDecl *Param,
2562                          SmallVectorImpl<TemplateArgument> &Converted) {
2563   TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
2564 
2565   // If the argument type is dependent, instantiate it now based
2566   // on the previously-computed template arguments.
2567   if (ArgType->getType()->isDependentType()) {
2568     TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2569                                       Converted.data(), Converted.size());
2570 
2571     MultiLevelTemplateArgumentList AllTemplateArgs
2572       = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2573 
2574     Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
2575                                      Template, Converted,
2576                                      SourceRange(TemplateLoc, RAngleLoc));
2577     if (Inst)
2578       return 0;
2579 
2580     Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
2581     ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
2582                                 Param->getDefaultArgumentLoc(),
2583                                 Param->getDeclName());
2584   }
2585 
2586   return ArgType;
2587 }
2588 
2589 /// \brief Substitute template arguments into the default template argument for
2590 /// the given non-type template parameter.
2591 ///
2592 /// \param SemaRef the semantic analysis object for which we are performing
2593 /// the substitution.
2594 ///
2595 /// \param Template the template that we are synthesizing template arguments
2596 /// for.
2597 ///
2598 /// \param TemplateLoc the location of the template name that started the
2599 /// template-id we are checking.
2600 ///
2601 /// \param RAngleLoc the location of the right angle bracket ('>') that
2602 /// terminates the template-id.
2603 ///
2604 /// \param Param the non-type template parameter whose default we are
2605 /// substituting into.
2606 ///
2607 /// \param Converted the list of template arguments provided for template
2608 /// parameters that precede \p Param in the template parameter list.
2609 ///
2610 /// \returns the substituted template argument, or NULL if an error occurred.
2611 static ExprResult
2612 SubstDefaultTemplateArgument(Sema &SemaRef,
2613                              TemplateDecl *Template,
2614                              SourceLocation TemplateLoc,
2615                              SourceLocation RAngleLoc,
2616                              NonTypeTemplateParmDecl *Param,
2617                         SmallVectorImpl<TemplateArgument> &Converted) {
2618   TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2619                                     Converted.data(), Converted.size());
2620 
2621   MultiLevelTemplateArgumentList AllTemplateArgs
2622     = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2623 
2624   Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
2625                                    Template, Converted,
2626                                    SourceRange(TemplateLoc, RAngleLoc));
2627   if (Inst)
2628     return ExprError();
2629 
2630   Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
2631   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
2632   return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
2633 }
2634 
2635 /// \brief Substitute template arguments into the default template argument for
2636 /// the given template template parameter.
2637 ///
2638 /// \param SemaRef the semantic analysis object for which we are performing
2639 /// the substitution.
2640 ///
2641 /// \param Template the template that we are synthesizing template arguments
2642 /// for.
2643 ///
2644 /// \param TemplateLoc the location of the template name that started the
2645 /// template-id we are checking.
2646 ///
2647 /// \param RAngleLoc the location of the right angle bracket ('>') that
2648 /// terminates the template-id.
2649 ///
2650 /// \param Param the template template parameter whose default we are
2651 /// substituting into.
2652 ///
2653 /// \param Converted the list of template arguments provided for template
2654 /// parameters that precede \p Param in the template parameter list.
2655 ///
2656 /// \param QualifierLoc Will be set to the nested-name-specifier (with
2657 /// source-location information) that precedes the template name.
2658 ///
2659 /// \returns the substituted template argument, or NULL if an error occurred.
2660 static TemplateName
2661 SubstDefaultTemplateArgument(Sema &SemaRef,
2662                              TemplateDecl *Template,
2663                              SourceLocation TemplateLoc,
2664                              SourceLocation RAngleLoc,
2665                              TemplateTemplateParmDecl *Param,
2666                        SmallVectorImpl<TemplateArgument> &Converted,
2667                              NestedNameSpecifierLoc &QualifierLoc) {
2668   TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2669                                     Converted.data(), Converted.size());
2670 
2671   MultiLevelTemplateArgumentList AllTemplateArgs
2672     = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2673 
2674   Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
2675                                    Template, Converted,
2676                                    SourceRange(TemplateLoc, RAngleLoc));
2677   if (Inst)
2678     return TemplateName();
2679 
2680   Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
2681   // Substitute into the nested-name-specifier first,
2682   QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
2683   if (QualifierLoc) {
2684     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2685                                                        AllTemplateArgs);
2686     if (!QualifierLoc)
2687       return TemplateName();
2688   }
2689 
2690   return SemaRef.SubstTemplateName(QualifierLoc,
2691                       Param->getDefaultArgument().getArgument().getAsTemplate(),
2692                               Param->getDefaultArgument().getTemplateNameLoc(),
2693                                    AllTemplateArgs);
2694 }
2695 
2696 /// \brief If the given template parameter has a default template
2697 /// argument, substitute into that default template argument and
2698 /// return the corresponding template argument.
2699 TemplateArgumentLoc
2700 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
2701                                               SourceLocation TemplateLoc,
2702                                               SourceLocation RAngleLoc,
2703                                               Decl *Param,
2704                       SmallVectorImpl<TemplateArgument> &Converted) {
2705    if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
2706     if (!TypeParm->hasDefaultArgument())
2707       return TemplateArgumentLoc();
2708 
2709     TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
2710                                                       TemplateLoc,
2711                                                       RAngleLoc,
2712                                                       TypeParm,
2713                                                       Converted);
2714     if (DI)
2715       return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
2716 
2717     return TemplateArgumentLoc();
2718   }
2719 
2720   if (NonTypeTemplateParmDecl *NonTypeParm
2721         = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2722     if (!NonTypeParm->hasDefaultArgument())
2723       return TemplateArgumentLoc();
2724 
2725     ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
2726                                                   TemplateLoc,
2727                                                   RAngleLoc,
2728                                                   NonTypeParm,
2729                                                   Converted);
2730     if (Arg.isInvalid())
2731       return TemplateArgumentLoc();
2732 
2733     Expr *ArgE = Arg.takeAs<Expr>();
2734     return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
2735   }
2736 
2737   TemplateTemplateParmDecl *TempTempParm
2738     = cast<TemplateTemplateParmDecl>(Param);
2739   if (!TempTempParm->hasDefaultArgument())
2740     return TemplateArgumentLoc();
2741 
2742 
2743   NestedNameSpecifierLoc QualifierLoc;
2744   TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
2745                                                     TemplateLoc,
2746                                                     RAngleLoc,
2747                                                     TempTempParm,
2748                                                     Converted,
2749                                                     QualifierLoc);
2750   if (TName.isNull())
2751     return TemplateArgumentLoc();
2752 
2753   return TemplateArgumentLoc(TemplateArgument(TName),
2754                 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
2755                 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2756 }
2757 
2758 /// \brief Check that the given template argument corresponds to the given
2759 /// template parameter.
2760 ///
2761 /// \param Param The template parameter against which the argument will be
2762 /// checked.
2763 ///
2764 /// \param Arg The template argument.
2765 ///
2766 /// \param Template The template in which the template argument resides.
2767 ///
2768 /// \param TemplateLoc The location of the template name for the template
2769 /// whose argument list we're matching.
2770 ///
2771 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
2772 /// the template argument list.
2773 ///
2774 /// \param ArgumentPackIndex The index into the argument pack where this
2775 /// argument will be placed. Only valid if the parameter is a parameter pack.
2776 ///
2777 /// \param Converted The checked, converted argument will be added to the
2778 /// end of this small vector.
2779 ///
2780 /// \param CTAK Describes how we arrived at this particular template argument:
2781 /// explicitly written, deduced, etc.
2782 ///
2783 /// \returns true on error, false otherwise.
2784 bool Sema::CheckTemplateArgument(NamedDecl *Param,
2785                                  const TemplateArgumentLoc &Arg,
2786                                  NamedDecl *Template,
2787                                  SourceLocation TemplateLoc,
2788                                  SourceLocation RAngleLoc,
2789                                  unsigned ArgumentPackIndex,
2790                             SmallVectorImpl<TemplateArgument> &Converted,
2791                                  CheckTemplateArgumentKind CTAK) {
2792   // Check template type parameters.
2793   if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2794     return CheckTemplateTypeArgument(TTP, Arg, Converted);
2795 
2796   // Check non-type template parameters.
2797   if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2798     // Do substitution on the type of the non-type template parameter
2799     // with the template arguments we've seen thus far.  But if the
2800     // template has a dependent context then we cannot substitute yet.
2801     QualType NTTPType = NTTP->getType();
2802     if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
2803       NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
2804 
2805     if (NTTPType->isDependentType() &&
2806         !isa<TemplateTemplateParmDecl>(Template) &&
2807         !Template->getDeclContext()->isDependentContext()) {
2808       // Do substitution on the type of the non-type template parameter.
2809       InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2810                                  NTTP, Converted,
2811                                  SourceRange(TemplateLoc, RAngleLoc));
2812       if (Inst)
2813         return true;
2814 
2815       TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2816                                         Converted.data(), Converted.size());
2817       NTTPType = SubstType(NTTPType,
2818                            MultiLevelTemplateArgumentList(TemplateArgs),
2819                            NTTP->getLocation(),
2820                            NTTP->getDeclName());
2821       // If that worked, check the non-type template parameter type
2822       // for validity.
2823       if (!NTTPType.isNull())
2824         NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2825                                                      NTTP->getLocation());
2826       if (NTTPType.isNull())
2827         return true;
2828     }
2829 
2830     switch (Arg.getArgument().getKind()) {
2831     case TemplateArgument::Null:
2832       llvm_unreachable("Should never see a NULL template argument here");
2833 
2834     case TemplateArgument::Expression: {
2835       TemplateArgument Result;
2836       ExprResult Res =
2837         CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
2838                               Result, CTAK);
2839       if (Res.isInvalid())
2840         return true;
2841 
2842       Converted.push_back(Result);
2843       break;
2844     }
2845 
2846     case TemplateArgument::Declaration:
2847     case TemplateArgument::Integral:
2848     case TemplateArgument::NullPtr:
2849       // We've already checked this template argument, so just copy
2850       // it to the list of converted arguments.
2851       Converted.push_back(Arg.getArgument());
2852       break;
2853 
2854     case TemplateArgument::Template:
2855     case TemplateArgument::TemplateExpansion:
2856       // We were given a template template argument. It may not be ill-formed;
2857       // see below.
2858       if (DependentTemplateName *DTN
2859             = Arg.getArgument().getAsTemplateOrTemplatePattern()
2860                                               .getAsDependentTemplateName()) {
2861         // We have a template argument such as \c T::template X, which we
2862         // parsed as a template template argument. However, since we now
2863         // know that we need a non-type template argument, convert this
2864         // template name into an expression.
2865 
2866         DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2867                                      Arg.getTemplateNameLoc());
2868 
2869         CXXScopeSpec SS;
2870         SS.Adopt(Arg.getTemplateQualifierLoc());
2871         // FIXME: the template-template arg was a DependentTemplateName,
2872         // so it was provided with a template keyword. However, its source
2873         // location is not stored in the template argument structure.
2874         SourceLocation TemplateKWLoc;
2875         ExprResult E = Owned(DependentScopeDeclRefExpr::Create(Context,
2876                                                 SS.getWithLocInContext(Context),
2877                                                                TemplateKWLoc,
2878                                                                NameInfo, 0));
2879 
2880         // If we parsed the template argument as a pack expansion, create a
2881         // pack expansion expression.
2882         if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
2883           E = ActOnPackExpansion(E.take(), Arg.getTemplateEllipsisLoc());
2884           if (E.isInvalid())
2885             return true;
2886         }
2887 
2888         TemplateArgument Result;
2889         E = CheckTemplateArgument(NTTP, NTTPType, E.take(), Result);
2890         if (E.isInvalid())
2891           return true;
2892 
2893         Converted.push_back(Result);
2894         break;
2895       }
2896 
2897       // We have a template argument that actually does refer to a class
2898       // template, alias template, or template template parameter, and
2899       // therefore cannot be a non-type template argument.
2900       Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2901         << Arg.getSourceRange();
2902 
2903       Diag(Param->getLocation(), diag::note_template_param_here);
2904       return true;
2905 
2906     case TemplateArgument::Type: {
2907       // We have a non-type template parameter but the template
2908       // argument is a type.
2909 
2910       // C++ [temp.arg]p2:
2911       //   In a template-argument, an ambiguity between a type-id and
2912       //   an expression is resolved to a type-id, regardless of the
2913       //   form of the corresponding template-parameter.
2914       //
2915       // We warn specifically about this case, since it can be rather
2916       // confusing for users.
2917       QualType T = Arg.getArgument().getAsType();
2918       SourceRange SR = Arg.getSourceRange();
2919       if (T->isFunctionType())
2920         Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2921       else
2922         Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2923       Diag(Param->getLocation(), diag::note_template_param_here);
2924       return true;
2925     }
2926 
2927     case TemplateArgument::Pack:
2928       llvm_unreachable("Caller must expand template argument packs");
2929     }
2930 
2931     return false;
2932   }
2933 
2934 
2935   // Check template template parameters.
2936   TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2937 
2938   // Substitute into the template parameter list of the template
2939   // template parameter, since previously-supplied template arguments
2940   // may appear within the template template parameter.
2941   {
2942     // Set up a template instantiation context.
2943     LocalInstantiationScope Scope(*this);
2944     InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2945                                TempParm, Converted,
2946                                SourceRange(TemplateLoc, RAngleLoc));
2947     if (Inst)
2948       return true;
2949 
2950     TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2951                                       Converted.data(), Converted.size());
2952     TempParm = cast_or_null<TemplateTemplateParmDecl>(
2953                       SubstDecl(TempParm, CurContext,
2954                                 MultiLevelTemplateArgumentList(TemplateArgs)));
2955     if (!TempParm)
2956       return true;
2957   }
2958 
2959   switch (Arg.getArgument().getKind()) {
2960   case TemplateArgument::Null:
2961     llvm_unreachable("Should never see a NULL template argument here");
2962 
2963   case TemplateArgument::Template:
2964   case TemplateArgument::TemplateExpansion:
2965     if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
2966       return true;
2967 
2968     Converted.push_back(Arg.getArgument());
2969     break;
2970 
2971   case TemplateArgument::Expression:
2972   case TemplateArgument::Type:
2973     // We have a template template parameter but the template
2974     // argument does not refer to a template.
2975     Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
2976       << getLangOpts().CPlusPlus11;
2977     return true;
2978 
2979   case TemplateArgument::Declaration:
2980     llvm_unreachable("Declaration argument with template template parameter");
2981   case TemplateArgument::Integral:
2982     llvm_unreachable("Integral argument with template template parameter");
2983   case TemplateArgument::NullPtr:
2984     llvm_unreachable("Null pointer argument with template template parameter");
2985 
2986   case TemplateArgument::Pack:
2987     llvm_unreachable("Caller must expand template argument packs");
2988   }
2989 
2990   return false;
2991 }
2992 
2993 /// \brief Diagnose an arity mismatch in the
2994 static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
2995                                   SourceLocation TemplateLoc,
2996                                   TemplateArgumentListInfo &TemplateArgs) {
2997   TemplateParameterList *Params = Template->getTemplateParameters();
2998   unsigned NumParams = Params->size();
2999   unsigned NumArgs = TemplateArgs.size();
3000 
3001   SourceRange Range;
3002   if (NumArgs > NumParams)
3003     Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3004                         TemplateArgs.getRAngleLoc());
3005   S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3006     << (NumArgs > NumParams)
3007     << (isa<ClassTemplateDecl>(Template)? 0 :
3008         isa<FunctionTemplateDecl>(Template)? 1 :
3009         isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3010     << Template << Range;
3011   S.Diag(Template->getLocation(), diag::note_template_decl_here)
3012     << Params->getSourceRange();
3013   return true;
3014 }
3015 
3016 /// \brief Check whether the template parameter is a pack expansion, and if so,
3017 /// determine the number of parameters produced by that expansion. For instance:
3018 ///
3019 /// \code
3020 /// template<typename ...Ts> struct A {
3021 ///   template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3022 /// };
3023 /// \endcode
3024 ///
3025 /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3026 /// is not a pack expansion, so returns an empty Optional.
3027 static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
3028   if (NonTypeTemplateParmDecl *NTTP
3029         = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3030     if (NTTP->isExpandedParameterPack())
3031       return NTTP->getNumExpansionTypes();
3032   }
3033 
3034   if (TemplateTemplateParmDecl *TTP
3035         = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3036     if (TTP->isExpandedParameterPack())
3037       return TTP->getNumExpansionTemplateParameters();
3038   }
3039 
3040   return None;
3041 }
3042 
3043 /// \brief Check that the given template argument list is well-formed
3044 /// for specializing the given template.
3045 bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3046                                      SourceLocation TemplateLoc,
3047                                      TemplateArgumentListInfo &TemplateArgs,
3048                                      bool PartialTemplateArgs,
3049                           SmallVectorImpl<TemplateArgument> &Converted,
3050                                      bool *ExpansionIntoFixedList) {
3051   if (ExpansionIntoFixedList)
3052     *ExpansionIntoFixedList = false;
3053 
3054   TemplateParameterList *Params = Template->getTemplateParameters();
3055 
3056   SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
3057 
3058   // C++ [temp.arg]p1:
3059   //   [...] The type and form of each template-argument specified in
3060   //   a template-id shall match the type and form specified for the
3061   //   corresponding parameter declared by the template in its
3062   //   template-parameter-list.
3063   bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
3064   SmallVector<TemplateArgument, 2> ArgumentPack;
3065   unsigned ArgIdx = 0, NumArgs = TemplateArgs.size();
3066   LocalInstantiationScope InstScope(*this, true);
3067   for (TemplateParameterList::iterator Param = Params->begin(),
3068                                        ParamEnd = Params->end();
3069        Param != ParamEnd; /* increment in loop */) {
3070     // If we have an expanded parameter pack, make sure we don't have too
3071     // many arguments.
3072     if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
3073       if (*Expansions == ArgumentPack.size()) {
3074         // We're done with this parameter pack. Pack up its arguments and add
3075         // them to the list.
3076         Converted.push_back(
3077           TemplateArgument::CreatePackCopy(Context,
3078                                            ArgumentPack.data(),
3079                                            ArgumentPack.size()));
3080         ArgumentPack.clear();
3081 
3082         // This argument is assigned to the next parameter.
3083         ++Param;
3084         continue;
3085       } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3086         // Not enough arguments for this parameter pack.
3087         Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3088           << false
3089           << (isa<ClassTemplateDecl>(Template)? 0 :
3090               isa<FunctionTemplateDecl>(Template)? 1 :
3091               isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3092           << Template;
3093         Diag(Template->getLocation(), diag::note_template_decl_here)
3094           << Params->getSourceRange();
3095         return true;
3096       }
3097     }
3098 
3099     if (ArgIdx < NumArgs) {
3100       // Check the template argument we were given.
3101       if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
3102                                 TemplateLoc, RAngleLoc,
3103                                 ArgumentPack.size(), Converted))
3104         return true;
3105 
3106       // We're now done with this argument.
3107       ++ArgIdx;
3108 
3109       if ((*Param)->isTemplateParameterPack()) {
3110         // The template parameter was a template parameter pack, so take the
3111         // deduced argument and place it on the argument pack. Note that we
3112         // stay on the same template parameter so that we can deduce more
3113         // arguments.
3114         ArgumentPack.push_back(Converted.back());
3115         Converted.pop_back();
3116       } else {
3117         // Move to the next template parameter.
3118         ++Param;
3119       }
3120 
3121       // If we just saw a pack expansion, then directly convert the remaining
3122       // arguments, because we don't know what parameters they'll match up
3123       // with.
3124       if (TemplateArgs[ArgIdx-1].getArgument().isPackExpansion()) {
3125         bool InFinalParameterPack = Param != ParamEnd &&
3126                                     Param + 1 == ParamEnd &&
3127                                     (*Param)->isTemplateParameterPack() &&
3128                                     !getExpandedPackSize(*Param);
3129 
3130         if (!InFinalParameterPack && !ArgumentPack.empty()) {
3131           // If we were part way through filling in an expanded parameter pack,
3132           // fall back to just producing individual arguments.
3133           Converted.insert(Converted.end(),
3134                            ArgumentPack.begin(), ArgumentPack.end());
3135           ArgumentPack.clear();
3136         }
3137 
3138         while (ArgIdx < NumArgs) {
3139           if (InFinalParameterPack)
3140             ArgumentPack.push_back(TemplateArgs[ArgIdx].getArgument());
3141           else
3142             Converted.push_back(TemplateArgs[ArgIdx].getArgument());
3143           ++ArgIdx;
3144         }
3145 
3146         // Push the argument pack onto the list of converted arguments.
3147         if (InFinalParameterPack) {
3148           Converted.push_back(
3149             TemplateArgument::CreatePackCopy(Context,
3150                                              ArgumentPack.data(),
3151                                              ArgumentPack.size()));
3152           ArgumentPack.clear();
3153         } else if (ExpansionIntoFixedList) {
3154           // We have expanded a pack into a fixed list.
3155           *ExpansionIntoFixedList = true;
3156         }
3157 
3158         return false;
3159       }
3160 
3161       continue;
3162     }
3163 
3164     // If we're checking a partial template argument list, we're done.
3165     if (PartialTemplateArgs) {
3166       if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
3167         Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3168                                                          ArgumentPack.data(),
3169                                                          ArgumentPack.size()));
3170 
3171       return false;
3172     }
3173 
3174     // If we have a template parameter pack with no more corresponding
3175     // arguments, just break out now and we'll fill in the argument pack below.
3176     if ((*Param)->isTemplateParameterPack()) {
3177       assert(!getExpandedPackSize(*Param) &&
3178              "Should have dealt with this already");
3179 
3180       // A non-expanded parameter pack before the end of the parameter list
3181       // only occurs for an ill-formed template parameter list, unless we've
3182       // got a partial argument list for a function template, so just bail out.
3183       if (Param + 1 != ParamEnd)
3184         return true;
3185 
3186       Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3187                                                        ArgumentPack.data(),
3188                                                        ArgumentPack.size()));
3189       ArgumentPack.clear();
3190 
3191       ++Param;
3192       continue;
3193     }
3194 
3195     // Check whether we have a default argument.
3196     TemplateArgumentLoc Arg;
3197 
3198     // Retrieve the default template argument from the template
3199     // parameter. For each kind of template parameter, we substitute the
3200     // template arguments provided thus far and any "outer" template arguments
3201     // (when the template parameter was part of a nested template) into
3202     // the default argument.
3203     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
3204       if (!TTP->hasDefaultArgument())
3205         return diagnoseArityMismatch(*this, Template, TemplateLoc,
3206                                      TemplateArgs);
3207 
3208       TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
3209                                                              Template,
3210                                                              TemplateLoc,
3211                                                              RAngleLoc,
3212                                                              TTP,
3213                                                              Converted);
3214       if (!ArgType)
3215         return true;
3216 
3217       Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3218                                 ArgType);
3219     } else if (NonTypeTemplateParmDecl *NTTP
3220                  = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
3221       if (!NTTP->hasDefaultArgument())
3222         return diagnoseArityMismatch(*this, Template, TemplateLoc,
3223                                      TemplateArgs);
3224 
3225       ExprResult E = SubstDefaultTemplateArgument(*this, Template,
3226                                                               TemplateLoc,
3227                                                               RAngleLoc,
3228                                                               NTTP,
3229                                                               Converted);
3230       if (E.isInvalid())
3231         return true;
3232 
3233       Expr *Ex = E.takeAs<Expr>();
3234       Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3235     } else {
3236       TemplateTemplateParmDecl *TempParm
3237         = cast<TemplateTemplateParmDecl>(*Param);
3238 
3239       if (!TempParm->hasDefaultArgument())
3240         return diagnoseArityMismatch(*this, Template, TemplateLoc,
3241                                      TemplateArgs);
3242 
3243       NestedNameSpecifierLoc QualifierLoc;
3244       TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
3245                                                        TemplateLoc,
3246                                                        RAngleLoc,
3247                                                        TempParm,
3248                                                        Converted,
3249                                                        QualifierLoc);
3250       if (Name.isNull())
3251         return true;
3252 
3253       Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3254                            TempParm->getDefaultArgument().getTemplateNameLoc());
3255     }
3256 
3257     // Introduce an instantiation record that describes where we are using
3258     // the default template argument.
3259     InstantiatingTemplate Instantiating(*this, RAngleLoc, Template,
3260                                         *Param, Converted,
3261                                         SourceRange(TemplateLoc, RAngleLoc));
3262     if (Instantiating)
3263       return true;
3264 
3265     // Check the default template argument.
3266     if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
3267                               RAngleLoc, 0, Converted))
3268       return true;
3269 
3270     // Core issue 150 (assumed resolution): if this is a template template
3271     // parameter, keep track of the default template arguments from the
3272     // template definition.
3273     if (isTemplateTemplateParameter)
3274       TemplateArgs.addArgument(Arg);
3275 
3276     // Move to the next template parameter and argument.
3277     ++Param;
3278     ++ArgIdx;
3279   }
3280 
3281   // If we have any leftover arguments, then there were too many arguments.
3282   // Complain and fail.
3283   if (ArgIdx < NumArgs)
3284     return diagnoseArityMismatch(*this, Template, TemplateLoc, TemplateArgs);
3285 
3286   return false;
3287 }
3288 
3289 namespace {
3290   class UnnamedLocalNoLinkageFinder
3291     : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
3292   {
3293     Sema &S;
3294     SourceRange SR;
3295 
3296     typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
3297 
3298   public:
3299     UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
3300 
3301     bool Visit(QualType T) {
3302       return inherited::Visit(T.getTypePtr());
3303     }
3304 
3305 #define TYPE(Class, Parent) \
3306     bool Visit##Class##Type(const Class##Type *);
3307 #define ABSTRACT_TYPE(Class, Parent) \
3308     bool Visit##Class##Type(const Class##Type *) { return false; }
3309 #define NON_CANONICAL_TYPE(Class, Parent) \
3310     bool Visit##Class##Type(const Class##Type *) { return false; }
3311 #include "clang/AST/TypeNodes.def"
3312 
3313     bool VisitTagDecl(const TagDecl *Tag);
3314     bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
3315   };
3316 }
3317 
3318 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
3319   return false;
3320 }
3321 
3322 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
3323   return Visit(T->getElementType());
3324 }
3325 
3326 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
3327   return Visit(T->getPointeeType());
3328 }
3329 
3330 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
3331                                                     const BlockPointerType* T) {
3332   return Visit(T->getPointeeType());
3333 }
3334 
3335 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
3336                                                 const LValueReferenceType* T) {
3337   return Visit(T->getPointeeType());
3338 }
3339 
3340 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
3341                                                 const RValueReferenceType* T) {
3342   return Visit(T->getPointeeType());
3343 }
3344 
3345 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
3346                                                   const MemberPointerType* T) {
3347   return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
3348 }
3349 
3350 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
3351                                                   const ConstantArrayType* T) {
3352   return Visit(T->getElementType());
3353 }
3354 
3355 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
3356                                                  const IncompleteArrayType* T) {
3357   return Visit(T->getElementType());
3358 }
3359 
3360 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
3361                                                    const VariableArrayType* T) {
3362   return Visit(T->getElementType());
3363 }
3364 
3365 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
3366                                             const DependentSizedArrayType* T) {
3367   return Visit(T->getElementType());
3368 }
3369 
3370 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
3371                                          const DependentSizedExtVectorType* T) {
3372   return Visit(T->getElementType());
3373 }
3374 
3375 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
3376   return Visit(T->getElementType());
3377 }
3378 
3379 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
3380   return Visit(T->getElementType());
3381 }
3382 
3383 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
3384                                                   const FunctionProtoType* T) {
3385   for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
3386                                          AEnd = T->arg_type_end();
3387        A != AEnd; ++A) {
3388     if (Visit(*A))
3389       return true;
3390   }
3391 
3392   return Visit(T->getResultType());
3393 }
3394 
3395 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
3396                                                const FunctionNoProtoType* T) {
3397   return Visit(T->getResultType());
3398 }
3399 
3400 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
3401                                                   const UnresolvedUsingType*) {
3402   return false;
3403 }
3404 
3405 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
3406   return false;
3407 }
3408 
3409 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
3410   return Visit(T->getUnderlyingType());
3411 }
3412 
3413 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
3414   return false;
3415 }
3416 
3417 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
3418                                                     const UnaryTransformType*) {
3419   return false;
3420 }
3421 
3422 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
3423   return Visit(T->getDeducedType());
3424 }
3425 
3426 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
3427   return VisitTagDecl(T->getDecl());
3428 }
3429 
3430 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
3431   return VisitTagDecl(T->getDecl());
3432 }
3433 
3434 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
3435                                                  const TemplateTypeParmType*) {
3436   return false;
3437 }
3438 
3439 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
3440                                         const SubstTemplateTypeParmPackType *) {
3441   return false;
3442 }
3443 
3444 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
3445                                             const TemplateSpecializationType*) {
3446   return false;
3447 }
3448 
3449 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
3450                                               const InjectedClassNameType* T) {
3451   return VisitTagDecl(T->getDecl());
3452 }
3453 
3454 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
3455                                                    const DependentNameType* T) {
3456   return VisitNestedNameSpecifier(T->getQualifier());
3457 }
3458 
3459 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
3460                                  const DependentTemplateSpecializationType* T) {
3461   return VisitNestedNameSpecifier(T->getQualifier());
3462 }
3463 
3464 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
3465                                                    const PackExpansionType* T) {
3466   return Visit(T->getPattern());
3467 }
3468 
3469 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
3470   return false;
3471 }
3472 
3473 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
3474                                                    const ObjCInterfaceType *) {
3475   return false;
3476 }
3477 
3478 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
3479                                                 const ObjCObjectPointerType *) {
3480   return false;
3481 }
3482 
3483 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
3484   return Visit(T->getValueType());
3485 }
3486 
3487 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
3488   if (Tag->getDeclContext()->isFunctionOrMethod()) {
3489     S.Diag(SR.getBegin(),
3490            S.getLangOpts().CPlusPlus11 ?
3491              diag::warn_cxx98_compat_template_arg_local_type :
3492              diag::ext_template_arg_local_type)
3493       << S.Context.getTypeDeclType(Tag) << SR;
3494     return true;
3495   }
3496 
3497   if (!Tag->hasNameForLinkage()) {
3498     S.Diag(SR.getBegin(),
3499            S.getLangOpts().CPlusPlus11 ?
3500              diag::warn_cxx98_compat_template_arg_unnamed_type :
3501              diag::ext_template_arg_unnamed_type) << SR;
3502     S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
3503     return true;
3504   }
3505 
3506   return false;
3507 }
3508 
3509 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
3510                                                     NestedNameSpecifier *NNS) {
3511   if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
3512     return true;
3513 
3514   switch (NNS->getKind()) {
3515   case NestedNameSpecifier::Identifier:
3516   case NestedNameSpecifier::Namespace:
3517   case NestedNameSpecifier::NamespaceAlias:
3518   case NestedNameSpecifier::Global:
3519     return false;
3520 
3521   case NestedNameSpecifier::TypeSpec:
3522   case NestedNameSpecifier::TypeSpecWithTemplate:
3523     return Visit(QualType(NNS->getAsType(), 0));
3524   }
3525   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
3526 }
3527 
3528 
3529 /// \brief Check a template argument against its corresponding
3530 /// template type parameter.
3531 ///
3532 /// This routine implements the semantics of C++ [temp.arg.type]. It
3533 /// returns true if an error occurred, and false otherwise.
3534 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
3535                                  TypeSourceInfo *ArgInfo) {
3536   assert(ArgInfo && "invalid TypeSourceInfo");
3537   QualType Arg = ArgInfo->getType();
3538   SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
3539 
3540   if (Arg->isVariablyModifiedType()) {
3541     return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
3542   } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
3543     return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
3544   }
3545 
3546   // C++03 [temp.arg.type]p2:
3547   //   A local type, a type with no linkage, an unnamed type or a type
3548   //   compounded from any of these types shall not be used as a
3549   //   template-argument for a template type-parameter.
3550   //
3551   // C++11 allows these, and even in C++03 we allow them as an extension with
3552   // a warning.
3553   if (LangOpts.CPlusPlus11 ?
3554      Diags.getDiagnosticLevel(diag::warn_cxx98_compat_template_arg_unnamed_type,
3555                               SR.getBegin()) != DiagnosticsEngine::Ignored ||
3556       Diags.getDiagnosticLevel(diag::warn_cxx98_compat_template_arg_local_type,
3557                                SR.getBegin()) != DiagnosticsEngine::Ignored :
3558       Arg->hasUnnamedOrLocalType()) {
3559     UnnamedLocalNoLinkageFinder Finder(*this, SR);
3560     (void)Finder.Visit(Context.getCanonicalType(Arg));
3561   }
3562 
3563   return false;
3564 }
3565 
3566 enum NullPointerValueKind {
3567   NPV_NotNullPointer,
3568   NPV_NullPointer,
3569   NPV_Error
3570 };
3571 
3572 /// \brief Determine whether the given template argument is a null pointer
3573 /// value of the appropriate type.
3574 static NullPointerValueKind
3575 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
3576                                    QualType ParamType, Expr *Arg) {
3577   if (Arg->isValueDependent() || Arg->isTypeDependent())
3578     return NPV_NotNullPointer;
3579 
3580   if (!S.getLangOpts().CPlusPlus11)
3581     return NPV_NotNullPointer;
3582 
3583   // Determine whether we have a constant expression.
3584   ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
3585   if (ArgRV.isInvalid())
3586     return NPV_Error;
3587   Arg = ArgRV.take();
3588 
3589   Expr::EvalResult EvalResult;
3590   SmallVector<PartialDiagnosticAt, 8> Notes;
3591   EvalResult.Diag = &Notes;
3592   if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
3593       EvalResult.HasSideEffects) {
3594     SourceLocation DiagLoc = Arg->getExprLoc();
3595 
3596     // If our only note is the usual "invalid subexpression" note, just point
3597     // the caret at its location rather than producing an essentially
3598     // redundant note.
3599     if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
3600         diag::note_invalid_subexpr_in_const_expr) {
3601       DiagLoc = Notes[0].first;
3602       Notes.clear();
3603     }
3604 
3605     S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
3606       << Arg->getType() << Arg->getSourceRange();
3607     for (unsigned I = 0, N = Notes.size(); I != N; ++I)
3608       S.Diag(Notes[I].first, Notes[I].second);
3609 
3610     S.Diag(Param->getLocation(), diag::note_template_param_here);
3611     return NPV_Error;
3612   }
3613 
3614   // C++11 [temp.arg.nontype]p1:
3615   //   - an address constant expression of type std::nullptr_t
3616   if (Arg->getType()->isNullPtrType())
3617     return NPV_NullPointer;
3618 
3619   //   - a constant expression that evaluates to a null pointer value (4.10); or
3620   //   - a constant expression that evaluates to a null member pointer value
3621   //     (4.11); or
3622   if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
3623       (EvalResult.Val.isMemberPointer() &&
3624        !EvalResult.Val.getMemberPointerDecl())) {
3625     // If our expression has an appropriate type, we've succeeded.
3626     bool ObjCLifetimeConversion;
3627     if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
3628         S.IsQualificationConversion(Arg->getType(), ParamType, false,
3629                                      ObjCLifetimeConversion))
3630       return NPV_NullPointer;
3631 
3632     // The types didn't match, but we know we got a null pointer; complain,
3633     // then recover as if the types were correct.
3634     S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
3635       << Arg->getType() << ParamType << Arg->getSourceRange();
3636     S.Diag(Param->getLocation(), diag::note_template_param_here);
3637     return NPV_NullPointer;
3638   }
3639 
3640   // If we don't have a null pointer value, but we do have a NULL pointer
3641   // constant, suggest a cast to the appropriate type.
3642   if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
3643     std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
3644     S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
3645       << ParamType
3646       << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
3647       << FixItHint::CreateInsertion(S.PP.getLocForEndOfToken(Arg->getLocEnd()),
3648                                     ")");
3649     S.Diag(Param->getLocation(), diag::note_template_param_here);
3650     return NPV_NullPointer;
3651   }
3652 
3653   // FIXME: If we ever want to support general, address-constant expressions
3654   // as non-type template arguments, we should return the ExprResult here to
3655   // be interpreted by the caller.
3656   return NPV_NotNullPointer;
3657 }
3658 
3659 /// \brief Checks whether the given template argument is the address
3660 /// of an object or function according to C++ [temp.arg.nontype]p1.
3661 static bool
3662 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
3663                                                NonTypeTemplateParmDecl *Param,
3664                                                QualType ParamType,
3665                                                Expr *ArgIn,
3666                                                TemplateArgument &Converted) {
3667   bool Invalid = false;
3668   Expr *Arg = ArgIn;
3669   QualType ArgType = Arg->getType();
3670 
3671   // If our parameter has pointer type, check for a null template value.
3672   if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
3673     switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
3674     case NPV_NullPointer:
3675       S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
3676       Converted = TemplateArgument(ParamType, /*isNullPtr*/true);
3677       return false;
3678 
3679     case NPV_Error:
3680       return true;
3681 
3682     case NPV_NotNullPointer:
3683       break;
3684     }
3685   }
3686 
3687   // See through any implicit casts we added to fix the type.
3688   Arg = Arg->IgnoreImpCasts();
3689 
3690   // C++ [temp.arg.nontype]p1:
3691   //
3692   //   A template-argument for a non-type, non-template
3693   //   template-parameter shall be one of: [...]
3694   //
3695   //     -- the address of an object or function with external
3696   //        linkage, including function templates and function
3697   //        template-ids but excluding non-static class members,
3698   //        expressed as & id-expression where the & is optional if
3699   //        the name refers to a function or array, or if the
3700   //        corresponding template-parameter is a reference; or
3701 
3702   // In C++98/03 mode, give an extension warning on any extra parentheses.
3703   // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
3704   bool ExtraParens = false;
3705   while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
3706     if (!Invalid && !ExtraParens) {
3707       S.Diag(Arg->getLocStart(),
3708              S.getLangOpts().CPlusPlus11 ?
3709                diag::warn_cxx98_compat_template_arg_extra_parens :
3710                diag::ext_template_arg_extra_parens)
3711         << Arg->getSourceRange();
3712       ExtraParens = true;
3713     }
3714 
3715     Arg = Parens->getSubExpr();
3716   }
3717 
3718   while (SubstNonTypeTemplateParmExpr *subst =
3719            dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
3720     Arg = subst->getReplacement()->IgnoreImpCasts();
3721 
3722   bool AddressTaken = false;
3723   SourceLocation AddrOpLoc;
3724   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
3725     if (UnOp->getOpcode() == UO_AddrOf) {
3726       Arg = UnOp->getSubExpr();
3727       AddressTaken = true;
3728       AddrOpLoc = UnOp->getOperatorLoc();
3729     }
3730   }
3731 
3732   if (S.getLangOpts().MicrosoftExt && isa<CXXUuidofExpr>(Arg)) {
3733     Converted = TemplateArgument(ArgIn);
3734     return false;
3735   }
3736 
3737   while (SubstNonTypeTemplateParmExpr *subst =
3738            dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
3739     Arg = subst->getReplacement()->IgnoreImpCasts();
3740 
3741   // Stop checking the precise nature of the argument if it is value dependent,
3742   // it should be checked when instantiated.
3743   if (Arg->isValueDependent()) {
3744     Converted = TemplateArgument(ArgIn);
3745     return false;
3746   }
3747 
3748   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
3749   if (!DRE) {
3750     S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
3751     << Arg->getSourceRange();
3752     S.Diag(Param->getLocation(), diag::note_template_param_here);
3753     return true;
3754   }
3755 
3756   if (!isa<ValueDecl>(DRE->getDecl())) {
3757     S.Diag(Arg->getLocStart(),
3758            diag::err_template_arg_not_object_or_func_form)
3759       << Arg->getSourceRange();
3760     S.Diag(Param->getLocation(), diag::note_template_param_here);
3761     return true;
3762   }
3763 
3764   ValueDecl *Entity = DRE->getDecl();
3765 
3766   // Cannot refer to non-static data members
3767   if (FieldDecl *Field = dyn_cast<FieldDecl>(Entity)) {
3768     S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
3769       << Field << Arg->getSourceRange();
3770     S.Diag(Param->getLocation(), diag::note_template_param_here);
3771     return true;
3772   }
3773 
3774   // Cannot refer to non-static member functions
3775   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
3776     if (!Method->isStatic()) {
3777       S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
3778         << Method << Arg->getSourceRange();
3779       S.Diag(Param->getLocation(), diag::note_template_param_here);
3780       return true;
3781     }
3782   }
3783 
3784   FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
3785   VarDecl *Var = dyn_cast<VarDecl>(Entity);
3786 
3787   // A non-type template argument must refer to an object or function.
3788   if (!Func && !Var) {
3789     // We found something, but we don't know specifically what it is.
3790     S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
3791       << Arg->getSourceRange();
3792     S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
3793     return true;
3794   }
3795 
3796   // Address / reference template args must have external linkage in C++98.
3797   if (Entity->getFormalLinkage() == InternalLinkage) {
3798     S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
3799              diag::warn_cxx98_compat_template_arg_object_internal :
3800              diag::ext_template_arg_object_internal)
3801       << !Func << Entity << Arg->getSourceRange();
3802     S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
3803       << !Func;
3804   } else if (!Entity->hasLinkage()) {
3805     S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
3806       << !Func << Entity << Arg->getSourceRange();
3807     S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
3808       << !Func;
3809     return true;
3810   }
3811 
3812   if (Func) {
3813     // If the template parameter has pointer type, the function decays.
3814     if (ParamType->isPointerType() && !AddressTaken)
3815       ArgType = S.Context.getPointerType(Func->getType());
3816     else if (AddressTaken && ParamType->isReferenceType()) {
3817       // If we originally had an address-of operator, but the
3818       // parameter has reference type, complain and (if things look
3819       // like they will work) drop the address-of operator.
3820       if (!S.Context.hasSameUnqualifiedType(Func->getType(),
3821                                             ParamType.getNonReferenceType())) {
3822         S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3823           << ParamType;
3824         S.Diag(Param->getLocation(), diag::note_template_param_here);
3825         return true;
3826       }
3827 
3828       S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3829         << ParamType
3830         << FixItHint::CreateRemoval(AddrOpLoc);
3831       S.Diag(Param->getLocation(), diag::note_template_param_here);
3832 
3833       ArgType = Func->getType();
3834     }
3835   } else {
3836     // A value of reference type is not an object.
3837     if (Var->getType()->isReferenceType()) {
3838       S.Diag(Arg->getLocStart(),
3839              diag::err_template_arg_reference_var)
3840         << Var->getType() << Arg->getSourceRange();
3841       S.Diag(Param->getLocation(), diag::note_template_param_here);
3842       return true;
3843     }
3844 
3845     // A template argument must have static storage duration.
3846     if (Var->getTLSKind()) {
3847       S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
3848         << Arg->getSourceRange();
3849       S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
3850       return true;
3851     }
3852 
3853     // If the template parameter has pointer type, we must have taken
3854     // the address of this object.
3855     if (ParamType->isReferenceType()) {
3856       if (AddressTaken) {
3857         // If we originally had an address-of operator, but the
3858         // parameter has reference type, complain and (if things look
3859         // like they will work) drop the address-of operator.
3860         if (!S.Context.hasSameUnqualifiedType(Var->getType(),
3861                                             ParamType.getNonReferenceType())) {
3862           S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3863             << ParamType;
3864           S.Diag(Param->getLocation(), diag::note_template_param_here);
3865           return true;
3866         }
3867 
3868         S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3869           << ParamType
3870           << FixItHint::CreateRemoval(AddrOpLoc);
3871         S.Diag(Param->getLocation(), diag::note_template_param_here);
3872 
3873         ArgType = Var->getType();
3874       }
3875     } else if (!AddressTaken && ParamType->isPointerType()) {
3876       if (Var->getType()->isArrayType()) {
3877         // Array-to-pointer decay.
3878         ArgType = S.Context.getArrayDecayedType(Var->getType());
3879       } else {
3880         // If the template parameter has pointer type but the address of
3881         // this object was not taken, complain and (possibly) recover by
3882         // taking the address of the entity.
3883         ArgType = S.Context.getPointerType(Var->getType());
3884         if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
3885           S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
3886             << ParamType;
3887           S.Diag(Param->getLocation(), diag::note_template_param_here);
3888           return true;
3889         }
3890 
3891         S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
3892           << ParamType
3893           << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
3894 
3895         S.Diag(Param->getLocation(), diag::note_template_param_here);
3896       }
3897     }
3898   }
3899 
3900   bool ObjCLifetimeConversion;
3901   if (ParamType->isPointerType() &&
3902       !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
3903       S.IsQualificationConversion(ArgType, ParamType, false,
3904                                   ObjCLifetimeConversion)) {
3905     // For pointer-to-object types, qualification conversions are
3906     // permitted.
3907   } else {
3908     if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
3909       if (!ParamRef->getPointeeType()->isFunctionType()) {
3910         // C++ [temp.arg.nontype]p5b3:
3911         //   For a non-type template-parameter of type reference to
3912         //   object, no conversions apply. The type referred to by the
3913         //   reference may be more cv-qualified than the (otherwise
3914         //   identical) type of the template- argument. The
3915         //   template-parameter is bound directly to the
3916         //   template-argument, which shall be an lvalue.
3917 
3918         // FIXME: Other qualifiers?
3919         unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
3920         unsigned ArgQuals = ArgType.getCVRQualifiers();
3921 
3922         if ((ParamQuals | ArgQuals) != ParamQuals) {
3923           S.Diag(Arg->getLocStart(),
3924                  diag::err_template_arg_ref_bind_ignores_quals)
3925             << ParamType << Arg->getType()
3926             << Arg->getSourceRange();
3927           S.Diag(Param->getLocation(), diag::note_template_param_here);
3928           return true;
3929         }
3930       }
3931     }
3932 
3933     // At this point, the template argument refers to an object or
3934     // function with external linkage. We now need to check whether the
3935     // argument and parameter types are compatible.
3936     if (!S.Context.hasSameUnqualifiedType(ArgType,
3937                                           ParamType.getNonReferenceType())) {
3938       // We can't perform this conversion or binding.
3939       if (ParamType->isReferenceType())
3940         S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
3941           << ParamType << ArgIn->getType() << Arg->getSourceRange();
3942       else
3943         S.Diag(Arg->getLocStart(),  diag::err_template_arg_not_convertible)
3944           << ArgIn->getType() << ParamType << Arg->getSourceRange();
3945       S.Diag(Param->getLocation(), diag::note_template_param_here);
3946       return true;
3947     }
3948   }
3949 
3950   // Create the template argument.
3951   Converted = TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
3952                                ParamType->isReferenceType());
3953   S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
3954   return false;
3955 }
3956 
3957 /// \brief Checks whether the given template argument is a pointer to
3958 /// member constant according to C++ [temp.arg.nontype]p1.
3959 static bool CheckTemplateArgumentPointerToMember(Sema &S,
3960                                                  NonTypeTemplateParmDecl *Param,
3961                                                  QualType ParamType,
3962                                                  Expr *&ResultArg,
3963                                                  TemplateArgument &Converted) {
3964   bool Invalid = false;
3965 
3966   // Check for a null pointer value.
3967   Expr *Arg = ResultArg;
3968   switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
3969   case NPV_Error:
3970     return true;
3971   case NPV_NullPointer:
3972     S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
3973     Converted = TemplateArgument(ParamType, /*isNullPtr*/true);
3974     return false;
3975   case NPV_NotNullPointer:
3976     break;
3977   }
3978 
3979   bool ObjCLifetimeConversion;
3980   if (S.IsQualificationConversion(Arg->getType(),
3981                                   ParamType.getNonReferenceType(),
3982                                   false, ObjCLifetimeConversion)) {
3983     Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
3984                               Arg->getValueKind()).take();
3985     ResultArg = Arg;
3986   } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
3987                 ParamType.getNonReferenceType())) {
3988     // We can't perform this conversion.
3989     S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
3990       << Arg->getType() << ParamType << Arg->getSourceRange();
3991     S.Diag(Param->getLocation(), diag::note_template_param_here);
3992     return true;
3993   }
3994 
3995   // See through any implicit casts we added to fix the type.
3996   while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
3997     Arg = Cast->getSubExpr();
3998 
3999   // C++ [temp.arg.nontype]p1:
4000   //
4001   //   A template-argument for a non-type, non-template
4002   //   template-parameter shall be one of: [...]
4003   //
4004   //     -- a pointer to member expressed as described in 5.3.1.
4005   DeclRefExpr *DRE = 0;
4006 
4007   // In C++98/03 mode, give an extension warning on any extra parentheses.
4008   // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4009   bool ExtraParens = false;
4010   while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4011     if (!Invalid && !ExtraParens) {
4012       S.Diag(Arg->getLocStart(),
4013              S.getLangOpts().CPlusPlus11 ?
4014                diag::warn_cxx98_compat_template_arg_extra_parens :
4015                diag::ext_template_arg_extra_parens)
4016         << Arg->getSourceRange();
4017       ExtraParens = true;
4018     }
4019 
4020     Arg = Parens->getSubExpr();
4021   }
4022 
4023   while (SubstNonTypeTemplateParmExpr *subst =
4024            dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4025     Arg = subst->getReplacement()->IgnoreImpCasts();
4026 
4027   // A pointer-to-member constant written &Class::member.
4028   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4029     if (UnOp->getOpcode() == UO_AddrOf) {
4030       DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4031       if (DRE && !DRE->getQualifier())
4032         DRE = 0;
4033     }
4034   }
4035   // A constant of pointer-to-member type.
4036   else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4037     if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4038       if (VD->getType()->isMemberPointerType()) {
4039         if (isa<NonTypeTemplateParmDecl>(VD) ||
4040             (isa<VarDecl>(VD) &&
4041              S.Context.getCanonicalType(VD->getType()).isConstQualified())) {
4042           if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4043             Converted = TemplateArgument(Arg);
4044           } else {
4045             VD = cast<ValueDecl>(VD->getCanonicalDecl());
4046             Converted = TemplateArgument(VD, /*isReferenceParam*/false);
4047           }
4048           return Invalid;
4049         }
4050       }
4051     }
4052 
4053     DRE = 0;
4054   }
4055 
4056   if (!DRE)
4057     return S.Diag(Arg->getLocStart(),
4058                   diag::err_template_arg_not_pointer_to_member_form)
4059       << Arg->getSourceRange();
4060 
4061   if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
4062     assert((isa<FieldDecl>(DRE->getDecl()) ||
4063             !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4064            "Only non-static member pointers can make it here");
4065 
4066     // Okay: this is the address of a non-static member, and therefore
4067     // a member pointer constant.
4068     if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4069       Converted = TemplateArgument(Arg);
4070     } else {
4071       ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
4072       Converted = TemplateArgument(D, /*isReferenceParam*/false);
4073     }
4074     return Invalid;
4075   }
4076 
4077   // We found something else, but we don't know specifically what it is.
4078   S.Diag(Arg->getLocStart(),
4079          diag::err_template_arg_not_pointer_to_member_form)
4080     << Arg->getSourceRange();
4081   S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4082   return true;
4083 }
4084 
4085 /// \brief Check a template argument against its corresponding
4086 /// non-type template parameter.
4087 ///
4088 /// This routine implements the semantics of C++ [temp.arg.nontype].
4089 /// If an error occurred, it returns ExprError(); otherwise, it
4090 /// returns the converted template argument. \p
4091 /// InstantiatedParamType is the type of the non-type template
4092 /// parameter after it has been instantiated.
4093 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
4094                                        QualType InstantiatedParamType, Expr *Arg,
4095                                        TemplateArgument &Converted,
4096                                        CheckTemplateArgumentKind CTAK) {
4097   SourceLocation StartLoc = Arg->getLocStart();
4098 
4099   // If either the parameter has a dependent type or the argument is
4100   // type-dependent, there's nothing we can check now.
4101   if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
4102     // FIXME: Produce a cloned, canonical expression?
4103     Converted = TemplateArgument(Arg);
4104     return Owned(Arg);
4105   }
4106 
4107   // C++ [temp.arg.nontype]p5:
4108   //   The following conversions are performed on each expression used
4109   //   as a non-type template-argument. If a non-type
4110   //   template-argument cannot be converted to the type of the
4111   //   corresponding template-parameter then the program is
4112   //   ill-formed.
4113   QualType ParamType = InstantiatedParamType;
4114   if (ParamType->isIntegralOrEnumerationType()) {
4115     // C++11:
4116     //   -- for a non-type template-parameter of integral or
4117     //      enumeration type, conversions permitted in a converted
4118     //      constant expression are applied.
4119     //
4120     // C++98:
4121     //   -- for a non-type template-parameter of integral or
4122     //      enumeration type, integral promotions (4.5) and integral
4123     //      conversions (4.7) are applied.
4124 
4125     if (CTAK == CTAK_Deduced &&
4126         !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4127       // C++ [temp.deduct.type]p17:
4128       //   If, in the declaration of a function template with a non-type
4129       //   template-parameter, the non-type template-parameter is used
4130       //   in an expression in the function parameter-list and, if the
4131       //   corresponding template-argument is deduced, the
4132       //   template-argument type shall match the type of the
4133       //   template-parameter exactly, except that a template-argument
4134       //   deduced from an array bound may be of any integral type.
4135       Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4136         << Arg->getType().getUnqualifiedType()
4137         << ParamType.getUnqualifiedType();
4138       Diag(Param->getLocation(), diag::note_template_param_here);
4139       return ExprError();
4140     }
4141 
4142     if (getLangOpts().CPlusPlus11) {
4143       // We can't check arbitrary value-dependent arguments.
4144       // FIXME: If there's no viable conversion to the template parameter type,
4145       // we should be able to diagnose that prior to instantiation.
4146       if (Arg->isValueDependent()) {
4147         Converted = TemplateArgument(Arg);
4148         return Owned(Arg);
4149       }
4150 
4151       // C++ [temp.arg.nontype]p1:
4152       //   A template-argument for a non-type, non-template template-parameter
4153       //   shall be one of:
4154       //
4155       //     -- for a non-type template-parameter of integral or enumeration
4156       //        type, a converted constant expression of the type of the
4157       //        template-parameter; or
4158       llvm::APSInt Value;
4159       ExprResult ArgResult =
4160         CheckConvertedConstantExpression(Arg, ParamType, Value,
4161                                          CCEK_TemplateArg);
4162       if (ArgResult.isInvalid())
4163         return ExprError();
4164 
4165       // Widen the argument value to sizeof(parameter type). This is almost
4166       // always a no-op, except when the parameter type is bool. In
4167       // that case, this may extend the argument from 1 bit to 8 bits.
4168       QualType IntegerType = ParamType;
4169       if (const EnumType *Enum = IntegerType->getAs<EnumType>())
4170         IntegerType = Enum->getDecl()->getIntegerType();
4171       Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
4172 
4173       Converted = TemplateArgument(Context, Value,
4174                                    Context.getCanonicalType(ParamType));
4175       return ArgResult;
4176     }
4177 
4178     ExprResult ArgResult = DefaultLvalueConversion(Arg);
4179     if (ArgResult.isInvalid())
4180       return ExprError();
4181     Arg = ArgResult.take();
4182 
4183     QualType ArgType = Arg->getType();
4184 
4185     // C++ [temp.arg.nontype]p1:
4186     //   A template-argument for a non-type, non-template
4187     //   template-parameter shall be one of:
4188     //
4189     //     -- an integral constant-expression of integral or enumeration
4190     //        type; or
4191     //     -- the name of a non-type template-parameter; or
4192     SourceLocation NonConstantLoc;
4193     llvm::APSInt Value;
4194     if (!ArgType->isIntegralOrEnumerationType()) {
4195       Diag(Arg->getLocStart(),
4196            diag::err_template_arg_not_integral_or_enumeral)
4197         << ArgType << Arg->getSourceRange();
4198       Diag(Param->getLocation(), diag::note_template_param_here);
4199       return ExprError();
4200     } else if (!Arg->isValueDependent()) {
4201       class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
4202         QualType T;
4203 
4204       public:
4205         TmplArgICEDiagnoser(QualType T) : T(T) { }
4206 
4207         virtual void diagnoseNotICE(Sema &S, SourceLocation Loc,
4208                                     SourceRange SR) {
4209           S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
4210         }
4211       } Diagnoser(ArgType);
4212 
4213       Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
4214                                             false).take();
4215       if (!Arg)
4216         return ExprError();
4217     }
4218 
4219     // From here on out, all we care about are the unqualified forms
4220     // of the parameter and argument types.
4221     ParamType = ParamType.getUnqualifiedType();
4222     ArgType = ArgType.getUnqualifiedType();
4223 
4224     // Try to convert the argument to the parameter's type.
4225     if (Context.hasSameType(ParamType, ArgType)) {
4226       // Okay: no conversion necessary
4227     } else if (ParamType->isBooleanType()) {
4228       // This is an integral-to-boolean conversion.
4229       Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).take();
4230     } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
4231                !ParamType->isEnumeralType()) {
4232       // This is an integral promotion or conversion.
4233       Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).take();
4234     } else {
4235       // We can't perform this conversion.
4236       Diag(Arg->getLocStart(),
4237            diag::err_template_arg_not_convertible)
4238         << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
4239       Diag(Param->getLocation(), diag::note_template_param_here);
4240       return ExprError();
4241     }
4242 
4243     // Add the value of this argument to the list of converted
4244     // arguments. We use the bitwidth and signedness of the template
4245     // parameter.
4246     if (Arg->isValueDependent()) {
4247       // The argument is value-dependent. Create a new
4248       // TemplateArgument with the converted expression.
4249       Converted = TemplateArgument(Arg);
4250       return Owned(Arg);
4251     }
4252 
4253     QualType IntegerType = Context.getCanonicalType(ParamType);
4254     if (const EnumType *Enum = IntegerType->getAs<EnumType>())
4255       IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
4256 
4257     if (ParamType->isBooleanType()) {
4258       // Value must be zero or one.
4259       Value = Value != 0;
4260       unsigned AllowedBits = Context.getTypeSize(IntegerType);
4261       if (Value.getBitWidth() != AllowedBits)
4262         Value = Value.extOrTrunc(AllowedBits);
4263       Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
4264     } else {
4265       llvm::APSInt OldValue = Value;
4266 
4267       // Coerce the template argument's value to the value it will have
4268       // based on the template parameter's type.
4269       unsigned AllowedBits = Context.getTypeSize(IntegerType);
4270       if (Value.getBitWidth() != AllowedBits)
4271         Value = Value.extOrTrunc(AllowedBits);
4272       Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
4273 
4274       // Complain if an unsigned parameter received a negative value.
4275       if (IntegerType->isUnsignedIntegerOrEnumerationType()
4276                && (OldValue.isSigned() && OldValue.isNegative())) {
4277         Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
4278           << OldValue.toString(10) << Value.toString(10) << Param->getType()
4279           << Arg->getSourceRange();
4280         Diag(Param->getLocation(), diag::note_template_param_here);
4281       }
4282 
4283       // Complain if we overflowed the template parameter's type.
4284       unsigned RequiredBits;
4285       if (IntegerType->isUnsignedIntegerOrEnumerationType())
4286         RequiredBits = OldValue.getActiveBits();
4287       else if (OldValue.isUnsigned())
4288         RequiredBits = OldValue.getActiveBits() + 1;
4289       else
4290         RequiredBits = OldValue.getMinSignedBits();
4291       if (RequiredBits > AllowedBits) {
4292         Diag(Arg->getLocStart(),
4293              diag::warn_template_arg_too_large)
4294           << OldValue.toString(10) << Value.toString(10) << Param->getType()
4295           << Arg->getSourceRange();
4296         Diag(Param->getLocation(), diag::note_template_param_here);
4297       }
4298     }
4299 
4300     Converted = TemplateArgument(Context, Value,
4301                                  ParamType->isEnumeralType()
4302                                    ? Context.getCanonicalType(ParamType)
4303                                    : IntegerType);
4304     return Owned(Arg);
4305   }
4306 
4307   QualType ArgType = Arg->getType();
4308   DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
4309 
4310   // Handle pointer-to-function, reference-to-function, and
4311   // pointer-to-member-function all in (roughly) the same way.
4312   if (// -- For a non-type template-parameter of type pointer to
4313       //    function, only the function-to-pointer conversion (4.3) is
4314       //    applied. If the template-argument represents a set of
4315       //    overloaded functions (or a pointer to such), the matching
4316       //    function is selected from the set (13.4).
4317       (ParamType->isPointerType() &&
4318        ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
4319       // -- For a non-type template-parameter of type reference to
4320       //    function, no conversions apply. If the template-argument
4321       //    represents a set of overloaded functions, the matching
4322       //    function is selected from the set (13.4).
4323       (ParamType->isReferenceType() &&
4324        ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
4325       // -- For a non-type template-parameter of type pointer to
4326       //    member function, no conversions apply. If the
4327       //    template-argument represents a set of overloaded member
4328       //    functions, the matching member function is selected from
4329       //    the set (13.4).
4330       (ParamType->isMemberPointerType() &&
4331        ParamType->getAs<MemberPointerType>()->getPointeeType()
4332          ->isFunctionType())) {
4333 
4334     if (Arg->getType() == Context.OverloadTy) {
4335       if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
4336                                                                 true,
4337                                                                 FoundResult)) {
4338         if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
4339           return ExprError();
4340 
4341         Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
4342         ArgType = Arg->getType();
4343       } else
4344         return ExprError();
4345     }
4346 
4347     if (!ParamType->isMemberPointerType()) {
4348       if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
4349                                                          ParamType,
4350                                                          Arg, Converted))
4351         return ExprError();
4352       return Owned(Arg);
4353     }
4354 
4355     if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
4356                                              Converted))
4357       return ExprError();
4358     return Owned(Arg);
4359   }
4360 
4361   if (ParamType->isPointerType()) {
4362     //   -- for a non-type template-parameter of type pointer to
4363     //      object, qualification conversions (4.4) and the
4364     //      array-to-pointer conversion (4.2) are applied.
4365     // C++0x also allows a value of std::nullptr_t.
4366     assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
4367            "Only object pointers allowed here");
4368 
4369     if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
4370                                                        ParamType,
4371                                                        Arg, Converted))
4372       return ExprError();
4373     return Owned(Arg);
4374   }
4375 
4376   if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
4377     //   -- For a non-type template-parameter of type reference to
4378     //      object, no conversions apply. The type referred to by the
4379     //      reference may be more cv-qualified than the (otherwise
4380     //      identical) type of the template-argument. The
4381     //      template-parameter is bound directly to the
4382     //      template-argument, which must be an lvalue.
4383     assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
4384            "Only object references allowed here");
4385 
4386     if (Arg->getType() == Context.OverloadTy) {
4387       if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
4388                                                  ParamRefType->getPointeeType(),
4389                                                                 true,
4390                                                                 FoundResult)) {
4391         if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
4392           return ExprError();
4393 
4394         Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
4395         ArgType = Arg->getType();
4396       } else
4397         return ExprError();
4398     }
4399 
4400     if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
4401                                                        ParamType,
4402                                                        Arg, Converted))
4403       return ExprError();
4404     return Owned(Arg);
4405   }
4406 
4407   // Deal with parameters of type std::nullptr_t.
4408   if (ParamType->isNullPtrType()) {
4409     if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4410       Converted = TemplateArgument(Arg);
4411       return Owned(Arg);
4412     }
4413 
4414     switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
4415     case NPV_NotNullPointer:
4416       Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
4417         << Arg->getType() << ParamType;
4418       Diag(Param->getLocation(), diag::note_template_param_here);
4419       return ExprError();
4420 
4421     case NPV_Error:
4422       return ExprError();
4423 
4424     case NPV_NullPointer:
4425       Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
4426       Converted = TemplateArgument(ParamType, /*isNullPtr*/true);
4427       return Owned(Arg);
4428     }
4429   }
4430 
4431   //     -- For a non-type template-parameter of type pointer to data
4432   //        member, qualification conversions (4.4) are applied.
4433   assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
4434 
4435   if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
4436                                            Converted))
4437     return ExprError();
4438   return Owned(Arg);
4439 }
4440 
4441 /// \brief Check a template argument against its corresponding
4442 /// template template parameter.
4443 ///
4444 /// This routine implements the semantics of C++ [temp.arg.template].
4445 /// It returns true if an error occurred, and false otherwise.
4446 bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
4447                                  const TemplateArgumentLoc &Arg,
4448                                  unsigned ArgumentPackIndex) {
4449   TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
4450   TemplateDecl *Template = Name.getAsTemplateDecl();
4451   if (!Template) {
4452     // Any dependent template name is fine.
4453     assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
4454     return false;
4455   }
4456 
4457   // C++0x [temp.arg.template]p1:
4458   //   A template-argument for a template template-parameter shall be
4459   //   the name of a class template or an alias template, expressed as an
4460   //   id-expression. When the template-argument names a class template, only
4461   //   primary class templates are considered when matching the
4462   //   template template argument with the corresponding parameter;
4463   //   partial specializations are not considered even if their
4464   //   parameter lists match that of the template template parameter.
4465   //
4466   // Note that we also allow template template parameters here, which
4467   // will happen when we are dealing with, e.g., class template
4468   // partial specializations.
4469   if (!isa<ClassTemplateDecl>(Template) &&
4470       !isa<TemplateTemplateParmDecl>(Template) &&
4471       !isa<TypeAliasTemplateDecl>(Template)) {
4472     assert(isa<FunctionTemplateDecl>(Template) &&
4473            "Only function templates are possible here");
4474     Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
4475     Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
4476       << Template;
4477   }
4478 
4479   TemplateParameterList *Params = Param->getTemplateParameters();
4480   if (Param->isExpandedParameterPack())
4481     Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
4482 
4483   return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
4484                                          Params,
4485                                          true,
4486                                          TPL_TemplateTemplateArgumentMatch,
4487                                          Arg.getLocation());
4488 }
4489 
4490 /// \brief Given a non-type template argument that refers to a
4491 /// declaration and the type of its corresponding non-type template
4492 /// parameter, produce an expression that properly refers to that
4493 /// declaration.
4494 ExprResult
4495 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
4496                                               QualType ParamType,
4497                                               SourceLocation Loc) {
4498   // C++ [temp.param]p8:
4499   //
4500   //   A non-type template-parameter of type "array of T" or
4501   //   "function returning T" is adjusted to be of type "pointer to
4502   //   T" or "pointer to function returning T", respectively.
4503   if (ParamType->isArrayType())
4504     ParamType = Context.getArrayDecayedType(ParamType);
4505   else if (ParamType->isFunctionType())
4506     ParamType = Context.getPointerType(ParamType);
4507 
4508   // For a NULL non-type template argument, return nullptr casted to the
4509   // parameter's type.
4510   if (Arg.getKind() == TemplateArgument::NullPtr) {
4511     return ImpCastExprToType(
4512              new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
4513                              ParamType,
4514                              ParamType->getAs<MemberPointerType>()
4515                                ? CK_NullToMemberPointer
4516                                : CK_NullToPointer);
4517   }
4518   assert(Arg.getKind() == TemplateArgument::Declaration &&
4519          "Only declaration template arguments permitted here");
4520 
4521   ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
4522 
4523   if (VD->getDeclContext()->isRecord() &&
4524       (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
4525     // If the value is a class member, we might have a pointer-to-member.
4526     // Determine whether the non-type template template parameter is of
4527     // pointer-to-member type. If so, we need to build an appropriate
4528     // expression for a pointer-to-member, since a "normal" DeclRefExpr
4529     // would refer to the member itself.
4530     if (ParamType->isMemberPointerType()) {
4531       QualType ClassType
4532         = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
4533       NestedNameSpecifier *Qualifier
4534         = NestedNameSpecifier::Create(Context, 0, false,
4535                                       ClassType.getTypePtr());
4536       CXXScopeSpec SS;
4537       SS.MakeTrivial(Context, Qualifier, Loc);
4538 
4539       // The actual value-ness of this is unimportant, but for
4540       // internal consistency's sake, references to instance methods
4541       // are r-values.
4542       ExprValueKind VK = VK_LValue;
4543       if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
4544         VK = VK_RValue;
4545 
4546       ExprResult RefExpr = BuildDeclRefExpr(VD,
4547                                             VD->getType().getNonReferenceType(),
4548                                             VK,
4549                                             Loc,
4550                                             &SS);
4551       if (RefExpr.isInvalid())
4552         return ExprError();
4553 
4554       RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
4555 
4556       // We might need to perform a trailing qualification conversion, since
4557       // the element type on the parameter could be more qualified than the
4558       // element type in the expression we constructed.
4559       bool ObjCLifetimeConversion;
4560       if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
4561                                     ParamType.getUnqualifiedType(), false,
4562                                     ObjCLifetimeConversion))
4563         RefExpr = ImpCastExprToType(RefExpr.take(), ParamType.getUnqualifiedType(), CK_NoOp);
4564 
4565       assert(!RefExpr.isInvalid() &&
4566              Context.hasSameType(((Expr*) RefExpr.get())->getType(),
4567                                  ParamType.getUnqualifiedType()));
4568       return RefExpr;
4569     }
4570   }
4571 
4572   QualType T = VD->getType().getNonReferenceType();
4573 
4574   if (ParamType->isPointerType()) {
4575     // When the non-type template parameter is a pointer, take the
4576     // address of the declaration.
4577     ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
4578     if (RefExpr.isInvalid())
4579       return ExprError();
4580 
4581     if (T->isFunctionType() || T->isArrayType()) {
4582       // Decay functions and arrays.
4583       RefExpr = DefaultFunctionArrayConversion(RefExpr.take());
4584       if (RefExpr.isInvalid())
4585         return ExprError();
4586 
4587       return RefExpr;
4588     }
4589 
4590     // Take the address of everything else
4591     return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
4592   }
4593 
4594   ExprValueKind VK = VK_RValue;
4595 
4596   // If the non-type template parameter has reference type, qualify the
4597   // resulting declaration reference with the extra qualifiers on the
4598   // type that the reference refers to.
4599   if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
4600     VK = VK_LValue;
4601     T = Context.getQualifiedType(T,
4602                               TargetRef->getPointeeType().getQualifiers());
4603   } else if (isa<FunctionDecl>(VD)) {
4604     // References to functions are always lvalues.
4605     VK = VK_LValue;
4606   }
4607 
4608   return BuildDeclRefExpr(VD, T, VK, Loc);
4609 }
4610 
4611 /// \brief Construct a new expression that refers to the given
4612 /// integral template argument with the given source-location
4613 /// information.
4614 ///
4615 /// This routine takes care of the mapping from an integral template
4616 /// argument (which may have any integral type) to the appropriate
4617 /// literal value.
4618 ExprResult
4619 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
4620                                                   SourceLocation Loc) {
4621   assert(Arg.getKind() == TemplateArgument::Integral &&
4622          "Operation is only valid for integral template arguments");
4623   QualType OrigT = Arg.getIntegralType();
4624 
4625   // If this is an enum type that we're instantiating, we need to use an integer
4626   // type the same size as the enumerator.  We don't want to build an
4627   // IntegerLiteral with enum type.  The integer type of an enum type can be of
4628   // any integral type with C++11 enum classes, make sure we create the right
4629   // type of literal for it.
4630   QualType T = OrigT;
4631   if (const EnumType *ET = OrigT->getAs<EnumType>())
4632     T = ET->getDecl()->getIntegerType();
4633 
4634   Expr *E;
4635   if (T->isAnyCharacterType()) {
4636     CharacterLiteral::CharacterKind Kind;
4637     if (T->isWideCharType())
4638       Kind = CharacterLiteral::Wide;
4639     else if (T->isChar16Type())
4640       Kind = CharacterLiteral::UTF16;
4641     else if (T->isChar32Type())
4642       Kind = CharacterLiteral::UTF32;
4643     else
4644       Kind = CharacterLiteral::Ascii;
4645 
4646     E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
4647                                        Kind, T, Loc);
4648   } else if (T->isBooleanType()) {
4649     E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
4650                                          T, Loc);
4651   } else if (T->isNullPtrType()) {
4652     E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
4653   } else {
4654     E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
4655   }
4656 
4657   if (OrigT->isEnumeralType()) {
4658     // FIXME: This is a hack. We need a better way to handle substituted
4659     // non-type template parameters.
4660     E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E, 0,
4661                                Context.getTrivialTypeSourceInfo(OrigT, Loc),
4662                                Loc, Loc);
4663   }
4664 
4665   return Owned(E);
4666 }
4667 
4668 /// \brief Match two template parameters within template parameter lists.
4669 static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
4670                                        bool Complain,
4671                                      Sema::TemplateParameterListEqualKind Kind,
4672                                        SourceLocation TemplateArgLoc) {
4673   // Check the actual kind (type, non-type, template).
4674   if (Old->getKind() != New->getKind()) {
4675     if (Complain) {
4676       unsigned NextDiag = diag::err_template_param_different_kind;
4677       if (TemplateArgLoc.isValid()) {
4678         S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
4679         NextDiag = diag::note_template_param_different_kind;
4680       }
4681       S.Diag(New->getLocation(), NextDiag)
4682         << (Kind != Sema::TPL_TemplateMatch);
4683       S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
4684         << (Kind != Sema::TPL_TemplateMatch);
4685     }
4686 
4687     return false;
4688   }
4689 
4690   // Check that both are parameter packs are neither are parameter packs.
4691   // However, if we are matching a template template argument to a
4692   // template template parameter, the template template parameter can have
4693   // a parameter pack where the template template argument does not.
4694   if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
4695       !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
4696         Old->isTemplateParameterPack())) {
4697     if (Complain) {
4698       unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
4699       if (TemplateArgLoc.isValid()) {
4700         S.Diag(TemplateArgLoc,
4701              diag::err_template_arg_template_params_mismatch);
4702         NextDiag = diag::note_template_parameter_pack_non_pack;
4703       }
4704 
4705       unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
4706                       : isa<NonTypeTemplateParmDecl>(New)? 1
4707                       : 2;
4708       S.Diag(New->getLocation(), NextDiag)
4709         << ParamKind << New->isParameterPack();
4710       S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
4711         << ParamKind << Old->isParameterPack();
4712     }
4713 
4714     return false;
4715   }
4716 
4717   // For non-type template parameters, check the type of the parameter.
4718   if (NonTypeTemplateParmDecl *OldNTTP
4719                                     = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
4720     NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
4721 
4722     // If we are matching a template template argument to a template
4723     // template parameter and one of the non-type template parameter types
4724     // is dependent, then we must wait until template instantiation time
4725     // to actually compare the arguments.
4726     if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
4727         (OldNTTP->getType()->isDependentType() ||
4728          NewNTTP->getType()->isDependentType()))
4729       return true;
4730 
4731     if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
4732       if (Complain) {
4733         unsigned NextDiag = diag::err_template_nontype_parm_different_type;
4734         if (TemplateArgLoc.isValid()) {
4735           S.Diag(TemplateArgLoc,
4736                  diag::err_template_arg_template_params_mismatch);
4737           NextDiag = diag::note_template_nontype_parm_different_type;
4738         }
4739         S.Diag(NewNTTP->getLocation(), NextDiag)
4740           << NewNTTP->getType()
4741           << (Kind != Sema::TPL_TemplateMatch);
4742         S.Diag(OldNTTP->getLocation(),
4743                diag::note_template_nontype_parm_prev_declaration)
4744           << OldNTTP->getType();
4745       }
4746 
4747       return false;
4748     }
4749 
4750     return true;
4751   }
4752 
4753   // For template template parameters, check the template parameter types.
4754   // The template parameter lists of template template
4755   // parameters must agree.
4756   if (TemplateTemplateParmDecl *OldTTP
4757                                     = dyn_cast<TemplateTemplateParmDecl>(Old)) {
4758     TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
4759     return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
4760                                             OldTTP->getTemplateParameters(),
4761                                             Complain,
4762                                         (Kind == Sema::TPL_TemplateMatch
4763                                            ? Sema::TPL_TemplateTemplateParmMatch
4764                                            : Kind),
4765                                             TemplateArgLoc);
4766   }
4767 
4768   return true;
4769 }
4770 
4771 /// \brief Diagnose a known arity mismatch when comparing template argument
4772 /// lists.
4773 static
4774 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
4775                                                 TemplateParameterList *New,
4776                                                 TemplateParameterList *Old,
4777                                       Sema::TemplateParameterListEqualKind Kind,
4778                                                 SourceLocation TemplateArgLoc) {
4779   unsigned NextDiag = diag::err_template_param_list_different_arity;
4780   if (TemplateArgLoc.isValid()) {
4781     S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
4782     NextDiag = diag::note_template_param_list_different_arity;
4783   }
4784   S.Diag(New->getTemplateLoc(), NextDiag)
4785     << (New->size() > Old->size())
4786     << (Kind != Sema::TPL_TemplateMatch)
4787     << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
4788   S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
4789     << (Kind != Sema::TPL_TemplateMatch)
4790     << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
4791 }
4792 
4793 /// \brief Determine whether the given template parameter lists are
4794 /// equivalent.
4795 ///
4796 /// \param New  The new template parameter list, typically written in the
4797 /// source code as part of a new template declaration.
4798 ///
4799 /// \param Old  The old template parameter list, typically found via
4800 /// name lookup of the template declared with this template parameter
4801 /// list.
4802 ///
4803 /// \param Complain  If true, this routine will produce a diagnostic if
4804 /// the template parameter lists are not equivalent.
4805 ///
4806 /// \param Kind describes how we are to match the template parameter lists.
4807 ///
4808 /// \param TemplateArgLoc If this source location is valid, then we
4809 /// are actually checking the template parameter list of a template
4810 /// argument (New) against the template parameter list of its
4811 /// corresponding template template parameter (Old). We produce
4812 /// slightly different diagnostics in this scenario.
4813 ///
4814 /// \returns True if the template parameter lists are equal, false
4815 /// otherwise.
4816 bool
4817 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
4818                                      TemplateParameterList *Old,
4819                                      bool Complain,
4820                                      TemplateParameterListEqualKind Kind,
4821                                      SourceLocation TemplateArgLoc) {
4822   if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
4823     if (Complain)
4824       DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
4825                                                  TemplateArgLoc);
4826 
4827     return false;
4828   }
4829 
4830   // C++0x [temp.arg.template]p3:
4831   //   A template-argument matches a template template-parameter (call it P)
4832   //   when each of the template parameters in the template-parameter-list of
4833   //   the template-argument's corresponding class template or alias template
4834   //   (call it A) matches the corresponding template parameter in the
4835   //   template-parameter-list of P. [...]
4836   TemplateParameterList::iterator NewParm = New->begin();
4837   TemplateParameterList::iterator NewParmEnd = New->end();
4838   for (TemplateParameterList::iterator OldParm = Old->begin(),
4839                                     OldParmEnd = Old->end();
4840        OldParm != OldParmEnd; ++OldParm) {
4841     if (Kind != TPL_TemplateTemplateArgumentMatch ||
4842         !(*OldParm)->isTemplateParameterPack()) {
4843       if (NewParm == NewParmEnd) {
4844         if (Complain)
4845           DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
4846                                                      TemplateArgLoc);
4847 
4848         return false;
4849       }
4850 
4851       if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
4852                                       Kind, TemplateArgLoc))
4853         return false;
4854 
4855       ++NewParm;
4856       continue;
4857     }
4858 
4859     // C++0x [temp.arg.template]p3:
4860     //   [...] When P's template- parameter-list contains a template parameter
4861     //   pack (14.5.3), the template parameter pack will match zero or more
4862     //   template parameters or template parameter packs in the
4863     //   template-parameter-list of A with the same type and form as the
4864     //   template parameter pack in P (ignoring whether those template
4865     //   parameters are template parameter packs).
4866     for (; NewParm != NewParmEnd; ++NewParm) {
4867       if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
4868                                       Kind, TemplateArgLoc))
4869         return false;
4870     }
4871   }
4872 
4873   // Make sure we exhausted all of the arguments.
4874   if (NewParm != NewParmEnd) {
4875     if (Complain)
4876       DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
4877                                                  TemplateArgLoc);
4878 
4879     return false;
4880   }
4881 
4882   return true;
4883 }
4884 
4885 /// \brief Check whether a template can be declared within this scope.
4886 ///
4887 /// If the template declaration is valid in this scope, returns
4888 /// false. Otherwise, issues a diagnostic and returns true.
4889 bool
4890 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
4891   if (!S)
4892     return false;
4893 
4894   // Find the nearest enclosing declaration scope.
4895   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4896          (S->getFlags() & Scope::TemplateParamScope) != 0)
4897     S = S->getParent();
4898 
4899   // C++ [temp]p2:
4900   //   A template-declaration can appear only as a namespace scope or
4901   //   class scope declaration.
4902   DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
4903   if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
4904       cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
4905     return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
4906              << TemplateParams->getSourceRange();
4907 
4908   while (Ctx && isa<LinkageSpecDecl>(Ctx))
4909     Ctx = Ctx->getParent();
4910 
4911   if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
4912     return false;
4913 
4914   return Diag(TemplateParams->getTemplateLoc(),
4915               diag::err_template_outside_namespace_or_class_scope)
4916     << TemplateParams->getSourceRange();
4917 }
4918 
4919 /// \brief Determine what kind of template specialization the given declaration
4920 /// is.
4921 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
4922   if (!D)
4923     return TSK_Undeclared;
4924 
4925   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
4926     return Record->getTemplateSpecializationKind();
4927   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
4928     return Function->getTemplateSpecializationKind();
4929   if (VarDecl *Var = dyn_cast<VarDecl>(D))
4930     return Var->getTemplateSpecializationKind();
4931 
4932   return TSK_Undeclared;
4933 }
4934 
4935 /// \brief Check whether a specialization is well-formed in the current
4936 /// context.
4937 ///
4938 /// This routine determines whether a template specialization can be declared
4939 /// in the current context (C++ [temp.expl.spec]p2).
4940 ///
4941 /// \param S the semantic analysis object for which this check is being
4942 /// performed.
4943 ///
4944 /// \param Specialized the entity being specialized or instantiated, which
4945 /// may be a kind of template (class template, function template, etc.) or
4946 /// a member of a class template (member function, static data member,
4947 /// member class).
4948 ///
4949 /// \param PrevDecl the previous declaration of this entity, if any.
4950 ///
4951 /// \param Loc the location of the explicit specialization or instantiation of
4952 /// this entity.
4953 ///
4954 /// \param IsPartialSpecialization whether this is a partial specialization of
4955 /// a class template.
4956 ///
4957 /// \returns true if there was an error that we cannot recover from, false
4958 /// otherwise.
4959 static bool CheckTemplateSpecializationScope(Sema &S,
4960                                              NamedDecl *Specialized,
4961                                              NamedDecl *PrevDecl,
4962                                              SourceLocation Loc,
4963                                              bool IsPartialSpecialization) {
4964   // Keep these "kind" numbers in sync with the %select statements in the
4965   // various diagnostics emitted by this routine.
4966   int EntityKind = 0;
4967   if (isa<ClassTemplateDecl>(Specialized))
4968     EntityKind = IsPartialSpecialization? 1 : 0;
4969   else if (isa<FunctionTemplateDecl>(Specialized))
4970     EntityKind = 2;
4971   else if (isa<CXXMethodDecl>(Specialized))
4972     EntityKind = 3;
4973   else if (isa<VarDecl>(Specialized))
4974     EntityKind = 4;
4975   else if (isa<RecordDecl>(Specialized))
4976     EntityKind = 5;
4977   else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
4978     EntityKind = 6;
4979   else {
4980     S.Diag(Loc, diag::err_template_spec_unknown_kind)
4981       << S.getLangOpts().CPlusPlus11;
4982     S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
4983     return true;
4984   }
4985 
4986   // C++ [temp.expl.spec]p2:
4987   //   An explicit specialization shall be declared in the namespace
4988   //   of which the template is a member, or, for member templates, in
4989   //   the namespace of which the enclosing class or enclosing class
4990   //   template is a member. An explicit specialization of a member
4991   //   function, member class or static data member of a class
4992   //   template shall be declared in the namespace of which the class
4993   //   template is a member. Such a declaration may also be a
4994   //   definition. If the declaration is not a definition, the
4995   //   specialization may be defined later in the name- space in which
4996   //   the explicit specialization was declared, or in a namespace
4997   //   that encloses the one in which the explicit specialization was
4998   //   declared.
4999   if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
5000     S.Diag(Loc, diag::err_template_spec_decl_function_scope)
5001       << Specialized;
5002     return true;
5003   }
5004 
5005   if (S.CurContext->isRecord() && !IsPartialSpecialization) {
5006     if (S.getLangOpts().MicrosoftExt) {
5007       // Do not warn for class scope explicit specialization during
5008       // instantiation, warning was already emitted during pattern
5009       // semantic analysis.
5010       if (!S.ActiveTemplateInstantiations.size())
5011         S.Diag(Loc, diag::ext_function_specialization_in_class)
5012           << Specialized;
5013     } else {
5014       S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5015         << Specialized;
5016       return true;
5017     }
5018   }
5019 
5020   if (S.CurContext->isRecord() &&
5021       !S.CurContext->Equals(Specialized->getDeclContext())) {
5022     // Make sure that we're specializing in the right record context.
5023     // Otherwise, things can go horribly wrong.
5024     S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5025       << Specialized;
5026     return true;
5027   }
5028 
5029   // C++ [temp.class.spec]p6:
5030   //   A class template partial specialization may be declared or redeclared
5031   //   in any namespace scope in which its definition may be defined (14.5.1
5032   //   and 14.5.2).
5033   bool ComplainedAboutScope = false;
5034   DeclContext *SpecializedContext
5035     = Specialized->getDeclContext()->getEnclosingNamespaceContext();
5036   DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
5037   if ((!PrevDecl ||
5038        getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5039        getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
5040     // C++ [temp.exp.spec]p2:
5041     //   An explicit specialization shall be declared in the namespace of which
5042     //   the template is a member, or, for member templates, in the namespace
5043     //   of which the enclosing class or enclosing class template is a member.
5044     //   An explicit specialization of a member function, member class or
5045     //   static data member of a class template shall be declared in the
5046     //   namespace of which the class template is a member.
5047     //
5048     // C++0x [temp.expl.spec]p2:
5049     //   An explicit specialization shall be declared in a namespace enclosing
5050     //   the specialized template.
5051     if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
5052       bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
5053       if (isa<TranslationUnitDecl>(SpecializedContext)) {
5054         assert(!IsCPlusPlus11Extension &&
5055                "DC encloses TU but isn't in enclosing namespace set");
5056         S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
5057           << EntityKind << Specialized;
5058       } else if (isa<NamespaceDecl>(SpecializedContext)) {
5059         int Diag;
5060         if (!IsCPlusPlus11Extension)
5061           Diag = diag::err_template_spec_decl_out_of_scope;
5062         else if (!S.getLangOpts().CPlusPlus11)
5063           Diag = diag::ext_template_spec_decl_out_of_scope;
5064         else
5065           Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
5066         S.Diag(Loc, Diag)
5067           << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
5068       }
5069 
5070       S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5071       ComplainedAboutScope =
5072         !(IsCPlusPlus11Extension && S.getLangOpts().CPlusPlus11);
5073     }
5074   }
5075 
5076   // Make sure that this redeclaration (or definition) occurs in an enclosing
5077   // namespace.
5078   // Note that HandleDeclarator() performs this check for explicit
5079   // specializations of function templates, static data members, and member
5080   // functions, so we skip the check here for those kinds of entities.
5081   // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5082   // Should we refactor that check, so that it occurs later?
5083   if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
5084       !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
5085         isa<FunctionDecl>(Specialized))) {
5086     if (isa<TranslationUnitDecl>(SpecializedContext))
5087       S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5088         << EntityKind << Specialized;
5089     else if (isa<NamespaceDecl>(SpecializedContext))
5090       S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
5091         << EntityKind << Specialized
5092         << cast<NamedDecl>(SpecializedContext);
5093 
5094     S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5095   }
5096 
5097   // FIXME: check for specialization-after-instantiation errors and such.
5098 
5099   return false;
5100 }
5101 
5102 /// \brief Subroutine of Sema::CheckClassTemplatePartialSpecializationArgs
5103 /// that checks non-type template partial specialization arguments.
5104 static bool CheckNonTypeClassTemplatePartialSpecializationArgs(Sema &S,
5105                                                 NonTypeTemplateParmDecl *Param,
5106                                                   const TemplateArgument *Args,
5107                                                         unsigned NumArgs) {
5108   for (unsigned I = 0; I != NumArgs; ++I) {
5109     if (Args[I].getKind() == TemplateArgument::Pack) {
5110       if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
5111                                                            Args[I].pack_begin(),
5112                                                            Args[I].pack_size()))
5113         return true;
5114 
5115       continue;
5116     }
5117 
5118     if (Args[I].getKind() != TemplateArgument::Expression)
5119       continue;
5120 
5121     Expr *ArgExpr = Args[I].getAsExpr();
5122 
5123     // We can have a pack expansion of any of the bullets below.
5124     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
5125       ArgExpr = Expansion->getPattern();
5126 
5127     // Strip off any implicit casts we added as part of type checking.
5128     while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
5129       ArgExpr = ICE->getSubExpr();
5130 
5131     // C++ [temp.class.spec]p8:
5132     //   A non-type argument is non-specialized if it is the name of a
5133     //   non-type parameter. All other non-type arguments are
5134     //   specialized.
5135     //
5136     // Below, we check the two conditions that only apply to
5137     // specialized non-type arguments, so skip any non-specialized
5138     // arguments.
5139     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
5140       if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
5141         continue;
5142 
5143     // C++ [temp.class.spec]p9:
5144     //   Within the argument list of a class template partial
5145     //   specialization, the following restrictions apply:
5146     //     -- A partially specialized non-type argument expression
5147     //        shall not involve a template parameter of the partial
5148     //        specialization except when the argument expression is a
5149     //        simple identifier.
5150     if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
5151       S.Diag(ArgExpr->getLocStart(),
5152            diag::err_dependent_non_type_arg_in_partial_spec)
5153         << ArgExpr->getSourceRange();
5154       return true;
5155     }
5156 
5157     //     -- The type of a template parameter corresponding to a
5158     //        specialized non-type argument shall not be dependent on a
5159     //        parameter of the specialization.
5160     if (Param->getType()->isDependentType()) {
5161       S.Diag(ArgExpr->getLocStart(),
5162            diag::err_dependent_typed_non_type_arg_in_partial_spec)
5163         << Param->getType()
5164         << ArgExpr->getSourceRange();
5165       S.Diag(Param->getLocation(), diag::note_template_param_here);
5166       return true;
5167     }
5168   }
5169 
5170   return false;
5171 }
5172 
5173 /// \brief Check the non-type template arguments of a class template
5174 /// partial specialization according to C++ [temp.class.spec]p9.
5175 ///
5176 /// \param TemplateParams the template parameters of the primary class
5177 /// template.
5178 ///
5179 /// \param TemplateArgs the template arguments of the class template
5180 /// partial specialization.
5181 ///
5182 /// \returns true if there was an error, false otherwise.
5183 static bool CheckClassTemplatePartialSpecializationArgs(Sema &S,
5184                                         TemplateParameterList *TemplateParams,
5185                        SmallVectorImpl<TemplateArgument> &TemplateArgs) {
5186   const TemplateArgument *ArgList = TemplateArgs.data();
5187 
5188   for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
5189     NonTypeTemplateParmDecl *Param
5190       = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
5191     if (!Param)
5192       continue;
5193 
5194     if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
5195                                                            &ArgList[I], 1))
5196       return true;
5197   }
5198 
5199   return false;
5200 }
5201 
5202 DeclResult
5203 Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
5204                                        TagUseKind TUK,
5205                                        SourceLocation KWLoc,
5206                                        SourceLocation ModulePrivateLoc,
5207                                        CXXScopeSpec &SS,
5208                                        TemplateTy TemplateD,
5209                                        SourceLocation TemplateNameLoc,
5210                                        SourceLocation LAngleLoc,
5211                                        ASTTemplateArgsPtr TemplateArgsIn,
5212                                        SourceLocation RAngleLoc,
5213                                        AttributeList *Attr,
5214                                MultiTemplateParamsArg TemplateParameterLists) {
5215   assert(TUK != TUK_Reference && "References are not specializations");
5216 
5217   // NOTE: KWLoc is the location of the tag keyword. This will instead
5218   // store the location of the outermost template keyword in the declaration.
5219   SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
5220     ? TemplateParameterLists[0]->getTemplateLoc() : SourceLocation();
5221 
5222   // Find the class template we're specializing
5223   TemplateName Name = TemplateD.getAsVal<TemplateName>();
5224   ClassTemplateDecl *ClassTemplate
5225     = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
5226 
5227   if (!ClassTemplate) {
5228     Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
5229       << (Name.getAsTemplateDecl() &&
5230           isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
5231     return true;
5232   }
5233 
5234   bool isExplicitSpecialization = false;
5235   bool isPartialSpecialization = false;
5236 
5237   // Check the validity of the template headers that introduce this
5238   // template.
5239   // FIXME: We probably shouldn't complain about these headers for
5240   // friend declarations.
5241   bool Invalid = false;
5242   TemplateParameterList *TemplateParams
5243     = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc,
5244                                               TemplateNameLoc,
5245                                               SS,
5246                                               TemplateParameterLists.data(),
5247                                               TemplateParameterLists.size(),
5248                                               TUK == TUK_Friend,
5249                                               isExplicitSpecialization,
5250                                               Invalid);
5251   if (Invalid)
5252     return true;
5253 
5254   if (TemplateParams && TemplateParams->size() > 0) {
5255     isPartialSpecialization = true;
5256 
5257     if (TUK == TUK_Friend) {
5258       Diag(KWLoc, diag::err_partial_specialization_friend)
5259         << SourceRange(LAngleLoc, RAngleLoc);
5260       return true;
5261     }
5262 
5263     // C++ [temp.class.spec]p10:
5264     //   The template parameter list of a specialization shall not
5265     //   contain default template argument values.
5266     for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
5267       Decl *Param = TemplateParams->getParam(I);
5268       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
5269         if (TTP->hasDefaultArgument()) {
5270           Diag(TTP->getDefaultArgumentLoc(),
5271                diag::err_default_arg_in_partial_spec);
5272           TTP->removeDefaultArgument();
5273         }
5274       } else if (NonTypeTemplateParmDecl *NTTP
5275                    = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5276         if (Expr *DefArg = NTTP->getDefaultArgument()) {
5277           Diag(NTTP->getDefaultArgumentLoc(),
5278                diag::err_default_arg_in_partial_spec)
5279             << DefArg->getSourceRange();
5280           NTTP->removeDefaultArgument();
5281         }
5282       } else {
5283         TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
5284         if (TTP->hasDefaultArgument()) {
5285           Diag(TTP->getDefaultArgument().getLocation(),
5286                diag::err_default_arg_in_partial_spec)
5287             << TTP->getDefaultArgument().getSourceRange();
5288           TTP->removeDefaultArgument();
5289         }
5290       }
5291     }
5292   } else if (TemplateParams) {
5293     if (TUK == TUK_Friend)
5294       Diag(KWLoc, diag::err_template_spec_friend)
5295         << FixItHint::CreateRemoval(
5296                                 SourceRange(TemplateParams->getTemplateLoc(),
5297                                             TemplateParams->getRAngleLoc()))
5298         << SourceRange(LAngleLoc, RAngleLoc);
5299     else
5300       isExplicitSpecialization = true;
5301   } else if (TUK != TUK_Friend) {
5302     Diag(KWLoc, diag::err_template_spec_needs_header)
5303       << FixItHint::CreateInsertion(KWLoc, "template<> ");
5304     TemplateKWLoc = KWLoc;
5305     isExplicitSpecialization = true;
5306   }
5307 
5308   // Check that the specialization uses the same tag kind as the
5309   // original template.
5310   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5311   assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
5312   if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
5313                                     Kind, TUK == TUK_Definition, KWLoc,
5314                                     *ClassTemplate->getIdentifier())) {
5315     Diag(KWLoc, diag::err_use_with_wrong_tag)
5316       << ClassTemplate
5317       << FixItHint::CreateReplacement(KWLoc,
5318                             ClassTemplate->getTemplatedDecl()->getKindName());
5319     Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
5320          diag::note_previous_use);
5321     Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
5322   }
5323 
5324   // Translate the parser's template argument list in our AST format.
5325   TemplateArgumentListInfo TemplateArgs;
5326   TemplateArgs.setLAngleLoc(LAngleLoc);
5327   TemplateArgs.setRAngleLoc(RAngleLoc);
5328   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
5329 
5330   // Check for unexpanded parameter packs in any of the template arguments.
5331   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
5332     if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
5333                                         UPPC_PartialSpecialization))
5334       return true;
5335 
5336   // Check that the template argument list is well-formed for this
5337   // template.
5338   SmallVector<TemplateArgument, 4> Converted;
5339   if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
5340                                 TemplateArgs, false, Converted))
5341     return true;
5342 
5343   // Find the class template (partial) specialization declaration that
5344   // corresponds to these arguments.
5345   if (isPartialSpecialization) {
5346     if (CheckClassTemplatePartialSpecializationArgs(*this,
5347                                          ClassTemplate->getTemplateParameters(),
5348                                          Converted))
5349       return true;
5350 
5351     bool InstantiationDependent;
5352     if (!Name.isDependent() &&
5353         !TemplateSpecializationType::anyDependentTemplateArguments(
5354                                              TemplateArgs.getArgumentArray(),
5355                                                          TemplateArgs.size(),
5356                                                      InstantiationDependent)) {
5357       Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
5358         << ClassTemplate->getDeclName();
5359       isPartialSpecialization = false;
5360     }
5361   }
5362 
5363   void *InsertPos = 0;
5364   ClassTemplateSpecializationDecl *PrevDecl = 0;
5365 
5366   if (isPartialSpecialization)
5367     // FIXME: Template parameter list matters, too
5368     PrevDecl
5369       = ClassTemplate->findPartialSpecialization(Converted.data(),
5370                                                  Converted.size(),
5371                                                  InsertPos);
5372   else
5373     PrevDecl
5374       = ClassTemplate->findSpecialization(Converted.data(),
5375                                           Converted.size(), InsertPos);
5376 
5377   ClassTemplateSpecializationDecl *Specialization = 0;
5378 
5379   // Check whether we can declare a class template specialization in
5380   // the current scope.
5381   if (TUK != TUK_Friend &&
5382       CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
5383                                        TemplateNameLoc,
5384                                        isPartialSpecialization))
5385     return true;
5386 
5387   // The canonical type
5388   QualType CanonType;
5389   if (PrevDecl &&
5390       (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
5391                TUK == TUK_Friend)) {
5392     // Since the only prior class template specialization with these
5393     // arguments was referenced but not declared, or we're only
5394     // referencing this specialization as a friend, reuse that
5395     // declaration node as our own, updating its source location and
5396     // the list of outer template parameters to reflect our new declaration.
5397     Specialization = PrevDecl;
5398     Specialization->setLocation(TemplateNameLoc);
5399     if (TemplateParameterLists.size() > 0) {
5400       Specialization->setTemplateParameterListsInfo(Context,
5401                                               TemplateParameterLists.size(),
5402                                               TemplateParameterLists.data());
5403     }
5404     PrevDecl = 0;
5405     CanonType = Context.getTypeDeclType(Specialization);
5406   } else if (isPartialSpecialization) {
5407     // Build the canonical type that describes the converted template
5408     // arguments of the class template partial specialization.
5409     TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
5410     CanonType = Context.getTemplateSpecializationType(CanonTemplate,
5411                                                       Converted.data(),
5412                                                       Converted.size());
5413 
5414     if (Context.hasSameType(CanonType,
5415                         ClassTemplate->getInjectedClassNameSpecialization())) {
5416       // C++ [temp.class.spec]p9b3:
5417       //
5418       //   -- The argument list of the specialization shall not be identical
5419       //      to the implicit argument list of the primary template.
5420       Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
5421         << (TUK == TUK_Definition)
5422         << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
5423       return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
5424                                 ClassTemplate->getIdentifier(),
5425                                 TemplateNameLoc,
5426                                 Attr,
5427                                 TemplateParams,
5428                                 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
5429                                 TemplateParameterLists.size() - 1,
5430                                 TemplateParameterLists.data());
5431     }
5432 
5433     // Create a new class template partial specialization declaration node.
5434     ClassTemplatePartialSpecializationDecl *PrevPartial
5435       = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
5436     unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
5437                             : ClassTemplate->getNextPartialSpecSequenceNumber();
5438     ClassTemplatePartialSpecializationDecl *Partial
5439       = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
5440                                              ClassTemplate->getDeclContext(),
5441                                                        KWLoc, TemplateNameLoc,
5442                                                        TemplateParams,
5443                                                        ClassTemplate,
5444                                                        Converted.data(),
5445                                                        Converted.size(),
5446                                                        TemplateArgs,
5447                                                        CanonType,
5448                                                        PrevPartial,
5449                                                        SequenceNumber);
5450     SetNestedNameSpecifier(Partial, SS);
5451     if (TemplateParameterLists.size() > 1 && SS.isSet()) {
5452       Partial->setTemplateParameterListsInfo(Context,
5453                                              TemplateParameterLists.size() - 1,
5454                                              TemplateParameterLists.data());
5455     }
5456 
5457     if (!PrevPartial)
5458       ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
5459     Specialization = Partial;
5460 
5461     // If we are providing an explicit specialization of a member class
5462     // template specialization, make a note of that.
5463     if (PrevPartial && PrevPartial->getInstantiatedFromMember())
5464       PrevPartial->setMemberSpecialization();
5465 
5466     // Check that all of the template parameters of the class template
5467     // partial specialization are deducible from the template
5468     // arguments. If not, this class template partial specialization
5469     // will never be used.
5470     llvm::SmallBitVector DeducibleParams(TemplateParams->size());
5471     MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
5472                                TemplateParams->getDepth(),
5473                                DeducibleParams);
5474 
5475     if (!DeducibleParams.all()) {
5476       unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
5477       Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
5478         << (NumNonDeducible > 1)
5479         << SourceRange(TemplateNameLoc, RAngleLoc);
5480       for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
5481         if (!DeducibleParams[I]) {
5482           NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
5483           if (Param->getDeclName())
5484             Diag(Param->getLocation(),
5485                  diag::note_partial_spec_unused_parameter)
5486               << Param->getDeclName();
5487           else
5488             Diag(Param->getLocation(),
5489                  diag::note_partial_spec_unused_parameter)
5490               << "<anonymous>";
5491         }
5492       }
5493     }
5494   } else {
5495     // Create a new class template specialization declaration node for
5496     // this explicit specialization or friend declaration.
5497     Specialization
5498       = ClassTemplateSpecializationDecl::Create(Context, Kind,
5499                                              ClassTemplate->getDeclContext(),
5500                                                 KWLoc, TemplateNameLoc,
5501                                                 ClassTemplate,
5502                                                 Converted.data(),
5503                                                 Converted.size(),
5504                                                 PrevDecl);
5505     SetNestedNameSpecifier(Specialization, SS);
5506     if (TemplateParameterLists.size() > 0) {
5507       Specialization->setTemplateParameterListsInfo(Context,
5508                                               TemplateParameterLists.size(),
5509                                               TemplateParameterLists.data());
5510     }
5511 
5512     if (!PrevDecl)
5513       ClassTemplate->AddSpecialization(Specialization, InsertPos);
5514 
5515     CanonType = Context.getTypeDeclType(Specialization);
5516   }
5517 
5518   // C++ [temp.expl.spec]p6:
5519   //   If a template, a member template or the member of a class template is
5520   //   explicitly specialized then that specialization shall be declared
5521   //   before the first use of that specialization that would cause an implicit
5522   //   instantiation to take place, in every translation unit in which such a
5523   //   use occurs; no diagnostic is required.
5524   if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
5525     bool Okay = false;
5526     for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
5527       // Is there any previous explicit specialization declaration?
5528       if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
5529         Okay = true;
5530         break;
5531       }
5532     }
5533 
5534     if (!Okay) {
5535       SourceRange Range(TemplateNameLoc, RAngleLoc);
5536       Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
5537         << Context.getTypeDeclType(Specialization) << Range;
5538 
5539       Diag(PrevDecl->getPointOfInstantiation(),
5540            diag::note_instantiation_required_here)
5541         << (PrevDecl->getTemplateSpecializationKind()
5542                                                 != TSK_ImplicitInstantiation);
5543       return true;
5544     }
5545   }
5546 
5547   // If this is not a friend, note that this is an explicit specialization.
5548   if (TUK != TUK_Friend)
5549     Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
5550 
5551   // Check that this isn't a redefinition of this specialization.
5552   if (TUK == TUK_Definition) {
5553     if (RecordDecl *Def = Specialization->getDefinition()) {
5554       SourceRange Range(TemplateNameLoc, RAngleLoc);
5555       Diag(TemplateNameLoc, diag::err_redefinition)
5556         << Context.getTypeDeclType(Specialization) << Range;
5557       Diag(Def->getLocation(), diag::note_previous_definition);
5558       Specialization->setInvalidDecl();
5559       return true;
5560     }
5561   }
5562 
5563   if (Attr)
5564     ProcessDeclAttributeList(S, Specialization, Attr);
5565 
5566   // Add alignment attributes if necessary; these attributes are checked when
5567   // the ASTContext lays out the structure.
5568   if (TUK == TUK_Definition) {
5569     AddAlignmentAttributesForRecord(Specialization);
5570     AddMsStructLayoutForRecord(Specialization);
5571   }
5572 
5573   if (ModulePrivateLoc.isValid())
5574     Diag(Specialization->getLocation(), diag::err_module_private_specialization)
5575       << (isPartialSpecialization? 1 : 0)
5576       << FixItHint::CreateRemoval(ModulePrivateLoc);
5577 
5578   // Build the fully-sugared type for this class template
5579   // specialization as the user wrote in the specialization
5580   // itself. This means that we'll pretty-print the type retrieved
5581   // from the specialization's declaration the way that the user
5582   // actually wrote the specialization, rather than formatting the
5583   // name based on the "canonical" representation used to store the
5584   // template arguments in the specialization.
5585   TypeSourceInfo *WrittenTy
5586     = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
5587                                                 TemplateArgs, CanonType);
5588   if (TUK != TUK_Friend) {
5589     Specialization->setTypeAsWritten(WrittenTy);
5590     Specialization->setTemplateKeywordLoc(TemplateKWLoc);
5591   }
5592 
5593   // C++ [temp.expl.spec]p9:
5594   //   A template explicit specialization is in the scope of the
5595   //   namespace in which the template was defined.
5596   //
5597   // We actually implement this paragraph where we set the semantic
5598   // context (in the creation of the ClassTemplateSpecializationDecl),
5599   // but we also maintain the lexical context where the actual
5600   // definition occurs.
5601   Specialization->setLexicalDeclContext(CurContext);
5602 
5603   // We may be starting the definition of this specialization.
5604   if (TUK == TUK_Definition)
5605     Specialization->startDefinition();
5606 
5607   if (TUK == TUK_Friend) {
5608     FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
5609                                             TemplateNameLoc,
5610                                             WrittenTy,
5611                                             /*FIXME:*/KWLoc);
5612     Friend->setAccess(AS_public);
5613     CurContext->addDecl(Friend);
5614   } else {
5615     // Add the specialization into its lexical context, so that it can
5616     // be seen when iterating through the list of declarations in that
5617     // context. However, specializations are not found by name lookup.
5618     CurContext->addDecl(Specialization);
5619   }
5620   return Specialization;
5621 }
5622 
5623 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
5624                               MultiTemplateParamsArg TemplateParameterLists,
5625                                     Declarator &D) {
5626   Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
5627   ActOnDocumentableDecl(NewDecl);
5628   return NewDecl;
5629 }
5630 
5631 Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
5632                                MultiTemplateParamsArg TemplateParameterLists,
5633                                             Declarator &D) {
5634   assert(getCurFunctionDecl() == 0 && "Function parsing confused");
5635   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5636 
5637   if (FTI.hasPrototype) {
5638     // FIXME: Diagnose arguments without names in C.
5639   }
5640 
5641   Scope *ParentScope = FnBodyScope->getParent();
5642 
5643   D.setFunctionDefinitionKind(FDK_Definition);
5644   Decl *DP = HandleDeclarator(ParentScope, D,
5645                               TemplateParameterLists);
5646   return ActOnStartOfFunctionDef(FnBodyScope, DP);
5647 }
5648 
5649 /// \brief Strips various properties off an implicit instantiation
5650 /// that has just been explicitly specialized.
5651 static void StripImplicitInstantiation(NamedDecl *D) {
5652   D->dropAttrs();
5653 
5654   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5655     FD->setInlineSpecified(false);
5656 
5657     for (FunctionDecl::param_iterator I = FD->param_begin(),
5658                                       E = FD->param_end();
5659          I != E; ++I)
5660       (*I)->dropAttrs();
5661   }
5662 }
5663 
5664 /// \brief Compute the diagnostic location for an explicit instantiation
5665 //  declaration or definition.
5666 static SourceLocation DiagLocForExplicitInstantiation(
5667     NamedDecl* D, SourceLocation PointOfInstantiation) {
5668   // Explicit instantiations following a specialization have no effect and
5669   // hence no PointOfInstantiation. In that case, walk decl backwards
5670   // until a valid name loc is found.
5671   SourceLocation PrevDiagLoc = PointOfInstantiation;
5672   for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
5673        Prev = Prev->getPreviousDecl()) {
5674     PrevDiagLoc = Prev->getLocation();
5675   }
5676   assert(PrevDiagLoc.isValid() &&
5677          "Explicit instantiation without point of instantiation?");
5678   return PrevDiagLoc;
5679 }
5680 
5681 /// \brief Diagnose cases where we have an explicit template specialization
5682 /// before/after an explicit template instantiation, producing diagnostics
5683 /// for those cases where they are required and determining whether the
5684 /// new specialization/instantiation will have any effect.
5685 ///
5686 /// \param NewLoc the location of the new explicit specialization or
5687 /// instantiation.
5688 ///
5689 /// \param NewTSK the kind of the new explicit specialization or instantiation.
5690 ///
5691 /// \param PrevDecl the previous declaration of the entity.
5692 ///
5693 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
5694 ///
5695 /// \param PrevPointOfInstantiation if valid, indicates where the previus
5696 /// declaration was instantiated (either implicitly or explicitly).
5697 ///
5698 /// \param HasNoEffect will be set to true to indicate that the new
5699 /// specialization or instantiation has no effect and should be ignored.
5700 ///
5701 /// \returns true if there was an error that should prevent the introduction of
5702 /// the new declaration into the AST, false otherwise.
5703 bool
5704 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
5705                                              TemplateSpecializationKind NewTSK,
5706                                              NamedDecl *PrevDecl,
5707                                              TemplateSpecializationKind PrevTSK,
5708                                         SourceLocation PrevPointOfInstantiation,
5709                                              bool &HasNoEffect) {
5710   HasNoEffect = false;
5711 
5712   switch (NewTSK) {
5713   case TSK_Undeclared:
5714   case TSK_ImplicitInstantiation:
5715     llvm_unreachable("Don't check implicit instantiations here");
5716 
5717   case TSK_ExplicitSpecialization:
5718     switch (PrevTSK) {
5719     case TSK_Undeclared:
5720     case TSK_ExplicitSpecialization:
5721       // Okay, we're just specializing something that is either already
5722       // explicitly specialized or has merely been mentioned without any
5723       // instantiation.
5724       return false;
5725 
5726     case TSK_ImplicitInstantiation:
5727       if (PrevPointOfInstantiation.isInvalid()) {
5728         // The declaration itself has not actually been instantiated, so it is
5729         // still okay to specialize it.
5730         StripImplicitInstantiation(PrevDecl);
5731         return false;
5732       }
5733       // Fall through
5734 
5735     case TSK_ExplicitInstantiationDeclaration:
5736     case TSK_ExplicitInstantiationDefinition:
5737       assert((PrevTSK == TSK_ImplicitInstantiation ||
5738               PrevPointOfInstantiation.isValid()) &&
5739              "Explicit instantiation without point of instantiation?");
5740 
5741       // C++ [temp.expl.spec]p6:
5742       //   If a template, a member template or the member of a class template
5743       //   is explicitly specialized then that specialization shall be declared
5744       //   before the first use of that specialization that would cause an
5745       //   implicit instantiation to take place, in every translation unit in
5746       //   which such a use occurs; no diagnostic is required.
5747       for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
5748         // Is there any previous explicit specialization declaration?
5749         if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
5750           return false;
5751       }
5752 
5753       Diag(NewLoc, diag::err_specialization_after_instantiation)
5754         << PrevDecl;
5755       Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
5756         << (PrevTSK != TSK_ImplicitInstantiation);
5757 
5758       return true;
5759     }
5760 
5761   case TSK_ExplicitInstantiationDeclaration:
5762     switch (PrevTSK) {
5763     case TSK_ExplicitInstantiationDeclaration:
5764       // This explicit instantiation declaration is redundant (that's okay).
5765       HasNoEffect = true;
5766       return false;
5767 
5768     case TSK_Undeclared:
5769     case TSK_ImplicitInstantiation:
5770       // We're explicitly instantiating something that may have already been
5771       // implicitly instantiated; that's fine.
5772       return false;
5773 
5774     case TSK_ExplicitSpecialization:
5775       // C++0x [temp.explicit]p4:
5776       //   For a given set of template parameters, if an explicit instantiation
5777       //   of a template appears after a declaration of an explicit
5778       //   specialization for that template, the explicit instantiation has no
5779       //   effect.
5780       HasNoEffect = true;
5781       return false;
5782 
5783     case TSK_ExplicitInstantiationDefinition:
5784       // C++0x [temp.explicit]p10:
5785       //   If an entity is the subject of both an explicit instantiation
5786       //   declaration and an explicit instantiation definition in the same
5787       //   translation unit, the definition shall follow the declaration.
5788       Diag(NewLoc,
5789            diag::err_explicit_instantiation_declaration_after_definition);
5790 
5791       // Explicit instantiations following a specialization have no effect and
5792       // hence no PrevPointOfInstantiation. In that case, walk decl backwards
5793       // until a valid name loc is found.
5794       Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
5795            diag::note_explicit_instantiation_definition_here);
5796       HasNoEffect = true;
5797       return false;
5798     }
5799 
5800   case TSK_ExplicitInstantiationDefinition:
5801     switch (PrevTSK) {
5802     case TSK_Undeclared:
5803     case TSK_ImplicitInstantiation:
5804       // We're explicitly instantiating something that may have already been
5805       // implicitly instantiated; that's fine.
5806       return false;
5807 
5808     case TSK_ExplicitSpecialization:
5809       // C++ DR 259, C++0x [temp.explicit]p4:
5810       //   For a given set of template parameters, if an explicit
5811       //   instantiation of a template appears after a declaration of
5812       //   an explicit specialization for that template, the explicit
5813       //   instantiation has no effect.
5814       //
5815       // In C++98/03 mode, we only give an extension warning here, because it
5816       // is not harmful to try to explicitly instantiate something that
5817       // has been explicitly specialized.
5818       Diag(NewLoc, getLangOpts().CPlusPlus11 ?
5819            diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
5820            diag::ext_explicit_instantiation_after_specialization)
5821         << PrevDecl;
5822       Diag(PrevDecl->getLocation(),
5823            diag::note_previous_template_specialization);
5824       HasNoEffect = true;
5825       return false;
5826 
5827     case TSK_ExplicitInstantiationDeclaration:
5828       // We're explicity instantiating a definition for something for which we
5829       // were previously asked to suppress instantiations. That's fine.
5830 
5831       // C++0x [temp.explicit]p4:
5832       //   For a given set of template parameters, if an explicit instantiation
5833       //   of a template appears after a declaration of an explicit
5834       //   specialization for that template, the explicit instantiation has no
5835       //   effect.
5836       for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
5837         // Is there any previous explicit specialization declaration?
5838         if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
5839           HasNoEffect = true;
5840           break;
5841         }
5842       }
5843 
5844       return false;
5845 
5846     case TSK_ExplicitInstantiationDefinition:
5847       // C++0x [temp.spec]p5:
5848       //   For a given template and a given set of template-arguments,
5849       //     - an explicit instantiation definition shall appear at most once
5850       //       in a program,
5851       Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
5852         << PrevDecl;
5853       Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
5854            diag::note_previous_explicit_instantiation);
5855       HasNoEffect = true;
5856       return false;
5857     }
5858   }
5859 
5860   llvm_unreachable("Missing specialization/instantiation case?");
5861 }
5862 
5863 /// \brief Perform semantic analysis for the given dependent function
5864 /// template specialization.
5865 ///
5866 /// The only possible way to get a dependent function template specialization
5867 /// is with a friend declaration, like so:
5868 ///
5869 /// \code
5870 ///   template \<class T> void foo(T);
5871 ///   template \<class T> class A {
5872 ///     friend void foo<>(T);
5873 ///   };
5874 /// \endcode
5875 ///
5876 /// There really isn't any useful analysis we can do here, so we
5877 /// just store the information.
5878 bool
5879 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
5880                    const TemplateArgumentListInfo &ExplicitTemplateArgs,
5881                                                    LookupResult &Previous) {
5882   // Remove anything from Previous that isn't a function template in
5883   // the correct context.
5884   DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
5885   LookupResult::Filter F = Previous.makeFilter();
5886   while (F.hasNext()) {
5887     NamedDecl *D = F.next()->getUnderlyingDecl();
5888     if (!isa<FunctionTemplateDecl>(D) ||
5889         !FDLookupContext->InEnclosingNamespaceSetOf(
5890                               D->getDeclContext()->getRedeclContext()))
5891       F.erase();
5892   }
5893   F.done();
5894 
5895   // Should this be diagnosed here?
5896   if (Previous.empty()) return true;
5897 
5898   FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
5899                                          ExplicitTemplateArgs);
5900   return false;
5901 }
5902 
5903 /// \brief Perform semantic analysis for the given function template
5904 /// specialization.
5905 ///
5906 /// This routine performs all of the semantic analysis required for an
5907 /// explicit function template specialization. On successful completion,
5908 /// the function declaration \p FD will become a function template
5909 /// specialization.
5910 ///
5911 /// \param FD the function declaration, which will be updated to become a
5912 /// function template specialization.
5913 ///
5914 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
5915 /// if any. Note that this may be valid info even when 0 arguments are
5916 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
5917 /// as it anyway contains info on the angle brackets locations.
5918 ///
5919 /// \param Previous the set of declarations that may be specialized by
5920 /// this function specialization.
5921 bool
5922 Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
5923                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
5924                                           LookupResult &Previous) {
5925   // The set of function template specializations that could match this
5926   // explicit function template specialization.
5927   UnresolvedSet<8> Candidates;
5928 
5929   DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
5930   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5931          I != E; ++I) {
5932     NamedDecl *Ovl = (*I)->getUnderlyingDecl();
5933     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
5934       // Only consider templates found within the same semantic lookup scope as
5935       // FD.
5936       if (!FDLookupContext->InEnclosingNamespaceSetOf(
5937                                 Ovl->getDeclContext()->getRedeclContext()))
5938         continue;
5939 
5940       // When matching a constexpr member function template specialization
5941       // against the primary template, we don't yet know whether the
5942       // specialization has an implicit 'const' (because we don't know whether
5943       // it will be a static member function until we know which template it
5944       // specializes), so adjust it now assuming it specializes this template.
5945       QualType FT = FD->getType();
5946       if (FD->isConstexpr()) {
5947         CXXMethodDecl *OldMD =
5948           dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5949         if (OldMD && OldMD->isConst()) {
5950           const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
5951           FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5952           EPI.TypeQuals |= Qualifiers::Const;
5953           FT = Context.getFunctionType(FPT->getResultType(), FPT->getArgTypes(),
5954                                        EPI);
5955         }
5956       }
5957 
5958       // C++ [temp.expl.spec]p11:
5959       //   A trailing template-argument can be left unspecified in the
5960       //   template-id naming an explicit function template specialization
5961       //   provided it can be deduced from the function argument type.
5962       // Perform template argument deduction to determine whether we may be
5963       // specializing this template.
5964       // FIXME: It is somewhat wasteful to build
5965       TemplateDeductionInfo Info(FD->getLocation());
5966       FunctionDecl *Specialization = 0;
5967       if (TemplateDeductionResult TDK
5968             = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs, FT,
5969                                       Specialization, Info)) {
5970         // FIXME: Template argument deduction failed; record why it failed, so
5971         // that we can provide nifty diagnostics.
5972         (void)TDK;
5973         continue;
5974       }
5975 
5976       // Record this candidate.
5977       Candidates.addDecl(Specialization, I.getAccess());
5978     }
5979   }
5980 
5981   // Find the most specialized function template.
5982   UnresolvedSetIterator Result
5983     = getMostSpecialized(Candidates.begin(), Candidates.end(),
5984                          TPOC_Other, 0, FD->getLocation(),
5985                   PDiag(diag::err_function_template_spec_no_match)
5986                     << FD->getDeclName(),
5987                   PDiag(diag::err_function_template_spec_ambiguous)
5988                     << FD->getDeclName() << (ExplicitTemplateArgs != 0),
5989                   PDiag(diag::note_function_template_spec_matched));
5990   if (Result == Candidates.end())
5991     return true;
5992 
5993   // Ignore access information;  it doesn't figure into redeclaration checking.
5994   FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
5995 
5996   FunctionTemplateSpecializationInfo *SpecInfo
5997     = Specialization->getTemplateSpecializationInfo();
5998   assert(SpecInfo && "Function template specialization info missing?");
5999 
6000   // Note: do not overwrite location info if previous template
6001   // specialization kind was explicit.
6002   TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
6003   if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
6004     Specialization->setLocation(FD->getLocation());
6005     // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6006     // function can differ from the template declaration with respect to
6007     // the constexpr specifier.
6008     Specialization->setConstexpr(FD->isConstexpr());
6009   }
6010 
6011   // FIXME: Check if the prior specialization has a point of instantiation.
6012   // If so, we have run afoul of .
6013 
6014   // If this is a friend declaration, then we're not really declaring
6015   // an explicit specialization.
6016   bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
6017 
6018   // Check the scope of this explicit specialization.
6019   if (!isFriend &&
6020       CheckTemplateSpecializationScope(*this,
6021                                        Specialization->getPrimaryTemplate(),
6022                                        Specialization, FD->getLocation(),
6023                                        false))
6024     return true;
6025 
6026   // C++ [temp.expl.spec]p6:
6027   //   If a template, a member template or the member of a class template is
6028   //   explicitly specialized then that specialization shall be declared
6029   //   before the first use of that specialization that would cause an implicit
6030   //   instantiation to take place, in every translation unit in which such a
6031   //   use occurs; no diagnostic is required.
6032   bool HasNoEffect = false;
6033   if (!isFriend &&
6034       CheckSpecializationInstantiationRedecl(FD->getLocation(),
6035                                              TSK_ExplicitSpecialization,
6036                                              Specialization,
6037                                    SpecInfo->getTemplateSpecializationKind(),
6038                                          SpecInfo->getPointOfInstantiation(),
6039                                              HasNoEffect))
6040     return true;
6041 
6042   // Mark the prior declaration as an explicit specialization, so that later
6043   // clients know that this is an explicit specialization.
6044   if (!isFriend) {
6045     SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
6046     MarkUnusedFileScopedDecl(Specialization);
6047   }
6048 
6049   // Turn the given function declaration into a function template
6050   // specialization, with the template arguments from the previous
6051   // specialization.
6052   // Take copies of (semantic and syntactic) template argument lists.
6053   const TemplateArgumentList* TemplArgs = new (Context)
6054     TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
6055   FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
6056                                         TemplArgs, /*InsertPos=*/0,
6057                                     SpecInfo->getTemplateSpecializationKind(),
6058                                         ExplicitTemplateArgs);
6059 
6060   // The "previous declaration" for this function template specialization is
6061   // the prior function template specialization.
6062   Previous.clear();
6063   Previous.addDecl(Specialization);
6064   return false;
6065 }
6066 
6067 /// \brief Perform semantic analysis for the given non-template member
6068 /// specialization.
6069 ///
6070 /// This routine performs all of the semantic analysis required for an
6071 /// explicit member function specialization. On successful completion,
6072 /// the function declaration \p FD will become a member function
6073 /// specialization.
6074 ///
6075 /// \param Member the member declaration, which will be updated to become a
6076 /// specialization.
6077 ///
6078 /// \param Previous the set of declarations, one of which may be specialized
6079 /// by this function specialization;  the set will be modified to contain the
6080 /// redeclared member.
6081 bool
6082 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
6083   assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
6084 
6085   // Try to find the member we are instantiating.
6086   NamedDecl *Instantiation = 0;
6087   NamedDecl *InstantiatedFrom = 0;
6088   MemberSpecializationInfo *MSInfo = 0;
6089 
6090   if (Previous.empty()) {
6091     // Nowhere to look anyway.
6092   } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
6093     for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6094            I != E; ++I) {
6095       NamedDecl *D = (*I)->getUnderlyingDecl();
6096       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
6097         if (Context.hasSameType(Function->getType(), Method->getType())) {
6098           Instantiation = Method;
6099           InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
6100           MSInfo = Method->getMemberSpecializationInfo();
6101           break;
6102         }
6103       }
6104     }
6105   } else if (isa<VarDecl>(Member)) {
6106     VarDecl *PrevVar;
6107     if (Previous.isSingleResult() &&
6108         (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
6109       if (PrevVar->isStaticDataMember()) {
6110         Instantiation = PrevVar;
6111         InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
6112         MSInfo = PrevVar->getMemberSpecializationInfo();
6113       }
6114   } else if (isa<RecordDecl>(Member)) {
6115     CXXRecordDecl *PrevRecord;
6116     if (Previous.isSingleResult() &&
6117         (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
6118       Instantiation = PrevRecord;
6119       InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
6120       MSInfo = PrevRecord->getMemberSpecializationInfo();
6121     }
6122   } else if (isa<EnumDecl>(Member)) {
6123     EnumDecl *PrevEnum;
6124     if (Previous.isSingleResult() &&
6125         (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
6126       Instantiation = PrevEnum;
6127       InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
6128       MSInfo = PrevEnum->getMemberSpecializationInfo();
6129     }
6130   }
6131 
6132   if (!Instantiation) {
6133     // There is no previous declaration that matches. Since member
6134     // specializations are always out-of-line, the caller will complain about
6135     // this mismatch later.
6136     return false;
6137   }
6138 
6139   // If this is a friend, just bail out here before we start turning
6140   // things into explicit specializations.
6141   if (Member->getFriendObjectKind() != Decl::FOK_None) {
6142     // Preserve instantiation information.
6143     if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
6144       cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
6145                                       cast<CXXMethodDecl>(InstantiatedFrom),
6146         cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
6147     } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
6148       cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
6149                                       cast<CXXRecordDecl>(InstantiatedFrom),
6150         cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
6151     }
6152 
6153     Previous.clear();
6154     Previous.addDecl(Instantiation);
6155     return false;
6156   }
6157 
6158   // Make sure that this is a specialization of a member.
6159   if (!InstantiatedFrom) {
6160     Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
6161       << Member;
6162     Diag(Instantiation->getLocation(), diag::note_specialized_decl);
6163     return true;
6164   }
6165 
6166   // C++ [temp.expl.spec]p6:
6167   //   If a template, a member template or the member of a class template is
6168   //   explicitly specialized then that specialization shall be declared
6169   //   before the first use of that specialization that would cause an implicit
6170   //   instantiation to take place, in every translation unit in which such a
6171   //   use occurs; no diagnostic is required.
6172   assert(MSInfo && "Member specialization info missing?");
6173 
6174   bool HasNoEffect = false;
6175   if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
6176                                              TSK_ExplicitSpecialization,
6177                                              Instantiation,
6178                                      MSInfo->getTemplateSpecializationKind(),
6179                                            MSInfo->getPointOfInstantiation(),
6180                                              HasNoEffect))
6181     return true;
6182 
6183   // Check the scope of this explicit specialization.
6184   if (CheckTemplateSpecializationScope(*this,
6185                                        InstantiatedFrom,
6186                                        Instantiation, Member->getLocation(),
6187                                        false))
6188     return true;
6189 
6190   // Note that this is an explicit instantiation of a member.
6191   // the original declaration to note that it is an explicit specialization
6192   // (if it was previously an implicit instantiation). This latter step
6193   // makes bookkeeping easier.
6194   if (isa<FunctionDecl>(Member)) {
6195     FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
6196     if (InstantiationFunction->getTemplateSpecializationKind() ==
6197           TSK_ImplicitInstantiation) {
6198       InstantiationFunction->setTemplateSpecializationKind(
6199                                                   TSK_ExplicitSpecialization);
6200       InstantiationFunction->setLocation(Member->getLocation());
6201     }
6202 
6203     cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
6204                                         cast<CXXMethodDecl>(InstantiatedFrom),
6205                                                   TSK_ExplicitSpecialization);
6206     MarkUnusedFileScopedDecl(InstantiationFunction);
6207   } else if (isa<VarDecl>(Member)) {
6208     VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
6209     if (InstantiationVar->getTemplateSpecializationKind() ==
6210           TSK_ImplicitInstantiation) {
6211       InstantiationVar->setTemplateSpecializationKind(
6212                                                   TSK_ExplicitSpecialization);
6213       InstantiationVar->setLocation(Member->getLocation());
6214     }
6215 
6216     Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
6217                                                 cast<VarDecl>(InstantiatedFrom),
6218                                                 TSK_ExplicitSpecialization);
6219     MarkUnusedFileScopedDecl(InstantiationVar);
6220   } else if (isa<CXXRecordDecl>(Member)) {
6221     CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
6222     if (InstantiationClass->getTemplateSpecializationKind() ==
6223           TSK_ImplicitInstantiation) {
6224       InstantiationClass->setTemplateSpecializationKind(
6225                                                    TSK_ExplicitSpecialization);
6226       InstantiationClass->setLocation(Member->getLocation());
6227     }
6228 
6229     cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
6230                                         cast<CXXRecordDecl>(InstantiatedFrom),
6231                                                    TSK_ExplicitSpecialization);
6232   } else {
6233     assert(isa<EnumDecl>(Member) && "Only member enums remain");
6234     EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
6235     if (InstantiationEnum->getTemplateSpecializationKind() ==
6236           TSK_ImplicitInstantiation) {
6237       InstantiationEnum->setTemplateSpecializationKind(
6238                                                    TSK_ExplicitSpecialization);
6239       InstantiationEnum->setLocation(Member->getLocation());
6240     }
6241 
6242     cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
6243         cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
6244   }
6245 
6246   // Save the caller the trouble of having to figure out which declaration
6247   // this specialization matches.
6248   Previous.clear();
6249   Previous.addDecl(Instantiation);
6250   return false;
6251 }
6252 
6253 /// \brief Check the scope of an explicit instantiation.
6254 ///
6255 /// \returns true if a serious error occurs, false otherwise.
6256 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
6257                                             SourceLocation InstLoc,
6258                                             bool WasQualifiedName) {
6259   DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
6260   DeclContext *CurContext = S.CurContext->getRedeclContext();
6261 
6262   if (CurContext->isRecord()) {
6263     S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
6264       << D;
6265     return true;
6266   }
6267 
6268   // C++11 [temp.explicit]p3:
6269   //   An explicit instantiation shall appear in an enclosing namespace of its
6270   //   template. If the name declared in the explicit instantiation is an
6271   //   unqualified name, the explicit instantiation shall appear in the
6272   //   namespace where its template is declared or, if that namespace is inline
6273   //   (7.3.1), any namespace from its enclosing namespace set.
6274   //
6275   // This is DR275, which we do not retroactively apply to C++98/03.
6276   if (WasQualifiedName) {
6277     if (CurContext->Encloses(OrigContext))
6278       return false;
6279   } else {
6280     if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
6281       return false;
6282   }
6283 
6284   if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
6285     if (WasQualifiedName)
6286       S.Diag(InstLoc,
6287              S.getLangOpts().CPlusPlus11?
6288                diag::err_explicit_instantiation_out_of_scope :
6289                diag::warn_explicit_instantiation_out_of_scope_0x)
6290         << D << NS;
6291     else
6292       S.Diag(InstLoc,
6293              S.getLangOpts().CPlusPlus11?
6294                diag::err_explicit_instantiation_unqualified_wrong_namespace :
6295                diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
6296         << D << NS;
6297   } else
6298     S.Diag(InstLoc,
6299            S.getLangOpts().CPlusPlus11?
6300              diag::err_explicit_instantiation_must_be_global :
6301              diag::warn_explicit_instantiation_must_be_global_0x)
6302       << D;
6303   S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
6304   return false;
6305 }
6306 
6307 /// \brief Determine whether the given scope specifier has a template-id in it.
6308 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
6309   if (!SS.isSet())
6310     return false;
6311 
6312   // C++11 [temp.explicit]p3:
6313   //   If the explicit instantiation is for a member function, a member class
6314   //   or a static data member of a class template specialization, the name of
6315   //   the class template specialization in the qualified-id for the member
6316   //   name shall be a simple-template-id.
6317   //
6318   // C++98 has the same restriction, just worded differently.
6319   for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
6320        NNS; NNS = NNS->getPrefix())
6321     if (const Type *T = NNS->getAsType())
6322       if (isa<TemplateSpecializationType>(T))
6323         return true;
6324 
6325   return false;
6326 }
6327 
6328 // Explicit instantiation of a class template specialization
6329 DeclResult
6330 Sema::ActOnExplicitInstantiation(Scope *S,
6331                                  SourceLocation ExternLoc,
6332                                  SourceLocation TemplateLoc,
6333                                  unsigned TagSpec,
6334                                  SourceLocation KWLoc,
6335                                  const CXXScopeSpec &SS,
6336                                  TemplateTy TemplateD,
6337                                  SourceLocation TemplateNameLoc,
6338                                  SourceLocation LAngleLoc,
6339                                  ASTTemplateArgsPtr TemplateArgsIn,
6340                                  SourceLocation RAngleLoc,
6341                                  AttributeList *Attr) {
6342   // Find the class template we're specializing
6343   TemplateName Name = TemplateD.getAsVal<TemplateName>();
6344   ClassTemplateDecl *ClassTemplate
6345     = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
6346 
6347   // Check that the specialization uses the same tag kind as the
6348   // original template.
6349   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6350   assert(Kind != TTK_Enum &&
6351          "Invalid enum tag in class template explicit instantiation!");
6352   if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
6353                                     Kind, /*isDefinition*/false, KWLoc,
6354                                     *ClassTemplate->getIdentifier())) {
6355     Diag(KWLoc, diag::err_use_with_wrong_tag)
6356       << ClassTemplate
6357       << FixItHint::CreateReplacement(KWLoc,
6358                             ClassTemplate->getTemplatedDecl()->getKindName());
6359     Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
6360          diag::note_previous_use);
6361     Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6362   }
6363 
6364   // C++0x [temp.explicit]p2:
6365   //   There are two forms of explicit instantiation: an explicit instantiation
6366   //   definition and an explicit instantiation declaration. An explicit
6367   //   instantiation declaration begins with the extern keyword. [...]
6368   TemplateSpecializationKind TSK
6369     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
6370                            : TSK_ExplicitInstantiationDeclaration;
6371 
6372   // Translate the parser's template argument list in our AST format.
6373   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
6374   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
6375 
6376   // Check that the template argument list is well-formed for this
6377   // template.
6378   SmallVector<TemplateArgument, 4> Converted;
6379   if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6380                                 TemplateArgs, false, Converted))
6381     return true;
6382 
6383   // Find the class template specialization declaration that
6384   // corresponds to these arguments.
6385   void *InsertPos = 0;
6386   ClassTemplateSpecializationDecl *PrevDecl
6387     = ClassTemplate->findSpecialization(Converted.data(),
6388                                         Converted.size(), InsertPos);
6389 
6390   TemplateSpecializationKind PrevDecl_TSK
6391     = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
6392 
6393   // C++0x [temp.explicit]p2:
6394   //   [...] An explicit instantiation shall appear in an enclosing
6395   //   namespace of its template. [...]
6396   //
6397   // This is C++ DR 275.
6398   if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
6399                                       SS.isSet()))
6400     return true;
6401 
6402   ClassTemplateSpecializationDecl *Specialization = 0;
6403 
6404   bool HasNoEffect = false;
6405   if (PrevDecl) {
6406     if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
6407                                                PrevDecl, PrevDecl_TSK,
6408                                             PrevDecl->getPointOfInstantiation(),
6409                                                HasNoEffect))
6410       return PrevDecl;
6411 
6412     // Even though HasNoEffect == true means that this explicit instantiation
6413     // has no effect on semantics, we go on to put its syntax in the AST.
6414 
6415     if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
6416         PrevDecl_TSK == TSK_Undeclared) {
6417       // Since the only prior class template specialization with these
6418       // arguments was referenced but not declared, reuse that
6419       // declaration node as our own, updating the source location
6420       // for the template name to reflect our new declaration.
6421       // (Other source locations will be updated later.)
6422       Specialization = PrevDecl;
6423       Specialization->setLocation(TemplateNameLoc);
6424       PrevDecl = 0;
6425     }
6426   }
6427 
6428   if (!Specialization) {
6429     // Create a new class template specialization declaration node for
6430     // this explicit specialization.
6431     Specialization
6432       = ClassTemplateSpecializationDecl::Create(Context, Kind,
6433                                              ClassTemplate->getDeclContext(),
6434                                                 KWLoc, TemplateNameLoc,
6435                                                 ClassTemplate,
6436                                                 Converted.data(),
6437                                                 Converted.size(),
6438                                                 PrevDecl);
6439     SetNestedNameSpecifier(Specialization, SS);
6440 
6441     if (!HasNoEffect && !PrevDecl) {
6442       // Insert the new specialization.
6443       ClassTemplate->AddSpecialization(Specialization, InsertPos);
6444     }
6445   }
6446 
6447   // Build the fully-sugared type for this explicit instantiation as
6448   // the user wrote in the explicit instantiation itself. This means
6449   // that we'll pretty-print the type retrieved from the
6450   // specialization's declaration the way that the user actually wrote
6451   // the explicit instantiation, rather than formatting the name based
6452   // on the "canonical" representation used to store the template
6453   // arguments in the specialization.
6454   TypeSourceInfo *WrittenTy
6455     = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6456                                                 TemplateArgs,
6457                                   Context.getTypeDeclType(Specialization));
6458   Specialization->setTypeAsWritten(WrittenTy);
6459 
6460   // Set source locations for keywords.
6461   Specialization->setExternLoc(ExternLoc);
6462   Specialization->setTemplateKeywordLoc(TemplateLoc);
6463   Specialization->setRBraceLoc(SourceLocation());
6464 
6465   if (Attr)
6466     ProcessDeclAttributeList(S, Specialization, Attr);
6467 
6468   // Add the explicit instantiation into its lexical context. However,
6469   // since explicit instantiations are never found by name lookup, we
6470   // just put it into the declaration context directly.
6471   Specialization->setLexicalDeclContext(CurContext);
6472   CurContext->addDecl(Specialization);
6473 
6474   // Syntax is now OK, so return if it has no other effect on semantics.
6475   if (HasNoEffect) {
6476     // Set the template specialization kind.
6477     Specialization->setTemplateSpecializationKind(TSK);
6478     return Specialization;
6479   }
6480 
6481   // C++ [temp.explicit]p3:
6482   //   A definition of a class template or class member template
6483   //   shall be in scope at the point of the explicit instantiation of
6484   //   the class template or class member template.
6485   //
6486   // This check comes when we actually try to perform the
6487   // instantiation.
6488   ClassTemplateSpecializationDecl *Def
6489     = cast_or_null<ClassTemplateSpecializationDecl>(
6490                                               Specialization->getDefinition());
6491   if (!Def)
6492     InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
6493   else if (TSK == TSK_ExplicitInstantiationDefinition) {
6494     MarkVTableUsed(TemplateNameLoc, Specialization, true);
6495     Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
6496   }
6497 
6498   // Instantiate the members of this class template specialization.
6499   Def = cast_or_null<ClassTemplateSpecializationDecl>(
6500                                        Specialization->getDefinition());
6501   if (Def) {
6502     TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
6503 
6504     // Fix a TSK_ExplicitInstantiationDeclaration followed by a
6505     // TSK_ExplicitInstantiationDefinition
6506     if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
6507         TSK == TSK_ExplicitInstantiationDefinition)
6508       Def->setTemplateSpecializationKind(TSK);
6509 
6510     InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
6511   }
6512 
6513   // Set the template specialization kind.
6514   Specialization->setTemplateSpecializationKind(TSK);
6515   return Specialization;
6516 }
6517 
6518 // Explicit instantiation of a member class of a class template.
6519 DeclResult
6520 Sema::ActOnExplicitInstantiation(Scope *S,
6521                                  SourceLocation ExternLoc,
6522                                  SourceLocation TemplateLoc,
6523                                  unsigned TagSpec,
6524                                  SourceLocation KWLoc,
6525                                  CXXScopeSpec &SS,
6526                                  IdentifierInfo *Name,
6527                                  SourceLocation NameLoc,
6528                                  AttributeList *Attr) {
6529 
6530   bool Owned = false;
6531   bool IsDependent = false;
6532   Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
6533                         KWLoc, SS, Name, NameLoc, Attr, AS_none,
6534                         /*ModulePrivateLoc=*/SourceLocation(),
6535                         MultiTemplateParamsArg(), Owned, IsDependent,
6536                         SourceLocation(), false, TypeResult());
6537   assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
6538 
6539   if (!TagD)
6540     return true;
6541 
6542   TagDecl *Tag = cast<TagDecl>(TagD);
6543   assert(!Tag->isEnum() && "shouldn't see enumerations here");
6544 
6545   if (Tag->isInvalidDecl())
6546     return true;
6547 
6548   CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
6549   CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
6550   if (!Pattern) {
6551     Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
6552       << Context.getTypeDeclType(Record);
6553     Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
6554     return true;
6555   }
6556 
6557   // C++0x [temp.explicit]p2:
6558   //   If the explicit instantiation is for a class or member class, the
6559   //   elaborated-type-specifier in the declaration shall include a
6560   //   simple-template-id.
6561   //
6562   // C++98 has the same restriction, just worded differently.
6563   if (!ScopeSpecifierHasTemplateId(SS))
6564     Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
6565       << Record << SS.getRange();
6566 
6567   // C++0x [temp.explicit]p2:
6568   //   There are two forms of explicit instantiation: an explicit instantiation
6569   //   definition and an explicit instantiation declaration. An explicit
6570   //   instantiation declaration begins with the extern keyword. [...]
6571   TemplateSpecializationKind TSK
6572     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
6573                            : TSK_ExplicitInstantiationDeclaration;
6574 
6575   // C++0x [temp.explicit]p2:
6576   //   [...] An explicit instantiation shall appear in an enclosing
6577   //   namespace of its template. [...]
6578   //
6579   // This is C++ DR 275.
6580   CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
6581 
6582   // Verify that it is okay to explicitly instantiate here.
6583   CXXRecordDecl *PrevDecl
6584     = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
6585   if (!PrevDecl && Record->getDefinition())
6586     PrevDecl = Record;
6587   if (PrevDecl) {
6588     MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
6589     bool HasNoEffect = false;
6590     assert(MSInfo && "No member specialization information?");
6591     if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
6592                                                PrevDecl,
6593                                         MSInfo->getTemplateSpecializationKind(),
6594                                              MSInfo->getPointOfInstantiation(),
6595                                                HasNoEffect))
6596       return true;
6597     if (HasNoEffect)
6598       return TagD;
6599   }
6600 
6601   CXXRecordDecl *RecordDef
6602     = cast_or_null<CXXRecordDecl>(Record->getDefinition());
6603   if (!RecordDef) {
6604     // C++ [temp.explicit]p3:
6605     //   A definition of a member class of a class template shall be in scope
6606     //   at the point of an explicit instantiation of the member class.
6607     CXXRecordDecl *Def
6608       = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
6609     if (!Def) {
6610       Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
6611         << 0 << Record->getDeclName() << Record->getDeclContext();
6612       Diag(Pattern->getLocation(), diag::note_forward_declaration)
6613         << Pattern;
6614       return true;
6615     } else {
6616       if (InstantiateClass(NameLoc, Record, Def,
6617                            getTemplateInstantiationArgs(Record),
6618                            TSK))
6619         return true;
6620 
6621       RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
6622       if (!RecordDef)
6623         return true;
6624     }
6625   }
6626 
6627   // Instantiate all of the members of the class.
6628   InstantiateClassMembers(NameLoc, RecordDef,
6629                           getTemplateInstantiationArgs(Record), TSK);
6630 
6631   if (TSK == TSK_ExplicitInstantiationDefinition)
6632     MarkVTableUsed(NameLoc, RecordDef, true);
6633 
6634   // FIXME: We don't have any representation for explicit instantiations of
6635   // member classes. Such a representation is not needed for compilation, but it
6636   // should be available for clients that want to see all of the declarations in
6637   // the source code.
6638   return TagD;
6639 }
6640 
6641 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
6642                                             SourceLocation ExternLoc,
6643                                             SourceLocation TemplateLoc,
6644                                             Declarator &D) {
6645   // Explicit instantiations always require a name.
6646   // TODO: check if/when DNInfo should replace Name.
6647   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6648   DeclarationName Name = NameInfo.getName();
6649   if (!Name) {
6650     if (!D.isInvalidType())
6651       Diag(D.getDeclSpec().getLocStart(),
6652            diag::err_explicit_instantiation_requires_name)
6653         << D.getDeclSpec().getSourceRange()
6654         << D.getSourceRange();
6655 
6656     return true;
6657   }
6658 
6659   // The scope passed in may not be a decl scope.  Zip up the scope tree until
6660   // we find one that is.
6661   while ((S->getFlags() & Scope::DeclScope) == 0 ||
6662          (S->getFlags() & Scope::TemplateParamScope) != 0)
6663     S = S->getParent();
6664 
6665   // Determine the type of the declaration.
6666   TypeSourceInfo *T = GetTypeForDeclarator(D, S);
6667   QualType R = T->getType();
6668   if (R.isNull())
6669     return true;
6670 
6671   // C++ [dcl.stc]p1:
6672   //   A storage-class-specifier shall not be specified in [...] an explicit
6673   //   instantiation (14.7.2) directive.
6674   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6675     Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
6676       << Name;
6677     return true;
6678   } else if (D.getDeclSpec().getStorageClassSpec()
6679                                                 != DeclSpec::SCS_unspecified) {
6680     // Complain about then remove the storage class specifier.
6681     Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
6682       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6683 
6684     D.getMutableDeclSpec().ClearStorageClassSpecs();
6685   }
6686 
6687   // C++0x [temp.explicit]p1:
6688   //   [...] An explicit instantiation of a function template shall not use the
6689   //   inline or constexpr specifiers.
6690   // Presumably, this also applies to member functions of class templates as
6691   // well.
6692   if (D.getDeclSpec().isInlineSpecified())
6693     Diag(D.getDeclSpec().getInlineSpecLoc(),
6694          getLangOpts().CPlusPlus11 ?
6695            diag::err_explicit_instantiation_inline :
6696            diag::warn_explicit_instantiation_inline_0x)
6697       << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6698   if (D.getDeclSpec().isConstexprSpecified())
6699     // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
6700     // not already specified.
6701     Diag(D.getDeclSpec().getConstexprSpecLoc(),
6702          diag::err_explicit_instantiation_constexpr);
6703 
6704   // C++0x [temp.explicit]p2:
6705   //   There are two forms of explicit instantiation: an explicit instantiation
6706   //   definition and an explicit instantiation declaration. An explicit
6707   //   instantiation declaration begins with the extern keyword. [...]
6708   TemplateSpecializationKind TSK
6709     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
6710                            : TSK_ExplicitInstantiationDeclaration;
6711 
6712   LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
6713   LookupParsedName(Previous, S, &D.getCXXScopeSpec());
6714 
6715   if (!R->isFunctionType()) {
6716     // C++ [temp.explicit]p1:
6717     //   A [...] static data member of a class template can be explicitly
6718     //   instantiated from the member definition associated with its class
6719     //   template.
6720     if (Previous.isAmbiguous())
6721       return true;
6722 
6723     VarDecl *Prev = Previous.getAsSingle<VarDecl>();
6724     if (!Prev || !Prev->isStaticDataMember()) {
6725       // We expect to see a data data member here.
6726       Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
6727         << Name;
6728       for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
6729            P != PEnd; ++P)
6730         Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
6731       return true;
6732     }
6733 
6734     if (!Prev->getInstantiatedFromStaticDataMember()) {
6735       // FIXME: Check for explicit specialization?
6736       Diag(D.getIdentifierLoc(),
6737            diag::err_explicit_instantiation_data_member_not_instantiated)
6738         << Prev;
6739       Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
6740       // FIXME: Can we provide a note showing where this was declared?
6741       return true;
6742     }
6743 
6744     // C++0x [temp.explicit]p2:
6745     //   If the explicit instantiation is for a member function, a member class
6746     //   or a static data member of a class template specialization, the name of
6747     //   the class template specialization in the qualified-id for the member
6748     //   name shall be a simple-template-id.
6749     //
6750     // C++98 has the same restriction, just worded differently.
6751     if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
6752       Diag(D.getIdentifierLoc(),
6753            diag::ext_explicit_instantiation_without_qualified_id)
6754         << Prev << D.getCXXScopeSpec().getRange();
6755 
6756     // Check the scope of this explicit instantiation.
6757     CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
6758 
6759     // Verify that it is okay to explicitly instantiate here.
6760     MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
6761     assert(MSInfo && "Missing static data member specialization info?");
6762     bool HasNoEffect = false;
6763     if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
6764                                         MSInfo->getTemplateSpecializationKind(),
6765                                               MSInfo->getPointOfInstantiation(),
6766                                                HasNoEffect))
6767       return true;
6768     if (HasNoEffect)
6769       return (Decl*) 0;
6770 
6771     // Instantiate static data member.
6772     Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
6773     if (TSK == TSK_ExplicitInstantiationDefinition)
6774       InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
6775 
6776     // FIXME: Create an ExplicitInstantiation node?
6777     return (Decl*) 0;
6778   }
6779 
6780   // If the declarator is a template-id, translate the parser's template
6781   // argument list into our AST format.
6782   bool HasExplicitTemplateArgs = false;
6783   TemplateArgumentListInfo TemplateArgs;
6784   if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6785     TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
6786     TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
6787     TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
6788     ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6789                                        TemplateId->NumArgs);
6790     translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
6791     HasExplicitTemplateArgs = true;
6792   }
6793 
6794   // C++ [temp.explicit]p1:
6795   //   A [...] function [...] can be explicitly instantiated from its template.
6796   //   A member function [...] of a class template can be explicitly
6797   //  instantiated from the member definition associated with its class
6798   //  template.
6799   UnresolvedSet<8> Matches;
6800   for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
6801        P != PEnd; ++P) {
6802     NamedDecl *Prev = *P;
6803     if (!HasExplicitTemplateArgs) {
6804       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
6805         if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
6806           Matches.clear();
6807 
6808           Matches.addDecl(Method, P.getAccess());
6809           if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
6810             break;
6811         }
6812       }
6813     }
6814 
6815     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
6816     if (!FunTmpl)
6817       continue;
6818 
6819     TemplateDeductionInfo Info(D.getIdentifierLoc());
6820     FunctionDecl *Specialization = 0;
6821     if (TemplateDeductionResult TDK
6822           = DeduceTemplateArguments(FunTmpl,
6823                                (HasExplicitTemplateArgs ? &TemplateArgs : 0),
6824                                     R, Specialization, Info)) {
6825       // FIXME: Keep track of almost-matches?
6826       (void)TDK;
6827       continue;
6828     }
6829 
6830     Matches.addDecl(Specialization, P.getAccess());
6831   }
6832 
6833   // Find the most specialized function template specialization.
6834   UnresolvedSetIterator Result
6835     = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other, 0,
6836                          D.getIdentifierLoc(),
6837                      PDiag(diag::err_explicit_instantiation_not_known) << Name,
6838                      PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
6839                          PDiag(diag::note_explicit_instantiation_candidate));
6840 
6841   if (Result == Matches.end())
6842     return true;
6843 
6844   // Ignore access control bits, we don't need them for redeclaration checking.
6845   FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
6846 
6847   if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
6848     Diag(D.getIdentifierLoc(),
6849          diag::err_explicit_instantiation_member_function_not_instantiated)
6850       << Specialization
6851       << (Specialization->getTemplateSpecializationKind() ==
6852           TSK_ExplicitSpecialization);
6853     Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
6854     return true;
6855   }
6856 
6857   FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
6858   if (!PrevDecl && Specialization->isThisDeclarationADefinition())
6859     PrevDecl = Specialization;
6860 
6861   if (PrevDecl) {
6862     bool HasNoEffect = false;
6863     if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
6864                                                PrevDecl,
6865                                      PrevDecl->getTemplateSpecializationKind(),
6866                                           PrevDecl->getPointOfInstantiation(),
6867                                                HasNoEffect))
6868       return true;
6869 
6870     // FIXME: We may still want to build some representation of this
6871     // explicit specialization.
6872     if (HasNoEffect)
6873       return (Decl*) 0;
6874   }
6875 
6876   Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
6877   AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
6878   if (Attr)
6879     ProcessDeclAttributeList(S, Specialization, Attr);
6880 
6881   if (TSK == TSK_ExplicitInstantiationDefinition)
6882     InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
6883 
6884   // C++0x [temp.explicit]p2:
6885   //   If the explicit instantiation is for a member function, a member class
6886   //   or a static data member of a class template specialization, the name of
6887   //   the class template specialization in the qualified-id for the member
6888   //   name shall be a simple-template-id.
6889   //
6890   // C++98 has the same restriction, just worded differently.
6891   FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
6892   if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
6893       D.getCXXScopeSpec().isSet() &&
6894       !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
6895     Diag(D.getIdentifierLoc(),
6896          diag::ext_explicit_instantiation_without_qualified_id)
6897     << Specialization << D.getCXXScopeSpec().getRange();
6898 
6899   CheckExplicitInstantiationScope(*this,
6900                    FunTmpl? (NamedDecl *)FunTmpl
6901                           : Specialization->getInstantiatedFromMemberFunction(),
6902                                   D.getIdentifierLoc(),
6903                                   D.getCXXScopeSpec().isSet());
6904 
6905   // FIXME: Create some kind of ExplicitInstantiationDecl here.
6906   return (Decl*) 0;
6907 }
6908 
6909 TypeResult
6910 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
6911                         const CXXScopeSpec &SS, IdentifierInfo *Name,
6912                         SourceLocation TagLoc, SourceLocation NameLoc) {
6913   // This has to hold, because SS is expected to be defined.
6914   assert(Name && "Expected a name in a dependent tag");
6915 
6916   NestedNameSpecifier *NNS
6917     = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6918   if (!NNS)
6919     return true;
6920 
6921   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6922 
6923   if (TUK == TUK_Declaration || TUK == TUK_Definition) {
6924     Diag(NameLoc, diag::err_dependent_tag_decl)
6925       << (TUK == TUK_Definition) << Kind << SS.getRange();
6926     return true;
6927   }
6928 
6929   // Create the resulting type.
6930   ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6931   QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
6932 
6933   // Create type-source location information for this type.
6934   TypeLocBuilder TLB;
6935   DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
6936   TL.setElaboratedKeywordLoc(TagLoc);
6937   TL.setQualifierLoc(SS.getWithLocInContext(Context));
6938   TL.setNameLoc(NameLoc);
6939   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
6940 }
6941 
6942 TypeResult
6943 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6944                         const CXXScopeSpec &SS, const IdentifierInfo &II,
6945                         SourceLocation IdLoc) {
6946   if (SS.isInvalid())
6947     return true;
6948 
6949   if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
6950     Diag(TypenameLoc,
6951          getLangOpts().CPlusPlus11 ?
6952            diag::warn_cxx98_compat_typename_outside_of_template :
6953            diag::ext_typename_outside_of_template)
6954       << FixItHint::CreateRemoval(TypenameLoc);
6955 
6956   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
6957   QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
6958                                  TypenameLoc, QualifierLoc, II, IdLoc);
6959   if (T.isNull())
6960     return true;
6961 
6962   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6963   if (isa<DependentNameType>(T)) {
6964     DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
6965     TL.setElaboratedKeywordLoc(TypenameLoc);
6966     TL.setQualifierLoc(QualifierLoc);
6967     TL.setNameLoc(IdLoc);
6968   } else {
6969     ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
6970     TL.setElaboratedKeywordLoc(TypenameLoc);
6971     TL.setQualifierLoc(QualifierLoc);
6972     TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
6973   }
6974 
6975   return CreateParsedType(T, TSI);
6976 }
6977 
6978 TypeResult
6979 Sema::ActOnTypenameType(Scope *S,
6980                         SourceLocation TypenameLoc,
6981                         const CXXScopeSpec &SS,
6982                         SourceLocation TemplateKWLoc,
6983                         TemplateTy TemplateIn,
6984                         SourceLocation TemplateNameLoc,
6985                         SourceLocation LAngleLoc,
6986                         ASTTemplateArgsPtr TemplateArgsIn,
6987                         SourceLocation RAngleLoc) {
6988   if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
6989     Diag(TypenameLoc,
6990          getLangOpts().CPlusPlus11 ?
6991            diag::warn_cxx98_compat_typename_outside_of_template :
6992            diag::ext_typename_outside_of_template)
6993       << FixItHint::CreateRemoval(TypenameLoc);
6994 
6995   // Translate the parser's template argument list in our AST format.
6996   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
6997   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
6998 
6999   TemplateName Template = TemplateIn.get();
7000   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
7001     // Construct a dependent template specialization type.
7002     assert(DTN && "dependent template has non-dependent name?");
7003     assert(DTN->getQualifier()
7004            == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
7005     QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
7006                                                           DTN->getQualifier(),
7007                                                           DTN->getIdentifier(),
7008                                                                 TemplateArgs);
7009 
7010     // Create source-location information for this type.
7011     TypeLocBuilder Builder;
7012     DependentTemplateSpecializationTypeLoc SpecTL
7013     = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
7014     SpecTL.setElaboratedKeywordLoc(TypenameLoc);
7015     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
7016     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
7017     SpecTL.setTemplateNameLoc(TemplateNameLoc);
7018     SpecTL.setLAngleLoc(LAngleLoc);
7019     SpecTL.setRAngleLoc(RAngleLoc);
7020     for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7021       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
7022     return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
7023   }
7024 
7025   QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
7026   if (T.isNull())
7027     return true;
7028 
7029   // Provide source-location information for the template specialization type.
7030   TypeLocBuilder Builder;
7031   TemplateSpecializationTypeLoc SpecTL
7032     = Builder.push<TemplateSpecializationTypeLoc>(T);
7033   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
7034   SpecTL.setTemplateNameLoc(TemplateNameLoc);
7035   SpecTL.setLAngleLoc(LAngleLoc);
7036   SpecTL.setRAngleLoc(RAngleLoc);
7037   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7038     SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
7039 
7040   T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
7041   ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
7042   TL.setElaboratedKeywordLoc(TypenameLoc);
7043   TL.setQualifierLoc(SS.getWithLocInContext(Context));
7044 
7045   TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
7046   return CreateParsedType(T, TSI);
7047 }
7048 
7049 
7050 /// Determine whether this failed name lookup should be treated as being
7051 /// disabled by a usage of std::enable_if.
7052 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
7053                        SourceRange &CondRange) {
7054   // We must be looking for a ::type...
7055   if (!II.isStr("type"))
7056     return false;
7057 
7058   // ... within an explicitly-written template specialization...
7059   if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
7060     return false;
7061   TypeLoc EnableIfTy = NNS.getTypeLoc();
7062   TemplateSpecializationTypeLoc EnableIfTSTLoc =
7063       EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
7064   if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
7065     return false;
7066   const TemplateSpecializationType *EnableIfTST =
7067     cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
7068 
7069   // ... which names a complete class template declaration...
7070   const TemplateDecl *EnableIfDecl =
7071     EnableIfTST->getTemplateName().getAsTemplateDecl();
7072   if (!EnableIfDecl || EnableIfTST->isIncompleteType())
7073     return false;
7074 
7075   // ... called "enable_if".
7076   const IdentifierInfo *EnableIfII =
7077     EnableIfDecl->getDeclName().getAsIdentifierInfo();
7078   if (!EnableIfII || !EnableIfII->isStr("enable_if"))
7079     return false;
7080 
7081   // Assume the first template argument is the condition.
7082   CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
7083   return true;
7084 }
7085 
7086 /// \brief Build the type that describes a C++ typename specifier,
7087 /// e.g., "typename T::type".
7088 QualType
7089 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
7090                         SourceLocation KeywordLoc,
7091                         NestedNameSpecifierLoc QualifierLoc,
7092                         const IdentifierInfo &II,
7093                         SourceLocation IILoc) {
7094   CXXScopeSpec SS;
7095   SS.Adopt(QualifierLoc);
7096 
7097   DeclContext *Ctx = computeDeclContext(SS);
7098   if (!Ctx) {
7099     // If the nested-name-specifier is dependent and couldn't be
7100     // resolved to a type, build a typename type.
7101     assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
7102     return Context.getDependentNameType(Keyword,
7103                                         QualifierLoc.getNestedNameSpecifier(),
7104                                         &II);
7105   }
7106 
7107   // If the nested-name-specifier refers to the current instantiation,
7108   // the "typename" keyword itself is superfluous. In C++03, the
7109   // program is actually ill-formed. However, DR 382 (in C++0x CD1)
7110   // allows such extraneous "typename" keywords, and we retroactively
7111   // apply this DR to C++03 code with only a warning. In any case we continue.
7112 
7113   if (RequireCompleteDeclContext(SS, Ctx))
7114     return QualType();
7115 
7116   DeclarationName Name(&II);
7117   LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
7118   LookupQualifiedName(Result, Ctx);
7119   unsigned DiagID = 0;
7120   Decl *Referenced = 0;
7121   switch (Result.getResultKind()) {
7122   case LookupResult::NotFound: {
7123     // If we're looking up 'type' within a template named 'enable_if', produce
7124     // a more specific diagnostic.
7125     SourceRange CondRange;
7126     if (isEnableIf(QualifierLoc, II, CondRange)) {
7127       Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
7128         << Ctx << CondRange;
7129       return QualType();
7130     }
7131 
7132     DiagID = diag::err_typename_nested_not_found;
7133     break;
7134   }
7135 
7136   case LookupResult::FoundUnresolvedValue: {
7137     // We found a using declaration that is a value. Most likely, the using
7138     // declaration itself is meant to have the 'typename' keyword.
7139     SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
7140                           IILoc);
7141     Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
7142       << Name << Ctx << FullRange;
7143     if (UnresolvedUsingValueDecl *Using
7144           = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
7145       SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
7146       Diag(Loc, diag::note_using_value_decl_missing_typename)
7147         << FixItHint::CreateInsertion(Loc, "typename ");
7148     }
7149   }
7150   // Fall through to create a dependent typename type, from which we can recover
7151   // better.
7152 
7153   case LookupResult::NotFoundInCurrentInstantiation:
7154     // Okay, it's a member of an unknown instantiation.
7155     return Context.getDependentNameType(Keyword,
7156                                         QualifierLoc.getNestedNameSpecifier(),
7157                                         &II);
7158 
7159   case LookupResult::Found:
7160     if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
7161       // We found a type. Build an ElaboratedType, since the
7162       // typename-specifier was just sugar.
7163       return Context.getElaboratedType(ETK_Typename,
7164                                        QualifierLoc.getNestedNameSpecifier(),
7165                                        Context.getTypeDeclType(Type));
7166     }
7167 
7168     DiagID = diag::err_typename_nested_not_type;
7169     Referenced = Result.getFoundDecl();
7170     break;
7171 
7172   case LookupResult::FoundOverloaded:
7173     DiagID = diag::err_typename_nested_not_type;
7174     Referenced = *Result.begin();
7175     break;
7176 
7177   case LookupResult::Ambiguous:
7178     return QualType();
7179   }
7180 
7181   // If we get here, it's because name lookup did not find a
7182   // type. Emit an appropriate diagnostic and return an error.
7183   SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
7184                         IILoc);
7185   Diag(IILoc, DiagID) << FullRange << Name << Ctx;
7186   if (Referenced)
7187     Diag(Referenced->getLocation(), diag::note_typename_refers_here)
7188       << Name;
7189   return QualType();
7190 }
7191 
7192 namespace {
7193   // See Sema::RebuildTypeInCurrentInstantiation
7194   class CurrentInstantiationRebuilder
7195     : public TreeTransform<CurrentInstantiationRebuilder> {
7196     SourceLocation Loc;
7197     DeclarationName Entity;
7198 
7199   public:
7200     typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
7201 
7202     CurrentInstantiationRebuilder(Sema &SemaRef,
7203                                   SourceLocation Loc,
7204                                   DeclarationName Entity)
7205     : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
7206       Loc(Loc), Entity(Entity) { }
7207 
7208     /// \brief Determine whether the given type \p T has already been
7209     /// transformed.
7210     ///
7211     /// For the purposes of type reconstruction, a type has already been
7212     /// transformed if it is NULL or if it is not dependent.
7213     bool AlreadyTransformed(QualType T) {
7214       return T.isNull() || !T->isDependentType();
7215     }
7216 
7217     /// \brief Returns the location of the entity whose type is being
7218     /// rebuilt.
7219     SourceLocation getBaseLocation() { return Loc; }
7220 
7221     /// \brief Returns the name of the entity whose type is being rebuilt.
7222     DeclarationName getBaseEntity() { return Entity; }
7223 
7224     /// \brief Sets the "base" location and entity when that
7225     /// information is known based on another transformation.
7226     void setBase(SourceLocation Loc, DeclarationName Entity) {
7227       this->Loc = Loc;
7228       this->Entity = Entity;
7229     }
7230 
7231     ExprResult TransformLambdaExpr(LambdaExpr *E) {
7232       // Lambdas never need to be transformed.
7233       return E;
7234     }
7235   };
7236 }
7237 
7238 /// \brief Rebuilds a type within the context of the current instantiation.
7239 ///
7240 /// The type \p T is part of the type of an out-of-line member definition of
7241 /// a class template (or class template partial specialization) that was parsed
7242 /// and constructed before we entered the scope of the class template (or
7243 /// partial specialization thereof). This routine will rebuild that type now
7244 /// that we have entered the declarator's scope, which may produce different
7245 /// canonical types, e.g.,
7246 ///
7247 /// \code
7248 /// template<typename T>
7249 /// struct X {
7250 ///   typedef T* pointer;
7251 ///   pointer data();
7252 /// };
7253 ///
7254 /// template<typename T>
7255 /// typename X<T>::pointer X<T>::data() { ... }
7256 /// \endcode
7257 ///
7258 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
7259 /// since we do not know that we can look into X<T> when we parsed the type.
7260 /// This function will rebuild the type, performing the lookup of "pointer"
7261 /// in X<T> and returning an ElaboratedType whose canonical type is the same
7262 /// as the canonical type of T*, allowing the return types of the out-of-line
7263 /// definition and the declaration to match.
7264 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
7265                                                         SourceLocation Loc,
7266                                                         DeclarationName Name) {
7267   if (!T || !T->getType()->isDependentType())
7268     return T;
7269 
7270   CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
7271   return Rebuilder.TransformType(T);
7272 }
7273 
7274 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
7275   CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
7276                                           DeclarationName());
7277   return Rebuilder.TransformExpr(E);
7278 }
7279 
7280 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
7281   if (SS.isInvalid())
7282     return true;
7283 
7284   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7285   CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
7286                                           DeclarationName());
7287   NestedNameSpecifierLoc Rebuilt
7288     = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
7289   if (!Rebuilt)
7290     return true;
7291 
7292   SS.Adopt(Rebuilt);
7293   return false;
7294 }
7295 
7296 /// \brief Rebuild the template parameters now that we know we're in a current
7297 /// instantiation.
7298 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
7299                                                TemplateParameterList *Params) {
7300   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
7301     Decl *Param = Params->getParam(I);
7302 
7303     // There is nothing to rebuild in a type parameter.
7304     if (isa<TemplateTypeParmDecl>(Param))
7305       continue;
7306 
7307     // Rebuild the template parameter list of a template template parameter.
7308     if (TemplateTemplateParmDecl *TTP
7309         = dyn_cast<TemplateTemplateParmDecl>(Param)) {
7310       if (RebuildTemplateParamsInCurrentInstantiation(
7311             TTP->getTemplateParameters()))
7312         return true;
7313 
7314       continue;
7315     }
7316 
7317     // Rebuild the type of a non-type template parameter.
7318     NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
7319     TypeSourceInfo *NewTSI
7320       = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
7321                                           NTTP->getLocation(),
7322                                           NTTP->getDeclName());
7323     if (!NewTSI)
7324       return true;
7325 
7326     if (NewTSI != NTTP->getTypeSourceInfo()) {
7327       NTTP->setTypeSourceInfo(NewTSI);
7328       NTTP->setType(NewTSI->getType());
7329     }
7330   }
7331 
7332   return false;
7333 }
7334 
7335 /// \brief Produces a formatted string that describes the binding of
7336 /// template parameters to template arguments.
7337 std::string
7338 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7339                                       const TemplateArgumentList &Args) {
7340   return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
7341 }
7342 
7343 std::string
7344 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7345                                       const TemplateArgument *Args,
7346                                       unsigned NumArgs) {
7347   SmallString<128> Str;
7348   llvm::raw_svector_ostream Out(Str);
7349 
7350   if (!Params || Params->size() == 0 || NumArgs == 0)
7351     return std::string();
7352 
7353   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
7354     if (I >= NumArgs)
7355       break;
7356 
7357     if (I == 0)
7358       Out << "[with ";
7359     else
7360       Out << ", ";
7361 
7362     if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
7363       Out << Id->getName();
7364     } else {
7365       Out << '$' << I;
7366     }
7367 
7368     Out << " = ";
7369     Args[I].print(getPrintingPolicy(), Out);
7370   }
7371 
7372   Out << ']';
7373   return Out.str();
7374 }
7375 
7376 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag) {
7377   if (!FD)
7378     return;
7379   FD->setLateTemplateParsed(Flag);
7380 }
7381 
7382 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
7383   DeclContext *DC = CurContext;
7384 
7385   while (DC) {
7386     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
7387       const FunctionDecl *FD = RD->isLocalClass();
7388       return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
7389     } else if (DC->isTranslationUnit() || DC->isNamespace())
7390       return false;
7391 
7392     DC = DC->getParent();
7393   }
7394   return false;
7395 }
7396