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