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