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