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