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