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