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