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