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