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