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