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