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