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