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