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