SemaTemplate.cpp revision 4b52e25f3b05ab0f9d2492276a52323a50a84fb7
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 "Sema.h"
13#include "Lookup.h"
14#include "TreeTransform.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/Parse/DeclSpec.h"
20#include "clang/Parse/Template.h"
21#include "clang/Basic/LangOptions.h"
22#include "clang/Basic/PartialDiagnostic.h"
23#include "llvm/ADT/StringExtras.h"
24using namespace clang;
25
26/// \brief Determine whether the declaration found is acceptable as the name
27/// of a template and, if so, return that template declaration. Otherwise,
28/// returns NULL.
29static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
30  if (!D)
31    return 0;
32
33  if (isa<TemplateDecl>(D))
34    return D;
35
36  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
37    // C++ [temp.local]p1:
38    //   Like normal (non-template) classes, class templates have an
39    //   injected-class-name (Clause 9). The injected-class-name
40    //   can be used with or without a template-argument-list. When
41    //   it is used without a template-argument-list, it is
42    //   equivalent to the injected-class-name followed by the
43    //   template-parameters of the class template enclosed in
44    //   <>. When it is used with a template-argument-list, it
45    //   refers to the specified class template specialization,
46    //   which could be the current specialization or another
47    //   specialization.
48    if (Record->isInjectedClassName()) {
49      Record = cast<CXXRecordDecl>(Record->getDeclContext());
50      if (Record->getDescribedClassTemplate())
51        return Record->getDescribedClassTemplate();
52
53      if (ClassTemplateSpecializationDecl *Spec
54            = dyn_cast<ClassTemplateSpecializationDecl>(Record))
55        return Spec->getSpecializedTemplate();
56    }
57
58    return 0;
59  }
60
61  return 0;
62}
63
64static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
65  LookupResult::Filter filter = R.makeFilter();
66  while (filter.hasNext()) {
67    NamedDecl *Orig = filter.next();
68    NamedDecl *Repl = isAcceptableTemplateName(C, Orig->getUnderlyingDecl());
69    if (!Repl)
70      filter.erase();
71    else if (Repl != Orig)
72      filter.replace(Repl);
73  }
74  filter.done();
75}
76
77TemplateNameKind Sema::isTemplateName(Scope *S,
78                                      const CXXScopeSpec &SS,
79                                      UnqualifiedId &Name,
80                                      TypeTy *ObjectTypePtr,
81                                      bool EnteringContext,
82                                      TemplateTy &TemplateResult) {
83  DeclarationName TName;
84
85  switch (Name.getKind()) {
86  case UnqualifiedId::IK_Identifier:
87    TName = DeclarationName(Name.Identifier);
88    break;
89
90  case UnqualifiedId::IK_OperatorFunctionId:
91    TName = Context.DeclarationNames.getCXXOperatorName(
92                                              Name.OperatorFunctionId.Operator);
93    break;
94
95  case UnqualifiedId::IK_LiteralOperatorId:
96    TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
97    break;
98
99  default:
100    return TNK_Non_template;
101  }
102
103  QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
104
105  LookupResult R(*this, TName, SourceLocation(), LookupOrdinaryName);
106  R.suppressDiagnostics();
107  LookupTemplateName(R, S, SS, ObjectType, EnteringContext);
108  if (R.empty())
109    return TNK_Non_template;
110
111  TemplateName Template;
112  TemplateNameKind TemplateKind;
113
114  unsigned ResultCount = R.end() - R.begin();
115  if (ResultCount > 1) {
116    // We assume that we'll preserve the qualifier from a function
117    // template name in other ways.
118    Template = Context.getOverloadedTemplateName(R.begin(), R.end());
119    TemplateKind = TNK_Function_template;
120  } else {
121    TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
122
123    if (SS.isSet() && !SS.isInvalid()) {
124      NestedNameSpecifier *Qualifier
125        = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
126      Template = Context.getQualifiedTemplateName(Qualifier, false, TD);
127    } else {
128      Template = TemplateName(TD);
129    }
130
131    if (isa<FunctionTemplateDecl>(TD))
132      TemplateKind = TNK_Function_template;
133    else {
134      assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
135      TemplateKind = TNK_Type_template;
136    }
137  }
138
139  TemplateResult = TemplateTy::make(Template);
140  return TemplateKind;
141}
142
143void Sema::LookupTemplateName(LookupResult &Found,
144                              Scope *S, const CXXScopeSpec &SS,
145                              QualType ObjectType,
146                              bool EnteringContext) {
147  // Determine where to perform name lookup
148  DeclContext *LookupCtx = 0;
149  bool isDependent = false;
150  if (!ObjectType.isNull()) {
151    // This nested-name-specifier occurs in a member access expression, e.g.,
152    // x->B::f, and we are looking into the type of the object.
153    assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
154    LookupCtx = computeDeclContext(ObjectType);
155    isDependent = ObjectType->isDependentType();
156    assert((isDependent || !ObjectType->isIncompleteType()) &&
157           "Caller should have completed object type");
158  } else if (SS.isSet()) {
159    // This nested-name-specifier occurs after another nested-name-specifier,
160    // so long into the context associated with the prior nested-name-specifier.
161    LookupCtx = computeDeclContext(SS, EnteringContext);
162    isDependent = isDependentScopeSpecifier(SS);
163
164    // The declaration context must be complete.
165    if (LookupCtx && RequireCompleteDeclContext(SS))
166      return;
167  }
168
169  bool ObjectTypeSearchedInScope = false;
170  if (LookupCtx) {
171    // Perform "qualified" name lookup into the declaration context we
172    // computed, which is either the type of the base of a member access
173    // expression or the declaration context associated with a prior
174    // nested-name-specifier.
175    LookupQualifiedName(Found, LookupCtx);
176
177    if (!ObjectType.isNull() && Found.empty()) {
178      // C++ [basic.lookup.classref]p1:
179      //   In a class member access expression (5.2.5), if the . or -> token is
180      //   immediately followed by an identifier followed by a <, the
181      //   identifier must be looked up to determine whether the < is the
182      //   beginning of a template argument list (14.2) or a less-than operator.
183      //   The identifier is first looked up in the class of the object
184      //   expression. If the identifier is not found, it is then looked up in
185      //   the context of the entire postfix-expression and shall name a class
186      //   or function template.
187      //
188      // FIXME: When we're instantiating a template, do we actually have to
189      // look in the scope of the template? Seems fishy...
190      if (S) LookupName(Found, S);
191      ObjectTypeSearchedInScope = true;
192    }
193  } else if (isDependent) {
194    // We cannot look into a dependent object type or
195    return;
196  } else {
197    // Perform unqualified name lookup in the current scope.
198    LookupName(Found, S);
199  }
200
201  // FIXME: Cope with ambiguous name-lookup results.
202  assert(!Found.isAmbiguous() &&
203         "Cannot handle template name-lookup ambiguities");
204
205  FilterAcceptableTemplateNames(Context, Found);
206  if (Found.empty())
207    return;
208
209  if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
210    // C++ [basic.lookup.classref]p1:
211    //   [...] If the lookup in the class of the object expression finds a
212    //   template, the name is also looked up in the context of the entire
213    //   postfix-expression and [...]
214    //
215    LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
216                            LookupOrdinaryName);
217    LookupName(FoundOuter, S);
218    FilterAcceptableTemplateNames(Context, FoundOuter);
219    // FIXME: Handle ambiguities in this lookup better
220
221    if (FoundOuter.empty()) {
222      //   - if the name is not found, the name found in the class of the
223      //     object expression is used, otherwise
224    } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
225      //   - if the name is found in the context of the entire
226      //     postfix-expression and does not name a class template, the name
227      //     found in the class of the object expression is used, otherwise
228    } else {
229      //   - if the name found is a class template, it must refer to the same
230      //     entity as the one found in the class of the object expression,
231      //     otherwise the program is ill-formed.
232      if (!Found.isSingleResult() ||
233          Found.getFoundDecl()->getCanonicalDecl()
234            != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
235        Diag(Found.getNameLoc(),
236             diag::err_nested_name_member_ref_lookup_ambiguous)
237          << Found.getLookupName();
238        Diag(Found.getRepresentativeDecl()->getLocation(),
239             diag::note_ambig_member_ref_object_type)
240          << ObjectType;
241        Diag(FoundOuter.getFoundDecl()->getLocation(),
242             diag::note_ambig_member_ref_scope);
243
244        // Recover by taking the template that we found in the object
245        // expression's type.
246      }
247    }
248  }
249}
250
251/// ActOnDependentIdExpression - Handle a dependent id-expression that
252/// was just parsed.  This is only possible with an explicit scope
253/// specifier naming a dependent type.
254Sema::OwningExprResult
255Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
256                                 DeclarationName Name,
257                                 SourceLocation NameLoc,
258                                 bool isAddressOfOperand,
259                           const TemplateArgumentListInfo *TemplateArgs) {
260  NestedNameSpecifier *Qualifier
261    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
262
263  if (!isAddressOfOperand &&
264      isa<CXXMethodDecl>(CurContext) &&
265      cast<CXXMethodDecl>(CurContext)->isInstance()) {
266    QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
267
268    // Since the 'this' expression is synthesized, we don't need to
269    // perform the double-lookup check.
270    NamedDecl *FirstQualifierInScope = 0;
271
272    return Owned(CXXDependentScopeMemberExpr::Create(Context,
273                                                     /*This*/ 0, ThisType,
274                                                     /*IsArrow*/ true,
275                                                     /*Op*/ SourceLocation(),
276                                                     Qualifier, SS.getRange(),
277                                                     FirstQualifierInScope,
278                                                     Name, NameLoc,
279                                                     TemplateArgs));
280  }
281
282  return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
283}
284
285Sema::OwningExprResult
286Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
287                                DeclarationName Name,
288                                SourceLocation NameLoc,
289                                const TemplateArgumentListInfo *TemplateArgs) {
290  return Owned(DependentScopeDeclRefExpr::Create(Context,
291               static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
292                                                 SS.getRange(),
293                                                 Name, NameLoc,
294                                                 TemplateArgs));
295}
296
297/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
298/// that the template parameter 'PrevDecl' is being shadowed by a new
299/// declaration at location Loc. Returns true to indicate that this is
300/// an error, and false otherwise.
301bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
302  assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
303
304  // Microsoft Visual C++ permits template parameters to be shadowed.
305  if (getLangOptions().Microsoft)
306    return false;
307
308  // C++ [temp.local]p4:
309  //   A template-parameter shall not be redeclared within its
310  //   scope (including nested scopes).
311  Diag(Loc, diag::err_template_param_shadow)
312    << cast<NamedDecl>(PrevDecl)->getDeclName();
313  Diag(PrevDecl->getLocation(), diag::note_template_param_here);
314  return true;
315}
316
317/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
318/// the parameter D to reference the templated declaration and return a pointer
319/// to the template declaration. Otherwise, do nothing to D and return null.
320TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
321  if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
322    D = DeclPtrTy::make(Temp->getTemplatedDecl());
323    return Temp;
324  }
325  return 0;
326}
327
328static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
329                                            const ParsedTemplateArgument &Arg) {
330
331  switch (Arg.getKind()) {
332  case ParsedTemplateArgument::Type: {
333    TypeSourceInfo *DI;
334    QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
335    if (!DI)
336      DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
337    return TemplateArgumentLoc(TemplateArgument(T), DI);
338  }
339
340  case ParsedTemplateArgument::NonType: {
341    Expr *E = static_cast<Expr *>(Arg.getAsExpr());
342    return TemplateArgumentLoc(TemplateArgument(E), E);
343  }
344
345  case ParsedTemplateArgument::Template: {
346    TemplateName Template
347      = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
348    return TemplateArgumentLoc(TemplateArgument(Template),
349                               Arg.getScopeSpec().getRange(),
350                               Arg.getLocation());
351  }
352  }
353
354  llvm_unreachable("Unhandled parsed template argument");
355  return TemplateArgumentLoc();
356}
357
358/// \brief Translates template arguments as provided by the parser
359/// into template arguments used by semantic analysis.
360void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
361                                      TemplateArgumentListInfo &TemplateArgs) {
362 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
363   TemplateArgs.addArgument(translateTemplateArgument(*this,
364                                                      TemplateArgsIn[I]));
365}
366
367/// ActOnTypeParameter - Called when a C++ template type parameter
368/// (e.g., "typename T") has been parsed. Typename specifies whether
369/// the keyword "typename" was used to declare the type parameter
370/// (otherwise, "class" was used), and KeyLoc is the location of the
371/// "class" or "typename" keyword. ParamName is the name of the
372/// parameter (NULL indicates an unnamed template parameter) and
373/// ParamName is the location of the parameter name (if any).
374/// If the type parameter has a default argument, it will be added
375/// later via ActOnTypeParameterDefault.
376Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
377                                         SourceLocation EllipsisLoc,
378                                         SourceLocation KeyLoc,
379                                         IdentifierInfo *ParamName,
380                                         SourceLocation ParamNameLoc,
381                                         unsigned Depth, unsigned Position) {
382  assert(S->isTemplateParamScope() &&
383         "Template type parameter not in template parameter scope!");
384  bool Invalid = false;
385
386  if (ParamName) {
387    NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
388    if (PrevDecl && PrevDecl->isTemplateParameter())
389      Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
390                                                           PrevDecl);
391  }
392
393  SourceLocation Loc = ParamNameLoc;
394  if (!ParamName)
395    Loc = KeyLoc;
396
397  TemplateTypeParmDecl *Param
398    = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
399                                   Depth, Position, ParamName, Typename,
400                                   Ellipsis);
401  if (Invalid)
402    Param->setInvalidDecl();
403
404  if (ParamName) {
405    // Add the template parameter into the current scope.
406    S->AddDecl(DeclPtrTy::make(Param));
407    IdResolver.AddDecl(Param);
408  }
409
410  return DeclPtrTy::make(Param);
411}
412
413/// ActOnTypeParameterDefault - Adds a default argument (the type
414/// Default) to the given template type parameter (TypeParam).
415void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
416                                     SourceLocation EqualLoc,
417                                     SourceLocation DefaultLoc,
418                                     TypeTy *DefaultT) {
419  TemplateTypeParmDecl *Parm
420    = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
421
422  TypeSourceInfo *DefaultTInfo;
423  GetTypeFromParser(DefaultT, &DefaultTInfo);
424
425  assert(DefaultTInfo && "expected source information for type");
426
427  // C++0x [temp.param]p9:
428  // A default template-argument may be specified for any kind of
429  // template-parameter that is not a template parameter pack.
430  if (Parm->isParameterPack()) {
431    Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
432    return;
433  }
434
435  // C++ [temp.param]p14:
436  //   A template-parameter shall not be used in its own default argument.
437  // FIXME: Implement this check! Needs a recursive walk over the types.
438
439  // Check the template argument itself.
440  if (CheckTemplateArgument(Parm, DefaultTInfo)) {
441    Parm->setInvalidDecl();
442    return;
443  }
444
445  Parm->setDefaultArgument(DefaultTInfo, false);
446}
447
448/// \brief Check that the type of a non-type template parameter is
449/// well-formed.
450///
451/// \returns the (possibly-promoted) parameter type if valid;
452/// otherwise, produces a diagnostic and returns a NULL type.
453QualType
454Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
455  // C++ [temp.param]p4:
456  //
457  // A non-type template-parameter shall have one of the following
458  // (optionally cv-qualified) types:
459  //
460  //       -- integral or enumeration type,
461  if (T->isIntegralType() || T->isEnumeralType() ||
462      //   -- pointer to object or pointer to function,
463      (T->isPointerType() &&
464       (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
465        T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
466      //   -- reference to object or reference to function,
467      T->isReferenceType() ||
468      //   -- pointer to member.
469      T->isMemberPointerType() ||
470      // If T is a dependent type, we can't do the check now, so we
471      // assume that it is well-formed.
472      T->isDependentType())
473    return T;
474  // C++ [temp.param]p8:
475  //
476  //   A non-type template-parameter of type "array of T" or
477  //   "function returning T" is adjusted to be of type "pointer to
478  //   T" or "pointer to function returning T", respectively.
479  else if (T->isArrayType())
480    // FIXME: Keep the type prior to promotion?
481    return Context.getArrayDecayedType(T);
482  else if (T->isFunctionType())
483    // FIXME: Keep the type prior to promotion?
484    return Context.getPointerType(T);
485
486  Diag(Loc, diag::err_template_nontype_parm_bad_type)
487    << T;
488
489  return QualType();
490}
491
492/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
493/// template parameter (e.g., "int Size" in "template<int Size>
494/// class Array") has been parsed. S is the current scope and D is
495/// the parsed declarator.
496Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
497                                                    unsigned Depth,
498                                                    unsigned Position) {
499  TypeSourceInfo *TInfo = 0;
500  QualType T = GetTypeForDeclarator(D, S, &TInfo);
501
502  assert(S->isTemplateParamScope() &&
503         "Non-type template parameter not in template parameter scope!");
504  bool Invalid = false;
505
506  IdentifierInfo *ParamName = D.getIdentifier();
507  if (ParamName) {
508    NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
509    if (PrevDecl && PrevDecl->isTemplateParameter())
510      Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
511                                                           PrevDecl);
512  }
513
514  T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
515  if (T.isNull()) {
516    T = Context.IntTy; // Recover with an 'int' type.
517    Invalid = true;
518  }
519
520  NonTypeTemplateParmDecl *Param
521    = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
522                                      Depth, Position, ParamName, T, TInfo);
523  if (Invalid)
524    Param->setInvalidDecl();
525
526  if (D.getIdentifier()) {
527    // Add the template parameter into the current scope.
528    S->AddDecl(DeclPtrTy::make(Param));
529    IdResolver.AddDecl(Param);
530  }
531  return DeclPtrTy::make(Param);
532}
533
534/// \brief Adds a default argument to the given non-type template
535/// parameter.
536void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
537                                                SourceLocation EqualLoc,
538                                                ExprArg DefaultE) {
539  NonTypeTemplateParmDecl *TemplateParm
540    = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
541  Expr *Default = static_cast<Expr *>(DefaultE.get());
542
543  // C++ [temp.param]p14:
544  //   A template-parameter shall not be used in its own default argument.
545  // FIXME: Implement this check! Needs a recursive walk over the types.
546
547  // Check the well-formedness of the default template argument.
548  TemplateArgument Converted;
549  if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
550                            Converted)) {
551    TemplateParm->setInvalidDecl();
552    return;
553  }
554
555  TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
556}
557
558
559/// ActOnTemplateTemplateParameter - Called when a C++ template template
560/// parameter (e.g. T in template <template <typename> class T> class array)
561/// has been parsed. S is the current scope.
562Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
563                                                     SourceLocation TmpLoc,
564                                                     TemplateParamsTy *Params,
565                                                     IdentifierInfo *Name,
566                                                     SourceLocation NameLoc,
567                                                     unsigned Depth,
568                                                     unsigned Position) {
569  assert(S->isTemplateParamScope() &&
570         "Template template parameter not in template parameter scope!");
571
572  // Construct the parameter object.
573  TemplateTemplateParmDecl *Param =
574    TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
575                                     Position, Name,
576                                     (TemplateParameterList*)Params);
577
578  // Make sure the parameter is valid.
579  // FIXME: Decl object is not currently invalidated anywhere so this doesn't
580  // do anything yet. However, if the template parameter list or (eventual)
581  // default value is ever invalidated, that will propagate here.
582  bool Invalid = false;
583  if (Invalid) {
584    Param->setInvalidDecl();
585  }
586
587  // If the tt-param has a name, then link the identifier into the scope
588  // and lookup mechanisms.
589  if (Name) {
590    S->AddDecl(DeclPtrTy::make(Param));
591    IdResolver.AddDecl(Param);
592  }
593
594  return DeclPtrTy::make(Param);
595}
596
597/// \brief Adds a default argument to the given template template
598/// parameter.
599void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
600                                                 SourceLocation EqualLoc,
601                                        const ParsedTemplateArgument &Default) {
602  TemplateTemplateParmDecl *TemplateParm
603    = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
604
605  // C++ [temp.param]p14:
606  //   A template-parameter shall not be used in its own default argument.
607  // FIXME: Implement this check! Needs a recursive walk over the types.
608
609  // Check only that we have a template template argument. We don't want to
610  // try to check well-formedness now, because our template template parameter
611  // might have dependent types in its template parameters, which we wouldn't
612  // be able to match now.
613  //
614  // If none of the template template parameter's template arguments mention
615  // other template parameters, we could actually perform more checking here.
616  // However, it isn't worth doing.
617  TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
618  if (DefaultArg.getArgument().getAsTemplate().isNull()) {
619    Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
620      << DefaultArg.getSourceRange();
621    return;
622  }
623
624  TemplateParm->setDefaultArgument(DefaultArg);
625}
626
627/// ActOnTemplateParameterList - Builds a TemplateParameterList that
628/// contains the template parameters in Params/NumParams.
629Sema::TemplateParamsTy *
630Sema::ActOnTemplateParameterList(unsigned Depth,
631                                 SourceLocation ExportLoc,
632                                 SourceLocation TemplateLoc,
633                                 SourceLocation LAngleLoc,
634                                 DeclPtrTy *Params, unsigned NumParams,
635                                 SourceLocation RAngleLoc) {
636  if (ExportLoc.isValid())
637    Diag(ExportLoc, diag::warn_template_export_unsupported);
638
639  return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
640                                       (NamedDecl**)Params, NumParams,
641                                       RAngleLoc);
642}
643
644Sema::DeclResult
645Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
646                         SourceLocation KWLoc, const CXXScopeSpec &SS,
647                         IdentifierInfo *Name, SourceLocation NameLoc,
648                         AttributeList *Attr,
649                         TemplateParameterList *TemplateParams,
650                         AccessSpecifier AS) {
651  assert(TemplateParams && TemplateParams->size() > 0 &&
652         "No template parameters");
653  assert(TUK != TUK_Reference && "Can only declare or define class templates");
654  bool Invalid = false;
655
656  // Check that we can declare a template here.
657  if (CheckTemplateDeclScope(S, TemplateParams))
658    return true;
659
660  TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
661  assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
662
663  // There is no such thing as an unnamed class template.
664  if (!Name) {
665    Diag(KWLoc, diag::err_template_unnamed_class);
666    return true;
667  }
668
669  // Find any previous declaration with this name.
670  DeclContext *SemanticContext;
671  LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
672                        ForRedeclaration);
673  if (SS.isNotEmpty() && !SS.isInvalid()) {
674    if (RequireCompleteDeclContext(SS))
675      return true;
676
677    SemanticContext = computeDeclContext(SS, true);
678    if (!SemanticContext) {
679      // FIXME: Produce a reasonable diagnostic here
680      return true;
681    }
682
683    LookupQualifiedName(Previous, SemanticContext);
684  } else {
685    SemanticContext = CurContext;
686    LookupName(Previous, S);
687  }
688
689  assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
690  NamedDecl *PrevDecl = 0;
691  if (Previous.begin() != Previous.end())
692    PrevDecl = *Previous.begin();
693
694  // If there is a previous declaration with the same name, check
695  // whether this is a valid redeclaration.
696  ClassTemplateDecl *PrevClassTemplate
697    = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
698
699  // We may have found the injected-class-name of a class template,
700  // class template partial specialization, or class template specialization.
701  // In these cases, grab the template that is being defined or specialized.
702  if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
703      cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
704    PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
705    PrevClassTemplate
706      = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
707    if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
708      PrevClassTemplate
709        = cast<ClassTemplateSpecializationDecl>(PrevDecl)
710            ->getSpecializedTemplate();
711    }
712  }
713
714  if (TUK == TUK_Friend) {
715    // C++ [namespace.memdef]p3:
716    //   [...] When looking for a prior declaration of a class or a function
717    //   declared as a friend, and when the name of the friend class or
718    //   function is neither a qualified name nor a template-id, scopes outside
719    //   the innermost enclosing namespace scope are not considered.
720    DeclContext *OutermostContext = CurContext;
721    while (!OutermostContext->isFileContext())
722      OutermostContext = OutermostContext->getLookupParent();
723
724    if (PrevDecl &&
725        (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
726         OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
727      SemanticContext = PrevDecl->getDeclContext();
728    } else {
729      // Declarations in outer scopes don't matter. However, the outermost
730      // context we computed is the semantic context for our new
731      // declaration.
732      PrevDecl = PrevClassTemplate = 0;
733      SemanticContext = OutermostContext;
734    }
735
736    if (CurContext->isDependentContext()) {
737      // If this is a dependent context, we don't want to link the friend
738      // class template to the template in scope, because that would perform
739      // checking of the template parameter lists that can't be performed
740      // until the outer context is instantiated.
741      PrevDecl = PrevClassTemplate = 0;
742    }
743  } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
744    PrevDecl = PrevClassTemplate = 0;
745
746  if (PrevClassTemplate) {
747    // Ensure that the template parameter lists are compatible.
748    if (!TemplateParameterListsAreEqual(TemplateParams,
749                                   PrevClassTemplate->getTemplateParameters(),
750                                        /*Complain=*/true,
751                                        TPL_TemplateMatch))
752      return true;
753
754    // C++ [temp.class]p4:
755    //   In a redeclaration, partial specialization, explicit
756    //   specialization or explicit instantiation of a class template,
757    //   the class-key shall agree in kind with the original class
758    //   template declaration (7.1.5.3).
759    RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
760    if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
761      Diag(KWLoc, diag::err_use_with_wrong_tag)
762        << Name
763        << CodeModificationHint::CreateReplacement(KWLoc,
764                            PrevRecordDecl->getKindName());
765      Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
766      Kind = PrevRecordDecl->getTagKind();
767    }
768
769    // Check for redefinition of this class template.
770    if (TUK == TUK_Definition) {
771      if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
772        Diag(NameLoc, diag::err_redefinition) << Name;
773        Diag(Def->getLocation(), diag::note_previous_definition);
774        // FIXME: Would it make sense to try to "forget" the previous
775        // definition, as part of error recovery?
776        return true;
777      }
778    }
779  } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
780    // Maybe we will complain about the shadowed template parameter.
781    DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
782    // Just pretend that we didn't see the previous declaration.
783    PrevDecl = 0;
784  } else if (PrevDecl) {
785    // C++ [temp]p5:
786    //   A class template shall not have the same name as any other
787    //   template, class, function, object, enumeration, enumerator,
788    //   namespace, or type in the same scope (3.3), except as specified
789    //   in (14.5.4).
790    Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
791    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
792    return true;
793  }
794
795  // Check the template parameter list of this declaration, possibly
796  // merging in the template parameter list from the previous class
797  // template declaration.
798  if (CheckTemplateParameterList(TemplateParams,
799            PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
800                                 TPC_ClassTemplate))
801    Invalid = true;
802
803  // FIXME: If we had a scope specifier, we better have a previous template
804  // declaration!
805
806  CXXRecordDecl *NewClass =
807    CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
808                          PrevClassTemplate?
809                            PrevClassTemplate->getTemplatedDecl() : 0,
810                          /*DelayTypeCreation=*/true);
811
812  ClassTemplateDecl *NewTemplate
813    = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
814                                DeclarationName(Name), TemplateParams,
815                                NewClass, PrevClassTemplate);
816  NewClass->setDescribedClassTemplate(NewTemplate);
817
818  // Build the type for the class template declaration now.
819  QualType T =
820    Context.getTypeDeclType(NewClass,
821                            PrevClassTemplate?
822                              PrevClassTemplate->getTemplatedDecl() : 0);
823  assert(T->isDependentType() && "Class template type is not dependent?");
824  (void)T;
825
826  // If we are providing an explicit specialization of a member that is a
827  // class template, make a note of that.
828  if (PrevClassTemplate &&
829      PrevClassTemplate->getInstantiatedFromMemberTemplate())
830    PrevClassTemplate->setMemberSpecialization();
831
832  // Set the access specifier.
833  if (!Invalid && TUK != TUK_Friend)
834    SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
835
836  // Set the lexical context of these templates
837  NewClass->setLexicalDeclContext(CurContext);
838  NewTemplate->setLexicalDeclContext(CurContext);
839
840  if (TUK == TUK_Definition)
841    NewClass->startDefinition();
842
843  if (Attr)
844    ProcessDeclAttributeList(S, NewClass, Attr);
845
846  if (TUK != TUK_Friend)
847    PushOnScopeChains(NewTemplate, S);
848  else {
849    if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
850      NewTemplate->setAccess(PrevClassTemplate->getAccess());
851      NewClass->setAccess(PrevClassTemplate->getAccess());
852    }
853
854    NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
855                                       PrevClassTemplate != NULL);
856
857    // Friend templates are visible in fairly strange ways.
858    if (!CurContext->isDependentContext()) {
859      DeclContext *DC = SemanticContext->getLookupContext();
860      DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
861      if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
862        PushOnScopeChains(NewTemplate, EnclosingScope,
863                          /* AddToContext = */ false);
864    }
865
866    FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
867                                            NewClass->getLocation(),
868                                            NewTemplate,
869                                    /*FIXME:*/NewClass->getLocation());
870    Friend->setAccess(AS_public);
871    CurContext->addDecl(Friend);
872  }
873
874  if (Invalid) {
875    NewTemplate->setInvalidDecl();
876    NewClass->setInvalidDecl();
877  }
878  return DeclPtrTy::make(NewTemplate);
879}
880
881/// \brief Diagnose the presence of a default template argument on a
882/// template parameter, which is ill-formed in certain contexts.
883///
884/// \returns true if the default template argument should be dropped.
885static bool DiagnoseDefaultTemplateArgument(Sema &S,
886                                            Sema::TemplateParamListContext TPC,
887                                            SourceLocation ParamLoc,
888                                            SourceRange DefArgRange) {
889  switch (TPC) {
890  case Sema::TPC_ClassTemplate:
891    return false;
892
893  case Sema::TPC_FunctionTemplate:
894    // C++ [temp.param]p9:
895    //   A default template-argument shall not be specified in a
896    //   function template declaration or a function template
897    //   definition [...]
898    // (This sentence is not in C++0x, per DR226).
899    if (!S.getLangOptions().CPlusPlus0x)
900      S.Diag(ParamLoc,
901             diag::err_template_parameter_default_in_function_template)
902        << DefArgRange;
903    return false;
904
905  case Sema::TPC_ClassTemplateMember:
906    // C++0x [temp.param]p9:
907    //   A default template-argument shall not be specified in the
908    //   template-parameter-lists of the definition of a member of a
909    //   class template that appears outside of the member's class.
910    S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
911      << DefArgRange;
912    return true;
913
914  case Sema::TPC_FriendFunctionTemplate:
915    // C++ [temp.param]p9:
916    //   A default template-argument shall not be specified in a
917    //   friend template declaration.
918    S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
919      << DefArgRange;
920    return true;
921
922    // FIXME: C++0x [temp.param]p9 allows default template-arguments
923    // for friend function templates if there is only a single
924    // declaration (and it is a definition). Strange!
925  }
926
927  return false;
928}
929
930/// \brief Checks the validity of a template parameter list, possibly
931/// considering the template parameter list from a previous
932/// declaration.
933///
934/// If an "old" template parameter list is provided, it must be
935/// equivalent (per TemplateParameterListsAreEqual) to the "new"
936/// template parameter list.
937///
938/// \param NewParams Template parameter list for a new template
939/// declaration. This template parameter list will be updated with any
940/// default arguments that are carried through from the previous
941/// template parameter list.
942///
943/// \param OldParams If provided, template parameter list from a
944/// previous declaration of the same template. Default template
945/// arguments will be merged from the old template parameter list to
946/// the new template parameter list.
947///
948/// \param TPC Describes the context in which we are checking the given
949/// template parameter list.
950///
951/// \returns true if an error occurred, false otherwise.
952bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
953                                      TemplateParameterList *OldParams,
954                                      TemplateParamListContext TPC) {
955  bool Invalid = false;
956
957  // C++ [temp.param]p10:
958  //   The set of default template-arguments available for use with a
959  //   template declaration or definition is obtained by merging the
960  //   default arguments from the definition (if in scope) and all
961  //   declarations in scope in the same way default function
962  //   arguments are (8.3.6).
963  bool SawDefaultArgument = false;
964  SourceLocation PreviousDefaultArgLoc;
965
966  bool SawParameterPack = false;
967  SourceLocation ParameterPackLoc;
968
969  // Dummy initialization to avoid warnings.
970  TemplateParameterList::iterator OldParam = NewParams->end();
971  if (OldParams)
972    OldParam = OldParams->begin();
973
974  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
975                                    NewParamEnd = NewParams->end();
976       NewParam != NewParamEnd; ++NewParam) {
977    // Variables used to diagnose redundant default arguments
978    bool RedundantDefaultArg = false;
979    SourceLocation OldDefaultLoc;
980    SourceLocation NewDefaultLoc;
981
982    // Variables used to diagnose missing default arguments
983    bool MissingDefaultArg = false;
984
985    // C++0x [temp.param]p11:
986    // If a template parameter of a class template is a template parameter pack,
987    // it must be the last template parameter.
988    if (SawParameterPack) {
989      Diag(ParameterPackLoc,
990           diag::err_template_param_pack_must_be_last_template_parameter);
991      Invalid = true;
992    }
993
994    if (TemplateTypeParmDecl *NewTypeParm
995          = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
996      // Check the presence of a default argument here.
997      if (NewTypeParm->hasDefaultArgument() &&
998          DiagnoseDefaultTemplateArgument(*this, TPC,
999                                          NewTypeParm->getLocation(),
1000               NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1001                                                       .getFullSourceRange()))
1002        NewTypeParm->removeDefaultArgument();
1003
1004      // Merge default arguments for template type parameters.
1005      TemplateTypeParmDecl *OldTypeParm
1006          = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
1007
1008      if (NewTypeParm->isParameterPack()) {
1009        assert(!NewTypeParm->hasDefaultArgument() &&
1010               "Parameter packs can't have a default argument!");
1011        SawParameterPack = true;
1012        ParameterPackLoc = NewTypeParm->getLocation();
1013      } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
1014                 NewTypeParm->hasDefaultArgument()) {
1015        OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1016        NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1017        SawDefaultArgument = true;
1018        RedundantDefaultArg = true;
1019        PreviousDefaultArgLoc = NewDefaultLoc;
1020      } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1021        // Merge the default argument from the old declaration to the
1022        // new declaration.
1023        SawDefaultArgument = true;
1024        NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
1025                                        true);
1026        PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1027      } else if (NewTypeParm->hasDefaultArgument()) {
1028        SawDefaultArgument = true;
1029        PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1030      } else if (SawDefaultArgument)
1031        MissingDefaultArg = true;
1032    } else if (NonTypeTemplateParmDecl *NewNonTypeParm
1033               = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
1034      // Check the presence of a default argument here.
1035      if (NewNonTypeParm->hasDefaultArgument() &&
1036          DiagnoseDefaultTemplateArgument(*this, TPC,
1037                                          NewNonTypeParm->getLocation(),
1038                    NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1039        NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1040        NewNonTypeParm->setDefaultArgument(0);
1041      }
1042
1043      // Merge default arguments for non-type template parameters
1044      NonTypeTemplateParmDecl *OldNonTypeParm
1045        = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
1046      if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
1047          NewNonTypeParm->hasDefaultArgument()) {
1048        OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1049        NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1050        SawDefaultArgument = true;
1051        RedundantDefaultArg = true;
1052        PreviousDefaultArgLoc = NewDefaultLoc;
1053      } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1054        // Merge the default argument from the old declaration to the
1055        // new declaration.
1056        SawDefaultArgument = true;
1057        // FIXME: We need to create a new kind of "default argument"
1058        // expression that points to a previous template template
1059        // parameter.
1060        NewNonTypeParm->setDefaultArgument(
1061                                        OldNonTypeParm->getDefaultArgument());
1062        PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1063      } else if (NewNonTypeParm->hasDefaultArgument()) {
1064        SawDefaultArgument = true;
1065        PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1066      } else if (SawDefaultArgument)
1067        MissingDefaultArg = true;
1068    } else {
1069      // Check the presence of a default argument here.
1070      TemplateTemplateParmDecl *NewTemplateParm
1071        = cast<TemplateTemplateParmDecl>(*NewParam);
1072      if (NewTemplateParm->hasDefaultArgument() &&
1073          DiagnoseDefaultTemplateArgument(*this, TPC,
1074                                          NewTemplateParm->getLocation(),
1075                     NewTemplateParm->getDefaultArgument().getSourceRange()))
1076        NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1077
1078      // Merge default arguments for template template parameters
1079      TemplateTemplateParmDecl *OldTemplateParm
1080        = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
1081      if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
1082          NewTemplateParm->hasDefaultArgument()) {
1083        OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1084        NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
1085        SawDefaultArgument = true;
1086        RedundantDefaultArg = true;
1087        PreviousDefaultArgLoc = NewDefaultLoc;
1088      } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1089        // Merge the default argument from the old declaration to the
1090        // new declaration.
1091        SawDefaultArgument = true;
1092        // FIXME: We need to create a new kind of "default argument" expression
1093        // that points to a previous template template parameter.
1094        NewTemplateParm->setDefaultArgument(
1095                                        OldTemplateParm->getDefaultArgument());
1096        PreviousDefaultArgLoc
1097          = OldTemplateParm->getDefaultArgument().getLocation();
1098      } else if (NewTemplateParm->hasDefaultArgument()) {
1099        SawDefaultArgument = true;
1100        PreviousDefaultArgLoc
1101          = NewTemplateParm->getDefaultArgument().getLocation();
1102      } else if (SawDefaultArgument)
1103        MissingDefaultArg = true;
1104    }
1105
1106    if (RedundantDefaultArg) {
1107      // C++ [temp.param]p12:
1108      //   A template-parameter shall not be given default arguments
1109      //   by two different declarations in the same scope.
1110      Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1111      Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1112      Invalid = true;
1113    } else if (MissingDefaultArg) {
1114      // C++ [temp.param]p11:
1115      //   If a template-parameter has a default template-argument,
1116      //   all subsequent template-parameters shall have a default
1117      //   template-argument supplied.
1118      Diag((*NewParam)->getLocation(),
1119           diag::err_template_param_default_arg_missing);
1120      Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1121      Invalid = true;
1122    }
1123
1124    // If we have an old template parameter list that we're merging
1125    // in, move on to the next parameter.
1126    if (OldParams)
1127      ++OldParam;
1128  }
1129
1130  return Invalid;
1131}
1132
1133/// \brief Match the given template parameter lists to the given scope
1134/// specifier, returning the template parameter list that applies to the
1135/// name.
1136///
1137/// \param DeclStartLoc the start of the declaration that has a scope
1138/// specifier or a template parameter list.
1139///
1140/// \param SS the scope specifier that will be matched to the given template
1141/// parameter lists. This scope specifier precedes a qualified name that is
1142/// being declared.
1143///
1144/// \param ParamLists the template parameter lists, from the outermost to the
1145/// innermost template parameter lists.
1146///
1147/// \param NumParamLists the number of template parameter lists in ParamLists.
1148///
1149/// \param IsExplicitSpecialization will be set true if the entity being
1150/// declared is an explicit specialization, false otherwise.
1151///
1152/// \returns the template parameter list, if any, that corresponds to the
1153/// name that is preceded by the scope specifier @p SS. This template
1154/// parameter list may be have template parameters (if we're declaring a
1155/// template) or may have no template parameters (if we're declaring a
1156/// template specialization), or may be NULL (if we were's declaring isn't
1157/// itself a template).
1158TemplateParameterList *
1159Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1160                                              const CXXScopeSpec &SS,
1161                                          TemplateParameterList **ParamLists,
1162                                              unsigned NumParamLists,
1163                                              bool &IsExplicitSpecialization) {
1164  IsExplicitSpecialization = false;
1165
1166  // Find the template-ids that occur within the nested-name-specifier. These
1167  // template-ids will match up with the template parameter lists.
1168  llvm::SmallVector<const TemplateSpecializationType *, 4>
1169    TemplateIdsInSpecifier;
1170  llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1171    ExplicitSpecializationsInSpecifier;
1172  for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1173       NNS; NNS = NNS->getPrefix()) {
1174    const Type *T = NNS->getAsType();
1175    if (!T) break;
1176
1177    // C++0x [temp.expl.spec]p17:
1178    //   A member or a member template may be nested within many
1179    //   enclosing class templates. In an explicit specialization for
1180    //   such a member, the member declaration shall be preceded by a
1181    //   template<> for each enclosing class template that is
1182    //   explicitly specialized.
1183    // We interpret this as forbidding typedefs of template
1184    // specializations in the scope specifiers of out-of-line decls.
1185    if (const TypedefType *TT = dyn_cast<TypedefType>(T)) {
1186      const Type *UnderlyingT = TT->LookThroughTypedefs().getTypePtr();
1187      if (isa<TemplateSpecializationType>(UnderlyingT))
1188        // FIXME: better source location information.
1189        Diag(DeclStartLoc, diag::err_typedef_in_def_scope) << QualType(T,0);
1190      T = UnderlyingT;
1191    }
1192
1193    if (const TemplateSpecializationType *SpecType
1194          = dyn_cast<TemplateSpecializationType>(T)) {
1195      TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1196      if (!Template)
1197        continue; // FIXME: should this be an error? probably...
1198
1199      if (const RecordType *Record = SpecType->getAs<RecordType>()) {
1200        ClassTemplateSpecializationDecl *SpecDecl
1201          = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1202        // If the nested name specifier refers to an explicit specialization,
1203        // we don't need a template<> header.
1204        if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1205          ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
1206          continue;
1207        }
1208      }
1209
1210      TemplateIdsInSpecifier.push_back(SpecType);
1211    }
1212  }
1213
1214  // Reverse the list of template-ids in the scope specifier, so that we can
1215  // more easily match up the template-ids and the template parameter lists.
1216  std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
1217
1218  SourceLocation FirstTemplateLoc = DeclStartLoc;
1219  if (NumParamLists)
1220    FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
1221
1222  // Match the template-ids found in the specifier to the template parameter
1223  // lists.
1224  unsigned Idx = 0;
1225  for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1226       Idx != NumTemplateIds; ++Idx) {
1227    QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1228    bool DependentTemplateId = TemplateId->isDependentType();
1229    if (Idx >= NumParamLists) {
1230      // We have a template-id without a corresponding template parameter
1231      // list.
1232      if (DependentTemplateId) {
1233        // FIXME: the location information here isn't great.
1234        Diag(SS.getRange().getBegin(),
1235             diag::err_template_spec_needs_template_parameters)
1236          << TemplateId
1237          << SS.getRange();
1238      } else {
1239        Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1240          << SS.getRange()
1241          << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1242                                                   "template<> ");
1243        IsExplicitSpecialization = true;
1244      }
1245      return 0;
1246    }
1247
1248    // Check the template parameter list against its corresponding template-id.
1249    if (DependentTemplateId) {
1250      TemplateDecl *Template
1251        = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1252
1253      if (ClassTemplateDecl *ClassTemplate
1254            = dyn_cast<ClassTemplateDecl>(Template)) {
1255        TemplateParameterList *ExpectedTemplateParams = 0;
1256        // Is this template-id naming the primary template?
1257        if (Context.hasSameType(TemplateId,
1258                             ClassTemplate->getInjectedClassNameType(Context)))
1259          ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1260        // ... or a partial specialization?
1261        else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1262                   = ClassTemplate->findPartialSpecialization(TemplateId))
1263          ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1264
1265        if (ExpectedTemplateParams)
1266          TemplateParameterListsAreEqual(ParamLists[Idx],
1267                                         ExpectedTemplateParams,
1268                                         true, TPL_TemplateMatch);
1269      }
1270
1271      CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
1272    } else if (ParamLists[Idx]->size() > 0)
1273      Diag(ParamLists[Idx]->getTemplateLoc(),
1274           diag::err_template_param_list_matches_nontemplate)
1275        << TemplateId
1276        << ParamLists[Idx]->getSourceRange();
1277    else
1278      IsExplicitSpecialization = true;
1279  }
1280
1281  // If there were at least as many template-ids as there were template
1282  // parameter lists, then there are no template parameter lists remaining for
1283  // the declaration itself.
1284  if (Idx >= NumParamLists)
1285    return 0;
1286
1287  // If there were too many template parameter lists, complain about that now.
1288  if (Idx != NumParamLists - 1) {
1289    while (Idx < NumParamLists - 1) {
1290      bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
1291      Diag(ParamLists[Idx]->getTemplateLoc(),
1292           isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1293                               : diag::err_template_spec_extra_headers)
1294        << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1295                       ParamLists[Idx]->getRAngleLoc());
1296
1297      if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1298        Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1299             diag::note_explicit_template_spec_does_not_need_header)
1300          << ExplicitSpecializationsInSpecifier.back();
1301        ExplicitSpecializationsInSpecifier.pop_back();
1302      }
1303
1304      ++Idx;
1305    }
1306  }
1307
1308  // Return the last template parameter list, which corresponds to the
1309  // entity being declared.
1310  return ParamLists[NumParamLists - 1];
1311}
1312
1313QualType Sema::CheckTemplateIdType(TemplateName Name,
1314                                   SourceLocation TemplateLoc,
1315                              const TemplateArgumentListInfo &TemplateArgs) {
1316  TemplateDecl *Template = Name.getAsTemplateDecl();
1317  if (!Template) {
1318    // The template name does not resolve to a template, so we just
1319    // build a dependent template-id type.
1320    return Context.getTemplateSpecializationType(Name, TemplateArgs);
1321  }
1322
1323  // Check that the template argument list is well-formed for this
1324  // template.
1325  TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1326                                        TemplateArgs.size());
1327  if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
1328                                false, Converted))
1329    return QualType();
1330
1331  assert((Converted.structuredSize() ==
1332            Template->getTemplateParameters()->size()) &&
1333         "Converted template argument list is too short!");
1334
1335  QualType CanonType;
1336
1337  if (Name.isDependent() ||
1338      TemplateSpecializationType::anyDependentTemplateArguments(
1339                                                      TemplateArgs)) {
1340    // This class template specialization is a dependent
1341    // type. Therefore, its canonical type is another class template
1342    // specialization type that contains all of the converted
1343    // arguments in canonical form. This ensures that, e.g., A<T> and
1344    // A<T, T> have identical types when A is declared as:
1345    //
1346    //   template<typename T, typename U = T> struct A;
1347    TemplateName CanonName = Context.getCanonicalTemplateName(Name);
1348    CanonType = Context.getTemplateSpecializationType(CanonName,
1349                                                   Converted.getFlatArguments(),
1350                                                   Converted.flatSize());
1351
1352    // FIXME: CanonType is not actually the canonical type, and unfortunately
1353    // it is a TemplateSpecializationType that we will never use again.
1354    // In the future, we need to teach getTemplateSpecializationType to only
1355    // build the canonical type and return that to us.
1356    CanonType = Context.getCanonicalType(CanonType);
1357  } else if (ClassTemplateDecl *ClassTemplate
1358               = dyn_cast<ClassTemplateDecl>(Template)) {
1359    // Find the class template specialization declaration that
1360    // corresponds to these arguments.
1361    llvm::FoldingSetNodeID ID;
1362    ClassTemplateSpecializationDecl::Profile(ID,
1363                                             Converted.getFlatArguments(),
1364                                             Converted.flatSize(),
1365                                             Context);
1366    void *InsertPos = 0;
1367    ClassTemplateSpecializationDecl *Decl
1368      = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1369    if (!Decl) {
1370      // This is the first time we have referenced this class template
1371      // specialization. Create the canonical declaration and add it to
1372      // the set of specializations.
1373      Decl = ClassTemplateSpecializationDecl::Create(Context,
1374                                    ClassTemplate->getDeclContext(),
1375                                    ClassTemplate->getLocation(),
1376                                    ClassTemplate,
1377                                    Converted, 0);
1378      ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1379      Decl->setLexicalDeclContext(CurContext);
1380    }
1381
1382    CanonType = Context.getTypeDeclType(Decl);
1383  }
1384
1385  // Build the fully-sugared type for this class template
1386  // specialization, which refers back to the class template
1387  // specialization we created or found.
1388  return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
1389}
1390
1391Action::TypeResult
1392Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
1393                          SourceLocation LAngleLoc,
1394                          ASTTemplateArgsPtr TemplateArgsIn,
1395                          SourceLocation RAngleLoc) {
1396  TemplateName Template = TemplateD.getAsVal<TemplateName>();
1397
1398  // Translate the parser's template argument list in our AST format.
1399  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
1400  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
1401
1402  QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
1403  TemplateArgsIn.release();
1404
1405  if (Result.isNull())
1406    return true;
1407
1408  TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
1409  TemplateSpecializationTypeLoc TL
1410    = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1411  TL.setTemplateNameLoc(TemplateLoc);
1412  TL.setLAngleLoc(LAngleLoc);
1413  TL.setRAngleLoc(RAngleLoc);
1414  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1415    TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1416
1417  return CreateLocInfoType(Result, DI).getAsOpaquePtr();
1418}
1419
1420Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1421                                              TagUseKind TUK,
1422                                              DeclSpec::TST TagSpec,
1423                                              SourceLocation TagLoc) {
1424  if (TypeResult.isInvalid())
1425    return Sema::TypeResult();
1426
1427  // FIXME: preserve source info, ideally without copying the DI.
1428  TypeSourceInfo *DI;
1429  QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
1430
1431  // Verify the tag specifier.
1432  TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
1433
1434  if (const RecordType *RT = Type->getAs<RecordType>()) {
1435    RecordDecl *D = RT->getDecl();
1436
1437    IdentifierInfo *Id = D->getIdentifier();
1438    assert(Id && "templated class must have an identifier");
1439
1440    if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1441      Diag(TagLoc, diag::err_use_with_wrong_tag)
1442        << Type
1443        << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1444                                                   D->getKindName());
1445      Diag(D->getLocation(), diag::note_previous_use);
1446    }
1447  }
1448
1449  QualType ElabType = Context.getElaboratedType(Type, TagKind);
1450
1451  return ElabType.getAsOpaquePtr();
1452}
1453
1454Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1455                                                 LookupResult &R,
1456                                                 bool RequiresADL,
1457                                 const TemplateArgumentListInfo &TemplateArgs) {
1458  // FIXME: Can we do any checking at this point? I guess we could check the
1459  // template arguments that we have against the template name, if the template
1460  // name refers to a single template. That's not a terribly common case,
1461  // though.
1462
1463  // These should be filtered out by our callers.
1464  assert(!R.empty() && "empty lookup results when building templateid");
1465  assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1466
1467  NestedNameSpecifier *Qualifier = 0;
1468  SourceRange QualifierRange;
1469  if (SS.isSet()) {
1470    Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1471    QualifierRange = SS.getRange();
1472  }
1473
1474  bool Dependent
1475    = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1476                                              &TemplateArgs);
1477  UnresolvedLookupExpr *ULE
1478    = UnresolvedLookupExpr::Create(Context, Dependent,
1479                                   Qualifier, QualifierRange,
1480                                   R.getLookupName(), R.getNameLoc(),
1481                                   RequiresADL, TemplateArgs);
1482  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1483    ULE->addDecl(*I);
1484
1485  return Owned(ULE);
1486}
1487
1488// We actually only call this from template instantiation.
1489Sema::OwningExprResult
1490Sema::BuildQualifiedTemplateIdExpr(const CXXScopeSpec &SS,
1491                                   DeclarationName Name,
1492                                   SourceLocation NameLoc,
1493                             const TemplateArgumentListInfo &TemplateArgs) {
1494  DeclContext *DC;
1495  if (!(DC = computeDeclContext(SS, false)) ||
1496      DC->isDependentContext() ||
1497      RequireCompleteDeclContext(SS))
1498    return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
1499
1500  LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1501  LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
1502
1503  if (R.isAmbiguous())
1504    return ExprError();
1505
1506  if (R.empty()) {
1507    Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1508      << Name << SS.getRange();
1509    return ExprError();
1510  }
1511
1512  if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1513    Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1514      << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1515    Diag(Temp->getLocation(), diag::note_referenced_class_template);
1516    return ExprError();
1517  }
1518
1519  return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
1520}
1521
1522/// \brief Form a dependent template name.
1523///
1524/// This action forms a dependent template name given the template
1525/// name and its (presumably dependent) scope specifier. For
1526/// example, given "MetaFun::template apply", the scope specifier \p
1527/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1528/// of the "template" keyword, and "apply" is the \p Name.
1529Sema::TemplateTy
1530Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1531                                 const CXXScopeSpec &SS,
1532                                 UnqualifiedId &Name,
1533                                 TypeTy *ObjectType,
1534                                 bool EnteringContext) {
1535  if ((ObjectType &&
1536       computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
1537      (SS.isSet() && computeDeclContext(SS, EnteringContext))) {
1538    // C++0x [temp.names]p5:
1539    //   If a name prefixed by the keyword template is not the name of
1540    //   a template, the program is ill-formed. [Note: the keyword
1541    //   template may not be applied to non-template members of class
1542    //   templates. -end note ] [ Note: as is the case with the
1543    //   typename prefix, the template prefix is allowed in cases
1544    //   where it is not strictly necessary; i.e., when the
1545    //   nested-name-specifier or the expression on the left of the ->
1546    //   or . is not dependent on a template-parameter, or the use
1547    //   does not appear in the scope of a template. -end note]
1548    //
1549    // Note: C++03 was more strict here, because it banned the use of
1550    // the "template" keyword prior to a template-name that was not a
1551    // dependent name. C++ DR468 relaxed this requirement (the
1552    // "template" keyword is now permitted). We follow the C++0x
1553    // rules, even in C++03 mode, retroactively applying the DR.
1554    TemplateTy Template;
1555    TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
1556                                          EnteringContext, Template);
1557    if (TNK == TNK_Non_template) {
1558      Diag(Name.getSourceRange().getBegin(),
1559           diag::err_template_kw_refers_to_non_template)
1560        << GetNameFromUnqualifiedId(Name)
1561        << Name.getSourceRange();
1562      return TemplateTy();
1563    }
1564
1565    return Template;
1566  }
1567
1568  NestedNameSpecifier *Qualifier
1569    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1570
1571  switch (Name.getKind()) {
1572  case UnqualifiedId::IK_Identifier:
1573    return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1574                                                             Name.Identifier));
1575
1576  case UnqualifiedId::IK_OperatorFunctionId:
1577    return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1578                                             Name.OperatorFunctionId.Operator));
1579
1580  case UnqualifiedId::IK_LiteralOperatorId:
1581    assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1582
1583  default:
1584    break;
1585  }
1586
1587  Diag(Name.getSourceRange().getBegin(),
1588       diag::err_template_kw_refers_to_non_template)
1589    << GetNameFromUnqualifiedId(Name)
1590    << Name.getSourceRange();
1591  return TemplateTy();
1592}
1593
1594bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
1595                                     const TemplateArgumentLoc &AL,
1596                                     TemplateArgumentListBuilder &Converted) {
1597  const TemplateArgument &Arg = AL.getArgument();
1598
1599  // Check template type parameter.
1600  if (Arg.getKind() != TemplateArgument::Type) {
1601    // C++ [temp.arg.type]p1:
1602    //   A template-argument for a template-parameter which is a
1603    //   type shall be a type-id.
1604
1605    // We have a template type parameter but the template argument
1606    // is not a type.
1607    SourceRange SR = AL.getSourceRange();
1608    Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
1609    Diag(Param->getLocation(), diag::note_template_param_here);
1610
1611    return true;
1612  }
1613
1614  if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
1615    return true;
1616
1617  // Add the converted template type argument.
1618  Converted.Append(
1619                 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
1620  return false;
1621}
1622
1623/// \brief Substitute template arguments into the default template argument for
1624/// the given template type parameter.
1625///
1626/// \param SemaRef the semantic analysis object for which we are performing
1627/// the substitution.
1628///
1629/// \param Template the template that we are synthesizing template arguments
1630/// for.
1631///
1632/// \param TemplateLoc the location of the template name that started the
1633/// template-id we are checking.
1634///
1635/// \param RAngleLoc the location of the right angle bracket ('>') that
1636/// terminates the template-id.
1637///
1638/// \param Param the template template parameter whose default we are
1639/// substituting into.
1640///
1641/// \param Converted the list of template arguments provided for template
1642/// parameters that precede \p Param in the template parameter list.
1643///
1644/// \returns the substituted template argument, or NULL if an error occurred.
1645static TypeSourceInfo *
1646SubstDefaultTemplateArgument(Sema &SemaRef,
1647                             TemplateDecl *Template,
1648                             SourceLocation TemplateLoc,
1649                             SourceLocation RAngleLoc,
1650                             TemplateTypeParmDecl *Param,
1651                             TemplateArgumentListBuilder &Converted) {
1652  TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
1653
1654  // If the argument type is dependent, instantiate it now based
1655  // on the previously-computed template arguments.
1656  if (ArgType->getType()->isDependentType()) {
1657    TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1658                                      /*TakeArgs=*/false);
1659
1660    MultiLevelTemplateArgumentList AllTemplateArgs
1661      = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1662
1663    Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1664                                     Template, Converted.getFlatArguments(),
1665                                     Converted.flatSize(),
1666                                     SourceRange(TemplateLoc, RAngleLoc));
1667
1668    ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1669                                Param->getDefaultArgumentLoc(),
1670                                Param->getDeclName());
1671  }
1672
1673  return ArgType;
1674}
1675
1676/// \brief Substitute template arguments into the default template argument for
1677/// the given non-type template parameter.
1678///
1679/// \param SemaRef the semantic analysis object for which we are performing
1680/// the substitution.
1681///
1682/// \param Template the template that we are synthesizing template arguments
1683/// for.
1684///
1685/// \param TemplateLoc the location of the template name that started the
1686/// template-id we are checking.
1687///
1688/// \param RAngleLoc the location of the right angle bracket ('>') that
1689/// terminates the template-id.
1690///
1691/// \param Param the non-type template parameter whose default we are
1692/// substituting into.
1693///
1694/// \param Converted the list of template arguments provided for template
1695/// parameters that precede \p Param in the template parameter list.
1696///
1697/// \returns the substituted template argument, or NULL if an error occurred.
1698static Sema::OwningExprResult
1699SubstDefaultTemplateArgument(Sema &SemaRef,
1700                             TemplateDecl *Template,
1701                             SourceLocation TemplateLoc,
1702                             SourceLocation RAngleLoc,
1703                             NonTypeTemplateParmDecl *Param,
1704                             TemplateArgumentListBuilder &Converted) {
1705  TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1706                                    /*TakeArgs=*/false);
1707
1708  MultiLevelTemplateArgumentList AllTemplateArgs
1709    = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1710
1711  Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1712                                   Template, Converted.getFlatArguments(),
1713                                   Converted.flatSize(),
1714                                   SourceRange(TemplateLoc, RAngleLoc));
1715
1716  return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1717}
1718
1719/// \brief Substitute template arguments into the default template argument for
1720/// the given template template parameter.
1721///
1722/// \param SemaRef the semantic analysis object for which we are performing
1723/// the substitution.
1724///
1725/// \param Template the template that we are synthesizing template arguments
1726/// for.
1727///
1728/// \param TemplateLoc the location of the template name that started the
1729/// template-id we are checking.
1730///
1731/// \param RAngleLoc the location of the right angle bracket ('>') that
1732/// terminates the template-id.
1733///
1734/// \param Param the template template parameter whose default we are
1735/// substituting into.
1736///
1737/// \param Converted the list of template arguments provided for template
1738/// parameters that precede \p Param in the template parameter list.
1739///
1740/// \returns the substituted template argument, or NULL if an error occurred.
1741static TemplateName
1742SubstDefaultTemplateArgument(Sema &SemaRef,
1743                             TemplateDecl *Template,
1744                             SourceLocation TemplateLoc,
1745                             SourceLocation RAngleLoc,
1746                             TemplateTemplateParmDecl *Param,
1747                             TemplateArgumentListBuilder &Converted) {
1748  TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1749                                    /*TakeArgs=*/false);
1750
1751  MultiLevelTemplateArgumentList AllTemplateArgs
1752    = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1753
1754  Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1755                                   Template, Converted.getFlatArguments(),
1756                                   Converted.flatSize(),
1757                                   SourceRange(TemplateLoc, RAngleLoc));
1758
1759  return SemaRef.SubstTemplateName(
1760                      Param->getDefaultArgument().getArgument().getAsTemplate(),
1761                              Param->getDefaultArgument().getTemplateNameLoc(),
1762                                   AllTemplateArgs);
1763}
1764
1765/// \brief If the given template parameter has a default template
1766/// argument, substitute into that default template argument and
1767/// return the corresponding template argument.
1768TemplateArgumentLoc
1769Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1770                                              SourceLocation TemplateLoc,
1771                                              SourceLocation RAngleLoc,
1772                                              Decl *Param,
1773                                     TemplateArgumentListBuilder &Converted) {
1774  if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1775    if (!TypeParm->hasDefaultArgument())
1776      return TemplateArgumentLoc();
1777
1778    TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
1779                                                      TemplateLoc,
1780                                                      RAngleLoc,
1781                                                      TypeParm,
1782                                                      Converted);
1783    if (DI)
1784      return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1785
1786    return TemplateArgumentLoc();
1787  }
1788
1789  if (NonTypeTemplateParmDecl *NonTypeParm
1790        = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1791    if (!NonTypeParm->hasDefaultArgument())
1792      return TemplateArgumentLoc();
1793
1794    OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1795                                                        TemplateLoc,
1796                                                        RAngleLoc,
1797                                                        NonTypeParm,
1798                                                        Converted);
1799    if (Arg.isInvalid())
1800      return TemplateArgumentLoc();
1801
1802    Expr *ArgE = Arg.takeAs<Expr>();
1803    return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1804  }
1805
1806  TemplateTemplateParmDecl *TempTempParm
1807    = cast<TemplateTemplateParmDecl>(Param);
1808  if (!TempTempParm->hasDefaultArgument())
1809    return TemplateArgumentLoc();
1810
1811  TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1812                                                    TemplateLoc,
1813                                                    RAngleLoc,
1814                                                    TempTempParm,
1815                                                    Converted);
1816  if (TName.isNull())
1817    return TemplateArgumentLoc();
1818
1819  return TemplateArgumentLoc(TemplateArgument(TName),
1820                TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1821                TempTempParm->getDefaultArgument().getTemplateNameLoc());
1822}
1823
1824/// \brief Check that the given template argument corresponds to the given
1825/// template parameter.
1826bool Sema::CheckTemplateArgument(NamedDecl *Param,
1827                                 const TemplateArgumentLoc &Arg,
1828                                 TemplateDecl *Template,
1829                                 SourceLocation TemplateLoc,
1830                                 SourceLocation RAngleLoc,
1831                                 TemplateArgumentListBuilder &Converted) {
1832  // Check template type parameters.
1833  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
1834    return CheckTemplateTypeArgument(TTP, Arg, Converted);
1835
1836  // Check non-type template parameters.
1837  if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1838    // Do substitution on the type of the non-type template parameter
1839    // with the template arguments we've seen thus far.
1840    QualType NTTPType = NTTP->getType();
1841    if (NTTPType->isDependentType()) {
1842      // Do substitution on the type of the non-type template parameter.
1843      InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1844                                 NTTP, Converted.getFlatArguments(),
1845                                 Converted.flatSize(),
1846                                 SourceRange(TemplateLoc, RAngleLoc));
1847
1848      TemplateArgumentList TemplateArgs(Context, Converted,
1849                                        /*TakeArgs=*/false);
1850      NTTPType = SubstType(NTTPType,
1851                           MultiLevelTemplateArgumentList(TemplateArgs),
1852                           NTTP->getLocation(),
1853                           NTTP->getDeclName());
1854      // If that worked, check the non-type template parameter type
1855      // for validity.
1856      if (!NTTPType.isNull())
1857        NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1858                                                     NTTP->getLocation());
1859      if (NTTPType.isNull())
1860        return true;
1861    }
1862
1863    switch (Arg.getArgument().getKind()) {
1864    case TemplateArgument::Null:
1865      assert(false && "Should never see a NULL template argument here");
1866      return true;
1867
1868    case TemplateArgument::Expression: {
1869      Expr *E = Arg.getArgument().getAsExpr();
1870      TemplateArgument Result;
1871      if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1872        return true;
1873
1874      Converted.Append(Result);
1875      break;
1876    }
1877
1878    case TemplateArgument::Declaration:
1879    case TemplateArgument::Integral:
1880      // We've already checked this template argument, so just copy
1881      // it to the list of converted arguments.
1882      Converted.Append(Arg.getArgument());
1883      break;
1884
1885    case TemplateArgument::Template:
1886      // We were given a template template argument. It may not be ill-formed;
1887      // see below.
1888      if (DependentTemplateName *DTN
1889            = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1890        // We have a template argument such as \c T::template X, which we
1891        // parsed as a template template argument. However, since we now
1892        // know that we need a non-type template argument, convert this
1893        // template name into an expression.
1894        Expr *E = DependentScopeDeclRefExpr::Create(Context,
1895                                                    DTN->getQualifier(),
1896                                               Arg.getTemplateQualifierRange(),
1897                                                    DTN->getIdentifier(),
1898                                                    Arg.getTemplateNameLoc());
1899
1900        TemplateArgument Result;
1901        if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1902          return true;
1903
1904        Converted.Append(Result);
1905        break;
1906      }
1907
1908      // We have a template argument that actually does refer to a class
1909      // template, template alias, or template template parameter, and
1910      // therefore cannot be a non-type template argument.
1911      Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
1912        << Arg.getSourceRange();
1913
1914      Diag(Param->getLocation(), diag::note_template_param_here);
1915      return true;
1916
1917    case TemplateArgument::Type: {
1918      // We have a non-type template parameter but the template
1919      // argument is a type.
1920
1921      // C++ [temp.arg]p2:
1922      //   In a template-argument, an ambiguity between a type-id and
1923      //   an expression is resolved to a type-id, regardless of the
1924      //   form of the corresponding template-parameter.
1925      //
1926      // We warn specifically about this case, since it can be rather
1927      // confusing for users.
1928      QualType T = Arg.getArgument().getAsType();
1929      SourceRange SR = Arg.getSourceRange();
1930      if (T->isFunctionType())
1931        Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
1932      else
1933        Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
1934      Diag(Param->getLocation(), diag::note_template_param_here);
1935      return true;
1936    }
1937
1938    case TemplateArgument::Pack:
1939      llvm_unreachable("Caller must expand template argument packs");
1940      break;
1941    }
1942
1943    return false;
1944  }
1945
1946
1947  // Check template template parameters.
1948  TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
1949
1950  // Substitute into the template parameter list of the template
1951  // template parameter, since previously-supplied template arguments
1952  // may appear within the template template parameter.
1953  {
1954    // Set up a template instantiation context.
1955    LocalInstantiationScope Scope(*this);
1956    InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1957                               TempParm, Converted.getFlatArguments(),
1958                               Converted.flatSize(),
1959                               SourceRange(TemplateLoc, RAngleLoc));
1960
1961    TemplateArgumentList TemplateArgs(Context, Converted,
1962                                      /*TakeArgs=*/false);
1963    TempParm = cast_or_null<TemplateTemplateParmDecl>(
1964                      SubstDecl(TempParm, CurContext,
1965                                MultiLevelTemplateArgumentList(TemplateArgs)));
1966    if (!TempParm)
1967      return true;
1968
1969    // FIXME: TempParam is leaked.
1970  }
1971
1972  switch (Arg.getArgument().getKind()) {
1973  case TemplateArgument::Null:
1974    assert(false && "Should never see a NULL template argument here");
1975    return true;
1976
1977  case TemplateArgument::Template:
1978    if (CheckTemplateArgument(TempParm, Arg))
1979      return true;
1980
1981    Converted.Append(Arg.getArgument());
1982    break;
1983
1984  case TemplateArgument::Expression:
1985  case TemplateArgument::Type:
1986    // We have a template template parameter but the template
1987    // argument does not refer to a template.
1988    Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1989    return true;
1990
1991  case TemplateArgument::Declaration:
1992    llvm_unreachable(
1993                       "Declaration argument with template template parameter");
1994    break;
1995  case TemplateArgument::Integral:
1996    llvm_unreachable(
1997                          "Integral argument with template template parameter");
1998    break;
1999
2000  case TemplateArgument::Pack:
2001    llvm_unreachable("Caller must expand template argument packs");
2002    break;
2003  }
2004
2005  return false;
2006}
2007
2008/// \brief Check that the given template argument list is well-formed
2009/// for specializing the given template.
2010bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2011                                     SourceLocation TemplateLoc,
2012                                const TemplateArgumentListInfo &TemplateArgs,
2013                                     bool PartialTemplateArgs,
2014                                     TemplateArgumentListBuilder &Converted) {
2015  TemplateParameterList *Params = Template->getTemplateParameters();
2016  unsigned NumParams = Params->size();
2017  unsigned NumArgs = TemplateArgs.size();
2018  bool Invalid = false;
2019
2020  SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2021
2022  bool HasParameterPack =
2023    NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
2024
2025  if ((NumArgs > NumParams && !HasParameterPack) ||
2026      (NumArgs < Params->getMinRequiredArguments() &&
2027       !PartialTemplateArgs)) {
2028    // FIXME: point at either the first arg beyond what we can handle,
2029    // or the '>', depending on whether we have too many or too few
2030    // arguments.
2031    SourceRange Range;
2032    if (NumArgs > NumParams)
2033      Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
2034    Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2035      << (NumArgs > NumParams)
2036      << (isa<ClassTemplateDecl>(Template)? 0 :
2037          isa<FunctionTemplateDecl>(Template)? 1 :
2038          isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2039      << Template << Range;
2040    Diag(Template->getLocation(), diag::note_template_decl_here)
2041      << Params->getSourceRange();
2042    Invalid = true;
2043  }
2044
2045  // C++ [temp.arg]p1:
2046  //   [...] The type and form of each template-argument specified in
2047  //   a template-id shall match the type and form specified for the
2048  //   corresponding parameter declared by the template in its
2049  //   template-parameter-list.
2050  unsigned ArgIdx = 0;
2051  for (TemplateParameterList::iterator Param = Params->begin(),
2052                                       ParamEnd = Params->end();
2053       Param != ParamEnd; ++Param, ++ArgIdx) {
2054    if (ArgIdx > NumArgs && PartialTemplateArgs)
2055      break;
2056
2057    // If we have a template parameter pack, check every remaining template
2058    // argument against that template parameter pack.
2059    if ((*Param)->isTemplateParameterPack()) {
2060      Converted.BeginPack();
2061      for (; ArgIdx < NumArgs; ++ArgIdx) {
2062        if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2063                                  TemplateLoc, RAngleLoc, Converted)) {
2064          Invalid = true;
2065          break;
2066        }
2067      }
2068      Converted.EndPack();
2069      continue;
2070    }
2071
2072    if (ArgIdx < NumArgs) {
2073      // Check the template argument we were given.
2074      if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2075                                TemplateLoc, RAngleLoc, Converted))
2076        return true;
2077
2078      continue;
2079    }
2080
2081    // We have a default template argument that we will use.
2082    TemplateArgumentLoc Arg;
2083
2084    // Retrieve the default template argument from the template
2085    // parameter. For each kind of template parameter, we substitute the
2086    // template arguments provided thus far and any "outer" template arguments
2087    // (when the template parameter was part of a nested template) into
2088    // the default argument.
2089    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2090      if (!TTP->hasDefaultArgument()) {
2091        assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2092        break;
2093      }
2094
2095      TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
2096                                                             Template,
2097                                                             TemplateLoc,
2098                                                             RAngleLoc,
2099                                                             TTP,
2100                                                             Converted);
2101      if (!ArgType)
2102        return true;
2103
2104      Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2105                                ArgType);
2106    } else if (NonTypeTemplateParmDecl *NTTP
2107                 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2108      if (!NTTP->hasDefaultArgument()) {
2109        assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2110        break;
2111      }
2112
2113      Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2114                                                              TemplateLoc,
2115                                                              RAngleLoc,
2116                                                              NTTP,
2117                                                              Converted);
2118      if (E.isInvalid())
2119        return true;
2120
2121      Expr *Ex = E.takeAs<Expr>();
2122      Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2123    } else {
2124      TemplateTemplateParmDecl *TempParm
2125        = cast<TemplateTemplateParmDecl>(*Param);
2126
2127      if (!TempParm->hasDefaultArgument()) {
2128        assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2129        break;
2130      }
2131
2132      TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2133                                                       TemplateLoc,
2134                                                       RAngleLoc,
2135                                                       TempParm,
2136                                                       Converted);
2137      if (Name.isNull())
2138        return true;
2139
2140      Arg = TemplateArgumentLoc(TemplateArgument(Name),
2141                  TempParm->getDefaultArgument().getTemplateQualifierRange(),
2142                  TempParm->getDefaultArgument().getTemplateNameLoc());
2143    }
2144
2145    // Introduce an instantiation record that describes where we are using
2146    // the default template argument.
2147    InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2148                                        Converted.getFlatArguments(),
2149                                        Converted.flatSize(),
2150                                        SourceRange(TemplateLoc, RAngleLoc));
2151
2152    // Check the default template argument.
2153    if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
2154                              RAngleLoc, Converted))
2155      return true;
2156  }
2157
2158  return Invalid;
2159}
2160
2161/// \brief Check a template argument against its corresponding
2162/// template type parameter.
2163///
2164/// This routine implements the semantics of C++ [temp.arg.type]. It
2165/// returns true if an error occurred, and false otherwise.
2166bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
2167                                 TypeSourceInfo *ArgInfo) {
2168  assert(ArgInfo && "invalid TypeSourceInfo");
2169  QualType Arg = ArgInfo->getType();
2170
2171  // C++ [temp.arg.type]p2:
2172  //   A local type, a type with no linkage, an unnamed type or a type
2173  //   compounded from any of these types shall not be used as a
2174  //   template-argument for a template type-parameter.
2175  //
2176  // FIXME: Perform the recursive and no-linkage type checks.
2177  const TagType *Tag = 0;
2178  if (const EnumType *EnumT = Arg->getAs<EnumType>())
2179    Tag = EnumT;
2180  else if (const RecordType *RecordT = Arg->getAs<RecordType>())
2181    Tag = RecordT;
2182  if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2183    SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2184    return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2185      << QualType(Tag, 0) << SR;
2186  } else if (Tag && !Tag->getDecl()->getDeclName() &&
2187           !Tag->getDecl()->getTypedefForAnonDecl()) {
2188    SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2189    Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
2190    Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2191    return true;
2192  } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
2193    SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2194    return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
2195  }
2196
2197  return false;
2198}
2199
2200/// \brief Checks whether the given template argument is the address
2201/// of an object or function according to C++ [temp.arg.nontype]p1.
2202bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
2203                                                          NamedDecl *&Entity) {
2204  bool Invalid = false;
2205
2206  // See through any implicit casts we added to fix the type.
2207  while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
2208    Arg = Cast->getSubExpr();
2209
2210  // C++0x allows nullptr, and there's no further checking to be done for that.
2211  if (Arg->getType()->isNullPtrType())
2212    return false;
2213
2214  // C++ [temp.arg.nontype]p1:
2215  //
2216  //   A template-argument for a non-type, non-template
2217  //   template-parameter shall be one of: [...]
2218  //
2219  //     -- the address of an object or function with external
2220  //        linkage, including function templates and function
2221  //        template-ids but excluding non-static class members,
2222  //        expressed as & id-expression where the & is optional if
2223  //        the name refers to a function or array, or if the
2224  //        corresponding template-parameter is a reference; or
2225  DeclRefExpr *DRE = 0;
2226
2227  // Ignore (and complain about) any excess parentheses.
2228  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2229    if (!Invalid) {
2230      Diag(Arg->getSourceRange().getBegin(),
2231           diag::err_template_arg_extra_parens)
2232        << Arg->getSourceRange();
2233      Invalid = true;
2234    }
2235
2236    Arg = Parens->getSubExpr();
2237  }
2238
2239  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2240    if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2241      DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2242  } else
2243    DRE = dyn_cast<DeclRefExpr>(Arg);
2244
2245  if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
2246    return Diag(Arg->getSourceRange().getBegin(),
2247                diag::err_template_arg_not_object_or_func_form)
2248      << Arg->getSourceRange();
2249
2250  // Cannot refer to non-static data members
2251  if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2252    return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2253      << Field << Arg->getSourceRange();
2254
2255  // Cannot refer to non-static member functions
2256  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2257    if (!Method->isStatic())
2258      return Diag(Arg->getSourceRange().getBegin(),
2259                  diag::err_template_arg_method)
2260        << Method << Arg->getSourceRange();
2261
2262  // Functions must have external linkage.
2263  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
2264    if (Func->getLinkage() != NamedDecl::ExternalLinkage) {
2265      Diag(Arg->getSourceRange().getBegin(),
2266           diag::err_template_arg_function_not_extern)
2267        << Func << Arg->getSourceRange();
2268      Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2269        << true;
2270      return true;
2271    }
2272
2273    // Okay: we've named a function with external linkage.
2274    Entity = Func;
2275    return Invalid;
2276  }
2277
2278  if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
2279    if (Var->getLinkage() != NamedDecl::ExternalLinkage) {
2280      Diag(Arg->getSourceRange().getBegin(),
2281           diag::err_template_arg_object_not_extern)
2282        << Var << Arg->getSourceRange();
2283      Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2284        << true;
2285      return true;
2286    }
2287
2288    // Okay: we've named an object with external linkage
2289    Entity = Var;
2290    return Invalid;
2291  }
2292
2293  // We found something else, but we don't know specifically what it is.
2294  Diag(Arg->getSourceRange().getBegin(),
2295       diag::err_template_arg_not_object_or_func)
2296      << Arg->getSourceRange();
2297  Diag(DRE->getDecl()->getLocation(),
2298       diag::note_template_arg_refers_here);
2299  return true;
2300}
2301
2302/// \brief Checks whether the given template argument is a pointer to
2303/// member constant according to C++ [temp.arg.nontype]p1.
2304bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2305                                                TemplateArgument &Converted) {
2306  bool Invalid = false;
2307
2308  // See through any implicit casts we added to fix the type.
2309  while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
2310    Arg = Cast->getSubExpr();
2311
2312  // C++0x allows nullptr, and there's no further checking to be done for that.
2313  if (Arg->getType()->isNullPtrType())
2314    return false;
2315
2316  // C++ [temp.arg.nontype]p1:
2317  //
2318  //   A template-argument for a non-type, non-template
2319  //   template-parameter shall be one of: [...]
2320  //
2321  //     -- a pointer to member expressed as described in 5.3.1.
2322  DeclRefExpr *DRE = 0;
2323
2324  // Ignore (and complain about) any excess parentheses.
2325  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2326    if (!Invalid) {
2327      Diag(Arg->getSourceRange().getBegin(),
2328           diag::err_template_arg_extra_parens)
2329        << Arg->getSourceRange();
2330      Invalid = true;
2331    }
2332
2333    Arg = Parens->getSubExpr();
2334  }
2335
2336  // A pointer-to-member constant written &Class::member.
2337  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2338    if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2339      DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2340      if (DRE && !DRE->getQualifier())
2341        DRE = 0;
2342    }
2343  }
2344  // A constant of pointer-to-member type.
2345  else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2346    if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2347      if (VD->getType()->isMemberPointerType()) {
2348        if (isa<NonTypeTemplateParmDecl>(VD) ||
2349            (isa<VarDecl>(VD) &&
2350             Context.getCanonicalType(VD->getType()).isConstQualified())) {
2351          if (Arg->isTypeDependent() || Arg->isValueDependent())
2352            Converted = TemplateArgument(Arg->Retain());
2353          else
2354            Converted = TemplateArgument(VD->getCanonicalDecl());
2355          return Invalid;
2356        }
2357      }
2358    }
2359
2360    DRE = 0;
2361  }
2362
2363  if (!DRE)
2364    return Diag(Arg->getSourceRange().getBegin(),
2365                diag::err_template_arg_not_pointer_to_member_form)
2366      << Arg->getSourceRange();
2367
2368  if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2369    assert((isa<FieldDecl>(DRE->getDecl()) ||
2370            !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2371           "Only non-static member pointers can make it here");
2372
2373    // Okay: this is the address of a non-static member, and therefore
2374    // a member pointer constant.
2375    if (Arg->isTypeDependent() || Arg->isValueDependent())
2376      Converted = TemplateArgument(Arg->Retain());
2377    else
2378      Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
2379    return Invalid;
2380  }
2381
2382  // We found something else, but we don't know specifically what it is.
2383  Diag(Arg->getSourceRange().getBegin(),
2384       diag::err_template_arg_not_pointer_to_member_form)
2385      << Arg->getSourceRange();
2386  Diag(DRE->getDecl()->getLocation(),
2387       diag::note_template_arg_refers_here);
2388  return true;
2389}
2390
2391/// \brief Check a template argument against its corresponding
2392/// non-type template parameter.
2393///
2394/// This routine implements the semantics of C++ [temp.arg.nontype].
2395/// It returns true if an error occurred, and false otherwise. \p
2396/// InstantiatedParamType is the type of the non-type template
2397/// parameter after it has been instantiated.
2398///
2399/// If no error was detected, Converted receives the converted template argument.
2400bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
2401                                 QualType InstantiatedParamType, Expr *&Arg,
2402                                 TemplateArgument &Converted) {
2403  SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2404
2405  // If either the parameter has a dependent type or the argument is
2406  // type-dependent, there's nothing we can check now.
2407  // FIXME: Add template argument to Converted!
2408  if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2409    // FIXME: Produce a cloned, canonical expression?
2410    Converted = TemplateArgument(Arg);
2411    return false;
2412  }
2413
2414  // C++ [temp.arg.nontype]p5:
2415  //   The following conversions are performed on each expression used
2416  //   as a non-type template-argument. If a non-type
2417  //   template-argument cannot be converted to the type of the
2418  //   corresponding template-parameter then the program is
2419  //   ill-formed.
2420  //
2421  //     -- for a non-type template-parameter of integral or
2422  //        enumeration type, integral promotions (4.5) and integral
2423  //        conversions (4.7) are applied.
2424  QualType ParamType = InstantiatedParamType;
2425  QualType ArgType = Arg->getType();
2426  if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
2427    // C++ [temp.arg.nontype]p1:
2428    //   A template-argument for a non-type, non-template
2429    //   template-parameter shall be one of:
2430    //
2431    //     -- an integral constant-expression of integral or enumeration
2432    //        type; or
2433    //     -- the name of a non-type template-parameter; or
2434    SourceLocation NonConstantLoc;
2435    llvm::APSInt Value;
2436    if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
2437      Diag(Arg->getSourceRange().getBegin(),
2438           diag::err_template_arg_not_integral_or_enumeral)
2439        << ArgType << Arg->getSourceRange();
2440      Diag(Param->getLocation(), diag::note_template_param_here);
2441      return true;
2442    } else if (!Arg->isValueDependent() &&
2443               !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
2444      Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2445        << ArgType << Arg->getSourceRange();
2446      return true;
2447    }
2448
2449    // FIXME: We need some way to more easily get the unqualified form
2450    // of the types without going all the way to the
2451    // canonical type.
2452    if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2453      ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2454    if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2455      ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2456
2457    // Try to convert the argument to the parameter's type.
2458    if (Context.hasSameType(ParamType, ArgType)) {
2459      // Okay: no conversion necessary
2460    } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2461               !ParamType->isEnumeralType()) {
2462      // This is an integral promotion or conversion.
2463      ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
2464    } else {
2465      // We can't perform this conversion.
2466      Diag(Arg->getSourceRange().getBegin(),
2467           diag::err_template_arg_not_convertible)
2468        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
2469      Diag(Param->getLocation(), diag::note_template_param_here);
2470      return true;
2471    }
2472
2473    QualType IntegerType = Context.getCanonicalType(ParamType);
2474    if (const EnumType *Enum = IntegerType->getAs<EnumType>())
2475      IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
2476
2477    if (!Arg->isValueDependent()) {
2478      // Check that an unsigned parameter does not receive a negative
2479      // value.
2480      if (IntegerType->isUnsignedIntegerType()
2481          && (Value.isSigned() && Value.isNegative())) {
2482        Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2483          << Value.toString(10) << Param->getType()
2484          << Arg->getSourceRange();
2485        Diag(Param->getLocation(), diag::note_template_param_here);
2486        return true;
2487      }
2488
2489      // Check that we don't overflow the template parameter type.
2490      unsigned AllowedBits = Context.getTypeSize(IntegerType);
2491      if (Value.getActiveBits() > AllowedBits) {
2492        Diag(Arg->getSourceRange().getBegin(),
2493             diag::err_template_arg_too_large)
2494          << Value.toString(10) << Param->getType()
2495          << Arg->getSourceRange();
2496        Diag(Param->getLocation(), diag::note_template_param_here);
2497        return true;
2498      }
2499
2500      if (Value.getBitWidth() != AllowedBits)
2501        Value.extOrTrunc(AllowedBits);
2502      Value.setIsSigned(IntegerType->isSignedIntegerType());
2503    }
2504
2505    // Add the value of this argument to the list of converted
2506    // arguments. We use the bitwidth and signedness of the template
2507    // parameter.
2508    if (Arg->isValueDependent()) {
2509      // The argument is value-dependent. Create a new
2510      // TemplateArgument with the converted expression.
2511      Converted = TemplateArgument(Arg);
2512      return false;
2513    }
2514
2515    Converted = TemplateArgument(Value,
2516                                 ParamType->isEnumeralType() ? ParamType
2517                                                             : IntegerType);
2518    return false;
2519  }
2520
2521  // Handle pointer-to-function, reference-to-function, and
2522  // pointer-to-member-function all in (roughly) the same way.
2523  if (// -- For a non-type template-parameter of type pointer to
2524      //    function, only the function-to-pointer conversion (4.3) is
2525      //    applied. If the template-argument represents a set of
2526      //    overloaded functions (or a pointer to such), the matching
2527      //    function is selected from the set (13.4).
2528      // In C++0x, any std::nullptr_t value can be converted.
2529      (ParamType->isPointerType() &&
2530       ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
2531      // -- For a non-type template-parameter of type reference to
2532      //    function, no conversions apply. If the template-argument
2533      //    represents a set of overloaded functions, the matching
2534      //    function is selected from the set (13.4).
2535      (ParamType->isReferenceType() &&
2536       ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
2537      // -- For a non-type template-parameter of type pointer to
2538      //    member function, no conversions apply. If the
2539      //    template-argument represents a set of overloaded member
2540      //    functions, the matching member function is selected from
2541      //    the set (13.4).
2542      // Again, C++0x allows a std::nullptr_t value.
2543      (ParamType->isMemberPointerType() &&
2544       ParamType->getAs<MemberPointerType>()->getPointeeType()
2545         ->isFunctionType())) {
2546    if (Context.hasSameUnqualifiedType(ArgType,
2547                                       ParamType.getNonReferenceType())) {
2548      // We don't have to do anything: the types already match.
2549    } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2550                 ParamType->isMemberPointerType())) {
2551      ArgType = ParamType;
2552      if (ParamType->isMemberPointerType())
2553        ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2554      else
2555        ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
2556    } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
2557      ArgType = Context.getPointerType(ArgType);
2558      ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
2559    } else if (FunctionDecl *Fn
2560                 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
2561      if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2562        return true;
2563
2564      Arg = FixOverloadedFunctionReference(Arg, Fn);
2565      ArgType = Arg->getType();
2566      if (ArgType->isFunctionType() && ParamType->isPointerType()) {
2567        ArgType = Context.getPointerType(Arg->getType());
2568        ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
2569      }
2570    }
2571
2572    if (!Context.hasSameUnqualifiedType(ArgType,
2573                                        ParamType.getNonReferenceType())) {
2574      // We can't perform this conversion.
2575      Diag(Arg->getSourceRange().getBegin(),
2576           diag::err_template_arg_not_convertible)
2577        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
2578      Diag(Param->getLocation(), diag::note_template_param_here);
2579      return true;
2580    }
2581
2582    if (ParamType->isMemberPointerType())
2583      return CheckTemplateArgumentPointerToMember(Arg, Converted);
2584
2585    NamedDecl *Entity = 0;
2586    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2587      return true;
2588
2589    if (Entity)
2590      Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
2591    Converted = TemplateArgument(Entity);
2592    return false;
2593  }
2594
2595  if (ParamType->isPointerType()) {
2596    //   -- for a non-type template-parameter of type pointer to
2597    //      object, qualification conversions (4.4) and the
2598    //      array-to-pointer conversion (4.2) are applied.
2599    // C++0x also allows a value of std::nullptr_t.
2600    assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
2601           "Only object pointers allowed here");
2602
2603    if (ArgType->isNullPtrType()) {
2604      ArgType = ParamType;
2605      ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
2606    } else if (ArgType->isArrayType()) {
2607      ArgType = Context.getArrayDecayedType(ArgType);
2608      ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
2609    }
2610
2611    if (IsQualificationConversion(ArgType, ParamType)) {
2612      ArgType = ParamType;
2613      ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
2614    }
2615
2616    if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2617      // We can't perform this conversion.
2618      Diag(Arg->getSourceRange().getBegin(),
2619           diag::err_template_arg_not_convertible)
2620        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
2621      Diag(Param->getLocation(), diag::note_template_param_here);
2622      return true;
2623    }
2624
2625    NamedDecl *Entity = 0;
2626    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2627      return true;
2628
2629    if (Entity)
2630      Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
2631    Converted = TemplateArgument(Entity);
2632    return false;
2633  }
2634
2635  if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
2636    //   -- For a non-type template-parameter of type reference to
2637    //      object, no conversions apply. The type referred to by the
2638    //      reference may be more cv-qualified than the (otherwise
2639    //      identical) type of the template-argument. The
2640    //      template-parameter is bound directly to the
2641    //      template-argument, which must be an lvalue.
2642    assert(ParamRefType->getPointeeType()->isObjectType() &&
2643           "Only object references allowed here");
2644
2645    if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
2646      Diag(Arg->getSourceRange().getBegin(),
2647           diag::err_template_arg_no_ref_bind)
2648        << InstantiatedParamType << Arg->getType()
2649        << Arg->getSourceRange();
2650      Diag(Param->getLocation(), diag::note_template_param_here);
2651      return true;
2652    }
2653
2654    unsigned ParamQuals
2655      = Context.getCanonicalType(ParamType).getCVRQualifiers();
2656    unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
2657
2658    if ((ParamQuals | ArgQuals) != ParamQuals) {
2659      Diag(Arg->getSourceRange().getBegin(),
2660           diag::err_template_arg_ref_bind_ignores_quals)
2661        << InstantiatedParamType << Arg->getType()
2662        << Arg->getSourceRange();
2663      Diag(Param->getLocation(), diag::note_template_param_here);
2664      return true;
2665    }
2666
2667    NamedDecl *Entity = 0;
2668    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2669      return true;
2670
2671    Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
2672    Converted = TemplateArgument(Entity);
2673    return false;
2674  }
2675
2676  //     -- For a non-type template-parameter of type pointer to data
2677  //        member, qualification conversions (4.4) are applied.
2678  // C++0x allows std::nullptr_t values.
2679  assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2680
2681  if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
2682    // Types match exactly: nothing more to do here.
2683  } else if (ArgType->isNullPtrType()) {
2684    ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2685  } else if (IsQualificationConversion(ArgType, ParamType)) {
2686    ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
2687  } else {
2688    // We can't perform this conversion.
2689    Diag(Arg->getSourceRange().getBegin(),
2690         diag::err_template_arg_not_convertible)
2691      << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
2692    Diag(Param->getLocation(), diag::note_template_param_here);
2693    return true;
2694  }
2695
2696  return CheckTemplateArgumentPointerToMember(Arg, Converted);
2697}
2698
2699/// \brief Check a template argument against its corresponding
2700/// template template parameter.
2701///
2702/// This routine implements the semantics of C++ [temp.arg.template].
2703/// It returns true if an error occurred, and false otherwise.
2704bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
2705                                 const TemplateArgumentLoc &Arg) {
2706  TemplateName Name = Arg.getArgument().getAsTemplate();
2707  TemplateDecl *Template = Name.getAsTemplateDecl();
2708  if (!Template) {
2709    // Any dependent template name is fine.
2710    assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2711    return false;
2712  }
2713
2714  // C++ [temp.arg.template]p1:
2715  //   A template-argument for a template template-parameter shall be
2716  //   the name of a class template, expressed as id-expression. Only
2717  //   primary class templates are considered when matching the
2718  //   template template argument with the corresponding parameter;
2719  //   partial specializations are not considered even if their
2720  //   parameter lists match that of the template template parameter.
2721  //
2722  // Note that we also allow template template parameters here, which
2723  // will happen when we are dealing with, e.g., class template
2724  // partial specializations.
2725  if (!isa<ClassTemplateDecl>(Template) &&
2726      !isa<TemplateTemplateParmDecl>(Template)) {
2727    assert(isa<FunctionTemplateDecl>(Template) &&
2728           "Only function templates are possible here");
2729    Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
2730    Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
2731      << Template;
2732  }
2733
2734  return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2735                                         Param->getTemplateParameters(),
2736                                         true,
2737                                         TPL_TemplateTemplateArgumentMatch,
2738                                         Arg.getLocation());
2739}
2740
2741/// \brief Determine whether the given template parameter lists are
2742/// equivalent.
2743///
2744/// \param New  The new template parameter list, typically written in the
2745/// source code as part of a new template declaration.
2746///
2747/// \param Old  The old template parameter list, typically found via
2748/// name lookup of the template declared with this template parameter
2749/// list.
2750///
2751/// \param Complain  If true, this routine will produce a diagnostic if
2752/// the template parameter lists are not equivalent.
2753///
2754/// \param Kind describes how we are to match the template parameter lists.
2755///
2756/// \param TemplateArgLoc If this source location is valid, then we
2757/// are actually checking the template parameter list of a template
2758/// argument (New) against the template parameter list of its
2759/// corresponding template template parameter (Old). We produce
2760/// slightly different diagnostics in this scenario.
2761///
2762/// \returns True if the template parameter lists are equal, false
2763/// otherwise.
2764bool
2765Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2766                                     TemplateParameterList *Old,
2767                                     bool Complain,
2768                                     TemplateParameterListEqualKind Kind,
2769                                     SourceLocation TemplateArgLoc) {
2770  if (Old->size() != New->size()) {
2771    if (Complain) {
2772      unsigned NextDiag = diag::err_template_param_list_different_arity;
2773      if (TemplateArgLoc.isValid()) {
2774        Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2775        NextDiag = diag::note_template_param_list_different_arity;
2776      }
2777      Diag(New->getTemplateLoc(), NextDiag)
2778          << (New->size() > Old->size())
2779          << (Kind != TPL_TemplateMatch)
2780          << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
2781      Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2782        << (Kind != TPL_TemplateMatch)
2783        << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2784    }
2785
2786    return false;
2787  }
2788
2789  for (TemplateParameterList::iterator OldParm = Old->begin(),
2790         OldParmEnd = Old->end(), NewParm = New->begin();
2791       OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2792    if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
2793      if (Complain) {
2794        unsigned NextDiag = diag::err_template_param_different_kind;
2795        if (TemplateArgLoc.isValid()) {
2796          Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2797          NextDiag = diag::note_template_param_different_kind;
2798        }
2799        Diag((*NewParm)->getLocation(), NextDiag)
2800          << (Kind != TPL_TemplateMatch);
2801        Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2802          << (Kind != TPL_TemplateMatch);
2803      }
2804      return false;
2805    }
2806
2807    if (isa<TemplateTypeParmDecl>(*OldParm)) {
2808      // Okay; all template type parameters are equivalent (since we
2809      // know we're at the same index).
2810    } else if (NonTypeTemplateParmDecl *OldNTTP
2811                 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2812      // The types of non-type template parameters must agree.
2813      NonTypeTemplateParmDecl *NewNTTP
2814        = cast<NonTypeTemplateParmDecl>(*NewParm);
2815
2816      // If we are matching a template template argument to a template
2817      // template parameter and one of the non-type template parameter types
2818      // is dependent, then we must wait until template instantiation time
2819      // to actually compare the arguments.
2820      if (Kind == TPL_TemplateTemplateArgumentMatch &&
2821          (OldNTTP->getType()->isDependentType() ||
2822           NewNTTP->getType()->isDependentType()))
2823        continue;
2824
2825      if (Context.getCanonicalType(OldNTTP->getType()) !=
2826            Context.getCanonicalType(NewNTTP->getType())) {
2827        if (Complain) {
2828          unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2829          if (TemplateArgLoc.isValid()) {
2830            Diag(TemplateArgLoc,
2831                 diag::err_template_arg_template_params_mismatch);
2832            NextDiag = diag::note_template_nontype_parm_different_type;
2833          }
2834          Diag(NewNTTP->getLocation(), NextDiag)
2835            << NewNTTP->getType()
2836            << (Kind != TPL_TemplateMatch);
2837          Diag(OldNTTP->getLocation(),
2838               diag::note_template_nontype_parm_prev_declaration)
2839            << OldNTTP->getType();
2840        }
2841        return false;
2842      }
2843    } else {
2844      // The template parameter lists of template template
2845      // parameters must agree.
2846      assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
2847             "Only template template parameters handled here");
2848      TemplateTemplateParmDecl *OldTTP
2849        = cast<TemplateTemplateParmDecl>(*OldParm);
2850      TemplateTemplateParmDecl *NewTTP
2851        = cast<TemplateTemplateParmDecl>(*NewParm);
2852      if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2853                                          OldTTP->getTemplateParameters(),
2854                                          Complain,
2855              (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
2856                                          TemplateArgLoc))
2857        return false;
2858    }
2859  }
2860
2861  return true;
2862}
2863
2864/// \brief Check whether a template can be declared within this scope.
2865///
2866/// If the template declaration is valid in this scope, returns
2867/// false. Otherwise, issues a diagnostic and returns true.
2868bool
2869Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
2870  // Find the nearest enclosing declaration scope.
2871  while ((S->getFlags() & Scope::DeclScope) == 0 ||
2872         (S->getFlags() & Scope::TemplateParamScope) != 0)
2873    S = S->getParent();
2874
2875  // C++ [temp]p2:
2876  //   A template-declaration can appear only as a namespace scope or
2877  //   class scope declaration.
2878  DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
2879  if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2880      cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
2881    return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
2882             << TemplateParams->getSourceRange();
2883
2884  while (Ctx && isa<LinkageSpecDecl>(Ctx))
2885    Ctx = Ctx->getParent();
2886
2887  if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2888    return false;
2889
2890  return Diag(TemplateParams->getTemplateLoc(),
2891              diag::err_template_outside_namespace_or_class_scope)
2892    << TemplateParams->getSourceRange();
2893}
2894
2895/// \brief Determine what kind of template specialization the given declaration
2896/// is.
2897static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2898  if (!D)
2899    return TSK_Undeclared;
2900
2901  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2902    return Record->getTemplateSpecializationKind();
2903  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2904    return Function->getTemplateSpecializationKind();
2905  if (VarDecl *Var = dyn_cast<VarDecl>(D))
2906    return Var->getTemplateSpecializationKind();
2907
2908  return TSK_Undeclared;
2909}
2910
2911/// \brief Check whether a specialization is well-formed in the current
2912/// context.
2913///
2914/// This routine determines whether a template specialization can be declared
2915/// in the current context (C++ [temp.expl.spec]p2).
2916///
2917/// \param S the semantic analysis object for which this check is being
2918/// performed.
2919///
2920/// \param Specialized the entity being specialized or instantiated, which
2921/// may be a kind of template (class template, function template, etc.) or
2922/// a member of a class template (member function, static data member,
2923/// member class).
2924///
2925/// \param PrevDecl the previous declaration of this entity, if any.
2926///
2927/// \param Loc the location of the explicit specialization or instantiation of
2928/// this entity.
2929///
2930/// \param IsPartialSpecialization whether this is a partial specialization of
2931/// a class template.
2932///
2933/// \returns true if there was an error that we cannot recover from, false
2934/// otherwise.
2935static bool CheckTemplateSpecializationScope(Sema &S,
2936                                             NamedDecl *Specialized,
2937                                             NamedDecl *PrevDecl,
2938                                             SourceLocation Loc,
2939                                             bool IsPartialSpecialization) {
2940  // Keep these "kind" numbers in sync with the %select statements in the
2941  // various diagnostics emitted by this routine.
2942  int EntityKind = 0;
2943  bool isTemplateSpecialization = false;
2944  if (isa<ClassTemplateDecl>(Specialized)) {
2945    EntityKind = IsPartialSpecialization? 1 : 0;
2946    isTemplateSpecialization = true;
2947  } else if (isa<FunctionTemplateDecl>(Specialized)) {
2948    EntityKind = 2;
2949    isTemplateSpecialization = true;
2950  } else if (isa<CXXMethodDecl>(Specialized))
2951    EntityKind = 3;
2952  else if (isa<VarDecl>(Specialized))
2953    EntityKind = 4;
2954  else if (isa<RecordDecl>(Specialized))
2955    EntityKind = 5;
2956  else {
2957    S.Diag(Loc, diag::err_template_spec_unknown_kind);
2958    S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
2959    return true;
2960  }
2961
2962  // C++ [temp.expl.spec]p2:
2963  //   An explicit specialization shall be declared in the namespace
2964  //   of which the template is a member, or, for member templates, in
2965  //   the namespace of which the enclosing class or enclosing class
2966  //   template is a member. An explicit specialization of a member
2967  //   function, member class or static data member of a class
2968  //   template shall be declared in the namespace of which the class
2969  //   template is a member. Such a declaration may also be a
2970  //   definition. If the declaration is not a definition, the
2971  //   specialization may be defined later in the name- space in which
2972  //   the explicit specialization was declared, or in a namespace
2973  //   that encloses the one in which the explicit specialization was
2974  //   declared.
2975  if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
2976    S.Diag(Loc, diag::err_template_spec_decl_function_scope)
2977      << Specialized;
2978    return true;
2979  }
2980
2981  if (S.CurContext->isRecord() && !IsPartialSpecialization) {
2982    S.Diag(Loc, diag::err_template_spec_decl_class_scope)
2983      << Specialized;
2984    return true;
2985  }
2986
2987  // C++ [temp.class.spec]p6:
2988  //   A class template partial specialization may be declared or redeclared
2989  //   in any namespace scope in which its definition may be defined (14.5.1
2990  //   and 14.5.2).
2991  bool ComplainedAboutScope = false;
2992  DeclContext *SpecializedContext
2993    = Specialized->getDeclContext()->getEnclosingNamespaceContext();
2994  DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
2995  if ((!PrevDecl ||
2996       getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
2997       getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
2998    // There is no prior declaration of this entity, so this
2999    // specialization must be in the same context as the template
3000    // itself.
3001    if (!DC->Equals(SpecializedContext)) {
3002      if (isa<TranslationUnitDecl>(SpecializedContext))
3003        S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3004        << EntityKind << Specialized;
3005      else if (isa<NamespaceDecl>(SpecializedContext))
3006        S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3007        << EntityKind << Specialized
3008        << cast<NamedDecl>(SpecializedContext);
3009
3010      S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3011      ComplainedAboutScope = true;
3012    }
3013  }
3014
3015  // Make sure that this redeclaration (or definition) occurs in an enclosing
3016  // namespace.
3017  // Note that HandleDeclarator() performs this check for explicit
3018  // specializations of function templates, static data members, and member
3019  // functions, so we skip the check here for those kinds of entities.
3020  // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
3021  // Should we refactor that check, so that it occurs later?
3022  if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
3023      !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3024        isa<FunctionDecl>(Specialized))) {
3025    if (isa<TranslationUnitDecl>(SpecializedContext))
3026      S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3027        << EntityKind << Specialized;
3028    else if (isa<NamespaceDecl>(SpecializedContext))
3029      S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3030        << EntityKind << Specialized
3031        << cast<NamedDecl>(SpecializedContext);
3032
3033    S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3034  }
3035
3036  // FIXME: check for specialization-after-instantiation errors and such.
3037
3038  return false;
3039}
3040
3041/// \brief Check the non-type template arguments of a class template
3042/// partial specialization according to C++ [temp.class.spec]p9.
3043///
3044/// \param TemplateParams the template parameters of the primary class
3045/// template.
3046///
3047/// \param TemplateArg the template arguments of the class template
3048/// partial specialization.
3049///
3050/// \param MirrorsPrimaryTemplate will be set true if the class
3051/// template partial specialization arguments are identical to the
3052/// implicit template arguments of the primary template. This is not
3053/// necessarily an error (C++0x), and it is left to the caller to diagnose
3054/// this condition when it is an error.
3055///
3056/// \returns true if there was an error, false otherwise.
3057bool Sema::CheckClassTemplatePartialSpecializationArgs(
3058                                        TemplateParameterList *TemplateParams,
3059                             const TemplateArgumentListBuilder &TemplateArgs,
3060                                        bool &MirrorsPrimaryTemplate) {
3061  // FIXME: the interface to this function will have to change to
3062  // accommodate variadic templates.
3063  MirrorsPrimaryTemplate = true;
3064
3065  const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
3066
3067  for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3068    // Determine whether the template argument list of the partial
3069    // specialization is identical to the implicit argument list of
3070    // the primary template. The caller may need to diagnostic this as
3071    // an error per C++ [temp.class.spec]p9b3.
3072    if (MirrorsPrimaryTemplate) {
3073      if (TemplateTypeParmDecl *TTP
3074            = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3075        if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
3076              Context.getCanonicalType(ArgList[I].getAsType()))
3077          MirrorsPrimaryTemplate = false;
3078      } else if (TemplateTemplateParmDecl *TTP
3079                   = dyn_cast<TemplateTemplateParmDecl>(
3080                                                 TemplateParams->getParam(I))) {
3081        TemplateName Name = ArgList[I].getAsTemplate();
3082        TemplateTemplateParmDecl *ArgDecl
3083          = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
3084        if (!ArgDecl ||
3085            ArgDecl->getIndex() != TTP->getIndex() ||
3086            ArgDecl->getDepth() != TTP->getDepth())
3087          MirrorsPrimaryTemplate = false;
3088      }
3089    }
3090
3091    NonTypeTemplateParmDecl *Param
3092      = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
3093    if (!Param) {
3094      continue;
3095    }
3096
3097    Expr *ArgExpr = ArgList[I].getAsExpr();
3098    if (!ArgExpr) {
3099      MirrorsPrimaryTemplate = false;
3100      continue;
3101    }
3102
3103    // C++ [temp.class.spec]p8:
3104    //   A non-type argument is non-specialized if it is the name of a
3105    //   non-type parameter. All other non-type arguments are
3106    //   specialized.
3107    //
3108    // Below, we check the two conditions that only apply to
3109    // specialized non-type arguments, so skip any non-specialized
3110    // arguments.
3111    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
3112      if (NonTypeTemplateParmDecl *NTTP
3113            = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
3114        if (MirrorsPrimaryTemplate &&
3115            (Param->getIndex() != NTTP->getIndex() ||
3116             Param->getDepth() != NTTP->getDepth()))
3117          MirrorsPrimaryTemplate = false;
3118
3119        continue;
3120      }
3121
3122    // C++ [temp.class.spec]p9:
3123    //   Within the argument list of a class template partial
3124    //   specialization, the following restrictions apply:
3125    //     -- A partially specialized non-type argument expression
3126    //        shall not involve a template parameter of the partial
3127    //        specialization except when the argument expression is a
3128    //        simple identifier.
3129    if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
3130      Diag(ArgExpr->getLocStart(),
3131           diag::err_dependent_non_type_arg_in_partial_spec)
3132        << ArgExpr->getSourceRange();
3133      return true;
3134    }
3135
3136    //     -- The type of a template parameter corresponding to a
3137    //        specialized non-type argument shall not be dependent on a
3138    //        parameter of the specialization.
3139    if (Param->getType()->isDependentType()) {
3140      Diag(ArgExpr->getLocStart(),
3141           diag::err_dependent_typed_non_type_arg_in_partial_spec)
3142        << Param->getType()
3143        << ArgExpr->getSourceRange();
3144      Diag(Param->getLocation(), diag::note_template_param_here);
3145      return true;
3146    }
3147
3148    MirrorsPrimaryTemplate = false;
3149  }
3150
3151  return false;
3152}
3153
3154Sema::DeclResult
3155Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3156                                       TagUseKind TUK,
3157                                       SourceLocation KWLoc,
3158                                       const CXXScopeSpec &SS,
3159                                       TemplateTy TemplateD,
3160                                       SourceLocation TemplateNameLoc,
3161                                       SourceLocation LAngleLoc,
3162                                       ASTTemplateArgsPtr TemplateArgsIn,
3163                                       SourceLocation RAngleLoc,
3164                                       AttributeList *Attr,
3165                               MultiTemplateParamsArg TemplateParameterLists) {
3166  assert(TUK != TUK_Reference && "References are not specializations");
3167
3168  // Find the class template we're specializing
3169  TemplateName Name = TemplateD.getAsVal<TemplateName>();
3170  ClassTemplateDecl *ClassTemplate
3171    = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3172
3173  if (!ClassTemplate) {
3174    Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3175      << (Name.getAsTemplateDecl() &&
3176          isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3177    return true;
3178  }
3179
3180  bool isExplicitSpecialization = false;
3181  bool isPartialSpecialization = false;
3182
3183  // Check the validity of the template headers that introduce this
3184  // template.
3185  // FIXME: We probably shouldn't complain about these headers for
3186  // friend declarations.
3187  TemplateParameterList *TemplateParams
3188    = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3189                        (TemplateParameterList**)TemplateParameterLists.get(),
3190                                              TemplateParameterLists.size(),
3191                                              isExplicitSpecialization);
3192  if (TemplateParams && TemplateParams->size() > 0) {
3193    isPartialSpecialization = true;
3194
3195    // C++ [temp.class.spec]p10:
3196    //   The template parameter list of a specialization shall not
3197    //   contain default template argument values.
3198    for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3199      Decl *Param = TemplateParams->getParam(I);
3200      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3201        if (TTP->hasDefaultArgument()) {
3202          Diag(TTP->getDefaultArgumentLoc(),
3203               diag::err_default_arg_in_partial_spec);
3204          TTP->removeDefaultArgument();
3205        }
3206      } else if (NonTypeTemplateParmDecl *NTTP
3207                   = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3208        if (Expr *DefArg = NTTP->getDefaultArgument()) {
3209          Diag(NTTP->getDefaultArgumentLoc(),
3210               diag::err_default_arg_in_partial_spec)
3211            << DefArg->getSourceRange();
3212          NTTP->setDefaultArgument(0);
3213          DefArg->Destroy(Context);
3214        }
3215      } else {
3216        TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
3217        if (TTP->hasDefaultArgument()) {
3218          Diag(TTP->getDefaultArgument().getLocation(),
3219               diag::err_default_arg_in_partial_spec)
3220            << TTP->getDefaultArgument().getSourceRange();
3221          TTP->setDefaultArgument(TemplateArgumentLoc());
3222        }
3223      }
3224    }
3225  } else if (TemplateParams) {
3226    if (TUK == TUK_Friend)
3227      Diag(KWLoc, diag::err_template_spec_friend)
3228        << CodeModificationHint::CreateRemoval(
3229                                SourceRange(TemplateParams->getTemplateLoc(),
3230                                            TemplateParams->getRAngleLoc()))
3231        << SourceRange(LAngleLoc, RAngleLoc);
3232    else
3233      isExplicitSpecialization = true;
3234  } else if (TUK != TUK_Friend) {
3235    Diag(KWLoc, diag::err_template_spec_needs_header)
3236      << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
3237    isExplicitSpecialization = true;
3238  }
3239
3240  // Check that the specialization uses the same tag kind as the
3241  // original template.
3242  TagDecl::TagKind Kind;
3243  switch (TagSpec) {
3244  default: assert(0 && "Unknown tag type!");
3245  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3246  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
3247  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
3248  }
3249  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
3250                                    Kind, KWLoc,
3251                                    *ClassTemplate->getIdentifier())) {
3252    Diag(KWLoc, diag::err_use_with_wrong_tag)
3253      << ClassTemplate
3254      << CodeModificationHint::CreateReplacement(KWLoc,
3255                            ClassTemplate->getTemplatedDecl()->getKindName());
3256    Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
3257         diag::note_previous_use);
3258    Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3259  }
3260
3261  // Translate the parser's template argument list in our AST format.
3262  TemplateArgumentListInfo TemplateArgs;
3263  TemplateArgs.setLAngleLoc(LAngleLoc);
3264  TemplateArgs.setRAngleLoc(RAngleLoc);
3265  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3266
3267  // Check that the template argument list is well-formed for this
3268  // template.
3269  TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3270                                        TemplateArgs.size());
3271  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3272                                TemplateArgs, false, Converted))
3273    return true;
3274
3275  assert((Converted.structuredSize() ==
3276            ClassTemplate->getTemplateParameters()->size()) &&
3277         "Converted template argument list is too short!");
3278
3279  // Find the class template (partial) specialization declaration that
3280  // corresponds to these arguments.
3281  llvm::FoldingSetNodeID ID;
3282  if (isPartialSpecialization) {
3283    bool MirrorsPrimaryTemplate;
3284    if (CheckClassTemplatePartialSpecializationArgs(
3285                                         ClassTemplate->getTemplateParameters(),
3286                                         Converted, MirrorsPrimaryTemplate))
3287      return true;
3288
3289    if (MirrorsPrimaryTemplate) {
3290      // C++ [temp.class.spec]p9b3:
3291      //
3292      //   -- The argument list of the specialization shall not be identical
3293      //      to the implicit argument list of the primary template.
3294      Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3295        << (TUK == TUK_Definition)
3296        << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
3297                                                           RAngleLoc));
3298      return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
3299                                ClassTemplate->getIdentifier(),
3300                                TemplateNameLoc,
3301                                Attr,
3302                                TemplateParams,
3303                                AS_none);
3304    }
3305
3306    // FIXME: Diagnose friend partial specializations
3307
3308    // FIXME: Template parameter list matters, too
3309    ClassTemplatePartialSpecializationDecl::Profile(ID,
3310                                                   Converted.getFlatArguments(),
3311                                                   Converted.flatSize(),
3312                                                    Context);
3313  } else
3314    ClassTemplateSpecializationDecl::Profile(ID,
3315                                             Converted.getFlatArguments(),
3316                                             Converted.flatSize(),
3317                                             Context);
3318  void *InsertPos = 0;
3319  ClassTemplateSpecializationDecl *PrevDecl = 0;
3320
3321  if (isPartialSpecialization)
3322    PrevDecl
3323      = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
3324                                                                    InsertPos);
3325  else
3326    PrevDecl
3327      = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3328
3329  ClassTemplateSpecializationDecl *Specialization = 0;
3330
3331  // Check whether we can declare a class template specialization in
3332  // the current scope.
3333  if (TUK != TUK_Friend &&
3334      CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
3335                                       TemplateNameLoc,
3336                                       isPartialSpecialization))
3337    return true;
3338
3339  // The canonical type
3340  QualType CanonType;
3341  if (PrevDecl &&
3342      (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3343       TUK == TUK_Friend)) {
3344    // Since the only prior class template specialization with these
3345    // arguments was referenced but not declared, or we're only
3346    // referencing this specialization as a friend, reuse that
3347    // declaration node as our own, updating its source location to
3348    // reflect our new declaration.
3349    Specialization = PrevDecl;
3350    Specialization->setLocation(TemplateNameLoc);
3351    PrevDecl = 0;
3352    CanonType = Context.getTypeDeclType(Specialization);
3353  } else if (isPartialSpecialization) {
3354    // Build the canonical type that describes the converted template
3355    // arguments of the class template partial specialization.
3356    CanonType = Context.getTemplateSpecializationType(
3357                                                  TemplateName(ClassTemplate),
3358                                                  Converted.getFlatArguments(),
3359                                                  Converted.flatSize());
3360
3361    // Create a new class template partial specialization declaration node.
3362    ClassTemplatePartialSpecializationDecl *PrevPartial
3363      = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
3364    ClassTemplatePartialSpecializationDecl *Partial
3365      = ClassTemplatePartialSpecializationDecl::Create(Context,
3366                                             ClassTemplate->getDeclContext(),
3367                                                       TemplateNameLoc,
3368                                                       TemplateParams,
3369                                                       ClassTemplate,
3370                                                       Converted,
3371                                                       TemplateArgs,
3372                                                       PrevPartial);
3373
3374    if (PrevPartial) {
3375      ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3376      ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3377    } else {
3378      ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3379    }
3380    Specialization = Partial;
3381
3382    // If we are providing an explicit specialization of a member class
3383    // template specialization, make a note of that.
3384    if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3385      PrevPartial->setMemberSpecialization();
3386
3387    // Check that all of the template parameters of the class template
3388    // partial specialization are deducible from the template
3389    // arguments. If not, this class template partial specialization
3390    // will never be used.
3391    llvm::SmallVector<bool, 8> DeducibleParams;
3392    DeducibleParams.resize(TemplateParams->size());
3393    MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3394                               TemplateParams->getDepth(),
3395                               DeducibleParams);
3396    unsigned NumNonDeducible = 0;
3397    for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3398      if (!DeducibleParams[I])
3399        ++NumNonDeducible;
3400
3401    if (NumNonDeducible) {
3402      Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3403        << (NumNonDeducible > 1)
3404        << SourceRange(TemplateNameLoc, RAngleLoc);
3405      for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3406        if (!DeducibleParams[I]) {
3407          NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3408          if (Param->getDeclName())
3409            Diag(Param->getLocation(),
3410                 diag::note_partial_spec_unused_parameter)
3411              << Param->getDeclName();
3412          else
3413            Diag(Param->getLocation(),
3414                 diag::note_partial_spec_unused_parameter)
3415              << std::string("<anonymous>");
3416        }
3417      }
3418    }
3419  } else {
3420    // Create a new class template specialization declaration node for
3421    // this explicit specialization or friend declaration.
3422    Specialization
3423      = ClassTemplateSpecializationDecl::Create(Context,
3424                                             ClassTemplate->getDeclContext(),
3425                                                TemplateNameLoc,
3426                                                ClassTemplate,
3427                                                Converted,
3428                                                PrevDecl);
3429
3430    if (PrevDecl) {
3431      ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3432      ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3433    } else {
3434      ClassTemplate->getSpecializations().InsertNode(Specialization,
3435                                                     InsertPos);
3436    }
3437
3438    CanonType = Context.getTypeDeclType(Specialization);
3439  }
3440
3441  // C++ [temp.expl.spec]p6:
3442  //   If a template, a member template or the member of a class template is
3443  //   explicitly specialized then that specialization shall be declared
3444  //   before the first use of that specialization that would cause an implicit
3445  //   instantiation to take place, in every translation unit in which such a
3446  //   use occurs; no diagnostic is required.
3447  if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3448    SourceRange Range(TemplateNameLoc, RAngleLoc);
3449    Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3450      << Context.getTypeDeclType(Specialization) << Range;
3451
3452    Diag(PrevDecl->getPointOfInstantiation(),
3453         diag::note_instantiation_required_here)
3454      << (PrevDecl->getTemplateSpecializationKind()
3455                                                != TSK_ImplicitInstantiation);
3456    return true;
3457  }
3458
3459  // If this is not a friend, note that this is an explicit specialization.
3460  if (TUK != TUK_Friend)
3461    Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3462
3463  // Check that this isn't a redefinition of this specialization.
3464  if (TUK == TUK_Definition) {
3465    if (RecordDecl *Def = Specialization->getDefinition(Context)) {
3466      SourceRange Range(TemplateNameLoc, RAngleLoc);
3467      Diag(TemplateNameLoc, diag::err_redefinition)
3468        << Context.getTypeDeclType(Specialization) << Range;
3469      Diag(Def->getLocation(), diag::note_previous_definition);
3470      Specialization->setInvalidDecl();
3471      return true;
3472    }
3473  }
3474
3475  // Build the fully-sugared type for this class template
3476  // specialization as the user wrote in the specialization
3477  // itself. This means that we'll pretty-print the type retrieved
3478  // from the specialization's declaration the way that the user
3479  // actually wrote the specialization, rather than formatting the
3480  // name based on the "canonical" representation used to store the
3481  // template arguments in the specialization.
3482  QualType WrittenTy
3483    = Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
3484  if (TUK != TUK_Friend)
3485    Specialization->setTypeAsWritten(WrittenTy);
3486  TemplateArgsIn.release();
3487
3488  // C++ [temp.expl.spec]p9:
3489  //   A template explicit specialization is in the scope of the
3490  //   namespace in which the template was defined.
3491  //
3492  // We actually implement this paragraph where we set the semantic
3493  // context (in the creation of the ClassTemplateSpecializationDecl),
3494  // but we also maintain the lexical context where the actual
3495  // definition occurs.
3496  Specialization->setLexicalDeclContext(CurContext);
3497
3498  // We may be starting the definition of this specialization.
3499  if (TUK == TUK_Definition)
3500    Specialization->startDefinition();
3501
3502  if (TUK == TUK_Friend) {
3503    FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3504                                            TemplateNameLoc,
3505                                            WrittenTy.getTypePtr(),
3506                                            /*FIXME:*/KWLoc);
3507    Friend->setAccess(AS_public);
3508    CurContext->addDecl(Friend);
3509  } else {
3510    // Add the specialization into its lexical context, so that it can
3511    // be seen when iterating through the list of declarations in that
3512    // context. However, specializations are not found by name lookup.
3513    CurContext->addDecl(Specialization);
3514  }
3515  return DeclPtrTy::make(Specialization);
3516}
3517
3518Sema::DeclPtrTy
3519Sema::ActOnTemplateDeclarator(Scope *S,
3520                              MultiTemplateParamsArg TemplateParameterLists,
3521                              Declarator &D) {
3522  return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3523}
3524
3525Sema::DeclPtrTy
3526Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
3527                               MultiTemplateParamsArg TemplateParameterLists,
3528                                      Declarator &D) {
3529  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3530  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3531         "Not a function declarator!");
3532  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3533
3534  if (FTI.hasPrototype) {
3535    // FIXME: Diagnose arguments without names in C.
3536  }
3537
3538  Scope *ParentScope = FnBodyScope->getParent();
3539
3540  DeclPtrTy DP = HandleDeclarator(ParentScope, D,
3541                                  move(TemplateParameterLists),
3542                                  /*IsFunctionDefinition=*/true);
3543  if (FunctionTemplateDecl *FunctionTemplate
3544        = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
3545    return ActOnStartOfFunctionDef(FnBodyScope,
3546                      DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
3547  if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3548    return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
3549  return DeclPtrTy();
3550}
3551
3552/// \brief Diagnose cases where we have an explicit template specialization
3553/// before/after an explicit template instantiation, producing diagnostics
3554/// for those cases where they are required and determining whether the
3555/// new specialization/instantiation will have any effect.
3556///
3557/// \param NewLoc the location of the new explicit specialization or
3558/// instantiation.
3559///
3560/// \param NewTSK the kind of the new explicit specialization or instantiation.
3561///
3562/// \param PrevDecl the previous declaration of the entity.
3563///
3564/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3565///
3566/// \param PrevPointOfInstantiation if valid, indicates where the previus
3567/// declaration was instantiated (either implicitly or explicitly).
3568///
3569/// \param SuppressNew will be set to true to indicate that the new
3570/// specialization or instantiation has no effect and should be ignored.
3571///
3572/// \returns true if there was an error that should prevent the introduction of
3573/// the new declaration into the AST, false otherwise.
3574bool
3575Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3576                                             TemplateSpecializationKind NewTSK,
3577                                             NamedDecl *PrevDecl,
3578                                             TemplateSpecializationKind PrevTSK,
3579                                        SourceLocation PrevPointOfInstantiation,
3580                                             bool &SuppressNew) {
3581  SuppressNew = false;
3582
3583  switch (NewTSK) {
3584  case TSK_Undeclared:
3585  case TSK_ImplicitInstantiation:
3586    assert(false && "Don't check implicit instantiations here");
3587    return false;
3588
3589  case TSK_ExplicitSpecialization:
3590    switch (PrevTSK) {
3591    case TSK_Undeclared:
3592    case TSK_ExplicitSpecialization:
3593      // Okay, we're just specializing something that is either already
3594      // explicitly specialized or has merely been mentioned without any
3595      // instantiation.
3596      return false;
3597
3598    case TSK_ImplicitInstantiation:
3599      if (PrevPointOfInstantiation.isInvalid()) {
3600        // The declaration itself has not actually been instantiated, so it is
3601        // still okay to specialize it.
3602        return false;
3603      }
3604      // Fall through
3605
3606    case TSK_ExplicitInstantiationDeclaration:
3607    case TSK_ExplicitInstantiationDefinition:
3608      assert((PrevTSK == TSK_ImplicitInstantiation ||
3609              PrevPointOfInstantiation.isValid()) &&
3610             "Explicit instantiation without point of instantiation?");
3611
3612      // C++ [temp.expl.spec]p6:
3613      //   If a template, a member template or the member of a class template
3614      //   is explicitly specialized then that specialization shall be declared
3615      //   before the first use of that specialization that would cause an
3616      //   implicit instantiation to take place, in every translation unit in
3617      //   which such a use occurs; no diagnostic is required.
3618      Diag(NewLoc, diag::err_specialization_after_instantiation)
3619        << PrevDecl;
3620      Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
3621        << (PrevTSK != TSK_ImplicitInstantiation);
3622
3623      return true;
3624    }
3625    break;
3626
3627  case TSK_ExplicitInstantiationDeclaration:
3628    switch (PrevTSK) {
3629    case TSK_ExplicitInstantiationDeclaration:
3630      // This explicit instantiation declaration is redundant (that's okay).
3631      SuppressNew = true;
3632      return false;
3633
3634    case TSK_Undeclared:
3635    case TSK_ImplicitInstantiation:
3636      // We're explicitly instantiating something that may have already been
3637      // implicitly instantiated; that's fine.
3638      return false;
3639
3640    case TSK_ExplicitSpecialization:
3641      // C++0x [temp.explicit]p4:
3642      //   For a given set of template parameters, if an explicit instantiation
3643      //   of a template appears after a declaration of an explicit
3644      //   specialization for that template, the explicit instantiation has no
3645      //   effect.
3646      return false;
3647
3648    case TSK_ExplicitInstantiationDefinition:
3649      // C++0x [temp.explicit]p10:
3650      //   If an entity is the subject of both an explicit instantiation
3651      //   declaration and an explicit instantiation definition in the same
3652      //   translation unit, the definition shall follow the declaration.
3653      Diag(NewLoc,
3654           diag::err_explicit_instantiation_declaration_after_definition);
3655      Diag(PrevPointOfInstantiation,
3656           diag::note_explicit_instantiation_definition_here);
3657      assert(PrevPointOfInstantiation.isValid() &&
3658             "Explicit instantiation without point of instantiation?");
3659      SuppressNew = true;
3660      return false;
3661    }
3662    break;
3663
3664  case TSK_ExplicitInstantiationDefinition:
3665    switch (PrevTSK) {
3666    case TSK_Undeclared:
3667    case TSK_ImplicitInstantiation:
3668      // We're explicitly instantiating something that may have already been
3669      // implicitly instantiated; that's fine.
3670      return false;
3671
3672    case TSK_ExplicitSpecialization:
3673      // C++ DR 259, C++0x [temp.explicit]p4:
3674      //   For a given set of template parameters, if an explicit
3675      //   instantiation of a template appears after a declaration of
3676      //   an explicit specialization for that template, the explicit
3677      //   instantiation has no effect.
3678      //
3679      // In C++98/03 mode, we only give an extension warning here, because it
3680      // is not not harmful to try to explicitly instantiate something that
3681      // has been explicitly specialized.
3682      if (!getLangOptions().CPlusPlus0x) {
3683        Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
3684          << PrevDecl;
3685        Diag(PrevDecl->getLocation(),
3686             diag::note_previous_template_specialization);
3687      }
3688      SuppressNew = true;
3689      return false;
3690
3691    case TSK_ExplicitInstantiationDeclaration:
3692      // We're explicity instantiating a definition for something for which we
3693      // were previously asked to suppress instantiations. That's fine.
3694      return false;
3695
3696    case TSK_ExplicitInstantiationDefinition:
3697      // C++0x [temp.spec]p5:
3698      //   For a given template and a given set of template-arguments,
3699      //     - an explicit instantiation definition shall appear at most once
3700      //       in a program,
3701      Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
3702        << PrevDecl;
3703      Diag(PrevPointOfInstantiation,
3704           diag::note_previous_explicit_instantiation);
3705      SuppressNew = true;
3706      return false;
3707    }
3708    break;
3709  }
3710
3711  assert(false && "Missing specialization/instantiation case?");
3712
3713  return false;
3714}
3715
3716/// \brief Perform semantic analysis for the given function template
3717/// specialization.
3718///
3719/// This routine performs all of the semantic analysis required for an
3720/// explicit function template specialization. On successful completion,
3721/// the function declaration \p FD will become a function template
3722/// specialization.
3723///
3724/// \param FD the function declaration, which will be updated to become a
3725/// function template specialization.
3726///
3727/// \param HasExplicitTemplateArgs whether any template arguments were
3728/// explicitly provided.
3729///
3730/// \param LAngleLoc the location of the left angle bracket ('<'), if
3731/// template arguments were explicitly provided.
3732///
3733/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3734/// if any.
3735///
3736/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3737/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3738/// true as in, e.g., \c void sort<>(char*, char*);
3739///
3740/// \param RAngleLoc the location of the right angle bracket ('>'), if
3741/// template arguments were explicitly provided.
3742///
3743/// \param PrevDecl the set of declarations that
3744bool
3745Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
3746                        const TemplateArgumentListInfo *ExplicitTemplateArgs,
3747                                          LookupResult &Previous) {
3748  // The set of function template specializations that could match this
3749  // explicit function template specialization.
3750  typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3751  CandidateSet Candidates;
3752
3753  DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
3754  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3755         I != E; ++I) {
3756    NamedDecl *Ovl = (*I)->getUnderlyingDecl();
3757    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
3758      // Only consider templates found within the same semantic lookup scope as
3759      // FD.
3760      if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3761        continue;
3762
3763      // C++ [temp.expl.spec]p11:
3764      //   A trailing template-argument can be left unspecified in the
3765      //   template-id naming an explicit function template specialization
3766      //   provided it can be deduced from the function argument type.
3767      // Perform template argument deduction to determine whether we may be
3768      // specializing this template.
3769      // FIXME: It is somewhat wasteful to build
3770      TemplateDeductionInfo Info(Context);
3771      FunctionDecl *Specialization = 0;
3772      if (TemplateDeductionResult TDK
3773            = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
3774                                      FD->getType(),
3775                                      Specialization,
3776                                      Info)) {
3777        // FIXME: Template argument deduction failed; record why it failed, so
3778        // that we can provide nifty diagnostics.
3779        (void)TDK;
3780        continue;
3781      }
3782
3783      // Record this candidate.
3784      Candidates.push_back(Specialization);
3785    }
3786  }
3787
3788  // Find the most specialized function template.
3789  FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3790                                                    Candidates.size(),
3791                                                    TPOC_Other,
3792                                                    FD->getLocation(),
3793                  PartialDiagnostic(diag::err_function_template_spec_no_match)
3794                    << FD->getDeclName(),
3795                  PartialDiagnostic(diag::err_function_template_spec_ambiguous)
3796                    << FD->getDeclName() << (ExplicitTemplateArgs != 0),
3797                  PartialDiagnostic(diag::note_function_template_spec_matched));
3798  if (!Specialization)
3799    return true;
3800
3801  // FIXME: Check if the prior specialization has a point of instantiation.
3802  // If so, we have run afoul of .
3803
3804  // Check the scope of this explicit specialization.
3805  if (CheckTemplateSpecializationScope(*this,
3806                                       Specialization->getPrimaryTemplate(),
3807                                       Specialization, FD->getLocation(),
3808                                       false))
3809    return true;
3810
3811  // C++ [temp.expl.spec]p6:
3812  //   If a template, a member template or the member of a class template is
3813  //   explicitly specialized then that specialization shall be declared
3814  //   before the first use of that specialization that would cause an implicit
3815  //   instantiation to take place, in every translation unit in which such a
3816  //   use occurs; no diagnostic is required.
3817  FunctionTemplateSpecializationInfo *SpecInfo
3818    = Specialization->getTemplateSpecializationInfo();
3819  assert(SpecInfo && "Function template specialization info missing?");
3820  if (SpecInfo->getPointOfInstantiation().isValid()) {
3821    Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3822      << FD;
3823    Diag(SpecInfo->getPointOfInstantiation(),
3824         diag::note_instantiation_required_here)
3825      << (Specialization->getTemplateSpecializationKind()
3826                                                != TSK_ImplicitInstantiation);
3827    return true;
3828  }
3829
3830  // Mark the prior declaration as an explicit specialization, so that later
3831  // clients know that this is an explicit specialization.
3832  SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
3833
3834  // Turn the given function declaration into a function template
3835  // specialization, with the template arguments from the previous
3836  // specialization.
3837  FD->setFunctionTemplateSpecialization(Context,
3838                                        Specialization->getPrimaryTemplate(),
3839                         new (Context) TemplateArgumentList(
3840                             *Specialization->getTemplateSpecializationArgs()),
3841                                        /*InsertPos=*/0,
3842                                        TSK_ExplicitSpecialization);
3843
3844  // The "previous declaration" for this function template specialization is
3845  // the prior function template specialization.
3846  Previous.clear();
3847  Previous.addDecl(Specialization);
3848  return false;
3849}
3850
3851/// \brief Perform semantic analysis for the given non-template member
3852/// specialization.
3853///
3854/// This routine performs all of the semantic analysis required for an
3855/// explicit member function specialization. On successful completion,
3856/// the function declaration \p FD will become a member function
3857/// specialization.
3858///
3859/// \param Member the member declaration, which will be updated to become a
3860/// specialization.
3861///
3862/// \param Previous the set of declarations, one of which may be specialized
3863/// by this function specialization;  the set will be modified to contain the
3864/// redeclared member.
3865bool
3866Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
3867  assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3868
3869  // Try to find the member we are instantiating.
3870  NamedDecl *Instantiation = 0;
3871  NamedDecl *InstantiatedFrom = 0;
3872  MemberSpecializationInfo *MSInfo = 0;
3873
3874  if (Previous.empty()) {
3875    // Nowhere to look anyway.
3876  } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
3877    for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3878           I != E; ++I) {
3879      NamedDecl *D = (*I)->getUnderlyingDecl();
3880      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
3881        if (Context.hasSameType(Function->getType(), Method->getType())) {
3882          Instantiation = Method;
3883          InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
3884          MSInfo = Method->getMemberSpecializationInfo();
3885          break;
3886        }
3887      }
3888    }
3889  } else if (isa<VarDecl>(Member)) {
3890    VarDecl *PrevVar;
3891    if (Previous.isSingleResult() &&
3892        (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
3893      if (PrevVar->isStaticDataMember()) {
3894        Instantiation = PrevVar;
3895        InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
3896        MSInfo = PrevVar->getMemberSpecializationInfo();
3897      }
3898  } else if (isa<RecordDecl>(Member)) {
3899    CXXRecordDecl *PrevRecord;
3900    if (Previous.isSingleResult() &&
3901        (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
3902      Instantiation = PrevRecord;
3903      InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
3904      MSInfo = PrevRecord->getMemberSpecializationInfo();
3905    }
3906  }
3907
3908  if (!Instantiation) {
3909    // There is no previous declaration that matches. Since member
3910    // specializations are always out-of-line, the caller will complain about
3911    // this mismatch later.
3912    return false;
3913  }
3914
3915  // Make sure that this is a specialization of a member.
3916  if (!InstantiatedFrom) {
3917    Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3918      << Member;
3919    Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3920    return true;
3921  }
3922
3923  // C++ [temp.expl.spec]p6:
3924  //   If a template, a member template or the member of a class template is
3925  //   explicitly specialized then that spe- cialization shall be declared
3926  //   before the first use of that specialization that would cause an implicit
3927  //   instantiation to take place, in every translation unit in which such a
3928  //   use occurs; no diagnostic is required.
3929  assert(MSInfo && "Member specialization info missing?");
3930  if (MSInfo->getPointOfInstantiation().isValid()) {
3931    Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
3932      << Member;
3933    Diag(MSInfo->getPointOfInstantiation(),
3934         diag::note_instantiation_required_here)
3935      << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
3936    return true;
3937  }
3938
3939  // Check the scope of this explicit specialization.
3940  if (CheckTemplateSpecializationScope(*this,
3941                                       InstantiatedFrom,
3942                                       Instantiation, Member->getLocation(),
3943                                       false))
3944    return true;
3945
3946  // Note that this is an explicit instantiation of a member.
3947  // the original declaration to note that it is an explicit specialization
3948  // (if it was previously an implicit instantiation). This latter step
3949  // makes bookkeeping easier.
3950  if (isa<FunctionDecl>(Member)) {
3951    FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
3952    if (InstantiationFunction->getTemplateSpecializationKind() ==
3953          TSK_ImplicitInstantiation) {
3954      InstantiationFunction->setTemplateSpecializationKind(
3955                                                  TSK_ExplicitSpecialization);
3956      InstantiationFunction->setLocation(Member->getLocation());
3957    }
3958
3959    cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
3960                                        cast<CXXMethodDecl>(InstantiatedFrom),
3961                                                  TSK_ExplicitSpecialization);
3962  } else if (isa<VarDecl>(Member)) {
3963    VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
3964    if (InstantiationVar->getTemplateSpecializationKind() ==
3965          TSK_ImplicitInstantiation) {
3966      InstantiationVar->setTemplateSpecializationKind(
3967                                                  TSK_ExplicitSpecialization);
3968      InstantiationVar->setLocation(Member->getLocation());
3969    }
3970
3971    Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
3972                                                cast<VarDecl>(InstantiatedFrom),
3973                                                TSK_ExplicitSpecialization);
3974  } else {
3975    assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
3976    CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
3977    if (InstantiationClass->getTemplateSpecializationKind() ==
3978          TSK_ImplicitInstantiation) {
3979      InstantiationClass->setTemplateSpecializationKind(
3980                                                   TSK_ExplicitSpecialization);
3981      InstantiationClass->setLocation(Member->getLocation());
3982    }
3983
3984    cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
3985                                        cast<CXXRecordDecl>(InstantiatedFrom),
3986                                                   TSK_ExplicitSpecialization);
3987  }
3988
3989  // Save the caller the trouble of having to figure out which declaration
3990  // this specialization matches.
3991  Previous.clear();
3992  Previous.addDecl(Instantiation);
3993  return false;
3994}
3995
3996/// \brief Check the scope of an explicit instantiation.
3997static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
3998                                            SourceLocation InstLoc,
3999                                            bool WasQualifiedName) {
4000  DeclContext *ExpectedContext
4001    = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4002  DeclContext *CurContext = S.CurContext->getLookupContext();
4003
4004  // C++0x [temp.explicit]p2:
4005  //   An explicit instantiation shall appear in an enclosing namespace of its
4006  //   template.
4007  //
4008  // This is DR275, which we do not retroactively apply to C++98/03.
4009  if (S.getLangOptions().CPlusPlus0x &&
4010      !CurContext->Encloses(ExpectedContext)) {
4011    if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
4012      S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
4013        << D << NS;
4014    else
4015      S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
4016        << D;
4017    S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4018    return;
4019  }
4020
4021  // C++0x [temp.explicit]p2:
4022  //   If the name declared in the explicit instantiation is an unqualified
4023  //   name, the explicit instantiation shall appear in the namespace where
4024  //   its template is declared or, if that namespace is inline (7.3.1), any
4025  //   namespace from its enclosing namespace set.
4026  if (WasQualifiedName)
4027    return;
4028
4029  if (CurContext->Equals(ExpectedContext))
4030    return;
4031
4032  S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
4033    << D << ExpectedContext;
4034  S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4035}
4036
4037/// \brief Determine whether the given scope specifier has a template-id in it.
4038static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4039  if (!SS.isSet())
4040    return false;
4041
4042  // C++0x [temp.explicit]p2:
4043  //   If the explicit instantiation is for a member function, a member class
4044  //   or a static data member of a class template specialization, the name of
4045  //   the class template specialization in the qualified-id for the member
4046  //   name shall be a simple-template-id.
4047  //
4048  // C++98 has the same restriction, just worded differently.
4049  for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4050       NNS; NNS = NNS->getPrefix())
4051    if (Type *T = NNS->getAsType())
4052      if (isa<TemplateSpecializationType>(T))
4053        return true;
4054
4055  return false;
4056}
4057
4058// Explicit instantiation of a class template specialization
4059// FIXME: Implement extern template semantics
4060Sema::DeclResult
4061Sema::ActOnExplicitInstantiation(Scope *S,
4062                                 SourceLocation ExternLoc,
4063                                 SourceLocation TemplateLoc,
4064                                 unsigned TagSpec,
4065                                 SourceLocation KWLoc,
4066                                 const CXXScopeSpec &SS,
4067                                 TemplateTy TemplateD,
4068                                 SourceLocation TemplateNameLoc,
4069                                 SourceLocation LAngleLoc,
4070                                 ASTTemplateArgsPtr TemplateArgsIn,
4071                                 SourceLocation RAngleLoc,
4072                                 AttributeList *Attr) {
4073  // Find the class template we're specializing
4074  TemplateName Name = TemplateD.getAsVal<TemplateName>();
4075  ClassTemplateDecl *ClassTemplate
4076    = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4077
4078  // Check that the specialization uses the same tag kind as the
4079  // original template.
4080  TagDecl::TagKind Kind;
4081  switch (TagSpec) {
4082  default: assert(0 && "Unknown tag type!");
4083  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
4084  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
4085  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
4086  }
4087  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
4088                                    Kind, KWLoc,
4089                                    *ClassTemplate->getIdentifier())) {
4090    Diag(KWLoc, diag::err_use_with_wrong_tag)
4091      << ClassTemplate
4092      << CodeModificationHint::CreateReplacement(KWLoc,
4093                            ClassTemplate->getTemplatedDecl()->getKindName());
4094    Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
4095         diag::note_previous_use);
4096    Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4097  }
4098
4099  // C++0x [temp.explicit]p2:
4100  //   There are two forms of explicit instantiation: an explicit instantiation
4101  //   definition and an explicit instantiation declaration. An explicit
4102  //   instantiation declaration begins with the extern keyword. [...]
4103  TemplateSpecializationKind TSK
4104    = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4105                           : TSK_ExplicitInstantiationDeclaration;
4106
4107  // Translate the parser's template argument list in our AST format.
4108  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4109  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4110
4111  // Check that the template argument list is well-formed for this
4112  // template.
4113  TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4114                                        TemplateArgs.size());
4115  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4116                                TemplateArgs, false, Converted))
4117    return true;
4118
4119  assert((Converted.structuredSize() ==
4120            ClassTemplate->getTemplateParameters()->size()) &&
4121         "Converted template argument list is too short!");
4122
4123  // Find the class template specialization declaration that
4124  // corresponds to these arguments.
4125  llvm::FoldingSetNodeID ID;
4126  ClassTemplateSpecializationDecl::Profile(ID,
4127                                           Converted.getFlatArguments(),
4128                                           Converted.flatSize(),
4129                                           Context);
4130  void *InsertPos = 0;
4131  ClassTemplateSpecializationDecl *PrevDecl
4132    = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4133
4134  // C++0x [temp.explicit]p2:
4135  //   [...] An explicit instantiation shall appear in an enclosing
4136  //   namespace of its template. [...]
4137  //
4138  // This is C++ DR 275.
4139  CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4140                                  SS.isSet());
4141
4142  ClassTemplateSpecializationDecl *Specialization = 0;
4143
4144  bool ReusedDecl = false;
4145  if (PrevDecl) {
4146    bool SuppressNew = false;
4147    if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
4148                                               PrevDecl,
4149                                              PrevDecl->getSpecializationKind(),
4150                                            PrevDecl->getPointOfInstantiation(),
4151                                               SuppressNew))
4152      return DeclPtrTy::make(PrevDecl);
4153
4154    if (SuppressNew)
4155      return DeclPtrTy::make(PrevDecl);
4156
4157    if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4158        PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4159      // Since the only prior class template specialization with these
4160      // arguments was referenced but not declared, reuse that
4161      // declaration node as our own, updating its source location to
4162      // reflect our new declaration.
4163      Specialization = PrevDecl;
4164      Specialization->setLocation(TemplateNameLoc);
4165      PrevDecl = 0;
4166      ReusedDecl = true;
4167    }
4168  }
4169
4170  if (!Specialization) {
4171    // Create a new class template specialization declaration node for
4172    // this explicit specialization.
4173    Specialization
4174      = ClassTemplateSpecializationDecl::Create(Context,
4175                                             ClassTemplate->getDeclContext(),
4176                                                TemplateNameLoc,
4177                                                ClassTemplate,
4178                                                Converted, PrevDecl);
4179
4180    if (PrevDecl) {
4181      // Remove the previous declaration from the folding set, since we want
4182      // to introduce a new declaration.
4183      ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4184      ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4185    }
4186
4187    // Insert the new specialization.
4188    ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
4189  }
4190
4191  // Build the fully-sugared type for this explicit instantiation as
4192  // the user wrote in the explicit instantiation itself. This means
4193  // that we'll pretty-print the type retrieved from the
4194  // specialization's declaration the way that the user actually wrote
4195  // the explicit instantiation, rather than formatting the name based
4196  // on the "canonical" representation used to store the template
4197  // arguments in the specialization.
4198  QualType WrittenTy
4199    = Context.getTemplateSpecializationType(Name, TemplateArgs,
4200                                  Context.getTypeDeclType(Specialization));
4201  Specialization->setTypeAsWritten(WrittenTy);
4202  TemplateArgsIn.release();
4203
4204  if (!ReusedDecl) {
4205    // Add the explicit instantiation into its lexical context. However,
4206    // since explicit instantiations are never found by name lookup, we
4207    // just put it into the declaration context directly.
4208    Specialization->setLexicalDeclContext(CurContext);
4209    CurContext->addDecl(Specialization);
4210  }
4211
4212  // C++ [temp.explicit]p3:
4213  //   A definition of a class template or class member template
4214  //   shall be in scope at the point of the explicit instantiation of
4215  //   the class template or class member template.
4216  //
4217  // This check comes when we actually try to perform the
4218  // instantiation.
4219  ClassTemplateSpecializationDecl *Def
4220    = cast_or_null<ClassTemplateSpecializationDecl>(
4221                                        Specialization->getDefinition(Context));
4222  if (!Def)
4223    InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
4224
4225  // Instantiate the members of this class template specialization.
4226  Def = cast_or_null<ClassTemplateSpecializationDecl>(
4227                                       Specialization->getDefinition(Context));
4228  if (Def)
4229    InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
4230
4231  return DeclPtrTy::make(Specialization);
4232}
4233
4234// Explicit instantiation of a member class of a class template.
4235Sema::DeclResult
4236Sema::ActOnExplicitInstantiation(Scope *S,
4237                                 SourceLocation ExternLoc,
4238                                 SourceLocation TemplateLoc,
4239                                 unsigned TagSpec,
4240                                 SourceLocation KWLoc,
4241                                 const CXXScopeSpec &SS,
4242                                 IdentifierInfo *Name,
4243                                 SourceLocation NameLoc,
4244                                 AttributeList *Attr) {
4245
4246  bool Owned = false;
4247  bool IsDependent = false;
4248  DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
4249                            KWLoc, SS, Name, NameLoc, Attr, AS_none,
4250                            MultiTemplateParamsArg(*this, 0, 0),
4251                            Owned, IsDependent);
4252  assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4253
4254  if (!TagD)
4255    return true;
4256
4257  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4258  if (Tag->isEnum()) {
4259    Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4260      << Context.getTypeDeclType(Tag);
4261    return true;
4262  }
4263
4264  if (Tag->isInvalidDecl())
4265    return true;
4266
4267  CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4268  CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4269  if (!Pattern) {
4270    Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4271      << Context.getTypeDeclType(Record);
4272    Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4273    return true;
4274  }
4275
4276  // C++0x [temp.explicit]p2:
4277  //   If the explicit instantiation is for a class or member class, the
4278  //   elaborated-type-specifier in the declaration shall include a
4279  //   simple-template-id.
4280  //
4281  // C++98 has the same restriction, just worded differently.
4282  if (!ScopeSpecifierHasTemplateId(SS))
4283    Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4284      << Record << SS.getRange();
4285
4286  // C++0x [temp.explicit]p2:
4287  //   There are two forms of explicit instantiation: an explicit instantiation
4288  //   definition and an explicit instantiation declaration. An explicit
4289  //   instantiation declaration begins with the extern keyword. [...]
4290  TemplateSpecializationKind TSK
4291    = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4292                           : TSK_ExplicitInstantiationDeclaration;
4293
4294  // C++0x [temp.explicit]p2:
4295  //   [...] An explicit instantiation shall appear in an enclosing
4296  //   namespace of its template. [...]
4297  //
4298  // This is C++ DR 275.
4299  CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
4300
4301  // Verify that it is okay to explicitly instantiate here.
4302  CXXRecordDecl *PrevDecl
4303    = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
4304  if (!PrevDecl && Record->getDefinition(Context))
4305    PrevDecl = Record;
4306  if (PrevDecl) {
4307    MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4308    bool SuppressNew = false;
4309    assert(MSInfo && "No member specialization information?");
4310    if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
4311                                               PrevDecl,
4312                                        MSInfo->getTemplateSpecializationKind(),
4313                                             MSInfo->getPointOfInstantiation(),
4314                                               SuppressNew))
4315      return true;
4316    if (SuppressNew)
4317      return TagD;
4318  }
4319
4320  CXXRecordDecl *RecordDef
4321    = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4322  if (!RecordDef) {
4323    // C++ [temp.explicit]p3:
4324    //   A definition of a member class of a class template shall be in scope
4325    //   at the point of an explicit instantiation of the member class.
4326    CXXRecordDecl *Def
4327      = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
4328    if (!Def) {
4329      Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4330        << 0 << Record->getDeclName() << Record->getDeclContext();
4331      Diag(Pattern->getLocation(), diag::note_forward_declaration)
4332        << Pattern;
4333      return true;
4334    } else {
4335      if (InstantiateClass(NameLoc, Record, Def,
4336                           getTemplateInstantiationArgs(Record),
4337                           TSK))
4338        return true;
4339
4340      RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4341      if (!RecordDef)
4342        return true;
4343    }
4344  }
4345
4346  // Instantiate all of the members of the class.
4347  InstantiateClassMembers(NameLoc, RecordDef,
4348                          getTemplateInstantiationArgs(Record), TSK);
4349
4350  // FIXME: We don't have any representation for explicit instantiations of
4351  // member classes. Such a representation is not needed for compilation, but it
4352  // should be available for clients that want to see all of the declarations in
4353  // the source code.
4354  return TagD;
4355}
4356
4357Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4358                                                  SourceLocation ExternLoc,
4359                                                  SourceLocation TemplateLoc,
4360                                                  Declarator &D) {
4361  // Explicit instantiations always require a name.
4362  DeclarationName Name = GetNameForDeclarator(D);
4363  if (!Name) {
4364    if (!D.isInvalidType())
4365      Diag(D.getDeclSpec().getSourceRange().getBegin(),
4366           diag::err_explicit_instantiation_requires_name)
4367        << D.getDeclSpec().getSourceRange()
4368        << D.getSourceRange();
4369
4370    return true;
4371  }
4372
4373  // The scope passed in may not be a decl scope.  Zip up the scope tree until
4374  // we find one that is.
4375  while ((S->getFlags() & Scope::DeclScope) == 0 ||
4376         (S->getFlags() & Scope::TemplateParamScope) != 0)
4377    S = S->getParent();
4378
4379  // Determine the type of the declaration.
4380  QualType R = GetTypeForDeclarator(D, S, 0);
4381  if (R.isNull())
4382    return true;
4383
4384  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4385    // Cannot explicitly instantiate a typedef.
4386    Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4387      << Name;
4388    return true;
4389  }
4390
4391  // C++0x [temp.explicit]p1:
4392  //   [...] An explicit instantiation of a function template shall not use the
4393  //   inline or constexpr specifiers.
4394  // Presumably, this also applies to member functions of class templates as
4395  // well.
4396  if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4397    Diag(D.getDeclSpec().getInlineSpecLoc(),
4398         diag::err_explicit_instantiation_inline)
4399      <<CodeModificationHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
4400
4401  // FIXME: check for constexpr specifier.
4402
4403  // C++0x [temp.explicit]p2:
4404  //   There are two forms of explicit instantiation: an explicit instantiation
4405  //   definition and an explicit instantiation declaration. An explicit
4406  //   instantiation declaration begins with the extern keyword. [...]
4407  TemplateSpecializationKind TSK
4408    = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4409                           : TSK_ExplicitInstantiationDeclaration;
4410
4411  LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4412  LookupParsedName(Previous, S, &D.getCXXScopeSpec());
4413
4414  if (!R->isFunctionType()) {
4415    // C++ [temp.explicit]p1:
4416    //   A [...] static data member of a class template can be explicitly
4417    //   instantiated from the member definition associated with its class
4418    //   template.
4419    if (Previous.isAmbiguous())
4420      return true;
4421
4422    VarDecl *Prev = Previous.getAsSingle<VarDecl>();
4423    if (!Prev || !Prev->isStaticDataMember()) {
4424      // We expect to see a data data member here.
4425      Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4426        << Name;
4427      for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4428           P != PEnd; ++P)
4429        Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
4430      return true;
4431    }
4432
4433    if (!Prev->getInstantiatedFromStaticDataMember()) {
4434      // FIXME: Check for explicit specialization?
4435      Diag(D.getIdentifierLoc(),
4436           diag::err_explicit_instantiation_data_member_not_instantiated)
4437        << Prev;
4438      Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4439      // FIXME: Can we provide a note showing where this was declared?
4440      return true;
4441    }
4442
4443    // C++0x [temp.explicit]p2:
4444    //   If the explicit instantiation is for a member function, a member class
4445    //   or a static data member of a class template specialization, the name of
4446    //   the class template specialization in the qualified-id for the member
4447    //   name shall be a simple-template-id.
4448    //
4449    // C++98 has the same restriction, just worded differently.
4450    if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4451      Diag(D.getIdentifierLoc(),
4452           diag::err_explicit_instantiation_without_qualified_id)
4453        << Prev << D.getCXXScopeSpec().getRange();
4454
4455    // Check the scope of this explicit instantiation.
4456    CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4457
4458    // Verify that it is okay to explicitly instantiate here.
4459    MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4460    assert(MSInfo && "Missing static data member specialization info?");
4461    bool SuppressNew = false;
4462    if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
4463                                        MSInfo->getTemplateSpecializationKind(),
4464                                              MSInfo->getPointOfInstantiation(),
4465                                               SuppressNew))
4466      return true;
4467    if (SuppressNew)
4468      return DeclPtrTy();
4469
4470    // Instantiate static data member.
4471    Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
4472    if (TSK == TSK_ExplicitInstantiationDefinition)
4473      InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4474                                            /*DefinitionRequired=*/true);
4475
4476    // FIXME: Create an ExplicitInstantiation node?
4477    return DeclPtrTy();
4478  }
4479
4480  // If the declarator is a template-id, translate the parser's template
4481  // argument list into our AST format.
4482  bool HasExplicitTemplateArgs = false;
4483  TemplateArgumentListInfo TemplateArgs;
4484  if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4485    TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4486    TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4487    TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
4488    ASTTemplateArgsPtr TemplateArgsPtr(*this,
4489                                       TemplateId->getTemplateArgs(),
4490                                       TemplateId->NumArgs);
4491    translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
4492    HasExplicitTemplateArgs = true;
4493    TemplateArgsPtr.release();
4494  }
4495
4496  // C++ [temp.explicit]p1:
4497  //   A [...] function [...] can be explicitly instantiated from its template.
4498  //   A member function [...] of a class template can be explicitly
4499  //  instantiated from the member definition associated with its class
4500  //  template.
4501  llvm::SmallVector<FunctionDecl *, 8> Matches;
4502  for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4503       P != PEnd; ++P) {
4504    NamedDecl *Prev = *P;
4505    if (!HasExplicitTemplateArgs) {
4506      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4507        if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4508          Matches.clear();
4509          Matches.push_back(Method);
4510          break;
4511        }
4512      }
4513    }
4514
4515    FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4516    if (!FunTmpl)
4517      continue;
4518
4519    TemplateDeductionInfo Info(Context);
4520    FunctionDecl *Specialization = 0;
4521    if (TemplateDeductionResult TDK
4522          = DeduceTemplateArguments(FunTmpl,
4523                               (HasExplicitTemplateArgs ? &TemplateArgs : 0),
4524                                    R, Specialization, Info)) {
4525      // FIXME: Keep track of almost-matches?
4526      (void)TDK;
4527      continue;
4528    }
4529
4530    Matches.push_back(Specialization);
4531  }
4532
4533  // Find the most specialized function template specialization.
4534  FunctionDecl *Specialization
4535    = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4536                         D.getIdentifierLoc(),
4537          PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4538          PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4539                PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4540
4541  if (!Specialization)
4542    return true;
4543
4544  if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
4545    Diag(D.getIdentifierLoc(),
4546         diag::err_explicit_instantiation_member_function_not_instantiated)
4547      << Specialization
4548      << (Specialization->getTemplateSpecializationKind() ==
4549          TSK_ExplicitSpecialization);
4550    Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4551    return true;
4552  }
4553
4554  FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
4555  if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4556    PrevDecl = Specialization;
4557
4558  if (PrevDecl) {
4559    bool SuppressNew = false;
4560    if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
4561                                               PrevDecl,
4562                                     PrevDecl->getTemplateSpecializationKind(),
4563                                          PrevDecl->getPointOfInstantiation(),
4564                                               SuppressNew))
4565      return true;
4566
4567    // FIXME: We may still want to build some representation of this
4568    // explicit specialization.
4569    if (SuppressNew)
4570      return DeclPtrTy();
4571  }
4572
4573  Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
4574
4575  if (TSK == TSK_ExplicitInstantiationDefinition)
4576    InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4577                                  false, /*DefinitionRequired=*/true);
4578
4579  // C++0x [temp.explicit]p2:
4580  //   If the explicit instantiation is for a member function, a member class
4581  //   or a static data member of a class template specialization, the name of
4582  //   the class template specialization in the qualified-id for the member
4583  //   name shall be a simple-template-id.
4584  //
4585  // C++98 has the same restriction, just worded differently.
4586  FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
4587  if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
4588      D.getCXXScopeSpec().isSet() &&
4589      !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4590    Diag(D.getIdentifierLoc(),
4591         diag::err_explicit_instantiation_without_qualified_id)
4592    << Specialization << D.getCXXScopeSpec().getRange();
4593
4594  CheckExplicitInstantiationScope(*this,
4595                   FunTmpl? (NamedDecl *)FunTmpl
4596                          : Specialization->getInstantiatedFromMemberFunction(),
4597                                  D.getIdentifierLoc(),
4598                                  D.getCXXScopeSpec().isSet());
4599
4600  // FIXME: Create some kind of ExplicitInstantiationDecl here.
4601  return DeclPtrTy();
4602}
4603
4604Sema::TypeResult
4605Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4606                        const CXXScopeSpec &SS, IdentifierInfo *Name,
4607                        SourceLocation TagLoc, SourceLocation NameLoc) {
4608  // This has to hold, because SS is expected to be defined.
4609  assert(Name && "Expected a name in a dependent tag");
4610
4611  NestedNameSpecifier *NNS
4612    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4613  if (!NNS)
4614    return true;
4615
4616  QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4617  if (T.isNull())
4618    return true;
4619
4620  TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4621  QualType ElabType = Context.getElaboratedType(T, TagKind);
4622
4623  return ElabType.getAsOpaquePtr();
4624}
4625
4626Sema::TypeResult
4627Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4628                        const IdentifierInfo &II, SourceLocation IdLoc) {
4629  NestedNameSpecifier *NNS
4630    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4631  if (!NNS)
4632    return true;
4633
4634  QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
4635  if (T.isNull())
4636    return true;
4637  return T.getAsOpaquePtr();
4638}
4639
4640Sema::TypeResult
4641Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4642                        SourceLocation TemplateLoc, TypeTy *Ty) {
4643  QualType T = GetTypeFromParser(Ty);
4644  NestedNameSpecifier *NNS
4645    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4646  const TemplateSpecializationType *TemplateId
4647    = T->getAs<TemplateSpecializationType>();
4648  assert(TemplateId && "Expected a template specialization type");
4649
4650  if (computeDeclContext(SS, false)) {
4651    // If we can compute a declaration context, then the "typename"
4652    // keyword was superfluous. Just build a QualifiedNameType to keep
4653    // track of the nested-name-specifier.
4654
4655    // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4656    return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4657  }
4658
4659  return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
4660}
4661
4662/// \brief Build the type that describes a C++ typename specifier,
4663/// e.g., "typename T::type".
4664QualType
4665Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4666                        SourceRange Range) {
4667  CXXRecordDecl *CurrentInstantiation = 0;
4668  if (NNS->isDependent()) {
4669    CurrentInstantiation = getCurrentInstantiationOf(NNS);
4670
4671    // If the nested-name-specifier does not refer to the current
4672    // instantiation, then build a typename type.
4673    if (!CurrentInstantiation)
4674      return Context.getTypenameType(NNS, &II);
4675
4676    // The nested-name-specifier refers to the current instantiation, so the
4677    // "typename" keyword itself is superfluous. In C++03, the program is
4678    // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
4679    // extraneous "typename" keywords, and we retroactively apply this DR to
4680    // C++03 code.
4681  }
4682
4683  DeclContext *Ctx = 0;
4684
4685  if (CurrentInstantiation)
4686    Ctx = CurrentInstantiation;
4687  else {
4688    CXXScopeSpec SS;
4689    SS.setScopeRep(NNS);
4690    SS.setRange(Range);
4691    if (RequireCompleteDeclContext(SS))
4692      return QualType();
4693
4694    Ctx = computeDeclContext(SS);
4695  }
4696  assert(Ctx && "No declaration context?");
4697
4698  DeclarationName Name(&II);
4699  LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
4700  LookupQualifiedName(Result, Ctx);
4701  unsigned DiagID = 0;
4702  Decl *Referenced = 0;
4703  switch (Result.getResultKind()) {
4704  case LookupResult::NotFound:
4705    DiagID = diag::err_typename_nested_not_found;
4706    break;
4707
4708  case LookupResult::Found:
4709    if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
4710      // We found a type. Build a QualifiedNameType, since the
4711      // typename-specifier was just sugar. FIXME: Tell
4712      // QualifiedNameType that it has a "typename" prefix.
4713      return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4714    }
4715
4716    DiagID = diag::err_typename_nested_not_type;
4717    Referenced = Result.getFoundDecl();
4718    break;
4719
4720  case LookupResult::FoundUnresolvedValue:
4721    llvm_unreachable("unresolved using decl in non-dependent context");
4722    return QualType();
4723
4724  case LookupResult::FoundOverloaded:
4725    DiagID = diag::err_typename_nested_not_type;
4726    Referenced = *Result.begin();
4727    break;
4728
4729  case LookupResult::Ambiguous:
4730    return QualType();
4731  }
4732
4733  // If we get here, it's because name lookup did not find a
4734  // type. Emit an appropriate diagnostic and return an error.
4735  Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
4736  if (Referenced)
4737    Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4738      << Name;
4739  return QualType();
4740}
4741
4742namespace {
4743  // See Sema::RebuildTypeInCurrentInstantiation
4744  class CurrentInstantiationRebuilder
4745    : public TreeTransform<CurrentInstantiationRebuilder> {
4746    SourceLocation Loc;
4747    DeclarationName Entity;
4748
4749  public:
4750    CurrentInstantiationRebuilder(Sema &SemaRef,
4751                                  SourceLocation Loc,
4752                                  DeclarationName Entity)
4753    : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
4754      Loc(Loc), Entity(Entity) { }
4755
4756    /// \brief Determine whether the given type \p T has already been
4757    /// transformed.
4758    ///
4759    /// For the purposes of type reconstruction, a type has already been
4760    /// transformed if it is NULL or if it is not dependent.
4761    bool AlreadyTransformed(QualType T) {
4762      return T.isNull() || !T->isDependentType();
4763    }
4764
4765    /// \brief Returns the location of the entity whose type is being
4766    /// rebuilt.
4767    SourceLocation getBaseLocation() { return Loc; }
4768
4769    /// \brief Returns the name of the entity whose type is being rebuilt.
4770    DeclarationName getBaseEntity() { return Entity; }
4771
4772    /// \brief Sets the "base" location and entity when that
4773    /// information is known based on another transformation.
4774    void setBase(SourceLocation Loc, DeclarationName Entity) {
4775      this->Loc = Loc;
4776      this->Entity = Entity;
4777    }
4778
4779    /// \brief Transforms an expression by returning the expression itself
4780    /// (an identity function).
4781    ///
4782    /// FIXME: This is completely unsafe; we will need to actually clone the
4783    /// expressions.
4784    Sema::OwningExprResult TransformExpr(Expr *E) {
4785      return getSema().Owned(E);
4786    }
4787
4788    /// \brief Transforms a typename type by determining whether the type now
4789    /// refers to a member of the current instantiation, and then
4790    /// type-checking and building a QualifiedNameType (when possible).
4791    QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
4792  };
4793}
4794
4795QualType
4796CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4797                                                     TypenameTypeLoc TL) {
4798  TypenameType *T = TL.getTypePtr();
4799
4800  NestedNameSpecifier *NNS
4801    = TransformNestedNameSpecifier(T->getQualifier(),
4802                              /*FIXME:*/SourceRange(getBaseLocation()));
4803  if (!NNS)
4804    return QualType();
4805
4806  // If the nested-name-specifier did not change, and we cannot compute the
4807  // context corresponding to the nested-name-specifier, then this
4808  // typename type will not change; exit early.
4809  CXXScopeSpec SS;
4810  SS.setRange(SourceRange(getBaseLocation()));
4811  SS.setScopeRep(NNS);
4812
4813  QualType Result;
4814  if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
4815    Result = QualType(T, 0);
4816
4817  // Rebuild the typename type, which will probably turn into a
4818  // QualifiedNameType.
4819  else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
4820    QualType NewTemplateId
4821      = TransformType(QualType(TemplateId, 0));
4822    if (NewTemplateId.isNull())
4823      return QualType();
4824
4825    if (NNS == T->getQualifier() &&
4826        NewTemplateId == QualType(TemplateId, 0))
4827      Result = QualType(T, 0);
4828    else
4829      Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4830  } else
4831    Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4832                                              SourceRange(TL.getNameLoc()));
4833
4834  TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4835  NewTL.setNameLoc(TL.getNameLoc());
4836  return Result;
4837}
4838
4839/// \brief Rebuilds a type within the context of the current instantiation.
4840///
4841/// The type \p T is part of the type of an out-of-line member definition of
4842/// a class template (or class template partial specialization) that was parsed
4843/// and constructed before we entered the scope of the class template (or
4844/// partial specialization thereof). This routine will rebuild that type now
4845/// that we have entered the declarator's scope, which may produce different
4846/// canonical types, e.g.,
4847///
4848/// \code
4849/// template<typename T>
4850/// struct X {
4851///   typedef T* pointer;
4852///   pointer data();
4853/// };
4854///
4855/// template<typename T>
4856/// typename X<T>::pointer X<T>::data() { ... }
4857/// \endcode
4858///
4859/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4860/// since we do not know that we can look into X<T> when we parsed the type.
4861/// This function will rebuild the type, performing the lookup of "pointer"
4862/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4863/// as the canonical type of T*, allowing the return types of the out-of-line
4864/// definition and the declaration to match.
4865QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4866                                                 DeclarationName Name) {
4867  if (T.isNull() || !T->isDependentType())
4868    return T;
4869
4870  CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4871  return Rebuilder.TransformType(T);
4872}
4873
4874/// \brief Produces a formatted string that describes the binding of
4875/// template parameters to template arguments.
4876std::string
4877Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4878                                      const TemplateArgumentList &Args) {
4879  // FIXME: For variadic templates, we'll need to get the structured list.
4880  return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
4881                                         Args.flat_size());
4882}
4883
4884std::string
4885Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4886                                      const TemplateArgument *Args,
4887                                      unsigned NumArgs) {
4888  std::string Result;
4889
4890  if (!Params || Params->size() == 0 || NumArgs == 0)
4891    return Result;
4892
4893  for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4894    if (I >= NumArgs)
4895      break;
4896
4897    if (I == 0)
4898      Result += "[with ";
4899    else
4900      Result += ", ";
4901
4902    if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4903      Result += Id->getName();
4904    } else {
4905      Result += '$';
4906      Result += llvm::utostr(I);
4907    }
4908
4909    Result += " = ";
4910
4911    switch (Args[I].getKind()) {
4912      case TemplateArgument::Null:
4913        Result += "<no value>";
4914        break;
4915
4916      case TemplateArgument::Type: {
4917        std::string TypeStr;
4918        Args[I].getAsType().getAsStringInternal(TypeStr,
4919                                                Context.PrintingPolicy);
4920        Result += TypeStr;
4921        break;
4922      }
4923
4924      case TemplateArgument::Declaration: {
4925        bool Unnamed = true;
4926        if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
4927          if (ND->getDeclName()) {
4928            Unnamed = false;
4929            Result += ND->getNameAsString();
4930          }
4931        }
4932
4933        if (Unnamed) {
4934          Result += "<anonymous>";
4935        }
4936        break;
4937      }
4938
4939      case TemplateArgument::Template: {
4940        std::string Str;
4941        llvm::raw_string_ostream OS(Str);
4942        Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
4943        Result += OS.str();
4944        break;
4945      }
4946
4947      case TemplateArgument::Integral: {
4948        Result += Args[I].getAsIntegral()->toString(10);
4949        break;
4950      }
4951
4952      case TemplateArgument::Expression: {
4953        assert(false && "No expressions in deduced template arguments!");
4954        Result += "<expression>";
4955        break;
4956      }
4957
4958      case TemplateArgument::Pack:
4959        // FIXME: Format template argument packs
4960        Result += "<template argument pack>";
4961        break;
4962    }
4963  }
4964
4965  Result += ']';
4966  return Result;
4967}
4968