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